import { Options } from './type';
import { queryDeviceProfileBy } from '/@/api/device/deviceManager';
import { findDictItemByCode } from '/@/api/system/dict';
import { getOrganizationList } from '/@/api/system/system';
import { FormSchema } from '/@/components/Form';
import { BasicColumn } from '/@/components/Table';
import { copyTransFun } from '/@/utils/fnUtils';

export enum FieldsEnum {
  ORGANIZATION_ID = 'organizationId',
  DEVICE_TYPE = 'deviceTypeEnum',
  TK_DEVICE_PROFILE_ID = 'tkDeviceProfileId',
  DEVICE_TYPE_NAME = 'deviceTypeName',
  DELIMITER = 'delimiter',
  HEADER = 'header',
  UPDATE = 'update',
}

export enum DelimiterEnum {
  COMMA = ',',
  SEMICOLON = ';',
  VERTICAL_LINE = '|',
  TAB = 'Tab',
}

export enum DelimiterNameEnum {
  ',' = 'COMMA',
  ';' = 'SEMICOLON',
  '|' = 'VERTICAL_LINE',
  'Tab' = 'TAB',
}

export enum ColumnFileEnum {
  EXAMPLE_VALUE = 'exampleValue',
  TYPE = 'type',
  KEY = 'key',
  OLD_VALUE = 'oldValue',
}

export enum ColumTypeEnum {
  NAME = 'NAME',
  // TYPE = 'TYPE',
  LABEL = 'LABEL',
  DESCRIPTION = 'DESCRIPTION',
  SHARED_ATTRIBUTE = 'SHARED_ATTRIBUTE',
  SERVER_ATTRIBUTE = 'SERVER_ATTRIBUTE',
  TIMESERIES = 'TIMESERIES',
  IS_GATEWAY = 'IS_GATEWAY',
}

export enum CredentialsEnum {
  ACCESS_TOKEN = 'ACCESS_TOKEN',
  X509 = 'X509',
  MQTT_CLIENT_ID = 'MQTT_CLIENT_ID',
  MQTT_USER_NAME = 'MQTT_USER_NAME',
  MQTT_PASSWORD = 'MQTT_PASSWORD',
  LWM2M_CLIENT_ENDPOINT = 'LWM2M_CLIENT_ENDPOINT',
  LWM2M_CLIENT_SECURITY_CONFIG_MODE = 'LWM2M_CLIENT_SECURITY_CONFIG_MODE',
  LWM2M_CLIENT_IDENTITY = 'LWM2M_CLIENT_IDENTITY',
  LWM2M_CLIENT_KEY = 'LWM2M_CLIENT_KEY',
  LWM2M_CLIENT_CERT = 'LWM2M_CLIENT_CERT',
  LWM2M_BOOTSTRAP_SERVER_SECURITY_MODE = 'LWM2M_BOOTSTRAP_SERVER_SECURITY_MODE',
  LWM2M_BOOTSTRAP_SERVER_PUBLIC_KEY_OR_ID = 'LWM2M_BOOTSTRAP_SERVER_PUBLIC_KEY_OR_ID',
  LWM2M_BOOTSTRAP_SERVER_SECRET_KEY = 'LWM2M_BOOTSTRAP_SERVER_SECRET_KEY',
  LWM2M_SERVER_SECURITY_MODE = 'LWM2M_SERVER_SECURITY_MODE',
  LWM2M_SERVER_CLIENT_PUBLIC_KEY_OR_ID = 'LWM2M_SERVER_CLIENT_PUBLIC_KEY_OR_ID',
  LWM2M_SERVER_CLIENT_SECRET_KEY = 'LWM2M_SERVER_CLIENT_SECRET_KEY',
}

export enum ColumnTypeNameEnum {
  NAME = '名称',
  // TYPE = '类型',
  LABEL = '标签',
  DESCRIPTION = '说明',
  SHARED_ATTRIBUTE = '共享属性',
  SERVER_ATTRIBUTE = '服务器属性',
  TIMESERIES = 'Timeseries',
  IS_GATEWAY = 'Is网关',
}

export enum CredentialsNameEnum {
  ACCESS_TOKEN = '访问令牌',
  X509 = 'X.509',
  MQTT_CLIENT_ID = 'MQTT client ID',
  MQTT_USER_NAME = 'MQTT user name',
  MQTT_PASSWORD = 'MQTT password',
  LWM2M_CLIENT_ENDPOINT = 'LwM2M endpoint client name',
  LWM2M_CLIENT_SECURITY_CONFIG_MODE = 'LwM2M security config mode',
  LWM2M_CLIENT_IDENTITY = 'LwM2M client identity',
  LWM2M_CLIENT_KEY = 'LwM2M client key',
  LWM2M_CLIENT_CERT = 'LwM2M client public key',
  LWM2M_BOOTSTRAP_SERVER_SECURITY_MODE = 'LwM2M bootstrap server security mode',
  LWM2M_BOOTSTRAP_SERVER_PUBLIC_KEY_OR_ID = 'LwM2M bootstrap server public key or id',
  LWM2M_BOOTSTRAP_SERVER_SECRET_KEY = 'LwM2M bootstrap server secret key',
  LWM2M_SERVER_SECURITY_MODE = 'LwM2M server security mode',
  LWM2M_SERVER_CLIENT_PUBLIC_KEY_OR_ID = 'LwM2M server public key or id',
  LWM2M_SERVER_CLIENT_SECRET_KEY = 'LwM2M server secret key',
}

export const basicInfoForm: FormSchema[] = [
  {
    field: FieldsEnum.ORGANIZATION_ID,
    label: '所属组织',
    component: 'ApiTreeSelect',
    rules: [{ required: true, message: '所属组织为必填项' }],
    componentProps: ({ formActionType }) => {
      const { submit } = formActionType;
      return {
        maxLength: 250,
        placeholder: '请选择所属组织',
        api: async () => {
          const data = (await getOrganizationList()) as unknown as Recordable[];
          copyTransFun(data);
          return data;
        },
        getPopupContainer: () => document.body,
        onChange: () => submit(),
      };
    },
  },
  {
    field: FieldsEnum.DEVICE_TYPE,
    label: '设备类型',
    component: 'ApiSelect',
    rules: [{ required: true, message: '设备类型为必填项' }],
    componentProps: ({ formActionType }) => {
      const { setFieldsValue, submit, clearValidate } = formActionType;
      return {
        api: findDictItemByCode,
        params: {
          dictCode: 'device_type',
        },
        labelField: 'itemText',
        valueField: 'itemValue',
        onChange: (value: string, options: Record<'deviceType' | 'label', string>) => {
          setFieldsValue({
            [FieldsEnum.DEVICE_TYPE_NAME]: value ? options.label : null,
            [FieldsEnum.TK_DEVICE_PROFILE_ID]: null,
          });
          submit();
          clearValidate();
        },
      };
    },
  },
  {
    field: FieldsEnum.TK_DEVICE_PROFILE_ID,
    component: 'ApiSelect',
    label: '产品',
    rules: [{ required: true, message: '产品为必填项' }],
    componentProps: ({ formActionType, formModel }) => {
      const { submit } = formActionType;
      const deviceType = Reflect.get(formModel, FieldsEnum.DEVICE_TYPE);
      return {
        api: queryDeviceProfileBy,
        labelField: 'name',
        valueField: 'id',
        placeholder: '请选择产品',
        params: { deviceType },
        getPopupContainer: () => document.body,
        onChange: () => submit(),
        showSearch: true,
        filterOption: (inputValue: string, options: Record<'label', string>) => {
          return options.label.includes(inputValue);
        },
      };
    },
  },
  {
    field: FieldsEnum.DEVICE_TYPE_NAME,
    component: 'Input',
    label: '设备名称',
    show: false,
  },
];

export const importConfigurationSchema: FormSchema[] = [
  {
    field: FieldsEnum.DELIMITER,
    label: 'csv分隔符',
    component: 'Select',
    rules: [{ required: true, message: 'csv分隔符为必填项' }],
    defaultValue: DelimiterEnum.COMMA,
    componentProps: {
      options: [
        { label: DelimiterEnum.COMMA, value: DelimiterEnum.COMMA },
        { label: DelimiterEnum.SEMICOLON, value: DelimiterEnum.SEMICOLON },
        { label: DelimiterEnum.VERTICAL_LINE, value: DelimiterEnum.VERTICAL_LINE },
        { label: DelimiterEnum.TAB, value: DelimiterEnum.TAB },
      ],
    },
  },
  {
    field: FieldsEnum.HEADER,
    label: '第一行包含列名',
    component: 'Checkbox',
    defaultValue: true,
  },
  {
    field: FieldsEnum.UPDATE,
    label: '更新属性/遥测',
    component: 'Checkbox',
    defaultValue: true,
  },
];

export const generateColumnTypeOptions = () => {
  const valueOptions = Object.keys(ColumTypeEnum);
  const labelOptions = Object.values(ColumnTypeNameEnum);
  const credentialsValueOptions = Object.keys(CredentialsEnum);
  const credentialsNameOptions = Object.values(CredentialsNameEnum);
  const options: Options[] = valueOptions.map((value, index) => ({
    label: labelOptions[index],
    value,
  }));

  const credentialsOption: Options = {
    label: 'credentials',
    options: credentialsValueOptions.map((value, index) => ({
      label: credentialsNameOptions[index],
      value: value,
    })) as Options[],
  };
  options.push(credentialsOption);

  return options;
};

export const columnTypeSchema: BasicColumn[] = [
  {
    title: '列名称',
    key: ColumnFileEnum.KEY,
    dataIndex: ColumnFileEnum.KEY,
    slots: {
      customRender: ColumnFileEnum.KEY,
    },
  },
  {
    title: '列类型',
    dataIndex: ColumnFileEnum.TYPE,
    key: ColumnFileEnum.TYPE,
    slots: {
      customRender: ColumnFileEnum.TYPE,
    },
  },
];

export const csvTemplate = `name,username,password
Device 11,admin,password
Device 22,admin1,password1
`;

export const downloadFile = (data: string, fileName: string, type: string, ext: string) => {
  const blob = new Blob([data], { type: type });
  const objectURL = URL.createObjectURL(blob);
  const element = document.createElement('a');
  element.href = objectURL;
  element.download = `${fileName}.${ext}`;
  element.style.display = 'none';
  document.body.appendChild(element);
  element.click();
  element.remove();
  URL.revokeObjectURL(objectURL);
};
