import { getDeviceAttributes, getMeetTheConditionsDevice } from '/@/api/dataBoard';
import { getOrganizationList } from '/@/api/system/system';
import { FormSchema } from '/@/components/Form';
import { copyTransFun } from '/@/utils/fnUtils';
import { DeviceAttributeParams, MasterDeviceList } from '/@/api/dataBoard/model';
import { FrontComponent } from '../../const/const';
import { getDeviceProfile } from '/@/api/alarm/position';
import { getModelServices } from '/@/api/device/modelOfMatter';
import { findDictItemByCode } from '/@/api/system/dict';
import { DeviceTypeEnum } from '/@/api/device/model/deviceModel';
import { DataTypeEnum } from '/@/components/Form/src/externalCompns/components/StructForm/config';

export enum BasicConfigField {
  NAME = 'name',
  REMARK = 'remark',
}

const getDeviceAttribute = async (params: DeviceAttributeParams) => {
  try {
    const data = await getDeviceAttributes(params);
    if (data) return data.map((item) => ({ label: item.name, value: item.identifier }));
  } catch (error) {}
  return [];
};

const getDeviceService = async (deviceProfileId: string) => {
  try {
    const data = await getModelServices({ deviceProfileId });
    if (data)
      return data.map((item) => ({ ...item, label: item.functionName, value: item.identifier }));
  } catch (error) {}
  return [];
};

export enum DataSourceField {
  IS_GATEWAY_DEVICE = 'gatewayDevice',
  DEVICE_TYPE = 'deviceType',
  TRANSPORT_TYPE = 'transportType',
  ORIGINATION_ID = 'organizationId',
  DEVICE_ID = 'deviceId',
  // SLAVE_DEVICE_ID = 'slaveDeviceId',
  DEVICE_PROFILE_ID = 'deviceProfileId',
  ATTRIBUTE = 'attribute',
  ATTRIBUTE_RENAME = 'attributeRename',
  DEVICE_NAME = 'deviceName',
  DEVICE_RENAME = 'deviceRename',
  LONGITUDE_ATTRIBUTE = 'longitudeAttribute',
  LATITUDE_ATTRIBUTE = 'latitudeAttribute',
}

export const isControlComponent = (frontId: FrontComponent) => {
  const list = [
    FrontComponent.CONTROL_COMPONENT_SLIDING_SWITCH,
    FrontComponent.CONTROL_COMPONENT_SWITCH_WITH_ICON,
    FrontComponent.CONTROL_COMPONENT_TOGGLE_SWITCH,
  ];
  return list.includes(frontId);
};

export const isMapComponent = (frontId: FrontComponent) => {
  const list = [
    FrontComponent.MAP_COMPONENT_TRACK_HISTORY,
    FrontComponent.MAP_COMPONENT_TRACK_REAL,
  ];
  return list.includes(frontId);
};

const isTcpProfile = (transportType: string) => {
  return transportType === 'TCP';
};

export const basicSchema: FormSchema[] = [
  {
    field: BasicConfigField.NAME,
    label: '组件名称',
    component: 'Input',
    // rules: [{ required: true, message: '组件名称为必填项' }],
    componentProps: {
      placeholder: '请输入组件名称',
      maxLength: 32,
    },
  },
  {
    field: BasicConfigField.REMARK,
    label: '组件备注',
    component: 'InputTextArea',
    // rules: [{ required: true, message: '组件备注为必填项' }],
    componentProps: {
      placeholder: '请输入组件备注',
      maxLength: 255,
    },
  },
];

export const dataSourceSchema = (isEdit: boolean, frontId?: FrontComponent): FormSchema[] => {
  return [
    {
      field: DataSourceField.IS_GATEWAY_DEVICE,
      component: 'Switch',
      label: '是否是网关设备',
      show: false,
    },
    {
      field: DataSourceField.DEVICE_NAME,
      component: 'Input',
      label: '设备名',
      show: false,
    },
    {
      field: DataSourceField.TRANSPORT_TYPE,
      component: 'Input',
      label: '设备配置类型',
      show: false,
    },
    {
      field: DataSourceField.DEVICE_TYPE,
      component: 'ApiSelect',
      label: '设备类型',
      colProps: { span: 8 },
      // defaultValue: DeviceTypeEnum.SENSOR,
      componentProps: ({ formActionType }) => {
        const { setFieldsValue } = formActionType;
        return {
          api: findDictItemByCode,
          params: {
            dictCode: 'device_type',
          },
          valueField: 'itemValue',
          labelField: 'itemText',
          placeholder: '请选择设备类型',
          onChange: (value: DeviceTypeEnum) => {
            setFieldsValue({
              [DataSourceField.IS_GATEWAY_DEVICE]: value === DeviceTypeEnum.GATEWAY,
              [DataSourceField.DEVICE_PROFILE_ID]: null,
              [DataSourceField.DEVICE_ID]: null,
              [DataSourceField.ATTRIBUTE]: null,
              [DataSourceField.TRANSPORT_TYPE]: null,
            });
          },
        };
      },
    },
    {
      field: DataSourceField.DEVICE_PROFILE_ID,
      component: 'ApiSelect',
      label: '产品',
      colProps: { span: 8 },
      rules: [{ required: true, message: '产品为必填项' }],
      componentProps: ({ formActionType, formModel }) => {
        const { setFieldsValue } = formActionType;
        const deviceType = formModel[DataSourceField.DEVICE_TYPE];
        return {
          api: async () => {
            if (!deviceType) return [];
            const list = await getDeviceProfile(deviceType);
            if (isEdit) {
              const deviceProfileId = formModel[DataSourceField.DEVICE_PROFILE_ID];
              const record = list.find((item) => item.id === deviceProfileId);
              setFieldsValue({ [DataSourceField.TRANSPORT_TYPE]: record?.transportType });
            }
            return list;
          },
          labelField: 'name',
          valueField: 'id',
          placeholder: '请选择产品',
          onChange: (_, option = {} as Record<'transportType', string>) => {
            setFieldsValue({
              [DataSourceField.DEVICE_ID]: null,
              [DataSourceField.ATTRIBUTE]: null,
              [DataSourceField.TRANSPORT_TYPE]: option[DataSourceField.TRANSPORT_TYPE],
            });
          },
        };
      },
    },
    {
      field: DataSourceField.ORIGINATION_ID,
      component: 'ApiTreeSelect',
      label: '组织',
      colProps: { span: 8 },
      rules: [{ required: true, message: '组织为必填项' }],
      componentProps({ formActionType }) {
        const { setFieldsValue } = formActionType;
        return {
          placeholder: '请选择组织',
          api: async () => {
            const data = await getOrganizationList();
            copyTransFun(data as any as any[]);
            return data;
          },
          onChange() {
            setFieldsValue({
              [DataSourceField.DEVICE_ID]: null,
            });
          },
          getPopupContainer: () => document.body,
        };
      },
    },
    {
      field: DataSourceField.DEVICE_PROFILE_ID,
      component: 'Input',
      label: '',
      show: false,
    },
    {
      field: DataSourceField.DEVICE_ID,
      component: 'ApiSelect',
      label: '设备',
      colProps: { span: 8 },
      rules: [{ required: true, message: '设备名称为必填项' }],
      componentProps({ formModel, formActionType }) {
        const { setFieldsValue } = formActionType;
        const organizationId = formModel[DataSourceField.ORIGINATION_ID];
        const deviceProfileId = formModel[DataSourceField.DEVICE_PROFILE_ID];
        const deviceType = formModel[DataSourceField.DEVICE_TYPE];

        return {
          api: async () => {
            if (organizationId) {
              try {
                const data = await getMeetTheConditionsDevice({
                  organizationId,
                  deviceProfileId,
                  deviceType,
                });
                if (data)
                  return data.map((item) => ({
                    ...item,
                    label: item.alias || item.name,
                    value: item.tbDeviceId,
                    deviceType: item.deviceType,
                  }));
              } catch (error) {}
            }
            return [];
          },
          onChange(_value, record: MasterDeviceList) {
            setFieldsValue({
              [DataSourceField.DEVICE_NAME]: record?.label,
            });
          },
          placeholder: '请选择设备',
          getPopupContainer: () => document.body,
        };
      },
    },
    {
      field: DataSourceField.ATTRIBUTE,
      component: 'ApiSelect',
      label: '属性',
      colProps: { span: 8 },
      rules: [{ required: true, message: '属性为必填项' }],
      componentProps({ formModel }) {
        const deviceProfileId = formModel[DataSourceField.DEVICE_PROFILE_ID];
        const transportType = formModel[DataSourceField.TRANSPORT_TYPE];
        if (isEdit && ![deviceProfileId, transportType].every(Boolean)) return {};
        return {
          api: async () => {
            try {
              if (isControlComponent(frontId as FrontComponent) && isTcpProfile(transportType)) {
                return await getDeviceService(deviceProfileId);
              }

              if (deviceProfileId) {
                return await getDeviceAttribute({
                  deviceProfileId,
                  dataType: isControlComponent(frontId!) ? DataTypeEnum.IS_BOOL : undefined,
                });
              }
            } catch (error) {}

            return [];
          },
          placeholder:
            isControlComponent(frontId as FrontComponent) && isTcpProfile(transportType)
              ? '请选择服务'
              : '请选择属性',
          getPopupContainer: () => document.body,
        };
      },
    },
    {
      field: DataSourceField.DEVICE_RENAME,
      component: 'Input',
      label: '设备名',
      colProps: { span: 8 },
      componentProps: {
        placeholder: '设备重命名',
      },
    },
    {
      field: DataSourceField.ATTRIBUTE_RENAME,
      component: 'Input',
      label: '属性',
      colProps: { span: 8 },
      componentProps: {
        placeholder: '属性重命名',
      },
    },
  ];
};
