<script lang="ts" setup>
import { ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { message } from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';

import {
  createPatientCallLogDict,
  updatePatientCallLogDict,
} from '../api';
import { modalFormProps } from '../config/form';

const isUpdate = ref(false);
const gridApi = ref();

const [Form, formApi] = useVbenForm(modalFormProps);

const [Modal, modalApi] = useVbenModal({
  fullscreenButton: false,
  draggable: true,
  onCancel() {
    modalApi.close();
  },
  onConfirm: async () => {
    formApi.validate().then(async (e: any) => {
      if (e.valid) {
        const values = await formApi.getValues();
        modalApi.setState({ loading: true, confirmLoading: true });
        const submitApi = isUpdate.value
          ? updatePatientCallLogDict
          : createPatientCallLogDict;
        submitApi(values)
          .then(() => {
            message.success('保存成功');
            gridApi.value?.reload();
            modalApi.close();
          })
          .finally(() => {
            modalApi.setState({ loading: false, confirmLoading: false });
          });
      }
    });
    await formApi.validateAndSubmitForm();
  },
  onOpenChange(isOpen: boolean) {
    gridApi.value = isOpen ? modalApi.getData()?.gridApi : null;
    if (isOpen) {
      const { values, update } = modalApi.getData<Record<string, any>>();
      if (values && update) {
        // 编辑：回填后端返回的字段
        isUpdate.value = true;
        formApi.setValues({
          id: values.id || '',
          type: values.type ?? 1,
          name: values.name || '',
          value: values.value || '',
          color: values.color || '#6acdbb',
          sort: values.sort ?? 0,
          status: values.status ?? 1,
        });
      } else {
        // 新增：默认值
        isUpdate.value = false;
        formApi.resetForm();
        formApi.setValues({
          id: '',
          type: 1,
          name: '',
          value: '',
          color: '#6acdbb',
          sort: 0,
          status: 1,
        });
      }
    } else {
      formApi.resetForm();
    }
  },
});
</script>
<template>
  <Modal :title="`${isUpdate === true ? '编辑' : '新增'}回访字典`" class="w-[50%]">
    <Form />
  </Modal>
</template>
