/**
 * Copyright (c) 2020 kedacom
 * OpenATC is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 * http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 **/
<template>
  <div class="crossImg">
    <div v-show="isShowState">
      <div class="stateText">
        <div style="border:0px solid red;float:right;">
          {{stateName }}
        </div>
      </div>
    </div>
    <div v-show="isShowMode">
      <div class="controlText">
        <div style="border:0px solid red;float:right;">
          {{controlName }}
        </div>
      </div>
      <div class="modeText">
        {{modeName }}
      </div>
    </div>
    <!-- 右行道路 B-->
    <div class="right-dir-road" v-if="roadDir === 'right'">
      <div class="centerText" v-if="crossType !== 'Customroads' && isHasPhase">
        <div v-if="isVipRoute" class="merge-direction-icon">
          <xdr-dir-selector
          :Data="xdrMData"
          Width="80px"
          Height="80px"
          Widths="80px"
          Heights="80px"
          :showlist="mergeShowList"></xdr-dir-selector>
        </div>
        <!-- 锁定状态 -->
        <div class="locked-status" v-if="isLoaded && isLockStatus">
          <svg-icon icon-class="locked" className="locked-icon"></svg-icon>
          <span class="locked-text">{{$t('openatccomponents.overview.locked')}}</span>
        </div>
      <!-- 相位倒计时 -->
      <div class="phaseCountdown" v-show="isShowInterval" v-if="isLoaded && isHasPhase && isHasCountdown && contrloType === 'ring'" :class="{'countdownBg': isLoaded}">
        <div v-for="curPhase in phaseCountdownList" :key="curPhase.id" :style="{color: curPhase.phaseCountdownColor}">
          <div v-if="curPhase.phaseCountdown !== undefined && curPhase.phaseCountdown !== -1" style="overflow: hidden;margin-bottom: 4px;">
            <span style="float: left;width: 42px;height: 42px;position: relative;border: 1px solid rgba(255, 255, 255, 0.1);margin-right: 5px;">
              <xdr-dir-selector :Data="xdrData" :Datas="xdrpedData" Width="55px" Height="55px" Widths="55px" Heights="55px" :showlist="curPhase.showlist" :roadDirection="roadDirection"></xdr-dir-selector>
            </span>
            <span style="float: left;color: #fff;margin-right: 8px;width: 30px;">P{{curPhase.id}}:</span>
            <span style="float: left;font-size: 25px;">{{curPhase.phaseCountdown}}</span>
          </div>
        </div>
      </div>
      <!-- 阶段倒计时 -->
      <div class="phaseCountdown" v-show="isShowInterval" v-if="isLoaded && isHasStageCountdown && contrloType === 'stage'" :class="{'countdownBg': isLoaded}">
          <div style="overflow: hidden;margin-bottom: 4px;" :style="{color: stageCountdownList[0].phaseCountdownColor}">
            <span style="float: left;width: 42px;height: 42px;position: relative;border: 1px solid rgba(255, 255, 255, 0.1);margin-right: 5px;">
              <xdr-dir-selector :Data="xdrData" :Datas="xdrpedData" Width="55px" Height="55px" Widths="55px" Heights="55px" :showlist="dirListSetTheme(stageCountdownList)" :roadDirection="roadDirection"></xdr-dir-selector>
            </span>
            <span style="float: left;color: #fff;margin-right: 8px;width: 30px;">S{{crossStatusData.current_stage}}:</span>
            <span style="float: left;font-size: 25px;">{{crossStatusData.current_stagecd}}</span>
          </div>
      </div>
      <!-- 手动刷新 -->
      <div v-if="!isLoaded">
        <RefreshSvg @click.native="refresh"/>
        <span class="text">{{$t('openatccomponents.overview.getintersectionmapagain')}}</span>
      </div>
    </div>
      <!-- 路口底图 -->
      <div class="baseImg" ref="svgContainer" @click="handleSvgClick">
        <!-- 城市道路 -->
        <CrossRoadsSvg v-if="crossType === 'Crossroads'" :road-names="roadNames" />
        <TShapeEastRoadsSvg v-if="crossType === 'TypeT-east'" :road-names="roadNames"/>
        <TShapeWestRoadsSvg v-if="crossType === 'TypeT-west'" :road-names="roadNames"/>
        <TShapeNorthRoadsSvg v-if="crossType === 'TypeT-north'" :road-names="roadNames"/>
        <TShapeSouthRoadsSvg v-if="crossType === 'TypeT-south'" :road-names="roadNames"/>
        <!-- 其他路口 -->
        <CustomRoadsSvg v-if="crossType === 'Customroads'"/>
        <!-- 匝道 -->
        <RampEastRoadsSvg v-if="crossType === 'ramp-east' && !isVipRoute" />
        <RampWestRoadsSvg v-if="crossType === 'ramp-west' && !isVipRoute" />
        <RampNorthRoadsSvg v-if="crossType === 'ramp-north' && !isVipRoute" />
        <RampSouthRoadsSvg v-if="crossType === 'ramp-south' && !isVipRoute" />
        <!-- 路段行人过街 -->
        <PedSectionSNSvg v-if="crossType === 'ped-section-south-north'" />
        <PedSectionEWSvg v-if="crossType === 'ped-section-east-west'" />
      </div>
      <!-- 城市道路状态-->
      <div v-if="mainType === '100' || mainType === '101' || mainType === '104'">
        <!-- 人行道 -->
        <div class="sidewalk" id="sidewalk" v-if="resetflag && isLoaded">
          <SidewalkClickSvg v-if="isVipRoute && compSidewalkPhaseData.length" :Data="compSidewalkPhaseData" :clickMode="clickMode" @handleClickSidewalkIcon="handleClickSidewalkIcon" />
          <SidewalkSvg v-else v-for="(side, index) in compSidewalkPhaseData" :key="side.key + '-' + index" :Data="side" :crossType="crossType" />
        </div>
        <!-- 车道相位 -->
        <div v-if="resetflag" class="phaseIcon">
          <PhaseIconSvg v-for="(item, index) in compLanePhaseData" :key="item.key + '-' + index" :Data="item" :isVipRoute="isVipRoute" :clickMode="clickMode" :beforeSelect="beforeClickPhaseIcon" @handleClickPhaseIcon="handleClickPhaseIcon" />
        </div>
        <!-- 车道灯 -->
        <div v-if="resetflag" class="roadwayLightIcon">
          <div :key="item.id" v-for="item in compRoadwayLightData" :style="{position: 'absolute', left: item.lightx, top: item.lighty}">
            <svg t="1773302927218" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="22220" width="17.59" height="17.59"><path d="M868.018201 392.930029h-79.379804V252.956975C789.432195 101.34155 665.070503 0 512.13208 0S234.567366 102.664546 234.567366 254.279972v138.650057h-79.379804A68.266631 68.266631 0 0 0 87.450129 460.932062v495.065377a68.266631 68.266631 0 0 0 68.531231 68.002032H868.018201a68.266631 68.266631 0 0 0 68.531231-68.002032V460.932062a68.266631 68.266631 0 0 0-68.531231-68.002033z m-317.519215 328.367789v108.221133a8.996378 8.996378 0 0 1-8.996378 8.996378h-59.005655a8.996378 8.996378 0 0 1-8.996377-8.996378v-108.221133a84.407192 84.407192 0 0 1-46.834085-74.881615 85.465589 85.465589 0 0 1 170.666579 0 83.877993 83.877993 0 0 1-46.834084 74.881615z m132.299673-326.515593H341.200902V243.695998c0-79.379804 76.73381-144.735843 170.931178-144.735842s170.931178 65.091439 170.931178 144.735842z" fill="#fff" p-id="22221"></path></svg>
          </div>
          <PhaseIconSvg v-for="(item, index) in compRoadwayLightData" :key="item.key + '-' + index" :Data="item" :clickMode="false" />
        </div>
         <!-- 公交相位 -->
        <div v-if="resetflag && !isVipRoute" class="busIcon">
          <BusMapSvg v-for="(item, index) in comdireBusPhaseData" :key="'Busmap-' + item.key + '-' + index" :Data="item" />
          <PhaseIconSvg v-for="(item, index) in comdireBusPhaseData" :key="item.key + '-' + index" :Data="item"/>
        </div>
        <!-- 有效方向 -->
        <div  v-if="isVipRoute" class="effectDir">
          <PhaseIconSvg v-for="(item, index) in effectDirData" :key="item.key + '-' + index" :Data="item" />
        </div>
      </div>
      <!-- 匝道状态 -->
        <!-- 车道相位 -->
      <div v-if="resetflag && mainType === '103' && !isVipRoute">
        <RampPhaseIconSvg v-for="(item, index) in LanePhaseData" :key="item.key + '-' + index" :Data="item" />
      </div>
    </div>
    <!-- 右行道路 E-->

    <!-- 左行道路 B-->
    <div class="left-dir-road" v-if="roadDir === 'left'">
      <div class="centerText" v-if="crossType !== 'Customroads' && isHasPhase">
        <!-- 锁定状态 -->
        <div class="locked-status" v-if="isLoaded && isLockStatus">
          <svg-icon icon-class="locked" className="locked-icon"></svg-icon>
          <span class="locked-text">{{$t('openatccomponents.overview.locked')}}</span>
        </div>
        <!-- 相位倒计时 -->
        <div class="phaseCountdown" v-show="isShowInterval" v-if="isLoaded && isHasPhase && isHasCountdown && contrloType === 'ring'" :class="{'countdownBg': isLoaded}">
          <div v-for="curPhase in phaseCountdownList" :key="curPhase.id" :style="{color: curPhase.phaseCountdownColor}">
            <div v-if="curPhase.phaseCountdown !== undefined && curPhase.phaseCountdown !== -1" style="overflow: hidden;margin-bottom: 4px;">
              <span style="float: left;width: 42px;height: 42px;position: relative;border: 1px solid rgba(255, 255, 255, 0.1);margin-right: 5px;">
                <xdr-dir-selector :Data="xdrData" :Datas="xdrpedData" Width="55px" Height="55px" Widths="55px" Heights="55px" :showlist="curPhase.showlist" :roadDirection="roadDirection"></xdr-dir-selector>
              </span>
              <span style="float: left;color: #fff;margin-right: 8px;width: 30px;">P{{curPhase.id}}:</span>
              <span style="float: left;font-size: 25px;">{{curPhase.phaseCountdown}}</span>
              </div>
            </div>
        </div>
        <!-- 阶段倒计时 -->
      <div class="phaseCountdown" v-show="isShowInterval" v-if="isLoaded && isHasStageCountdown && contrloType === 'stage'" :class="{'countdownBg': isLoaded}">
          <div style="overflow: hidden;margin-bottom: 4px;" :style="{color: stageCountdownList[0].phaseCountdownColor}">
            <span style="float: left;width: 42px;height: 42px;position: relative;border: 1px solid rgba(255, 255, 255, 0.1);margin-right: 5px;">
              <xdr-dir-selector :Data="xdrData" :Datas="xdrpedData" Width="55px" Height="55px" Widths="55px" Heights="55px" :showlist="dirListSetTheme(stageCountdownList)" :roadDirection="roadDirection"></xdr-dir-selector>
            </span>
            <span style="float: left;color: #fff;margin-right: 8px;width: 30px;">S{{crossStatusData.current_stage}}:</span>
            <span style="float: left;font-size: 25px;">{{crossStatusData.current_stagecd}}</span>
          </div>
      </div>
        <!-- 手动刷新 -->
        <div v-if="!isLoaded">
          <RefreshSvg @click.native="refresh"/>
          <span class="text">{{$t('openatccomponents.overview.getintersectionmapagain')}}</span>
        </div>
      </div>
      <!-- 路口底图 -->
      <div class="baseImg">
        <!-- 城市道路 -->
        <LCrossRoadsSvg v-if="crossType === 'Crossroads'"/>
        <LTShapeEastRoadsSvg v-if="crossType === 'TypeT-east'"/>
        <LTShapeWestRoadsSvg v-if="crossType === 'TypeT-west'"/>
        <LTShapeNorthRoadsSvg v-if="crossType === 'TypeT-north'"/>
        <LTShapeSouthRoadsSvg v-if="crossType === 'TypeT-south'"/>
        <!-- 其他路口 -->
        <CustomRoadsSvg v-if="mainType !== '100' && mainType !== '101'"/>
      </div>
      <!-- 城市道路状态-->
      <div v-if="mainType === '100' || mainType === '101'">
        <!-- 人行道 -->
        <div class="sidewalk" v-if="resetflag && isLoaded">
          <SidewalkClickSvg v-if="isVipRoute && compSidewalkPhaseData.length" :Data="compSidewalkPhaseData" :clickMode="clickMode" @handleClickSidewalkIcon="handleClickSidewalkIcon" />
          <SidewalkSvg v-else v-for="side in compSidewalkPhaseData" :key="side.key" :Data="side" :crossType="crossType" />
        </div>
        <!-- 车道相位 -->
        <div v-if="resetflag" class="phaseIcon">
          <LPhaseIconSvg v-for="item in compLanePhaseData" :key="item.key" :Data="item" :isVipRoute="isVipRoute" :clickMode="clickMode" :beforeSelect="beforeClickPhaseIcon" @handleClickPhaseIcon="handleClickPhaseIcon"/>
        </div>
         <!-- 公交相位 -->
        <div v-if="resetflag" class="busIcon">
          <BusMapSvg v-for="(item, index) in comdireBusPhaseData" :key="'Busmap-' + item.key + '-' + index" :Data="item" />
          <LPhaseIconSvg v-for="(item, index) in comdireBusPhaseData" :key="item.key + '-' + index" :Data="item"/>
        </div>
      </div>
    </div>
    <!-- 左行道路 E-->
    <!-- 路段名称编辑弹窗 -->
    <RoadNameEditDialog
      :visible.sync="dialogVisible"
      :direction="currentEditDirection"
      :current-name="roadNames[currentEditDirection] || ''"
      @confirm="onRoadNameConfirm"
    />
  </div>
</template>
<script>
import PhaseIconSvg from './phaseIcon/phaseIconSvg'
import PhaseDataModel from './utils.js'
import { getIntersectionInfo } from '../../../../api/template.js'
import { uploadSingleTscParam } from '../../../../api/param.js'
import CrossRoadsSvg from './baseImg/CrossRoadsSvg'
import TShapeEastRoadsSvg from './baseImg/TShapeEastRoadsSvg'
import TShapeWestRoadsSvg from './baseImg/TShapeWestRoadsSvg.vue'
import TShapeNorthRoadsSvg from './baseImg/TShapeNorthRoadsSvg.vue'
import TShapeSouthRoadsSvg from './baseImg/TShapeSouthRoadsSvg.vue'
import CustomRoadsSvg from './baseImg/CustomRoadsSvg.vue'
import RefreshSvg from './baseImg/refreshSvg'
import SidewalkSvg from './baseImg/SidewalkSvg'
import SidewalkClickSvg from './baseImg/SidewalkClickSvg'
import RampEastRoadsSvg from './baseImg/RampEastSvg'
import RampWestRoadsSvg from './baseImg/RampWestSvg'
import RampNorthRoadsSvg from './baseImg/RampNorthSvg'
import RampSouthRoadsSvg from './baseImg/RampSouthSvg'
import RampPhaseIconSvg from './phaseIcon/rampPhaseIconSvg'
import PedSectionEWSvg from './baseImg/PedSectionEWSvg'
import PedSectionSNSvg from './baseImg/PedSectionSNSvg'
// import { mapState } from 'vuex'
import LCrossRoadsSvg from './baseImg/leftroad/LCrossRoadsSvg'
import LTShapeEastRoadsSvg from './baseImg/leftroad/LTShapeEastRoadsSvg'
import LTShapeWestRoadsSvg from './baseImg/leftroad/LTShapeWestRoadsSvg.vue'
import LTShapeNorthRoadsSvg from './baseImg/leftroad/LTShapeNorthRoadsSvg.vue'
import LTShapeSouthRoadsSvg from './baseImg/leftroad/LTShapeSouthRoadsSvg.vue'
import LPhaseIconSvg from './phaseIcon/LphaseIconSvg'
import CrossDiagramMgr from '../../../../EdgeMgr/controller/crossDiagramMgr.js'
import BusMapSvg from './busIcon/busMapSvg'
import { getMessageByCode } from '../../../../utils/responseMessage.js'
// 引入路段名称编辑弹窗组件
import RoadNameEditDialog from './RoadNameEditDialog.vue'

import CrossDirectionConflictList from '../../../../utils/conflictList.js'
import RingDataModel from '../../../../utils/RingDataModel.js'
import { getValidDirections, getMergeDirections } from '../../../../api/cross.js'
import { queryDevice, UpdateDevice } from '../../../../api/control.js'

export default {
  name: 'crossDiagram',
  components: {
    PhaseIconSvg,
    CrossRoadsSvg,
    TShapeEastRoadsSvg,
    TShapeWestRoadsSvg,
    TShapeNorthRoadsSvg,
    TShapeSouthRoadsSvg,
    CustomRoadsSvg,
    RefreshSvg,
    SidewalkSvg,
    RampEastRoadsSvg,
    RampWestRoadsSvg,
    RampNorthRoadsSvg,
    RampSouthRoadsSvg,
    RampPhaseIconSvg,
    PedSectionEWSvg,
    PedSectionSNSvg,
    LCrossRoadsSvg,
    LTShapeEastRoadsSvg,
    LTShapeWestRoadsSvg,
    LTShapeNorthRoadsSvg,
    LTShapeSouthRoadsSvg,
    LPhaseIconSvg,
    BusMapSvg,
    SidewalkClickSvg,
    RoadNameEditDialog
  },
  props: {
    crossStatusData: {
      type: Object
    },
    agentId: {
      type: String
    },
    // devStatus: {
    //   type: Number
    // },
    isShowInterval: {
      type: Boolean,
      devault: true
    },
    isShowMessage: {
      type: Boolean,
      default: true
    },
    roadDirection: {
      type: String
    },
    isShowState: {
      type: Boolean,
      devault: false
    },
    isShowMode: {
      type: Boolean,
      devault: false
    },
    modeName: {
      type: String,
      default: ''
    },
    controlName: {
      type: String,
      default: ''
    },
    stateName: {
      type: String,
      default: ''
    },
    choosedDirection: {
      type: Array,
      default: () => []
    },
    choosedPedDirection: {
      type: Array,
      default: () => []
    },
    isVipRoute: { // 区分普通路口和VIP路口，如果是vip路口（特勤路线和分组管控），才需要获取通道和处理通道冲突，并显示已选方向
      type: Boolean,
      default: false
    },
    clickMode: {
      type: Boolean,
      default: false
    },
    isThirdSignal: {
      type: Boolean,
      default: false
    },
    channelType: {
      type: Boolean,
      default: false
    },
    isRcp: {
      type: Boolean,
      default: false
    }
  },
  // computed: {
  //   ...mapState({
  //     roadDirection: state => state.globalParam.roadDirection
  //   })
  // },
  watch: {
    tempType: {
      handler: function (val) {
        this.getCrossType()
      }
    },
    crossStatusData: {
      handler: function (val, oldVal) {
        // 路口状态数据
        // console.log(val)
        if (!this.channelType || (this.channelType && this.isThirdSignal)) {
          this.compareIsChangedPhase(val, oldVal) // 比较相位状态决定是否更新相位图标（解决虚相位显示问题，虚相位图标不显示）
        }
        this.statusData = JSON.parse(JSON.stringify(val))
        // 默认显示相位数据（包括黄闪、全红、关灯状态下，或者匝道，均不做比对跟随相位的处理）
        this.drawDefaultPhaseIcon()
        if (this.channelType && !this.isThirdSignal) {
          // 通道路口图状态数据（实时通道展示排除第三方信号机，第三方信号机还是按模版路口一样展示相位状态）
          this.channelStatusList = val.channellamp
          this.createChannelStatusMap()
          this.getChannelPhaseStatus()
          this.getChannelPedStatus()
          return
        }
        this.handleTempCrossStatus(val)
      },
      // 深度观察监听
      deep: true
    },
    devStatus: {
      handler: function (val) {
        if (val === 3) return
        this.handleDefaultStatus()
      }
    },
    // roadDirection: {
    //   handler: function (val1, val2) {
    //     if (val1 !== val2) {
    //       this.init()
    //     }
    //   }
    // },
    agentId: {
      handler: function (val1, val2) {
        if (val1 !== val2) {
          this.init()
        }
      },
      immediate: true
    }
  },
  data () {
    return {
      roadDir: 'right', // 道路行车方向，默认右行
      phaseCountdownList: [], // 相位倒计时列表
      stageCountdownList: [], // 阶段倒计时列表
      statusData: null, // 信号机状态
      LanePhaseData: [], // 车道相位数据
      overlapLanePhaseData: [], // 车道跟随相位数据
      curPhase: [], // 当前相位列表
      roadwayLightData: [], // 车道灯数据
      phaseStatusList: [], // 相位状态列表
      phaseStatusMap: new Map(), // 相位状态映射
      overlapPhaseStatusMap: new Map(), // 跟随相位状态映射
      roadwayLightStatusMap: new Map(), // 车道灯状态映射
      ColorMap: new Map([[0, '#828282'], [1, '#ff2828'], [2, '#f7b500'], [3, '#77fb65'], [4, '#77fb65'], [5, '#f7b500'], [6, '#ff2828']]), // 当前相位状态 --- 0：关灯, 1：红, 2：黄,  3：绿, 4：绿闪, 5：黄闪  6：红闪
      SidewalkColorMap: new Map([[0, '#828282'], [1, '#e24b4b'], [3, '#7bd66b']]),
      tempType: '', // 模版类型
      mainType: '101', // 路口形状
      mainDirection: '000', // 路口方向
      crossType: '', // 路口底图类型
      isLoaded: false, // 是否成功加载底图
      isHasPhase: true, // 是否有相位状态数据
      phaseControlColorMap: new Map([['全红', '#ff2828'], ['关灯', '#828282'], ['默认', '#fff'], ['方向锁定', '#fff']]),
      sidewalkPhaseData: [], // 行人相位
      overlapsidewalkPhaseData: [], // 行人跟随相位
      resetflag: true, // 离线后，控制行人相位、车道相位reset标识
      compLanePhaseData: [], // 对比车道相位和车道跟随相位后，显示的数据
      compSidewalkPhaseData: [], // // 对比行人相位和车道跟随相位后，显示的数据
      comdirePhaseData: [], // 对比相同方向车道相位数据后，被删减的唯一direction的数组
      comdireOverlapPhaseData: [], // 对比相同方向车道跟随相位数据后，被删减的唯一direction的数组
      busPhaseData: [], // 公交相位数据
      comdireBusPhaseData: [], //  对比相同方向公交车道数据后，被删减的唯一direction的数组
      compRoadwayLightData: [], // 车道灯状态映射过的车道灯数据
      channelStatusMap: new Map(), // 通道实时状态映射
      channelStatusList: [], // 通道实时状态列表
      phaseDirMap: new Map(),
      xdrData: {
        left: '5px',
        top: '4px'
      },
      xdrpedData: {
        left: '1px',
        top: '1px'
      },
      isHasCountdown: false,
      isHasStageCountdown: false,
      contrloType: 'ring',
      isMphaseStatusDataReturnMap: new Map(), // 每个跟随相位的母相位是否返回了相位状态数据
      overlapStatusCompareSum: 0, // 首次加载跳过比较母相位状态数据是否返回
      effectDirData: [], // 路口有效方向
      mergeShowList: [2, 4, 10],
      xdrMData: {
        left: '18px',
        top: '18px'
      },
      // 路段点击相关数据
      selectedRoad: null, // 当前选中的路段 { direction: 'east', name: '东向路口' }
      roadNames: {
        east: '',
        west: '',
        south: '',
        north: ''
      },
      // 路段名称对话框相关数据
      dialogVisible: false,
      currentEditDirection: '',
      isLockStatus: false // 是否锁定
    }
  },
  methods: {
    compareIsChangedPhase (newCrossStatus, oldCrossStatus) {
      if (!oldCrossStatus || !newCrossStatus) return
      if (!newCrossStatus.phase) return
      if (!oldCrossStatus.phase) return
      if (newCrossStatus.control === 1 || newCrossStatus.control === 2 || newCrossStatus.control === 3) return
    // 返回的相位状态改变后，按照返回的相位状态更新路口相位显示（下个周期生效）
      let newPhaseIds = newCrossStatus.phase.map(item => item.id)
      let oldPhaseIds = oldCrossStatus.phase.map(item => item.id)
      if (!this.isArraysEqual(newPhaseIds, oldPhaseIds)) { // 通过比较相位id是否完全一致
        this.getIntersectionInfo()
      }
    },
    isArraysEqual (arr1, arr2) {
      if (arr1.length !== arr2.length) return false
      for (let i = 0; i < arr1.length; i++) {
          if (arr1[i] !== arr2[i]) return false
      }
      return true
    },
    handleTempCrossStatus (val) {
      // 模版路口图状态数据
      this.isLockStatus = val.control === 4 || val.control === 16 || val.control === 22 // 手动锁定控制时，包含：阶段锁定，相位锁定，通道锁定
      this.phaseStatusList = val.phase
      this.overlapStatusList = val.overlap
      this.laneLampStatusList = val.lanelamp
      if (val.control === 1 || val.control === 2 || val.control === 3) {
        // 黄闪、全红、关灯属于特殊控制，优先级最高，直接改变灯色，不用判断phase里的type，也不需要考虑跟随相位的灯色优先级
        if (val.control === 1) {
          this.getYellowFlashColor()
        } else {
          this.SpecialControl(val)
        }
        this.isHasPhase = false
        // 特殊控制拿不到状态数据，需要重置车道灯map，状态映射车道灯消失
        this.roadwayLightStatusMap = new Map()
        this.getRoadwayLightStatus()
        return
      }
      if (!val.phase && !this.overlapStatusList) {
        // 非特殊控制，相位和跟随相位不存在的情况下，灯色恢复默认
        this.handleSpecialControlStatus('默认')
        this.isHasPhase = false
        return
      }
      if (val.control === 16) {
        // 方向锁定时，相位状态显示与通道无关，显示接口返回的红灯会有歧义，此处特殊处理显示默认白色
        this.handleSpecialControlStatus('方向锁定')
        this.isHasPhase = false
        return
      }
      this.curPhase = val.current_phase
      this.curStage = val.current_stage
      this.isHasPhase = true
      if (val.phase) {
        this.createPhaseStatusMap()
      }
      if (val.overlap) {
        this.createOverlapPhaseStatusMap()
      }
      if (val.lanelamp) {
        this.createRoadwayLightStatusMap()
      }
      // 正常情况下，获取车道相位、车道跟随相位、相位倒计时、行人相位、行人跟随相位 车道灯的状态
      this.getPhaseStatus()
      this.getOverlapPhaseStatus()
      this.getRoadwayLightStatus()
      this.getCurPhaseCountdown()
      this.getCurStageCountdown()
      this.getBusPhaseStatus()
      if (this.mainType === '100' || this.mainType === '101' || this.mainType === '104') {
        // 城市道路和路段行人过街才显示人行道状态
        this.getpedStatus()
        this.getOverlapPedStatus()
        // 算法对比行人相位与行人跟随相位的状态
        this.comparePedStatus()
        // 算法对比车道相位与车道跟随相位的状态
        this.comparePhaseStatus()
      }
      // console.log('this.phaseStatusMap 相位状态映射', this.phaseStatusMap)
      // console.log('LanePhaseData 车道相位', this.LanePhaseData)
      // console.log('sidewalkPhaseData 行人相位', this.sidewalkPhaseData)
      // console.log('overlapPhaseStatusMap 跟随相位状态映射', this.overlapPhaseStatusMap)
      // console.log('overlapLanePhaseData 车道跟随相位', this.overlapLanePhaseData)
      // console.log('this.overlapsidewalkPhaseData 行人跟随相位', this.overlapsidewalkPhaseData)
    },
    init () {
      this.CrossDiagramMgr = new CrossDiagramMgr()
      this.getRoadDirection()
      this.PhaseDataModel = new PhaseDataModel(this.roadDirection)
      this.getIntersectionInfo() // 获取路口信息
      this.queryDevParams() // 获取路口数据
    },
    drawDefaultPhaseIcon () {
      this.compLanePhaseData = JSON.parse(JSON.stringify(this.CrossDiagramMgr.compare(this.LanePhaseData, this.overlapLanePhaseData, 'type', 'nostatus')))
      this.compSidewalkPhaseData = JSON.parse(JSON.stringify(this.CrossDiagramMgr.compare(this.sidewalkPhaseData, this.overlapsidewalkPhaseData, 'pedtype', 'nostatus')))
      this.comdireBusPhaseData = JSON.parse(JSON.stringify(this.busPhaseData))
      console.log(this.LanePhaseData)
      console.log(this.overlapLanePhaseData)
      console.log('###################', this.compLanePhaseData)
    },
    comparePhaseStatus () {
      // 对比车道： 跟随相位和相位的状态数据（此处判断是为了保证被比较的数据direction都是唯一的）
      if (!this.comdirePhaseData && !this.comdireOverlapPhaseData) {
        this.compLanePhaseData = this.CrossDiagramMgr.compare(this.LanePhaseData, this.overlapLanePhaseData, 'type')
      } else if (!this.comdireOverlapPhaseData) {
        this.compLanePhaseData = this.CrossDiagramMgr.compare(this.comdirePhaseData, this.overlapLanePhaseData, 'type')
      } else if (!this.comdirePhaseData) {
        this.compLanePhaseData = this.CrossDiagramMgr.compare(this.LanePhaseData, this.comdireOverlapPhaseData, 'type')
      } else {
        this.compLanePhaseData = this.CrossDiagramMgr.compare(this.comdirePhaseData, this.comdireOverlapPhaseData, 'type')
      }
      // 车道灯灯态优先级最高，有车道灯状态就不展示相位状态
      const roadwayLightIds = Array.from(new Set(this.roadwayLightData.map(item => item.id)))
      this.compLanePhaseData = this.compLanePhaseData.filter(phase => roadwayLightIds.indexOf(phase.id) === -1)
    },
    comparePedStatus () {
      // 对比人行道： 跟随相位和相位的状态数据
      this.compSidewalkPhaseData = this.CrossDiagramMgr.compare(this.sidewalkPhaseData, this.overlapsidewalkPhaseData, 'pedtype')
    },
    resetPhaseStatus () {
      // 车道相位、行人相位恢复默认状态
      this.resetflag = false
      this.$nextTick(() => {
        this.resetflag = true
      })
    },
    SpecialControl (data) {
      switch (data.control) {
        case 2: this.handleSpecialControlStatus('全红')
          break
        case 3: this.handleSpecialControlStatus('关灯')
          break
        default: this.handleSpecialControlStatus('默认')
      }
    },
    handleDefaultStatus () {
      // 恢复默认状态
      if (this.compLanePhaseData.length) {
        this.phaseCountdown = ''
        this.phaseCountdownColor = '#fff'
        this.compLanePhaseData.forEach(data => {
          data.color = '#fff'
        })
      }
      if (this.compSidewalkPhaseData.length) {
        this.compSidewalkPhaseData.forEach(data => {
          data.color = '#fff'
        })
      }
      if (this.comdireBusPhaseData.length) {
        this.comdireBusPhaseData.forEach(data => {
          data.color = '#fff'
        })
      }
      this.phaseCountdownList = []
      this.stageCountdownList = []
      this.resetPhaseStatus()
    },
    handleSpecialControlStatus (Control) {
      this.resetPhaseStatus()
      // 控制黄闪、全红、关灯、默认情况下的车道相位颜色和倒计时颜色
      if (Control === '默认') {
        // 倒计时恢复默认颜色
        this.phaseCountdownList.forEach(item => {
          item.phaseCountdown = ''
          item.id = ''
          item.phaseCountdownColor = '#fff'
        })
      }
      if (this.compLanePhaseData.length) {
        const compLanePhaseData = this.compLanePhaseData.map(data => ({
          ...data,
          color: this.phaseControlColorMap.get(Control)
        }))
        this.compLanePhaseData = JSON.parse(JSON.stringify(compLanePhaseData))
      }
      if (this.compSidewalkPhaseData.length) {
        const compSidewalkPhaseData = this.compSidewalkPhaseData.map(data => ({
          ...data,
          color: this.phaseControlColorMap.get(Control)
        }))
        this.compSidewalkPhaseData = JSON.parse(JSON.stringify(compSidewalkPhaseData))
      }
      if (this.comdireBusPhaseData.length) {
        const comdireBusPhaseData = this.comdireBusPhaseData.map(data => ({
          ...data,
          color: this.phaseControlColorMap.get(Control)
        }))
        this.comdireBusPhaseData = JSON.parse(JSON.stringify(comdireBusPhaseData))
      }
      if (this.mainType === '103') {
        if (this.LanePhaseData.length) {
          const LanePhaseData = this.LanePhaseData.map(data => ({
            ...data,
            color: this.phaseControlColorMap.get(Control)
          }))
          this.LanePhaseData = JSON.parse(JSON.stringify(LanePhaseData))
        }
      }
    },
    createPhaseStatusMap () {
      // 生成相位id和相位状态对应数据结构
      this.phaseStatusMap = new Map()
      this.phaseStatusList.map(phase => {
        let phaseId = phase.id
        let phaseInfo = {
          type: phase.type,
          phaseCountdown: phase.countdown,
          pedtype: phase.pedtype
        }
        this.phaseStatusMap.set(phaseId, phaseInfo)
      })
    },
    getYellowFlashColor () {
      // 车道相位（左行右行）
      let curLanePhaseData = []
      for (let i = 0; i < this.compLanePhaseData.length; i++) {
        const data = {
          ...this.compLanePhaseData[i],
          type: '黄闪',
          control: 1
        }
        curLanePhaseData.push(data)
      }
      this.compLanePhaseData = JSON.parse(JSON.stringify(curLanePhaseData))

      // 行人相位
      let curPedStatus = []
      for (let i = 0; i < this.compSidewalkPhaseData.length; i++) {
        const data = {
          ...this.compSidewalkPhaseData[i],
          pedtype: '黄闪',
          control: 1
        }
        curPedStatus.push(data)
      }
      this.compSidewalkPhaseData = JSON.parse(JSON.stringify(curPedStatus))

      // 公交相位
      let curBusLanePhaseData = []
      for (let i = 0; i < this.comdireBusPhaseData.length; i++) {
        const data = {
          ...this.comdireBusPhaseData[i],
          type: '黄闪',
          control: 1
        }
        curBusLanePhaseData.push(data)
      }
      this.comdireBusPhaseData = JSON.parse(JSON.stringify(curBusLanePhaseData))

      if (this.mainType === '103') {
        // 匝道相位
        if (this.LanePhaseData.length) {
          const LanePhaseData = this.LanePhaseData.map(data => ({
            ...data,
            type: '黄闪',
            control: 1
          }))
          this.LanePhaseData = JSON.parse(JSON.stringify(LanePhaseData))
        }
      }
    },
    getPhaseStatus () {
      // 得到车道相位状态（颜色）
      this.comdirePhaseData = []
      let curLanePhaseData = []
      for (let i = 0; i < this.LanePhaseData.length; i++) {
        let curPhaseStatus = this.phaseStatusMap.get(this.LanePhaseData[i].phaseid)
        if (!curPhaseStatus) continue
        const data = {
          ...this.LanePhaseData[i],
          type: curPhaseStatus.type,
          color: this.ColorMap.get(curPhaseStatus.type),
          phaseCountdown: curPhaseStatus.phaseCountdown,
          flag: 'phase' // 车道相位数据标识
        }
        curLanePhaseData.push(data)
      }
      this.LanePhaseData = JSON.parse(JSON.stringify(curLanePhaseData))
      // 处理相位数据中，方向direction重复的情况：相同direction下，按照状态的优先级显示该方向的灯色：绿灯(3) > 绿闪(4) > 黄灯(2) > 红灯(1)
      // 如果有相同direction，处理后会改变原数组长度，导致第二次无法正确比较状态，因此需要中间变量存储
      this.comdirePhaseData = JSON.parse(JSON.stringify(this.CrossDiagramMgr.compareRepeatDirection(this.LanePhaseData, 'type', 'phase')))
    },
    createOverlapPhaseStatusMap () {
      // 处理跟随相位的母相位设置为忽略相位后的情况（如果跟随相位的母相位包含忽略相位，过滤掉跟随相位的状态数据，参照相位状态数据处理）
      let isMphaseStatusDataReturn = false
      let reset = false
      this.overlapStatusList = this.overlapStatusList.filter(ele => {
        let phaseids = this.phaseStatusList.map(item => item.id)
        let mphase = ele.mphase
        console.log(phaseids)
        console.log(mphase)
        const phaseidsSet = new Set(phaseids)
        isMphaseStatusDataReturn = mphase.every(value => phaseidsSet.has(value))
        console.log(`跟随相位${ele.id}的母相位状态数据是否均返回?`, isMphaseStatusDataReturn)
        if (isMphaseStatusDataReturn !== this.isMphaseStatusDataReturnMap.get(ele.id) && !reset && this.overlapStatusCompareSum > 0) {
          this.getIntersectionInfo()
          reset = true
        }
        this.isMphaseStatusDataReturnMap = this.isMphaseStatusDataReturnMap.set(ele.id, isMphaseStatusDataReturn)
        return isMphaseStatusDataReturn
      })
      this.overlapStatusCompareSum = this.overlapStatusCompareSum + 1
      // 得到跟随相位状态Map数据
      this.overlapPhaseStatusMap = new Map()
      this.overlapStatusList.map(phase => {
        let phaseId = phase.id
        let phaseInfo = {
          type: phase.type,
          phaseCountdown: phase.countdown,
          pedtype: phase.pedtype
        }
        this.overlapPhaseStatusMap.set(phaseId, phaseInfo)
      })
    },
    getOverlapPhaseStatus () {
      // 得到车道跟随相位状态（颜色）
      this.comdireOverlapPhaseData = []
      let curLanePhaseData = []
      for (let i = 0; i < this.overlapLanePhaseData.length; i++) {
        let curPhaseStatus = this.overlapPhaseStatusMap.get(this.overlapLanePhaseData[i].phaseid)
        if (!curPhaseStatus) continue
        const data = {
          ...this.overlapLanePhaseData[i],
          type: curPhaseStatus.type,
          color: this.ColorMap.get(curPhaseStatus.type),
          phaseCountdown: curPhaseStatus.phaseCountdown,
          flag: 'overlapphase' // 车道跟随相位数据标识
        }
        curLanePhaseData.push(data)
      }
      this.overlapLanePhaseData = JSON.parse(JSON.stringify(curLanePhaseData))
      // 处理跟随相位数据中，方向direction重复的情况：相同direction下，按照状态的优先级显示该方向的灯色：绿灯(3) > 绿闪(4) > 黄灯(2) > 红灯(1)
      // 如果有相同direction，处理后会改变原数组长度，导致第二次无法正确比较状态，因此需要中间变量存储
      this.comdireOverlapPhaseData = JSON.parse(JSON.stringify(this.CrossDiagramMgr.compareRepeatDirection(this.overlapLanePhaseData, 'type', 'overlapphase')))
    },
    createRoadwayLightStatusMap () {
      this.roadwayLightStatusMap = new Map()
      this.laneLampStatusList.map(channel => {
        let channelId = channel.id
        let info = {
          type: channel.type
        }
        this.roadwayLightStatusMap.set(channelId, info)
      })
    },
    getRoadwayLightStatus () {
      // 得到车道灯状态（颜色）
      let curData = []
      for (let i = 0; i < this.roadwayLightData.length; i++) {
        let curPhaseStatus = this.roadwayLightStatusMap.get(this.roadwayLightData[i].channelid)
        if (!curPhaseStatus) continue
        const data = {
          ...this.roadwayLightData[i],
          type: curPhaseStatus.type,
          color: this.ColorMap.get(curPhaseStatus.type),
          flag: 'roadwaLight' // 车道灯数据标识
        }
        curData.push(data)
      }
      this.compRoadwayLightData = JSON.parse(JSON.stringify(curData))
    },
    getBusPhaseStatus () {
      // 得到公交车道相位状态（颜色）
      this.comdireBusPhaseData = []
      let curLanePhaseData = []
      for (let i = 0; i < this.busPhaseData.length; i++) {
        let curPhaseStatus = this.phaseStatusMap.get(this.busPhaseData[i].phaseid)
        if (!curPhaseStatus) continue
        const data = {
          ...this.busPhaseData[i],
          type: curPhaseStatus.type,
          color: this.ColorMap.get(curPhaseStatus.type),
          phaseCountdown: curPhaseStatus.phaseCountdown,
          flag: 'busphase' // 车道相位数据标识
        }
        curLanePhaseData.push(data)
      }
      this.busPhaseData = JSON.parse(JSON.stringify(curLanePhaseData))
      // 处理相位数据中，方向direction重复的情况：相同direction下，按照状态的优先级显示该方向的灯色：绿灯(3) > 绿闪(4) > 黄灯(2) > 红灯(1)
      // 如果有相同direction，处理后会改变原数组长度，导致第二次无法正确比较状态，因此需要中间变量存储
      this.comdireBusPhaseData = JSON.parse(JSON.stringify(this.CrossDiagramMgr.compareRepeatDirection(this.busPhaseData, 'type', 'busphase')))
    },
    getCurPhaseCountdown () {
      // 获取当前相位倒计时颜色
      this.phaseCountdownList = []
      this.isHasCountdown = false
      this.curPhase.forEach(curP => {
        this.phaseStatusList.forEach(phaseInfo => {
          if (phaseInfo.id === curP) {
            let countdownObj = {}
            countdownObj.id = phaseInfo.id
            countdownObj.phaseCountdown = phaseInfo.countdown
            countdownObj.phaseCountdownColor = this.ColorMap.get(phaseInfo.type)
            let curphasedir = this.phaseDirMap.get(phaseInfo.id)
            if (curphasedir !== undefined) {
              if (curphasedir.direction && curphasedir.direction.length > 0) {
                countdownObj.showlist = curphasedir.direction.map(dir => {
                return {
                  id: dir,
                  peddirection: this.getshowped(curphasedir.peddirection),
                  color: '#fff'
                }
              })
              } else {
                countdownObj.showlist = [
                  {
                  id: '',
                  peddirection: this.getshowped(curphasedir.peddirection),
                  color: '#fff'
                  }
                ]
              }
            } else {
              countdownObj.showlist = []
            }

            this.phaseCountdownList.push(countdownObj)
            if (phaseInfo.countdown !== undefined && phaseInfo.countdown !== -1) {
              this.isHasCountdown = true
            }
          }
        })
      })
    },
    stagesList () {
      let list = []
      this.isHasStageCountdown = false
      if (this.crossStatusData && this.crossStatusData.stages && this.crossInfo && this.crossInfo.phaseList && this.crossInfo.phaseList.length > 0) {
        this.isHasStageCountdown = true
        let ringDataModel = new RingDataModel(this.crossStatusData, this.crossInfo.phaseList)
        list = ringDataModel.getStageData()
        if (this.isShowCurrentStage) {
          this.currentStage = this.crossStatusData.current_stage
        }
      }
      return list
    },
    dirListSetTheme (list) {
      let dirArr = []
      for (let rec of list) {
        let recd = {
          ...rec,
          color: '#fff'
        }
        dirArr.push(recd)
        for (let i = 0; i < rec.peddirection.length; i++) {
          rec.peddirection[i].color = 'rgba(255, 255, 255, 0.6)'
        }
      }
      return dirArr
    },
    getCurStageCountdown () {
      // 获取当前相位倒计时颜色
      this.stageCountdownList = []
      let stagesList = this.stagesList()
      this.stageCountdownList = stagesList[this.curStage - 1]
      if (!this.stageCountdownList) return
      this.stageCountdownList = this.stageCountdownList.map(phaseInfo => {
        return {
          ...phaseInfo,
          phaseCountdownColor: this.ColorMap.get(phaseInfo.type)
        }
      })
      // console.log(this.stageCountdownList)
    },
    getshowped (peddirection) {
      let peddirarr = []
      if (peddirection) {
        peddirection.map(peddir => ({
          id: peddir,
          name: this.PhaseDataModel.getSidePos(peddir).name,
          color: 'rgba(255, 255, 255, 0.4)'
        }))
      }
      return peddirarr
    },
    getIntersectionInfo () {
      // 获取路口信息
      this.contrloType = 'ring'
      const agentid = this.agentId
      getIntersectionInfo(agentid).then(res => {
        if (!res.data.success) {
          this.isLoaded = false
          let commomMsg = this.$t('openatccomponents.overview.signalID') + ' : ' + agentid
          let msg = getMessageByCode(res.data.code, this.$i18n.locale)
          if (res.data.data) {
            // 子类型错误
            let childErrorCode = res.data.data.errorCode
            if (childErrorCode) {
              let childerror = getMessageByCode(res.data.data.errorCode, this.$i18n.locale)
              msg = msg + ' - ' + childerror
            }
          }
          msg = msg + ' - ' + commomMsg
          // this.isShowMessage && this.$message.error(msg)
          if (this.isShowMessage) {
            console.log(msg)
          }
          return
        }
        this.isLoaded = true
        this.InfoRes = res
        this.handleInfo(res)
      })
    },
    refreshArrow () {
      // 刷新所选方向箭头，不重新请求接口
      this.handleInfo(this.InfoRes)
    },
    handleInfo (res) {
      this.tempType = res.data.data.type
        // 获取车道相位、行人相位信息（坐标、名称）
        this.mainType = this.tempType.split('-')[0]
        this.mainDirection = this.tempType.split('-')[1]
        if (this.isVipRoute) {
          this.getValidDirections()
          this.getMergeDirections()
        }
        if (this.isVipRoute && !this.isThirdSignal && !this.isRcp) {
          // 特勤、分组管控下，非第三方设备且不是rcp协议，按通道显示相位方向；第三方设备和rcp协议还是按路口相位配置显示相位方向
          this.getChannelInfo()
          return
        }
        if (this.channelType && !this.isThirdSignal) {
          this.getChannelInfo()
          return
        }
        let CrossInfo = res
        if (this.isRcp) {
          // rcp协议数据格式不一样，需要转换成原路口信息数据结构
          CrossInfo = this.transRcpPhaseData(res)
        }
        this.getTempCrossInfo(CrossInfo)
        if (!this.isRcp) {
          // 显示阶段的判断条件
          this.allPatternList = res.data.data.param.patternList
          if (this.allPatternList[0].rings === undefined || this.allPatternList[0].rings.length === 0) {
            this.contrloType = 'stage'
          } else if (this.allPatternList[0].contrloType === 'stage') {
            this.contrloType = 'stage'
          } else {
            this.contrloType = 'ring'
          }
        }
    },
    getTempCrossInfo (res) {
      this.crossInfo = res.data.data.param
      this.crossInfo.phaseList.forEach(cross => this.phaseDirMap.set(cross.id, {direction: cross.direction, peddirection: cross.peddirection}))
      if (this.mainType === '100' || this.mainType === '101' || this.mainType === '104') {
        // 城市道路加载车道相位坐标和人行道坐标
        this.getPhasePos()
        this.getOverlapPhasePos()
        this.getPedPhasePos()
        this.getOverlapPedPhasePos()
        this.getRoadwayLightPos()
        if (!this.isVipRoute) {
          this.getBusPos()
        }
      }
      if (!this.isVipRoute && this.mainType === '103') {
        // 获取匝道道路的主路和支路的相位坐标
        this.getRampPhasePos()
      }
      if (!this.isVipRoute) {
        this.drawDefaultPhaseIcon()
      }
      if ((this.isVipRoute && this.isThirdSignal) || (this.isVipRoute && this.isRcp)) {
        this.LanePhaseData = this.CrossDiagramMgr.compare(this.LanePhaseData, this.overlapLanePhaseData, 'type', 'nostatus')
        // console.log(this.LanePhaseData)
        this.sidewalkPhaseData = this.CrossDiagramMgr.compare(this.sidewalkPhaseData, this.overlapsidewalkPhaseData, 'pedtype', 'nostatus')
        let allDir = this.LanePhaseData.map(ele => ele.id)
        let allPedDir = this.sidewalkPhaseData.map(ele => ele.id)
        this.inneChoosedDirection = this.choosedDirection.filter(dir => allDir.indexOf(dir) !== -1)
        this.inneChoosedPedDirection = this.choosedPedDirection.filter(dir => allPedDir.indexOf(dir) !== -1)
        this.drawPhaseIcon()
      }
    },
    transRcpPhaseData (rcpCrossInfo) {
      const phaseConfigs = rcpCrossInfo.data.data.param.Phase.PhaseConfig
      const phaseList = phaseConfigs.map(phase => {
          return {
              id: phase.Index,
              direction: phase.direction || [],
              peddirection: phase.peddirection || []
          }
      })
      // 返回转换后的数据结构
      const CrossInfo = {
        data: {
          data: {
            type: rcpCrossInfo.data.data.type,
            param: {
                phaseList: phaseList
            }
          }
        }
      }
      return CrossInfo
    },
    getBusPos () {
      // 公交相位信息
      this.busPhaseData = []
      this.crossInfo.phaseList.forEach((ele, i) => {
        if (ele.controltype >= 3 && ele.controltype <= 6) {
          if (ele.direction) {
            ele.direction.forEach((dir, index) => {
            // 车道相位
              this.busPhaseData.push({
                key: this.CrossDiagramMgr.getUniqueKey('busphase'),
                phaseid: ele.id, // 相位id，用于对应相位状态
                id: dir, // 接口返回的dir字段，对应前端定义的相位方向id，唯一标识
                name: this.PhaseDataModel.getBusPhasePos(dir).name,
                left: this.PhaseDataModel.getBusPhasePos(dir).x,
                top: this.PhaseDataModel.getBusPhasePos(dir).y,
                busleft: this.PhaseDataModel.getBusMapPos(dir).x,
                bustop: this.PhaseDataModel.getBusMapPos(dir).y,
                controltype: ele.controltype
              })
            })
          }
        }
      })
      // 去掉重复方向的数据
      this.busPhaseData = Array.from(new Set(this.busPhaseData.map(item => item.id)))
        .map(id => this.busPhaseData.find(item => item.id === id))
    },
    createRandomType () {
      for (var i = 3; i <= 5; i++) {
        return Math.floor(Math.random() * (5 - 3)) + 3
      }
    },
    getPhasePos () {
      // 车道相位信息
      this.LanePhaseData = []
      this.crossInfo.phaseList.forEach((ele, i) => {
        if (ele.controltype === undefined || ele.controltype <= 2) {
          if (ele.direction) {
            ele.direction.forEach((dir, index) => {
            // 车道相位
              this.LanePhaseData.push({
                key: this.CrossDiagramMgr.getUniqueKey('phase'),
                phaseid: ele.id, // 相位id，用于对应相位状态
                id: dir, // 接口返回的dir字段，对应前端定义的相位方向id，唯一标识
                name: this.PhaseDataModel.getPhase(dir).name,
                left: this.PhaseDataModel.getPhase(dir).x,
                top: this.PhaseDataModel.getPhase(dir).y
              })
            })
          }
        }
      })
      // 特勤配置点击模式下，去掉重复方向的数据；实时状态展示保留所有相位-方向的完整映射关系，由相位状态匹配决定显示
      if (this.clickMode) {
        this.LanePhaseData = Array.from(new Set(this.LanePhaseData.map(item => item.id)))
        .map(id => this.LanePhaseData.find(item => item.id === id))
      }
    },
    getOverlapPhasePos () {
      // 车道跟随相位信息
      if (!this.crossInfo.overlaplList) return
      this.overlapLanePhaseData = []
      this.crossInfo.overlaplList.forEach((ele, i) => {
        if (ele.direction) {
          ele.direction.forEach((dir, index) => {
            this.overlapLanePhaseData.push({
              key: this.CrossDiagramMgr.getUniqueKey('overlapphase'),
              phaseid: ele.id, // 相位id，用于对应相位状态
              id: dir, // 接口返回的dir字段，对应前端定义的相位方向id，唯一标识
              name: this.PhaseDataModel.getPhase(dir).name,
              left: this.PhaseDataModel.getPhase(dir).x,
              top: this.PhaseDataModel.getPhase(dir).y
            })
          })
        }
      })
      // 特勤配置点击模式下，去掉重复方向的数据；实时状态展示保留所有相位-方向的完整映射关系，由相位状态匹配决定显示
      if (this.clickMode) {
        this.overlapLanePhaseData = Array.from(new Set(this.overlapLanePhaseData.map(item => item.id)))
        .map(id => this.overlapLanePhaseData.find(item => item.id === id))
      }
    },
    getRampPhasePos () {
      // 匝道车道相位信息
      this.LanePhaseData = []
      this.crossInfo.phaseList.forEach((ele, i) => {
        if (ele.direction) {
          ele.direction.forEach((dir, index) => {
            if (ele.controltype === 0) {
              this.handleRampPhasePosData(`${i}-${index}`, ele, dir, this.PhaseDataModel.getMainPhasePos)
            }
            if (ele.controltype === 1) {
              this.handleRampPhasePosData(`${i}-${index}`, ele, dir, this.PhaseDataModel.getSidePhasePos)
            }
          })
        }
      })
      // 特勤配置点击模式下，去掉重复方向的数据；实时状态展示保留所有相位-方向的完整映射关系，由相位状态匹配决定显示
      if (this.clickMode) {
        this.LanePhaseData = Array.from(new Set(this.LanePhaseData.map(item => item.id)))
        .map(id => this.LanePhaseData.find(item => item.id === id))
      }
    },
    handleRampPhasePosData (key, phase, dir) {
      let posInfo = phase.controltype === 0 ? this.PhaseDataModel.getMainPhasePos(dir) : this.PhaseDataModel.getSidePhasePos(dir)
      this.LanePhaseData.push({
        key,
        controlType: phase.controltype,
        phaseid: phase.id, // 相位id，用于对应相位状态
        id: dir, // 接口返回的dir字段，对应前端定义的相位方向id，唯一标识
        name: posInfo.name,
        left: posInfo.x,
        top: posInfo.y
      })
    },
    getPedPhasePos () {
      // 行人相位信息
      this.sidewalkPhaseData = []
      this.crossInfo.phaseList.forEach((ele, i) => {
        if (ele.peddirection) {
          ele.peddirection.forEach((dir, index) => {
          // 行人相位
            if (this.PhaseDataModel.getSidePos(dir)) {
              let key = this.CrossDiagramMgr.getUniqueKey('pedphase')
              if (this.isVipRoute && this.isThirdSignal) {
                key = this.CrossDiagramMgr.getUniqueKey('pedphase') + `-${this.agentId}`
              }
              this.sidewalkPhaseData.push({
                key,
                phaseid: ele.id, // 相位id，用于对应相位状态
                id: dir,
                name: this.PhaseDataModel.getSidePos(dir).name,
                left: this.PhaseDataModel.getSidePos(dir).x,
                top: this.PhaseDataModel.getSidePos(dir).y
              })
            }
          })
        }
      })
      // 特勤配置点击模式下，去掉重复方向的数据；实时状态展示保留所有相位-方向的完整映射关系，由相位状态匹配决定显示
      if (this.clickMode) {
        this.sidewalkPhaseData = Array.from(new Set(this.sidewalkPhaseData.map(item => item.id)))
        .map(id => this.sidewalkPhaseData.find(item => item.id === id))
      }
    },
    getOverlapPedPhasePos () {
      // 行人跟随相位信息
      if (!this.crossInfo.overlaplList) return
      this.overlapsidewalkPhaseData = []
      this.crossInfo.overlaplList.forEach((ele, i) => {
        if (ele.peddirection) {
          ele.peddirection.forEach((dir, index) => {
            if (this.PhaseDataModel.getSidePos(dir)) {
              this.overlapsidewalkPhaseData.push({
                key: this.CrossDiagramMgr.getUniqueKey('overlappedphase'),
                phaseid: ele.id, // 相位id，用于对应相位状态
                id: dir,
                name: this.PhaseDataModel.getSidePos(dir).name,
                left: this.PhaseDataModel.getSidePos(dir).x,
                top: this.PhaseDataModel.getSidePos(dir).y
              })
            }
          })
        }
      })
      // 特勤配置点击模式下，去掉重复方向的数据；实时状态展示保留所有相位-方向的完整映射关系，由相位状态匹配决定显示
      if (this.clickMode) {
        this.overlapsidewalkPhaseData = Array.from(new Set(this.overlapsidewalkPhaseData.map(item => item.id)))
        .map(id => this.overlapsidewalkPhaseData.find(item => item.id === id))
      }
    },
    getRoadwayLightPos () {
      // 车道跟随相位信息
      if (!this.crossInfo.channelList) return
      this.roadwayLightData = []
      this.crossInfo.channelList.forEach((ele, i) => {
        if (ele.controltype === 6 && ele.realdir) {
          ele.realdir.forEach((dir, index) => {
            this.roadwayLightData.push({
              key: this.CrossDiagramMgr.getUniqueKey('roadwayLight'),
              channelid: ele.id, // 通道id，用于对应通道状态
              id: dir, // 接口返回的dir字段，对应前端定义的相位方向id，唯一标识
              name: this.PhaseDataModel.getPhase(dir).name,
              left: this.PhaseDataModel.getPhase(dir).x,
              top: this.PhaseDataModel.getPhase(dir).y,
              lightx: this.PhaseDataModel.getPhase(dir).lightx,
              lighty: this.PhaseDataModel.getPhase(dir).lighty
            })
          })
        }
      })
      // 去掉重复方向的数据
      const ids = Array.from(new Set(this.roadwayLightData.map(item => item.id)))
      this.compRoadwayLightData = ids.map(id => this.roadwayLightData.find(item => item.id === id))
    },
    getEffectDirectionPos () {
      this.effectDirData = []
      // this.effectiveDirection = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
      this.effectiveDirection.forEach((dir, i) => {
        this.effectDirData.push({
          key: this.CrossDiagramMgr.getUniqueKey('effectiveDir'),
          id: dir,
          name: this.PhaseDataModel.getEffectPos(dir).name,
          left: this.PhaseDataModel.getEffectPos(dir).x,
          top: this.PhaseDataModel.getEffectPos(dir).y,
          color: '#6e737c'
        })
      })
    },
    getCrossType () {
      // 路口类型对应底图决策
      if (this.mainType === '101') {
        // 十字路口
        this.crossType = 'Crossroads'
      }
      if (this.mainType === '100') {
        // T型路口
        switch (this.mainDirection) {
          case '001': this.crossType = 'TypeT-east'
            break
          case '002': this.crossType = 'TypeT-south'
            break
          case '003': this.crossType = 'TypeT-west'
            break
          case '004': this.crossType = 'TypeT-north'
            break
        }
      }
      if (this.mainType === '103') {
        // 匝道
        switch (this.mainDirection) {
          case '001': this.crossType = 'ramp-east'
            break
          case '002': this.crossType = 'ramp-south'
            break
          case '003': this.crossType = 'ramp-west'
            break
          case '004': this.crossType = 'ramp-north'
            break
        }
      }
      if (this.mainType === '104') {
        // 路段行人过街
        switch (this.mainDirection) {
          case '005': this.crossType = 'ped-section-east-west'
            break
          case '006': this.crossType = 'ped-section-south-north'
            break
        }
      }
      if (this.mainType === '999') {
        // 其他路口
        this.crossType = 'Customroads'
      }
    },
    refresh () {
      this.getIntersectionInfo()
    },
    getpedStatus () {
      // 行人相位状态
      let curPedStatus = []
      for (let i = 0; i < this.sidewalkPhaseData.length; i++) {
        if (this.sidewalkPhaseData[i].phaseid) {
          let curPhaseStatus = this.phaseStatusMap.get(this.sidewalkPhaseData[i].phaseid)
          if (!curPhaseStatus) continue
          const data = {
            ...this.sidewalkPhaseData[i],
            pedtype: curPhaseStatus.pedtype,
            color: this.SidewalkColorMap.get(curPhaseStatus.pedtype),
            flag: 'ped' // 行人相位数据标识
          }
          curPedStatus.push(data)
        } else {
          // 无状态的行人道
          const data = {
            ...this.sidewalkPhaseData[i],
            pedtype: undefined
          }
          curPedStatus.push(data)
        }
      }
      this.sidewalkPhaseData = JSON.parse(JSON.stringify(curPedStatus))
    },
    getOverlapPedStatus () {
      // 行人跟随相位状态
      let curPedStatus = []
      for (let i = 0; i < this.overlapsidewalkPhaseData.length; i++) {
        if (this.overlapsidewalkPhaseData[i].phaseid) {
          let curPhaseStatus = this.overlapPhaseStatusMap.get(this.overlapsidewalkPhaseData[i].phaseid)
          if (!curPhaseStatus) {
            // 无状态的行人道,也显示出来
            // const data = {
            //   ...this.overlapsidewalkPhaseData[i],
            //   pedtype: undefined
            // }
            // curPedStatus.push(data)
            continue
          }
          const data = {
            ...this.overlapsidewalkPhaseData[i],
            pedtype: curPhaseStatus.pedtype,
            color: this.SidewalkColorMap.get(curPhaseStatus.pedtype),
            flag: 'overlapped' // 行人跟随相位数据标识
          }
          curPedStatus.push(data)
        } else {
          // 无状态的行人道
          const data = {
            ...this.overlapsidewalkPhaseData[i],
            pedtype: undefined
          }
          curPedStatus.push(data)
        }
      }
      this.overlapsidewalkPhaseData = JSON.parse(JSON.stringify(curPedStatus))
    },
    getRoadDirection () {
      // 获取行车方向（从平台或配置工具的配置文件中读取）
      this.roadDir = this.roadDirection
    },
    getChannelInfo () {
      uploadSingleTscParam('channel', this.agentId).then(data => {
        let res = data.data
        if (!res.success) {
          if (res.code === '4003') {
            // this.isShowMessage && this.$message.error(this.$t('openatccomponents.errorTip.devicenotonline'))
            if (this.isShowMessage) {
              console.log(this.$t('openatccomponents.errorTip.devicenotonline'))
            }
            return
          }
          // this.isShowMessage && this.$message.error(getMessageByCode(data.data.code, this.$i18n.locale))
          if (this.isShowMessage) {
            console.log(getMessageByCode(data.data.code, this.$i18n.locale))
          }
          return
        }
        let channelList = res.data.data.channelList.filter(ele => ele.type !== undefined)
        this.channelList = this.handleRepeatRealdir(channelList)
        console.log('this.channelList', this.channelList)
        this.handleChannelDirection()
      })
    },
    handleRepeatRealdir (channelList) {
      // 按realdir去掉重复方向的数据
      let dirChannelList = channelList.filter(ele => ele.realdir !== undefined && (ele.type === 0 || ele.type === 1 || ele.type === 3))
      let pedDirChannelList = channelList.filter(ele => ele.realdir !== undefined && ele.type === 2)
      let map = new Map()
      let map2 = new Map()
      dirChannelList.forEach(ele => {
        ele.realdir.forEach(dir => {
          if (map.get(dir) === undefined) {
            map.set(dir, ele)
          }
        })
      })
      pedDirChannelList.forEach(ele => {
        ele.realdir.forEach(dir => {
          if (map2.get(dir) === undefined) {
            map2.set(dir, ele)
          }
        })
      })
      let arr = Array.from(map)
      let pedarr = Array.from(map2)
      let newarr = []
      arr.forEach(ele => {
        ele[1].realdir = [ele[0]]
        let obj = {
          ...ele[1],
          realdir: [ele[0]]
        }
        newarr.push(obj)
      })
      pedarr.forEach(ele => {
        ele[1].realdir = [ele[0]]
        let obj = {
          ...ele[1],
          realdir: [ele[0]]
        }
        newarr.push(obj)
      })
      // console.log(newarr)
      return newarr
    },
    handleChannelDirection () {
      this.LanePhaseData = []
      this.sidewalkPhaseData = []
      this.sidewalkDir = []
      let realphasedirarr = []
      let realpeddirarr = []
      this.channelList.forEach((ele, i) => {
        if (ele.type === 0 || ele.type === 1 || ele.type === 3) {
          if (ele.realdir) {
            ele.realdir.forEach((dir, index) => {
            // 车道相位（通道类型是机动车，非机动车，公交时，对应相位机动车）
              this.LanePhaseData.push({
                key: this.CrossDiagramMgr.getUniqueKey('phase'),
                channelid: ele.id, // 通道id
                id: dir, // 接口返回的dir字段，对应前端定义的相位方向id，唯一标识
                name: this.PhaseDataModel.getPhase(dir).name,
                left: this.PhaseDataModel.getPhase(dir).x,
                top: this.PhaseDataModel.getPhase(dir).y
              })
            })
            realphasedirarr = Array.from(new Set(realphasedirarr.concat(ele.realdir)))
          }
        }
        if (ele.type === 2) {
          if (ele.realdir) {
            ele.realdir.forEach((dir, index) => {
              // 行人相位
              if (this.sidewalkDir.indexOf(dir) === -1 && this.PhaseDataModel.getSidePos(dir)) {
                let obj = {
                  key: this.CrossDiagramMgr.getUniqueKey('pedphase') + `-${this.agentId}`,
                  channelid: ele.id, // 通道id
                  id: dir,
                  name: this.PhaseDataModel.getSidePos(dir).name
                }
                if (this.channelType) {
                  obj.left = this.PhaseDataModel.getSidePos(dir).x
                  obj.top = this.PhaseDataModel.getSidePos(dir).y
                }
                this.sidewalkPhaseData.push(obj)
              }
            })
            realpeddirarr = Array.from(new Set(realpeddirarr.concat(ele.realdir)))
            this.sidewalkDir = Array.from(new Set([...this.sidewalkDir.concat(ele.realdir)]))
          }
        }
      })
      this.inneChoosedDirection = this.choosedDirection.filter(dir => realphasedirarr.indexOf(dir) !== -1)
      this.inneChoosedPedDirection = this.choosedPedDirection.filter(dir => realpeddirarr.indexOf(dir) !== -1)
      this.drawPhaseIcon()
    },
    async drawPhaseIcon () {
      const targetIds = [4, 8, 12, 16] // 掉头相位后画
      this.LanePhaseData = this.LanePhaseData.filter(item => !targetIds.includes(item.id)).concat(this.LanePhaseData.filter(item => targetIds.includes(item.id)))
      if (!this.isThirdSignal && this.isVipRoute && !this.isRcp) {
        await this.getConflictList()
        this.handleClickedPhase()
        this.compLanePhaseData = JSON.parse(JSON.stringify(this.LanePhaseData))
        this.handleClickedPedPhase()
        this.compSidewalkPhaseData = JSON.parse(JSON.stringify(this.sidewalkPhaseData))
      } else {
        // 第三方信号机不需要处理冲突关系/特勤下rcp协议不需要处理冲突
        this.handleClickedPhase()
        this.compLanePhaseData = JSON.parse(JSON.stringify(this.LanePhaseData))
        this.handleClickedPedPhase()
        this.compSidewalkPhaseData = JSON.parse(JSON.stringify(this.sidewalkPhaseData))
      }
    },
    handleClickedPhase () {
      if (!this.isThirdSignal && !this.isRcp) {
        this.inneChoosedDirection = this.inneChoosedDirection.filter(dir => this.phaseConflictList.indexOf(dir) === -1)
      }
      for (let index = 0; index < this.LanePhaseData.length; index++) {
        const element = this.LanePhaseData[index]
        if (this.inneChoosedDirection.indexOf(element.id) !== -1) {
          element.clicked = true
        }
      }
    },

    async handleClickDirection (direction) {
      const id = direction.id
      // console.log(id)
      // console.log(this.inneChoosedDirection)
      const isSelected = this.inneChoosedDirection.includes(id)
      let nextSelected
      if (!isSelected) {
        nextSelected = [...this.inneChoosedDirection, id]
      } else {
        nextSelected = this.inneChoosedDirection.filter(d => d !== id)
      }
      // 检查是否冲突，冲突提示是否确定
      if (this.checkConflict(nextSelected)) {
        try {
          await this.$confirm(this.$t('openatccomponents.overview.conflictdirectionstips'), this.$t('openatccomponents.common.tipsmodaltitle'), {
            confirmButtonText: this.$t('openatccomponents.button.OK'),
            cancelButtonText: this.$t('openatccomponents.button.Cancel'),
            type: 'warning'
          })
          // 用户点击确定
          return {
            ok: true,
            nextSelected
          }
        } catch (e) {
          // 用户点击取消
          return {
            ok: false
          }
        }
      }
      // 无冲突，正常选中
      return {
        ok: true,
        nextSelected
      }
    },

    checkConflict (list) {
      // 默认冲突规则： 东直 东左 西直 西左 其中 任意一个 ，与 南直 南左 北直 北左 其中任意一个，同时选中，则提示冲突
      const groupA = [1, 2, 5, 6]
      const groupB = [9, 10, 13, 14]

      const hasA = list.some(id => groupA.includes(id))
      const hasB = list.some(id => groupB.includes(id))

      return hasA && hasB
    },
    beforeClickPhaseIcon (key) {
      // 进入冲突判断
      return new Promise(async (resolve) => {
        for (let element of this.LanePhaseData) {
          if (element.key === key) {
            const result = await this.handleClickDirection(element)
            resolve(result.ok) // ok: true / false
          }
        }
      })
    },
    handleClickPhaseIcon (key, action) {
      let curClickedPhase = {}
      if (action === 'clicked') {
        for (let index = 0; index < this.LanePhaseData.length; index++) {
          const element = this.LanePhaseData[index]
          if (element.key === key) {
            element.clicked = true
            curClickedPhase = JSON.parse(JSON.stringify(element))
          }
        }
      }
      if (action === 'cancle') {
        for (let index = 0; index < this.LanePhaseData.length; index++) {
          const element = this.LanePhaseData[index]
          if (element.key === key) {
            delete element.clicked
          }
        }
      }
      this.compLanePhaseData = JSON.parse(JSON.stringify(this.LanePhaseData))
      let clickedDirection = this.compLanePhaseData.filter(ele => ele.clicked && !ele.disabled)
      this.inneChoosedDirection = clickedDirection.map(ele => ele.id)
      this.EmitAllChoosedDirection(curClickedPhase)
    },
    handleClickedPedPhase () {
      if (!this.isThirdSignal && !this.isRcp) {
        this.inneChoosedPedDirection = this.inneChoosedPedDirection.filter(dir => this.pedConflictList.indexOf(dir) === -1)
      }
      // 排他
      for (let index = 0; index < this.sidewalkPhaseData.length; index++) {
        const element = this.sidewalkPhaseData[index]
        delete element.clicked
      }
      for (let index = 0; index < this.sidewalkPhaseData.length; index++) {
        const element = this.sidewalkPhaseData[index]
        if (this.inneChoosedPedDirection.indexOf(element.id) !== -1) {
          element.clicked = true
        }
      }
    },
    handleClickSidewalkIcon (data, curChoosePed) {
      this.clickedPedDirection = data.filter(ele => ele.clicked && !ele.disabled)
      this.inneChoosedPedDirection = this.clickedPedDirection.map(ele => ele.id)
      this.EmitAllChoosedDirection(curChoosePed)
    },
    EmitAllChoosedDirection (curClickedPhase) {
      let allChoosedDir = {
        direction: this.inneChoosedDirection,
        peddirection: this.inneChoosedPedDirection
      }
      this.$emit('handleClickCrossIcon', allChoosedDir, curClickedPhase)
      this.drawPhaseIcon()
    },
    async getConflictList () {
      let ConflictList = new CrossDirectionConflictList(this.agentId)
      return ConflictList.getConflictListByAgentid().then(res => {
        if (res) {
          let conflictList = ConflictList.getListDirConflict(this.inneChoosedDirection, this.inneChoosedPedDirection)
          this.phaseConflictList = conflictList.allConflictDir
          this.pedConflictList = conflictList.allPedConflictDir
          // 排他
          for (let index = 0; index < this.LanePhaseData.length; index++) {
            const element = this.LanePhaseData[index]
            delete element.disabled
          }
          for (let index = 0; index < this.sidewalkPhaseData.length; index++) {
            const element = this.sidewalkPhaseData[index]
            delete element.disabled
          }
          for (let index = 0; index < this.LanePhaseData.length; index++) {
            const element = this.LanePhaseData[index]
            if (this.phaseConflictList.indexOf(element.id) !== -1) {
              element.disabled = true
            }
          }
          for (let index = 0; index < this.sidewalkPhaseData.length; index++) {
            const element = this.sidewalkPhaseData[index]
            if (this.pedConflictList.indexOf(element.id) !== -1) {
              element.disabled = true
            }
          }
          // console.log(this.LanePhaseData)
        }
      })
    },
    createChannelStatusMap () {
      // 生成相位id和相位状态对应数据结构
      this.channelStatusList.map(channel => {
        let channelId = channel.id
        let channelInfo = {
          light: channel.light
        }
        this.channelStatusMap.set(channelId, channelInfo)
      })
    },
    getChannelPhaseStatus () {
      // 通道相位机动车状态
      this.comdirePhaseData = []
      let curLanePhaseData = []
      for (let i = 0; i < this.LanePhaseData.length; i++) {
        let curPhaseStatus = this.channelStatusMap.get(this.LanePhaseData[i].channelid)
        if (!curPhaseStatus) continue
        const data = {
          ...this.LanePhaseData[i],
          type: curPhaseStatus.light,
          color: this.ColorMap.get(curPhaseStatus.light),
          flag: 'phasechannel' // 车道相位数据标识
        }
        curLanePhaseData.push(data)
      }
      this.LanePhaseData = JSON.parse(JSON.stringify(curLanePhaseData))
      this.compLanePhaseData = JSON.parse(JSON.stringify(this.LanePhaseData))
    },
    getChannelPedStatus () {
      // 通道行人相位状态
      let curPedStatus = []
      for (let i = 0; i < this.sidewalkPhaseData.length; i++) {
        console.log(this.sidewalkPhaseData[i])
        if (this.sidewalkPhaseData[i].channelid) {
          let curPhaseStatus = this.channelStatusMap.get(this.sidewalkPhaseData[i].channelid)
          if (!curPhaseStatus) continue
          const data = {
            ...this.sidewalkPhaseData[i],
            pedtype: curPhaseStatus.light,
            color: this.ColorMap.get(curPhaseStatus.light),
            flag: 'pedchannel' // 行人相位数据标识
          }
          curPedStatus.push(data)
        } else {
          // 无状态的行人道
          const data = {
            ...this.sidewalkPhaseData[i],
            pedtype: undefined
          }
          curPedStatus.push(data)
        }
      }
      this.compSidewalkPhaseData = JSON.parse(JSON.stringify(curPedStatus))
    },
    getValidDirections () {
      getValidDirections(this.agentId).then((data) => {
        if (!data.data.success) {
          this.$message.error(getMessageByCode(data.data.code, this.$i18n.locale))
          return
        }
        this.effectiveDirection = data.data.data.validDirections || []
        this.getEffectDirectionPos()
      })
    },
    getMergeDirections () {
      getMergeDirections(this.agentId).then((data) => {
        if (!data.data.success) {
          this.$message.error(getMessageByCode(data.data.code, this.$i18n.locale))
          return
        }
        this.mergeDirection = data.data.data.mergeDirections || []
        if (this.mergeDirection && this.mergeDirection.length > 0) {
              this.mergeShowList = this.mergeDirection.map(dir => {
                return {
                  id: dir,
                  color: '#6e737c'
                }
              })
              } else {
                this.mergeShowList = [
                  {
                  id: '',
                  color: '#fff'
                  }
                ]
              }
      })
    },
    // 处理 SVG 点击事件
    handleSvgClick (event) {
      // 获取带有 data-road 的元素
      const roadElement = event.target.closest('[data-road]')
      if (roadElement) {
        const direction = roadElement.getAttribute('data-road')
        // 打开编辑对话框，选中高亮
        this.openEditDialog(direction)
        this.highlightRoad(this.currentEditDirection)
      } else {
        // 点击空白处，取消选中
        this.selectedRoad = null
        this.clearHighlight()
      }
    },
    // 高亮路段
    highlightRoad (direction) {
      // 清除高亮
      this.clearHighlight()
      // 获取 SVG 容器内的所有元素
      const svgContainer = this.$refs.svgContainer
      if (!svgContainer) return
      // 为指定方向的路段添加高亮类
      const roadElements = svgContainer.querySelectorAll(`[data-road="${direction}"]`)
      roadElements.forEach(el => {
        el.classList.add('road-highlight')
      })
    },
    // 清除高亮
    clearHighlight () {
      const svgContainer = this.$refs.svgContainer
      if (!svgContainer) return
      const highlightedElements = svgContainer.querySelectorAll('.road-highlight')
      highlightedElements.forEach(el => {
        el.classList.remove('road-highlight')
      })
    },
    // 打开编辑对话框
    openEditDialog (direction) {
      this.currentEditDirection = direction
      this.dialogVisible = true
    },
    // 确认修改名称
    onRoadNameConfirm ({ direction, name }) {
      if (direction) {
        // 更新 roadNames 对象
        this.$set(this.roadNames, direction, name)
        this.updateDevice()
        this.selectedRoad = {
          direction: direction,
          name: name
        }
      }
    },
    queryDevParams () {
      queryDevice(this.agentId).then(res => {
        if (!res.data.success) {
          this.$message.error(getMessageByCode(res.data.code, this.$i18n.locale))
          return
        }
        this.devParams = res.data.data
        if (this.devParams.jsonparam && this.devParams.jsonparam.roadNames) {
          this.roadNames = {
            east: this.devParams.jsonparam.roadNames.east || '',
            west: this.devParams.jsonparam.roadNames.west || '',
            south: this.devParams.jsonparam.roadNames.south || '',
            north: this.devParams.jsonparam.roadNames.north || ''
          }
        }
      })
    },
    updateDevice () {
      // console.log(this.roadNames)
      this.devParams.jsonparam.roadNames = this.roadNames
      // console.log(this.devParams)
      UpdateDevice(this.devParams).then(res => {
        if (!res.data.success) {
          this.$message.error(getMessageByCode(res.data.code, this.$i18n.locale))
          return
        }
        this.$message({
          message: this.$t('openatccomponents.common.updatesuccess'),
          type: 'success'
        })
      })
    }
  },
  mounted () {
    // this.init()
  }
}
</script>
<style scoped>
.invisible {
  visibility: hidden;
}
.crossImg{
    position: relative;
    width: 870px;
    height: 650px;
    left: 50%;
    transform: translateX(-50%);
}
.centerText {
  position: absolute;
  width: 140px;
  height: 140px;
  left: 50%;
  top: 50%;
  transform: translateX(-50%) translateY(-50%);
  z-index: 9;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
.phaseCountdown {
  line-height: 42PX;
  font-size: 18px;
  font-weight: normal;
  font-stretch: normal;
  letter-spacing: 0px;
  color: #fff;
  width: 150px;
  margin: 0 auto;
}
.countdownBg {
  border-radius: 10PX;
  background-color: rgba(94, 90, 90, 0.8);
  padding-left: 14PX;
  padding-top: 10PX;
  padding-bottom: 10PX;
  width: 100%;
}
.centerText .text {
  display: inline-block;
  color: #299BCC;
  margin-top: 20PX;
}
.locked-status {
  width: 100%;
  display: block;
  text-align: center;
}
.locked-icon {
  width: 12PX;
  height: 14PX;
}
.locked-text {
  color: #77FB65;
  font-size: 16PX;
  line-height: 24PX;
}

.merge-direction-icon {
  width: 80PX;
  height: 80PX;
  margin: 0 auto;
}

.baseImg {
    width: 100%;
    height: 650px;
    position: relative;
}

/* 新增：路口名称标签样式 */
.road-name-label {
  position: absolute;
  padding: 8px 16px;
  background-color: rgba(41, 155, 204, 0.9);
  color: #fff;
  font-size: 14px;
  border-radius: 4px;
  z-index: 10;
  pointer-events: none;
  white-space: nowrap;
}

/* 路口名称位置 - 根据方向定位到路口外侧 */
.road-name-label.east {
  right: 20px;
  top: 50%;
  transform: translateY(-50%);
}

.road-name-label.west {
  left: 20px;
  top: 50%;
  transform: translateY(-50%);
}

.road-name-label.south {
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
}

.road-name-label.north {
  top: 20px;
  left: 50%;
  transform: translateX(-50%);
}

/* 新增：路段高亮样式 - 使用深度选择器穿透 SVG 组件 */
.baseImg ::v-deep .road-highlight {
  filter: brightness(1.3) drop-shadow(0 0 8px rgba(41, 155, 204, 0.8));
  cursor: pointer;
}

/* SVG 内部可点击元素的鼠标样式 */
.baseImg ::v-deep [data-road] {
  cursor: pointer;
}
</style>
