import { BasicColumn } from '/@/components/Table';
import { FormSchema } from '/@/components/Table';
import { findDictItemByCode } from '/@/api/system/dict';
import { MessageEnum } from '/@/enums/messageEnum';
import { numberRule } from '/@/utils/rules';

import { deviceConfigGetRuleChain } from '/@/api/device/deviceConfigApi';
import { FormField, FunctionType } from './step/cpns/physical/cpns/config';
import { h } from 'vue';
import { Tag, Tooltip } from 'ant-design-vue';
import { EventType, EventTypeColor, EventTypeName } from '../list/cpns/tabs/EventManage/config';
import { useCopyToClipboard } from '/@/hooks/web/useCopyToClipboard';
import { useMessage } from '/@/hooks/web/useMessage';

export enum Mode {
  CARD = 'card',
  TABLE = 'table',
}

export enum DeviceTypeName {
  DIRECT_CONNECTION = '直连设备',
  GATEWAY = '网关设备',
  SENSOR = '网关子设备',
}
export enum ProductPermission {
  DETAIL = 'api:yt:deviceProfile:get',
  CREATE = 'api:yt:deviceProfile:post',
  UPDATE = 'api:yt:deviceProfile:update',
  DELETE = 'api:yt:deviceProfile:delete',
  SET_DEFAULT = '',
  IMPORT = 'api:yt:deviceProfile:import',
  EXPORT = 'api:yt:deviceProfile:export',
}

export enum ModelOfMatterPermission {
  CREATE = 'api:yt:things_model:post',
  UPDATE = 'api:yt:things_model:put',
  DELETE = 'api:yt:things_model:delete',
  RELEASE = 'api:yt:things_model:release',
}

const handleCopy = (value: string) => {
  const { createMessage } = useMessage();
  const { clipboardRef, isSuccessRef } = useCopyToClipboard(value);
  clipboardRef.value = value;
  if (isSuccessRef.value) createMessage.success('复制成功~');
  else createMessage.error('复制失败～');
};

export const steps = [
  {
    title: '产品',
    content: 'First-content',
  },
  {
    title: '传输配置',
    content: 'Second-content',
  },
];

export const formatFunctionType: Record<FunctionType, string> = {
  [FunctionType.PROPERTIES]: '属性',
  [FunctionType.EVENTS]: '事件',
  [FunctionType.SERVICE]: '服务',
};

export const physicalColumn: BasicColumn[] = [
  {
    title: '功能类型',
    dataIndex: FormField.FUNCTION_TYPE,
    width: 90,
    format: (text: FunctionType) => {
      return formatFunctionType[text];
    },
  },
  {
    title: '功能名称',
    dataIndex: FormField.FUNCTION_NAME,
    width: 90,
  },
  {
    title: '标识符',
    dataIndex: FormField.IDENTIFIER,
    width: 90,
    customRender: ({ text }: Record<'text', string>) => {
      return h(Tooltip, { title: text }, () =>
        h('span', { class: 'cursor-pointer', onClick: () => handleCopy(text) }, text)
      );
    },
  },
  {
    title: '数据类型',
    dataIndex: 'functionJson.dataType.type',
    width: 100,
    format: (text: string) => {
      return text || '--';
    },
  },
  {
    title: '事件类型',
    dataIndex: 'eventType',
    customRender({ text }) {
      return h(
        Tag,
        {
          color: EventTypeColor[text as EventType],
        },
        () => EventTypeName[text as EventType]
      );
    },
  },
  {
    title: '状态',
    dataIndex: 'status',
    width: 100,
    customRender: (value: Record<'text', number>) => {
      const { text } = value;
      return h(
        Tag,
        {
          color: text ? 'green' : 'red',
        },
        () => (text ? '已发布' : '待发布')
      );
    },
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    width: 150,
  },
];

export const modelOfMatterForm: FormSchema[] = [
  {
    field: 'functionType',
    label: '功能类型',
    component: 'Select',
    colProps: { span: 8 },
    componentProps: {
      options: [
        { label: formatFunctionType[FunctionType.PROPERTIES], value: FunctionType.PROPERTIES },
        { label: formatFunctionType[FunctionType.EVENTS], value: FunctionType.EVENTS },
        { label: formatFunctionType[FunctionType.SERVICE], value: FunctionType.SERVICE },
      ],
    },
  },
  {
    field: 'nameOrIdentifier',
    label: '功能名称/标识符',
    component: 'Input',
    colProps: { span: 8 },
  },
];

export const step1Schemas: FormSchema[] = [
  {
    field: 'image',
    label: '上传图片',
    component: 'Input',
    slot: 'imageSelect',
  },
  {
    field: 'deviceType',
    component: 'ApiRadioGroup',
    label: '设备类型',
    required: true,
    colProps: {
      span: 14,
    },
    defaultValue: 'GATEWAY',
    componentProps: {
      api: findDictItemByCode,
      params: {
        dictCode: 'device_type',
      },
      labelField: 'itemText',
      valueField: 'itemValue',
    },
  },
  {
    field: 'name',
    label: '产品名称',
    required: true,
    component: 'Input',
    colProps: { span: 14 },
    componentProps: {
      disabled: false,
      maxLength: 63,
      placeholder: '请输入产品名称',
    },
  },
  {
    field: 'defaultRuleChainId',
    label: '规则链',
    component: 'ApiSelect',
    colProps: { span: 14 },

    componentProps: {
      api: async () => {
        const data = await deviceConfigGetRuleChain();
        const returnData = data.map((m) => {
          return {
            getValueField: m.name,
            getKeyField: m.id.id,
          };
        });
        return returnData;
      },
      labelField: 'getValueField',
      valueField: 'getKeyField',
      immediate: true,
    },
  },
  {
    field: 'defaultQueueName',
    label: '处理队列',
    component: 'ApiSelect',
    colProps: { span: 14 },

    componentProps: {
      api: findDictItemByCode,
      params: {
        dictCode: 'queen_execute_sequence',
      },
      labelField: 'itemText',
      valueField: 'itemValue',
      resultField: 'items',
    },
  },

  {
    label: '描述',
    field: 'description',
    colProps: { span: 14 },
    component: 'InputTextArea',
    componentProps: {
      maxLength: 255,
      placeholder: '请输入描述',
      rows: 6,
    },
  },
];

export const step2Schemas: FormSchema[] = [
  {
    field: 'transportType',
    component: 'Select',
    required: true,
    label: '接入协议',
    defaultValue: 'DEFAULT',
    componentProps() {
      return {
        options: [
          { label: '默认', value: 'DEFAULT' },
          { label: 'MQTT', value: 'MQTT' },
          { label: 'CoAP', value: 'COAP' },
          { label: 'LWM2M', value: 'LWM2M' },
          { label: 'SNMP', value: 'SNMP' },
        ],
      };
    },
    colProps: { span: 10 },
  },
];

const deviceTypeStatic = [
  {
    key: 'DIRECT_CONNECTION',
    value: '直连设备',
  },
  {
    key: 'GATEWAY',
    value: '网关设备',
  },
  {
    key: 'SENSOR',
    value: '网关子设备',
  },
];

export const columns: BasicColumn[] = [
  {
    title: '配置图片', //图标
    dataIndex: 'image',
    width: 80,
    slots: { customRender: 'img' },
  },
  {
    title: '名称',
    dataIndex: 'name',
    width: 120,
  },
  {
    title: '设备类型',
    dataIndex: 'deviceType',
    width: 90,
    format: (text) => {
      return deviceTypeStatic.find((f) => f.key === text)!.value;
    },
  },
  {
    title: '配置类型',
    dataIndex: 'type',
    width: 90,
  },
  {
    title: '接入协议',
    dataIndex: 'transportType',
    width: 90,
  },
  {
    title: '默认配置',
    dataIndex: 'default',
    width: 80,
    customRender: ({ text }) =>
      text ? h(Tag, { color: 'blue' }, () => '是') : h(Tag, { color: 'red' }, () => '否'),
  },
  {
    title: '描述',
    dataIndex: 'description',
    width: 90,
    ellipsis: true,
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    width: 120,
  },
];

export const defaultObj = {
  headers: {
    normalizedNames: {},
    lazyUpdate: null,
  },
  params: {
    updates: null,
    cloneFrom: null,
    encoder: {},
    map: null,
    interceptorConfig: {
      ignoreLoading: false,
      ignoreErrors: false,
      resendRequest: false,
    },
  },
};

export const searchFormSchema: FormSchema[] = [
  {
    field: 'name',
    label: '产品名称',
    component: 'Input',
    colProps: { span: 6 },
    componentProps: {
      maxLength: 255,
      placeholder: '请输入产品名称',
    },
  },
];

export const isMessage = (type: string) => {
  return type === MessageEnum.IS_SMS;
};
export const isEmail = (type: string) => {
  return type === MessageEnum.IS_EMAIL;
};

export const formSchema: FormSchema[] = [
  {
    field: 'configName',
    label: '产品名称',
    required: true,
    component: 'Input',
    componentProps: {
      maxLength: 255,
      placeholder: '请输入产品名称',
    },
  },
  {
    field: 'messageType',
    label: '消息类型',
    required: true,
    component: 'ApiSelect',
    componentProps: {
      api: findDictItemByCode,
      params: {
        dictCode: 'message_type',
      },
      labelField: 'itemText',
      valueField: 'itemValue',
    },
  },
  {
    field: 'platformType',
    label: '平台类型',
    required: true,
    component: 'ApiSelect',
    componentProps: {
      api: findDictItemByCode,
      params: {
        dictCode: 'platform_type',
      },
      labelField: 'itemText',
      valueField: 'itemValue',
    },
    ifShow: ({ values }) => isMessage(Reflect.get(values, 'messageType')),
  },
  {
    field: 'accessKeyId',
    label: 'accessKeyId',
    required: true,
    component: 'Input',
    componentProps: {
      maxLength: 36,
      placeholder: '请输入accessKeyId',
    },

    ifShow: ({ values }) => isMessage(Reflect.get(values, 'messageType')),
  },
  {
    field: 'accessKeySecret',
    label: 'accessKeySecret',
    required: true,
    component: 'Input',
    componentProps: {
      maxLength: 36,
      placeholder: '请输入accessKeySecret',
    },

    ifShow: ({ values }) => isMessage(Reflect.get(values, 'messageType')),
  },
  {
    field: 'host',
    label: '服务器地址',
    defaultValue: 'smtp.163.com',
    required: true,
    component: 'Input',
    componentProps: {
      maxLength: 36,
      placeholder: '请输入accessKeySecret',
    },

    ifShow: ({ values }) => isEmail(Reflect.get(values, 'messageType')),
  },
  {
    field: 'port',
    label: '端口',
    defaultValue: 25,
    required: true,
    component: 'InputNumber',
    rules: numberRule,
    componentProps: {
      maxLength: 36,
      placeholder: '请输入端口',
    },

    ifShow: ({ values }) => isEmail(Reflect.get(values, 'messageType')),
  },
  {
    field: 'username',
    label: '用户名',
    required: true,
    component: 'Input',
    componentProps: {
      maxLength: 255,
      placeholder: '请输入用户名',
    },

    ifShow: ({ values }) => isEmail(Reflect.get(values, 'messageType')),
  },
  {
    field: 'password',
    label: '密码',
    required: true,
    component: 'InputPassword',
    ifShow: ({ values }) => isEmail(Reflect.get(values, 'messageType')),
  },
  {
    field: 'config',
    label: '消息配置',
    component: 'Input',
    show: false,
    componentProps: {
      maxLength: 255,
      placeholder: '请输入消息配置',
    },
  },
  {
    field: 'id',
    label: '主键',
    component: 'Input',
    show: false,
    componentProps: {
      maxLength: 36,
      placeholder: '请输入主键',
    },
  },
  {
    field: 'status',
    label: '状态',
    component: 'RadioButtonGroup',
    defaultValue: 0,
    componentProps: {
      options: [
        { label: '启用', value: 1 },
        { label: '停用', value: 0 },
      ],
    },
  },
  {
    label: '备注',
    field: 'remark',
    component: 'InputTextArea',
    componentProps: {
      maxLength: 255,
      placeholder: '请输入备注',
    },
  },
];
