/**
 * 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="channelization-with-interface">
      <Channelization
        ref="channelization"
        :AgentId="AgentId"
        :crossStatusData="crossStatusData"
        :detectorStatusData="detectorStatusData" />
  </div>
</template>
<script>
import Channelization from '../Channelization/Channelization'
import { getMessageByCode } from '../../../utils/responseMessage'
import { getTscControl, queryDevice, putTscControl } from '../../../api/control.js'
import { registerMessage, uploadSingleTscParam } from '../../../api/param'
import { setIframdevid, setToken, setHost } from '../../../utils/auth.js'
import ControlFormat from '../../../utils/ControlFormat.js'
import { getDetectorStatus } from '../../../api/cross'
export default {
  name: 'channelization-with-interface',
  components: {
    Channelization
  },
  data () {
    return {
      controlData: {},
      crossStatusData: {}, // 路口状态数据
      detectorStatusData: {}, // 检测器状态数据（包括车辆检测器状态和行人检测器状态）
      // devStatus: 1,
      isResend: true,
      intervalFlag: true,
      phaseControlTimer: null, // 定时器
      registerMessageTimer: null // 延时器
    }
  },
  props: {
    reqUrl: {
      type: String,
      default: ''
    },
    AgentId: {
      type: String,
      default: '0'
    },
    Token: {
      type: String,
      default: ''
    }
    // isShowInterval: {
    //   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, oldVal) {
        this.agentId = val
      },
      // 深度观察监听
      deep: true
    },
    Token: {
      handler: function (val) {
        this.setPropsToken(val)
      }
    }
  },
  methods: {
    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
          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.$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.$message.error(parrenterror + ',' + childerror)
            }
          } else {
            this.$message.error(parrenterror)
          }
          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) => {
        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.$message.error(this.$t(errormsg))
              return
            }
          }
          if (data.data.code === '4003') {
            // this.devStatus = 2
            this.clearPatternInterval() // 清除其他定时器
            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.$message.error(parrenterror + ',' + childerror)
            }
          } else {
            this.$message.error(parrenterror)
          }
          this.clearPatternInterval() // 清除其他定时器
          if (this.isResend) {
            this.reSend()
          }
          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)
        this.$emit('getTscControl', data)
      }).catch(error => {
        this.$message.error(error)
        console.log(error)
      })
    },
    reconnectionDev () {
      this.registerMessage()
    },
    queryDevParams () {
      let _this = this
      queryDevice(this.AgentId).then(res => {
        if (!res.data.success) {
          _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.$refs.intersectionMap.resetCrossDiagram()
        _this.registerMessage() // 注册消息
        _this.$emit('queryDevice', res)
        _this.getDetectorStatus()
      })
    },
    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.$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 === '4002' && data.data.data.errorCode === '4209') {
            let success = data.data.data.content.success
            if (success !== 0) {
              let errormsg = 'openatccomponents.overview.putTscControlError' + success
              this.$message.error(this.$t(errormsg))
              return
            }
          }
          if (data.data.code === '4003') {
            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.$message.error(parrenterror + ',' + childerror)
            }
          } else {
            this.$message.error(parrenterror)
          }
          return
        }
        let tscData = JSON.parse(JSON.stringify(res.data.data))
        let stageData = []
        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.$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.$message.error(this.$t('openatccomponents.errorTip.devicenotonline'))
            return
          }
          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
    },
    getDetectorStatus () {
      this.detIntervalFlag = false
      // let agentid = getIframdevid()
      return new Promise((resolve, reject) => {
        getDetectorStatus(this.agentId).then(data => {
          this.detIntervalFlag = true
          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)
            }
            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)
      }
    },
    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.agentId = this.AgentId
    this.setHost(this.reqUrl)
    this.controlFormat = new ControlFormat()
  },
  mounted () {
    setIframdevid(this.AgentId)
    this.resetIntersectionMap()
  },
  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>
