<script lang="ts" setup>
/**
 * 配送仓建品弹窗
 * 新建：不传 status（后端强制草稿）；编辑：按 audit_status 控制 status 显隐
 * 用法字典复用西药 getDrugUseList，避免各品类重复维护
 */
import { nextTick, ref } from 'vue';

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

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

import { useVbenForm } from '#/adapter/form';
import { getDrugUseList } from '#/views/doctor/doctor-reception/api';

import {
  createDeliveryWarehouseProduct,
  getDeliveryWarehouseProductInfo,
  updateDeliveryWarehouseProduct,
} from '../api';
import { modalFormProps } from '../config/form';

const isUpdate = ref(false);
const gridApi = ref();
const drugTime = ref<{ label: string; value: number }[]>([]);
const drugType = ref<{ label: string; value: number }[]>([]);
const drugUnit = ref<{ label: string; value: number }[]>([]);
const drugFrequency = ref<{ label: string; value: number }[]>([]);

/** 预拉取用法字典，打开弹窗时注入 Select options */
getDrugUseList().then((res) => {
  drugTime.value = (res.drug_time || []).map((item: any) => ({
    label: item.name,
    value: item.id,
  }));
  drugType.value = (res.drug_use_type || []).map((item: any) => ({
    label: item.name,
    value: item.id,
  }));
  drugUnit.value = (res.drug_unit || []).map((item: any) => ({
    label: item.name,
    value: item.id,
  }));
  drugFrequency.value = (res.drug_use_frequency || []).map((item: any) => ({
    label: item.name,
    value: item.id,
  }));
});

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

/** 把用法字典写入四个 Select，保证每次打开都有最新 options */
function injectUseDictOptions() {
  formApi.updateSchema([
    { fieldName: 'time_id', componentProps: { options: drugTime.value } },
    { fieldName: 'unit_id', componentProps: { options: drugUnit.value } },
    { fieldName: 'type_id', componentProps: { options: drugType.value } },
    {
      fieldName: 'frequency_id',
      componentProps: { options: drugFrequency.value },
    },
  ]);
}

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();
        // 新建不提交 status；未审核编辑也不提交（后端也会忽略，前端再挡一层）
        const payload = { ...values };
        if (!isUpdate.value || Number(payload.audit_status) === 0) {
          delete payload.status;
        }
        delete payload.audit_status;
        modalApi.setState({ loading: true, confirmLoading: true });
        const submitApi = isUpdate.value
          ? updateDeliveryWarehouseProduct
          : createDeliveryWarehouseProduct;
        submitApi(payload)
          .then(() => {
            message.success('保存成功');
            gridApi.value?.query?.() ?? gridApi.value?.reload?.();
            modalApi.close();
          })
          .finally(() => {
            modalApi.setState({ loading: false, confirmLoading: false });
          });
      }
    });
    await formApi.validateAndSubmitForm();
  },
  async onOpenChange(isOpen: boolean) {
    gridApi.value = isOpen ? modalApi.getData()?.gridApi : null;
    if (!isOpen) {
      return;
    }
    injectUseDictOptions();
    await formApi.resetForm();
    const { values, update } = modalApi.getData<Record<string, any>>() || {};
    isUpdate.value = !!update;
    if (update && values?.id) {
      // 编辑拉详情；zone_id 联动会清空 category_id，需 nextTick 后补回
      try {
        const detail = await getDeliveryWarehouseProductInfo(values.id);
        const merged = {
          ...values,
          ...(detail || {}),
          introduction_images: detail?.introduction_images || [],
        };
        const categoryId = merged.category_id;
        await formApi.setValues(merged);
        await nextTick();
        if (categoryId) {
          await formApi.setFieldValue('category_id', categoryId);
        }
      } catch {
        await formApi.setValues(values || {});
      }
    } else if (values) {
      await formApi.setValues(values);
    }
  },
});
</script>

<template>
  <Modal
    :title="`${isUpdate === true ? '编辑' : '新增'}仓品`"
    class="w-[80%] md:w-[50%] lg:w-[40%] h-[70%]"
  >
    <Form />
  </Modal>
</template>
