/**
 * 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="LanePhaseStatisticsData"
      :Pedwalk="sidewalkPhaseData"
      :Countdown="Countdown"
      :customText="customText"
      :textFontSize="textFontSize"
      :Detector="DetectorData"
      :bcgColor="bcgColor"
    />
  </div>
</template>

<script>
import ChannelizationElements from '../DrawChannelization/drawsvg/channelizationElements'
import { getChannelizatonChart } from '../../../api/cross'

export default {
  name: 'channelization-flow-statistic',
  components: {
    ChannelizationElements
  },
  computed: {
  },
  props: {
    phasesStatisticsList: {
      type: Array,
      default: () => []
    },
    AgentId: {
      type: String,
      default: '0'
    },
    resizeMap: { // 重新获取容器大小，调整底图大小
      type: Boolean,
      default: false
    },
    customText: {
      type: String
    },
    bcgColor: {
      type: String
    },
    textFontSize: {
      type: String
    }
  },
  watch: {
    phasesStatisticsList: {
      handler: function (val) {
        // 相位统计数据数据
        this.phasesStatisticsData = JSON.parse(JSON.stringify(val))
        this.createPhaseStatisticsMap()
        this.getLanePhaseStatusData()
      },
      // 深度观察监听
      deep: true
    },
    AgentId: {
      handler: function (val) {
        // 平台设备切换时，重载当前路口保存的渠化配置
        this.load('all')
      },
      deep: true
    },
    resizeMap: {
      handler: function (newval, oldval) {
        if (newval === true && oldval === false) {
          this.getParentSize()
        }
      }
    }
  },
  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
      },
      LanePhaseStatisticsData: [], // 车道相位数据
      phasesStatisticsMap: new Map(), // 相位统计数据映射
      colorMap: new Map([['A', '#009900'], ['B', '#00FF00'], ['C', '#FFFF00'], ['D', '#FF9900'], ['E', '#FF0000'], ['F', '#990000']]),
      sidewalkPhaseData: [], // 行人相位
      DetectorData: [] // 检测器数据（包括车辆和行人）
    }
  },
  methods: {
    createPhaseStatisticsMap () {
      // 生成相位id和相位状态对应数据结构
      this.phasesStatisticsData.map(phase => {
        let phaseId = phase.phaseno
        let phaseInfo = {
          time: phase.time,
          ...phase.phasestatistics
        }
        this.phasesStatisticsMap.set(phaseId, phaseInfo)
      })
    },
    getLanePhaseStatusData () {
      let curLanePhaseData = []
      for (let i = 0; i < this.LanePhaseStatisticsData.length; i++) {
        let curPhaseStatus
        if (this.LanePhaseStatisticsData[i].phasetype === 'phase') {
          console.log(this.phasesStatisticsMap)
          curPhaseStatus = this.phasesStatisticsMap.get(this.LanePhaseStatisticsData[i].phaseid)
        }
        // if (!curPhaseStatus) continue // 没有关联相位的车道不显示
        let data
        if (curPhaseStatus) {
          data = {
            ...this.LanePhaseStatisticsData[i],
            congestionindex: curPhaseStatus.congestionindex,
            color: this.colorMap.get(curPhaseStatus.congestionindex)
          }
        } else {
          // 没有关联的，或者没有对应状态的，车道显示默认白色
          data = {
            ...this.LanePhaseStatisticsData[i],
            congestionindex: undefined,
            color: '#fff'
          }
        }
        curLanePhaseData.push(data)
      }
      this.LanePhaseStatisticsData = JSON.parse(JSON.stringify(curLanePhaseData))
    },
    // 加载
    load (type) {
      this.getChannelizatonChart().then((channelizatondata) => {
        console.log(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.LanePhaseStatisticsData = JSON.parse(JSON.stringify(this.Motorways))
        this.sidewalkPhaseData = JSON.parse(JSON.stringify(this.Pedwalk))
        this.DetectorData = JSON.parse(JSON.stringify(this.Detector))
        this.getLanePhaseStatusData()
      })
    },
    // 重置
    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.LanePhaseStatisticsData = []
      this.sidewalkPhaseData = []
      this.DetectorData = []
    },
    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 => {
          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)
        })
      })
    },
    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)
      })
    }
  },
  created () {
    this.load()
  },
  mounted () {
    this.getParentSize()
    this.phasesStatisticsData = JSON.parse(JSON.stringify(this.phasesStatisticsList))
    this.createPhaseStatisticsMap()
  },
  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>
