<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-input/config/form';

import { createStoreInput, getStoreInputDetail, updateStoreInput } from '../api';
import dayjs from 'dayjs';

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 ? updateStoreInput : createStoreInput;
        submitApi(values)
          .then(() => {
            message.success(isUpdate.value ? '更新成功' : '录入成功');
            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];
        
        // 处理合同文件
        if (values.contract_files && Array.isArray(values.contract_files)) {
          values.contract_files = values.contract_files.map((file: any) => {
            if (typeof file === 'string') {
              return { url: file, name: file.split('/').pop() || '合同文件' };
            }
            return file;
          });
        }
        
        formApi.setValues({
          ...values,
          start_time: dayjs(values.start_time || '08:00', 'HH:mm'),
          end_time: dayjs(values.end_time || '20:00', 'HH:mm'),
          subscribe_price_change: values.subscribe_price_change ?? 0,
        });
      } else {
        isUpdate.value = false;
      }
    }
  },
});
</script>

<template>
  <Modal :title="`${isUpdate === true ? '编辑' : '新增'}录入`" class="w-[50%]">
    <Form />
  </Modal>
</template>
