<template>
  <div class="tentativeplan-control manual-common-content">
    <!-- <div class="title" style="margin-bottom: 18px">
      {{ $t('openatccomponents.overview.tentativeplan') }}
    </div> -->
    <el-row>
      <el-col :span="12">
        <el-form
          ref="manual"
          label-position="left"
          :model="manualInfo"
          label-width="90px"
        >
          <el-form-item
            :label="$t('openatccomponents.overview.patternid')"
            prop="count"
          >
            <el-select
              @change="selectPattern()"
              v-model="manualInfo.tempPatternid"
              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-input v-model="manualInfo.tempDuration" size="small" :placeholder="$t('openatccomponents.common.input')"></el-input> -->
          </el-form-item>
          <el-form-item
            :label="$t('openatccomponents.overview.delay')"
            prop="intersection"
          >
            <el-input-number
              :placeholder="$t('openatccomponents.common.input')"
              :min="0"
              :max="65535"
              :precision="0"
              :step="1"
              :controls="false"
              v-model.number="manualInfo.tempDelay"
              size="small"
            ></el-input-number>
            <!-- <el-input v-model="manualInfo.tempDelay" size="small" :placeholder="$t('openatccomponents.common.input')"></el-input> -->
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="12">
        <el-form
          ref="manual"
          label-position="left"
          :model="manualInfo"
          label-width="90px"
        >
          <el-form-item
            :label="$t('openatccomponents.overview.patternoffset')"
            prop="count"
          >
            <el-input-number
              :placeholder="$t('openatccomponents.common.input')"
              :min="0"
              :max="65535"
              :precision="0"
              :step="1"
              :controls="false"
              v-model.number="manualInfo.offset"
              size="small"
            ></el-input-number>
            <!-- <el-input v-model="manualInfo.offset" size="small" :placeholder="$t('openatccomponents.common.input')"></el-input> -->
          </el-form-item>
          <el-form-item
            :label="$t('openatccomponents.overview.duration')"
            prop="intersection"
          >
            <el-input-number
              :placeholder="$t('openatccomponents.common.input')"
              :min="0"
              :max="65535"
              :precision="0"
              :step="1"
              :controls="false"
              v-model.number="manualInfo.duration"
              size="small"
            ></el-input-number>
            <!-- <el-input v-model="manualInfo.duration" size="small" :placeholder="$t('openatccomponents.common.input')"></el-input> -->
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    <el-row style="margin-top: 20px;">
      <el-radio v-model="isRing" :label="false" @change="changeRing">{{
        $t('openatccomponents.common.ringStyle')
      }}</el-radio>
      <el-radio v-model="isRing" :label="true" @change="changeStage">{{
        $t('openatccomponents.common.stageStyle')
      }}</el-radio>
      <!-- <div class="title" style="margin-top:18px; margin-bottom:10px">{{$t('openatccomponents.overview.patternstate')}}:
            <span>({{$t('openatccomponents.overview.cycle')}}: {{cycle}}  {{$t('openatccomponents.overview.patternoffset')}}: {{offset}})</span>
        </div> -->
      <!-- <stage-status
        :patternStatusList="patternOne.length===0?planPattern.rings:patternOne[0].rings"
        >
        </stage-status> -->
      <pattern-list
        :key="keyChange"
        :allPatternList="allPatternList"
        :contrloType="contrloType"
        :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>
    </el-row>
    <el-row style="margin-top: 20px;">
      <el-tabs v-model="activeTab" type="card">
        <el-tab-pane
          v-if="!isRing"
          :label="$t('openatccomponents.pattern.ringConfig')"
          name="kanban"
        >
          <div style="width: 100%; overflow: hidden;">
            <kan-ban
              v-for="n in ringCount"
              :key="n"
              class="closephasekanban"
              :index="n"
              :options="options"
              :list="
                patternOne.length === 0
                  ? planPattern.rings[n - 1]
                  : patternOne[0].rings[n - 1]
              "
              :phaseList="phaseList"
              :header-text="$t('openatccomponents.pattern.ring') + n"
              @handleSplit="handleSplit"
            >
            </kan-ban>
          </div>
        </el-tab-pane>
        <!-- <el-tab-pane v-if="isRing" :label="$t('openatccomponents.pattern.stageConfig')" name="kanban">
              <div class="stage-panel-contener">
                <StageKanban
                  v-for="(stage, index) in scope.row.stagesList"
                  class="kanban todo"
                  :key="index"
                  :stage="stage"
                  :stageInfo="scope.row.stagesList"
                  :isRing="isRing"
                  :options="scope.row.options"
                  :coordphaseOption="coordphaseOption"
                  :rowIndex="scope.$index"
                  :subIndex="index"
                  @onStageSplitChange="onStageSplitChange"
                  @stageSplitChange="stageSplitChange"
                  @onStageDelaystartChange="onStageDelaystartChange"
                  @onStageAdvanceendChange="onStageAdvanceendChange"
                />
                <div v-if="isRing" style="margin-left: 20px">
                  <el-button
                    type="primary"
                    @click="addStage(scope.row.stagesList)"
                    icon="el-icon-plus"
                    circle
                  ></el-button>
                </div>
              </div>
            </el-tab-pane> -->
        <el-tab-pane
          v-if="isRing"
          :label="$t('openatccomponents.pattern.stageConfig')"
          name="ring"
        >
          <div class="stage-panel-contener">
            <stage-bord
              v-for="(stage, index) in patternOne.length === 0
                ? planPattern.stagesList
                : patternOne[0].stagesList"
              class="kanban todo"
              :key="index"
              :stage="stage"
              :options="options"
              :isRing="isRing"
              :stageInfo="
                patternOne.length === 0
                  ? planPattern.stagesList
                  : patternOne[0].stagesList
              "
              :coordphaseOption="coordphaseOption"
              :subIndex="index"
              @onStageSplitChange="onStageSplitChange"
              @stageSplitChange="stageSplitChange"
              @onStageDelaystartChange="onStageDelaystartChange"
              @onStageAdvanceendChange="onStageAdvanceendChange"
            >
            </stage-bord>
            <div v-if="isRing" style="margin-left: 10px">
              <el-button
                type="primary"
                @click="
                  addStage(
                    patternOne.length === 0
                      ? planPattern.stagesList
                      : patternOne[0].stagesList
                  )
                "
                icon="el-icon-plus"
                circle
              ></el-button>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane
          v-if="!isRing"
          :label="$t('openatccomponents.pattern.parameters')"
          name="parame"
        >
          <el-row>
            <expend-config
              v-for="(j, index) in ringCounts"
              :key="index"
              class="expendkanban"
              :options="options"
              :header-text="$t('openatccomponents.pattern.ring') + j"
              :list="
                patternOne.length === 0
                  ? planPattern.rings[j - 1]
                  : patternOne[0].rings[j - 1]
              "
            >
            </expend-config>
            <div class="forbiddenstage">
              {{ $t('openatccomponents.pattern.forbiddenstage') }}
              <el-input
                class="stage-value"
                size="small"
                v-model="forbiddenstage"
              ></el-input>
            </div>
            <div class="forbiddenstage">
              {{ $t('openatccomponents.pattern.screenstage') }}
              <el-input
                class="stage-value"
                size="small"
                v-model="screenstage"
              ></el-input>
            </div>
            <div class="forbiddenstage">
              {{ $t('openatccomponents.pattern.coordinatestage') }}
              <el-input
                class="stage-value"
                size="small"
                v-model="coordinatestage"
              ></el-input>
            </div>
          </el-row>
        </el-tab-pane>
        <el-tab-pane
          v-if="!isRing"
          :label="$t('openatccomponents.pattern.overLap')"
          name="overlap"
        >
          <el-row :gutter="20">
            <el-col :span="24">
              <over-lap
                :stageList="stagesList"
                :overlap="overlap"
                :checked="true"
                :tentative="true"
                :cycleChange="false"
                :cycle="overLapCycle"
              >
              </over-lap>
            </el-col>
          </el-row>
        </el-tab-pane>
        <el-tab-pane
          v-if="!isRing"
          :label="$t('openatccomponents.pattern.patternOptimize')"
          name="patternOptimize"
        >
          <pattern-optimize
            class="expendkanban"
            :rings="patternOne.length === 0 ? planPattern : patternOne[0]"
            :phaseList="phaseList"
            :tableRing="tableRing"
            :showStyle="showStyle"
            :styles="styles"
            :isTentative="true"
            @handleSplit="handleSplit"
          >
          </pattern-optimize>
          <!-- ref="patternOptimize"
                :tableRing="tableRing"
                :id="selectedRow.id"
                @optimizesucess="optimizesucess" -->
        </el-tab-pane>
      </el-tabs>
    </el-row>
    <div class="footer">
      <el-button v-if="isShowBack" @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>
  </div>
</template>

<script>
import { hasPermission } from '../../../../utils/auth'
import PhaseDataModel from '../../IntersectionMap/crossDirection/utils.js'
import CrossDiagramMgr from '../../../../EdgeMgr/controller/crossDiagramMgr.js'
export default {
  name: 'tentativeplancontrol',
  props: {
    realtimeStatusModalvisible: {
      type: Boolean,
      default: true
    },
    controlData: {
      type: Object
    },
    phaseList: {
      type: Array
    },
    overlap: {
      type: Array
    },
    allPatternList: {
      type: Array
    },
    patternSelect: {
      type: Array
    },
    isShowBack: {
      type: Boolean,
      default: true
    },
    isShowRecovery: {
      type: Boolean,
      default: true
    },
    isShowImplement: {
      type: Boolean,
      default: true
    }
  },
  watch: {
    isRing (newVal) {
      this.activeTab = newVal ? 'ring' : 'kanban'
    }
  },
  computed: {
    computedActiveTab () {
      return this.isRing ? 'ring' : 'kanban'
    },
    rings () {
      return this.patternOne.length === 0 ? this.planPattern.rings : this.patternOne[0].rings
    },
    cycle () {
      return this.patternOne.length === 0 ? this.max : (this.patternOne.length > 0 && (this.patternOne[0].cycle < this.max)) ? this.max : this.patternOne[0].cycle
    },
    offset () {
      return Number((this.patternOne.length === 0 || this.manualInfo.offset > 0) ? this.manualInfo.offset : this.patternOne[0].offset)
    },
    forbiddenstage () {
      return this.patternOne.length === 0 ? this.allPatternList[0].forbiddenstage : this.patternOne[0].forbiddenstage
    },
    screenstage () {
      return this.patternOne.length === 0 ? this.allPatternList[0].screenstage : this.patternOne[0].screenstage
    },
    coordinatestage () {
      return this.patternOne.length === 0 ? this.allPatternList[0].coordinatestage : this.patternOne[0].coordinatestage
    }
  },
  data () {
    return {
      stagesList: [],
      phaseRings: [],
      keyChange: false,
      overLapCycle: 0,
      options: {
        group: 'pattern'
      },
      styles: {
        left: '2px',
        top: 0
      },
      showStyle: {
        left: '2px',
        top: 0
      },
      max: '',
      tableRing: [],
      contrloType: '',
      patternCycleEqual: true,
      // activeList: 'ring',
      activeTab: 'kanban',
      isRing: false,
      // isChange: false,
      ringCount: 1,
      ringCounts: 1,
      barriers: [],
      optimizes: 1,
      coordphaseOption: [],
      patternOne: [],
      planPattern: {},
      manualInfo: {
        tempPatternid: '',
        offset: 0,
        duration: 300,
        tempDelay: 0 // 控制方式手动操作的情况下的延迟时间的临时值。
        // tempDuration: 300 // 控制方式手动操作的情况下的持续时间的临时值。
      }
    }
  },
  created () {
    this.PhaseDataModel = new PhaseDataModel()
    this.CrossDiagramMgr = new CrossDiagramMgr()
    this.patternPlan()
    this.getCycle()
    if (this.patternOne.length === 0) {
      this.handleStageData(this.planPattern.rings)
    }
    this.initData()
    if (!this.allPatternList[0].contrloType && this.allPatternList[0].rings.length > 0) {
      this.contrloType = 'ring'
    } else if (!this.allPatternList[0].contrloType && this.allPatternList[0].rings.length === 0) {
      this.contrloType = 'stage'
    } else {
      this.contrloType = this.allPatternList[0].contrloType
    }
    for (let i = 0; i < this.allPatternList.length; i++) {
      if (this.allPatternList[i].contrloType === 'stage' || (this.isRing && !this.allPatternList[i].contrloType)) {
        this.isRing = true
        // this.setStageList(this.allPatternList[i].stagesList, this.allPatternList[i].id)
      } else if (this.allPatternList[i].contrloType === 'ring' || (!this.isRing && !this.allPatternList[i].contrloType && this.allPatternList[i].rings.length > 0)) {
        this.isRing = false
        // this.handleStageData(this.allPatternList[i].rings)
      } else if (this.allPatternList[i].rings.length === 0 && this.allPatternList[i].stagesList.length > 0) {
        this.isRing = true
        // this.setStageList(this.allPatternList[i].stagesList, this.allPatternList[i].id)
      }
    }
  },
  methods: {
    addStage (row) {
      // this.isChange = false
      if (row.length > 15) {
        this.$message.error(
          this.$t('openatccomponents.pattern.mostlist')
        )
        return
      }
      if (this.patternOne.length !== 0) {
        this.patternOne[0].stagesList.push({
          key: row.length,
          green: 25,
          yellow: 3,
          red: 2,
          stageNo: 0,
          phases: [],
          stageSplit: 30
        })
      } else {
        this.planPattern.stagesList.push({
          key: row.length,
          green: 25,
          yellow: 3,
          red: 2,
          phases: [],
          stageSplit: 30
        })
      }
    },
    changeRing () {
      this.contrloType = 'ring'
      this.isRing = false
      // const globalParamModel = this.$store.getters.globalParamModel
      // let pattern = globalParamModel.getParamsByType('patternList')
      // let pattern = this.allPatternList
      this.getCycle()
      this.patternOne = this.allPatternList.filter(item => {
        return item.id === Number(this.manualInfo.tempPatternid)
      })
      // if (this.isChange) {
      //   for (let i = 0; i < pattern.length; i++) {
      this.handleStageData(this.patternOne.rings)
      //   }
      // } else {
      //   for (let i = 0; i < pattern.length; i++) {
      //     this.setStageList(pattern[i].stagesList, pattern[i].id)
      //   }
      // }
    },
    changeStage () {
      this.contrloType = 'stage'
      this.isRing = true
      // this.patternOne = this.allPatternList.filter(item => {
      //   return item.id === Number(this.manualInfo.tempPatternid)
      // })
      // this.getStageCycle()
    },
    getStageCycle () {
      // this.patternOne.length === 0 ? this.allPatternList this.patternOne
      if (this.patternOne.length === 0) {
        // this.setStageList(this.planPattern.stagesList, this.planPattern.id)
        // this.planPattern.stagesList = []
      } else {
        //   this.patternOne = this.allPatternList.filter(item => {
        //   return item.id === Number(this.manualInfo.tempPatternid)
        // })
        // this.setStageList(this.patternOne[0].stagesList, this.patternOne[0].id)
      }
    },
    setStageList (stageChange, id) {
      // let patternList = this.globalParamModel.getParamsByType('patternList')
      // let patternList = this.allPatternList
      let stagesList = []
      for (let i = 0; i < stageChange.length; i++) {
        let stage = JSON.parse(JSON.stringify(stageChange[i]))
        let stageItem = this.getStageItems(stage.phases, i, stageChange)
        stagesList.push(JSON.parse(JSON.stringify(stageItem)))
      }
      (this.patternOne.length === 0 ? this.planPattern : this.patternOne).map(item => { // 添加特征参数stage
        if (item.id === id) {
          if (this.isRing) {
            item.contrloType = 'stage'
          } else {
            item.contrloType = 'ring'
          }
          item.stagesList = JSON.parse(JSON.stringify(stagesList.filter(item => item.stageSplit)))
        }
      })
      this.stagesList = stagesList.filter(item => item.stageSplit)
    },
    getStageItems (stageArr, i, stageChange) {
      let res = {
        key: i,
        split: this.narr[i], // 阶段绿性比
        phases: stageArr,
        delaystart: 0,
        advanceend: 0
      }
      for (let rings of stageChange) {
        if (i === rings.key) {
          res.green = rings.green ? rings.green : rings.green === 0 ? 0 : 25
          res.yellow = rings.yellow ? rings.yellow : rings.yellow === 0 ? 0 : 3
          res.red = rings.red ? rings.red : rings.red === 0 ? 0 : 2
          res.phases = rings.phases ? rings.phases : stageArr
          res.stageNo = rings.stageNo ? rings.stageNo : 0
          // res.stageSplit = rings.split ? rings.split : 30
          if (rings.split) {
            res.stageSplit = rings.split
          } else if (rings.stageSplit) {
            res.stageSplit = rings.stageSplit
          } else {
            res.stageSplit = 0
          }
        }
      }
      return res
    },
    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
    },
    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)
        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
      const flatArray = this.planPattern.rings.flat().filter(item => item !== null)
      this.tableRing = flatArray.map(item => {
        return {
          id: item.id,
          desc: item.desc,
          flowperhour: item.flowperhour ? item.flowperhour : 0,
          saturation: item.saturation ? item.saturation : 0
        }
      })
    },
    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
        }
      }
    },
    getCycles () {
      if (!this.patternOne[0].stages) return
      let stages = this.patternOne[0].stages
      let modeId = stages.filter(item => item.length === 1)[0]
      for (let rings of this.patternOne[0].rings) {
        let num = 0
        for (let i = 0; i < rings.length; i++) {
          if (rings[i].length !== 0) {
            if (rings[i].mode === 7 && (modeId && modeId[0] === rings[i].id)) { // 忽略相位不计周期
              continue
            }
            num = num + Number(rings[i].value)
          }
        }
        if (num !== 0) {
          this.patternOne[0].cycle = num
          break
        }
      }
    },
    // getPhaseDescription (phaseList) {
    //   if (!phaseList) return
    //   let list = []
    //   for (let id of phaseList) {
    //     let obj = {}
    //     obj.id = id
    //     obj.color = '#454545'
    //     list.push(obj)
    //   }
    //   return list
    // },
    getPedPhasePos () {
      // 行人相位信息
      this.sidewalkPhaseData = []
      // let phaseList = this.globalParamModel.getParamsByType('phaseList')
      this.phaseList.forEach((ele, i) => {
        if (ele.peddirection) {
          ele.peddirection.forEach((dir, index) => {
            // 行人相位
            if (this.PhaseDataModel.getSidePos(dir)) {
              this.sidewalkPhaseData.push({
                key: this.CrossDiagramMgr.getUniqueKey('pedphase'),
                phaseid: ele.id, // 相位id，用于对应相位状态
                id: dir,
                name: this.PhaseDataModel.getSidePos(dir).name
              })
            }
          })
        }
      })
      return this.sidewalkPhaseData
    },
    getPhaseDescription (phaseList) {
      let list = []
      let peddirections = []
      let sidewalkPhaseData = this.getPedPhasePos()
      for (let walk of sidewalkPhaseData) {
        if (phaseList.peddirection) {
          for (let ped of phaseList.peddirection) {
            // if (stg === walk.phaseid) {
            let obj = {}
            obj.name = walk.name
            obj.id = walk.id
            if (ped === walk.id) {
              peddirections.push(obj)
              peddirections = Array.from(new Set(peddirections))
            }
            // }
          }
        } else {
          peddirections = []
        }
      }
      if (phaseList.direction.length > 0) {
        for (let id of phaseList.direction) {
          let obj = {}
          obj.id = id
          obj.peddirection = peddirections
          obj.color = '#454545'
          list.push(obj)
        }
      } else {
        let obj = {}
        obj.id = ''
        obj.peddirection = peddirections
        obj.color = '#454545'
        list.push(obj)
      }
      return list
    },
    handleClose () {
      this.$emit('closePhaseBack')
    },
    onStageSplitChange (diff, rowIndex, subIndex) {
      let stageArr = this.stagesList[subIndex].stages
      let row = this.patternList[rowIndex]
      let ringsList = row.rings
      for (let rings of ringsList) {
        for (let ring of rings) {
          if (stageArr.includes(ring.id)) {
            ring.value = (ring.value ? ring.value : 0) + diff
            continue
          }
        }
      }
    },
    stageSplitChange (diff, rowIndex, subIndex) {
      let row = this.patternOne.length === 0 ? this.planPattern : this.patternOne
      let ringsList = this.patternOne.length === 0 ? row.stagesList : row[0].stagesList
      for (let rings of ringsList) {
        // if (subIndex === rings.key) {
        rings.stageSplit = (rings.green ? rings.green : 0) + (rings.yellow ? rings.yellow : 0) + (rings.red ? rings.red : 0)
        continue
        // }
      }
    },
    onStageDelaystartChange (diff, rowIndex, subIndex) {
      let stageArr = this.stagesList[subIndex].stages
      let row = this.patternList[rowIndex]
      let ringsList = row.rings
      for (let rings of ringsList) {
        for (let ring of rings) {
          if (stageArr.includes(ring.id)) {
            ring.delaystart = (ring.delaystart ? ring.delaystart : 0) + diff
            continue
          }
        }
      }
    },
    onStageAdvanceendChange (diff, rowIndex, subIndex) {
      let stageArr = this.stagesList[subIndex].stages
      let row = this.patternList[rowIndex]
      let ringsList = row.rings
      for (let rings of ringsList) {
        for (let ring of rings) {
          if (stageArr.includes(ring.id)) {
            ring.advanceend = (ring.advanceend ? ring.advanceend : 0) + diff
            continue
          }
        }
      }
    },
    handleSplit (index) {
      if (this.patternOne.length > 0) {
        let currPattern = this.patternOne[0].rings
        setTimeout(() => {
          this.handleStageData(currPattern)
          this.getCycles()
          // this.patternOne[0].stagesList = this.stagesList
        }, 50)
      } else {
        let currPattern = this.planPattern.rings
        setTimeout(() => {
          this.handleStageData(currPattern)
          this.getCycle()
          // this.allPatternList[0].stagesList = this.stagesList
        }, 50)
      }
    },
    selectPattern () {
      this.manualInfo.offset = 0
      let selectId = Number(this.manualInfo.tempPatternid)
      this.patternOne = this.allPatternList.filter(item => {
        return item.id === selectId
      })
      // if (this.patternOne[0].contrloType === 'stage') {
      //   this.changeStage()
      // }
      const flatArray = this.patternOne[0].rings.flat().filter(item => item !== null)
      this.tableRing = flatArray.map(item => {
        return {
          id: item.id,
          desc: item.desc,
          flowperhour: item.flowperhour ? item.flowperhour : 0,
          saturation: item.saturation ? item.saturation : 0
        }
      })
      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))
        }
      }
    },
    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
    },
    initData () {
      // 判断有几个环，就创建几个看板
      // let phaseList = this.globalParamModel.getParamsByType('phaseList')
      // this.coordphaseOption = this.phaseList.map(ele => {
      //   return {
      //     value: ele.id
      //   }
      // })
      this.coordphaseOption = this.phaseList
      //   this.overlap = this.globalParamModel.getParamsByType('overlaplList')
      //   this.agentId = getIframdevid()
      let rings = []
      if (this.phaseList.length === 0) {
        // this.$store.getters.tscParam.patternList = []
        return
      }
      for (let phase of this.phaseList) {
        rings.push(phase.ring)
      }
      this.ringCount = Array.from(new Set(rings)) // 去除数组重复的元素
      this.ringCount = this.ringCount.sort(this.sortNumbers) // 把数组中的值按照从小到大的顺序重新排序
      this.ringCounts = Array.from(new Set(rings)) // 去除数组重复的元素
      this.ringCounts = this.ringCounts.sort(this.sortNumbers) // 把数组中的值按照从小到大的顺序重新排序
      this.optimizes = Array.from(new Set(rings)) // 去除数组重复的元素
      this.optimizes = this.optimizes.sort(this.sortNumbers) // 把数组中的值按照从小到大的顺序重新排序
      //   this.increaseId()
      //   this.getCycle()
      //   this.updatePhaseDescription()
      //   this.getOptionsOfRing()
    },
    sortNumbers (a, b) {
      return a - b
    },
    isRingCycleEqual (rings) {
      let isequal = true
      // this.patternmsg = []
      let maxCycle = 0
      for (let ring of rings) {
        if (ring.length === 0) continue
        let cycle = 0
        for (let r of ring) {
          if (r.mode === 7) { // 忽略相位不计周期
            continue
          }
          cycle = cycle + r.value
        }
        if (cycle > maxCycle && maxCycle === 0) {
          maxCycle = cycle
        }
        if (cycle !== maxCycle) {
          // this.patternmsg.push(rings.id)
          isequal = false
        }
      }
      return isequal
    },
    getMaxCycleStage (pattern) {
      let rings = pattern.stagesList
      let stageCycleList = rings.map(item => {
        if (item.stageSplit) {
          return item.stageSplit
        } else {
          return 0
        }
      })
      let maxCycle = stageCycleList.reduce((a, b) => {
        return a + b
      }, 0)
      return maxCycle
    },
    getMaxCycle (pattern) {
      let rings = pattern.rings
      let maxCycle = 0
      for (let ring of rings) {
        if (ring.length === 0) continue
        let cycle = 0
        for (let r of ring) {
          if (r.mode === 7) { // 忽略相位不计周期
            continue
          }
          cycle = cycle + r.value
        }
        if (cycle > maxCycle) {
          maxCycle = cycle
        }
      }
      return maxCycle
    },
    handleManualControl () {
      let submitdata = {
        control: 100,
        delay: this.manualInfo.tempDelay !== undefined ? Number(this.manualInfo.tempDelay) : 0,
        duration: Number(this.manualInfo.duration),
        // duration: this.manualInfo.tempDuration !== undefined ? Number(this.manualInfo.tempDuration) : 0,
        data: {}
      }
      if (this.manualInfo.tempPatternid) {
        submitdata.terminal = Number(this.manualInfo.tempPatternid)
      }
      if (this.patternOne.length === 0) {
        if (this.isRing) {
          submitdata.data.cycle = this.getMaxCycleStage(this.planPattern)
        } else {
          submitdata.data.cycle = this.getMaxCycle(this.planPattern)
        }
        submitdata.data.stagesList = this.planPattern.stagesList
      } else {
        if (this.isRing) {
          submitdata.data.cycle = this.getMaxCycleStage(this.patternOne[0])
        } else {
          submitdata.data.cycle = this.getMaxCycle(this.patternOne[0])
        }
        this.patternOne[0].stagesList.forEach((stage) => {
          delete stage.split
        })
        submitdata.data.stagesList = this.patternOne[0].stagesList
      }
      submitdata.data.contrloType = this.contrloType
      submitdata.data.offset = this.offset
      if (this.patternOne.length === 0) {
        submitdata.data.rings = this.planPattern.rings
      } else {
        submitdata.data.rings = this.patternOne[0].rings
      }
      // submitdata.data.rings = this.patternOne.length === 0 ? this.planPattern.rings : this.patternOne[0].rings
      // this.checkPatternRules(submitdata.data.rings)
      if (this.patternCycleEqual) {
        this.$emit('closePhaseControl', submitdata)
      }
    },
    toAutoControl () {
      this.$emit('toAutoControl')
    },
    isHasPermission (path) {
      let res = hasPermission(path)
      return res
    }
  }
}
</script>

<style>

</style>
