<script lang="ts" setup>
/**
 * 中药新增/编辑弹窗
 * 支持通过 modalApi.setData({ onSuccess }) 在保存成功后回调（金方缺失药「添加药材」复用）
 */
import { ref } from 'vue';

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

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

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

import { createChinaMedicine, updateChinaMedicine } from '../api';
import { modalFormProps } from '../config/form';
import { getDrugUseList } from '#/views/doctor/doctor-reception/api';

const drugTime = ref([]);
const drugType = ref([]);
const drugUnit = ref([]);
const drugFrequency = ref([]);
getDrugUseList().then((res) => {
  drugTime.value = res.drug_time.map((item) => {
    return {
      label: item.name,
      value: item.id,
    };
  });
  drugType.value = res.drug_use_type.map((item) => {
    return {
      label: item.name,
      value: item.id,
    };
  });
  drugUnit.value = res.drug_unit.map((item) => {
    return {
      label: item.name,
      value: item.id,
    };
  });
  drugFrequency.value = res.drug_use_frequency.map((item) => {
    return {
      label: item.name,
      value: item.id,
    };
  });
  return res;
});

const isUpdate = ref(false);
const gridApi = ref();
/** 外部传入的成功回调（如金方缺失药处理） */
const onSuccessCb = ref<null | (() => void | Promise<void>)>(null);

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

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({ loading: true, confirmLoading: true });
    try {
      const submitApi = isUpdate.value
        ? updateChinaMedicine
        : createChinaMedicine;
      await submitApi(values);
      message.success('保存成功');
      gridApi.value?.reload?.();
      gridApi.value?.query?.();
      // 外部回调：金方缺失药「添加药材」成功后标记已解决
      if (typeof onSuccessCb.value === 'function') {
        await onSuccessCb.value();
      }
      modalApi.close();
    } finally {
      modalApi.setState({ loading: false, confirmLoading: false });
    }
  },
  onOpenChange(isOpen: boolean) {
    if (!isOpen) {
      onSuccessCb.value = null;
      formApi.resetForm();
      return;
    }
    const data = modalApi.getData<Record<string, any>>() || {};
    gridApi.value = data.gridApi || null;
    onSuccessCb.value =
      typeof data.onSuccess === 'function' ? data.onSuccess : null;
    formApi.updateSchema([
      {
        componentProps: {
          options: drugTime.value,
        },
        fieldName: 'time_id',
      },
      {
        componentProps: {
          options: drugUnit.value,
        },
        fieldName: 'unit_id',
      },
      {
        componentProps: {
          options: drugType.value,
        },
        fieldName: 'type_id',
      },
      {
        componentProps: {
          options: drugFrequency.value,
        },
        fieldName: 'frequency_id',
      },
    ]);
    const { values, update } = data;
    isUpdate.value = !!update;
    if (values) {
      formApi.setValues(values);
    } else {
      formApi.resetForm();
      formApi.setValues({ status: 1 });
    }
  },
});
</script>
<template>
  <Modal
    :title="`${isUpdate === true ? '编辑' : '新增'}中药`"
    class="w-[80%] md:w-[50%] lg:w-[30%] h-[60%]"
  >
    <Form />
  </Modal>
</template>
