<script lang="ts" setup>
import { ref, onMounted } from 'vue';

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

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

import { useVbenForm } from '#/adapter/form';
import { getPlatformInfoDetail, updatePlatformInfo } from '#/views/system/platform-info/api';
import { modalFormProps } from '#/views/system/platform-info/config/form';

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 });
        updatePlatformInfo(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 platformId = modalApi.getData()?.platform_id || 1;
      // 先设置默认值，确保所有字段都有值
      const defaultFormData = {
        id: '',
        platform_id: platformId,
        contact_phone: '',
        contact_email: '',
        contact_address: '',
        complaint_phone: '',
        complaint_email: '',
        complaint_address: '',
      };
      formApi.setValues(defaultFormData);
      
      getPlatformInfoDetail({ platform_id: platformId })
        .then((res: any) => {
          const data = res.data?.data || res.data?.result || {};
          // 将嵌套的数据结构展开为扁平结构，确保所有字段都有值
          const formData: any = {
            id: data.id || '',
            platform_id: platformId,
            contact_phone: data.contact?.phone || '',
            contact_email: data.contact?.email || '',
            contact_address: data.contact?.address || '',
            complaint_phone: data.complaint?.phone || '',
            complaint_email: data.complaint?.email || '',
            complaint_address: data.complaint?.address || '',
          };
          formApi.setValues(formData);
        })
        .catch(() => {
          // 如果加载失败，使用默认值（已经在上面设置了）
        });
    } else {
      // 关闭时重置表单
      formApi.resetForm();
    }
  },
});
</script>
<template>
  <Modal title="平台信息管理" class="w-[60%]">
    <Form />
  </Modal>
</template>
