import { ref, unref } from 'vue';
import { BasicColumn, FormSchema } from '/@/components/Table';
import {
  byOrganizationIdGetMasterDevice,
  screenLinkOrganizationGetApi,
  getAttribute,
} from '/@/api/ruleengine/ruleengineApi';
import { scheduleOptions } from './formatData';
import { copyTransFun } from '/@/utils/fnUtils';
import { numberAndNonegativeRule } from '/@/utils/rules';
import { findDictItemByCode } from '/@/api/system/dict';
import { queryDeviceProfileBy } from '/@/api/device/deviceManager';
import { getModelServices } from '/@/api/device/modelOfMatter';
import { ModelOfMatterParams } from '/@/api/device/model/modelOfMatterModel';
import useCommonFun from '../hooks/useCommonFun';

const { useByProductGetAttribute } = useCommonFun();
export type TOption = {
  label: string;
  value: string;
};

export enum CommandTypeEnum {
  CUSTOM = 0,
  SERVICE = 1,
}

/**
 * 所使用的枚举值
 */

export enum TriggerEnum {
  IS_DEVICE_ACT = 'DEVICE_TRIGGER',
  IS_TIME_ACT = 'SCHEDULE_TRIGGER',
  IS_SCENE_ACT = 'SCENE_TRIGGER',
  IS_HAND_ACT = 'HAND_ACT',
  IS_MSG_NOTIFY = 'MSG_NOTIFY',
  IS_DEVICE_STATUS = 'DEVICE_STATUS',
  IS_TIME_ALL = 'SCHEDULE_TRIGGER',
}
export const isDevice = (type: string) => {
  return type === TriggerEnum.IS_DEVICE_ACT;
};

export const isTime = (type: string) => {
  return type === TriggerEnum.IS_TIME_ACT;
};

export const columns: BasicColumn[] = [
  {
    title: '场景联动名称',
    dataIndex: 'name',
    width: 200,
  },
  {
    title: '触发方式',
    dataIndex: 'triggerType',
    format: (_: string, record: Recordable) => {
      return record.triggers[0]?.triggerType == 'DEVICE_TRIGGER'
        ? '设备触发'
        : record.triggers[0]?.triggerType == 'SCHEDULE_TRIGGER'
        ? '定时触发'
        : record.triggers[0]?.triggerType == 'SCENE_TRIGGER'
        ? '场景触发'
        : '手动触发';
    },
    width: 200,
  },
  {
    title: '状态',
    dataIndex: 'status',
    width: 120,
    slots: { customRender: 'status' },
  },
  {
    title: '描述',
    dataIndex: 'description',
    width: 200,
  },
  {
    title: '创建者',
    dataIndex: 'creatorName',
    width: 200,
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    width: 180,
  },
];
export const organizationId = ref('');
export const formSchema: FormSchema[] = [
  {
    field: 'name',
    label: '场景联动名称',
    colProps: { span: 24 },
    required: true,
    component: 'Input',

    componentProps: {
      maxLength: 36,
      placeholder: '请输入场景联动名称',
    },
  },
  {
    required: true,
    field: 'organizationId',
    label: '所属组织',
    colProps: { span: 24 },
    component: 'ApiTreeSelect',
    componentProps: {
      api: async () => {
        const data = await screenLinkOrganizationGetApi();
        copyTransFun(data as any as any[]);
        return data;
      },
      onChange(value) {
        organizationId.value = value;
      },
    },
  },
  {
    field: 'description',
    label: '描述',
    colProps: { span: 24 },
    component: 'InputTextArea',
    componentProps: {
      maxLength: 255,
      placeholder: '请输入描述',
    },
  },
];

export const searchFormSchema: FormSchema[] = [
  {
    field: 'organizationId',
    label: '所属组织',
    colProps: { span: 6 },
    component: 'ApiTreeSelect',
    componentProps: {
      placeholder: '请选择组织',
      api: async () => {
        const data = await screenLinkOrganizationGetApi();
        copyTransFun(data as any as any[]);
        return data;
      },
    },
  },
  {
    field: 'name',
    label: '名称',
    component: 'Input',
    colProps: { span: 6 },
    componentProps: {
      maxLength: 36,
      placeholder: '请输入场景联动名称',
    },
  },
  {
    field: 'status',
    label: '状态',
    component: 'Select',
    componentProps: {
      placeholder: '请选择状态',
      options: [
        { label: '启用', value: '1' },
        { label: '禁用', value: '0' },
      ],
    },
    colProps: { span: 6 },
  },
];
// 持续时间
const isTimeDuration = (type) => {
  return type === 'DURATION';
};
const isReplace = (type) => {
  return type === 'REPEATING';
};
// 部分
const isPart = (type: string) => {
  return type === 'PART';
};
//新增代码2022-11-23
const isPartOrAll = (type: string) => {
  return type === 'ALL' || type === 'PART';
};
const isService = (type: string) => {
  return Number(type) === 1;
};
const isDefine = (type: string) => {
  return Number(type) === 0;
};
//新增代码2022-11-23

export const trigger_condition_schema: FormSchema[] = [
  {
    field: 'triggered',
    label: '',
    component: 'Select',
    defaultValue: 'SIMPLE',
    componentProps: {
      placeholder: '请选择触发类型',
      options: [
        { label: '简单', value: 'SIMPLE' },
        { label: '持续时长', value: 'DURATION' },
        { label: '重复次数', value: 'REPEATING' },
      ],
    },
    colProps: { span: 6 },
  },
  {
    field: 'deviceType',
    label: '',
    component: 'ApiSelect',
    colProps: { span: 6 },
    defaultValue: 'SENSOR',
    componentProps: ({ formActionType }) => {
      const { setFieldsValue } = formActionType;
      return {
        api: findDictItemByCode,
        params: {
          dictCode: 'device_type',
        },
        placeholder: '请选择类型',
        labelField: 'itemText',
        valueField: 'itemValue',
        getPopupContainer: () => document.body,
        onChange(e) {
          if (e) {
            setFieldsValue({ deviceProfileId: '' });
          }
        },
      };
    },
  },
  {
    field: 'deviceProfileId',
    label: '',
    component: 'ApiSelect',
    colProps: { span: 6 },
    componentProps: ({ formActionType, formModel }) => {
      const { updateSchema, setFieldsValue } = formActionType;
      const deviceType = formModel['deviceType'];

      return {
        api: queryDeviceProfileBy,
        params: {
          deviceType,
        },
        showSearch: true,
        placeholder: '请选择产品',
        labelField: 'name',
        valueField: 'id',
        getPopupContainer: () => document.body,
        onChange: async (e) => {
          if (e) {
            setFieldsValue({ type2: '', entityId: [] });
            const res = await getAttribute(e);
            const options = ref<TOption[]>([]);
            useByProductGetAttribute(res, updateSchema, options);
          }
        },
      };
    },
  },
  {
    field: 'device',
    label: '',
    component: 'Select',
    componentProps: {
      placeholder: '请选择设备',
      options: [
        { label: '全部', value: 'ALL' },
        { label: '部分', value: 'PART' },
      ],
    },
    colProps: { span: 6 },
  },

  {
    field: 'entityId',
    label: '',
    component: 'ApiSelect',
    componentProps: ({ formModel }) => {
      const deviceProfileId = formModel['deviceProfileId'];
      return {
        mode: 'multiple',
        api: async () => {
          if (unref(organizationId)) {
            try {
              const data = await byOrganizationIdGetMasterDevice({
                organizationId: unref(organizationId),
                deviceProfileId,
              });
              if (data)
                return data.map((item) => ({
                  ...item,
                  label: item.alias || item.name,
                  value: item.tbDeviceId,
                }));
            } catch (error) {}
          }
          return [];
        },
        placeholder: '请选择设备',
        getPopupContainer: () => document.body,
      };
    },
    ifShow: ({ values }) => isPart(values.device),
    colProps: { span: 6 },
  },

  {
    field: 'time',
    label: '',
    component: 'Input',
    ifShow: ({ values }) => isTimeDuration(values.triggered),
    colProps: { span: 6 },
    slot: 'time',
    rules: numberAndNonegativeRule,
  },
  {
    field: 'timeUnit',
    label: '',
    component: 'Select',
    defaultValue: 'SECONDS',
    ifShow: ({ values }) => isTimeDuration(values.triggered),
    show: false,
  },
  {
    field: 'replaceValue',
    label: '',
    component: 'Input',
    componentProps: {
      placeholder: '事件计数值',
    },
    ifShow: ({ values }) => isReplace(values.triggered),
    colProps: { span: 6 },
    rules: numberAndNonegativeRule,
  },
  {
    field: 'triggerType',
    label: '',
    component: 'Select',
    componentProps: {
      placeholder: '设备触发',
      options: [
        { label: '设备触发', value: 'DEVICE_TRIGGER' },
        // { label: '定时触发', value: 'SCHEDULE_TRIGGER' },
        // { label: '场景触发', value: 'SCENE_TRIGGER' },
        // { label: '手动触发', value: 'HAND_ACT' },
      ],
    },
    colProps: { span: 6 },
  },

  {
    field: 'type1',
    label: '',
    component: 'Select',
    componentProps: {
      placeholder: '属性触发方式',
      options: [{ label: '属性触发', value: 'TIME_SERIES' }],
    },
    ifShow: ({ values }) => isDevice(values.triggerType),
    colProps: { span: 6 },
  },
  {
    field: 'type2',
    label: '',
    component: 'AutoComplete',
    componentProps: {
      placeholder: '请选择属性',
    },
    ifShow: ({ values }) => isDevice(values.triggerType),
    colProps: { span: 6 },
    // rules: numberAndEngLishRule,
  },
  {
    field: 'operationType',
    label: '',
    component: 'Select',
    slot: 'operationType',
    colProps: { span: 6 },
  },
  // {
  //   field: 'detail',
  //   label: '',
  //   component: 'InputTextArea',
  //   componentProps: {
  //     placeholder: '请输入详情',
  //   },
  //   colProps: {
  //     span: 13,
  //   },
  // },
];
// !!!----------------------------------------------------^_^------------------------------------------------------------!!!
enum ActionEnum {
  DEVICE_OUT = 'DEVICE_OUT',
  ALARM_OUT = 'MSG_NOTIFY',
}
const isDeviceOut = (type: string) => type === ActionEnum.DEVICE_OUT;
const isAlarmOut = (type: string) => type === ActionEnum.ALARM_OUT;

export const actionSchema: FormSchema[] = [
  {
    field: 'outTarget',
    label: '',
    component: 'Select',
    required: true,
    componentProps: {
      placeholder: '请选择执行动作',
    },
    slot: 'outTarget',
    colProps: { span: 6 },
  },
  {
    field: 'deviceType',
    label: '',
    component: 'ApiSelect',
    colProps: { span: 6 },
    defaultValue: 'SENSOR',
    componentProps: ({ formActionType }) => {
      const { setFieldsValue } = formActionType;
      return {
        api: findDictItemByCode,
        params: {
          dictCode: 'device_type',
        },
        placeholder: '请选择类型',
        labelField: 'itemText',
        valueField: 'itemValue',
        getPopupContainer: () => document.body,
        onChange(e) {
          if (e) {
            setFieldsValue({ deviceProfileId: '' });
          }
        },
      };
    },
    ifShow: ({ values }) => isDeviceOut(values.outTarget),
  },
  {
    field: 'deviceProfileId',
    label: '',
    component: 'ApiSelect',
    colProps: { span: 6 },
    componentProps: ({ formActionType, formModel }) => {
      const { setFieldsValue } = formActionType;
      const deviceType = formModel['deviceType'];
      return {
        api: queryDeviceProfileBy,
        params: {
          deviceType,
        },
        placeholder: '请选择产品',
        labelField: 'name',
        valueField: 'id',
        getPopupContainer: () => document.body,
        onChange: () => {
          setFieldsValue({ thingsModelId: '', deviceId: [] });
        },
      };
    },
    ifShow: ({ values }) => isDeviceOut(values.outTarget),
  },
  {
    field: 'device',
    label: '',
    component: 'Select',
    componentProps: ({ formActionType }) => {
      const { setFieldsValue } = formActionType;
      return {
        placeholder: '请选择设备',
        options: [
          { label: '全部', value: 'ALL' },
          { label: '部分', value: 'PART' },
        ],
        onChange: () => {
          setFieldsValue({ deviceId: [], thingsModelId: null });
        },
      };
    },
    ifShow: ({ values }) => isDeviceOut(values.outTarget) && values['deviceProfileId'],
    colProps: { span: 6 },
  },
  {
    field: 'deviceId',
    label: '',
    component: 'ApiSelect',
    componentProps: ({ formModel }) => {
      const deviceProfileId = formModel['deviceProfileId'];
      return {
        mode: 'multiple',
        api: async () => {
          if (unref(organizationId)) {
            try {
              const data = await byOrganizationIdGetMasterDevice({
                organizationId: unref(organizationId),
                deviceProfileId,
              });
              if (data)
                return data.map((item) => ({
                  ...item,
                  label: item.alias || item.name,
                  value: item.tbDeviceId,
                }));
            } catch (error) {}
          }
          return [];
        },
        placeholder: '请选择设备',
        getPopupContainer: () => document.body,
      };
    },
    ifShow: ({ values }) => isPart(values.device) && isDeviceOut(values.outTarget),
    colProps: { span: 6 },
  },
  //新增代码2022-11-23
  {
    field: 'commandType',
    label: '',
    required: true,
    component: 'ApiSelect',
    colProps: {
      span: 6,
    },
    defaultValue: '0',
    componentProps: ({ formActionType }) => {
      const { setFieldsValue } = formActionType;
      return {
        placeholder: '请选择类型',
        api: findDictItemByCode,
        labelField: 'itemText',
        valueField: 'itemValue',
        params: {
          dictCode: 'custom_define',
        },
        numberToString: true,
        getPopupContainer: () => document.body,
        onChange: () => {
          setFieldsValue({ doContext: null, thingsModelId: null });
        },
      };
    },
    ifShow: ({ values }) => isDeviceOut(values.outTarget) && isPartOrAll(values.device),
  },
  //新增代码2022-11-23
  {
    field: 'callType',
    label: '',
    required: true,
    component: 'ApiSelect',
    colProps: {
      span: 6,
    },
    defaultValue: 'SYNC',
    componentProps: {
      placeholder: '请选择类型',
      api: findDictItemByCode,
      params: {
        dictCode: 'call_mode',
      },
      labelField: 'itemText',
      valueField: 'itemValue',
      getPopupContainer: () => document.body,
    },
    ifShow: ({ values }) =>
      isDeviceOut(values.outTarget) && isPartOrAll(values.device) && isDefine(values.commandType),
  },
  //新增代码2022-11-23
  {
    field: 'thingsModelId',
    label: '',
    required: true,
    component: 'ApiSelect',
    colProps: {
      span: 6,
    },
    componentProps: ({ formModel, formActionType }) => {
      const { updateSchema } = formActionType;
      const deviceProfileId = Reflect.get(formModel, 'deviceProfileId');
      const thingsModelId = Reflect.get(formModel, 'thingsModelId');
      return {
        placeholder: '请选择服务',
        api: async (params: Recordable) => {
          try {
            if (!Reflect.get(params, 'deviceProfileId')) return [];
            const record =
              (await getModelServices(params as Record<'deviceProfileId', string>)) || [];
            const selected = record.find((item) => item.id === thingsModelId);
            selected &&
              updateSchema({
                field: 'serviceInputValue',
                componentProps: {
                  inputData: selected?.functionJson.inputData,
                },
              });
            return record;
          } catch (error) {
            console.error(error);
            return [];
          }
        },
        params: {
          deviceProfileId,
        },
        labelField: 'functionName',
        valueField: 'id',
        getPopupContainer: () => document.body,
        onChange: (_, options: ModelOfMatterParams) => {
          if (options) {
            // setFieldsValue({ doContext: { ...options.functionJson, callType: options.callType } });
            updateSchema({
              field: 'serviceInputValue',
              componentProps: {
                inputData: options.functionJson.inputData,
              },
            });
          }
        },
      };
    },
    ifShow: ({ values }) => isDeviceOut(values.outTarget) && isService(values.commandType),
  },
  //新增代码2022-11-23
  {
    field: 'alarm_config',
    label: '',
    component: 'Input',
    componentProps: {
      placeholder: '请选择告警配置',
    },
    slot: 'alarmConfigSlot',
    ifShow: ({ values }) => values.outTarget === 'MSG_NOTIFY',
    colProps: { span: 6 },
  },
  //新增代码2022-11-23
  {
    field: 'doContext',
    component: 'Input',
    label: '',
    slot: 'doContext',
    show: ({ values }) => {
      return (
        isDeviceOut(values.outTarget) && isPartOrAll(values.device) && isDefine(values.commandType)
      );
    },
    colProps: {
      span: 24,
    },
  },
  //新增代码2022-11-23
  {
    field: 'alarm_level',
    component: 'Select',
    label: '',
    show: ({ values }) => isAlarmOut(values.outTarget),
    componentProps: {
      placeholder: '请选择告警等级',
      options: [
        {
          label: '紧急',
          value: 'CRITICAL',
        },
        {
          label: '重要',
          value: 'MAJOR',
        },
        {
          label: '次要',
          value: 'MINOR',
        },
        {
          label: '警告',
          value: 'WARNING',
        },
        {
          label: '不确定',
          value: 'INDETERMINATE',
        },
      ],
    },
    colProps: {
      span: 6,
    },
  },
  {
    field: 'clear_alarm',
    component: 'Checkbox',
    label: '',
    show: ({ values }) => isAlarmOut(values.outTarget),
    colProps: {
      span: 8,
    },
    slot: 'clearAlarm',
  },
  {
    field: 'serviceInputValue',
    component: 'ObjectModelValidateForm',
    label: '',
    changeEvent: 'update:value',
    valueField: 'value',
    show: ({ values }) => values['thingsModelId'],
    colProps: {
      span: 24,
    },
    componentProps: {},
  },
];

export const alarmScheduleSchemas: FormSchema[] = [
  {
    field: 'schedule',
    label: '',
    component: 'Select',
    componentProps({ formActionType }) {
      const { resetFields } = formActionType;
      return {
        options: scheduleOptions,
        allowClear: false,
        onChange() {
          resetFields();
        },
      };
    },
  },
  {
    field: 'timezone',
    label: '时区',
    component: 'Select',
    defaultValue: 'Asia/Shanghai',
    componentProps: {
      options: [
        {
          label: 'Asia/Shanghai',
          value: 'Asia/Shanghai',
        },
      ],
      allowClear: false,
    },
    ifShow: ({ values }) => values.schedule !== 'ANY_TIME',
  },
  {
    field: 'daysOfWeek',
    label: '天',
    component: 'CheckboxGroup',
    rules: [
      {
        message: '请至少选择一天',
        required: true,
      },
    ],
    componentProps: {
      options: [
        { label: '星期一', value: 1 },
        { label: '星期二', value: 2 },
        { label: '星期三', value: 3 },
        { label: '星期四', value: 4 },
        { label: '星期五', value: 5 },
        { label: '星期六', value: 6 },
        { label: '星期日', value: 7 },
      ],
    },
    colProps: {
      span: 24,
    },
    ifShow: ({ values }) => values.schedule === 'SPECIFIC_TIME',
  },
  {
    field: 'time',
    label: '时间',
    labelWidth: 40,
    component: 'RangePicker',
    ifShow: ({ values }) => values.schedule === 'SPECIFIC_TIME',
    slot: 'timing',
  },
  {
    field: 'day',
    label: '天',
    component: 'CheckboxGroup',
    slot: 'customEnable',
    ifShow: ({ values }) => values.schedule === 'CUSTOM',
  },
];
