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

import { computed, ref } from 'vue';

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

import { ElMessage } from 'element-plus';

import { useVbenForm, z } from '#/adapter/form';
import {
  addCoupon1Api,
  editCoupon1Api,
  getCoupon1DetailApi,
} from '#/api/coupon/coupon1';
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: '优惠券名称', field: 'couponmc' },
    // { title: '优惠券可用产品', field: 'couponproductids' },
    // { title: '优惠券是否可用', field: 'couponsfky' },
    {
      component: 'Input',
      fieldName: 'couponmc',
      label: '优惠券名称',
      componentProps: {
        placeholder: $t('ui.placeholder.input'),
        allowClear: true,
      },
      rules: z.string().min(1, { message: '请输入优惠券名称' }),
    },
    {
      component: 'Input',
      fieldName: 'couponproductids',
      label: '优惠券可用产品',
      componentProps: {
        placeholder: $t('ui.placeholder.input'),
        allowClear: true,
      },
      rules: z.string().min(1, { message: '请输入优惠券可用产品' }),
    },
    {
      component: 'Input',
      fieldName: 'couponsfky',
      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: () => addCoupon1Api(validate.values as Coupon1Entity),
        edit: () =>
          editCoupon1Api({
            ...validate.values,
            'couponid.value': data.value.row.couponid,
          } 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 getCoupon1DetailApi({
          couponid: data.value.row.couponid,
        });

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

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

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