import type { VbenFormSchema } from '#/adapter/form';
import type { VxeTableGridOptions } from '#/adapter/vxe-table';

import { h } from 'vue';

import { z } from '#/adapter/form';

// 代理产品配置列表列配置
export function useColumns(): VxeTableGridOptions['columns'] {
  return [
    {
      field: 'id',
      title: 'ID',
      width: 80,
    },
    {
      field: 'product_name',
      title: '产品名称',
    },
    {
      field: 'base_price',
      title: '基础底价',
      formatter: ({ cellValue }: { cellValue: number }) =>
        `¥${cellValue.toFixed(2)}`,
    },
    {
      field: 'price_range_max',
      title: '最高定价',
      formatter: ({ cellValue }: { cellValue: number }) =>
        `¥${cellValue.toFixed(2)}`,
    },
    {
      field: 'price_threshold',
      title: '价格阈值',
      formatter: ({ cellValue }: { cellValue: number }) =>
        `¥${cellValue.toFixed(2)}`,
    },
    {
      field: 'price_fee_rate',
      title: '提价费率',
      formatter: ({ cellValue }: { cellValue: number }) =>
        `${(cellValue * 100).toFixed(2)}%`,
    },
    {
      align: 'center',
      slots: { default: 'operation' },
      field: 'operation',
      fixed: 'right',
      title: '操作',
      width: 120,
    },
  ] as const;
}

// 代理产品配置搜索表单配置
export function useGridFormSchema(): VbenFormSchema[] {
  return [
    {
      component: 'Input',
      fieldName: 'product_name',
      label: '产品名称',
    },
  ];
}

// 代理产品配置编辑表单配置
export function useFormSchema(): VbenFormSchema[] {
  return [
    {
      component: 'InputNumber',
      fieldName: 'base_price',
      label: '基础底价',
      rules: 'required',
      componentProps: {
        min: 0,
        precision: 2,
        step: 0.01,
      },
    },
    {
      component: 'InputNumber',
      fieldName: 'price_range_max',
      label: '最高定价',
      rules: 'required',
      componentProps: {
        min: 0,
        precision: 2,
        step: 0.01,
      },
    },
    {
      component: 'InputNumber',
      fieldName: 'price_threshold',
      label: '价格阈值',
      defaultValue: undefined,
      componentProps: {
        min: 0,
        precision: 2,
        step: 0.01,
        placeholder: '可选，不设置则不限制',
      },
      rules: z
        .number({
          invalid_type_error: '请输入有效的数字',
        })
        .min(0, '价格阈值不能小于0')
        .optional()
        .nullable(),
      dependencies: {
        triggerFields: ['base_price'],
        rules(values) {
          // 动态校验：价格阈值不能低于基础底价
          const basePrice = values.base_price;
          if (basePrice !== undefined && basePrice !== null) {
            return z
              .number({
                invalid_type_error: '请输入有效的数字',
              })
              .min(0, '价格阈值不能小于0')
              .refine(
                (val) => {
                  if (val === undefined || val === null) return true;
                  return val >= basePrice;
                },
                {
                  message: `价格阈值不能低于基础底价 ${basePrice}`,
                },
              )
              .optional()
              .nullable();
          }
          return z
            .number({
              invalid_type_error: '请输入有效的数字',
            })
            .min(0, '价格阈值不能小于0')
            .optional()
            .nullable();
        },
        trigger(_values, formApi) {
          // 当基础底价变化时，重新校验价格阈值
          formApi.validateField('price_threshold');
        },
      },
      suffix: () => h('span', { class: 'text-gray-400 text-xs' }, '可选'),
    },
    {
      component: 'InputNumber',
      fieldName: 'price_fee_rate',
      label: '提价费率',
      defaultValue: undefined,
      componentProps: {
        min: 0,
        max: 100,
        precision: 4,
        step: 0.01,
        addonAfter: '%',
        controls: true,
        placeholder: '可选，不设置则不收费',
        validateTrigger: ['blur', 'change'],
      },
      rules: z
        .number({
          invalid_type_error: '请输入有效的数字',
        })
        .min(0, '提价费率不能小于0')
        .max(100, '提价费率不能大于100%')
        .optional()
        .nullable(),
      dependencies: {
        triggerFields: ['price_threshold'],
        required(values) {
          // 如果价格阈值有值，提价费率必填
          return values.price_threshold !== undefined && values.price_threshold !== null;
        },
        rules(values) {
          // 如果价格阈值有值，提价费率必填
          if (values.price_threshold !== undefined && values.price_threshold !== null) {
            return z.number().min(0, '提价费率不能小于0').max(100, '提价费率不能大于100%');
          }
          return z.number().optional().nullable();
        },
        trigger(values, formApi) {
          // 当价格阈值清空时，也清空提价费率
          if (values.price_threshold === undefined || values.price_threshold === null) {
            formApi.setFieldValue('price_fee_rate', undefined);
          }
        },
      },
      suffix: () => h('span', { class: 'text-gray-400 text-xs' }, '可选'),
    },
  ];
}
