<template>
  <BasicModal
    v-bind="$attrs"
    destroyOnClose
    @register="registerModal"
    :title="getTitle"
    :width="width"
    @ok="handleSubmit"
    :showFooter="true"
  >
    <div class="!pl-8 !pt-4">
      <BasicForm @register="registerForm" layout="vertical" />
    </div>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { dataFormSchema } from './data';

  import {
    archivesPatientBasicAdd,
    archivesPatientBasicEdit,
    archivesPatientBasicDetail,
  } from '/@/api/biz/archives/patientBasicApi';

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

  const getTitle = computed(() => (!unref(isUpdate) ? '新增基础病历' : '编辑基础病历'));
  const width = '45%';
  const isUpdate = ref(false);
  const rowId = ref();

  const { createMessage } = useMessage();
  const [registerForm, { setFieldsValue, resetFields, validate }] = useForm({
    labelWidth: 100,
    schemas: dataFormSchema,
    showActionButtonGroup: false,
    actionColOptions: {
      span: 23,
    },
    baseColProps: {
      span: 12,
    },
    wrapperCol: {
      span: 22,
    },
  });
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async data => {
    await resetFields();
    setModalProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;

    if (unref(isUpdate)) {
      const resData = await archivesPatientBasicDetail(data.record.id);
      rowId.value = resData.id;
      resData.cardNo = {
        input: resData.cardNo,
        dictValue: resData.cardType,
      };
      await setFieldsValue({
        ...resData,
      });
    } else {
      await setFieldsValue({
        cardNo: {
          input: '',
          dictValue: 'pb_card_sfz',
        },
      });
    }
  });

  // 提交按钮事件
  async function handleSubmit() {
    try {
      const values = await validate();
      setModalProps({ confirmLoading: true });
      const cardInfo = values.cardNo;
      values.cardNo = cardInfo?.input;
      values.cardType = cardInfo?.dictValue;
      !unref(isUpdate)
        ? await archivesPatientBasicAdd({ ...values })
        : await archivesPatientBasicEdit({ ...values, id: rowId.value });
      !unref(isUpdate) ? createMessage.success('新增成功！') : createMessage.success('编辑成功！');
      closeModal();
      emit('success', {
        isUpdate: unref(isUpdate),
        values: { ...values, id: rowId.value },
      });
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
