useDrawer.vue 17.5 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
<template>
  <div class="drawer-class">
    <BasicDrawer
      v-bind="$attrs"
      @register="registerDrawer"
      showFooter
      :title="getTitle"
      :destroyOnClose="true"
      width="700px"
      @ok="handleSubmit"
    >
      <BasicForm @register="registerForm">
        <template #isolatedTbRuleEngine="{ model }">
          <div class="flex items-center">
            <Checkbox v-model:checked="model.isolatedTbRuleEngine" @change="handleCheckbox" />
            <span>使用独立的规则引擎服务</span>
            <span style="color: grey">(每个独立租户需要单独的规则引擎微服务)</span>
          </div>
        </template>
      </BasicForm>
      <!-- <CpnsTenantSet ref="getChildData" :parentData="parentSetData" /> -->

      <CollapseContainer
        title="队列"
        :defaultExpand="true"
        v-if="isolatedTbRuleEngine"
        class="mb-2"
      >
        <CollapseContainer
          v-for="(item, index) in queueConfiguration"
          :key="item.id"
          :title="item.name"
          :defaultExpand="true"
          class="my-4"
          style="box-shadow: 0 3px 1px -2px #0003, 0 2px 2px #00000024, 0 1px 5px #0000001f"
        >
          <template #action v-if="item.name !== 'Main'">
            <Tooltip title="删除">
              <Icon
                class="ml-2 cursor-pointer"
                icon="fluent:delete-off-20-regular"
                size="20"
                @click="handleDeleteTenant(index)"
              />
            </Tooltip>
          </template>
          <TenantConfig
            ref="getTenantConfig"
            :record="item"
            @handleNameChange="(name) => handleNameChange(index, name)"
          />
        </CollapseContainer>

        <Button @click="handleCreateQueue" type="primary" class="my-3">添加队列</Button>
      </CollapseContainer>
      <CollapseContainer title="实体 (0-无限制)" :defaultExpand="false">
        <Entity ref="getEntity" />
      </CollapseContainer>
      <CollapseContainer title="规则引擎 (0-无限制)" :defaultExpand="false">
        <RuleEngine ref="getRuleEngine" />
      </CollapseContainer>
      <CollapseContainer title="TTL (0-无限制)" :defaultExpand="false">
        <Ttl ref="getTtl" />
      </CollapseContainer>
      <CollapseContainer title="告警与通知 (0-无限制)" :defaultExpand="false">
        <Alarm ref="getAlarm" />
      </CollapseContainer>
      <CollapseContainer title="OTA文件(字节)(0-无限制)" :defaultExpand="false">
        <Ota ref="getOta" />
      </CollapseContainer>
      <CollapseContainer title="WS (0-无限制)" :defaultExpand="false">
        <Ws ref="getWs" />
      </CollapseContainer>
      <CollapseContainer title="速率限制" :defaultExpand="false">
        <Speed ref="getSpeed" />
      </CollapseContainer>
    </BasicDrawer>
  </div>
</template>
<script lang="ts">
  import {
    defineComponent,
    ref,
    computed,
    unref,
    getCurrentInstance,
    reactive,
    nextTick,
  } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form';
  import { formSchema } from './config';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  // import CpnsTenantSet from './cpns/index.vue';
  import Entity from './configuration/entity.vue';
  import Ttl from './configuration/ttl.vue';
  import Alarm from './configuration/alarm.vue';
  import Ota from './configuration/ota.vue';
  import Ws from './configuration/ws.vue';
  import Speed from './configuration/speed.vue';
  import RuleEngine from './configuration/ruleEngine.vue';
  import { saveTenantProfileApi } from '/@/api/tenant/tenantApi';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { CollapseContainer } from '/@/components/Container/index';
  import { Checkbox, Tooltip, Button } from 'ant-design-vue';
  import TenantConfig from './components/TenantConfig.vue';
  import { buildUUID } from '/@/utils/uuid';

  export default defineComponent({
    name: 'ConfigDrawer',
    components: {
      BasicDrawer,
      BasicForm,
      CollapseContainer,
      // CpnsTenantSet,
      Ws,
      RuleEngine,
      Ttl,
      Alarm,
      Ota,
      Speed,
      Entity,
      Checkbox,
      Tooltip,
      Button,
      TenantConfig,
    },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const { createMessage } = useMessage();
      const isUpdate = ref(true);
      let postAllData: any = reactive({});
      const parentSetData: any = ref(null);
      let getValuesFormData: any = reactive({});
      const { proxy } = getCurrentInstance() as any;
      const getChildData = ref(null);

      const getEntity = ref(null);
      const getRuleEngine = ref(null);
      const getTtl = ref(null);
      const getAlarm = ref(null);
      const getOta = ref(null);
      const getWs = ref(null);
      const getSpeed = ref(null);
      const getTenantConfig = ref(null);

      const editGetId: any = ref('');
      const isDefault = ref(false);
      const createTime = ref<string>('');

      // 独立规则引擎默认的三项Main不能删除其他能删除
      const defaultQueueConfiguration = () => {
        return [
          {
            name: 'Main',
            topic: 'tb_rule_engine.main',
            pollInterval: 2000,
            partitions: 1,
            consumerPerPartition: false,
            packProcessingTimeout: 10000,
            submitStrategy: {
              type: 'BURST',
              batchSize: 1000,
            },
            processingStrategy: {
              type: 'SKIP_ALL_FAILURES',
              retries: 3,
              failurePercentage: 0,
              pauseBetweenRetries: 3,
              maxPauseBetweenRetries: 3,
            },
            id: buildUUID(),
            disabled: true,
            nameOnly: true,
            additionalInfo: {
              description: '',
              customProperties: '',
            },
          },
          {
            name: 'HighPriority',
            topic: 'tb_rule_engine.hp',
            pollInterval: 2000,
            partitions: 1,
            consumerPerPartition: false,
            packProcessingTimeout: 10000,
            submitStrategy: {
              type: 'BURST',
              batchSize: 100,
            },
            processingStrategy: {
              type: 'RETRY_FAILED_AND_TIMED_OUT',
              retries: 0,
              failurePercentage: 0,
              pauseBetweenRetries: 5,
              maxPauseBetweenRetries: 5,
            },
            id: buildUUID(),
            disabled: true,
            nameOnly: true,
            additionalInfo: {
              description: '',
              customProperties: '',
            },
          },
          {
            name: 'SequentialByOriginator',
            topic: 'tb_rule_engine.sq',
            pollInterval: 2000,
            partitions: 1,
            consumerPerPartition: false,
            packProcessingTimeout: 10000,
            submitStrategy: {
              type: 'SEQUENTIAL_BY_ORIGINATOR',
              batchSize: 100,
            },
            processingStrategy: {
              type: 'RETRY_FAILED_AND_TIMED_OUT',
              retries: 3,
              failurePercentage: 0,
              pauseBetweenRetries: 5,
              maxPauseBetweenRetries: 5,
            },
            id: buildUUID(),
            disabled: true,
            nameOnly: true,
            additionalInfo: {
              description: '',
              customProperties: '',
            },
          },
        ];
      };
      const queueConfiguration = ref<any>([]);

      const [registerForm, { validate, resetFields, setFieldsValue, updateSchema }] = useForm({
        schemas: formSchema,
        showActionButtonGroup: false,
      });

      // 判断是否启用独立规则引擎
      const isolatedTbRuleEngine = ref<boolean>(false);
      const handleCheckbox = (checkedValue) => {
        const {
          target: { checked },
        } = checkedValue || {};
        isolatedTbRuleEngine.value = checked;
        if (checked && !unref(isUpdate)) {
          queueConfiguration.value = defaultQueueConfiguration();
          nextTick(() => {
            unref(queueConfiguration).forEach((item, index) => {
              proxy.$refs.getTenantConfig[index]?.setAllFieldsValue(item);
            });
          });
        }
      };

      // 删除队列
      const handleDeleteTenant = (index: number) => {
        queueConfiguration.value.splice(index, 1);
      };

      const handleNameChange = async (index: number, name: string) => {
        const isRepeat = unref(queueConfiguration).every((item) => item.name !== name);
        nextTick(() => {
          queueConfiguration.value[index].name = name;
        });
        if (!isRepeat) {
          createMessage.warning('队列名称必须唯一。');
          proxy.$refs.getTenantConfig[index]?.setFieldsValue({
            nameOnly: false,
            topic: 'tb_rule_engine.' + name,
          });
          return;
        }
        proxy.$refs.getTenantConfig[index]?.setFieldsValue({
          nameOnly: true,
          topic: 'tb_rule_engine.' + name,
        });
      };

      const handleCreateQueue = () => {
        const values = {
          name: '',
          pollInterval: 2000,
          partitions: 1,
          consumerPerPartition: false,
          packProcessingTimeout: 10000,
          submitStrategy: {
            type: 'BURST',
            batchSize: 1000,
          },
          processingStrategy: {
            type: 'SKIP_ALL_FAILURES',
            retries: 3,
            failurePercentage: 0,
            pauseBetweenRetries: 3,
            maxPauseBetweenRetries: 3,
          },
          disabled: false,
          id: buildUUID(),
          nameOnly: true,
          additionalInfo: {
            description: '',
            customProperties: '',
          },
        };
        queueConfiguration.value.push(values);
        nextTick(() => {
          proxy.$refs.getTenantConfig[unref(queueConfiguration).length - 1]?.setAllFieldsValue(
            values
          );
        });
      };

      const funcResetFields = () => {
        proxy.$refs.getEntity.funcResetFields();
        proxy.$refs.getRuleEngine.funcResetFields();
        proxy.$refs.getTtl.funcResetFields();
        proxy.$refs.getAlarm.funcResetFields();
        proxy.$refs.getOta.funcResetFields();
        proxy.$refs.getWs.funcResetFields();
        proxy.$refs.getSpeed.funcResetFields();
      };

      const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
        //清除表单值
        funcResetFields();
        await resetFields();
        setDrawerProps({ confirmLoading: false });
        isUpdate.value = !!data?.isUpdate;
        if (!unref(isUpdate)) {
          editGetId.value = '';
          updateStatusSchema(false);
        }
        //编辑
        if (unref(isUpdate)) {
          parentSetData.value = { ...data.record.profileData.configuration };
          proxy.$refs.getEntity.setFieldsValueFunc(parentSetData.value);
          proxy.$refs.getRuleEngine.setFieldsValueFunc(parentSetData.value);
          proxy.$refs.getTtl.setFieldsValueFunc(parentSetData.value);
          proxy.$refs.getAlarm.setFieldsValueFunc(parentSetData.value);
          proxy.$refs.getOta.setFieldsValueFunc(parentSetData.value);
          proxy.$refs.getWs.setFieldsValueFunc(parentSetData.value);
          proxy.$refs.getSpeed.setFieldsValueFunc(parentSetData.value);
          editGetId.value = data.record.id;
          isDefault.value = data.record.default;
          await setFieldsValue({
            ...data.record,
          });
          const { isolatedTbRuleEngine: dataIsolatedTbRuleEngine } = data.record || {};
          isolatedTbRuleEngine.value = dataIsolatedTbRuleEngine;

          const oldQueueConfiguration = data.record.profileData.queueConfiguration;
          //独立规则引擎服务赋值
          if (dataIsolatedTbRuleEngine && oldQueueConfiguration?.length) {
            queueConfiguration.value =
              oldQueueConfiguration.map((item) => {
                return {
                  ...item,
                  id: buildUUID(),
                  disabled: true,
                  nameOnly: true,
                };
              }) || defaultQueueConfiguration();
            nextTick(() => {
              unref(queueConfiguration).forEach((item, index) => {
                proxy.$refs.getTenantConfig[index]?.setAllFieldsValue(item);
              });
            });
          }

          createTime.value = data.record.createdTime;
          updateStatusSchema(true);
        }
      });
      const getTitle = computed(() => (!unref(isUpdate) ? '新增租户配置' : '编辑租户配置'));

      const updateStatusSchema = (status) => {
        updateSchema([
          {
            field: 'isolatedTbRuleEngine',
            componentProps: {
              disabled: status,
            },
          },
          // {
          //   field: 'isolatedTbRuleEngine',
          //   componentProps: {
          //     disabled: status,
          //   },
          // },
        ]);
      };

      const getAllFieldsFunc = async (isUpdate?: boolean) => {
        getValuesFormData = await validate();
        if (!getValuesFormData) return;
        let getEntity = proxy.$refs.getEntity.getAllFields();
        let getRuleEngine = proxy.$refs.getRuleEngine.getAllFields();
        let getTtl = proxy.$refs.getTtl.getAllFields();
        let getAlarm = proxy.$refs.getAlarm.getAllFields();
        let getOta = proxy.$refs.getOta.getAllFields();
        let getWs = proxy.$refs.getWs.getAllFields();
        let getSpeed = proxy.$refs.getSpeed.getAllFields();
        let profileData1 = {
          configuration: {
            ...getEntity,
            ...getRuleEngine,
            ...getTtl,
            ...getAlarm,
            ...getOta,
            ...getWs,
            ...getSpeed,
            type: 'DEFAULT',
          },
          queueConfiguration: null,
        };
        const id: any = {
          id: unref(isUpdate) ? editGetId.value : '',
        };

        const createTime1 = {
          createdTime: isUpdate ? unref(createTime) : Date.now(),
        };

        // const defaultInfo = {
        //   default: unref(isUpdate) ? isDefault.value : false,
        // };
        Object.assign(
          postAllData,
          {
            profileData: profileData1,
          },
          getValuesFormData,
          id,
          createTime1
          // defaultInfo
        );
        if (!unref(isUpdate)) {
          delete postAllData.id;
        }
      };

      async function handleSubmit() {
        setDrawerProps({ confirmLoading: true });
        try {
          if (!unref(isUpdate)) {
            await getAllFieldsFunc();
            const getTenantConfigRefs = proxy.$refs.getTenantConfig;
            const queueConfigValues: any = [];
            for (let i = 0; i < getTenantConfigRefs?.length; i++) {
              await proxy.$refs.getTenantConfig[i].validateAll();
              const values = proxy.$refs.getTenantConfig[i].getAllFieldsValue();
              queueConfigValues.push({ ...values, nameOnly: undefined });
              const { nameOnly } = values || {};
              if (!nameOnly) {
                createMessage.success('队列名称必须唯一。');
                return false;
              }
            }
            const {
              profileData: { configuration },
            } = postAllData || {};
            await saveTenantProfileApi({
              ...postAllData,
              profileData: { configuration, queueConfiguration: queueConfigValues },
            });
            createMessage.success('租户配置新增成功');

            closeDrawer();
            emit('success');
            resetFields();
          } else {
            await getAllFieldsFunc(true);
            const getTenantConfigRefs = proxy.$refs.getTenantConfig;
            // proxy.$refs.getTenantConfig[index].getAllFieldsValue();
            const queueConfigValues: any = [];
            for (let i = 0; i < getTenantConfigRefs?.length; i++) {
              await proxy.$refs.getTenantConfig[i].validateAll();
              const values = proxy.$refs.getTenantConfig[i].getAllFieldsValue();
              queueConfigValues.push({ ...values, nameOnly: undefined });
              const { nameOnly } = values || {};
              if (!nameOnly) {
                createMessage.warning('队列名称必须唯一。');
                return false;
              }
            }
            const {
              profileData: { configuration },
            } = postAllData || {};
            await saveTenantProfileApi({
              ...postAllData,
              profileData: { configuration, queueConfiguration: queueConfigValues },
            });
            createMessage.success('租户配置编辑成功');
            closeDrawer();
            emit('success');
          }
        } catch (e) {
        } finally {
          setTimeout(() => {
            setDrawerProps({ confirmLoading: false });
          }, 300);
        }
      }
      return {
        parentSetData,
        getChildData,
        registerDrawer,
        registerForm,
        getTitle,
        handleSubmit,
        getEntity,
        getRuleEngine,
        getTtl,
        getAlarm,
        getOta,
        getWs,
        getSpeed,
        handleCheckbox,
        isolatedTbRuleEngine,
        handleDeleteTenant,
        queueConfiguration,
        getTenantConfig,
        handleNameChange,
        handleCreateQueue,
      };
    },
  });
</script>

<style lang="less">
  .drawer-class {
    .ant-row {
      .ant-col {
        :deep .ant-input-number {
          width: 34vw !important;
        }
      }
    }
  }
</style>