<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 { modalFormProps } from '#/views/system/store/config/form';

import { createStore, updateStore } from '../api';
import dayjs from "dayjs";

const isUpdate = ref(false);
const gridApi = ref();

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

const [Modal, modalApi] = useVbenModal({
  closeOnClickModal: false,
  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 ? updateStore : createStore;
        // 固定设置type=0（诊所类型），无论是新增还是编辑
        submitApi(values)
          .then(() => {
            message.success('保存成功');
            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) {
      const { values, update } = modalApi.getData<Record<string, any>>();
      if (values) {
        isUpdate.value = update;
        values.address = [values.province_id, values.city_id];
        formApi.setValues({
          ...values,
          start_time: dayjs(values.start_time || '08:00', 'HH:mm'),
          end_time: dayjs(values.end_time || '20:00', 'HH:mm'),
          // 确保订阅状态有值，如果后端没有返回则默认为0（订阅）
          subscribe_price_change: values.subscribe_price_change ?? 0,
          sync_admin_phone: false,
        });
      }
    }
  },
});
</script>
<template>
  <Modal :title="`${isUpdate === true ? '编辑' : '新增'}诊所`" class="w-[50%]">
    <Form />
  </Modal>
</template>
