/**
 * 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="container-main">
    <div class="overview-component-content" :style="{'transform': `scale(${shrink})`, 'transform-origin': 'left top', 'height': '100%'}">
      <div class="tuxingjiemian" v-show="curHomePage === 'Graphical' || curHomePage === 'Channelization'" :class="{'minifont': curBodyWidth <= 650}">
        <div :class="{'changeWidth': graphicMode, 'tuxing-left': !onlyShowIntersectionMap}" ref="tuxingLeft">
          <intersection-base-map
            v-if="curHomePage === 'Graphical'"
            ref="intersectionMap"
            :stateName="stateName"
            :crossStatusData="crossStatusData"
            :agentId="agentId"
            :isShowMessage ="isShowMessage"
            :isShowInterval="isShowInterval"
            :roadDirection="roadDirection" />
          <channelization
            v-if="curHomePage === 'Channelization'"
             ref="channelization"
            :AgentId="agentId"
            :crossStatusData="crossStatusData"
            :detectorStatusData="detectorStatusData" />
          <div class="pattern-status" v-if="!graphicMode && !onlyShowIntersectionMap && crossStatusData.control !== 1 && crossStatusData.control !== 2 && crossStatusData.control !== 3">
            <div class="pattern-name cross-mess">{{$t('openatccomponents.overviewcomponent.patternstate')}}</div>
            <div class="pattern-message">({{$t('openatccomponents.overviewcomponent.cycle')}}: {{controlData.cycle}}  {{$t('openatccomponents.overviewcomponent.patternoffset')}}: {{controlData.patternoffset}} {{$t('openatccomponents.overviewcomponent.coordinationtime')}}: {{controlData.offset}})</div>
              <span class="pattern-explain"><el-checkbox v-model="checked">{{$t('openatccomponents.overviewcomponent.overLap')}}</el-checkbox></span>
          <!-- 没ring数据显示方案图 -->
          <pattern-list
          v-if="
            (controlData &&
              !controlData.rings &&
              contrloType === 'ring' &&
              !controlData.syncTime) ||
              (controlData && !controlData.rings && contrloType === 'ring')
          "
          :showBarrier="true"
          :controlPhase ="controlData"
          :contrloType="contrloType"
          :syncTime="controlData.syncTime"
          :patternStatusList="patterData ? patterData.rings : []"
          :cycles="patterData ? patterData.cycle : 0"
          :isPhase="false"
          :phaseList="phaseList"
        >
        </pattern-list>
            <!-- 1049没ring数据显示阶段图 -->
            <pattern-list
            v-else-if="controlData && !controlData.rings && contrloType === 'stage'"
            ref="boardCard"
            :stagesChange="patterData ? patterData.stagesList : []"
            :contrloType="contrloType"
            :controlData="controlData"
            :cycles="patterData ? patterData.cycle : 0"
            :syncTime="controlData.syncTime"
            :localPatternList="allPatternList"
            :showBarrier="true"
            :isPhase="false"
            :phaseList="phaseList"
          >
          </pattern-list>
          <pattern-list
            v-else
            ref="boardCard"
            :cycle="crossStatusData ? crossStatusData.cycle : 0"
            :syncTime="crossStatusData ? crossStatusData.syncTime : 0"
            :controlData="controlData"
            :contrloType="contrloType"
            :localPatternList="allPatternList"
            :phaseList="phaseList"
            :showBarrier="true"
            :isPhase="false"
            :agentId="agentId"
          >
          </pattern-list>
            <!-- <over-lap
            v-if="this.contrloType === 'ring'"
            :checked="checked"
            :overlap="overlap"
            :stageList="stagesListOver"
            :cycle="overlapCycle"
            :controlData="controlData"
            >
            </over-lap> -->
          </div>
        </div>

        <div ref="tuxingRight" class="tuxing-right" v-if="!onlyShowIntersectionMap">
          <RcpRightPanel v-if="protocol === 'rcp'" :agent-id="agentId"></RcpRightPanel>
          <scheme-config
            v-else
            ref="rightpanel"
            :statusData="crossStatusData"
            :phaseList="phaseList"
            :agentName="agentName"
            :responseTime="responseTime"
            :agentId="agentId"
            :ip="ip"
            :platform="platform"
            :roadDirection="roadDirection"
            :isFromAtc="isfromatc" />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getTscControl, queryDevice } from '../../../api/control.js'
import { registerMessage, uploadSingleTscParam } from '../../../api/param'
import { getIntersectionInfo } from '../../../api/template'
import { setIframdevid } from '../../../utils/auth.js'
import { getMessageByCode } from '../../../utils/responseMessage'
import PhaseDataModel from '../IntersectionMap/crossDirection/utils.js'
import CrossDiagramMgr from '../../../EdgeMgr/controller/crossDiagramMgr.js'
import { getChannelizatonChart, getDetectorStatus } from '../../../api/cross'
export default {
  name: 'overview-component',
  components: {
  },
  props: {
    AgentId: {
      type: String,
      default: '0'
    },
    roadDirection: {
      type: String,
      default: 'right'
    },
    isShowInterval: {
      type: Boolean,
      default: true
    },
    isShowMessage: {
      type: Boolean,
      default: true
    },
    isfromatc: {
      type: Boolean,
      default: true
    },
    onlyShowIntersectionMap: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      stateName: this.$t('openatccomponents.overview.offline'),
      curBodyWidth: 1920,
      controlData: {},
      checked: false,
      overlap: [],
      contrloType: '',
      narr: [],
      // patternList: [],
      // patternSelect: [], // 所有方案id
      // planPattern: {}, // 默认显示方案
      allPatternList: [], // 所有方案
      stagesListOver: [],
      sidewalkPhaseData: [],
      phaseControlTimer: null, // 定时器
      registerMessageTimer: null, // 延时器
      volumeControlTimer: null, // 流量定时器
      detectorStatusTimer: null, // 检测器定时器
      ParamsMode: new Map([[0, '自主控制'], [1, '本地手动'], [2, '平台控制'], [3, '配置软件控制'], [4, '遥控器控制'], [5, '黄闪器控制'], [6, '降级控制'], [7, '脚本控制'], [8, '算法控制']]),
      ParamsModeEn: new Map([[0, 'Autonomous Control'], [1, 'Local Manual'], [2, 'Platform Control'], [3, 'Configuration Software Control'], [4, 'Remote Control'], [5, 'Yellow Flasher Control'], [6, 'Degradation Control'], [7, 'Script Control'], [8, 'Algorithm Control']]),
      ParamsControl: new Map([[0, '多时段'], [1, '黄闪'], [2, '全红'], [3, '关灯'], [4, '步进'], [5, '定周期控制'], [6, '自适应'], [7, '协调感应控制'], [8, '方案选择控制'], [9, '方案生成'], [10, '无电缆控制'], [11, '有电缆控制'], [12, '行人过街控制'], [13, '方案恢复过渡'], [14, '相位驻留'], [15, '通道检测'], [16, '方向锁定'], [17, '韦伯斯特单点控制'], [18, '预留18'], [19, '感应式行人过街'], [20, '方案干预'], [100, '方案干预'], [21, '预留21'], [22, '相位锁定'], [23, '相位放行控制'], [24, '紧急控制'], [99, '设备维护']]),
      ParamsControlEn: new Map([[0, 'Multi Period'], [1, 'Yellow Flash Control'], [2, 'Red Control'], [3, 'Dark Control'], [4, 'Step'], [5, 'Fixed_Cycle Control'], [6, 'Free Control'], [7, 'Coordinated Induction Control'], [8, 'Pattern Selection Control'], [9, 'Adaptive Control'], [10, 'Wireless Control'], [11, 'Cable Control'], [12, 'Pedestrian Crossing Control'], [13, 'Pattern recovery'], [14, 'Phase dwell'], [15, 'Channel Detection'], [16, 'Direction lock'], [17, 'Webster Single Point Coordination'], [18, 'Reserving18'], [19, 'Inductive Pedestrian Crossing Control'], [20, 'Program Intervention'], [100, 'Program Intervention'], [21, 'Reserving21'], [22, 'Priority Control'], [23, 'Close Phase'], [24, 'Emergency Control'], [99, 'Device Mantenance']]),
      phaseType: new Map([[1, '红'], [2, '黄'], [3, '绿'], [4, '绿闪']]), // phaseType表示红，黄，绿
      phaseTypeEn: new Map([[1, 'Red'], [2, 'Yellow'], [3, 'Green'], [4, 'Greenclear']]), // phaseType表示红，黄，绿
      ip: '--',
      port: '--',
      protocol: '--',
      // devStatus: 1,
      mode: '2',
      agentId: '0',
      agentName: '',
      overlapCycle: 0,
      platform: undefined,
      crossStatusData: {}, // 路口状态数据
      detectorStatusData: {}, // 检测器状态数据（包括车辆检测器状态和行人检测器状态）
      reset: false,
      responseTime: 0,
      phaseList: [], // 当前相位集合
      intervalFlag: true,
      detIntervalFlag: true,
      shrink: 1,
      isResend: true,
      commonHeight: undefined, // 左右侧面板的高度值
      graphicMode: false,
      resetcomponent: true,
      curHomePage: 'Graphical',
      detectorList: [],
      pedestrainDetectorList: []
    }
  },
  computed: {
    // patternList () {
    //   return this.$store.state.globalParam.tscParam.patternList
    // },
    patterData () {
      if (!this.allPatternList) {
        return undefined
      }
      return this.allPatternList.filter(item => {
        return item.id === this.controlData.patternid
      })[0]
    }
  },
  watch: {
    AgentId: {
      handler: async function (val, oldVal) {
        this.agentId = val
        this.resetcomponent = false
        setIframdevid(val)
        // this.registerMessage() // 注册消息
        await this.getIntersectionInfo(val)
        this.$nextTick(() => {
          this.resetcomponent = true
          this.getChannelizatonChart()
          this.getPlatform()
          this.getPhase()
          this.initData()
        })
      },
      // 深度观察监听
      deep: true
    },
    phaseList: {
      handler: function (val, oldVal) {
        this.getPedPhasePos()
      },
      // 深度观察监听
      deep: true
    }
  },
  created () {
    this.globalParamModel = this.$store.getters.globalParamModel
    this.PhaseDataModel = new PhaseDataModel()
    this.CrossDiagramMgr = new CrossDiagramMgr()
    this.agentId = this.AgentId
    setIframdevid(this.agentId)
    // this.registerMessage() // 注册消息
    this.getIntersectionInfo(this.agentId)
  },
  mounted () {
    this.getPlatform()
    if (this.$route.query.shrink) {
      this.shrink = Number(this.$route.query.shrink)
    }
    this.getChannelizatonChart()
    if (this.curHomePage === 'Graphical') {
      this.$nextTick(() => {
        this.$refs.intersectionMap.resetCrossDiagram()
      })
    }
  },
  updated () {
    if (this.$refs.tuxingLeft.offsetHeight !== this.commonHeight) {
      // 根据左侧面板动态变化的高度，同步更新右侧面板高度
      this.commonHeight = this.$refs.tuxingLeft.offsetHeight
      this.$refs.tuxingRight.style.height = this.commonHeight + 'PX'
    }
  },
  methods: {
    getIntersectionInfo (agentid) {
      // 获取路口信息
      return new Promise((resolve, reject) => {
        getIntersectionInfo(agentid).then(res => {
          if (sessionStorage.getItem('firstGet') !== 'false') {
            if (res.data.data.param.manualpanel === undefined) {
              res.data.data.param.manualpanel = {}
            }
            if (res.data.data.param.channellock === undefined) {
              res.data.data.param.channellock = []
            }
            if (res.data.data.param.channelList === undefined) {
              res.data.data.param.channelList = []
            }
            if (res.data.data.param.overlaplList === undefined) {
              res.data.data.param.overlaplList = []
            }
            if (res.data.data.param.detectorList === undefined) {
              res.data.data.param.detectorList = []
            }
            if (res.data.data.param.pedestrainDetectorList === undefined) {
              res.data.data.param.pedestrainDetectorList = []
            }
            if (res.data.data.param.preemptList === undefined) {
              res.data.data.param.preemptList = []
            }
            if (res.data.data.param.channelGreenConflictInfo === undefined) {
              res.data.data.param.channelGreenConflictInfo = []
            }
            if (res.data.data.param.singleoptim === undefined) {
              res.data.data.param.singleoptim = []
            }
          }
          this.allPatternList = res.data.data.param.patternList
          if (!this.allPatternList) {
            resolve(res.data.data)
            return
          }
          console.log(this.allPatternList)
          if (!this.allPatternList[0].contrloType && this.allPatternList[0].rings.length > 0) {
            this.contrloType = 'ring'
          } else if (!this.allPatternList[0].contrloType && this.allPatternList[0].rings.length === 0) {
            this.contrloType = 'stage'
          } else {
            this.contrloType = this.allPatternList[0].contrloType
          }
          this.overlap = res.data.data.param.overlaplList
          this.detectorList = res.data.data.param.detectorList
          this.pedestrainDetectorList = res.data.data.param.pedestrainDetectorList
          this.handleDetectorTimer()
          resolve(res.data.data)
          // this.phaseList = res.data.data.param.phaseList
          // this.patternPlan()
          // this.getCycle()
          // if (id) {
          //   this.patternList = res.data.data.param.patternList.filter(item => {
          //     return item.id === id
          //   })[0].rings
          // }
        })
      })
    },
    getChannelizatonChart () {
      let _this = this
      getChannelizatonChart(this.AgentId).then(data => {
        if (!data.data.success) {
          // let parrenterror = getMessageByCode(data.data.code, _this.$i18n.locale)
          // if (data.data.data) {
          //   // 子类型错误
          //   let childErrorCode = data.data.data.errorCode
          //   if (childErrorCode) {
          //     let childerror = getMessageByCode(data.data.data.errorCode, _this.$i18n.locale)
          //     _this.isShowMessage && _this.$message.error(parrenterror + ',' + childerror)
          //   }
          // } else {
          //   _this.isShowMessage && _this.$message.error(parrenterror)
          // }
          _this.curHomePage = 'Graphical'
          return
        }
        // 路口已设置渠化，则总览默认显示渠化路口，未设置显示模版路口
        if (_this.isfromatc === true && data.data.success === true && data.data.data !== undefined && JSON.stringify(data.data.data) !== '{}') {
          _this.curHomePage = 'Channelization'
        } else {
          _this.curHomePage = 'Graphical'
        }
      })
    },
    getPedPhasePos () {
      // 行人相位信息
      this.sidewalkPhaseData = []
      this.phaseList.forEach((ele, i) => {
        if (ele.peddirection) {
          ele.peddirection.forEach((dir, index) => {
            // 行人相位
            if (this.PhaseDataModel.getSidePos(dir)) {
              this.sidewalkPhaseData.push({
                key: this.CrossDiagramMgr.getUniqueKey('pedphase'),
                phaseid: ele.id, // 相位id，用于对应相位状态
                id: dir,
                name: this.PhaseDataModel.getSidePos(dir).name
              })
            }
          })
        }
      })
    },
    registerMessage () {
      registerMessage(this.agentId, this.protocol).then(data => {
        if (!data.data.success && this.protocol !== 'rcp') {
          // this.devStatus = 2
          if (data.data.code === '4002' && data.data.data.errorCode === '4209') {
            let success = data.data.data.content.success
            if (success !== 0) {
              let errormsg = 'openatccomponents.overview.putTscControlError' + success
              this.isShowMessage && this.$message.error(this.$t(errormsg))
              return
            }
          }
          let parrenterror = getMessageByCode(data.data.code, this.$i18n.locale)
          if (data.data.data) {
            // 子类型错误
            let childErrorCode = data.data.data.errorCode
            if (childErrorCode) {
              let childerror = getMessageByCode(data.data.data.errorCode, this.$i18n.locale)
              this.isShowMessage && this.$message.error(parrenterror + ',' + childerror)
            }
          } else {
            this.isShowMessage && this.$message.error(parrenterror)
          }
          if (this.isResend) {
            this.reSend()
          }
          return
        } else {
          if (data.data.code === '4002' && data.data.data.errorCode === '4210') {
            let successArray = data.data.data.content
            successArray.forEach(success => {
              let dataType = this.$t('openatccomponents.common.datatype') + ':' + success.DataClass // 数据类
              let objectID = this.$t('openatccomponents.common.objectid') + ':' + success.ObjectID // 对象
              let propertyID = this.$t('openatccomponents.common.propertyid') + ':' + success.PropertyID // 属性
              let elementID = this.$t('openatccomponents.common.elementid') + ':' + success.ElementID // 元素
              let returnCode = this.$t('openatccomponents.common.returncode') + ':' + this.getError(success.ReturnCode) // 数据值
              let errormsg = `${dataType} ${objectID} ${propertyID} ${elementID} ${returnCode}`
              this.$message.error(this.$t(errormsg))
            })
            return
          }
        }
        // this.devStatus = 3
        this.clearPatternInterval() // 清除其他定时器
        this.clearVolumeInterval()
        this.phaseControlTimer = setInterval(() => {
          if (this.intervalFlag) {
            this.initData()
          }
        }, 1000)
        this.getPhase()
      })
    },
    getError (val) {
      if (val === 'Status_BadValue') {
        return this.$t('openatccomponents.common.statusbadvalue')
      } else if (val === 'Status_WrongLength') {
        return this.$t('openatccomponents.common.statuswronglength')
      } else if (val === 'Status_Overflow') {
        return this.$t('openatccomponents.common.statusvverflow')
      } else if (val === 'Status_ReadOnly') {
        return this.$t('openatccomponents.common.statusreadonly')
      } else if (val === 'Status_NullValue') {
        return this.$t('openatccomponents.common.statusnullvalue')
      } else if (val === 'Status_Error') {
        return this.$t('openatccomponents.common.statuserror')
      } else if (val === 'Status_ControlFail') {
        return this.$t('openatccomponents.common.statuscontrolfail')
      } else if (val === 'Status_AccessDenied') {
        return this.$t('openatccomponents.common.statusaccessdenied')
      } else if (val === 'Status_InvalidKey') {
        return this.$t('openatccomponents.common.statusinvalidkey')
      } else if (val === 'Status_ChecksumError') {
        return this.$t('openatccomponents.common.statuschecksumerror')
      } else {
        return ''
      }
    },
    reSend () { // 设备掉线重连机制
      // this.devStatus = 1
      this.clearRegisterMessageTimer()
      this.registerMessageTimer = setTimeout(() => {
        this.reconnectionDev()
      }, 5000)
    },
    clearPatternInterval () {
      if (this.phaseControlTimer !== null) {
        clearInterval(this.phaseControlTimer) // 清除定时器
        this.phaseControlTimer = null
      }
    },
    clearVolumeInterval () {
      if (this.volumeControlTimer !== null) {
        clearInterval(this.volumeControlTimer) // 清除流量定时器
        this.volumeControlTimer = null
      }
    },
    clearRegisterMessageTimer () {
      if (this.registerMessageTimer !== null) {
        clearTimeout(this.registerMessageTimer) // 清除延时器
        this.registerMessageTimer = null
      }
    },
    clearDetectorStatusTimer () {
      if (this.detectorStatusTimer !== null) {
        clearInterval(this.detectorStatusTimer) // 清除定时器
        this.detectorStatusTimer = null
      }
    },
    initData () {
      this.intervalFlag = false
      let startTime = new Date().getTime()
      getTscControl(this.agentId).then((data) => {
        let endTime = new Date().getTime()
        let diffTime = endTime - startTime
        this.responseTime = diffTime
        this.intervalFlag = true
        if (!data.data.success) {
          if (data.data.code === '4002' && data.data.data.errorCode === '4209') {
            let success = data.data.data.content.success
            if (success !== 0) {
              let errormsg = 'openatccomponents.overview.putTscControlError' + success
              this.isShowMessage && this.$message.error(this.$t(errormsg))
              return
            }
          }
          if (data.data.code === '4003') {
            // this.devStatus = 2
            this.clearPatternInterval() // 清除其他定时器
            this.clearVolumeInterval()
            this.isShowMessage && this.$message.error(getMessageByCode(data.data.code, this.$i18n.locale))
            if (this.isResend) {
              this.reSend()
            }
            return
          }
          let parrenterror = getMessageByCode(data.data.code, this.$i18n.locale)
          if (data.data.data) {
            // 子类型错误
            let childErrorCode = data.data.data.errorCode
            if (childErrorCode) {
              let childerror = getMessageByCode(data.data.data.errorCode, this.$i18n.locale)
              this.isShowMessage && this.$message.error(parrenterror + ',' + childerror)
            }
          } else {
            this.isShowMessage && this.$message.error(parrenterror)
          }
          this.clearPatternInterval() // 清除其他定时器
          this.clearVolumeInterval()
          if (this.isResend) {
            this.reSend()
          }
          return
        }
        this.$emit('getTscControl', data)
        if (data.data.data.data) {
          this.crossStatusData = JSON.parse(JSON.stringify(data.data.data.data))
        } else {
          this.crossStatusData = {}
        }
        let TscData = JSON.parse(JSON.stringify(data.data.data.data))
        // this.handleStageData(TscData) // 处理阶段（驻留）stage数据
        this.controlData = this.handleGetData(TscData)
        console.log('this.controlData', this.controlData)
        this.checkStage(this.controlData)
      }).catch(error => {
        // this.isShowMessage && this.$message.error(error)
        console.log(error)
      })
    },
    getControl (newList) { // 总揽实时数据
      let currentIds = ''
      let lastCurrentIds = ''
      this.stateList = [0]
      this.narr = []
      let overstagesList = []
      let phaseList = []
      for (let j = 0; j <= this.max; j++) { // 指针长度
        for (let i = 0; i < newList.length; i++) { // 环列表
          let ring = newList[i]// 每个环对象
          let sum = 0
          for (let n = 0; n < ring.length; n++) { // 相位累计长度
            // if (ring[n].mode !== 7) {
            sum = sum + ring[n].value + (ring[n].sum ? ring[n].sum : 0)
            if (j < sum) {
              let phaseId = ring[n].id
              currentIds = currentIds + '-' + phaseId
              break
            }
            // }
          }
          // for (let n = 0; n < ring.length; n++) { // 相位累计长度
          //   if (ring[n].mode !== 7) {
          //     sum = sum + ring[n].split
          //     if (j < sum) {
          //       let phaseId = ring[n].id
          //       currentIds = currentIds + '-' + phaseId
          //       break
          //     }
          //   }
          // }
        }
        if (lastCurrentIds !== currentIds && lastCurrentIds !== '') { // 当前相位id和上一个相比不同说明相位变化了
          phaseList.push(lastCurrentIds)
          this.stateList.push(j)// 阶段累计长度的集合
        }
        lastCurrentIds = currentIds
        currentIds = ''
      }
      let newPhaselist = []
      phaseList.forEach(i => {
        let rangeArr = i.split('-').map(Number)
        if (rangeArr.length > 2) {
          newPhaselist.push([
            JSON.parse(JSON.stringify(rangeArr[1])),
            JSON.parse(JSON.stringify(rangeArr[2]))
          ])
        } else {
          newPhaselist.push([
            JSON.parse(JSON.stringify(rangeArr[1]))
          ])
        }
      })
      for (let i = this.stateList.length - 1; i >= 1; i--) {
        this.narr.push(this.stateList[i] - this.stateList[i - 1])
      }
      this.narr.reverse()// 阶段差
      for (let i = 0; i < newPhaselist.length; i++) {
        let stage = JSON.parse(JSON.stringify(newPhaselist[i]))
        let newStage = []
        stage.map(item => {
          for (let ring of newList) {
            for (let ringItem of ring) {
              if (item === ringItem.id && (ringItem.mode !== 7 && ringItem.mode !== 8 && ringItem.mode !== 9)) {
                newStage.push(item)
              }
            }
          }
        })
        let stageItem = this.getStageItem(newStage, newList, i)
        overstagesList.push(JSON.parse(JSON.stringify(stageItem)))
      }
      this.overlapCycle = overstagesList.reduce((prev, curr) => prev + parseInt(curr.split), 0)
      this.stagesListOver = JSON.parse(JSON.stringify(overstagesList))
      console.log(this.stagesListOver)
    },
    getStageItem (stageArr, ringsList, i) {
      let res = {
        key: i,
        split: this.narr[i], // 阶段绿性比
        phases: stageArr,
        delaystart: 0,
        advanceend: 0
      }
      // let splitArr = []
      let delaystartArr = []
      let advanceendArr = []
      for (let rings of ringsList) {
        for (let ring of rings) {
          if (stageArr.includes(ring.id)) {
            // let split = ring.value
            let delaystart = ring.delaystart
            let advanceend = ring.advanceend
            // splitArr.push(split)
            delaystartArr.push(delaystart)
            advanceendArr.push(advanceend)
          }
        }
      }
      // splitArr.sort(function (a, b) { return a - b })
      delaystartArr.sort(function (a, b) { return b - a })
      advanceendArr.sort(function (a, b) { return a - b })
      // res.split = splitArr.length > 0 ? splitArr[0] : 0
      res.delaystart = delaystartArr.length > 0 ? delaystartArr[0] : 0
      res.advanceend = advanceendArr.length > 0 ? advanceendArr[0] : 0
      return res
    },
    checkStage (rings) {
      if (!rings.phase || !rings.rings) return
      let idPattern = this.allPatternList.filter(item => item.id === rings.patternid)
      if (idPattern.length === 0) return
      let ringList = this.allPatternList.filter(item => {
        return item.id === rings.patternid
      })[0].rings
      let filterPattern = []
      for (let i of ringList) {
        for (let j of this.controlData.rings) {
          let filterSequence = i.filter(item => j.sequence.includes(item.id))
          if (filterSequence.length > 0) {
            filterPattern.push(filterSequence)
          }
        }
      }
      // let mapAdd = rings.phase.map(item => {
      //   return {
      //     id: item.id,
      //     split: item.split
      //   }
      // })
      // let newRings = rings.rings.map(j => {
      //   return j.sequence
      // })
      // let newList = newRings.map(item => {
      //   let ret = []
      //   item.map(i => {
      //     const find = mapAdd.find(j => j.id === i)
      //     if (find) {
      //       ret.push(find)
      //     }
      //   })
      //   return ret
      // })
      // let mapAdds = newList.map(item => {
      //   return item.map(val => {
      //     return val.split
      //   })
      // })
      // let maxCycle = mapAdds.length > 0 ? mapAdds.map(item => {
      //   return item.length > 0 ? item.reduce((a, b) => {
      //     return a + b
      //   }) : 0
      // }) : 0
      let mapAdd = filterPattern.map(item => {
        return item.map(val => {
          return val.value + (val.sum ? val.sum : 0)
        })
      })
      let maxCycle = mapAdd.length > 0 ? mapAdd.map(item => {
        return item.length > 0 ? item.reduce((a, b) => {
          return a + b
        }) : 0
      }) : 0
      this.max = Math.max(...maxCycle)// 每个环的周期最大值
      this.getControl(filterPattern)
    },
    handleGetData (data) {
      let that = this
      if (data.name === '') {
        data.name = this.$t('openatccomponents.pattern.plan') + data.patternid
      }
      Object.keys(data).forEach(function (key) {
         if (key === 'mode') {
          if (data[key] > 0 && data[key] < 9) {
              data[key] = that.$t('openatccomponents.overview.ParamsMode' + data[key])
            } else {
              data[key] = that.$t('openatccomponents.overview.ParamsMode0')
            }
          }
          if (key === 'phase' || key === 'overlap') {
            for (let val of data[key]) {
              val.typestr = that.$t('openatccomponents.overview.phaseType' + val.type)
              val.pedtypestr = that.$t('openatccomponents.overview.phaseType' + val.pedtype)
            }
          }
      })
      return data
    },
    reconnectionDev () {
      this.registerMessage()
    },
    // queryDevParams () {
    //   queryDevice(this.AgentId).then(res => {
    //     if (!res.data.success) {
    //       this.isShowMessage && this.$message.error(getMessageByCode(res.data.code, this.$i18n.locale))
    //       return
    //     }
    //     let devParams = res.data.data.jsonparam
    //     this.ip = devParams.ip
    //     this.port = String(devParams.port)
    //     this.protocol = res.data.data.protocol
    //     this.agentId = res.data.data.agentid
    //     if (res.data.data.name) {
    //       this.agentName = res.data.data.name
    //     }
    //     this.platform = res.data.data.platform
    //     let state = res.data.data.state
    //     if (state === 'UP') {
    //       this.stateName = this.$t('openatccomponents.overview.online')
    //     } else {
    //       this.stateName = this.$t('openatccomponents.overview.offline')
    //     }
    //     this.registerMessage() // 注册消息
    //     this.initData()
    //     // 配置工具没参数的时候
    //     this.getIntersectionInfo(this.agentId)
    //     if (this.curHomePage === 'Channelization') {
    //       this.getDetectorStatus()
    //     }
    //   })
    // },
    getPhase () {
      uploadSingleTscParam('phase', this.agentId).then(data => {
        let res = data.data
        if (!res.success) {
          if (data.data.code === '4002' && data.data.data.errorCode === '4209') {
            let success = data.data.data.content.success
            if (success !== 0) {
              let errormsg = 'openatccomponents.overview.putTscControlError' + success
              this.isShowMessage && this.$message.error(this.$t(errormsg))
              return
            }
          }
          let parrenterror = getMessageByCode(data.data.code, this.$i18n.locale)
          if (data.data.data) {
            // 子类型错误
            let childErrorCode = data.data.data.errorCode
            if (childErrorCode) {
              let childerror = getMessageByCode(data.data.data.errorCode, this.$i18n.locale)
              this.isShowMessage && this.$message.error(parrenterror + ',' + childerror)
            }
          } else {
            this.isShowMessage && this.$message.error(parrenterror)
          }
          return
        }
        if (res.data.data && res.data.data.phaseList) {
          this.phaseList = res.data.data.phaseList
        }
      })
    },
    getPlatform () {
      queryDevice(this.AgentId).then(res => {
        if (!res.data.success) {
          this.isShowMessage && this.$message.error(getMessageByCode(res.data.code, this.$i18n.locale))
          return
        }
        let devParams = res.data.data.jsonparam
        this.ip = devParams.ip
        this.port = String(devParams.port)
        this.protocol = res.data.data.protocol
        this.agentId = res.data.data.agentid
        if (res.data.data.name) {
          this.agentName = res.data.data.name
        }
        this.platform = res.data.data.platform
        this.registerMessage() // 注册消息
      })
    },
    getDetectorStatus () {
      this.detIntervalFlag = false
      // let agentid = getIframdevid()
      return new Promise((resolve, reject) => {
        getDetectorStatus(this.agentId).then(data => {
          this.detIntervalFlag = true
          if (!data.data.success) {
            if (data.data.code === '4002' && data.data.data.errorCode === '4209') {
              let success = data.data.data.content.success
              if (success !== 0) {
                let errormsg = 'openatccomponents.overview.putTscControlError' + success
                console.log(this.$t(errormsg))
                return
              }
            }
            let parrenterror = getMessageByCode(data.data.code, this.$i18n.locale)
            if (data.data.data) {
            // 子类型错误
              let childErrorCode = data.data.data.errorCode
              if (childErrorCode) {
                let childerror = getMessageByCode(data.data.data.errorCode, this.$i18n.locale)
                console.log(parrenterror + ',' + childerror)
              }
            } else {
              console.log(parrenterror)
            }
            this.clearDetectorStatusTimer()
            return
          }
          this.detectorStatusData = JSON.parse(JSON.stringify(data.data.data))
          resolve(this.detectorStatusData)
        })
      })
    },
    handleDetectorTimer () {
      this.clearDetectorStatusTimer()
      if (this.detectorList.length > 0 || this.pedestrainDetectorList.length > 0) {
        this.detectorStatusTimer = setInterval(() => {
          if (this.detIntervalFlag) {
            this.getDetectorStatus()
          }
        }, 1000)
      }
    },
    handleClearInterval () {
      this.isResend = false
      this.clearPatternInterval() // 清除定时器
      this.clearVolumeInterval()
      this.clearDetectorStatusTimer()
      this.clearRegisterMessageTimer() // 清除定时器
    }
  },
  destroyed () {
    this.handleClearInterval()
    this.getPlatform()
  }
}
</script>
