<script lang="ts" setup>
/**
 * 病历词条新增/编辑弹窗
 * scope 从 modalApi.getData() 读取：public | store
 */
import { ref } from 'vue';

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

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

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

import {
  createMedicalRecordEntry,
  updateMedicalRecordEntry,
} from '../api';
import { buildEntryFormProps } from '../config/entry-form';

const isUpdate = ref(false);
const gridApi = ref();
const entryScope = ref<'public' | 'store'>('public');
const fixedFieldCode = ref('');
const [Form, formApi] = useVbenForm(buildEntryFormProps());
const [Modal, modalApi] = useVbenModal({
  fullscreenButton: false,
  draggable: true,
  onCancel() {
    modalApi.close();
  },
  onConfirm: async () => {
    const e = await formApi.validate();
    if (!e.valid) return;
    const values = await formApi.getValues();
    modalApi.setState({ confirmLoading: true });
    try {
      const payload = {
        ...values,
        scope: entryScope.value,
        ...(fixedFieldCode.value ? { field_code: fixedFieldCode.value } : {}),
      };
      if (isUpdate.value) {
        await updateMedicalRecordEntry(payload);
      } else {
        await createMedicalRecordEntry(payload);
      }
      message.success('保存成功');
      gridApi.value?.query();
      modalApi.close();
    } finally {
      modalApi.setState({ confirmLoading: false });
    }
  },
  onOpenChange(isOpen: boolean) {
    const data = isOpen ? modalApi.getData<Record<string, any>>() : null;
    gridApi.value = data?.gridApi || null;
    entryScope.value = (data?.scope as 'public' | 'store') || 'public';
    fixedFieldCode.value = String(data?.fixedFieldCode || '');
    if (!isOpen) {
      formApi.resetForm();
      return;
    }
    // 按字段拆页时隐藏「所属字段」，并去掉必填校验（提交时由 fixedFieldCode 注入）
    formApi.updateSchema([
      {
        fieldName: 'field_code',
        rules: fixedFieldCode.value ? '' : 'selectRequired',
        dependencies: {
          show: () => !fixedFieldCode.value,
          triggerFields: ['title'],
        },
      },
    ]);
    const { values, update } = data || {};
    isUpdate.value = !!update;
    if (values && update) {
      formApi.setValues({ ...values });
    } else {
      formApi.resetForm();
      formApi.setValues({
        sort: 0,
        status: 1,
        content: '',
        remark: '',
        field_code: fixedFieldCode.value || undefined,
      });
    }
  },
});
</script>
<template>
  <Modal :title="`${isUpdate ? '编辑' : '新增'}词条`" class="w-[640px]">
    <Form />
  </Modal>
</template>
