import { FormSchema } from '/@/components/Form';
import { findDictItemByCode } from '/@/api/system/dict';
import { deviceProfile, getGatewayDevice } from '/@/api/device/deviceManager';
import { DeviceTypeEnum } from '/@/api/device/model/deviceModel';
import { TransportTypeEnum } from '../../profiles/components/TransportDescript/const';

export enum TypeEnum {
  IS_GATEWAY = 'GATEWAY',
  SENSOR = 'SENSOR',
}
export const isGateWay = (type: string) => {
  return type === TypeEnum.IS_GATEWAY;
};
// 第一步的表单
export const step1Schemas: FormSchema[] = [
  {
    field: 'icon',
    label: '设备图片',
    slot: 'iconSelect',
    component: 'Input',
  },
  {
    field: 'name',
    label: '设备名称',
    required: true,
    component: 'Input',
    colProps: { span: 14 },
    componentProps: {
      placeholder: '设备名称',
      maxLength: 36,
    },
  },
  {
    field: 'alias',
    label: '别名 ',
    component: 'Input',
    labelWidth: 60,
    colProps: { span: 10 },
    componentProps: {
      maxLength: 255,
    },
  },
  {
    field: 'sn',
    label: 'SN码',
    component: 'Input',
    required: true,
    slot: 'snCode',
  },
  {
    field: 'transportType',
    label: '类型',
    component: 'Input',
    show: false,
  },
  {
    field: 'deviceProfileId',
    label: '',
    component: 'Input',
    show: false,
  },
  {
    field: 'profileId',
    label: '所属产品',
    required: true,
    component: 'ApiSelect',
    componentProps: ({ formActionType, formModel }) => {
      const { setFieldsValue } = formActionType;
      return {
        api: async () => {
          const options = await deviceProfile();
          const { profileId } = formModel;
          if (profileId) {
            const selectRecord = options.find((item) => item.tbProfileId === profileId);
            selectRecord && setFieldsValue({ transportType: selectRecord!.transportType });
          }
          return options;
        },
        labelField: 'name',
        valueField: 'tbProfileId',
        onChange(
          _value: string,
          option: { deviceType: string; transportType: string; id: string }
        ) {
          const { deviceType, transportType, id } = option;
          setFieldsValue({
            deviceType: deviceType,
            transportType,
            deviceProfileId: id,
            gatewayId: null,
          });
        },
        showSearch: true,
        filterOption: (inputValue: string, option: Record<'label' | 'value', string>) =>
          option.label.includes(inputValue),
      };
    },
  },
  {
    field: 'deviceType',
    label: '设备类型',
    required: true,
    component: 'ApiSelect',
    dynamicDisabled: true,
    helpMessage: ['选择所属产品,自动关联设备类型'],
    componentProps: {
      placeholder: '设备类型',
      api: findDictItemByCode,
      params: {
        dictCode: 'device_type',
      },
      labelField: 'itemText',
      valueField: 'itemValue',
    },
  },
  {
    field: 'code',
    label: '地址码',
    component: 'Input',
    ifShow: ({ model }) => {
      return (
        model['transportType'] === TransportTypeEnum.TCP &&
        model['deviceType'] === DeviceTypeEnum.SENSOR
      );
    },
    dynamicRules: ({ model }) => {
      return [{ required: model['transportType'] === 'TCP', message: '地址码为必填项' }];
    },
  },
  {
    field: 'brand',
    component: 'ApiRadioGroup',
    label: '选择厂家',
    required: true,
    colProps: {
      span: 8,
    },
    defaultValue: 'DIY_',
    componentProps: {
      api: findDictItemByCode,
      params: {
        dictCode: 'device_brand_gateway',
      },
      labelField: 'itemText',
      valueField: 'itemValue',
    },
    ifShow: ({ values }) => isGateWay(values.deviceType),
  },
  {
    field: 'organizationId',
    label: '所属组织',
    component: 'Input',
    required: true,
    slot: 'addOrg',
  },
  {
    field: 'gatewayId',
    label: '网关设备',
    required: true,
    component: 'ApiSelect',
    ifShow: ({ values }) => values.deviceType === 'SENSOR' && values.organizationId,
    componentProps: ({ formModel }) => {
      const { organizationId, transportType } = formModel;
      if (![organizationId, transportType].every(Boolean)) return {};
      return {
        api: getGatewayDevice,
        showSearch: true,
        params: {
          organizationId,
          transportType,
        },
        valueField: 'tbDeviceId',
        labelField: 'name',
      };
    },
  },
  {
    field: 'label',
    label: '设备标签',
    component: 'Input',
    componentProps: {
      maxLength: 255,
      placeholder: '请输入设备标签',
    },
    dynamicRules: () => {
      return [
        {
          required: false,
          validator: (_, value) => {
            if (String(value).length > 255) {
              return Promise.reject('字数不超过255个字');
            }
            return Promise.resolve();
          },
        },
      ];
    },
  },
  {
    field: 'deviceAddress',
    label: '设备位置',
    component: 'Input',
    slot: 'deviceAddress',
  },
  {
    field: 'description',
    label: '备注',
    component: 'InputTextArea',
    componentProps: {
      maxLength: 500,
      placeholder: '请输入备注',
    },
    dynamicRules: () => {
      return [
        {
          required: false,
          validator: (_, value) => {
            if (String(value).length > 500) {
              return Promise.reject('字数不超过500个字');
            }
            return Promise.resolve();
          },
        },
      ];
    },
  },
  {
    field: 'id',
    label: 'id',
    component: 'Input',
    show: false,
    componentProps: {
      maxLength: 36,
      placeholder: '请输入id',
    },
  },
  {
    field: 'tenantId',
    label: '租户Code',
    component: 'Input',
    show: false,
    componentProps: {
      maxLength: 36,
      placeholder: '请输入租户Code',
    },
    dynamicRules: () => {
      return [
        {
          required: false,
          validator: (_, value) => {
            if (String(value).length > 36) {
              return Promise.reject('字数不超过36个字');
            }
            return Promise.resolve();
          },
        },
      ];
    },
  },
  {
    field: 'tbDeviceId',
    label: 'tbDeviceId',
    component: 'Input',
    show: false,
    componentProps: {
      maxLength: 36,
      placeholder: '请输入tbDeviceId',
    },
  },
];

export enum credentialTypeEnum {
  ACCESS_TOKEN = 'ACCESS_TOKEN',
  X_509 = 'X509_CERTIFICATE',
  MQTT_BASIC = 'MQTT_BASIC',
}
// 第二步的表单
export const step2Schemas: FormSchema[] = [
  {
    label: '',
    component: 'Checkbox',
    field: 'addAgree',
    slot: 'addAgree',
  },
  {
    label: '凭据类型',
    component: 'Select',
    field: 'credentialType',
    required: true,
    componentProps({ formActionType }) {
      const { updateSchema, setFieldsValue } = formActionType;
      return {
        options: [
          {
            value: credentialTypeEnum.ACCESS_TOKEN,
            label: 'Access Token',
          },
          {
            value: credentialTypeEnum.X_509,
            label: 'X.509',
          },
          {
            value: credentialTypeEnum.MQTT_BASIC,
            label: 'MQTT Basic',
          },
        ],
        onChange(value) {
          setFieldsValue({
            publicKey: '',
            credentialsId: '',
            clientId: '',
            username: '',
            password: '',
          });
          if (value === credentialTypeEnum.ACCESS_TOKEN) {
            updateSchema([
              {
                field: 'credentialsId',
                ifShow: true,
              },
              {
                field: 'clientId',
                ifShow: false,
              },
              {
                field: 'username',
                ifShow: false,
              },
              {
                field: 'password',
                ifShow: false,
              },
              {
                field: 'publicKey',
                ifShow: false,
              },
            ]);
          } else if (value === credentialTypeEnum.X_509) {
            updateSchema([
              {
                field: 'publicKey',
                ifShow: true,
              },
              {
                field: 'credentialsId',
                ifShow: false,
              },
              {
                field: 'clientId',
                ifShow: false,
              },
              {
                field: 'username',
                ifShow: false,
              },
              {
                field: 'password',
                ifShow: false,
              },
            ]);
          } else if (value === credentialTypeEnum.MQTT_BASIC) {
            updateSchema([
              {
                field: 'clientId',
                ifShow: true,
              },
              {
                field: 'username',
                ifShow: true,
              },
              {
                field: 'password',
                ifShow: true,
              },
              {
                field: 'publicKey',
                ifShow: false,
              },
              {
                field: 'credentialsId',
                ifShow: false,
              },
            ]);
          } else {
            updateSchema([
              {
                field: 'clientId',
                ifShow: false,
              },
              {
                field: 'username',
                ifShow: false,
              },
              {
                field: 'password',
                ifShow: false,
              },
              {
                field: 'publicKey',
                ifShow: false,
              },
              {
                field: 'credentialsId',
                ifShow: false,
              },
            ]);
          }
        },
      };
    },
    ifShow: ({ values }) => values.addAgree,
  },
  {
    label: '访问令牌',
    component: 'Input',
    field: 'credentialsId',
    required: true,
    ifShow: false,
    slot: 'credentialsId',
    componentProps: {
      maxLength: 36,
      placeholder: '请输入访问令牌',
    },
  },
  {
    label: 'RSA公钥',
    component: 'InputTextArea',
    field: 'publicKey',
    required: true,
    ifShow: false,
    componentProps: {
      rows: 8,
      placeholder: '请输入RSA公钥',
    },
  },
  {
    label: '客户端ID',
    component: 'Input',
    field: 'clientId',
    required: true,
    ifShow: false,
    slot: 'clientId',
    componentProps: {
      maxLength: 36,
      placeholder: '请输入客户端ID',
    },
  },
  {
    label: '用户名',
    component: 'Input',
    field: 'username',
    required: true,
    ifShow: false,
    componentProps: {
      maxLength: 255,
      placeholder: '请输入用户名',
    },
  },
  {
    label: '密码',
    component: 'InputPassword',
    field: 'password',
    componentProps: {
      maxLength: 36,
      placeholder: '请输入密码',
    },
    dynamicRules: () => {
      return [
        {
          required: false,
          validator: (_, value) => {
            if (String(value).length > 36) {
              return Promise.reject('字数不超过36个字');
            }
            return Promise.resolve();
          },
        },
      ];
    },
    ifShow: false,
  },
];

// 管理凭证的表单配置项
export const TokenSchemas: FormSchema[] = [
  {
    label: '凭据类型',
    component: 'Select',
    field: 'credentialType',
    required: true,
    componentProps({ formActionType }) {
      const { updateSchema, setFieldsValue } = formActionType;
      return {
        options: [
          {
            value: credentialTypeEnum.ACCESS_TOKEN,
            label: 'Access Token',
          },
          {
            value: credentialTypeEnum.X_509,
            label: 'X.509',
          },
          {
            value: credentialTypeEnum.MQTT_BASIC,
            label: 'MQTT Basic',
          },
        ],
        onChange(value) {
          setFieldsValue({
            publicKey: '',
            credentialsId: '',
            clientId: '',
            username: '',
            password: '',
          });
          if (value === credentialTypeEnum.ACCESS_TOKEN) {
            updateSchema([
              {
                field: 'credentialsId',
                ifShow: true,
              },
              {
                field: 'clientId',
                ifShow: false,
              },
              {
                field: 'username',
                ifShow: false,
              },
              {
                field: 'password',
                ifShow: false,
              },
              {
                field: 'publicKey',
                ifShow: false,
              },
            ]);
          } else if (value === credentialTypeEnum.X_509) {
            updateSchema([
              {
                field: 'publicKey',
                ifShow: true,
              },
              {
                field: 'credentialsId',
                ifShow: false,
              },
              {
                field: 'clientId',
                ifShow: false,
              },
              {
                field: 'username',
                ifShow: false,
              },
              {
                field: 'password',
                ifShow: false,
              },
            ]);
          } else if (value === credentialTypeEnum.MQTT_BASIC) {
            updateSchema([
              {
                field: 'clientId',
                ifShow: true,
              },
              {
                field: 'username',
                ifShow: true,
              },
              {
                field: 'password',
                ifShow: true,
              },
              {
                field: 'publicKey',
                ifShow: false,
              },
              {
                field: 'credentialsId',
                ifShow: false,
              },
            ]);
          } else {
            updateSchema([
              {
                field: 'clientId',
                ifShow: false,
              },
              {
                field: 'username',
                ifShow: false,
              },
              {
                field: 'password',
                ifShow: false,
              },
              {
                field: 'publicKey',
                ifShow: false,
              },
              {
                field: 'credentialsId',
                ifShow: false,
              },
            ]);
          }
        },
      };
    },
  },
  {
    label: '访问令牌',
    component: 'Input',
    field: 'credentialsId',
    required: true,
    ifShow: false,
    slot: 'credentialsId',
    componentProps: {
      maxLength: 36,
      placeholder: '请输入访问令牌',
    },
  },
  {
    label: 'RSA公钥',
    component: 'InputTextArea',
    field: 'publicKey',
    required: true,
    ifShow: false,
    componentProps: {
      rows: 8,
      placeholder: '请输入RSA公钥',
    },
  },
  {
    label: '客户端ID',
    component: 'Input',
    field: 'clientId',
    ifShow: false,
    slot: 'clientId',
    componentProps: {
      maxLength: 36,
      placeholder: '请输入客户端ID',
    },
  },
  {
    label: '用户名',
    component: 'Input',
    field: 'username',
    required: true,
    ifShow: false,
    componentProps: {
      maxLength: 255,
      placeholder: '请输入用户名',
    },
  },
  {
    label: '密码',
    component: 'InputPassword',
    field: 'password',
    ifShow: false,
    componentProps: {
      maxLength: 36,
      placeholder: '请输入密码',
    },
    dynamicRules: () => {
      return [
        {
          required: false,
          validator: (_, value) => {
            if (String(value).length > 36) {
              return Promise.reject('字数不超过36个字');
            }
            return Promise.resolve();
          },
        },
      ];
    },
  },
  {
    label: 'id',
    component: 'Input',
    field: 'id',
    show: false,
    componentProps: {
      maxLength: 36,
      placeholder: '请输入id',
    },
  },
  {
    label: 'tbDeviceId',
    component: 'Input',
    field: 'tbDeviceId',
    show: false,
    componentProps: {
      maxLength: 36,
      placeholder: '请输入tbDeviceId',
    },
    dynamicRules: () => {
      return [
        {
          required: false,
          validator: (_, value) => {
            if (String(value).length > 36) {
              return Promise.reject('字数不超过36个字');
            }
            return Promise.resolve();
          },
        },
      ];
    },
  },
];

export const CommandSchemas = (transportType: TransportTypeEnum): FormSchema[] => {
  return [
    {
      field: 'commandType',
      component: 'RadioGroup',
      label: '下发类型',
      colProps: {
        span: 8,
      },
      defaultValue: 'OneWay',
      componentProps: {
        options: [
          {
            label: '单向',
            value: 'OneWay',
          },
          {
            label: '双向',
            value: 'TwoWay',
          },
        ],
      },
    },
    {
      field: 'valueType',
      label: '命令类型',
      component: 'RadioGroup',
      defaultValue: transportType === TransportTypeEnum.TCP ? 'string' : 'json',
      componentProps: () => {
        const options: Record<'label' | 'value', string>[] = [];
        if (transportType === TransportTypeEnum.TCP) {
          options.push({ label: '字符串', value: 'string' });
        } else {
          options.push({ label: 'JSON', value: 'json' });
        }
        return {
          options,
        };
      },
    },
    {
      field: 'commandText',
      label: '请输入命令内容',
      ifShow: ({ model }) => {
        return model['valueType'] === 'string';
      },
      component: 'InputTextArea',
      componentProps: {
        autosize: {
          minRows: 6,
        },
      },
    },
    {
      field: 'commandValue',
      label: '请输入命令内容',
      slot: 'commandSlot',
      component: 'InputTextArea',
      show: ({ model }) => {
        return model['valueType'] === 'json';
      },
    },
  ];
};
