<script lang="ts" setup>
import type { ExtendedFormApi } from '@vben/common-ui';
import type { OrdersEntity } 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 { addOrdersApi, editOrdersApi, getOrdersDetailApi } from '#/api/orders';

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: 'ordersnumber',
      label: '订单号',
      componentProps: {
        placeholder: '请输入订单号',
        allowClear: true,
      },
      rules: z.string().min(1, { message: '请输入订单号' }),
    },
    {
      component: 'Input',
      fieldName: 'ordersuserid',
      label: '订单关联用户id',
      componentProps: {
        placeholder: '请输入订单关联用户id',
        allowClear: true,
      },
      rules: z.string().min(1, { message: '请输入订单关联用户id' }),
    },
    {
      component: 'Input',
      fieldName: 'ordersproductid',
      label: '订单关联产品id',
      componentProps: {
        placeholder: '请输入订单关联产品id',
        allowClear: true,
      },
      rules: z.string().min(1, { message: '请输入订单关联产品id' }),
    },
    {
      component: 'Input',
      fieldName: 'ordersproductname',
      label: '产品名称',
      componentProps: {
        placeholder: '请输入产品名称',
        allowClear: true,
      },
      rules: z.string().min(1, { message: '请输入产品名称' }),
    },
    {
      component: 'Input',
      fieldName: 'ordersproductsn',
      label: '产品sn',
      componentProps: {
        placeholder: '请输入产品sn',
        allowClear: true,
      },
      rules: z.string().min(1, { message: '请输入产品sn' }),
    },
    {
      component: 'Input',
      fieldName: 'productsmodel',
      label: '产品型号',
      componentProps: {
        placeholder: '请输入产品型号',
        allowClear: true,
      },
      rules: z.string().min(1, { message: '请输入产品型号' }),
    },
    {
      component: 'Input',
      fieldName: 'jxsname',
      label: '经销商',
      componentProps: {
        placeholder: '请输入经销商',
        allowClear: true,
      },
      rules: z.string().min(1, { message: '请输入经销商' }),
    },
    {
      component: 'Input',
      fieldName: 'orderstotalprice',
      label: '订单总金额',
      componentProps: {
        placeholder: '请输入订单总金额',
        allowClear: true,
      },
      rules: z.number().min(0, { message: '请输入有效的订单总金额' }),
    },
    {
      component: 'Input',
      fieldName: 'ordersdiscountprice',
      label: '订单优惠后金额',
      componentProps: {
        placeholder: '请输入订单优惠后金额',
        allowClear: true,
      },
      rules: z.number().min(0, { message: '请输入有效的订单优惠后金额' }),
    },
    {
      component: 'Input',
      fieldName: 'ordersyhprice',
      label: '优惠金额',
      componentProps: {
        placeholder: '请输入优惠金额',
        allowClear: true,
      },
      rules: z.number().min(0, { message: '请输入有效的优惠金额' }),
    },
    {
      component: 'Input',
      fieldName: 'orderscouponid',
      label: '优惠券id',
      componentProps: {
        placeholder: '请输入优惠券id',
        allowClear: true,
      },
      rules: z.string().min(1, { message: '请输入优惠券id' }),
    },
    {
      component: 'Select',
      fieldName: 'ordersorderstatus',
      label: '订单状态',
      componentProps: {
        placeholder: '请选择订单状态',
        options: [
          { label: '待审核', value: 0 },
          { label: '已支付', value: 1 },
          { label: '已完成', value: 2 },
        ],
      },
      rules: z.number().min(0, { 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: () => addOrdersApi(validate.values as OrdersEntity),
        edit: () =>
          editOrdersApi({
            ...validate.values,
            'ordersid.value': data.value.row.ordersid,
          } 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.resetForm();
        return;
      }

      // 编辑模式，加载订单详情
      try {
        modalApi.setState({ loading: true });
        await getOrderDetail(data.value.row.ordersid, baseFormApi);
      } catch (error) {
        console.error('加载订单详情失败:', error);
      }

      modalApi.setState({ loading: false });
    }
  },
});

// 获取订单详情
const getOrderDetail = async (ordersid: string, formApi: ExtendedFormApi) => {
  const detailData = await getOrdersDetailApi({
    ordersid,
  });

  formApi.setValues(detailData);
};
</script>

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