<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 { getProductListApi } from '#/api/product';
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 productOptions = ref<{ label: string; value: string }[]>([]);

// 获取产品列表
const fetchProductOptions = async () => {
  try {
    const response = await getProductListApi({
      pageindex: 1,
      rows: 100,
    });

    if (response && response.Data && Array.isArray(response.Data)) {
      productOptions.value = response.Data.map((item: any) => ({
        label: item.productsname || '未命名产品',
        value: item.productsid || '',
      })).filter((item: any) => item.value);
    }
  } catch (error) {
    console.error('获取产品列表失败', error);
  }
};

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: 'Select',
      fieldName: 'couponproductids',
      label: '可用产品',
      componentProps: {
        placeholder: '请选择可用产品',
        options: productOptions,
        clearable: true,
        filterable: true,
        noDataText: '暂无产品数据',
        style: { width: '100%' },
      },
      rules: z.string().min(1, { message: '请选择优惠券可用产品' }),
    },
    {
      component: 'Switch',
      fieldName: 'couponsfky',
      label: '是否可用',
      componentProps: {
        activeValue: 1,
        inactiveValue: 0,
      },
      defaultValue: 1,
      rules: z.number().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' },
      });

      // 获取产品列表
      await fetchProductOptions();

      if (data.value.formType === 'create') {
        baseFormApi.setValues({
          couponsfky: 1,
        });
        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>
