/**
 * 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="scheme-config openatc-scheme-config" style="height: 100%;">
    <fault-detail-modal ref="faultDetail" :agentId="agentId" :isFromAtc="isFromAtc" @refreshFault="getFaultById"></fault-detail-modal>
        <!-- 带实时面板的完整功能（带动画） -->
        <div style="height: 100%;" v-if="realtimeStatusModalvisible">
          <transition name="fade-right" mode="out-in"
          :enter-active-class="toPage === 1 ? 'animated fadeInRight' : 'animated fadeInLeft'"
          :leave-active-class="toPage === 1 ? 'animated fadeOutRight' : 'animated fadeOutLeft' ">
            <div class="new" style="position: absolute;width: 100%;height:100%;"  v-show="(isOperation && !isClosePhase)">
              <ManualControlModalNew
              v-if="resetcomponent"
              ref="ManualControlModalNew"
              :residentControlList="residentControlList"
              :specialControlList="specialControlList"
              :patternChooseControlList="patternChooseControlList"
              :othersControlList="othersControlList"
              :controlData="controlData"
              :patternAll="patternAll"
              :crossStatusData="crossStatusData"
              :preselectModel="preselectModel"
              :preselectStages="preselectStages"
              :realtimeStatusModalvisible="realtimeStatusModalvisible"
              :roadDirection="roadDirection"
              :closePhaseRings="phaseRings"
              :sidewalkPhaseData="sidewalkPhaseData"
              :phaseList="phaseList"
              :statusData="statusData"
              :overlap="overlap"
              :patternSelect="patternSelect"
              :allPatternList="allPatternList"
              :funcSort="funcSort"
              :thirdPartyControlMenu="thirdPartyControlMenu"
              :thirdPartyControl="thirdPartyControl"
              :isShowBack="isShowBack"
              :isShowRecovery="isShowRecovery"
              :isShowImplement="isShowImplement"
              :protocol="protocol"
              @closeManualModal="closeManualModal"
              @selectModel="selectModel"
              @selectStages="selectStages"
              @patternCommit="patternCommit"
              @closePhaseBack="closePhaseBack"
              @closePhaseControl="closePhaseControl"
              @selectSpecialModel="selectSpecialModelNew" />
            </div>
          </transition>

          <transition name="fade-left" mode="out-in"
          enter-active-class="animated fadeInLeft"
          leave-active-class="animated fadeOutLeft">
            <div class="right-control-part" style="position: absolute;width: 100%;" v-show="!isOperation">
              <RealtimeStatusModal
                :controlData="controlData"
                :currModel="currModel"
                :ip="ip"
                :platform="platform"
                :firm="firm"
                :responseTime="responseTime"
                :curFaultList="curFaultList"
                :confirmedFault="confirmedFault"
                :ignoredFault="ignoredFault"
                :untreatedFault="untreatedFault"
                :closePhase="closePhase"
                :agentName="agentName"
                :agentId="agentId"
                :crossStatusData="crossStatusData"
                :phaseList="phaseList"
                :sidewalkPhaseData="sidewalkPhaseData"
                :roadDirection="roadDirection"
                :faultboardState="faultboardState"
                @changeStatus="changeStatus"
                @showFaultDetail="showFaultDetail"/>
            </div>
          </transition>
        </div>
        <!-- 只有控制功能（无动画） -->
        <div v-else style="height: 100%;">
          <div class="new" style="position: absolute;width: 100%;height:100%;"  v-show="(isOperation && !isClosePhase)">
            <ManualControlModalNew
            v-if="resetcomponent"
            ref="ManualControlModalNew"
            :residentControlList="residentControlList"
            :specialControlList="specialControlList"
            :patternChooseControlList="patternChooseControlList"
            :othersControlList="othersControlList"
            :controlData="controlData"
            :patternAll="patternAll"
            :crossStatusData="crossStatusData"
            :preselectModel="preselectModel"
            :preselectStages="preselectStages"
            :realtimeStatusModalvisible="realtimeStatusModalvisible"
            :roadDirection="roadDirection"
            :closePhaseRings="phaseRings"
            :sidewalkPhaseData="sidewalkPhaseData"
            :phaseList="phaseList"
            :statusData="statusData"
            :overlap="overlap"
            :patternSelect="patternSelect"
            :allPatternList="allPatternList"
            :funcSort="funcSort"
            :thirdPartyControlMenu="thirdPartyControlMenu"
            :thirdPartyControl="thirdPartyControl"
            :isShowBack="isShowBack"
            :isShowRecovery="isShowRecovery"
            :isShowImplement="isShowImplement"
            :protocol="protocol"
            @closeManualModal="closeManualModal"
            @selectModel="selectModel"
            @selectStages="selectStages"
            @patternCommit="patternCommit"
            @closePhaseBack="closePhaseBack"
            @closePhaseControl="closePhaseControl"
            @selectSpecialModel="selectSpecialModelNew" />
          </div>
        </div>
  </div>
</template>

<script>
import { putTscControl } from '../../../api/control.js'
import { uploadSingleTscParam } from '../../../api/param.js'
import RealtimeStatusModal from './realtimeStatusModal'
import ManualControlModal from './manualControlModal'
import ManualControlModalNew from './manualControlModalNew'
import ClosePhaseControlModal from './closePhaselControlModal'
import LockingPhaseControlModal from './lockingPhaselControlModal'
import TentativePlanControlModal from './tentativeplancontrolmodal'
import AzimuthLocking from './azimuthlocking'
import priorityControl from './priorityControl'
import { getMessageByCode } from '../../../utils/responseMessage'
import { GetAllFaultRange } from '../../../api/fault'
import PhaseDataModel from '../IntersectionMap/crossDirection/utils.js'
import CrossDiagramMgr from '../../../EdgeMgr/controller/crossDiagramMgr.js'
import { setToken, setHost, getTheme } from '../../../utils/auth.js'
import RingDataModel from '../../../utils/RingDataModel.js'
import { getIntersectionInfo } from '../../../api/template'
import { GetRoleByName } from '../../../api/permission.js'
import { getPermissionMenu, getPermissionControl } from './utils/thirdPartypermission.js'

export default {
  name: 'scheme-config',
  components: {
    RealtimeStatusModal,
    ManualControlModal,
    ClosePhaseControlModal,
    LockingPhaseControlModal,
    priorityControl,
    AzimuthLocking,
    TentativePlanControlModal,
    ManualControlModalNew
  },
  props: {
    phaseList: {
      type: Array,
      default: () => []
    },
    reqUrl: {
      type: String,
      default: ''
    },
    responseTime: {
      type: Number,
      default: 0
    },
    statusData: {
      type: Object,
      required: true
    },
    agentName: {
      type: String,
      default: ''
    },
    // devStatus: {
    //   type: Number,
    //   default: 0
    // },
    agentId: {
      type: String,
      default: '0'
    },
    ip: {
      type: String
    },
    // allPatternList: {
    //   type: Array
    // },
    // overlap: {
    //   type: Array
    // },
    platform: {
      type: String
    },
    firm: {
      type: String
    },
    realtimeStatusModalvisible: {
      type: Boolean,
      default: true
    },
    Token: {
      type: String,
      default: ''
    },
    roadDirection: {
      type: String,
      default: 'right'
    },
    isFromAtc: {
      type: Boolean,
      default: true
    },
    isShowBack: {
      type: Boolean,
      default: true
    },
    isShowRecovery: {
      type: Boolean,
      default: true
    },
    isShowImplement: {
      type: Boolean,
      default: true
    },
    protocol: {
      type: String,
      default: 'ocp'
    },
    faultboardState: {
      type: Number,
      default: null,
      validator: function (value) {
        return value === null || value === 1 || value === 2
      }
    }
  },
  data () {
    return {
      crossStatusData: null,
      controlData: {},
      control: '',
      allPatternList: [],
      overlap: [],
      sidewalkPhaseData: [],
      list: [{
        iconClass: 'model',
        name: '控制模式',
        value: '--'
      }, {
        iconClass: 'cycle',
        name: '周期',
        value: '--'
      }, {
        iconClass: 'time',
        name: '当前时间',
        value: '--'
      }, {
        iconClass: 'maincontrol',
        name: '控制方式',
        value: '--'
      }, {
        iconClass: 'phasediff',
        name: '相位差',
        value: '--'
      }, {
        iconClass: 'time',
        name: '剩余时间',
        value: '--'
      }],
      faultTimer: null, // 当前故障定时器
      ParamsMode: new Map([[0, '自主控制'], [1, '本地手动'], [2, '平台控制'], [3, '配置软件控制'], [4, '遥控器控制'], [5, '黄闪器控制'], [6, '降级控制'], [7, '脚本控制'], [8, '算法控制']]),
      ParamsModeEn: new Map([[0, 'Autonomous Control'], [1, 'Local Manual'], [2, 'Platform Control'], [3, 'Configuration Software Control'], [4, 'Remote Control'], [5, 'Yellow Flasher Control'], [6, 'Degradation Control'], [7, 'Script Control'], [8, 'Algorithm Control']]),
      ParamsControl: new Map([[0, '多时段'], [1, '黄闪'], [2, '全红'], [3, '关灯'], [4, '步进'], [5, '定周期控制'], [6, '自适应'], [7, '协调感应控制'], [8, '方案选择控制'], [9, '方案生成'], [10, '无电缆控制'], [11, '有电缆控制'], [12, '行人过街控制'], [13, '方案恢复过渡'], [14, '相位驻留'], [15, '通道检测'], [16, '方向锁定'], [17, '韦伯斯特单点控制'], [18, '预留18'], [19, '感应式行人过街'], [20, '方案干预'], [100, '方案干预'], [21, '预留21'], [22, '相位锁定'], [23, '相位放行控制'], [24, '紧急控制'], [99, '设备维护']]),
      ParamsControlEn: new Map([[0, 'Multi Period'], [1, 'Yellow Flash Control'], [2, 'Red Control'], [3, 'Dark Control'], [4, 'Step'], [5, 'Fixed_Cycle Control'], [6, 'Free Control'], [7, 'Coordinated Induction Control'], [8, 'Pattern Selection Control'], [9, 'Adaptive Control'], [10, 'Wireless Control'], [11, 'Cable Control'], [12, 'Pedestrian Crossing Control'], [13, 'Pattern recovery'], [14, 'Phase dwell'], [15, 'Channel Detection'], [16, 'Direction lock'], [17, 'Webster Single Point Coordination'], [18, 'Reserving18'], [19, 'Inductive Pedestrian Crossing Control'], [20, 'Program Intervention'], [100, 'Program Intervention'], [21, 'Reserving21'], [22, 'Priority Control'], [23, 'Close Phase'], [24, 'Emergency Control'], [99, 'Device Mantenance']]),
      phaseType: new Map([[1, '红'], [2, '黄'], [3, '绿']]), // phaseType表示红，黄，绿
      phaseTypeEn: new Map([[1, 'Red'], [2, 'Yellow'], [3, 'Green']]), // phaseType表示红，黄，绿
      mode: '2',
      loading: {},
      modelList: [{
        id: 1,
        iconClass: 'huangshan',
        permission: 'configer:manual:senior',
        iconName: '黄闪'
      }, {
        id: 2,
        iconClass: 'quanhong',
        permission: 'configer:manual:senior',
        iconName: '全红'
      }, {
        id: 3,
        iconClass: 'guandeng',
        permission: 'configer:manual:senior',
        iconName: '关灯'
      }, {
        id: 4,
        iconClass: 'bujin',
        permission: 'configer:manual:dwell',
        iconName: '步进'
      }, {
        id: 5,
        iconClass: 'dingzhouqi',
        permission: 'configer:manual:base',
        iconName: '定周期'
      }, {
        id: 6,
        iconClass: 'ganyingkongzhi',
        permission: 'configer:manual:base',
        iconName: '感应控制'
      }, {
        id: 9,
        iconClass: 'zishiying',
        permission: 'configer:manual:base',
        iconName: '方案生成'
      }, {
        id: 10,
        iconClass: 'wuxianlan',
        permission: 'configer:manual:base',
        iconName: '无电缆协调'
      }, {
        id: 12,
        iconClass: 'xingrenguojie',
        permission: 'configer:manual:base',
        iconName: '行人过街'
      }, {
        id: 19,
        iconClass: 'ganyingshixingrenguojie',
        permission: 'configer:manual:base',
        iconName: '感应式行人过街控制'
      }],
      originResidentControlList: [
        {
          type: '步进',
          id: 4,
          iconClass: 'bujin',
          permission: 'configer:manual:dwell',
          iconName: this.$t('openatccomponents.overview.modelList4'),
          bgcolor: getTheme() === 'light' ? '#edf6ff' : '#243d59'
        },
        {
          type: '阶段锁定',
          id: 4,
          iconClass: 'jieduansuoding',
          permission: 'configer:manual:dwell',
          iconName: this.$t('openatccomponents.overview.modelList4-'),
          bgcolor: getTheme() === 'light' ? '#edf6ff' : '#243d59'
        },
        {
          type: '相位锁定',
          id: 22,
          iconClass: 'xiangweisuoding',
          permission: 'configer:manual:optimize',
          iconName: this.$t('openatccomponents.overview.modelList22'),
          bgcolor: getTheme() === 'light' ? '#edf6ff' : '#243d59'
        },
        {
          type: '方向锁定',
          id: 25,
          iconClass: 'fangxiangsuoding',
          permission: 'configer:manual:dwell',
          iconName: this.$t('openatccomponents.overview.modelList25'),
          bgcolor: getTheme() === 'light' ? '#edf6ff' : '#243d59'
        }
      ],
      residentControlList: [],
      specialControlList: [
        {
          type: '黄闪',
          id: 1,
          iconClass: 'huangshan',
          permission: 'configer:manual:senior',
          iconName: this.$t('openatccomponents.overview.modelList1'),
          bgcolor: getTheme() === 'light' ? '#edf6ff' : '#243d59'
        }, {
          type: '全红',
          id: 2,
          iconClass: 'quanhong',
          permission: 'configer:manual:senior',
          iconName: this.$t('openatccomponents.overview.modelList2'),
          bgcolor: getTheme() === 'light' ? '#edf6ff' : '#243d59'
        }, {
          type: '关灯',
          id: 3,
          iconClass: 'guandeng',
          permission: 'configer:manual:senior',
          iconName: this.$t('openatccomponents.overview.modelList3'),
          bgcolor: getTheme() === 'light' ? '#edf6ff' : '#243d59'
        }
      ],
      patternChooseControlList: [
        {
          type: '定周期',
          id: 5,
          iconClass: 'dingzhouqi',
          permission: 'configer:manual:base',
          iconName: this.$t('openatccomponents.overview.modelList5'),
          bgcolor: getTheme() === 'light' ? '#edf6ff' : '#243d59'
        }, {
          type: '自适应',
          id: 6,
          iconClass: 'ganyingkongzhi',
          permission: 'configer:manual:base',
          iconName: this.$t('openatccomponents.overview.modelList6'),
          bgcolor: getTheme() === 'light' ? '#edf6ff' : '#243d59'
        }, {
          type: '方案生成',
          id: 9,
          iconClass: 'zishiying',
          permission: 'configer:manual:base',
          iconName: this.$t('openatccomponents.overview.modelList9'),
          bgcolor: getTheme() === 'light' ? '#edf6ff' : '#243d59'
        }, {
          type: '无电缆协调',
          id: 10,
          iconClass: 'wuxianlan',
          permission: 'configer:manual:base',
          iconName: this.$t('openatccomponents.overview.modelList10'),
          bgcolor: getTheme() === 'light' ? '#edf6ff' : '#243d59'
        }, {
          type: '行人过街',
          id: 12,
          iconClass: 'xingrenguojie',
          permission: 'configer:manual:base',
          iconName: this.$t('openatccomponents.overview.modelList12'),
          bgcolor: getTheme() === 'light' ? '#edf6ff' : '#243d59'
        }, {
          type: '感应式行人过街',
          id: 19,
          iconClass: 'ganyingshixingrenguojie',
          permission: 'configer:manual:base',
          iconName: this.$t('openatccomponents.overview.modelList19'),
          bgcolor: getTheme() === 'light' ? '#edf6ff' : '#243d59'
        }, {
          type: '感应式自适应',
          id: 18,
          iconClass: 'ganyingshizishiying',
          permission: 'configer:manual:base',
          iconName: this.$t('openatccomponents.overview.modelList18'),
          bgcolor: getTheme() === 'light' ? '#edf6ff' : '#243d59'
        }, {
          type: '自动分级控制',
          id: 26,
          iconClass: 'zidongfenjikongzhi',
          permission: 'configer:manual:base',
          iconName: this.$t('openatccomponents.overview.modelList26'),
          bgcolor: getTheme() === 'light' ? '#edf6ff' : '#243d59'
        }, {
          type: '自适应微调',
          id: 21,
          iconClass: 'zidongfenjikongzhi',
          permission: 'configer:manual:base',
          iconName: this.$t('openatccomponents.overview.modelList21'),
          bgcolor: getTheme() === 'light' ? '#edf6ff' : '#243d59'
        }, {
          type: '自适应协调',
          id: 7,
          iconClass: 'zidongfenjikongzhi',
          permission: 'configer:manual:base',
          iconName: this.$t('openatccomponents.overview.modelList7'),
          bgcolor: getTheme() === 'light' ? '#edf6ff' : '#243d59'
        }
      ],
      othersControlList: [
        { // 特殊控制
          type: '相位关断',
          id: 23,
          permission: 'configer:manual:optimize',
          iconClass: 'closephase',
          iconName: this.$t('openatccomponents.overview.modelList23'),
          bgcolor: getTheme() === 'light' ? '#edf6ff' : '#243d59'
        }, {
          type: '临时方案',
          id: 100,
          permission: 'configer:manual:optimize',
          iconClass: 'tentativeplan',
          iconName: this.$t('openatccomponents.overview.modelList100'),
          bgcolor: getTheme() === 'light' ? '#edf6ff' : '#243d59'
        }, {
          type: '优先控制',
          id: 24,
          permission: 'configer:manual:preempt',
          iconClass: 'prioritycontrol',
          iconName: this.$t('openatccomponents.overview.modelList24'),
          bgcolor: getTheme() === 'light' ? '#edf6ff' : '#243d59'
        }],
      currModel: -1,
      preselectModel: -1, // 预选方案
      preselectStages: -1, // 预选阶段
      closePhase: [],
      isOperation: false, // 是否为手动可操作状态
      tempPatternid: 0, // 控制方式手动操作的情况下的控制编号的临时值。
      tempDelay: 0, // 控制方式手动操作的情况下的延迟时间的临时值。
      tempDuration: 0, // 控制方式手动操作的情况下的持续时间的临时值。
      // phaseList: [], // 当前相位集合
      faultvisible: false,
      isClosePhase: false, // 是否在相位关断
      toPage: 1, // 与哪一个页面交互，1 代表路口信息页面，3代表 相位关断页面
      phaseRings: [],
      curFaultList: [],
      confirmedFault: [],
      ignoredFault: [],
      untreatedFault: [],
      patternAll: [],
      patternSelect: [], // 所有方案id
      specialPage: '', // 哪一个特殊控制页面
      nextcycleefficcontrol: [5, 6, 9, 10, 12, 19], // 下周期生效的控制方式
      resetcomponent: false,
      funcSort: 'allFunc',
      thirdPartyControlMenu: [],
      thirdPartyControl: []
    }
  },
  watch: {
    platform: {
      handler: function (val1, val2) {
        if (val1 !== val2 && val2 !== undefined) {
          this.handeleChangeStatus()
        }
      },
      // 深度观察监听
      deep: true
    },
    agentId: {
      handler: function (val1, val2) {
        if (val1 !== val2) {
          this.resetComponent()
        }
        this.getIntersectionInfo(val1)
      },
      // 深度观察监听
      deep: true
    },
    statusData: {
      handler: function (val) {
        this.initData()
        this.getPedPhasePos()
      },
      // 深度观察监听
      deep: true
    },
    phaseList: {
      handler: function (val, oldVal) {
        this.getPedPhasePos()
      },
      // 深度观察监听
      deep: true
    },
    Token: {
      handler: function (val) {
        this.setPropsToken(val)
      }
    },
    roadDirection: {
      handler: function (val) {
        if (val === 'left' || val === 'right') {
          this.PhaseDataModel = new PhaseDataModel(val)
        }
      }
    },
    protocol: {
      handler: function (val, oldVal) {
        // 20999 协议驻留控制里仅支持阶段锁定
        if (val === 'rcp') {
          this.residentControlList = this.originResidentControlList.filter(item => item.type === '阶段锁定')
        } else {
          this.residentControlList = [...this.originResidentControlList]
        }
      },
      deep: true,
      immediate: true
    }
  },
  created () {
    this.setHost(this.reqUrl)
    this.PhaseDataModel = new PhaseDataModel(this.roadDirection)
    this.CrossDiagramMgr = new CrossDiagramMgr()
  },
  async mounted () {
    this.resetcomponent = true
    this.init()
  },
  methods: {
    resetComponent () {
      this.resetcomponent = false
      this.$nextTick(() => {
        this.resetcomponent = true
        this.init()
      })
    },
    init () {
      this.getIntersectionInfo(this.agentId)
      if (this.realtimeStatusModalvisible === false) {
        this.changeStatus()
      }
      this.setPropsToken(this.Token)
      this.hiddenPartControl()
      // await this.getPhase()
      this.getFault()
      this.initData()
    },
    setHost (host) {
      // 获取组件外传入的token，便于独立组件调用接口
      if (host && host !== '') {
        setHost(host)
      }
    },
    getIntersectionInfo (agentid) {
      // 获取路口信息
      getIntersectionInfo(agentid).then(res => {
        this.patternAll = res.data.data.param.patternList
        this.allPatternList = res.data.data.param.patternList
        this.overlap = res.data.data.param.overlaplList
        this.patternSelect = res.data.data.param.patternList.map(item => {
          return {
            value: item.id,
            label: item.desc ? item.desc : '' + item.id ? item.id : ''
          }
        })
      })
    },
    getFault () {
      this.getFaultById()
      this.faultTimer = setInterval(() => {
        this.getFaultById()
      }, 30000)
    },
    getPedPhasePos () {
      let ringDataModel = new RingDataModel(this.statusData, this.phaseList)
      this.sidewalkPhaseData = ringDataModel.getPedPhasePos()
      this.ringDataModel = ringDataModel
    },
    clearFaultInterval () {
      if (this.faultTimer !== null) {
        clearInterval(this.faultTimer) // 清除流量定时器
        this.faultTimer = null
      }
    },
    initData () {
      this.crossStatusData = JSON.parse(JSON.stringify(this.statusData))
      let TscData = JSON.parse(JSON.stringify(this.crossStatusData))
      this.currModel = TscData.control
      this.controlData = this.handleGetData(TscData)
      this.handleGetPhaseClose()
    },
    lockScreen () {
      this.loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.5)'
      })
    },
    unlockScreen () {
      this.loading.close()
    },
    selectModel (value) {
      if (!this.isOperation) return
      this.preselectStages = -1
      this.recoverLastModel = this.preselectModel // 记录恢复前选中的控制方式
      this.preselectModel = value
    },
    selectStages (value) {
      if (!this.isOperation) return
      if (this.preselectStages !== -1) {
        if (this.preselectStages === value) {
          this.preselectStages = -1
        } else {
          this.preselectStages = value
          this.preselectModel = 4 // 如果选了阶段，默认控制方式为步进
        }
      } else {
        this.preselectStages = value
        this.preselectModel = 4 // 如果选了阶段，默认控制方式为步进
      }
    },
    changeStatus () {
      this.isOperation = true
      this.handeleChangeStatus()
    },
    handeleChangeStatus () {
      this.toPage = 1
      if (this.platform !== undefined && this.platform !== 'OpenATC') {
        this.queryThirdParty()
      } else {
        this.funcSort = 'allFunc'
        this.thirdPartyControlMenu = []
        this.thirdPartyControl = []
      }
      this.$refs.ManualControlModalNew.init()
    },
    queryThirdParty () {
      this.funcSort = 'allFunc'
      GetRoleByName(`td--${this.platform}`).then(res => {
        if (!res.data.success) {
          let msg = getMessageByCode(res.data.code, this.$i18n.locale)
          // this.$message.error(msg)
          console.log(msg)
          return
        }
        this.funcSort = 'thirdPartyFunc'
        this.thirdPartyControl = getPermissionControl(res.data.data)
        this.thirdPartyControlMenu = getPermissionMenu(this.thirdPartyControl)
        this.$refs.ManualControlModalNew.activeName = this.thirdPartyControlMenu[0]
      })
    },
    handleGetData (data) {
      let that = this
      if (data.name === '') {
        data.name = this.$t('openatccomponents.pattern.plan') + data.patternid
      }
      Object.keys(data).forEach(function (key) {
        if (key === 'mode') {
          if (data[key] > 0 && data[key] < 9) {
              data[key] = that.$t('openatccomponents.overview.ParamsMode' + data[key])
            } else {
              data[key] = that.$t('openatccomponents.overview.ParamsMode0')
            }
          }
          if (key === 'control') {
            data[key] = that.$t('openatccomponents.overview.modelList' + data[key])
          }
          if (key === 'phase') {
            for (let val of data[key]) {
              val.type = that.$t('openatccomponents.overview.phaseType' + val.type)
            }
          }
      })
      return data
    },
    closeManualModal () {
      this.isOperation = false
      this.preselectModel = -1
      this.preselectStages = -1
      this.tempPatternid = 0
      this.tempDelay = 0
      this.tempDuration = 0
      this.modelList = this.modelList.filter((item) => {
        return item.id !== 0
      })
      this.toPage = 1
    },
    handleManualConfirm (manualInfo) {
      this.$emit('handleManualConfirm', manualInfo)
    },
    patternCommit (manualInfo) {
      let that = this
      let control = {}
      if (that.preselectModel === -1) {
        this.$message.error(this.$t('openatccomponents.overview.noselectcontroltip'))
        return
      }
      that.ParamsMode.forEach(function (value, key, map) {
        if (that.controlData.mode === value) {
          control.mode = key
        }
      })
      control.control = that.preselectModel
      // control.terminal = isNaN(parseInt(manualInfo.tempPatternid)) ? Number(manualInfo.tempPatternid.replace(/[^0-9]/ig, '')) : manualInfo.tempPatternid
      control.terminal = manualInfo.tempPatternid === undefined ? null : Number(manualInfo.tempPatternid)
      // control.delay = Number(manualInfo.tempDelay)
      control.duration = Number(manualInfo.tempDuration)
      control.value = that.preselectStages === -1 ? 0 : that.preselectStages
      if (control.control === 0) {
        // 恢复自主控制（多时段）时，value为当前控制方式
        control.value = this.currModel
        if (manualInfo && manualInfo.fromControl) {
          const specialControlArr = [40, 4, 100, 101]
          if (specialControlArr.includes(manualInfo.fromControl)) {
            control.value = manualInfo.fromControl
          }
        }
      }
      if (!this.isShowImplement) {
        console.log(control)
        this.$emit('patternCommitCallback', control)
        return
      }
      this.lockScreen()
      putTscControl(control, this.agentId).then(data => {
        that.unlockScreen()
        if (control.control === 0) {
          that.preselectModel = that.recoverLastModel
        }
        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 (this.nextcycleefficcontrol.indexOf(that.currModel) !== -1 && this.nextcycleefficcontrol.indexOf(that.preselectModel) !== -1) {
          that.$message.success(this.$t('openatccomponents.overview.nextcycleeffic'))
          return
        }
        if (that.preselectModel === 4) {
          that.$message.success(this.$t('openatccomponents.overview.transitioneffic'))
          return
        }
        if (success === 0) {
          that.$message.success(this.$t('openatccomponents.common.download'))
        }
      }).catch(error => {
        that.unlockScreen()
        if (control.control === 0) {
          that.preselectModel = that.recoverLastModel
        }
        console.log(error)
      })
    },
    getPhase () {
      let _this = this
      return new Promise(function (resolve, reject) {
        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
          resolve()
        })
      })
    },
    handleFaultsVisible () {
      this.faultvisible = !this.faultvisible
    },
    handleGetPhaseClose () {
      if (this.crossStatusData.phase) {
        this.crossStatusData.phase = this.crossStatusData.phase.map(ele => {
          return {
            ...ele,
            close: ele.close || 0,
            locktype: 0 // 默认所有相位显示解锁状态
          }
        })
        // 相位关断标签
        let closePhase = []
        this.crossStatusData.phase.forEach(phase => {
          if (phase.close !== undefined && phase.close !== 0) {
            let typename
            switch (phase.close) {
              case 1: typename = ''
                break
              case 2: typename = this.$t('openatccomponents.overview.vehicle')
                break
              case 3: typename = this.$t('openatccomponents.overview.pedestrian')
                break
              default:typename = ''
            }
            closePhase.push({
              id: phase.id,
              typename: typename
            })
          }
        })
        this.closePhase = JSON.parse(JSON.stringify(closePhase))
      } else {
        this.closePhase = []
      }
    },
    selectSpecialModelNew () {
      let ringDataModel = new RingDataModel(this.statusData, this.phaseList)
      this.phaseRings = ringDataModel.initRingPhaseData()
    },
    selectSpecialModel (id) {
      let ringDataModel = new RingDataModel(this.statusData, this.phaseList)
      if (id === 23) {
        this.toPage = 3
        this.isClosePhase = true
        this.phaseRings = ringDataModel.initRingPhaseData()
        this.specialPage = 'closephase'
      } else if (id === 22) {
        this.toPage = 3
        this.isClosePhase = true
        this.phaseRings = ringDataModel.initRingPhaseData()
        this.specialPage = 'lockingphase'
      } else if (id === 100) {
        this.toPage = 3
        this.isClosePhase = true
        this.phaseRings = ringDataModel.initRingPhaseData()
        this.specialPage = 'tentativeplan'
      } else if (id === 24) {
        this.toPage = 3
        this.isClosePhase = true
        this.phaseRings = ringDataModel.initRingPhaseData()
        this.specialPage = 'prioritycontrol'
      } else if (id === 25) {
        this.toPage = 3
        this.isClosePhase = true
        this.phaseRings = ringDataModel.initRingPhaseData()
        this.specialPage = 'azimuthlocking'
      } else {
        this.isClosePhase = false
        this.specialPage = ''
      }
    },
    closePhaseBack () {
      this.toPage = 3
      this.isClosePhase = false
    },
    closePhaseControl (controldata) {
      if (!this.isShowImplement) {
        this.$emit('patternCommitCallback', controldata)
        return
      }
      this.lockScreen()
      putTscControl(controldata, this.agentId).then(data => {
        this.unlockScreen()
        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
            }
          }
          this.$message.error(getMessageByCode(data.data.code, this.$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
            this.$message.error(this.$t(errormsg))
            return
          }
        }
        this.$message.success(this.$t('openatccomponents.common.download'))
      }).catch(error => {
        this.unlockScreen()
        console.log(error)
      })
    },
    // initRingPhaseData () {
    //   // 环信息从单独上载相位信息里获取，以免相位锁定后，方案状态数据里没有rings，导致相位锁定控制列表无法显示
    //   this.phaseRings = []
    //   let map = {}
    //   let dest = []
    //   for (let i = 0; i < this.phaseList.length; i++) {
    //     let ai = this.phaseList[i]
    //     if (!map[ai.ring]) {
    //       let addphse = this.addPhaseInfo(ai)
    //       dest.push({
    //         num: ai.ring,
    //         phases: [{...ai, ...addphse}]
    //       })
    //       map[ai.ring] = ai
    //     } else {
    //       for (var j = 0; j < dest.length; j++) {
    //         var dj = dest[j]
    //         if (dj.num === ai.ring) {
    //           let addphse = this.addPhaseInfo(ai)
    //           dj.phases.push({...ai, ...addphse})
    //           break
    //         }
    //       }
    //     }
    //   }
    //   this.phaseRings = JSON.parse(JSON.stringify(dest))
    // },
    // addPhaseInfo (phase) {
    //   let addphse = {}
    //   addphse.name = this.$t('openatccomponents.overview.phase') + phase.id
    //   addphse.desc = this.getPhaseDescription(phase.direction)
    //   // 相位锁定选项默认都按照解锁状态显示
    //   addphse.locktype = 0
    //   addphse.close = 0
    //   if (this.crossStatusData !== null && this.crossStatusData.phase) {
    //     // 如果方案状态相位有close字段，这边就需要对应close状态进相位关断控制的选项里
    //     let phaseStatus = this.crossStatusData.phase.filter(ele => ele.id === phase.id)[0]
    //     addphse = {...addphse, ...phaseStatus}
    //   }
    //   return addphse
    // },
    // getPhaseDescription (phaseList) {
    //   let list = []
    //   for (let id of phaseList) {
    //     let obj = {}
    //     obj.id = id
    //     obj.color = '#454545'
    //     list.push(obj)
    //   }
    //   return list
    // },
    getFaultById () {
      let param = {
        agentId: this.agentId,
        isCurrentFault: true
      }
      GetAllFaultRange(param).then(res => {
        if (res.data.success !== true) {
          // this.$message.error(getMessageByCode(res.data.code, this.$i18n.locale))
          console.log(getMessageByCode(res.data.code, this.$i18n.locale))
          return
        }
        this.curFaultList = res.data.data.content
        this.confirmedFault = this.curFaultList.filter(ele => ele.enumerate === '2')
        this.ignoredFault = this.curFaultList.filter(ele => ele.enumerate === '1')
        this.untreatedFault = this.curFaultList.filter(ele => ele.enumerate === '0')
      })
    },
    showFaultDetail () {
      this.$refs.faultDetail.onViewFaultClick()
    },
    setPropsToken (token) {
      // 获取组件外传入的token，便于独立组件调用接口
      if (token && token !== '') {
        setToken(token)
      }
    },
    hiddenPartControl () {
      // 保存的面板，不显示方位锁定的功能
      if (this.isShowImplement === false) {
        this.residentControlList = this.residentControlList.filter(item => item.id !== 25)
      }
    }
  },
  destroyed () {
    this.clearFaultInterval()
  }
}
</script>
