/**
 * 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="show-channelization channelization-base-map" :class="{
    'widescreenCrossImg': bodyDomWidth > 1680,
    'superlargeCrossImg': bodyDomWidth <= 1680 && bodyDomWidth > 1440,
    'largeCrossImg': bodyDomWidth <= 1440 && bodyDomWidth > 1280,
    'middleCrossImg2': bodyDomWidth <= 1280 && bodyDomWidth > 960,
    'smallCrossImg': bodyDomWidth <= 960 && bodyDomWidth > 890,
    'smallCrossImg2': bodyDomWidth <= 890 && bodyDomWidth > 720,
    'miniCrossImg': bodyDomWidth <= 720 && bodyDomWidth > 650,
    'superminiCrossImg': bodyDomWidth <= 650 && bodyDomWidth > 450,
    'transMiddleCrossImg': bodyDomWidth <= 450 && bodyDomWidth > 350,
    'transMiddleCrossImg2': bodyDomWidth <= 350 && bodyDomWidth > 300,
    'transMiddleCrossImg3': bodyDomWidth <= 300 && bodyDomWidth > 260,
    'transMiniCrossImg': bodyDomWidth <= 260,
    'changePaddingBottom': true }">
    <ChannelizationElements
      ref="channelizationElements"
      UsageMode="show"
      :allitem="allitem"
      :CrossMapVisible="CrossMapVisible"
      :CrossMapData="CrossMapData"
      :isSeletable="isSeletable"
      :Motorways="LanePhaseData"
      :Pedwalk="sidewalkPhaseData"
      :Countdown="Countdown"
      :CountdownList="phaseCountdownList"
      :Detector="DetectorData"
      :isHasPhase="isHasPhase"
    />
  </div>
</template>

<script>
// import { mapState, mapGetters } from 'vuex'
import ChannelizationElements from '../DrawChannelization/drawsvg/channelizationElements'
// import { getIframdevid } from '../../../utils/auth.js'
import { getChannelizatonChart } from '../../../api/cross'

export default {
  name: 'channelization',
  components: {
    ChannelizationElements
  },
  computed: {
    // ...mapState({
    //   curOpenatcAgentid: state => state.globalParam.curOpenatcAgentid
    // })
    // ,
    // ...mapGetters([
    //   'isfromatc'
    // ])
  },
  props: {
    crossStatusData: {
      type: Object
    },
    detectorStatusData: {
      type: Object
    },
    AgentId: {
      type: String,
      default: '0'
    }
  },
  watch: {
    crossStatusData: {
      handler: function (val) {
        // 路口状态数据
        this.statusData = JSON.parse(JSON.stringify(val))
        this.phaseStatusList = val.phase
        this.overlapStatusList = val.overlap
        if (val.control === 1 || val.control === 2 || val.control === 3) {
          // 黄闪、全红、关灯属于特殊控制，优先级最高，直接改变灯色，不用判断phase里的type，也不需要考虑跟随相位的灯色优先级
          if (val.control === 1) {
            this.getYellowFlashColor()
          } else {
            this.SpecialControl(val)
          }
          return
        }
        if (!val.phase && !this.overlapStatusList) {
          // 非特殊控制，相位和跟随相位不存在的情况下，灯色恢复默认
          this.handleSpecialControlStatus('默认')
          return
        }
        this.curPhase = val.current_phase
        this.isHasPhase = true
        this.createPhaseStatusMap()
        this.createOverlapPhaseStatusMap()
        this.getLanePhaseStatusData()
        this.getpedStatus()
        this.getCurPhaseCountdown()
      },
      // 深度观察监听
      deep: true
    },
    detectorStatusData: {
      handler: function (detectorsStatus) {
        // 检测器状态数据
        this.detectorStatusList = detectorsStatus.detector
        this.pedDetectorStatusList = detectorsStatus.io
        this.createDetectorStatusMap()
        this.getDetectorStatus()
      },
      deep: true
    },
    AgentId: {
      handler: function (val) {
        // 平台设备切换时，重载当前路口保存的渠化配置
        this.load('all')
      },
      deep: true
    }
  },
  data () {
    return {
      isSeletable: false,
      bodyDomWidth: 352,
      bodyDomSize: {
        width: 1920,
        height: 1080
      },
      CrossMapVisible: true, // 控制底图显示隐藏
      CrossMapData: {
        x: 400,
        y: 100,
        w: 800,
        h: 200,
        angle: 0,
        svgstr: '',
        imgfilesrc: ''
      }, // 管理底图数据
      Motorways: [],
      Texts: [],
      Pedwalk: [],
      Countdown: [],
      Detector: [],
      allitem: {
        x: 435,
        y: 325,
        w: 870,
        h: 650,
        angle: 0
      },
      LanePhaseData: [], // 车道相位数据
      // overlapLanePhaseData: [], // 车道跟随相位数据
      curPhase: [], // 当前相位列表
      phaseStatusList: [], // 相位状态列表
      phaseStatusMap: new Map(), // 相位状态映射
      phaseCountdownList: [], // 相位倒计时列表
      overlapPhaseStatusMap: new Map(), // 跟随相位状态映射
      ColorMap: new Map([[0, '#828282'], [1, '#ff2828'], [2, '#f7b500'], [3, '#77fb65'], [4, '#77fb65'], [5, '#f7b500']]), // 当前相位状态 --- 0：关灯, 1：红, 2：黄,  3：绿, 4：绿闪, 5：黄闪
      SidewalkColorMap: new Map([[0, '#828282'], [1, '#e24b4b'], [3, '#7bd66b']]),
      phaseControlColorMap: new Map([['黄闪', '#f7b500'], ['全红', '#ff2828'], ['关灯', '#828282'], ['默认', '#fff']]),
      sidewalkPhaseData: [], // 行人相位
      isHasPhase: true, // 是否有相位状态数据

      detectorStatusList: [], // 车辆检测器状态列表
      pedDetectorStatusList: [], // 行人检测器状态列表
      detectorStatusMap: new Map(), // 车辆检测器状态映射
      pedDetectorStatusMap: new Map(), // 行人检测器状态映射
      DetectorData: [], // 检测器数据（包括车辆和行人）
      DetectorColorMap: new Map([[0, 'transparent'], [1, '#00CCFF'], [2, '#FF0000']]) // 检测器状态填充颜色定义 0: 低电平 无车, 1: 高电平 有车, 2: 故障
    }
  },
  methods: {
    createPhaseStatusMap () {
      // 生成相位id和相位状态对应数据结构
      this.phaseStatusList.map(phase => {
        let phaseId = phase.id
        let phaseInfo = {
          type: phase.type,
          phaseCountdown: phase.countdown,
          pedtype: phase.pedtype
        }
        this.phaseStatusMap.set(phaseId, phaseInfo)
      })
    },
    createOverlapPhaseStatusMap () {
      if (this.overlapStatusList) {
        this.overlapStatusList.map(phase => {
          let phaseId = phase.id
          let phaseInfo = {
            type: phase.type,
            phaseCountdown: phase.countdown,
            pedtype: phase.pedtype
          }
          this.overlapPhaseStatusMap.set(phaseId, phaseInfo)
        })
      }
    },
    getLanePhaseStatusData () {
      let curLanePhaseData = []
      for (let i = 0; i < this.LanePhaseData.length; i++) {
        let curPhaseStatus
        if (this.LanePhaseData[i].phasetype === 'phase') {
          curPhaseStatus = this.phaseStatusMap.get(this.LanePhaseData[i].phaseid)
        }
        if (this.LanePhaseData[i].phasetype === 'overlap') {
          curPhaseStatus = this.overlapPhaseStatusMap.get(this.LanePhaseData[i].phaseid)
        }
        // if (!curPhaseStatus) continue // 没有关联相位的车道不显示
        let data
        if (curPhaseStatus) {
          data = {
            ...this.LanePhaseData[i],
            type: curPhaseStatus.type,
            color: this.ColorMap.get(curPhaseStatus.type),
            phaseCountdown: curPhaseStatus.phaseCountdown,
            flag: 'phase' // 车道相位数据标识
          }
        } else {
          // 没有关联的，或者没有对应状态的，车道显示默认白色
          data = {
            ...this.LanePhaseData[i],
            type: undefined,
            color: '#fff',
            flag: 'phase' // 车道相位数据标识
          }
        }
        curLanePhaseData.push(data)
      }
      this.LanePhaseData = JSON.parse(JSON.stringify(curLanePhaseData))
      // console.log(this.LanePhaseData)
    },
    getpedStatus () {
      // 行人相位状态
      let curPedStatus = []
      for (let i = 0; i < this.sidewalkPhaseData.length; i++) {
        let curPhaseStatus
        if (this.sidewalkPhaseData[i].phasetype === 'phase') {
          curPhaseStatus = this.phaseStatusMap.get(this.sidewalkPhaseData[i].phaseid)
        }
        if (this.sidewalkPhaseData[i].phasetype === 'overlap') {
          curPhaseStatus = this.overlapPhaseStatusMap.get(this.sidewalkPhaseData[i].phaseid)
        }
        // if (!curPhaseStatus) continue
        let data
        if (curPhaseStatus) {
          data = {
            ...this.sidewalkPhaseData[i],
            pedtype: curPhaseStatus.pedtype,
            color: this.SidewalkColorMap.get(curPhaseStatus.pedtype),
            flag: 'ped' // 行人相位数据标识
          }
        } else {
          // 接口没有对应的状态
          data = {
            ...this.sidewalkPhaseData[i],
            pedtype: undefined,
            color: '#fff',
            flag: 'ped' // 行人相位数据标识
          }
        }
        curPedStatus.push(data)
      }
      this.sidewalkPhaseData = JSON.parse(JSON.stringify(curPedStatus))
      // this.Pedwalk = JSON.parse(JSON.stringify(this.sidewalkPhaseData))
    },
    getCurPhaseCountdown () {
      // 获取当前相位倒计时颜色
      let phaseCountdownList = []
      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)
            phaseCountdownList.push(countdownObj)
          }
        })
      })
      this.phaseCountdownList = JSON.parse(JSON.stringify(phaseCountdownList))
      // console.log(this.phaseCountdownList)
    },
    // 加载
    load (type) {
      this.getChannelizatonChart().then((channelizatondata) => {
        let savedTemp = JSON.parse(JSON.stringify(channelizatondata))
        for (const [key, value] of Object.entries(savedTemp)) {
          if (key === 'vehile') {
            this.Motorways = value
          }
          if (key === 'text') {
            this.Texts = value
          }
          if (key === 'ped') {
            this.Pedwalk = value
          }
          if (key === 'countdown') {
            this.Countdown = value
          }
          if (key === 'detector') {
            this.Detector = value.filter(ele => ele.detailtype === 'detector')
          }
          if (key === 'crossMap') {
            this.CrossMapData = JSON.parse(JSON.stringify(value))
          }
        }
        this.isSeletable = false
        // 从接口得到所有渠化车道和人行道数据
        this.LanePhaseData = JSON.parse(JSON.stringify(this.Motorways))
        this.sidewalkPhaseData = JSON.parse(JSON.stringify(this.Pedwalk))
        this.DetectorData = JSON.parse(JSON.stringify(this.Detector))
      })
    },
    // 重置
    handleReset () {
      this.Texts = []
      this.Motorways = []
      this.Countdown = []
      this.phaseCountdownList = []
      this.Pedwalk = []
      this.Detector = []
      this.CrossMapData = {
        x: 400,
        y: 100,
        w: 800,
        h: 200,
        angle: 0,
        svgstr: '',
        imgfilesrc: ''
      }
      this.LanePhaseData = []
      this.sidewalkPhaseData = []
      this.DetectorData = []
      this.isHasPhase = true
    },
    getChannelizatonChart () {
      // let agentid = getIframdevid()
      // 路口已设置渠化，则总览默认显示渠化路口，未设置显示模版路口
      // if (this.isfromatc === true) {
      //   this.$store.dispatch('SetShowHomePage', 'Graphical')
      // }
      this.handleReset()
      return new Promise((resolve, reject) => {
        getChannelizatonChart(this.AgentId).then(data => {
          // this.$emit('getChannelizationSetting', 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.$message.error(parrenterror + ',' + childerror)
            //   }
            // } else {
            //   this.$message.error(parrenterror)
            // }
            return
          }
          if (data.data.data === undefined || JSON.stringify(data.data.data) === '{}') return
          // if (this.isfromatc === true) {
          //   this.$store.dispatch('SetShowHomePage', 'Channelization')
          // }
          this.handleReset()
          let channelizatondata = data.data.data
          resolve(channelizatondata)
        })
      })
    },
    SpecialControl (data) {
      switch (data.control) {
        case 1: this.handleSpecialControlStatus('黄闪')
          break
        case 2: this.handleSpecialControlStatus('全红')
          break
        case 3: this.handleSpecialControlStatus('关灯')
          break
        default: this.handleSpecialControlStatus('默认')
      }
    },
    handleSpecialControlStatus (Control) {
      this.$refs.channelizationElements.resetPhaseStatus()
      // 控制黄闪、全红、关灯、默认情况下的车道相位颜色和倒计时颜色
      if (Control === '默认') {
        // 倒计时恢复默认颜色
        this.phaseCountdownList.forEach(item => {
          item.phaseCountdown = ''
          item.id = ''
          item.phaseCountdownColor = '#fff'
        })
      }
      if (this.LanePhaseData.length) {
        const LanePhaseData = this.LanePhaseData.map(data => ({
          ...data,
          color: this.phaseControlColorMap.get(Control)
        }))
        this.LanePhaseData = JSON.parse(JSON.stringify(LanePhaseData))
      }
      if (this.sidewalkPhaseData.length) {
        const sidewalkPhaseData = this.sidewalkPhaseData.map(data => ({
          ...data,
          color: this.phaseControlColorMap.get(Control)
        }))
        this.sidewalkPhaseData = JSON.parse(JSON.stringify(sidewalkPhaseData))
      }
      this.isHasPhase = false
    },
    createDetectorStatusMap () {
      this.detectorStatusMap = new Map()
      if (this.detectorStatusList) {
        this.detectorStatusList.map(detector => {
          let detectorId = detector.id
          let detectorInfo = {
            state: detector.state,
            queue: detector.q
          }
          this.detectorStatusMap.set(detectorId, detectorInfo)
        })
      }
      if (this.pedDetectorStatusList) {
        this.pedDetectorStatusList.map(peddetector => {
          let peddetectorId = peddetector.id
          let peddetectorInfo = {
            state: peddetector.state
          }
          this.pedDetectorStatusMap.set(peddetectorId, peddetectorInfo)
        })
      }
      // console.log(this.detectorStatusMap)
      // console.log(this.pedDetectorStatusMap)
    },
    getDetectorStatus () {
      let curDetectorData = []
      for (let i = 0; i < this.DetectorData.length; i++) {
        let curDetectorStatus
        let curDetectortype = this.DetectorData[i].detectortype
        if (curDetectortype === 1) {
          // 车辆检测器
          curDetectorStatus = this.detectorStatusMap.get(this.DetectorData[i].detectorid)
        }
        if (curDetectortype === 2) {
          // 行人检测器
          curDetectorStatus = this.pedDetectorStatusMap.get(this.DetectorData[i].detectorid)
        }
        // if (!curDetectorStatus) continue // 没有关联检测器不显示
        let data
        if (curDetectorStatus) {
          data = {
            ...this.DetectorData[i],
            state: curDetectorStatus.state,
            queue: curDetectorStatus.queue,
            fillcolor: this.DetectorColorMap.get(curDetectorStatus.state),
            flag: curDetectortype === 1 ? 'detector' : 'peddetector' // 车道相位数据标识
          }
        } else {
          // 没有关联检测器的填充透明
          data = {
            ...this.DetectorData[i],
            state: undefined,
            queue: undefined,
            fillcolor: 'transparent',
            flag: curDetectortype === 1 ? 'detector' : 'peddetector' // 车道相位数据标识
          }
        }
        curDetectorData.push(data)
      }
      this.DetectorData = JSON.parse(JSON.stringify(curDetectorData))
    },
    getParentSize () {
      // 获取最外层dom尺寸，适配准备
      var _this = this
      this.$nextTick(function () {
        if (this.$el.parentElement === null || this.$el.parentElement === undefined) return
        this.bodyDomSize.width = this.$el.parentElement.clientWidth
        this.bodyDomWidth = this.bodyDomSize.width
        window.addEventListener('resize', () => {
        // 定义窗口大小变更通知事件
          if (_this.$el.parentElement === null || _this.$el.parentElement === undefined) return
          _this.bodyDomSize.width = _this.$el.parentElement.clientWidth
          this.bodyDomWidth = this.bodyDomSize.width
          console.log('resize this.bodyDomSize.width', _this.bodyDomSize.width)
        }, false)
      })
    },
    getYellowFlashColor () {
      // 渠化车道相位
      let curLanePhaseData = []
      for (let i = 0; i < this.LanePhaseData.length; i++) {
        const data = {
          ...this.LanePhaseData[i],
          type: '黄闪',
          control: 1
        }
        curLanePhaseData.push(data)
      }
      this.LanePhaseData = JSON.parse(JSON.stringify(curLanePhaseData))

      // 渠化行人相位
      let curPedStatus = []
      for (let i = 0; i < this.sidewalkPhaseData.length; i++) {
        const data = {
          ...this.sidewalkPhaseData[i],
          pedtype: '黄闪',
          control: 1
        }
        curPedStatus.push(data)
      }
      this.sidewalkPhaseData = JSON.parse(JSON.stringify(curPedStatus))
    }
  },
  created () {
    this.load()
  },
  mounted () {
    this.getParentSize()
  },
  destroyed () {
    this.handleReset()
  }
}
</script>

<style lang="css" rel="stylesheet/scss">
  .show-channelization {
    position: relative;
    overflow: hidden;
  }
  .widescreenCrossImg {
    zoom: 1.3;
  }
  .superlargeCrossImg {
    zoom: 1.1;
  }
  .largeCrossImg {
    zoom: 1.1;
  }
  .middleCrossImg {
    zoom: 1;
  }
  .middleCrossImg2 {
    zoom: 0.8;
  }
  .smallCrossImg {
    zoom: 0.8;
  }
  .smallCrossImg2 {
    zoom: 0.8;
  }
  .miniCrossImg {
    zoom: 0.7;
  }
  .superminiCrossImg {
    zoom: 0.6;
  }
  .minimumCrossImg {
    zoom: 0.35;
  }
  .transMiddleCrossImg {
    -webkit-transform-origin-y: 0;
     transform: scale(0.55);
     margin-top: 3%;
     padding: 0PX;
   }
   .transMiddleCrossImg2 {
    -webkit-transform-origin-y: 0;
     transform: scale(0.27);
     margin-top: -1.5%;
     padding: 0PX;
   }
   .transMiddleCrossImg3 {
    -webkit-transform-origin-y: 0;
     transform: scale(0.22);
     margin-top: -1%;
     padding: 0PX;
   }
   .transMiniCrossImg {
    -webkit-transform-origin-y: 0;
     transform: scale(0.18);
     margin-top: -1.6%;
     padding: 0PX;
   }
</style>
