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

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

import { requestClient } from '#/api/request';
import { selectAllSysStationAreaList } from '#/api/system/infoEntry/stationInfo/stationInfo';
import { getFileUploadConfig } from '#/components/upload';
// import { uploadFile } from '#/api/upload';
import { getDictOptions } from '#/utils/dict';
import { renderDict } from '#/utils/render';

// 字典标识常量
const DICT_KEYS = {
  // 驾照字典标识
  ID_PAPERS_NAME: 'id_papers_name',
  // 机构字典标识
  ID_PAPERS_ORGANIZATION: 'id_papers_organization',
  // 存放处字典标识
  ID_PAPERS_STORAGE: 'id_papers_storage',
  // 状态字典标识
  STATUS: 'status',
};

// 获取证照类型列表
const getCertificateTypes = async () => {
  try {
    const resp = await requestClient.get('/sysLicenseRule/rule/allList');
    const data = resp || [];
    return Array.isArray(data)
      ? data.map((item: any) => ({
          label: item.licenseName,
          value: item.id,
        }))
      : [];
  } catch (error) {
    console.error('获取证照类型失败:', error);
    return [];
  }
};

// 获取机构类型字典选项
const getOrganizationTypes = () =>
  getDictOptions(DICT_KEYS.ID_PAPERS_ORGANIZATION);

// 获取存放处字典选项
const getStorageLocations = () => getDictOptions(DICT_KEYS.ID_PAPERS_STORAGE);

export const queryFormSchema: FormSchemaGetter = () => [
  {
    component: 'ApiSelect',
    fieldName: 'stationId',
    label: '油站',
    componentProps: {
      placeholder: '请选择油站',
      api: async () => {
        const resp = await selectAllSysStationAreaList();
        const data = resp || [];
        return Array.isArray(data)
          ? data.map((item: any) => ({
              label: item.stationName,
              value: item.id.toString(),
            }))
          : [];
      },
    },
  },
  {
    component: 'ApiSelect',
    componentProps: {
      placeholder: '请选择证照名称',
      api: getCertificateTypes,
    },
    fieldName: 'licenseNameCode',
    label: '证照名称',
  },
  {
    component: 'DatePicker',
    componentProps: {
      type: 'daterange',
      format: 'YYYY-MM-DD',
      valueFormat: 'YYYY-MM-DD HH:mm:ss',
      startPlaceholder: '开始日期',
      endPlaceholder: '结束日期',
      style: {
        width: '100%',
      },
    },
    fieldName: 'validDate',
    label: '有效日期',
  },

  {
    component: 'Select',
    componentProps: {
      placeholder: '请选择状态',
      options: getDictOptions(DictEnum.SYS_DISABLED_STATUS),
    },
    fieldName: 'statusCode',
    label: '状态',
  },
];

export const tableColumns: VxeGridProps['columns'] = [
  {
    type: 'checkbox',
    width: 80,
    fixed: 'left',
  },

  {
    field: 'licenseName',
    title: '证照名称',
    minWidth: 150,
    fixed: 'left',
  },
  {
    field: 'stationName',
    title: '油站',
    minWidth: 120,
    fixed: 'left',
  },
  {
    field: 'orgTypeCode',
    title: '机构',
    minWidth: 100,
    formatter: (params: { cellValue: string; column: any; row: any }) => {
      const options = getOrganizationTypes();
      const option = options.find((item) => item.value === params.cellValue);
      return option ? option.label : params.cellValue;
    },
  },
  {
    field: 'issuingAuthority',
    title: '发证机关',
    minWidth: 120,
  },
  {
    field: 'certificateNumber',
    title: '证件编号',
    minWidth: 150,
    formatter: (params: { cellValue: string; column: any; row: any }) =>
      params.cellValue,
  },
  {
    field: 'issueDate',
    title: '发证日期',
    minWidth: 200,
  },
  {
    field: 'validDate',
    title: '有效日期',
    minWidth: 200,
    formatter: (params: { row: any }) => {
      if (params.row.isLongTerm) {
        return '长期';
      }
      return params.row.validDate;
    },
  },
  // {
  //   field: 'storageLocationCode',
  //   title: '存放处',
  //   minWidth: 100,
  //   formatter: (params: { cellValue: string; column: any; row: any }) => {
  //     const options = getStorageLocations();
  //     const option = options.find((item) => item.value === params.cellValue);
  //     return option ? option.label : params.cellValue;
  //   },
  // },
  {
    field: 'renewalRequirements',
    title: '更换要求',
    minWidth: 120,
    formatter: (params: { cellValue: string; column: any; row: any }) =>
      params.cellValue,
  },
  {
    field: 'nextAnnualReviewDate',
    title: '下次年审时间',
    minWidth: 200,
    formatter: (params: { cellValue: string; column: any; row: any }) =>
      params.cellValue,
  },
  {
    field: 'nextRenewalDate',
    title: '下次换证日期',
    minWidth: 200,
    formatter: (params: { cellValue: string; column: any; row: any }) =>
      params.cellValue,
  },
  {
    field: 'statusCode',
    title: '状态',
    minWidth: 100,
    slots: {
      default: ({ row }) => {
        return renderDict(
          row.statusCode.toString(),
          DictEnum.SYS_DISABLED_STATUS,
        );
      },
    },
  },
  {
    field: 'action',
    fixed: 'right',
    slots: { default: 'action' },
    title: '操作',
    width: 150,
  },
];

export const drawerFormSchema: FormSchemaGetter = () => [
  {
    component: 'Input',
    dependencies: {
      show: () => false,
      triggerFields: [''],
    },
    fieldName: 'id',
  },
  {
    component: 'ApiSelect',
    fieldName: 'stationId',
    label: '油站',
    componentProps: {
      placeholder: '请输入油站名称',
      maxlength: 100,
      api: async () => {
        const resp = await selectAllSysStationAreaList();
        const data = resp || [];
        return Array.isArray(data)
          ? data.map((item: any) => ({
              label: item.stationName,
              value: item.id.toString(),
            }))
          : [];
      },
    },
    rules: 'required',
  },
  {
    component: 'Input',
    dependencies: {
      show: () => false,
      triggerFields: [''],
    },
    fieldName: 'licenseName',
  },
  {
    component: 'ApiSelect',
    componentProps: (form: any) => {
      return {
        placeholder: '请选择证照名称',
        api: async () => {
          const resp = await requestClient.get('/sysLicenseRule/rule/allList');
          const data = resp || [];
          return Array.isArray(data)
            ? data.map((item: any) => ({
                label: item.licenseName,
                value: item.id,
                // 存储任务要求信息
                renewalRequirements: item.renewRequirements,
              }))
            : [];
        },
        onChange: async (selectedId: number | string) => {
          if (selectedId && form) {
            try {
              // 获取选中的证照信息
              const resp = await requestClient.get(
                '/sysLicenseRule/rule/allList',
              );
              const data = resp || [];
              const selectedLicense = data.find(
                (item: any) => item.id === selectedId,
              );
              if (selectedLicense) {
                // 设置任务要求
                form.renewalRequirements = selectedLicense.renewRequirements;
                form.licenseName = selectedLicense.licenseName;
              }
            } catch (error) {
              console.error('获取证照详情失败:', error);
            }
          }
        },
      };
    },
    fieldName: 'licenseRuleId',
    label: '证照名称',
    rules: 'required',
  },
  {
    component: 'Select',
    componentProps: {
      placeholder: '请选择机构类型',
      options: getOrganizationTypes(),
    },
    fieldName: 'orgTypeCode',
    label: '机构',
    rules: 'required',
  },
  {
    component: 'Input',
    fieldName: 'issuingAuthority',
    label: '发证机关',
    componentProps: {
      placeholder: '请输入发证机关',
      maxlength: 100,
    },
    rules: 'required',
  },
  {
    component: 'Input',
    dependencies: {
      show: () => true,
      triggerFields: [''],
    },
    componentProps: {
      placeholder: '请输入证件编号',
      maxlength: 100,
    },
    fieldName: 'certificateNumber',
    label: '证件编号',
    rules: 'required',
  },
  {
    component: 'DatePicker',
    componentProps: {
      type: 'date',
      format: 'YYYY-MM-DD',
      valueFormat: 'YYYY-MM-DD HH:mm:ss',
      placeholder: '请选择发证日期',
      style: {
        width: '100%',
      },
    },
    fieldName: 'issueDate',
    label: '发证日期',
    rules: 'required',
  },
  {
    component: 'DatePicker',
    componentProps: {
      type: 'date',
      format: 'YYYY-MM-DD',
      valueFormat: 'YYYY-MM-DD HH:mm:ss',
      placeholder: '请选择有效日期',
      style: {
        width: '100%',
      },
    },
    dependencies: {
      show: (values) => !values.isLongTerm,
      triggerFields: ['isLongTerm'],
    },
    fieldName: 'validDate',
    label: '有效日期',
  },
  {
    component: 'Checkbox',
    componentProps: {
      label: '长期有效',
    },
    fieldName: 'isLongTerm',
    label: '长期',
  },
  {
    component: 'Select',
    componentProps: {
      placeholder: '请选择存放处',
      options: getStorageLocations(),
    },
    fieldName: 'storageLocationCode',
    label: '存放处',
    rules: 'required',
  },
  {
    component: 'Input',
    fieldName: 'renewalRequirements',
    label: '更换要求',
    componentProps: {
      placeholder: '请输入更换要求',
      maxlength: 200,
      type: 'textarea',
      showWordLimit: true,
    },
  },
  {
    component: 'Input',
    fieldName: 'certificateScanPath',
    label: '证件扫描件',
    dependencies: {
      show: () => false,
      triggerFields: [''],
    },
  },
  {
    component: 'Upload',
    fieldName: 'certificateScanPathUrl',
    label: '证件扫描件',
    componentProps: (row: any) => {
      return {
        ...getFileUploadConfig(
          '.png,.jpg,.jpeg',
          'picture-card',
          1,
          '/common/upload',
        ),
        onSuccess: (res: any) => {},
      };
    },
    renderComponentContent: () => {
      return {
        default: () => '点击上传',
      };
    },
  },
  {
    component: 'RadioGroup',
    componentProps: {
      // 直接使用具体的选项对象，避免可能的getDictOptions问题
      options: getDictOptions(DictEnum.SYS_DISABLED_STATUS),
      isButton: true,
    },
    fieldName: 'statusCode',
    defaultValue: 'enabled',
    label: '状态',
    required: false,
  },
  {
    component: 'Input',
    dependencies: {
      show: () => false,
      triggerFields: [''],
    },
    componentProps: {
      placeholder: '请输入油站ID',
      maxlength: 100,
    },
    fieldName: 'stationId',
    label: '油站ID',
  },
];
