import type { VbenFormSchema } from '#/adapter/form';
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { MesPdBaseDataApi } from '#/api/mes/pd/basedata';

import { DICT_TYPE } from '@vben/constants';
import { getDictOptions } from '@vben/hooks';

import {
  createDiscountPolicy,
  createElectricityType,
  createPriceStandard,
  createServicePackage,
  createTieredPrice,
  createVoltageLevel,
  deleteDiscountPolicy,
  deleteElectricityType,
  deletePriceStandard,
  deleteServicePackage,
  deleteTieredPrice,
  deleteVoltageLevel,
  exportDiscountPolicy,
  exportElectricityType,
  exportPriceStandard,
  exportServicePackage,
  exportTieredPrice,
  exportVoltageLevel,
  getDiscountPolicy,
  getDiscountPolicyPage,
  getElectricityType,
  getElectricityTypeList,
  getElectricityTypePage,
  getPriceStandard,
  getPriceStandardPage,
  getServicePackage,
  getServicePackageList,
  getServicePackagePage,
  getTieredPrice,
  getTieredPricePage,
  getVoltageLevel,
  getVoltageLevelList,
  getVoltageLevelPage,
  updateDiscountPolicy,
  updateElectricityType,
  updatePriceStandard,
  updateServicePackage,
  updateTieredPrice,
  updateVoltageLevel,
} from '#/api/mes/pd/basedata';

/** 表单类型 */
export type FormType = 'create' | 'detail' | 'update';

/** 实体 API 映射（泛型 CRUD） */
export interface EntityApi {
  page: (params: any) => Promise<any>;
  get: (id: number) => Promise<any>;
  create: (data: any) => Promise<any>;
  update: (data: any) => Promise<any>;
  remove: (id: number) => Promise<any>;
  exportExcel: (params: any) => Promise<any>;
}

/** 基础数据 Tab 配置 */
export interface BaseDataEntity {
  key: string;
  title: string;
  api: EntityApi;
  columns: VxeTableGridOptions<any>['columns'];
  gridFormSchema: VbenFormSchema[];
  formSchema: VbenFormSchema[];
}

/** 加载定价对象下拉（1服务套餐/2电压等级/3用电类型） */
export async function loadObjectOptions(
  type?: number | null,
): Promise<{ label: string; value: number }[]> {
  if (type === 1) {
    const list = await getServicePackageList();
    return list.map((i) => ({ label: i.name ?? '', value: i.id ?? 0 }));
  }
  if (type === 2) {
    const list = await getVoltageLevelList();
    return list.map((i) => ({ label: i.name ?? '', value: i.id ?? 0 }));
  }
  if (type === 3) {
    const list = await getElectricityTypeList();
    return list.map((i) => ({ label: i.name ?? '', value: i.id ?? 0 }));
  }
  return [];
}

/** 对象类型下拉（1服务套餐/2电压等级/3用电类型） */
function useObjectTypeOptions() {
  return getDictOptions(DICT_TYPE.MES_PD_PRICE_OBJECT_TYPE, 'number');
}

/** 通用启用状态列 */
function useStatusColumn(title = '启用状态') {
  return {
    field: 'status',
    title,
    width: 90,
    cellRender: {
      name: 'CellDict',
      props: { type: DICT_TYPE.MES_PD_PRODUCT_STATUS },
    },
  } as const;
}

/** 用电类型 */
export const ElectricityTypeConfig: BaseDataEntity = {
  key: 'electricityType',
  title: '用电类型',
  api: {
    page: getElectricityTypePage,
    get: getElectricityType,
    create: createElectricityType,
    update: updateElectricityType,
    remove: deleteElectricityType,
    exportExcel: exportElectricityType,
  },
  columns: [
    { field: 'code', title: '类型编码', width: 140 },
    { field: 'name', title: '类型名称', minWidth: 160 },
    { field: 'description', title: '类型说明', minWidth: 200 },
    { field: 'sort', title: '排序', width: 80 },
    useStatusColumn(),
    {
      field: 'createTime',
      title: '创建时间',
      width: 170,
      formatter: 'formatDateTime',
    },
    { title: '操作', width: 200, fixed: 'right', slots: { default: 'actions' } },
  ],
  gridFormSchema: [
    {
      fieldName: 'name',
      label: '类型名称',
      component: 'Input',
      componentProps: { placeholder: '请输入类型名称' },
    },
  ],
  formSchema: [
    {
      fieldName: 'id',
      component: 'Input',
      dependencies: { triggerFields: [''], show: () => false },
    },
    {
      fieldName: 'code',
      label: '类型编码',
      component: 'Input',
      componentProps: { placeholder: '请输入类型编码' },
      rules: 'required',
    },
    {
      fieldName: 'name',
      label: '类型名称',
      component: 'Input',
      componentProps: { placeholder: '请输入类型名称' },
      rules: 'required',
    },
    {
      fieldName: 'description',
      label: '类型说明',
      component: 'Textarea',
      formItemClass: 'col-span-3',
      componentProps: { placeholder: '请输入类型说明', rows: 2 },
    },
    {
      fieldName: 'sort',
      label: '排序',
      component: 'InputNumber',
      componentProps: { class: '!w-full', min: 0, precision: 0 },
    },
    {
      fieldName: 'status',
      label: '启用状态',
      component: 'Select',
      componentProps: {
        allowClear: true,
        options: getDictOptions(DICT_TYPE.MES_PD_PRODUCT_STATUS, 'number'),
        placeholder: '请选择启用状态',
      },
    },
  ],
};

/** 电压等级 */
export const VoltageLevelConfig: BaseDataEntity = {
  key: 'voltageLevel',
  title: '电压等级',
  api: {
    page: getVoltageLevelPage,
    get: getVoltageLevel,
    create: createVoltageLevel,
    update: updateVoltageLevel,
    remove: deleteVoltageLevel,
    exportExcel: exportVoltageLevel,
  },
  columns: [
    { field: 'code', title: '等级编码', width: 140 },
    { field: 'name', title: '等级名称', minWidth: 160 },
    { field: 'voltageValue', title: '电压数值(kV)', width: 120 },
    { field: 'sort', title: '排序', width: 80 },
    useStatusColumn(),
    {
      field: 'createTime',
      title: '创建时间',
      width: 170,
      formatter: 'formatDateTime',
    },
    { title: '操作', width: 200, fixed: 'right', slots: { default: 'actions' } },
  ],
  gridFormSchema: [
    {
      fieldName: 'name',
      label: '等级名称',
      component: 'Input',
      componentProps: { placeholder: '请输入等级名称' },
    },
  ],
  formSchema: [
    {
      fieldName: 'id',
      component: 'Input',
      dependencies: { triggerFields: [''], show: () => false },
    },
    {
      fieldName: 'code',
      label: '等级编码',
      component: 'Input',
      componentProps: { placeholder: '请输入等级编码' },
      rules: 'required',
    },
    {
      fieldName: 'name',
      label: '等级名称',
      component: 'Input',
      componentProps: { placeholder: '请输入等级名称' },
      rules: 'required',
    },
    {
      fieldName: 'voltageValue',
      label: '电压数值(kV)',
      component: 'InputNumber',
      componentProps: { class: '!w-full', min: 0, precision: 2 },
    },
    {
      fieldName: 'sort',
      label: '排序',
      component: 'InputNumber',
      componentProps: { class: '!w-full', min: 0, precision: 0 },
    },
    {
      fieldName: 'status',
      label: '启用状态',
      component: 'Select',
      componentProps: {
        allowClear: true,
        options: getDictOptions(DICT_TYPE.MES_PD_PRODUCT_STATUS, 'number'),
        placeholder: '请选择启用状态',
      },
    },
  ],
};

/** 服务套餐 */
export const ServicePackageConfig: BaseDataEntity = {
  key: 'servicePackage',
  title: '服务套餐',
  api: {
    page: getServicePackagePage,
    get: getServicePackage,
    create: createServicePackage,
    update: updateServicePackage,
    remove: deleteServicePackage,
    exportExcel: exportServicePackage,
  },
  columns: [
    { field: 'code', title: '套餐编码', width: 150 },
    { field: 'name', title: '套餐名称', minWidth: 160 },
    {
      field: 'price',
      title: '套餐价格',
      width: 110,
      formatter: 'formatNumber',
    },
    {
      field: 'effectiveDate',
      title: '生效日期',
      width: 160,
      formatter: 'formatDateTime',
    },
    {
      field: 'expireDate',
      title: '失效日期',
      width: 160,
      formatter: 'formatDateTime',
    },
    useStatusColumn(),
    {
      field: 'createTime',
      title: '创建时间',
      width: 170,
      formatter: 'formatDateTime',
    },
    { title: '操作', width: 200, fixed: 'right', slots: { default: 'actions' } },
  ],
  gridFormSchema: [
    {
      fieldName: 'name',
      label: '套餐名称',
      component: 'Input',
      componentProps: { placeholder: '请输入套餐名称' },
    },
  ],
  formSchema: [
    {
      fieldName: 'id',
      component: 'Input',
      dependencies: { triggerFields: [''], show: () => false },
    },
    {
      fieldName: 'code',
      label: '套餐编码',
      component: 'Input',
      componentProps: { placeholder: '保存时自动生成', disabled: true },
    },
    {
      fieldName: 'name',
      label: '套餐名称',
      component: 'Input',
      componentProps: { placeholder: '请输入套餐名称' },
      rules: 'required',
    },
    {
      fieldName: 'description',
      label: '套餐说明',
      component: 'Textarea',
      formItemClass: 'col-span-3',
      componentProps: { placeholder: '请输入套餐说明', rows: 2 },
    },
    {
      fieldName: 'price',
      label: '套餐价格',
      component: 'InputNumber',
      componentProps: { class: '!w-full', min: 0, precision: 2 },
    },
    {
      fieldName: 'effectiveDate',
      label: '生效日期',
      component: 'DatePicker',
      componentProps: { class: '!w-full', valueFormat: 'YYYY-MM-DD HH:mm:ss' },
    },
    {
      fieldName: 'expireDate',
      label: '失效日期',
      component: 'DatePicker',
      componentProps: { class: '!w-full', valueFormat: 'YYYY-MM-DD HH:mm:ss' },
    },
    {
      fieldName: 'status',
      label: '启用状态',
      component: 'Select',
      componentProps: {
        allowClear: true,
        options: getDictOptions(DICT_TYPE.MES_PD_PRODUCT_STATUS, 'number'),
        placeholder: '请选择启用状态',
      },
    },
  ],
};

/** 定价标准 */
export const PriceStandardConfig: BaseDataEntity = {
  key: 'priceStandard',
  title: '定价标准',
  api: {
    page: getPriceStandardPage,
    get: getPriceStandard,
    create: createPriceStandard,
    update: updatePriceStandard,
    remove: deletePriceStandard,
    exportExcel: exportPriceStandard,
  },
  columns: [
    {
      field: 'objectType',
      title: '定价对象类型',
      width: 120,
      cellRender: {
        name: 'CellDict',
        props: { type: DICT_TYPE.MES_PD_PRICE_OBJECT_TYPE },
      },
    },
    { field: 'objectName', title: '定价对象', minWidth: 180 },
    {
      field: 'price',
      title: '价格',
      width: 110,
      formatter: 'formatNumber',
    },
    { field: 'unit', title: '计价单位', width: 100 },
    {
      field: 'effectiveDate',
      title: '生效日期',
      width: 160,
      formatter: 'formatDateTime',
    },
    useStatusColumn(),
    {
      field: 'createTime',
      title: '创建时间',
      width: 170,
      formatter: 'formatDateTime',
    },
    { title: '操作', width: 200, fixed: 'right', slots: { default: 'actions' } },
  ],
  gridFormSchema: [
    {
      fieldName: 'objectType',
      label: '定价对象类型',
      component: 'Select',
      componentProps: {
        allowClear: true,
        options: useObjectTypeOptions(),
        placeholder: '请选择定价对象类型',
      },
    },
  ],
  formSchema: [
    {
      fieldName: 'id',
      component: 'Input',
      dependencies: { triggerFields: [''], show: () => false },
    },
    {
      fieldName: 'objectType',
      label: '定价对象类型',
      component: 'Select',
      rules: 'selectRequired',
      componentProps: {
        allowClear: true,
        options: useObjectTypeOptions(),
        placeholder: '请选择定价对象类型',
      },
    },
    {
      fieldName: 'objectId',
      label: '定价对象',
      component: 'Select',
      rules: 'selectRequired',
      dependencies: {
        triggerFields: ['objectType'],
        async componentProps(values, form) {
          const options = await loadObjectOptions(values.objectType);
          return {
            allowClear: true,
            placeholder: '请选择定价对象',
            options,
            onChange: (value: number) => {
              const opt = options.find((o) => o.value === value);
              form.setFieldValue('objectName', opt?.label ?? '');
            },
          };
        },
      },
    },
    {
      fieldName: 'objectName',
      component: 'Input',
      dependencies: { triggerFields: [''], show: () => false },
    },
    {
      fieldName: 'price',
      label: '价格',
      component: 'InputNumber',
      componentProps: { class: '!w-full', min: 0, precision: 2 },
      rules: 'required',
    },
    {
      fieldName: 'unit',
      label: '计价单位',
      component: 'Input',
      componentProps: { placeholder: '请输入计价单位' },
    },
    {
      fieldName: 'effectiveDate',
      label: '生效日期',
      component: 'DatePicker',
      componentProps: { class: '!w-full', valueFormat: 'YYYY-MM-DD HH:mm:ss' },
    },
    {
      fieldName: 'status',
      label: '启用状态',
      component: 'Select',
      componentProps: {
        allowClear: true,
        options: getDictOptions(DICT_TYPE.MES_PD_PRODUCT_STATUS, 'number'),
        placeholder: '请选择启用状态',
      },
    },
  ],
};

/** 优惠策略 */
export const DiscountPolicyConfig: BaseDataEntity = {
  key: 'discountPolicy',
  title: '优惠策略',
  api: {
    page: getDiscountPolicyPage,
    get: getDiscountPolicy,
    create: createDiscountPolicy,
    update: updateDiscountPolicy,
    remove: deleteDiscountPolicy,
    exportExcel: exportDiscountPolicy,
  },
  columns: [
    { field: 'name', title: '策略名称', minWidth: 160 },
    {
      field: 'policyType',
      title: '策略类型',
      width: 100,
      cellRender: {
        name: 'CellDict',
        props: { type: DICT_TYPE.MES_PD_DISCOUNT_POLICY_TYPE },
      },
    },
    {
      field: 'policyValue',
      title: '策略值',
      width: 110,
      formatter: 'formatNumber',
    },
    {
      field: 'targetType',
      title: '适用对象类型',
      width: 120,
      cellRender: {
        name: 'CellDict',
        props: { type: DICT_TYPE.MES_PD_PRICE_OBJECT_TYPE },
      },
    },
    {
      field: 'startDate',
      title: '生效日期',
      width: 160,
      formatter: 'formatDateTime',
    },
    {
      field: 'endDate',
      title: '失效日期',
      width: 160,
      formatter: 'formatDateTime',
    },
    useStatusColumn(),
    {
      field: 'createTime',
      title: '创建时间',
      width: 170,
      formatter: 'formatDateTime',
    },
    { title: '操作', width: 200, fixed: 'right', slots: { default: 'actions' } },
  ],
  gridFormSchema: [
    {
      fieldName: 'name',
      label: '策略名称',
      component: 'Input',
      componentProps: { placeholder: '请输入策略名称' },
    },
    {
      fieldName: 'policyType',
      label: '策略类型',
      component: 'Select',
      componentProps: {
        allowClear: true,
        options: getDictOptions(DICT_TYPE.MES_PD_DISCOUNT_POLICY_TYPE, 'number'),
        placeholder: '请选择策略类型',
      },
    },
  ],
  formSchema: [
    {
      fieldName: 'id',
      component: 'Input',
      dependencies: { triggerFields: [''], show: () => false },
    },
    {
      fieldName: 'name',
      label: '策略名称',
      component: 'Input',
      componentProps: { placeholder: '请输入策略名称' },
      rules: 'required',
    },
    {
      fieldName: 'policyType',
      label: '策略类型',
      component: 'Select',
      rules: 'selectRequired',
      componentProps: {
        allowClear: true,
        options: getDictOptions(DICT_TYPE.MES_PD_DISCOUNT_POLICY_TYPE, 'number'),
        placeholder: '请选择策略类型',
      },
    },
    {
      fieldName: 'policyValue',
      label: '策略值',
      component: 'InputNumber',
      componentProps: {
        class: '!w-full',
        min: 0,
        precision: 2,
        placeholder: '折扣填0-1比例，立减填金额',
      },
      help: '折扣：0-1 之间的比例；立减：按金额减免',
      rules: 'required',
    },
    {
      fieldName: 'targetType',
      label: '适用对象类型',
      component: 'Select',
      componentProps: {
        allowClear: true,
        options: useObjectTypeOptions(),
        placeholder: '不选则全局适用',
      },
    },
    {
      fieldName: 'targetId',
      label: '适用对象',
      component: 'Select',
      dependencies: {
        triggerFields: ['targetType'],
        disabled: (values) => !values.targetType,
        async componentProps(values) {
          const options = await loadObjectOptions(values.targetType);
          return {
            allowClear: true,
            placeholder: values.targetType ? '请选择适用对象' : '全局适用',
            options,
          };
        },
      },
    },
    {
      fieldName: 'startDate',
      label: '生效日期',
      component: 'DatePicker',
      componentProps: { class: '!w-full', valueFormat: 'YYYY-MM-DD HH:mm:ss' },
    },
    {
      fieldName: 'endDate',
      label: '失效日期',
      component: 'DatePicker',
      componentProps: { class: '!w-full', valueFormat: 'YYYY-MM-DD HH:mm:ss' },
    },
    {
      fieldName: 'status',
      label: '启用状态',
      component: 'Select',
      componentProps: {
        allowClear: true,
        options: getDictOptions(DICT_TYPE.MES_PD_PRODUCT_STATUS, 'number'),
        placeholder: '请选择启用状态',
      },
    },
  ],
};

/** 阶梯电价 */
export const TieredPriceConfig: BaseDataEntity = {
  key: 'tieredPrice',
  title: '阶梯电价',
  api: {
    page: getTieredPricePage,
    get: getTieredPrice,
    create: createTieredPrice,
    update: updateTieredPrice,
    remove: deleteTieredPrice,
    exportExcel: exportTieredPrice,
  },
  columns: [
    { field: 'packageId', title: '服务套餐ID', width: 110 },
    { field: 'voltageLevelId', title: '电压等级ID', width: 110 },
    { field: 'startValue', title: '下限(含,kWh)', width: 120 },
    { field: 'endValue', title: '上限(不含,kWh)', width: 130 },
    {
      field: 'pricePerUnit',
      title: '档位单价',
      width: 110,
      formatter: 'formatNumber',
    },
    useStatusColumn(),
    {
      field: 'createTime',
      title: '创建时间',
      width: 170,
      formatter: 'formatDateTime',
    },
    { title: '操作', width: 200, fixed: 'right', slots: { default: 'actions' } },
  ],
  gridFormSchema: [
    {
      fieldName: 'packageId',
      label: '服务套餐ID',
      component: 'Input',
      componentProps: { placeholder: '请输入服务套餐ID' },
    },
  ],
  formSchema: [
    {
      fieldName: 'id',
      component: 'Input',
      dependencies: { triggerFields: [''], show: () => false },
    },
    {
      fieldName: 'packageId',
      label: '服务套餐',
      component: 'Select',
      componentProps: {
        allowClear: true,
        placeholder: '选择服务套餐（与电压等级二选一）',
      },
      dependencies: {
        triggerFields: ['voltageLevelId'],
        disabled: (values) => !!values.voltageLevelId,
        async componentProps(values) {
          const list = await getServicePackageList();
          return {
            allowClear: true,
            options: list.map((i) => ({ label: i.name, value: i.id })),
            placeholder: '选择服务套餐（与电压等级二选一）',
          };
        },
      },
    },
    {
      fieldName: 'voltageLevelId',
      label: '电压等级',
      component: 'Select',
      componentProps: {
        allowClear: true,
        placeholder: '选择电压等级（与服务套餐二选一）',
      },
      dependencies: {
        triggerFields: ['packageId'],
        disabled: (values) => !!values.packageId,
        async componentProps() {
          const list = await getVoltageLevelList();
          return {
            allowClear: true,
            options: list.map((i) => ({ label: i.name, value: i.id })),
            placeholder: '选择电压等级（与服务套餐二选一）',
          };
        },
      },
    },
    {
      fieldName: 'startValue',
      label: '档位下限(含,kWh)',
      component: 'InputNumber',
      componentProps: { class: '!w-full', min: 0, precision: 2 },
      rules: 'required',
    },
    {
      fieldName: 'endValue',
      label: '档位上限(不含,kWh)',
      component: 'InputNumber',
      componentProps: {
        class: '!w-full',
        min: 0,
        precision: 2,
        placeholder: '为空表示上不封顶',
      },
    },
    {
      fieldName: 'pricePerUnit',
      label: '档位单价',
      component: 'InputNumber',
      componentProps: { class: '!w-full', min: 0, precision: 4 },
      rules: 'required',
    },
    {
      fieldName: 'status',
      label: '启用状态',
      component: 'Select',
      componentProps: {
        allowClear: true,
        options: getDictOptions(DICT_TYPE.MES_PD_TIERED_PRICE_STATUS, 'number'),
        placeholder: '请选择启用状态',
      },
    },
  ],
};

/** 全部 Tab 配置 */
export const BaseDataConfigs: BaseDataEntity[] = [
  ElectricityTypeConfig,
  VoltageLevelConfig,
  ServicePackageConfig,
  PriceStandardConfig,
  DiscountPolicyConfig,
  TieredPriceConfig,
];
