<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 {getDrugUseList} from '#/views/doctor/doctor-reception/api';

import {createNonDrug, getNonDrugInfo, updateNonDrug,} from '../api';
import {modalFormProps} from '../config/form';

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

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
          ? updateNonDrug
          : createNonDrug;
        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) {
      formApi.updateSchema([
        {
          componentProps: {
            options: drugUnit.value,
          },
          fieldName: 'unit_id',
        },
      ]);
      const { values, update } = modalApi.getData<Record<string, any>>();
      if (values) {
        isUpdate.value = update;

        if (update && values.id) {
          getNonDrugInfo(values.id)
            .then((res: any) => {
              if (res) {
                formApi.setValues({
                  ...values,
                  introduction_images: res.introduction_images,
                });
              } else {
                formApi.setValues(values);
              }
            })
            .catch((error) => {
              console.error('获取商品详情失败:', error);
              formApi.setValues(values);
            });
        } else {
          formApi.setValues(values);
        }
      }
    }
  },
});
</script>
<template>
  <Modal
    :title="`${isUpdate === true ? '编辑' : '新增'}非药品`"
    class="w-[80%] md:w-[50%] lg:w-[30%] h-[60%]"
  >
    <Form />
  </Modal>
</template>








