index.vue 14.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
<script lang="ts" setup>
  import { computed, ref, toRaw, watch } from 'vue';
  import { BasicInfoForm } from './components/BasicInfoForm';
  import { ModalParamsType } from '/#/utils';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { Divider, Tabs, Button, Spin } from 'ant-design-vue';
  import { DataSourceForm } from './components/DataSourceForm';
  import { WidgetLibrary } from '../widgetLibrary';
  import { CreateComponentType, PackagesCategoryEnum } from '../packages/index.type';
  import { TextComponent1Config } from '../packages/components/Text/TextComponent1';
  import { DataSourceType, SelectedWidgetKeys } from './index.type';
  import { buildUUID } from '/@/utils/uuid';
  import { unref } from 'vue';
  import { AddDataComponentParams } from '/@/api/dataBoard/model';
  import { useCalcNewWidgetPosition } from '../palette/hooks/useCalcNewWidgetPosition';
  import { Layout } from 'vue3-grid-layout';
  import { useBoardId } from '../palette/hooks/useBoardId';
  import { addDataComponent, updateDataComponent } from '/@/api/dataBoard';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { DataActionModeEnum } from '/@/enums/toolEnum';
  import { WidgetDataType } from '../palette/hooks/useDataSource';
  import { DATA_SOURCE_LIMIT_NUMBER } from '.';
  import { DataSource } from '../palette/types';
  import { useGetComponentConfig } from '../packages/hook/useGetComponetConfig';
  import { MessageAlert } from './components/MessageAlert';
  import { createSelectWidgetKeysContext, createSelectWidgetModeContext } from './useContext';
  import { useGetCategoryByComponentKey } from '../packages/hook/useGetCategoryByComponentKey';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { deleteFilePath } from '/@/api/oss/ossFileUploader';
  import { FileItem } from '/@/components/Form/src/components/ApiUpload.vue';

  const props = defineProps<{
    layout: Layout[];
  }>();

  const emit = defineEmits(['register', 'ok']);

  enum TabKeyEnum {
    BASIC = 'basic',
    VISUAL = 'visual',
  }

  const { t } = useI18n();

  const { boardId } = useBoardId();

  const { createMessage } = useMessage();

  const loading = ref(false);

  const dataSourceFormSpinning = ref(false);

  let firstEnter = true;

  const selectWidgetKeys = ref<SelectedWidgetKeys>({
    componentKey: TextComponent1Config.key,
    categoryKey: PackagesCategoryEnum.TEXT,
  });

  createSelectWidgetKeysContext(selectWidgetKeys);

  const getComponentConfig = computed<CreateComponentType>(() => {
    return useGetComponentConfig(unref(selectWidgetKeys).componentKey);
  });

  const activeKey = ref(TabKeyEnum.BASIC);

  const genNewDataSourceItem = () => {
    return {
      uuid: buildUUID(),
      componentInfo: unref(getComponentConfig).persetOption || {},
    } as DataSourceType;
  };

  const dataSource = ref<DataSourceType[]>([]);

  const currentMode = ref<DataActionModeEnum>(DataActionModeEnum.CREATE);

  createSelectWidgetModeContext(currentMode);

  const currentRecord = ref<Nullable<Recordable>>({});

  const [registerModal, { closeModal }] = useModalInner(
    (params: ModalParamsType<WidgetDataType>) => {
      resetFormValues();
      const { mode, record } = params;
      currentMode.value = mode;
      currentRecord.value = record;
      firstEnter = false;
      if (mode === DataActionModeEnum.UPDATE) {
        const config = useGetComponentConfig(record.frontId);
        if (!config) return;
        selectWidgetKeys.value = {
          componentKey: config.componentConfig.key,
          categoryKey: config.componentConfig.package,
        };
        activeKey.value = TabKeyEnum.BASIC;
        setFormValues(record);
      } else {
        selectWidgetKeys.value = {
          componentKey: TextComponent1Config.key,
          categoryKey: PackagesCategoryEnum.TEXT,
        };
        activeKey.value = TabKeyEnum.BASIC;
        dataSource.value = [genNewDataSourceItem()];
      }
    }
  );

  const basicInfoFromEl = ref<Nullable<InstanceType<typeof BasicInfoForm>>>(null);

  const dataSourceFormEl = ref<Nullable<InstanceType<typeof DataSourceForm>>>(null);

  const handleTabsChange = (activeKey: TabKeyEnum) => {
    if (activeKey === TabKeyEnum.VISUAL) {
      dataSource.value = (dataSourceFormEl.value?.getFormValues() as DataSourceType[]) || [];
    }
    const value = basicInfoFromEl.value?.getFormValues() || {};
    currentRecord.value = { ...unref(currentRecord), ...value };
  };

  const handleNewRecord = () => {
    const { componentKey } = unref(selectWidgetKeys);

    if (componentKey === 'ComponentStructural' && unref(dataSource).length >= 1) {
      createMessage.warning('结构体组件绑定的数据源不能超过1条');
      return;
    }
    if (componentKey === 'HumidityComponent2' && unref(dataSource).length >= 6) {
      createMessage.warning(t('visual.board.notMax6'));
      return;
    }
    if (unref(dataSource).length >= DATA_SOURCE_LIMIT_NUMBER) {
      createMessage.warning(t('visual.board.notMax10'));
      return;
    }
    dataSource.value.push(genNewDataSourceItem());
  };

  /**
   * @description 可视化组件变化 数据源组件变更 重新赋值表单
   */
  watch(
    () => selectWidgetKeys.value.componentKey,
    (value, oldValue) => {
      if (value) {
        const oldCategory = useGetCategoryByComponentKey(oldValue);
        const category = useGetCategoryByComponentKey(value);
        const needReset =
          [oldCategory, category].some((item) => item === PackagesCategoryEnum.CONTROL) &&
          oldCategory !== category &&
          firstEnter;

        dataSource.value = unref(dataSource).map((item) => ({
          ...item,
          ...(needReset ? { attribute: null } : {}),
          componentInfo: {
            ...toRaw(unref(getComponentConfig).persetOption),
            ...(firstEnter ? {} : item.componentInfo),
          },
        }));

        if ((window as any).requestIdleCallback as unknown as boolean) {
          (window as any).requestIdleCallback(
            () => {
              setFormValues({ dataSource: unref(dataSource) } as WidgetDataType);
            },
            { timeout: 500 }
          );
        } else {
          setTimeout(() => {
            setFormValues({ dataSource: unref(dataSource) } as WidgetDataType);
          }, 500);
        }

        firstEnter = true;
      }
    }
  );

  const validate = async () => {
    return await unref(dataSourceFormEl)?.validate?.();
  };

  const resetFormValues = () => {
    unref(basicInfoFromEl)?.resetFormValues();
    unref(dataSourceFormEl)?.resetFormValues();
  };

  const setFormValues = (data: WidgetDataType) => {
    const { dataSource: newDataSource } = data;
    const { name, remark } = unref(currentRecord) || {};
    dataSource.value = newDataSource;
    unref(basicInfoFromEl)?.setFormValues({ name, remark });
    dataSourceFormSpinning.value = true;
    setTimeout(() => {
      unref(dataSourceFormEl)?.setFormValues(newDataSource);
      dataSourceFormSpinning.value = false;
    }, 500);
  };

  const getFormValues = () => {
    const dataSource = (
      (unref(dataSourceFormEl)?.getFormValues() as unknown as DataSource[]) || []
    ).map((item) => {
      Reflect.deleteProperty(item, 'uuid');
      return item;
    });

    const basicInfo = unref(basicInfoFromEl)?.getFormValues();

    const layout = useCalcNewWidgetPosition(props.layout);

    const frontId = unref(selectWidgetKeys).componentKey;
    return {
      boardId: unref(boardId),
      record: {
        ...(unref(currentMode) === DataActionModeEnum.UPDATE
          ? { id: unref(currentRecord)?.id }
          : {}),
        ...basicInfo,
        dataSource,
        layout,
        frontId,
      },
    } as AddDataComponentParams;
  };

  const getVisualConfigTitle = computed(() => {
    const { categoryKey } = unref(selectWidgetKeys);
    // const category = PackagesCategoryNameEnum[PackagesCategoryEnum[categoryKey]];
    const category = t(`enum.packagesCategory.${PackagesCategoryEnum[categoryKey]}`);
    const { componentConfig } = unref(getComponentConfig);
    return `${category} / ${componentConfig.title}`;
  });

  const countElementOccurrences = (arr) => {
    const countMap = {};

    arr.forEach((element) => {
      if (countMap[element]) {
        countMap[element]++;
      } else {
        countMap[element] = 1;
      }
    });

    return countMap;
  };

  const handleSubmit = async () => {
    const validateResult = await validate();
    if (validateResult && !validateResult.flag) {
      const { errors } = validateResult;
      if (errors && errors.errorFields.length) {
        const errorRecord = errors.errorFields[0];
        createMessage.warning(errorRecord.errors.join(''));
        if (activeKey.value === TabKeyEnum.VISUAL) {
          activeKey.value = TabKeyEnum.BASIC;
        }
        return;
      }
    }
    const value = getFormValues();
    const { record } = value || {};
    const { componentKey } = unref(selectWidgetKeys);
    try {
      const currentRecordIconUrl = ref<any>([]);
      // 判断当前自定义组件表单以前自定义图片的url
      if (unref(currentRecord)?.dataSource) {
        currentRecord.value?.dataSource?.forEach((item) => {
          if (item.componentInfo?.customIcon || componentKey !== 'ComponentStructural') {
            item.componentInfo?.customIcon?.forEach((icon: FileItem) => {
              currentRecordIconUrl.value.push(icon.url);
            });
          }
          // if (componentKey === 'ComponentStructural' && item?.StructuralDeleteUrl) {
          //   currentRecordIconUrl.value.push(...item?.StructuralDeleteUrl?.split(','));

          // }
          for (const item1 in item.componentInfo) {
            if (item1.includes('StructuralCustomIcon')) {
              currentRecordIconUrl.value.push(item.componentInfo[item1]?.[0].url);
            }
          }
        });
      }
      // 取当前修改过后的自定义图片url

      const dataSourceUrl =
        componentKey !== 'ComponentStructural'
          ? record.dataSource?.map((item) => item.componentInfo.customIcon?.[0].url)
          : [];

      if (componentKey === 'ComponentStructural') {
        record.dataSource?.forEach((item) => {
          for (const item1 in item.componentInfo) {
            if (item1.includes('StructuralCustomIcon')) {
              dataSourceUrl?.push(item.componentInfo[item1]?.[0].url);
            }
          }
        });
      }

      // StructuralCustomIcon

      // 当前自定义组件取出要进行删除的图标url ->判断当前组件的自定义图标url是跟以前不一样  取出不一样的以前自定义组件的url进行删除
      const dataSourceDeleteUrl = unref(currentRecordIconUrl).filter(
        (item) => !dataSourceUrl?.includes(item)
      );

      //查询外部所有组件的自定义图标的url
      const oldDataSource = props.layout;
      const customIconUrls = ref<any>([]);
      oldDataSource?.forEach((item: any) => {
        item.dataSource?.forEach((dataSource) => {
          if (dataSource.componentInfo?.customIcon || componentKey !== 'ComponentStructural') {
            dataSource?.componentInfo?.customIcon?.forEach((icon: FileItem) => {
              customIconUrls.value.push(icon.url);
            });
          }
          if (componentKey === 'ComponentStructural') {
            for (const structural in dataSource?.componentInfo) {
              if (structural?.includes('StructuralCustomIcon')) {
                customIconUrls.value.push(dataSource?.componentInfo[structural]?.[0].url);
              }
            }
          }
        });
      });
      // const dataSourceDeleteUrl = record.dataSource?.map((item) => item.componentInfo.deleteUrl);

      if (unref(customIconUrls) && unref(customIconUrls).length && dataSourceDeleteUrl?.length) {
        // 判断外部所有组件是否有dataSourceDeleteUrl使用中的url
        const deletePromise = unref(customIconUrls)?.filter((item) =>
          dataSourceDeleteUrl?.includes(item)
        );
        const deleteUrlInfo = countElementOccurrences(deletePromise);
        const deleteUrl = deletePromise?.filter((item) => deleteUrlInfo?.[item] == 1);
        Promise.all(
          deleteUrl.map((item) => {
            deleteFilePath(item);
          })
        );
      }
    } catch (err) {
      // eslint-disable-next-line no-console
      console.log(err);
    }

    try {
      loading.value = true;
      unref(currentMode) === DataActionModeEnum.UPDATE
        ? await updateDataComponent(value)
        : await addDataComponent(value);
      createMessage.success(
        `${
          unref(currentMode) === DataActionModeEnum.UPDATE
            ? t('common.editText')
            : t('common.createText')
        }${t('common.successText')}`
      );
      closeModal();
      emit('ok');
    } catch (error) {
      throw error;
    } finally {
      activeKey.value = TabKeyEnum.BASIC;
      selectWidgetKeys.value = {
        componentKey: TextComponent1Config.key,
        categoryKey: PackagesCategoryEnum.TEXT,
      };
      dataSource.value = [];
      loading.value = false;
    }
  };
</script>

<template>
  <BasicModal
    :title="t('visual.board.custom.title')"
    width="70%"
    :destroy-on-close="true"
    @register="registerModal"
    @ok="handleSubmit"
    :ok-button-props="{ loading }"
  >
    <Tabs v-model:active-key="activeKey" type="card" @change="handleTabsChange" :animated="true">
      <Tabs.TabPane :tab="t('visual.board.custom.configuration')" :key="TabKeyEnum.BASIC">
        <Divider orientation="left">{{ t('visual.board.custom.information') }}</Divider>

        <BasicInfoForm ref="basicInfoFromEl" />

        <MessageAlert :select-widget-keys="selectWidgetKeys" />

        <Divider orientation="left">{{ t('visual.board.custom.dataConfiguration') }}</Divider>

        <Spin :spinning="dataSourceFormSpinning">
          <DataSourceForm
            ref="dataSourceFormEl"
            :key="getComponentConfig.componentConfig.datasourceConKey"
            :select-widget-keys="selectWidgetKeys"
            v-model:dataSource="dataSource"
            :component-config="getComponentConfig"
          />
        </Spin>

        <div class="flex justify-center">
          <Button type="primary" @click="handleNewRecord">{{
            t('visual.board.custom.addButton')
          }}</Button>
        </div>
      </Tabs.TabPane>
      <Tabs.TabPane :key="TabKeyEnum.VISUAL">
        <template #tab>
          <span>{{ t('visual.board.custom.visualConfiguration') }}</span>
          <span class="mx-1">-</span>
          <span> {{ getVisualConfigTitle }}</span>
        </template>
        <WidgetLibrary v-model:checked="selectWidgetKeys" />
      </Tabs.TabPane>
    </Tabs>
  </BasicModal>
</template>