<template>
  <BasicModal
    v-bind="$attrs"
    :title="title"
    @register="registerInnerModal"
    @ok="handleSubmit"
    @cancel="resetForm"
  >
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>

<script setup lang="ts">
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { BasicForm, useForm } from '@/components/Form';
  import { computed, ref, unref } from 'vue';
  import { ContractualTasksInfo, ContractualTasksAdd, ContractualTasksUpdate } from '@/api/contractReview/ContractualTasks';
  import { modalSchemas } from './ContractualTasks.data';
  import { ModelUserPromptssettingInfoByUserId } from '@/api/modelConfiguration/ModelUserPromptssetting/index';
  import { TaskType } from '@/enums/taskEnum';

  defineOptions({ name: 'ContractualTasksModal' });

  const emit = defineEmits(['register', 'reload']);

  const isUpdate = ref<boolean>(false);
  const title = computed<string>(() => {
    return isUpdate.value ? '新增合同任务' : '新增合同任务';
  });

  const [registerInnerModal, { modalLoading, closeModal }] = useModalInner(
    async (data: { record?: Recordable; update: boolean }) => {
      modalLoading(true);
      const settings = await ModelUserPromptssettingInfoByUserId({taskType:TaskType.CONTRACT_REVIEW.value});
      await setFieldsValue(settings);
      const { record, update } = data;
      isUpdate.value = update;
      if (update && record) {
        // const ret = await ContractualTasksInfo(record.id);
        await setFieldsValue(record);
      }
      modalLoading(false);
    },
  );

  const [registerForm, { setFieldsValue, resetForm, validate }] = useForm({
    labelWidth: 100,
    showActionButtonGroup: false,
    baseColProps: { span: 24 },
    schemas: modalSchemas,
  });

  async function handleSubmit() {
    try {
      modalLoading(true);
      const data = await validate();
      data['ossId'] = data['ossId'][0];
      await ContractualTasksAdd(data);
      emit('reload');
      closeModal();
      await resetForm();
    } catch (e) {
    } finally {
      modalLoading(false);
    }
  }
</script>

<style scoped></style>
