<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 { JyjcontractualTaskBatchInfo, JyjcontractualTaskBatchAdd, JyjcontractualTaskBatchUpdate } from '@/api/contractReview/JyjcontractualTaskBatch';
  import { modalSchemas } from './JyjcontractualTaskBatch.data';

  defineOptions({ name: 'JyjcontractualTaskBatchModal' });

  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 { record, update } = data;
      isUpdate.value = update;
      if (update && record) {
        const ret = await JyjcontractualTaskBatchInfo(record.id);
        await setFieldsValue(ret);
      }
      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();
      //修改
      if (unref(isUpdate)) {
        data["ossId"]=data["ossId"][0]
        await JyjcontractualTaskBatchUpdate(data);
      } else {
        //新增
        data["ossId"]=data["ossId"][0]
        data["taskName"]="batchReview"
        data["taskType"]="contract_review"
        await JyjcontractualTaskBatchAdd(data); 
      }
      emit('reload');
      closeModal();
      await resetForm();
    } catch (e) {
    } finally {
      modalLoading(false);
    }
  }
</script>

<style scoped></style>
