<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 {
  createHomeZones,
  updateHomeZones,
} 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 () => {
    formApi.validate().then(async (e: any) => {
      if (e.valid) {
        const values = await formApi.getValues();
        // 处理 store_id，如果为空字符串则设为 null
        if (values.store_id === '' || values.store_id === undefined) {
          values.store_id = null;
        }
        modalApi.setState({ loading: true, confirmLoading: true });
        const submitApi = isUpdate.value ? updateHomeZones : createHomeZones;
        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) {
      const { values, update } = modalApi.getData<Record<string, any>>();
      if (values && update) {
        // 编辑时，确保所有字段都有值
        isUpdate.value = true;
        const formData: any = {
          id: values.id || '',
          title: values.title || '',
          type: values.type || '',
          icon: values.icon || '',
          description: values.description || '',
          sort_order: values.sort_order ?? 0,
          status: values.status ?? 1,
          store_id: values.store_id ?? null,
          drug_type: values.drug_type ?? undefined,
        };
        formApi.setValues(formData);
      } else {
        // 新增时重置表单并设置默认值
        isUpdate.value = false;
        formApi.resetFields();
        formApi.setValues({
          id: '',
          title: '',
          type: undefined,
          icon: '',
          description: '',
          sort_order: 0,
          status: 1,
          store_id: null,
          drug_type: undefined,
        });
      }
    } else {
      // 关闭时重置表单
      formApi.resetFields();
    }
  },
});
</script>
<template>
  <Modal :title="`${isUpdate === true ? '编辑' : '新增'}首页专区`" class="w-[60%]">
    <Form />
  </Modal>
</template>

