riku
2025-06-12 a3b2d94cbfb9bea819346a1b738237f72819a833
src/views/sourcetrace/SourceTrace.vue
@@ -1,30 +1,95 @@
<template>
  <BaseCard>
    <template #content>
      <div>
        <el-input type="text" v-model="inputVal" />
        <button @click="handleSend">send</button>
        <button @click="handleLink">link</button>
      </div>
      <div>业务状态中控</div>
      <el-scrollbar ref="scrollbarRef" :height="height">
        <div ref="scrollContentRef">
          <div v-for="(item, index) in streams" :key="index">
            <el-text type="primary">[{{ item }}]: </el-text>
          </div>
        </div>
      </el-scrollbar>
    </template>
  </BaseCard>
  <el-row>
    <el-col span="2" class="flex-col">
      <el-row justify="end">
        <CardButton
          direction="left"
          name="动态溯源"
          @click="() => (show = !show)"
        ></CardButton>
      </el-row>
      <el-row class="flex-col">
        <PollutedExceptionItem
          :item="selectedException"
          @showMarksAndPolygon="showMarksAndPolygon"
        ></PollutedExceptionItem>
      </el-row>
    </el-col>
    <el-col v-show="show" span="10">
      <BaseCard>
        <template #content>
          <el-checkbox-group v-model="selectedMsgTypes" size="default" :min="1">
            <el-space>
              <el-checkbox value="1">异常切片</el-checkbox>
              <el-checkbox value="2">污染线索</el-checkbox>
            </el-space>
          </el-checkbox-group>
          <el-scrollbar ref="scrollbarRef" class="scrollbar">
            <!-- <div
              ref="scrollContentRef"
              style="display: flex; width: fit-content"
            > -->
            <TransitionGroup name="list">
              <div
                v-for="item in filterStreams"
                :key="item.guid ? item.guid : item.time"
              >
                <ClueRecordItem
                  :item="item"
                  @open="handleOpen(item)"
                ></ClueRecordItem>
              </div>
            </TransitionGroup>
            <!-- </div> -->
          </el-scrollbar>
        </template>
      </BaseCard>
    </el-col>
    <PollutedClueItem
      v-model="clueDialog"
      :item="selectedClue"
    ></PollutedClueItem>
  </el-row>
</template>
<script setup>
import { reactive, ref, onMounted, onUnmounted, inject } from 'vue';
import { ws } from '@/api/index';
/**
 * 动态溯源信息管理
 * 通过websocket方式接收后端推送的异常信息并展示
 */
import { reactive, ref, onMounted, onUnmounted, computed, watch } from 'vue';
import moment from 'moment';
const height = `60vh`;
import websocket from '@/api/websocket';
import sector from '@/utils/map/sector';
import mapUtil from '@/utils/map/util';
import { sceneTypes, sceneIcon } from '@/constant/scene-types';
import marks from '@/utils/map/marks';
import { map, onMapMounted } from '@/utils/map/index_old';
import { FactorDatas } from '@/model/FactorDatas';
import factorDataParser from '@/utils/chart/factor-data-parser';
import websocketMsgParser from '@/views/sourcetrace/websocketMsgParser.js';
import PollutedExceptionItem from './component/PollutedExceptionItem.vue';
import ClueRecordItem from './component/ClueRecordItem.vue';
import PollutedClueItem from '@/views/sourcetrace/component/PollutedClueItem.vue';
const props = defineProps({
  factorType: String
});
const emits = defineEmits(['update:factorType']);
const height = `30vh`;
const width = `60vh`;
const show = ref(false);
const clueDialog = ref(false);
const scrollContentRef = ref();
const scrollbarRef = ref();
const selectedException = ref();
const selectedClue = ref();
const selectedMsgTypes = ref(['1', '2']);
function scrollToBottom() {
  const h1 = scrollContentRef.value.clientHeight + 100;
@@ -33,50 +98,364 @@
  }, 100);
}
const streams = reactive([]);
function scrollToTop() {
  setTimeout(() => {
    scrollbarRef.value.setScrollTop(0);
  }, 100);
}
let socket;
const streams = reactive([]);
const filterStreams = computed(() => {
  return streams.filter((v) => {
    return selectedMsgTypes.value.indexOf(v._type) != -1;
  });
});
const inputVal = ref('');
const handleSend = () => {
  if (socket) {
    socket.send(inputVal.value);
  }
  websocket.send(inputVal.value);
};
const handleLink = () => {
  if (socket) {
    socket.close();
let showFirstClueTask;
function dealMsg(data) {
  const { type, content } = websocketMsgParser.parseMsg(data);
  // 污染线索 PollutedClue
  if (type == '1') {
    const obj = reactive(JSON.parse(content));
    obj._type = type;
    // obj.showMore = true;
    obj.showMore = false;
    console.log('污染异常切片: ', obj);
    // if (streams.length == 0) {
    //   streams.push(obj);
    // } else {
    //   // streams.forEach((s) => {
    //   //   showMarksAndPolygon(s);
    //   // });
    //   // hideAll();
    //   streams.unshift(obj);
    // }
    addNewMsg(obj);
    show.value = true;
    // scrollToBottom();
    // scrollToTop();
    // drawPolygon(obj.pollutedArea);
    parseChartData(obj);
    // if (showFirstClueTask) {
    //   clearTimeout(showFirstClueTask);
    // }
    // showFirstClueTask = setTimeout(() => {
    //   showMarksAndPolygon(obj);
    // }, 1000);
  } else if (type == '2') {
    const obj = JSON.parse(content);
    obj._type = type;
    console.log('污染线索结果: ', obj);
    obj._timestr = timeFormatter(obj.time);
    // streams.unshift(obj);
    addNewMsg(obj);
  }
  const url = 'ws://' + ws + '/ws';
  // socket = new WebSocket(`ws://192.168.0.138:8080/workstream`)
  socket = new WebSocket(url);
  // 与服务器建立连接:发送消息到服务器
  socket.onopen = () => {
    console.log('connect: ');
  };
  // 收到服务器发送的消息:event处理服务器返回的数据
  socket.onmessage = (event) => {
    console.log('receive: ', event.data);
    putWorkStream(event.data);
  };
  // 连接或通信过程中发生错误
  socket.onerror = (event) => {
    console.log('errror: ', event);
  };
  // 与服务器断开连接
  socket.onclose = (event) => {
    console.log('close: ', event.code);
  };
};
}
// 按照一定时间间隔新增一条消息
let addNewMsgTask;
const leftMsgList = [];
function addNewMsg(msg, inside) {
  if (!addNewMsgTask && (leftMsgList.length == 0 || inside)) {
    streams.splice(0, 0, msg);
    addNewMsgTask = setTimeout(() => {
      clearTimeout(addNewMsgTask);
      addNewMsgTask = undefined;
      if (leftMsgList.length > 0) {
        const next = leftMsgList.shift();
        addNewMsg(next, true);
      }
    }, 1000);
  } else {
    leftMsgList.push(msg);
  }
}
onMounted(() => {
  websocket.registerReceiveEvent(dealMsg);
});
onUnmounted(() => {
  websocket.removeReceiveEvent(dealMsg);
  sector.clearSectorPt();
  mapUtil.clearMap();
  // if (layer != undefined) {
  //   mapUtil.removeViews(layer);
  //   layer = undefined;
  // }
});
watch(clueDialog, (nV, oV) => {
  if (nV != oV && !nV) {
    selectedClue.value._selected = false;
  }
});
function handleOpen(item) {
  switch (item._type) {
    case '1':
      if (selectedException.value) {
        selectedException.value._selected = false;
      }
      showMarksAndPolygon(item);
      selectedException.value = item;
      break;
    case '2':
      if (selectedClue.value) {
        selectedClue.value._selected = false;
      }
      selectedClue.value = item;
      clueDialog.value = true;
      break;
  }
  item._selected = true;
}
function hideAll() {
  streams.forEach((s) => {
    if (polygonMap.has(s.guid)) {
      s.showMore = false;
      map.remove(polygonMap.get(s.guid));
    }
  });
}
function showMarksAndPolygon(item) {
  item.showMore = !item.showMore;
  if (item.showMore) {
    hideAll();
    item.showMore = true;
    drawPolygon(item);
  } else {
    if (polygonMap.has(item.guid)) {
      map.remove(polygonMap.get(item.guid));
      selectedException.value._selected = false;
    }
  }
}
// 绘制污染区域(高德地图的多边形对象,通过vue的reactive包装为响应式对象后,无法正确在地图中使用)
const polygonMap = new Map();
function drawPolygon(item) {
  const pollutedArea = item.pollutedArea;
  if (polygonMap.has(item.guid)) {
    map.add(polygonMap.get(item.guid));
  } else {
    const bounds = pollutedArea.polygon.map((v) => [v.first, v.second]);
    // eslint-disable-next-line no-undef
    const pollutedAreaPolygon = new AMap.Polygon({
      map: map, //显示该覆盖物的地图对象
      strokeWeight: 2, //轮廓线宽度
      path: bounds, //多边形轮廓线的节点坐标数组
      fillOpacity: 0, //多边形填充透明度
      fillColor: '#CCF3FF', //多边形填充颜色
      strokeColor: '#02ffea', //线条颜色
      // strokeColor: '#0552f7', //线条颜色
      strokeStyle: 'dashed',
      zIndex: 9
    });
    polygonMap.set(item.guid, pollutedAreaPolygon);
  }
  // map.setFitView(polygonMap.get(item.guid));
}
function parseChartData(obj) {
  // console.log('折线图:start');
  const factorDatas = new FactorDatas();
  factorDatas.setData(obj.pollutedData.historyDataList, 0, () => {
    obj._chartOptions = factorDataParser.parseData(factorDatas, [
      {
        label: obj.pollutedData.factorName,
        name: obj.pollutedData.factorName,
        value: obj.pollutedData.factorId + ''
      }
    ]);
    // console.log('折线图:', obj._chartOptions);
  });
}
function timeFormatter(time) {
  return moment(time).format('YYYY-MM-DD HH:mm:ss');
}
/******************************************************************************************************************** */
/**
 * 添加一条工作流信息
 * @param {*} data
 */
function putWorkStream(data) {
const putWorkStream = (data) => {
  data.substring();
  const obj = JSON.parse(data);
  streams.push(obj);
  scrollToBottom();
  console.log('sourcetrace: ', obj);
  obj._statusStr = exceptionStatus(obj.status);
  if (streams.length == 0) {
    streams.push(obj);
  } else {
    const index = streams.findIndex((v) => {
      return v.guid == obj.guid;
    });
    if (index != -1) {
      const old = streams[index];
      obj.showMore = old.showMore;
      old.relatedSceneList.forEach((s) => {
        const index = obj.relatedSceneList.findIndex((v) => {
          return v.guid == s.guid;
        });
        if (index == -1) {
          obj.relatedSceneList.push(s);
        }
      });
      streams.splice(index, 1, obj);
    } else {
      streams.unshift(obj);
    }
    show.value = true;
  }
  // scrollToBottom();
  scrollToTop();
  const excObj = streams.find((v) => {
    return v.factorId + '' == props.factorType;
  });
  if (excObj) {
    drawSector(excObj);
  }
};
function exceptionStatus(value) {
  switch (value) {
    case 1:
      return '异常发生中';
    case 2:
      return '异常已结束';
    default:
      return '异常已结束';
  }
}
let lastDrawObjGuid;
function drawSector(exceptionObj) {
  emits('update:factorType', exceptionObj.factorId + '');
  setTimeout(() => {
    if (exceptionObj.guid != lastDrawObjGuid) {
      sector.clearSectorPt();
      lastDrawObjGuid = exceptionObj.guid;
    }
    // 1. 绘制新扇形区域
    const datavo = exceptionObj.midData;
    const factorDatas = new FactorDatas();
    factorDatas.setData([datavo], 0, () => {
      const pr = sector.drawSectorPt(factorDatas, 0);
      // 调整视角居中显示
      // mapUtil.setCenter(pr.p);
      drawMarks(exceptionObj.relatedSceneList);
    });
  }, 1000);
}
let layer = undefined;
function drawMarks(sceneList) {
  if (layer != undefined) {
    mapUtil.removeViews(layer);
    // layer = undefined;
  }
  if (sceneList.length != 0) {
    const icons = [];
    sceneList.forEach((s) => {
      icons.push(sceneIcon(s.typeId));
    });
    layer = marks.createLabelMarks(icons, sceneList, true);
  }
}
</script>
<style scoped>
:deep(.el-statistic) {
  --el-statistic-title-color: rgb(215, 215, 215);
  --el-statistic-content-color: white;
}
:deep(.el-text.el-text--primary) {
  --el-text-color: white;
}
:deep(.el-link) {
  --el-link-text-color: #23dad1;
}
.el-checkbox {
  --el-checkbox-text-color: white;
  --main-color: #23dad1;
  --el-checkbox-checked-text-color: var(--main-color);
  --el-checkbox-checked-input-border-color: var(--main-color);
  --el-checkbox-checked-bg-color: var(--main-color);
  --el-checkbox-input-border-color-hover: var(--main-color);
  --el-checkbox-disabled-checked-input-fill: var(--main-color);
  --el-checkbox-disabled-checked-input-border-color: var(--main-color);
  --el-checkbox-disabled-checked-icon-color: white;
  margin-right: 6px;
  /* height: initial; */
}
.scrollbar {
  width: 400px;
  /* max-width: 60vw; */
  height: 45vh;
  /* color: #02ffea; */
  padding-right: 10px;
}
.clue-card {
  padding: 0 4px;
  /* margin-right: 2px; */
  width: 340px;
  height: 35vh;
  border-right: 1px solid white;
  border-radius: 2px;
}
.border-dashed {
  /* border: 1px dashed white; */
  border: 1px dashed #ffbc58;
  padding: 0px 1px;
  margin-bottom: 4px;
}
.flex-col {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}
</style>
<style>
.list-move, /* 对移动中的元素应用的过渡 */
.list-enter-active,
.list-leave-active {
  /* transition: all 0.8s cubic-bezier(0.55, 0, 0.1, 1); */
  transition: all 0.5s ease;
}
.list-enter-from,
.list-leave-to {
  opacity: 0;
  transform: scaleY(0.01) translate(300px, 0);
}
/* 确保将离开的元素从布局流中删除
  以便能够正确地计算移动的动画。 */
.list-leave-active {
  position: absolute;
}
</style>