/**
 * 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.
 **/
 <!--动态路口图，只需要设备AgentId，此组件会处理方案状态接口轮询-->
<template>
  <div class="intersection-with-interface">
      <IntersectionMap
        ref="intersectionMap"
        :crossStatusData="crossStatusData"
        :agentId="agentId"
        :graphicMode="true"
        :roadDirection="roadDirection"
        :modeName="modeName !== '' ? modeName : controlData.mode"
        :controlName="controlName !== '' ? controlName : controlData.control"
        :stateName="stateName"
        :isShowMode="isShowMode"
        :isShowState="isShowState"
        :isShowMessage ="isShowMessage"
        :isShowInterval="isShowInterval"
        @onSelectStages="onSelectStages"/>
  </div>
</template>
<script>
/* eslint-disable */
import IntersectionMap from '../IntersectionMap'
import { getMessageByCode } from '../../../utils/responseMessage'
import { getTscControl, queryDevice, putTscControl } from '../../../api/control.js'
import { registerMessage, uploadSingleTscParam } from '../../../api/param'
import { getIframdevid, setIframdevid, setToken, setHost } from '../../../utils/auth.js'
import ControlFormat from '../../../utils/ControlFormat.js'
export default {
  name: 'intersection-with-interface',
  components: {
    IntersectionMap
  },
  data () {
    return {
      stateName: this.$t('openatccomponents.overview.offline'),
      controlData: {},
      boxVisible: false,
      dialogWidth: '100%',
      crossStatusData: {}, // 路口状态数据
      // devStatus: 1,
      isResend: true,
      intervalFlag: true,
      phaseControlTimer: null, // 定时器
      registerMessageTimer: null // 延时器
    }
  },
  props: {
    reqUrl: {
      type: String,
      default: ''
    },
    AgentId: {
      type: String
    },
    Token: {
      type: String,
      default: ''
    },
    roadDirection: {
      type: String,
      default: 'right'
    },
    isShowInterval: {
      type: Boolean,
      default: true
    },
    isShowMessage: {
      type: Boolean,
      default: true
    },
    isShowState: {
      type: Boolean,
      devault: false
    },
    isShowMode: {
      type: Boolean,
      default: false
    },
    modeName: {
      type: String,
      default: ''
    },
    controlName: {
      type: String,
      default: ''
    }
  },
  watch: {
    AgentId: {
      handler: function (val) {
        this.agentId = val
      },
      // 深度观察监听
      deep: true,
      immediate: true
    },
    Token: {
      handler: function (val) {
        this.setPropsToken(val)
      }
    }
  },
  methods: {
    oncancle () {
      this.boxVisible = false
    },
    handleOpenConfigPanel () {
      this.boxVisible = true
    },
    setDialogWidth () {
      var val = document.body.offsetWidth
      const def = 1200 // 默认宽度
      if (val < def) {
        this.dialogWidth = '100%'
      } else {
        this.dialogWidth = def + 'px'
      }
    },
    resetIntersectionMap () {
      this.setPropsToken(this.Token)
      this.firstInit()
      this.$refs.intersectionMap.resetCrossDiagram()
      this.initData()
    },
    registerMessage () {
      registerMessage(this.AgentId).then(data => {
        if (!data.data.success) {
          // this.devStatus = 2
          let commomMsg = this.$t('openatccomponents.overview.signalID') + ' : ' + this.AgentId
          let msg = getMessageByCode(data.data.code, this.$i18n.locale)
          if (data.data.data) {
            let errorCode = data.data.data.errorCode
            if (errorCode) {
              msg = msg + ' - ' + getMessageByCode(errorCode, this.$i18n.locale)
            }
          }
          msg = msg + ' - ' + commomMsg
          this.isShowMessage && this.$message.error(msg)
          if (this.isResend) {
            this.reSend()
          }
          return
        }
        this.$emit('registerMessage', data)
        // this.devStatus = 3
        this.clearPatternInterval() // 清除其他定时器
        this.phaseControlTimer = setInterval(() => {
          if (this.intervalFlag) {
            this.initData()
          }
        }, 1000)
      })
    },
    reSend () { // 设备掉线重连机制
      // this.devStatus = 1
      this.clearRegisterMessageTimer()
      this.registerMessageTimer = setTimeout(() => {
        this.reconnectionDev()
      }, 5000)
    },
    clearPatternInterval () {
      if (this.phaseControlTimer !== null) {
        clearInterval(this.phaseControlTimer) // 清除定时器
        this.phaseControlTimer = null
      }
    },
    clearRegisterMessageTimer () {
      if (this.registerMessageTimer !== null) {
        clearTimeout(this.registerMessageTimer) // 清除延时器
        this.registerMessageTimer = null
      }
    },
    initData () {
      this.intervalFlag = false
      let iframdevid = getIframdevid()
      console.log(iframdevid)
      let startTime = new Date().getTime()
      getTscControl(this.AgentId).then((data) => {
        this.$emit('getTscControl', data)
        let endTime = new Date().getTime()
        let diffTime = endTime - startTime
        this.responseTime = diffTime
        this.intervalFlag = true
        console.log(data, 'datad')
        if (!data.data.success) {
          let commomMsg = this.$t('openatccomponents.overview.signalID') + ' : ' + this.AgentId
          if (data.data.code === '4003') {
            // this.devStatus = 2
            this.clearPatternInterval() // 清除其他定时器
            this.clearVolumeInterval()
            this.isShowMessage && this.$message.error(getMessageByCode(data.data.code, this.$i18n.locale) + ' - ' + commomMsg)
            if (this.isResend) {
              this.reSend()
            }
            return
          }
          let msg = 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)
              msg = msg + ' - ' + childerror
            }
          }
          msg = msg + ' - ' + commomMsg
          this.isShowMessage && this.$message.error(msg)
          this.clearPatternInterval() // 清除其他定时器
          if (this.isResend) {
            this.reSend()
          }
          return
        }
        if (!data.data.data.data) return
        this.crossStatusData = JSON.parse(JSON.stringify(data.data.data.data))
        let param = JSON.parse(JSON.stringify(data.data.data.data))
        // this.controlData = this.handleGetData(param)
        this.controlData = this.controlFormat.handleGetData(param, this.$i18n)
      }).catch(error => {
        this.isShowMessage && this.$message.error(error)
        console.log(error)
      })
    },
    reconnectionDev () {
      this.registerMessage()
    },
    queryDevParams () {
      let _this = this
      queryDevice(this.AgentId).then(res => {
        if (!res.data.success) {
          let commomMsg = this.$t('openatccomponents.overview.signalID') + ': ' + this.AgentId
          let msg = getMessageByCode(res.data.code, this.$i18n.locale) + ', ' + commomMsg
          this.isShowMessage && this.$message.error(msg)
          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.$refs.intersectionMap.resetCrossDiagram()
        _this.registerMessage() // 注册消息
        _this.$emit('queryDevice', res)
      })
    },
    firstInit () {
      if (this.$route.query !== undefined && Object.keys(this.$route.query).length && this.$route.query.agentid !== undefined) {
        this.agentId = this.$route.query.agentid
        setIframdevid(this.agentId)
        this.registerMessage() // 注册消息
      } else {
        this.queryDevParams() // 查询设备信息
      }
    },
    destroyIntersectionMap () {
      this.isResend = false
      this.clearPatternInterval() // 清除定时器
      this.clearRegisterMessageTimer() // 清除定时器
    },
    setPropsToken (token) {
      // 获取组件外传入的token，便于独立组件调用接口
      if (token && token !== '') {
        setToken(token)
      }
    },
    setHost (host) {
      // 获取组件外传入的token，便于独立组件调用接口
      if (host && host !== '') {
        setHost(host)
      }
    },
    async doPatternCommit (control) {
      let that = this
      let resData
      await putTscControl(control, this.agentId).then(data => {
        resData = data
        let success = 0
        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
            }
          }
          that.$message.error(getMessageByCode(data.data.code, that.$i18n.locale))
          return
        }
        if (data.data.data && data.data.data.data) {
          success = data.data.data.data.success
          if (success !== 0) {
            let errormsg = 'openatccomponents.overview.putTscControlError' + success
            that.$message.error(this.$t(errormsg))
            return
          }
        }
        // this.closeManualModal()
        if (success === 0) {
          that.$message.success(this.$t('openatccomponents.common.download'))
        }
      }).catch(error => {
        that.$message.error(error)
        console.log(error)
      })
      return resData
    },
    async getTscControlInfo () {
      await getTscControl(this.agentId).then((data) => {
        let res = data
        this.controlInfo = {
          tscData: null,
          stageData: null,
          controlData: null
        }
        if (!data.data.success) {
          if (data.data.code === '4003') {
            this.isShowMessage && this.$message.error(getMessageByCode(data.data.code, this.$i18n.locale))
            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
        }
        let tscData = JSON.parse(JSON.stringify(res.data.data))
        let stageData = []
        // stageData = this.handleStageData(tscData) // 处理阶段（驻留）stage数据
        let controlData = {}
        let param = Object.assign({}, tscData)
        controlData = this.controlFormat.handleGetData(param, this.$i18n)
        this.controlData = controlData
        this.controlInfo = {
          tscData: tscData,
          stageData: stageData,
          controlData: controlData
        }
      }).catch(error => {
        this.isShowMessage && this.$message.error(error)
        console.log(error)
      })
    },
    async getPhase () {
      await uploadSingleTscParam('phase', 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'))
            return
          }
          this.isShowMessage && this.$message.error(getMessageByCode(data.data.code, this.$i18n.locale))
          return
        }
        this.phaseList = res.data.data.phaseList
      })
    },
    async getPhaseInfo () {
      await this.getPhase()
      let res = [...this.phaseList]
      return res
    },
    async getControlInfo () {
      await this.getTscControlInfo()
      // let res = this.controlInfo.controlData
      let res = this.controlInfo.tscData
      return res
    },
    clearInterVals () {
      this.clearPatternInterval() // 清除定时器
      this.clearRegisterMessageTimer() // 清除定时器
    },
    onSelectStages (value) {
      this.currentStage = value
      this.$emit('onSelectStages', value)
    },
    async lockPhase (reqData) {
      let res = await this.doPatternCommit(reqData)
      return res
    },
    async unlockPhase (reqData) {
      let res = await this.doPatternCommit(reqData)
      return res
    },
    async changeControlPattern (reqData) {
      let res = await this.doPatternCommit(reqData)
      return res
    },
    getBusPos () {
      // 公交相位信息
      this.busPhaseData = []
      this.phaseList.forEach((ele, i) => {
        if (ele.controltype >= 3 && ele.controltype <= 5) {
          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,
              controltype: ele.controltype
            })
          })
        }
      })
      let result = []
      let obj = {}
      for (var i = 0; i < this.busPhaseData.length; i++) {
        if (!obj[this.busPhaseData[i].phaseid]) {
          result.push(this.busPhaseData[i])
          obj[this.busPhaseData[i].phaseid] = true
        }
      }
      this.busPhaseData = result
    },
    handleStageData (data) {
      this.getBusPos()
      this.stagesList = []
      let busPhaseData = this.busPhaseData
      let stages = data.stages
      if (!stages) return
      let stagesTemp = []
      for (let stage of stages) {
        let tempList = []
        let directionList = []
        let stageControType = 0
        let peddirections = []
        for (let stg of stage) {
          let currPhase = this.phaseList.filter((item) => {
            return item.id === stg
          })[0]
          if (currPhase !== undefined) {
            directionList = [...currPhase.direction, ...directionList]
          }
          for (let walk of this.sidewalkPhaseData) {
            if (stg === walk.phaseid) {
              peddirections.push(...currPhase.peddirection)
              peddirections = Array.from(new Set(peddirections))
            }
          }
          for (let busPhase of busPhaseData) {
            if (stg === busPhase.phaseid) {
              stageControType = busPhase.controltype
            }
          }
        }
        directionList = [...new Set(directionList)]
        if (directionList.length === 0) return
        tempList = directionList.map(dir => ({
          id: dir,
          color: '#606266',
          controltype: stageControType,
          peddirection: peddirections
        }))
        stagesTemp.push(tempList)
      }
      this.stagesList = JSON.parse(JSON.stringify(stagesTemp))
      // 相位变化时触发回调
      if (this.currentStage !== data.current_stage) {
        this.$emit('onPhaseChange', this.stagesList, data.current_stage)
      }
      this.currentStage = data.current_stage
    }
  },
  created () {
    this.setDialogWidth()
    this.setHost(this.reqUrl)
    this.controlFormat = new ControlFormat()
  },
  mounted () {
    setIframdevid(this.AgentId)
    this.resetIntersectionMap()
    window.onresize = () => {
      return (() => {
        this.setDialogWidth()
      })()
    }
  },
  destroyed () {
    this.destroyIntersectionMap()
  }
}
</script>
<style lang="scss">
.abow_dialog {
    display: flex;
    justify-content: center;
    align-items: Center;
    overflow: hidden;
    .el-dialog {
        margin: 0 auto !important;
        height: 90%;
        overflow: hidden;
        .el-dialog__body {
            position: absolute;
            left: 0;
            top: 54px;
            bottom: 0;
            right: 0;
            padding: 0;
            z-index: 1;
            overflow-y: auto;
            overflow-x: auto;
        }
    }
}
</style>
