common.config.ts 18.3 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543
import { unref } from 'vue';
import { useSelectWidgetKeys, useSelectWidgetMode } from '../../dataSourceBindPanel/useContext';
import { PackagesCategoryEnum } from '../index.type';
import { getDeviceProfile } from '/@/api/alarm/position';
import { getDeviceAttributes, getMeetTheConditionsDevice } from '/@/api/dataBoard';
import { DeviceAttributeParams } from '/@/api/dataBoard/model';
import { getModelServices } from '/@/api/device/modelOfMatter';
import { findDictItemByCode } from '/@/api/system/dict';
import { ApiCascader, FormSchema, useComponentRegister } from '/@/components/Form';
import { OrgTreeSelect } from '/@/views/common/OrgTreeSelect';
import { DataActionModeEnum } from '/@/enums/toolEnum';
import { TaskTypeEnum } from '/@/views/task/center/config';
import { createPickerSearch } from '/@/utils/pickerSearch';
import { DataTypeEnum } from '/@/enums/objectModelEnum';
import { CommandTypeEnum, CommandTypeNameEnum } from '/@/enums/deviceEnum';
import { TransportTypeEnum } from '/@/enums/deviceEnum';
import { DeviceTypeEnum } from '/@/api/device/model/deviceModel';
import { ControlComponentEnum } from '../components/Control';
import { isNullOrUnDef } from '/@/utils/is';
import { validateTCPCustomCommand } from '/@/components/Form/src/components/ThingsModelForm';
import { CategoryEnum } from '../components';

useComponentRegister('OrgTreeSelect', OrgTreeSelect);
useComponentRegister('ApiCascader', ApiCascader);

export interface CommonDataSourceBindValueType extends Record<DataSourceField, string> {
  customCommand?: {
    transportType?: string;
    service?: string;
    command?: string;
    commandType?: string;
    callType?: string;
    [ksy: string]: string | undefined;
  };
}

export enum DataSourceField {
  // IS_GATEWAY_DEVICE = 'gatewayDevice',
  DEVICE_TYPE = 'deviceType',
  TRANSPORT_TYPE = 'transportType',
  ORIGINATION_ID = 'organizationId',
  DEVICE_ID = 'deviceId',
  // DEVICE_CODE = 'deviceCode', //设备地址码
  DEVICE_PROFILE_ID = 'deviceProfileId',
  ATTRIBUTE = 'attribute',
  // ATTRIBUTE_NAME = 'attributeName',
  ATTRIBUTE_RENAME = 'attributeRename',
  DEVICE_NAME = 'deviceName',
  DEVICE_RENAME = 'deviceRename',

  CODE_TYPE = 'codeType',
  // COMMAND = 'command',

  OPEN_COMMAND = 'openCommand',
  CLOSE_COMMAND = 'closeCommand',

  COMMAND_TYPE = 'commandType',

  // SERVICE = 'service',

  /**
   * @description 关服务标识符
   */
  OPEN_SERVICE = 'openService',

  /**
   * @description 开服务标识符
   */
  CLOSE_SERVICE = 'closeService',

  /**
   * @description 经度标识符
   */
  LONGITUDE_IDENTIFIER = 'longitudeIdentifier',

  /**
   * @description 纬度标识符号
   */
  LATITUDE_IDENTIFIER = 'latitudeIdentifier',

  // EXTENSION_DESC = 'extensionDesc',
  // CALL_TYPE = 'callType',
}

const isTcpProfile = (transportType: string) => transportType === TransportTypeEnum.TCP;

const isControlComponent = (category?: string) => PackagesCategoryEnum.CONTROL === category;

const isBooleanComponent = (componentKeys: { categoryKey?: string; componentKey?: string }) => {
  const { categoryKey, componentKey } = componentKeys;
  return (
    categoryKey == 'OTHER' &&
    (componentKey == 'SwitchSignalLight' || componentKey == 'SwitchStatus')
  );
};

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

export const commonDataSourceSchemas = (): FormSchema[] => {
  const mode = useSelectWidgetMode();
  const isUpdate = unref(mode) === DataActionModeEnum.UPDATE;
  const selectWidgetKeys = useSelectWidgetKeys();
  const category = unref(selectWidgetKeys).categoryKey;

  return [
    {
      field: DataSourceField.DEVICE_TYPE,
      component: 'ApiSelect',
      label: '设备类型',
      colProps: { span: 8 },
      rules: [{ message: '请选择设备类型', required: true }],
      componentProps: ({ formActionType }) => {
        const { setFieldsValue } = formActionType;
        return {
          api: findDictItemByCode,
          params: {
            dictCode: 'device_type',
          },
          valueField: 'itemValue',
          labelField: 'itemText',
          placeholder: '请选择设备类型',
          onChange: () => {
            setFieldsValue({
              [DataSourceField.DEVICE_PROFILE_ID]: null,
              [DataSourceField.DEVICE_ID]: null,
              [DataSourceField.ATTRIBUTE]: null,
              [DataSourceField.TRANSPORT_TYPE]: null,
            });
          },
          getPopupContainer: () => document.body,
        };
      },
    },
    {
      field: DataSourceField.TRANSPORT_TYPE,
      label: '传输协议',
      component: 'Input',
      ifShow: false,
    },
    {
      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 (isUpdate) {
              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: Record<'transportType', string>) => {
            setFieldsValue({
              [DataSourceField.DEVICE_ID]: null,
              [DataSourceField.ATTRIBUTE]: null,
              [DataSourceField.TRANSPORT_TYPE]: option?.[DataSourceField.TRANSPORT_TYPE],
              [DataSourceField.COMMAND_TYPE]: null,
            });
          },
          getPopupContainer: () => document.body,
        };
      },
    },
    {
      field: DataSourceField.ORIGINATION_ID,
      component: 'OrgTreeSelect',
      label: '组织',
      colProps: { span: 8 },
      rules: [{ required: true, message: '组织为必填项' }],
      componentProps({ formActionType }) {
        const { setFieldsValue } = formActionType;
        return {
          placeholder: '请选择组织',
          onChange() {
            setFieldsValue({
              [DataSourceField.DEVICE_ID]: null,
            });
          },
          showCreate: false,
          apiTreeSelectProps: {
            params: { organizationId: location?.pathname?.split('/')?.pop() || '' },
          },
          getPopupContainer: () => document.body,
        };
      },
    },
    {
      field: DataSourceField.DEVICE_NAME,
      component: 'Input',
      label: '设备名称',
      ifShow: 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) {
                  const result = data.map((item) => ({
                    ...item,
                    label: item.alias || item.name,
                    value: item.tbDeviceId,
                    deviceType: item.deviceType,
                  }));

                  if (
                    unref(selectWidgetKeys).componentKey ===
                      ControlComponentEnum.LATERAL_NUMERICAL_CONTROL &&
                    isTcpProfile(formModel[DataSourceField.TRANSPORT_TYPE])
                  ) {
                    return result.filter((item) => item.codeType === TaskTypeEnum.MODBUS_RTU);
                  }

                  return result;
                }
              } catch (error) {}
            }
            return [];
          },
          onChange(_value, options: Record<'label' | 'codeType', string>) {
            setFieldsValue({
              [DataSourceField.COMMAND_TYPE]: null,
              [DataSourceField.DEVICE_NAME]: options?.label,
              [DataSourceField.CODE_TYPE]: options?.codeType,
            });
          },
          placeholder: '请选择设备',
          ...createPickerSearch(),
        };
      },
    },
    {
      field: DataSourceField.CODE_TYPE,
      label: '设备标识符类型',
      component: 'Input',
      ifShow: false,
    },
    {
      field: DataSourceField.ATTRIBUTE,
      component: 'ApiSelect',
      label: '属性',
      colProps: { span: 8 },
      rules: [{ required: true, message: '请选择属性' }],
      ifShow: () => category !== CategoryEnum.MAP,
      componentProps({ formModel, formActionType }) {
        const { setFieldsValue } = formActionType;
        const deviceProfileId = formModel[DataSourceField.DEVICE_PROFILE_ID];
        return {
          api: async () => {
            try {
              if (deviceProfileId) {
                const option = await getDeviceAttribute({
                  deviceProfileId,
                  dataType:
                    (isControlComponent(category!) &&
                      unref(selectWidgetKeys).componentKey !==
                        ControlComponentEnum.LATERAL_NUMERICAL_CONTROL) ||
                    isBooleanComponent(unref(selectWidgetKeys))
                      ? DataTypeEnum.BOOL
                      : undefined,
                });

                // 选择控制组件4的时候只能选择属性且是(int double类型)
                if (
                  unref(selectWidgetKeys).componentKey ===
                  ControlComponentEnum.LATERAL_NUMERICAL_CONTROL
                ) {
                  setFieldsValue({
                    [DataSourceField.COMMAND_TYPE]: CommandTypeEnum.ATTRIBUTE.toString(),
                  });
                  return option.filter(
                    (item) =>
                      item.detail.dataType.type === DataTypeEnum.NUMBER_INT ||
                      item.detail.dataType.type == DataTypeEnum.NUMBER_DOUBLE
                  );
                }
                return option;
              }
            } catch (error) {}
            return [];
          },
          placeholder: '请选择属性',
          ...createPickerSearch(),
        };
      },
    },
    {
      field: DataSourceField.LONGITUDE_IDENTIFIER,
      label: '经度',
      component: 'ApiCascader',
      ifShow: ({}) => category === CategoryEnum.MAP,
      colProps: { span: 8 },
      changeEvent: 'update:value',
      valueField: 'value',
      componentProps: ({ formModel }) => {
        const deviceProfileId = formModel[DataSourceField.DEVICE_PROFILE_ID];
        return {
          api: async () => {
            try {
              if (deviceProfileId) {
                const options = await getDeviceAttributes({
                  deviceProfileId,
                });

                const _options = options.map((item) => {
                  item = Object.assign(item, { functionName: item.name });
                  if (item.detail.dataType.type === DataTypeEnum.STRUCT) {
                    return Object.assign(item, { specs: item.detail.dataType.specs });
                  }
                  return item;
                });
                return _options;
              }
            } catch (error) {}
            return [];
          },
          placeholder: '请选择经度',
          getPopupContainer: () => document.body,
          fieldNames: { label: 'functionName', value: 'identifier', children: 'specs' },
        };
      },
    },
    {
      field: DataSourceField.LATITUDE_IDENTIFIER,
      label: '纬度',
      component: 'ApiCascader',
      ifShow: ({}) => category === CategoryEnum.MAP,
      colProps: { span: 8 },
      changeEvent: 'update:value',
      valueField: 'value',
      componentProps: ({ formModel }) => {
        const deviceProfileId = formModel[DataSourceField.DEVICE_PROFILE_ID];

        return {
          api: async () => {
            try {
              if (deviceProfileId) {
                const options = await getDeviceAttributes({
                  deviceProfileId,
                });

                const _options = options.map((item) => {
                  item = Object.assign(item, { functionName: item.name });

                  if (item.detail.dataType.type === DataTypeEnum.STRUCT) {
                    return Object.assign(item, { specs: item.detail.dataType.specs });
                  }
                  return item;
                });

                return _options;
              }
            } catch (error) {}
            return [];
          },
          placeholder: '请选择纬度',
          getPopupContainer: () => document.body,
          fieldNames: { label: 'functionName', value: 'identifier', children: 'specs' },
        };
      },
    },
    {
      field: DataSourceField.COMMAND_TYPE,
      component: 'Select',
      label: '命令类型',
      defaultValue: CommandTypeEnum.CUSTOM,
      rules: [
        {
          required: true,
          validator(_, value: number | string) {
            if (isNullOrUnDef(value)) return Promise.reject('请选择命令类型');
            return Promise.resolve();
          },
        },
      ],
      colProps: { span: 8 },
      ifShow: ({ model }) => {
        return (
          isControlComponent(category!) &&
          unref(selectWidgetKeys).componentKey !== ControlComponentEnum.LATERAL_NUMERICAL_CONTROL &&
          isTcpProfile(model[DataSourceField.TRANSPORT_TYPE]) &&
          model[DataSourceField.CODE_TYPE] === TaskTypeEnum.CUSTOM
        );
      },
      componentProps: ({ formActionType, formModel }) => {
        const { setFieldsValue } = formActionType;
        const deviceType = formModel[DataSourceField.DEVICE_TYPE];
        const options: Record<'label' | 'value', string | number>[] = [
          { label: CommandTypeNameEnum.CUSTOM, value: CommandTypeEnum.CUSTOM },
        ];

        // 网关子设备无服务
        if (deviceType !== DeviceTypeEnum.SENSOR)
          options.push({ label: CommandTypeNameEnum.SERVICE, value: CommandTypeEnum.SERVICE });

        return {
          options,
          placeholder: '请选择命令类型',
          getPopupContainer: () => document.body,
          onChange() {
            setFieldsValue({
              [DataSourceField.OPEN_COMMAND]: null,
              [DataSourceField.CLOSE_COMMAND]: null,
              [DataSourceField.OPEN_SERVICE]: null,
              [DataSourceField.CLOSE_SERVICE]: null,
            });
          },
        };
      },
    },
    {
      field: DataSourceField.OPEN_SERVICE,
      component: 'ApiSelect',
      label: '开服务',
      colProps: { span: 8 },
      rules: [{ required: true, message: '请选择开服务' }],
      ifShow: ({ model }) =>
        isControlComponent(category!) &&
        model[DataSourceField.COMMAND_TYPE] === CommandTypeEnum.SERVICE &&
        isTcpProfile(model[DataSourceField.TRANSPORT_TYPE]),
      componentProps({ formModel }) {
        const deviceProfileId = formModel[DataSourceField.DEVICE_PROFILE_ID];
        return {
          api: getModelServices,
          params: {
            deviceProfileId,
          },
          placeholder: '请选择开服务',
          labelField: 'functionName',
          valueField: 'identifier',
          getPopupContainer: () => document.body,
        };
      },
    },
    {
      field: DataSourceField.CLOSE_SERVICE,
      component: 'ApiSelect',
      label: '关服务',
      colProps: { span: 8 },
      rules: [{ required: true, message: '请选择关服务' }],
      ifShow: ({ model }) =>
        isControlComponent(category!) &&
        model[DataSourceField.COMMAND_TYPE] === CommandTypeEnum.SERVICE &&
        isTcpProfile(model[DataSourceField.TRANSPORT_TYPE]),
      componentProps({ formModel }) {
        const deviceProfileId = formModel[DataSourceField.DEVICE_PROFILE_ID];
        return {
          api: getModelServices,
          params: {
            deviceProfileId,
          },
          placeholder: '请选择关服务',
          labelField: 'functionName',
          valueField: 'identifier',
          getPopupContainer: () => document.body,
        };
      },
    },
    {
      field: DataSourceField.OPEN_COMMAND,
      component: 'Input',
      label: '命令',
      colProps: { span: 8 },
      rules: [{ validator: validateTCPCustomCommand }],
      // 是控制组件  && 自定义命令  && 传输协议为TCP
      ifShow: ({ model }) =>
        isControlComponent(category!) &&
        model[DataSourceField.COMMAND_TYPE] === CommandTypeEnum.CUSTOM &&
        model[DataSourceField.TRANSPORT_TYPE] &&
        isTcpProfile(model[DataSourceField.TRANSPORT_TYPE]),
      componentProps: {
        placeholder: '请输入开下发命令',
      },
    },
    {
      field: DataSourceField.CLOSE_COMMAND,
      component: 'Input',
      label: '命令',
      colProps: { span: 8 },
      rules: [{ validator: validateTCPCustomCommand }],
      // 是控制组件  && 自定义命令  && 传输协议为TCP
      ifShow: ({ model }) =>
        isControlComponent(category!) &&
        model[DataSourceField.COMMAND_TYPE] === CommandTypeEnum.CUSTOM &&
        model[DataSourceField.TRANSPORT_TYPE] &&
        isTcpProfile(model[DataSourceField.TRANSPORT_TYPE]),
      componentProps: {
        placeholder: '请输入关下发命令',
      },
    },
    {
      field: DataSourceField.DEVICE_RENAME,
      component: 'Input',
      label: '设备名',
      colProps: { span: 8 },
      componentProps: {
        placeholder: '设备重命名',
      },
    },
    {
      field: DataSourceField.ATTRIBUTE_RENAME,
      component: 'Input',
      label: '属性',
      colProps: { span: 8 },
      componentProps: {
        placeholder: '属性重命名',
      },
    },
  ];
};