import type { FormSchemaGetter } from '#/adapter/form';
import type { VxeGridProps } from '#/adapter/vxe-table';

import { DictEnum } from '@vben/constants';

import { ElOption, ElSelect } from 'element-plus';

import { assetTypeList } from '#/api/system/asset/asset';
import { selectAllSysStationAreaList } from '#/api/system/infoEntry/stationInfo/stationInfo';
import { getFileUploadConfig } from '#/components/upload';
import { getDictOptions } from '#/utils/dict';
import { renderDictTag } from '#/utils/render';

// // 字典标识常量
// export const DICT_KEYS = {
//   // 资产状态字典标识
//   ASSET_STATUS: 'asset_status',
//   // 资产预警类型
//   ALERT_TYPE: 'alert_type',
// };

// 获取资产类型列表
const getAssetTypeList = async () => {
  try {
    const resp = await assetTypeList({});
    const data = resp.rows || [];
    return Array.isArray(data)
      ? data.map((item: any) => ({
          label: item.typeName,
          value: item.id.toString(),
        }))
      : [];
  } catch (error) {
    console.error('获取资产类型失败:', error);
    return [];
  }
};

// 获取油站列表
const getStationList = async () => {
  try {
    const resp = await selectAllSysStationAreaList();
    const data = resp || [];
    return Array.isArray(data)
      ? data.map((item: any) => ({
          label: item.stationName,
          value: item.id.toString(),
        }))
      : [];
  } catch (error) {
    console.error('获取油站列表失败:', error);
    return [];
  }
};

// 获取资产状态字典选项
const getAssetStatusOptions = () => getDictOptions(DictEnum.ASSET_STATUS);

export const queryFormSchema: FormSchemaGetter = () => [
  {
    component: 'ApiSelect',
    fieldName: 'typeId',
    label: '资产类型',
    componentProps: {
      placeholder: '请选择资产类型',
      api: getAssetTypeList,
    },
  },
  {
    component: 'Input',
    fieldName: 'assetName',
    label: '资产名称',
    componentProps: {
      placeholder: '请输入资产名称',
    },
  },
  {
    component: 'Input',
    fieldName: 'assetCode',
    label: '资产编码',
    componentProps: {
      placeholder: '请输入资产编码',
    },
  },
  {
    component: 'ApiSelect',
    fieldName: 'stationId',
    label: '所在油站',
    componentProps: {
      placeholder: '请选择所在油站',
      api: getStationList,
    },
  },
  {
    component: 'Input',
    fieldName: 'manufacturer',
    label: '生产厂商',
    componentProps: {
      placeholder: '请输入生产厂商',
    },
  },
  {
    component: 'Input',
    fieldName: 'manufacturerContact',
    label: '厂商联系人',
    componentProps: {
      placeholder: '请输入生产厂商联系人',
    },
  },
  {
    component: 'DatePicker',
    componentProps: {
      type: 'daterange',
      format: 'YYYY-MM-DD',
      valueFormat: 'YYYY-MM-DD HH:mm:ss',
      placeholder: '请选择资产生产日期',
      style: {
        width: '100%',
      },
    },
    fieldName: 'productionDate',
    label: '生产日期',
  },
  {
    component: 'DatePicker',
    componentProps: {
      type: 'daterange',
      format: 'YYYY-MM-DD',
      valueFormat: 'YYYY-MM-DD HH:mm:ss',
      placeholder: '请选择资产投用日期',
      style: {
        width: '100%',
      },
    },
    fieldName: 'useDate',
    label: '投用日期',
  },
  // {
  //   component: 'InputNumber',
  //   fieldName: 'serviceLife',
  //   label: '使用年限',
  //   componentProps: {
  //     placeholder: '请输入资产使用年限',
  //     min: 0,
  //   },
  // },
  // {
  //   component: 'Select',
  //   fieldName: 'alertType',
  //   label: '预警提醒',
  //   componentProps: {
  //     placeholder: '请选择预警类型',
  //     options: getAlertTypeOptions(),
  //   },
  // },
  {
    component: 'Select',
    componentProps: {
      placeholder: '请选择资产状态',
      options: getAssetStatusOptions(),
    },
    fieldName: 'status',
    label: '资产状态',
  },
];

export const tableColumns: VxeGridProps['columns'] = [
  {
    type: 'checkbox',
    width: 80,
  },
  {
    field: 'typeName',
    title: '资产类型',
    minWidth: 120,
  },
  {
    field: 'assetName',
    title: '资产名称',
    minWidth: 150,
  },
  {
    field: 'assetCode',
    title: '资产编码',
    minWidth: 120,
  },
  {
    field: 'stationName',
    title: '所在油站',
    minWidth: 120,
  },
  {
    field: 'manufacturer',
    title: '生产厂商',
    minWidth: 120,
  },
  {
    field: 'manufacturerContact',
    title: '生产厂商联系人',
    minWidth: 120,
  },
  {
    field: 'productionDate',
    title: '资产生产日期',
    minWidth: 120,
  },
  {
    field: 'useDate',
    title: '资产投用日期',
    minWidth: 120,
  },
  {
    field: 'status',
    title: '资产状态',
    minWidth: 100,
    slots: {
      default: ({ row }) => {
        // const statusMap = {
        //   normal: { type: 'success', text: '正常' },
        //   warning: { type: 'warning', text: '预警' },
        //   expired: { type: 'danger', text: '过期' },
        // };
        // const statusInfo = statusMap[row.status] || {
        //   type: 'info',
        //   text: row.status,
        // };
        return renderDictTag(row.status, getAssetStatusOptions());
      },
    },
  },
  {
    field: 'alertDate',
    title: '资产到期时间',
    minWidth: 120,
    slots: {
      default: ({ row }) => {
        // 计算剩余天数
        if (!row.alertDate) {
          return '-';
        }
        const alertDate = new Date(row.alertDate);
        const today = new Date();
        const diffTime = alertDate.getTime() - today.getTime();
        const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));

        // 根据剩余天数设置颜色
        let type = 'success';
        if (diffDays <= 0) {
          type = 'danger';
        } else if (diffDays <= 30) {
          type = 'warning';
        }

        return <el-tag type={type}>{row.alertDate}</el-tag>;
      },
    },
  },
  {
    field: 'action',
    fixed: 'right',
    slots: { default: 'action' },
    title: '操作',
    width: 200,
  },
];

export const drawerFormSchema: FormSchemaGetter = () => [
  {
    component: 'Input',
    dependencies: {
      show: () => false,
      triggerFields: [''],
    },
    fieldName: 'id',
  },
  {
    component: 'ApiSelect',
    fieldName: 'typeId',
    label: '资产类型',
    componentProps: {
      placeholder: '请选择资产类型',
      api: getAssetTypeList,
    },
    rules: 'required',
  },
  {
    component: 'Input',
    fieldName: 'assetName',
    label: '资产名称',
    componentProps: {
      placeholder: '请输入资产名称',
      maxlength: 100,
    },
    rules: 'required',
  },
  {
    component: 'Input',
    fieldName: 'assetCode',
    label: '资产编码',
    componentProps: {
      placeholder: '请输入资产编码',
      maxlength: 100,
    },
  },
  {
    component: 'ApiSelect',
    fieldName: 'stationId',
    label: '所在油站',
    componentProps: {
      placeholder: '请选择所在油站',
      api: getStationList,
    },
    rules: 'required',
  },
  {
    component: 'Input',
    fieldName: 'manufacturer',
    label: '生产厂商',
    componentProps: {
      placeholder: '请输入生产厂商',
      maxlength: 100,
    },
  },
  {
    component: 'Input',
    fieldName: 'manufacturerContact',
    label: '生产厂商联系人',
    componentProps: {
      placeholder: '请输入生产厂商联系人',
      maxlength: 100,
    },
  },
  {
    component: 'DatePicker',
    componentProps: {
      type: 'date',
      format: 'YYYY-MM-DD',
      valueFormat: 'YYYY-MM-DD HH:mm:ss',
      placeholder: '请选择资产生产日期',
      style: {
        width: '100%',
      },
    },
    fieldName: 'productionDate',
    label: '资产生产日期',
  },
  {
    component: 'DatePicker',
    componentProps: {
      type: 'date',
      format: 'YYYY-MM-DD',
      valueFormat: 'YYYY-MM-DD HH:mm:ss',
      placeholder: '请选择资产投用日期',
      style: {
        width: '100%',
      },
    },
    fieldName: 'useDate',
    label: '资产投用日期',
  },
  {
    component: 'InputNumber',
    fieldName: 'serviceLife',
    label: '资产使用年限',
    componentProps: {
      placeholder: '请输入资产使用年限',
      min: 0,
      style: {
        width: '100%',
      },
    },
  },
  {
    component: 'Input',
    fieldName: 'alert',
    label: '预警提醒',
    help: '资产到期时间预警提醒值',
    componentProps: (data: any, formApi: any) => {
      return {
        placeholder: '请输入预警提醒值',
        min: 0,
        max: 100,
        style: {
          width: '100%',
        },
        onBlur: () => {
          // 正则判断输入的是不是整数，不是的话就改为空
          if (!/^\d+$/.test(data.alert)) {
            data.alert = '';
            formApi.setFieldValue('alert', '');
          } else if (Number(data.alert) > 100) {
            data.alert = '100';
            formApi.setFieldValue('alert', '100');
          }
        },
      };
    },
    renderComponentContent: (row: any) => {
      return {
        // append: () => '天',
        append: () => {
          const options = [
            { label: '月', value: '月' },
            { label: '日', value: '日' },
          ];
          return (
            <ElSelect
              clearable
              placeholder="请选择"
              style={{ width: '100px' }}
              v-model={row.alertType}
            >
              {options.map((option) => (
                <ElOption
                  key={option.value}
                  label={option.label}
                  value={option.value}
                />
              ))}
            </ElSelect>
          );
        },
      };
    },
  },
  // {
  //   component: 'Input',
  //   fieldName: 'alertType',
  //   label: '预警类型',
  //   dependencies: {
  //     show: () => false,
  //     // triggerFields: ['alert'],
  //   },
  // },
  {
    component: 'Input',
    fieldName: 'attachments',
    dependencies: {
      show: () => false,
      triggerFields: [''],
    },
  },
  {
    component: 'Upload',
    fieldName: 'attachmentsUrl',
    label: '资产附件',
    componentProps: () => {
      return {
        ...getFileUploadConfig(
          '.jpg,.jpeg,.png',
          'picture-card',
          5,
          '/common/upload',
        ),
        onSuccess: () => {},
      };
    },
    renderComponentContent: () => {
      return {
        default: () => '点击上传照片',
      };
    },
  },
  {
    component: 'Select',
    fieldName: 'status',
    label: '资产状态',
    componentProps: {
      placeholder: '请选择资产状态',
      options: getAssetStatusOptions(),
    },
  },
];
