/**
 * 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="direction-list-configuration">
    <div class="dir-config-row">
      <div class="label" :style="{width: labelWidth}">{{$t('openatccomponents.phase.desc')}}：</div>
      <div class="dir-btn lane-dir">
        <div class="each-icon" v-for="(item, index) in laneList" :key="index" :class="item.disabled ? 'disabled-icon': ''">
          <el-tooltip class="item" effect="dark" :content="item.name" placement="bottom-start">
            <div class="single-icon"
              @click="selectDire(item, 'lane')"
              :class="!item.disabled && preselectDirection.indexOf(item.id) !== -1 ? 'single-icon-select' : ''">
              <i :class="item.iconclass"></i>
              <div class="single-icon-name">{{item.name}}</div>
            </div>
          </el-tooltip>
        </div>
      </div>
    </div>
    <div class="dir-config-row">
      <div class="label" :style="{width: labelWidth}">{{$t('openatccomponents.phase.peddesc')}}：</div>
      <div class="dir-btn ped-dir">
        <div class="each-icon" v-for="(item, index) in pedList" :key="index" :class="item.disabled ? 'disabled-icon': ''">
          <el-tooltip class="item" effect="dark" :content="item.name" placement="bottom-start">
            <div class="single-icon ped-icon"
            @click="selectDire(item, 'ped')"
            :class="!item.disabled && preselectPedDirection.indexOf(item.id) !== -1 ? 'single-icon-select' : ''">
              <PedSvg :pedId="item.id" />
              <div class="single-icon-name" style="margin-top: 5px;">{{item.name}}</div>
            </div>
          </el-tooltip>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import xdrdirselector from '../XRDDirSelector/XRDDirSelector'
import { uploadSingleTscParam } from '../../../api/param.js'
import { getMessageByCode } from '../../../utils/responseMessage.js'
// import { getIntersectionInfo } from '../../../api/template.js'
import CrossDiagramMgr from '../../../EdgeMgr/controller/crossDiagramMgr.js'
import PhaseDataModel from '../IntersectionMap/crossDirection/utils.js'
// import { getTheme } from '../../../utils/auth'
import { getPhaseImages } from '../../../utils/phasedesc.js'
import PedSvg from './svg/pedSvg'

import CrossDirectionConflictList from '../../../utils/conflictList.js'

export default {
  name: 'direction-list-configuration',
  data () {
    return {
      laneList: [],
      pedList: [],
      preselectDirection: [], // 预选方向
      preselectPedDirection: [] // 预选行人方向
    }
  },
  components: {
    xdrdirselector,
    PedSvg
  },
  props: {
    labelWidth: {
      type: String,
      default: '130px'
    },
    agentId: {
      type: String
    },
    list: {
      type: Array,
      default () {
        return []
      }
    },
    roadDirection: {
      type: String,
      default: 'right'
    },
    isThirdSignal: {
      type: Boolean,
      default: false
    },
    choosedDirection: {
      type: Array
    },
    choosedPedDirection: {
      type: Array
    }
  },
  methods: {
    init (IntersectionInfo) {
      this.CrossDiagramMgr = new CrossDiagramMgr()
      this.PhaseDataModel = new PhaseDataModel(this.roadDirection)
      this.getIntersectionInfo(IntersectionInfo) // 获取路口信息
    },
    getIntersectionInfo (res) {
      // 获取路口信息
      // const agentid = this.agentId || '0'
      // getIntersectionInfo(agentid).then(res => {
      //   if (!res.data.success) {
      //     this.isLoaded = false
      //     let commomMsg = this.$t('openatccomponents.overview.signalID') + ' : ' + agentid
      //     let msg = getMessageByCode(res.data.code, this.$i18n.locale)
      //     if (res.data.data) {
      //       // 子类型错误
      //       let childErrorCode = res.data.data.errorCode
      //       if (childErrorCode) {
      //         let childerror = getMessageByCode(res.data.data.errorCode, this.$i18n.locale)
      //         msg = msg + ' - ' + childerror
      //       }
      //     }
      //     msg = msg + ' - ' + commomMsg
      //     this.$message.error(msg)
      //     return
      //   }
      this.tempType = res.data.data.type
      // 获取车道相位、行人相位信息（坐标、名称）
      this.mainType = this.tempType.split('-')[0]
      this.mainDirection = this.tempType.split('-')[1]
      if (!this.isThirdSignal) {
        // 可点击模式下，非第三方设备，按通道显示相位方向
        this.getChannelInfo()
        return
      }
      this.crossInfo = res.data.data.param
      // 城市道路加载车道相位坐标和人行道坐标
      this.getPhasePos()
      this.getOverlapPhasePos()
      this.getPedPhasePos()
      this.getOverlapPedPhasePos()
      if (this.isThirdSignal) {
        // 第三方设备，按相位方向显示相位方向
        this.compLanePhaseData = this.CrossDiagramMgr.compare(this.LanePhaseData, this.overlapLanePhaseData, 'type', 'nostatus')
        this.compSidewalkPhaseData = this.CrossDiagramMgr.compare(this.sidewalkPhaseData, this.overlapsidewalkPhaseData, 'pedtype', 'nostatus')
        let allDir = this.compLanePhaseData.map(ele => ele.id)
        let allPedDir = this.compSidewalkPhaseData.map(ele => ele.id)
        this.inneChoosedDirection = this.choosedDirection.filter(dir => allDir.indexOf(dir) !== -1)
        this.inneChoosedPedDirection = this.choosedPedDirection.filter(dir => allPedDir.indexOf(dir) !== -1)
        this.drawPhaseIcon()
      }
      // })
    },
    getPhasePos () {
      // 车道相位信息
      this.LanePhaseData = []
      this.crossInfo.phaseList.forEach((ele, i) => {
        if (ele.controltype === undefined || ele.controltype <= 2) {
          ele.direction.forEach((dir, index) => {
            let dirinfo = this.PhaseDataModel.getPhase(dir)
            if (dir <= 16) {
            // 车道相位
              this.LanePhaseData.push({
                key: this.CrossDiagramMgr.getUniqueKey('phase'),
                phaseid: ele.id, // 相位id，用于对应相位状态
                id: dir, // 接口返回的dir字段，对应前端定义的相位方向id，唯一标识
                name: dirinfo.name
              })
            }
          })
        }
      })
    },
    getOverlapPhasePos () {
      // 车道跟随相位信息
      if (!this.crossInfo.overlaplList) return
      this.overlapLanePhaseData = []
      this.crossInfo.overlaplList.forEach((ele, i) => {
        if (ele.direction) {
          ele.direction.forEach((dir, index) => {
            this.overlapLanePhaseData.push({
              key: this.CrossDiagramMgr.getUniqueKey('overlapphase'),
              phaseid: ele.id, // 相位id，用于对应相位状态
              id: dir, // 接口返回的dir字段，对应前端定义的相位方向id，唯一标识
              name: this.PhaseDataModel.getPhase(dir).name,
              left: this.PhaseDataModel.getPhase(dir).x,
              top: this.PhaseDataModel.getPhase(dir).y
            })
          })
        }
      })
    },
    getPedPhasePos () {
      // 行人相位信息
      this.sidewalkPhaseData = []
      this.crossInfo.phaseList.forEach((ele, i) => {
        if (ele.peddirection) {
          ele.peddirection.forEach((dir, index) => {
          // 行人相位
            let dirinfo = this.PhaseDataModel.getSidePos(dir)
            if (dir <= 16) {
              let key = this.CrossDiagramMgr.getUniqueKey('pedphase')
              if (this.isVipRoute && this.isThirdSignal) {
                key = this.CrossDiagramMgr.getUniqueKey('pedphase') + `-${this.agentId}`
              }
              this.sidewalkPhaseData.push({
                key,
                phaseid: ele.id, // 相位id，用于对应相位状态
                id: dir,
                name: dirinfo.name
              })
            }
          })
        }
      })
    },
    getOverlapPedPhasePos () {
      // 行人跟随相位信息
      if (!this.crossInfo.overlaplList) return
      this.overlapsidewalkPhaseData = []
      this.crossInfo.overlaplList.forEach((ele, i) => {
        if (ele.peddirection) {
          ele.peddirection.forEach((dir, index) => {
            if (this.PhaseDataModel.getSidePos(dir)) {
              this.overlapsidewalkPhaseData.push({
                key: this.CrossDiagramMgr.getUniqueKey('overlappedphase'),
                phaseid: ele.id, // 相位id，用于对应相位状态
                id: dir,
                name: this.PhaseDataModel.getSidePos(dir).name,
                left: this.PhaseDataModel.getSidePos(dir).x,
                top: this.PhaseDataModel.getSidePos(dir).y
              })
            }
          })
        }
      })
    },
    getChannelInfo () {
      uploadSingleTscParam('channel', 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
        }
        let channelList = res.data.data.channelList.filter(ele => ele.type !== undefined)
        this.channelList = this.handleRepeatRealdir(channelList)
        console.log('this.channelList', this.channelList)
        this.handleChannelDirection()
      })
    },
    handleRepeatRealdir (channelList) {
      let map = new Map()
      channelList.forEach(ele => {
        if (ele.realdir !== undefined && ele.realdir.length > 0) {
          ele.realdir.forEach(dir => {
            if (map.get(dir) === undefined) {
              map.set(dir, ele)
            }
          })
        }
      })
      let arr = Array.from(map)
      let newarr = []
      arr.forEach(ele => {
        newarr.push(ele[1])
      })
      // console.log(newarr)
      return newarr
    },
    handleChannelDirection () {
      this.LanePhaseData = []
      this.sidewalkPhaseData = []
      this.sidewalkDir = []
      let realphasedirarr = []
      let realpeddirarr = []
      this.channelList.forEach((ele, i) => {
        if (ele.type === 0 || ele.type === 1 || ele.type === 3) {
          if (ele.realdir) {
            ele.realdir.forEach((dir, index) => {
              let phaseinfo = this.PhaseDataModel.getPhase(dir)
              // 车道相位（通道类型是机动车，非机动车，公交时，对应相位机动车）
              this.LanePhaseData.push({
                key: this.CrossDiagramMgr.getUniqueKey('phase'),
                channelid: ele.id, // 通道id
                id: dir, // 接口返回的dir字段，对应前端定义的相位方向id，唯一标识
                name: this.$t(phaseinfo.commonname)
              })
            })
            realphasedirarr = Array.from(new Set(realphasedirarr.concat(ele.realdir)))
          }
        }
        if (ele.type === 2) {
          if (ele.realdir) {
            ele.realdir.forEach((dir, index) => {
              // 行人相位
              if (this.sidewalkDir.indexOf(dir) === -1 && this.PhaseDataModel.getSidePos(dir)) {
                let pedinfo = this.PhaseDataModel.getSidePos(dir)
                this.sidewalkPhaseData.push({
                  key: this.CrossDiagramMgr.getUniqueKey('pedphase'),
                  channelid: ele.id, // 通道id
                  id: dir,
                  name: this.$t(pedinfo.commondesc)
                })
              }
            })
            realpeddirarr = Array.from(new Set(realpeddirarr.concat(ele.realdir)))
            this.sidewalkDir = Array.from(new Set([...this.sidewalkDir.concat(ele.realdir)]))
          }
        }
      })
      this.inneChoosedDirection = this.choosedDirection.filter(dir => realphasedirarr.indexOf(dir) !== -1)
      this.inneChoosedPedDirection = this.choosedPedDirection.filter(dir => realpeddirarr.indexOf(dir) !== -1)
      this.drawPhaseIcon()
    },
    async drawPhaseIcon () {
      if (!this.isThirdSignal) {
        await this.getConflictList()
        this.handleClickedPhase()
        this.handleClickedPedPhase()
        this.handleLaneDir()
        this.handlePedDir()
      } else {
        this.handleClickedPhase()
        this.handleClickedPedPhase()
        this.handleLaneDir()
        this.handlePedDir()
      }
    },
    async getConflictList () {
      let ConflictList = new CrossDirectionConflictList(this.agentId)
      return ConflictList.getConflictListByAgentid().then(res => {
        if (res) {
          let conflictList = ConflictList.getListDirConflict(this.inneChoosedDirection, this.inneChoosedPedDirection)
          this.phaseConflictList = conflictList.allConflictDir
          this.pedConflictList = conflictList.allPedConflictDir
          // 排他
          for (let index = 0; index < this.LanePhaseData.length; index++) {
            const element = this.LanePhaseData[index]
            delete element.disabled
          }
          for (let index = 0; index < this.sidewalkPhaseData.length; index++) {
            const element = this.sidewalkPhaseData[index]
            delete element.disabled
          }
          for (let index = 0; index < this.LanePhaseData.length; index++) {
            const element = this.LanePhaseData[index]
            if (this.phaseConflictList.indexOf(element.id) !== -1) {
              element.disabled = true
            }
          }
          for (let index = 0; index < this.sidewalkPhaseData.length; index++) {
            const element = this.sidewalkPhaseData[index]
            if (this.pedConflictList.indexOf(element.id) !== -1) {
              element.disabled = true
            }
          }
        }
      })
    },
    handleClickedPhase () {
      if (!this.isThirdSignal) {
        this.preselectDirection = this.inneChoosedDirection.filter(dir => this.phaseConflictList.indexOf(dir) === -1)
      } else {
        this.preselectDirection = JSON.parse(JSON.stringify(this.inneChoosedDirection))
      }
    },
    handleClickedPedPhase () {
      if (!this.isThirdSignal) {
        this.preselectPedDirection = this.inneChoosedPedDirection.filter(dir => this.pedConflictList.indexOf(dir) === -1)
      } else {
        this.preselectPedDirection = JSON.parse(JSON.stringify(this.inneChoosedPedDirection))
      }
    },

    handleLaneDir () {
      if (!this.isThirdSignal) {
        this.laneList = this.getPhaseDirIcon(this.LanePhaseData)
      } else {
        this.laneList = this.getPhaseDirIcon(this.compLanePhaseData)
      }
    },
    handlePedDir () {
      if (!this.isThirdSignal) {
        this.pedList = JSON.parse(JSON.stringify(this.sidewalkPhaseData))
      } else {
        this.pedList = JSON.parse(JSON.stringify(this.compSidewalkPhaseData))
      }
    },
    getPhaseDirIcon (list) {
      let idarr = []
      let dirlist = []
      const images = getPhaseImages(this.$i18n)
      for (let i = 0; i < list.length; i++) {
        if (list[i].id <= 16 && idarr.indexOf(list[i].id) === -1) {
          idarr.push(list[i].id)
          let obj = {
            ...list[i],
            iconclass: images.filter(ele => ele.id === list[i].id)[0].class
          }
          if (this.roadDirection === 'left') {
            if (list[i].id === 4 || list[i].id === 8 || list[i].id === 12 || list[i].id === 16) {
              obj.iconclass = images.filter(ele => ele.id === list[i].id)[0].leftclass
            }
          }
          dirlist.push(obj)
        }
      }
      return dirlist
    },
    selectDire (value, type) {
      if (value.disabled) return
      let id = value.id
      if (type === 'lane') {
        let index = this.preselectDirection.indexOf(id)
        if (index === -1) {
          this.preselectDirection.push(id)
        } else {
          this.preselectDirection.splice(index, 1)
        }
        // console.log(this.preselectDirection)
        this.choosedLanePhase = this.laneList.filter(lane => this.preselectDirection.includes(lane.id))
        // console.log(this.choosedLanePhase)
        this.inneChoosedDirection = JSON.parse(JSON.stringify(this.preselectDirection))
      }
      if (type === 'ped') {
        let index = this.preselectPedDirection.indexOf(id)
        if (index === -1) {
          this.preselectPedDirection.push(id)
        } else {
          this.preselectPedDirection.splice(index, 1)
        }
        // console.log(this.preselectPedDirection)
        this.choosedPedPhase = this.pedList.filter(lane => this.preselectPedDirection.includes(lane.id))
        // console.log(this.choosedPedPhase)
        this.inneChoosedPedDirection = JSON.parse(JSON.stringify(this.preselectPedDirection))
      }
      this.EmitAllChoosedDirection(value)
    },
    EmitAllChoosedDirection (curClickedPhase) {
      let allChoosedDir = {
        direction: this.preselectDirection,
        peddirection: this.preselectPedDirection
      }
      this.$emit('handleClickCrossIcon', allChoosedDir, curClickedPhase)
      this.drawPhaseIcon()
    }
  },
  mounted () {
    // this.init()
  }
}
</script>
