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

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

import { ElMessage } from 'element-plus';

import { useVbenForm, z } from '#/adapter/form';
import {
  addSubsidyApplicationsApi,
  editSubsidyApplicationsApi,
  getSubsidyApplicationsDetailApi,
} from '#/api/subsidyapplications';
import { $t } from '#/locales';

const emit = defineEmits(['finish']);
const data = ref();
const formType = ref<'create' | 'detail' | 'edit'>('create');

const titleMap = {
  create: '新增补贴申请',
  detail: '补贴申请详情',
  edit: '编辑补贴申请',
} as const;

const getTitle = computed(() => titleMap[formType.value]);

const [BaseForm, baseFormApi] = useVbenForm({
  showDefaultActions: false,
  // 所有表单项共用，可单独在表单内覆盖
  commonConfig: {
    labelWidth: 140,
    // 所有表单项
    componentProps: {
      class: 'w-full',
    },
  },
  wrapperClass: 'grid-cols-1 lg:grid-cols-2',
  schema: [
    // { title: '经销商ID', field: 'subsidyapplicationsmerchantid' },
    // { title: '补贴金额', field: 'subsidyapplicationssubsidyamount' },
    // { title: '审批状态', field: 'subsidyapplicationsapprovalstatus' },
    // { title: '申请日期', field: 'subsidyapplicationsapplydate' },
    {
      component: 'Input',
      fieldName: 'subsidyapplicationsmerchantid',
      label: '经销商ID',
      componentProps: {
        placeholder: $t('ui.placeholder.input'),
        allowClear: true,
      },
      rules: z.string().min(1, { message: '请输入经销商ID' }),
    },
    {
      component: 'Input',
      fieldName: 'subsidyapplicationssubsidyamount',
      label: '补贴金额',
      componentProps: {
        placeholder: $t('ui.placeholder.input'),
        allowClear: true,
      },
      rules: z.string().min(1, { message: '请输入补贴金额' }),
    },
    {
      component: 'Input',
      fieldName: 'subsidyapplicationsapprovalstatus',
      label: '审批状态',
      componentProps: {
        placeholder: $t('ui.placeholder.input'),
        allowClear: true,
      },
      rules: z.string().min(1, { message: '请输入审批状态' }),
    },
  ],
});

const [Modal, modalApi] = useVbenModal({
  class: 'w-7/12',
  onCancel() {
    modalApi.close();
  },
  async onConfirm() {
    // 校验输入的数据
    const validate = await baseFormApi.validate();
    if (!validate.valid) {
      return;
    }

    try {
      // 调用新增或编辑接口
      const apiMap = {
        create: () => {
          const params = {
            ...validate?.values,
            'subsidyapplicationsmerchantid.value':
              validate?.values?.subsidyapplicationsmerchantid,
            'subsidyapplicationstotalsales.value':
              validate?.values?.subsidyapplicationstotalsales,
            'subsidyapplicationssubsidyamount.value':
              validate?.values?.subsidyapplicationssubsidyamount,
            'subsidyapplicationsapprovalstatus.value':
              validate?.values?.subsidyapplicationsapprovalstatus,
          } as any;

          return addSubsidyApplicationsApi(params);
        },
        edit: () =>
          editSubsidyApplicationsApi({
            ...validate.values,
            'subsidyapplicationsmerchantid.value':
              data.value.row.subsidyapplicationsmerchantid,
            'subsidyapplicationsid.value': data.value.row.subsidyapplicationsid,
            'subsidyapplicationstotalsales.value':
              data.value.row.subsidyapplicationstotalsales,
            'subsidyapplicationssubsidyamount.value':
              data.value.row.subsidyapplicationssubsidyamount,
            'subsidyapplicationsapprovalstatus.value':
              data.value.row.subsidyapplicationsapprovalstatus,
          } as any),
      };

      if (formType.value === 'detail') {
        modalApi.close();
        return;
      }

      await apiMap[formType.value]();
      ElMessage.success('操作成功');

      emit('finish');
      modalApi.close();
    } catch {}
  },
  async onOpenChange(isOpen) {
    if (isOpen) {
      data.value = modalApi.getData();

      formType.value = data.value.formType;

      baseFormApi.setState({
        commonConfig: { disabled: formType.value === 'detail' },
      });

      if (data.value.formType === 'create') {
        return;
      }

      try {
        modalApi.setState({ loading: true });
        const detailData = await getSubsidyApplicationsDetailApi({
          subsidyapplicationsid: data.value.row.subsidyapplicationsid,
        });

        baseFormApi.setValues(detailData);
      } catch {
        // console.log(error);
      }

      modalApi.setState({ loading: false });
    }
  },
});
</script>

<template>
  <Modal :title="getTitle">
    <BaseForm />
  </Modal>
</template>
