<script lang="ts" setup>
/**
 * 金方新增/编辑弹窗（基础信息）
 * 药方组成已拆到独立「药方设置」弹窗，本弹窗不再编辑 drugs_json
 */
import { ref } from 'vue';

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

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

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

import {
  createGoldenFormula,
  getGoldenFormulaSourceOption,
  updateGoldenFormula,
} 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 () => {
    const e = await formApi.validate();
    if (!e.valid) return;
    const values = await formApi.getValues();
    modalApi.setState({ confirmLoading: true });
    try {
      // 基础信息保存不带 drugs_json，避免覆盖已有药方组成
      const api = isUpdate.value ? updateGoldenFormula : createGoldenFormula;
      await api(values);
      message.success('保存成功');
      gridApi.value?.query?.();
      gridApi.value?.reload?.();
      modalApi.close();
    } finally {
      modalApi.setState({ confirmLoading: false });
    }
  },
  async onOpenChange(isOpen: boolean) {
    gridApi.value = isOpen ? modalApi.getData()?.gridApi : null;
    if (!isOpen) {
      formApi.resetForm();
      return;
    }
    // 打开时拉取金方来源下拉选项并注入
    try {
      const list = await getGoldenFormulaSourceOption();
      const options = (Array.isArray(list) ? list : []).map((item: any) => ({
        label: String(item.name || ''),
        value: Number(item.id || 0),
      }));
      formApi.updateSchema([
        {
          fieldName: 'source_id',
          componentProps: { options },
        },
      ]);
    } catch {
      // 拉取失败不阻塞表单
    }
    const { values, update } = modalApi.getData<Record<string, any>>() || {};
    isUpdate.value = !!update;
    if (values && update) {
      formApi.setValues({ ...values });
    } else {
      formApi.resetForm();
      formApi.setValues({ sort: 0, status: 1, source_id: 0 });
    }
  },
});
</script>
<template>
  <Modal :title="`${isUpdate ? '编辑' : '新增'}金方`" class="w-[720px]">
    <Form />
  </Modal>
</template>
