/**
 * 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="manual-control-modal-new">
    <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
      <el-tab-pane :label="$t('openatccomponents.overview.residentcontrol')" name="residentcontrol"
        v-if="(funcSort === 'allFunc' || (funcSort === 'thirdPartyFunc'&& thirdPartyControlMenu.indexOf('residentcontrol') !== -1))">
        <ControlModelGroup
          v-if="activeName === 'residentcontrol'"
          ref="ControlModelGroup"
          className="residentcontrol"
          :controlList="residentControlList"
          :funcSort="funcSort"
          :thirdPartyControl="thirdPartyControl"
          @selectModel="selectModel"
        />

        <div class="common-config" v-if="activeName === 'residentcontrol' && preselecttype !== '相位锁定' && preselecttype !== '方向锁定'">
          <el-form
           v-if="isHasPermission('configer:manual:dwell')"
           ref="manual"
           label-position="left"
           :model="manualInfo"
           label-width="90px">
            <el-form-item
                :label="$t('openatccomponents.overview.duration')"
                prop="count">
              <el-input-number style="width: 170px;" v-model="manualInfo.tempDuration" :controls="false" :max="65535" :min="0" :precision="0" :step="1" :placeholder="$t('openatccomponents.common.input')" size="small"></el-input-number>
            </el-form-item>
           </el-form>
        </div>

        <div class="stage-part" v-if="preselecttype === '阶段锁定'">
          <div class="stage-label">{{$t('openatccomponents.overview.stage')}}</div>
          <div style="width: 100%; height: auto;overflow: hidden;" v-if="isHasPermission('configer:manual:dwell')">
            <Stages :crossStatusData="manuals?manualsStage:realtimeStage"
                    :phaseList="phaseList"
                    :preselectStages="preselectStages"
                    :preselectModel="preselectModel"
                    :isShowCurrentStage="false"
                    @onSelectStages="selectStages"></Stages>
          </div>
        </div>

        <LockingPhaseControlModal
          v-if="preselecttype === '相位锁定'"
          :roadDirection="roadDirection"
          :phaseList="phaseList"
          :patternStatus="statusData"
          :isShowBack="isShowBack"
          :isShowRecovery="isShowRecovery"
          :isShowImplement="isShowImplement"
          @closePhaseBack="handleClose"
          @closePhaseControl="closePhaseControl"
          @toAutoControl="toAutoControl" />

        <AzimuthLocking
          v-if="preselecttype === '方向锁定' && isShowImplement"
          :realtimeStatusModalvisible="realtimeStatusModalvisible"
          :phaseList="phaseList"
          :patternStatus="statusData"
          :isShowBack="isShowBack"
          :isShowRecovery="isShowRecovery"
          :isShowImplement="isShowImplement"
           @closePhaseBack="handleClose"
           @toAutoControl="toAutoControl"
          />

        <div class="footer" v-if="((activeName === 'residentcontrol' && preselecttype !== '相位锁定' && preselecttype !== '方向锁定') || activeName === 'specialcontrol' || activeName === 'schemeselection')">
            <el-button v-if="isShowBack && realtimeStatusModalvisible" @click="handleClose()">{{$t('openatccomponents.button.Back')}}</el-button>
            <el-button v-if="isShowRecovery && isHasPermission('configer:manual:renew')" @click="toAutoControl()">{{$t('openatccomponents.overview.recovery')}}</el-button>
            <el-button v-if="isShowImplement" type="primary" @click="handleManualControl()">{{$t('openatccomponents.overview.implement')}}</el-button>
            <el-button v-if="!isShowImplement" type="primary" @click="handleManualControl()">{{$t('openatccomponents.overview.comfirm')}}</el-button>
        </div>
      </el-tab-pane>
      <el-tab-pane :label="$t('openatccomponents.overview.specialcontrol')" name="specialcontrol"
        v-if="(funcSort === 'allFunc' || (funcSort === 'thirdPartyFunc'&& thirdPartyControlMenu.indexOf('specialcontrol') !== -1))">
        <ControlModelGroup
          v-if="activeName === 'specialcontrol'"
          ref="ControlModelGroup"
          className="specialcontrol"
          :controlList="specialControlList"
          :funcSort="funcSort"
          :thirdPartyControl="thirdPartyControl"
          @selectModel="selectModel"
        />

        <div class="common-config" v-if="isHasPermission('configer:manual:senior')">
          <el-form
           ref="manual"
           label-position="left"
           :model="manualInfo"
           label-width="90px">
            <el-form-item
                :label="$t('openatccomponents.overview.duration')"
                prop="count">
              <el-input-number style="width: 170px;" v-model="manualInfo.tempDuration" :controls="false" :max="65535" :min="0" :precision="0" :step="1" :placeholder="$t('openatccomponents.common.input')" size="small"></el-input-number>
            </el-form-item>
           </el-form>
        </div>

        <div class="footer" v-if="((activeName === 'residentcontrol' && preselecttype !== '相位锁定' && preselecttype !== '方向锁定') || activeName === 'specialcontrol' || activeName === 'schemeselection')">
          <el-button v-if="isShowBack && realtimeStatusModalvisible" @click="handleClose()">{{$t('openatccomponents.button.Back')}}</el-button>
          <el-button v-if="isShowRecovery && isHasPermission('configer:manual:renew')" @click="toAutoControl()">{{$t('openatccomponents.overview.recovery')}}</el-button>
          <el-button v-if="isShowImplement" type="primary" @click="handleManualControl()">{{$t('openatccomponents.overview.implement')}}</el-button>
          <el-button v-if="!isShowImplement" type="primary" @click="handleManualControl()">{{$t('openatccomponents.overview.comfirm')}}</el-button>
      </div>

      </el-tab-pane>
      <el-tab-pane :label="$t('openatccomponents.overview.schemeselection')" name="schemeselection"
        v-if="protocol !== 'rcp' && (funcSort === 'allFunc' || (funcSort === 'thirdPartyFunc'&& thirdPartyControlMenu.indexOf('schemeselection') !== -1))">
        <ControlModelGroup
          v-if="activeName === 'schemeselection'"
          ref="ControlModelGroup"
          className="otherscontrol"
          :controlList="patternChooseControlList"
          :funcSort="funcSort"
          :thirdPartyControl="thirdPartyControl"
          @selectModel="selectModel"
          @selectSpecialModel="selectSpecialModel" />

          <div class="common-config" v-if="activeName === 'schemeselection' && isHasPermission('configer:manual:base')">
            <el-form
             ref="manual"
             label-position="left"
             :model="manualInfo"
             label-width="90px">
              <el-form-item
                  :label="$t('openatccomponents.overview.duration')"
                  prop="count">
                <el-input-number style="width: 170px;" v-model="manualInfo.tempDuration" :controls="false" :max="65535" :min="0" :precision="0" :step="1" :placeholder="$t('openatccomponents.common.input')" size="small"></el-input-number>
              </el-form-item>
              <el-form-item
              :label="$t('openatccomponents.overview.controlnumber')"
              prop="shape">
                  <el-select style="width: 170px;" v-model="manualInfo.tempPatternid" @change="handleSelectPatternOption" class="col-inner"  size="small" :placeholder="$t('openatccomponents.common.select')">
                    <el-option
                      v-for="item in patternSelect"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                    </el-option>
                  </el-select>
              </el-form-item>
             </el-form>

             <div>
                <pattern-list
                  :key="keyChange"
                  :allPatternList="allPatternList"
                  :contrloType="!this.isRing ? 'ring' : 'stage'"
                  :stagesChange="
                    patternOne.length === 0
                      ? planPattern.stagesList
                      : patternOne[0].stagesList
                  "
                  :patternList="patternOne.length === 0 ? planPattern.rings : patternOne"
                  :patternStatusList="
                    patternOne.length === 0 ? planPattern.rings : patternOne[0].rings
                  "
                  :cycles="
                    patternOne.length === 0 ? planPattern.cycle : patternOne[0].cycle
                  "
                  :phaseList="phaseList"
                >
                </pattern-list>
             </div>
          </div>

          <div class="footer" v-if="((activeName === 'residentcontrol' && preselecttype !== '相位锁定' && preselecttype !== '方向锁定') || activeName === 'specialcontrol' || activeName === 'schemeselection')">
            <el-button v-if="isShowBack && realtimeStatusModalvisible" @click="handleClose()">{{$t('openatccomponents.button.Back')}}</el-button>
            <el-button v-if="isShowRecovery && isHasPermission('configer:manual:renew')" @click="toAutoControl()">{{$t('openatccomponents.overview.recovery')}}</el-button>
            <el-button v-if="isShowImplement" type="primary" @click="handleManualControl()">{{$t('openatccomponents.overview.implement')}}</el-button>
            <el-button v-if="!isShowImplement" type="primary" @click="handleManualControl()">{{$t('openatccomponents.overview.comfirm')}}</el-button>
        </div>
      </el-tab-pane>
      <el-tab-pane :label="$t('openatccomponents.overview.others')" name="others"
        v-if="protocol !== 'rcp' && (funcSort === 'allFunc' || (funcSort === 'thirdPartyFunc'&& thirdPartyControlMenu.indexOf('others') !== -1))">
        <ControlModelGroup
          v-if="activeName === 'others'"
          ref="ControlModelGroup"
          className="otherscontrol"
          othersControl
          :controlList="othersControlList"
          :funcSort="funcSort"
          :thirdPartyControl="thirdPartyControl"
          @selectModel="selectModel"
          @selectSpecialModel="selectSpecialModel"
        />
        <ClosePhaseControlModal
        v-if="preselecttype === '相位关断'"
        :controlData="controlData"
        :closePhaseRings="closePhaseRings"
        :sidewalkPhaseData="sidewalkPhaseData"
        :realtimeStatusModalvisible="realtimeStatusModalvisible"
        :roadDirection="roadDirection"
        :isShowBack="isShowBack"
        :isShowRecovery="isShowRecovery"
        :isShowImplement="isShowImplement"
        @closePhaseBack="handleClose"
        @closePhaseControl="closePhaseControl"
        @toAutoControl="toAutoControl" />
        <TentativePlanControlModal
         v-if="preselecttype === '临时方案'"
         :realtimeStatusModalvisible="realtimeStatusModalvisible"
         :controlData="controlData"
         :phaseList="phaseList"
         :overlap="overlap"
         :patternSelect="patternSelect"
         :allPatternList="allPatternList"
         :isShowBack="isShowBack"
         :isShowRecovery="isShowRecovery"
         :isShowImplement="isShowImplement"
         @closePhaseBack="handleClose"
         @closePhaseControl="closePhaseControl"
         @toAutoControl="toAutoControl"
        />
        <PriorityControl
        v-if="preselecttype === '优先控制'"
        :realtimeStatusModalvisible="realtimeStatusModalvisible"
        :phaseList="phaseList"
        :isShowBack="isShowBack"
        :isShowRecovery="isShowRecovery"
        :isShowImplement="isShowImplement"
         @closePhaseBack="handleClose"
         @closePhaseControl="closePhaseControl"
         @toAutoControl="toAutoControl"
        />
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import xdrdirselector from '../../XRDDirSelector/XRDDirSelector'
import Stages from '../../Stages/index'
import { hasPermission } from '../../../../utils/auth'
import LockingPhaseControlModal from '../lockingPhaselControlModal'
import AzimuthLocking from '../azimuthlocking'
import ControlModelGroup from './controlModelGroup'
import ClosePhaseControlModal from '../closePhaselControlModal'
import TentativePlanControlModal from '../tentativeplancontrolmodal'
import PriorityControl from '../priorityControl'

export default {
  name: 'manualControl',
  components: {
    xdrdirselector,
    Stages,
    LockingPhaseControlModal,
    AzimuthLocking,
    ControlModelGroup,
    ClosePhaseControlModal,
    TentativePlanControlModal,
    PriorityControl
  },
  props: {
    patternAll: {
      type: Array
    },
    crossStatusData: {
      type: Object,
      default: () => {}
    },
    phaseList: {
      type: Array,
      default () {
        return []
      }
    },
    Visible: {
      type: Boolean
    },
    controlData: {
      type: Object
    },
    modelList: {
      type: Array
    },
    residentControlList: {
      type: Array
    },
    // stagesList: {
    //   type: Array
    // },
    patternSelect: {
      type: Array
    },
    currModel: {
      type: Number
    },
    preselectModel: {
      type: Number
    },
    currentStage: {
      type: Number
    },
    preselectStages: {
      type: Number
    },
    specialcontrolList: {
      type: Array
    },
    realtimeStatusModalvisible: { // 区分是保存方案还是提交方案，保存方案没有路口实时信息
      type: Boolean,
      default: true
    },
    funcSort: {
      type: String,
      default: 'allFunc'
    },
    roadDirection: {
      type: String
    },
    statusData: {
      type: Object
    },
    specialControlList: {
      type: Array
    },
    othersControlList: {
      type: Array
    },
    closePhaseRings: {
      type: Array
    },
    sidewalkPhaseData: {
      type: Array
    },
    overlap: {
      type: Array
    },
    allPatternList: {
      type: Array
    },
    patternChooseControlList: {
      type: Array
    },
    isShowBack: {
      type: Boolean,
      default: true
    },
    isShowRecovery: {
      type: Boolean,
      default: true
    },
    isShowImplement: {
      type: Boolean,
      default: true
    },
    thirdPartyControlMenu: {
      type: Array
    },
    thirdPartyControl: {
      type: Array
    },
    protocol: {
      type: String
    }
  },
  watch: {
    patternSelect: {
      handler: function (val) {
        this.manualInfo.tempPatternid = this.crossStatusData.patternid
      },
      // 深度观察监听
      deep: true
    },
    crossStatusData: {
      handler: function (val) {
        this.manualInfo.tempPatternid = this.manualInfo.tempPatternid ? this.manualInfo.tempPatternid : val.patternid
        this.realtimeStage = JSON.parse(JSON.stringify(this.crossStatusData))
      },
      // 深度观察监听
      deep: true
    }
  },
  data () {
    return {
      visible: this.Visible,
      manuals: false,
      realtimeStage: {},
      manualsStage: {},
      manualInfo: {
        tempPatternid: '', // 控制方式手动操作的情况下的控制编号的临时值。
        // tempDelay: 0, // 控制方式手动操作的情况下的延迟时间的临时值。
        tempDuration: 300 // 控制方式手动操作的情况下的持续时间的临时值。
      },
      activeName: 'residentcontrol',
      preselecttype: '',
      keyChange: false,
      isRing: false,
      patternOne: [],
      planPattern: {}
    }
  },
  methods: {
    handleClick (tab, event) {
      this.$nextTick(() => {
        this.init(tab)
      })
    },
    isHasPermission (path) {
      let res = hasPermission(path)
      return res
    },
    handleSelectPatternOption (value) {
      if (value === '') {
        this.manualInfo.tempPatternid = 0
        return
      }
      this.changeStage(value)
      this.selectPattern()
    },
    selectPattern () {
      this.manualInfo.offset = 0
      let selectId = Number(this.manualInfo.tempPatternid)
      this.patternOne = this.allPatternList.filter(item => {
        return item.id === selectId
      })
      this.manualInfo.offset = this.offset
      for (let rings of this.patternOne[0].rings) {
        if (rings.length === 0) continue
        for (let ring of rings) {
          if (ring.value === 0) continue
          let currPhase = this.phaseList.filter((item) => {
            return item.id === ring.id
          })[0]
          ring.desc = currPhase.direction.map(item => {
            return {
              id: item,
              color: '#454545'
            }
          })
        }
      }
      this.handleStageData(this.patternOne[0].rings)
    },
    handleStageData (rings) { // stagesList
      if (!rings) return
      for (let i = 0; i < rings.length; i++) {
        if (rings[i].length > 0) {
          let phaseList = []
          let stagesList = []
          // rings = JSON.parse(JSON.stringify(rings))
          let mapAdd = rings.map(item => {
            return item.map(val => {
              // if (val.mode !== 7) {
              return val.value + (val.sum ? val.sum : 0)
              // } else {
              //   return 0
              // }
            })
          })
          let maxCycle = mapAdd.length > 0 ? mapAdd.map(item => {
            return item.length > 0 ? item.reduce((a, b) => {
              return a + b
            }) : 0
          }) : 0
          this.max = Math.max(...maxCycle)// 每个环的周期最大值
          this.stateList = [0]
          this.narr = []
          let currentIds = ''
          let lastCurrentIds = ''
          for (let j = 0; j <= this.max; j++) { // 指针长度
            for (let i = 0; i < rings.length; i++) { // 环列表
              let ring = rings[i]// 每个环对象
              let sum = 0
              for (let n = 0; n < ring.length; n++) { // 相位累计长度
                // if (ring[n].mode !== 7) {
                sum = sum + ring[n].value + (ring[n].sum ? ring[n].sum : 0)
                if (j < sum) {
                  let phaseId = ring[n].id
                  currentIds = currentIds + '-' + phaseId
                  break
                }
                // }
              }
            }
            if (lastCurrentIds !== currentIds && lastCurrentIds !== '') { // 当前相位id和上一个相比不同说明相位变化了
              phaseList.push(lastCurrentIds)
              this.stateList.push(j)// 阶段累计长度的集合
            }
            lastCurrentIds = currentIds
            currentIds = ''
          }
          let newPhaselist = []
          phaseList.forEach(i => {
            let rangeArr = i.split('-').map(Number)
            if (rangeArr.length > 2) {
              newPhaselist.push([
                JSON.parse(JSON.stringify(rangeArr[1])),
                JSON.parse(JSON.stringify(rangeArr[2]))
              ])
            } else {
              newPhaselist.push([
                JSON.parse(JSON.stringify(rangeArr[1]))
              ])
            }
          })
          for (let i = this.stateList.length - 1; i >= 1; i--) {
            this.narr.push(this.stateList[i] - this.stateList[i - 1])
          }
          // newPhaselist
          this.narr.reverse()// 阶段差
          for (let i = 0; i < newPhaselist.length; i++) {
            let stage = JSON.parse(JSON.stringify(newPhaselist[i]))
            let newStage = []
            stage.map(item => {
              for (let ring of rings) {
                for (let ringItem of ring) {
                  if (item === ringItem.id && (ringItem.mode !== 7 && ringItem.mode !== 8 && ringItem.mode !== 9)) {
                    newStage.push(item)
                  }
                }
              }
            })
            let stageItem = this.getStageItem(newStage, stage, rings, i)
            stagesList.push(JSON.parse(JSON.stringify(stageItem)))
          }
          this.overLapCycle = stagesList.reduce((prev, curr) => prev + parseInt(curr.split), 0)
          this.stagesList = JSON.parse(JSON.stringify(stagesList))
        }
      }
    },
    getCycle () {
      for (let rings of this.planPattern.rings) {
        let num = 0
        for (let i = 0; i < rings.length; i++) {
          if (rings[i].length !== 0) {
            if (rings[i].mode === 7) { // 忽略相位不计周期
              continue
            }
            num = num + Number(rings[i].value)
          }
        }
        if (num !== 0) {
          this.planPattern.cycle = num
          break
        }
      }
    },
    patternPlan () {
      let Pattern = {
        offset: 0,
        cycle: 0,
        stagesList: [],
        rings: [[], [], [], []]
      }
      var newPattern = JSON.parse(JSON.stringify(Pattern))
      for (let phase of this.phaseList) {
        let ring = {}
        ring.name = 'Phase ' + phase.id
        // ring.desc = this.getPhaseDescription(phase.direction)
        ring.id = phase.id
        ring.value = 30
        ring.mode = 2
        ring.options = []
        ring.delaystart = 0
        ring.advanceend = 0
        if (phase.ring === 1) {
          newPattern.rings[0].push(ring)
        } else if (phase.ring === 2) {
          newPattern.rings[1].push(ring)
        } else if (phase.ring === 3) {
          newPattern.rings[2].push(ring)
        } else if (phase.ring === 4) {
          newPattern.rings[3].push(ring)
        }
      }
      let barrier = this.handleCurrentChange(newPattern.rings)
      newPattern.barriers = barrier
      this.planPattern = newPattern
    },
    tranform (arr) { // 分barrier
      let newMap = new Map()
      arr.forEach(({ id, current }) => {
        const find = newMap.get(current.join())
        if (find) newMap.get(current.join()).push(id)
        else newMap.set(current.join(), [id])
      })
      let ret = []
      newMap.forEach((value, key) => {
        ret.push(Array.from(new Set(key.split(',').map(Number).concat(value))))
      })
      const result = []
      for (const a of ret) {
        let merged = false
        for (const r of result) {
          if (this.check([...r], a)) {
            a.forEach(item => r.add(item))
            merged = true
          }
        }
        if (!merged) {
          result.push(new Set(a))
        }
        merged = false
      }
      return result.map(s => [...s])
    },
    check (arr1, arr2) {
      return arr1.some(a1 => arr2.some(a2 => a1 === a2))
    },
    handleCurrentChange (val) { // 两个ring的数据
      if (val === null || val.length === 0) return
      // 按环序分组
      let ringlength = []
      let ringsequence = val.map(item => {
        if (item.length === 0) return
        ringlength.push(item.length)
        return item.map(k => {
          return k.id
        })
      })
      let newRings = ringsequence.filter(item => item)
      let minLength = Math.min(...ringlength)
      let resultArrs = [] // 环1分组
      let resultArr = [] // 环2分组
      for (let j = 0; j < ringsequence[0].length; j += minLength) {
        resultArrs.push(ringsequence[0].slice(j, j + minLength))
        if (ringsequence[0].length === minLength) {
          resultArrs.push([])
        }
      }
      if (newRings.length > 1) {
        for (let i = 0; i < ringsequence[1].length; i += minLength) {
          resultArr.push(ringsequence[1].slice(i, i + minLength))
        }
      }
      // this.patternInfo = []
      // this.barrierList = []
      let currentArr = []
      let newPattern = []
      val.map(i => {
        newPattern.push(...i)
      })
      if (this.phaseList.length === 0) return
      for (let patternStatus of val[0]) {
        // if (patternStatus.mode !== 7) {
        let concurrent = this.phaseList.filter((item) => {
          return item.id === patternStatus.id // patternStatus.id当前相位id concurrent当前相位的并发相位
        })[0].concurrent// 当前相位的并发相位
        if (concurrent) {
          let obj = {
            id: patternStatus.id,
            current: concurrent.sort()
          }
          currentArr.push(obj)
        }
        // }
      }
      if (currentArr.length !== 0) {
        let newCurrent = this.tranform(currentArr)
        // 取没个环与环关系的并集
        let barrierRing1 = []
        let barrierRing2 = []
        let ring1 = [] // 环1与关系1的并集
        for (let h = 0; h < newCurrent.length; h++) {
          let adds = [...new Set(resultArrs[0])].filter(item => newCurrent[h].includes(item))
          ring1.push(adds)
        }
        let ring1s = [] // 环1与关系2的并集
        for (let h = 0; h < newCurrent.length; h++) {
          let addRing1 = [...new Set(resultArrs[1])].filter(item => newCurrent[h].includes(item))
          ring1s.push(addRing1)
        }
        barrierRing1.push(...ring1, ...ring1s)
        let resultList = []
        if (newRings.length > 1) {
          let ring2s = [] // 环2与关系1的并集
          for (let h = 0; h < newCurrent.length; h++) {
            let addRing2 = [...new Set(resultArr[1])].filter(item => newCurrent[h].includes(item))
            ring2s.push(addRing2)
          }
          let ring2 = [] // 环2与关系1的并集
          for (let h = 0; h < newCurrent.length; h++) {
            let add = [...new Set(resultArr[0])].filter(item => newCurrent[h].includes(item))
            ring2.push(add)
          }
          barrierRing2.push(...ring2, ...ring2s)
          for (let k = 0; k < barrierRing1.length; k++) {
            resultList.push(barrierRing1[k].concat(barrierRing2[k]))
          }
        }
        let resultLists = resultList.filter(item => item.length !== 0)
        let ringArr = []
        for (let l = 0; l < resultLists.length; l++) {
          for (let d = 0; d < newCurrent.length; d++) {
            if (newCurrent[d].filter(item => resultLists[l].includes(item)).length > 0) {
              ringArr.push({
                data: resultLists[l],
                id: d + 1,
                index: l
              })
            }
          }
        }
        for (var i = 0; i < ringArr.length; i++) {
          for (var j = i + 1; j < ringArr.length; j++) {
            if (ringArr[i].id === ringArr[j].id && ringArr[i].index + 1 === ringArr[j].index) {
              ringArr[i].data = ringArr[i].data.concat(ringArr[j].data)
              ringArr.splice(ringArr.indexOf(ringArr[j].id), 1)
            }
          }
        }
        let resArr = ringArr.map(item => item.data)
        let ringTeam = this.step1(this.phaseList, resArr)
        let ringTeams = ringTeam.filter(item => item.length !== 0)
        return this.setBarrier(ringTeams, val)
      }
    },
    setBarrier (ringTeam, val) {
      const patternObjs = {}
      val.forEach(l => {
        l.map(k => {
          patternObjs[k.id] = k.value
        })
      })
      let ret = ringTeam.map((y, index) => {
        if (!y || y.length === 0) return
        y.map(n => {
          n.length = n.data.length > 1 ? n.data.reduce((pre, cur) => pre + patternObjs[cur], 0) : patternObjs[n.data[0]]
        })
        return {
          barrier: index + 1,
          length: y[0].length,
          items: y.map(j => {
            return {
              ring: j.ring,
              data: j.data
            }
          })
        }
      })
      return ret
    },
    step1 (list, arr) { // 各个环包含的相位
      const ret = []
      const listObj = {}
      list.forEach(l => {
        listObj[l.id] = l.ring
      })
      arr.forEach(a => {
        const retItem = []
        a.forEach(b => {
          if (listObj[b]) {
            const find = retItem.find(r => r.ring === listObj[b])
            if (find) find.data.push(b)
            else retItem.push({ ring: listObj[b], data: [b] })
          }
        })
        ret.push(retItem)
      })
      return ret
    },
    getStageItem (stageArr, stage, ringsList, i) {
      let res = {
        key: i,
        split: this.narr[i], // 阶段绿性比
        phases: stageArr,
        stageKanban: stage,
        delaystart: 0,
        advanceend: 0
      }
      // let splitArr = []
      let delaystartArr = []
      let advanceendArr = []
      for (let rings of ringsList) {
        for (let ring of rings) {
          if (stageArr.includes(ring.id)) {
            // let split = ring.value
            let delaystart = ring.delaystart
            let advanceend = ring.advanceend
            // splitArr.push(split)
            delaystartArr.push(delaystart)
            advanceendArr.push(advanceend)
          }
        }
      }
      // splitArr.sort(function (a, b) { return a - b })
      delaystartArr.sort(function (a, b) { return b - a })
      advanceendArr.sort(function (a, b) { return a - b })
      // res.split = splitArr.length > 0 ? splitArr[0] : 0
      res.delaystart = delaystartArr.length > 0 ? delaystartArr[0] : 0
      res.advanceend = advanceendArr.length > 0 ? advanceendArr[0] : 0
      return res
    },
    changeStage (value) {
      if (value) {
        this.manualsStage = {}
        this.manuals = true
        let stages = []
        let secletIds = isNaN(parseInt(value)) ? Number(value.replace(/[^0-9]/ig, '')) : value
        stages = this.patternAll.filter(item => {
          return item.id === secletIds
        })[0].stages
        this.manualsStage.stages = stages
      } else {
        this.manuals = false
        this.realtimeStage = JSON.parse(JSON.stringify(this.crossStatusData))
      }
    },
    handleClose () {
      this.$emit('closeManualModal')
    },
    handleManualControl () {
      this.$emit('patternCommit', this.manualInfo)
    },
    selectModel (item) {
      this.preselecttype = item.type
      this.manualInfo.fromControl = item.id
      if (item.iconClass === 'jieduansuoding') {
        this.manualInfo.fromControl = 40
      }
      this.$emit('selectModel', item.id)
    },
    selectStages (value) {
      this.$emit('selectStages', value)
    },
    selectSpecialModel () {
      this.$emit('selectSpecialModel')
    },
    init (tab) {
      this.$refs.ControlModelGroup.init()
      if (!tab) return
      if (this.controlData.patternid) {
        this.manualInfo.tempPatternid = this.controlData.patternid
      }
      if (this.controlData.tempDuration) {
        this.manualInfo.tempDuration = this.controlData.duration
      }
      if (tab.name === 'schemeselection') {
        this.initPattern()
        this.selectPattern()
      }
    },
    closePhaseBack () {
      this.$emit('closePhaseBack')
    },
    closePhaseControl (controldata) {
      this.$emit('closePhaseControl', controldata)
    },
    initPattern () {
      this.patternPlan()
      this.getCycle()
      if (this.patternOne.length === 0) {
        this.handleStageData(this.planPattern.rings)
      }
    },
    toAutoControl () {
      let autonomyControl = {
        id: 0,
        iconClass: 'zizhukongzhi',
        permission: 'configer:manual:renew',
        iconName: '自主控制'
      }
      this.$emit('selectModel', autonomyControl.id)
      this.handleManualControl()
    }
  },
  mounted () {
  }
}
</script>
