<script lang="ts" setup>
import type { Coupon2Entity } from '@vben/types';

import { computed, ref } from 'vue';

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

import dayjs from 'dayjs';
import { ElMessage } from 'element-plus';

import { useVbenForm, z } from '#/adapter/form';
import {
  addCoupon2Api,
  editCoupon2Api,
  getCoupon2DetailApi,
} from '#/api/coupon/coupon2';
import { $t } from '#/locales';

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

const titleMap = {
  create: '新增优惠券',
  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: [
    {
      component: 'Input',
      fieldName: 'coupon2code',
      label: '优惠券代码',
      componentProps: {
        placeholder: $t('ui.placeholder.input'),
        allowClear: true,
      },
      rules: z.string().min(1, { message: '请输入优惠券代码' }),
    },
    {
      component: 'DatePicker',
      fieldName: 'coupon2reviewdatetime',
      label: '审核时间',
      defaultValue: dayjs().format('YYYY-MM-DD HH:mm:ss'),
      componentProps: {
        placeholder: $t('ui.placeholder.select'),
        allowClear: true,
        type: 'datetime',
        valueFormat: 'YYYY-MM-DD HH:mm:ss',
        style: { width: '100%' },
      },
      rules: z.string().min(1, { message: '请选择审核时间' }),
    },
    {
      component: 'Select',
      fieldName: 'coupon2sype',
      label: '优惠券状态',
      componentProps: {
        placeholder: $t('ui.placeholder.select'),
        allowClear: true,
        options: [
          { label: '申请中', value: 0 },
          { label: '审核通过', value: 1 },
          { label: '审核不通过', value: 2 },
        ],
      },
      rules: z.number().min(0, { message: '请选择优惠券状态' }),
    },
    {
      component: 'Select',
      fieldName: 'coupon2isused',
      label: '使用状态',
      componentProps: {
        placeholder: $t('ui.placeholder.select'),
        allowClear: true,
        options: [
          { label: '未使用', value: 0 },
          { label: '已使用', value: 1 },
        ],
      },
      rules: z.number().min(0, { message: '请选择使用状态' }),
    },
    {
      component: 'Input',
      fieldName: 'coupon2productids',
      label: '可用产品',
      componentProps: {
        placeholder: $t('ui.placeholder.input'),
        allowClear: true,
      },
      rules: z.string().min(1, { message: '请输入可用产品' }),
    },
    {
      component: 'Input',
      fieldName: 'coupon2coupon1id',
      label: '关联主券ID',
      componentProps: {
        placeholder: $t('ui.placeholder.input'),
        allowClear: true,
      },
      rules: z.string().min(1, { message: '请输入关联主券ID' }),
    },
  ],
});

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: () => addCoupon2Api(validate.values as Coupon2Entity),
        edit: () =>
          editCoupon2Api({
            ...validate.values,
            'coupon2sid.value': data.value.row.coupon2sid,
          } as any),
      };

      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;

      if (data.value.formType === 'create') {
        baseFormApi.setValues({
          coupon2reviewdatetime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
        });
        return;
      }

      // 编辑模式，加载详情数据
      if (data.value.formType === 'edit') {
        try {
          modalApi.setState({ loading: true });
          const detailData = await getCoupon2DetailApi({
            coupon2sid: data.value.row.coupon2sid,
          });

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

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

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