<template>
<div class="overLap" v-if="checked" :style="{'margin':this.controlData ? '20px 0 0 0' :tentative ? '0' : '0 147px 0 468px'}">
    <div class="ring-first" v-for="(list, index1) in this.overlapDatas" :key="index1">
        <div v-for="(item,index2) in list.stageLists" :key="index2" >
          <!-- {{list.peddirection}} -->
            <div class="first-2">
              <el-tooltip v-if="item.greenWidth" placement="top-start" effect="light">
                <div slot="content">
                    O{{list.id}}-
                    <span v-for="(ids,index3) in list.includedphases" :key="index3">
                        {{$t('openatccomponents.phase.phase')}}{{ids}}<span v-if="index3+1!==list.includedphases.length">,</span>
                    </span>
                     <span v-if="list.modifyphase && list.modifyphase.length>0">(<span v-for="(ids, index4) in list.modifyphase" :key="index4">
                      *{{$t('openatccomponents.phase.phase')}}{{ ids
                      }}<span v-if="index4 + 1 !== list.modifyphase.length"
                        >,</span
                      >
                    </span>)</span>
                </div>
                <div style="cursor:pointer;">
                    <div class="ring-phase">
                        <!-- <patternwalksvg :showWalk="list.peddirection" :Width="'32'" :Height="'34'"></patternwalksvg> -->
                        <xdrdirselector  Width="60px" Height="60px" Widths="50px" Heights="50px" :showlist="item.direction"></xdrdirselector>
                    </div>
                    <div class="box">
                        <div class="ring-nums">
                            O{{list.id}}-
                            <span v-for="(ids,index3) in list.includedphases" :key="index3">
                                {{$t('openatccomponents.phase.phase')}}{{ids}}<span v-if="index3+1!==list.includedphases.length">,</span>
                            </span>
                            <span v-if="list.modifyphase && list.modifyphase.length>0">(<span v-for="(ids, index4) in list.modifyphase" :key="index4">
                              *{{$t('openatccomponents.phase.phase')}}{{ ids
                                }}<span v-if="index4 + 1 !== list.modifyphase.length"
                                >,</span
                              >
                            </span>)</span>
                        </div>
                    </div>
                </div>
            </el-tooltip>
            </div>
            <!-- 晚启动（lategreen）产生的头部红灯 -->
        <div
          v-if="item.headRedWidth && item.headRedWidth !== '0%'"
          class="first-1"
          :style="{
            width: item.headRedWidth,
            marginTop: '9px',
            height: '17px',
            background: '#f27979',
          }"
        ></div>
        <!-- 主体绿灯（可能已被 leadinggreen / lategreen 削减） -->
        <div
          class="first-1"
          :style="{
            width: item.greenWidth,
            height: '34px',
            background: '#7ccc66',
          }"
        ></div>
        <!-- 早结束（leadinggreen）产生的尾部红灯 -->
        <div
          v-if="item.tailRedWidth && item.tailRedWidth !== '0%'"
          class="first-1"
          :style="{
            width: item.tailRedWidth,
            marginTop: '9px',
            height: '17px',
            background: '#f27979',
          }"
        ></div>
        <!-- 非重叠阶段或剩余红灯时间 -->
        <div
          class="first-1"
          :style="{
            width: item.redWidth,
            height: '17px',
            marginTop: '9px',
            background: '#f27979',
          }"
        ></div>
        </div>
    </div>
</div>
</template>

<script>
import PhaseDataModel from '../IntersectionMap/crossDirection/utils.js'
import CrossDiagramMgr from '../../../EdgeMgr/controller/crossDiagramMgr.js'
import xdrdirselector from '../XRDDirSelector/XRDDirSelector'
// import patternwalksvg from '../PatternWalkSvg/PatternWalkSvg'
export default {
  name: 'over-lap',
  components: {
    // patternwalksvg,
    xdrdirselector
  },
  data () {
    return {
      overlapDatas: [],
      max: ''
    }
  },
  props: {
    overlap: {
      type: Array,
      default () {
        return []
      }
    },
    stageList: {
      type: Array
    },
    patternoverlaplist: {
      type: Array
    },
    checked: {
      type: Boolean
    },
    tentative: {
      type: Boolean,
      default: false
    },
    cycleChange: {
      type: Boolean,
      default: false
    },
    cycle: {
      type: Number
    },
    controlData: {
      type: Object
    }
  },
  watch: {
    controlData: {
      handler: function (val, oldVal) {
        this.doAdd(this.stageList, this.overlap)
      },
      // 深度观察监听
      deep: true
    },
    cycleChange: {
      handler: function (val, oldVal) {
        this.doAdd(this.stageList, this.overlap)
      },
      // 深度观察监听
      deep: true
    },
    stageList: {
      handler: function (val, oldVal) {
        this.doAdd(this.stageList, this.overlap)
      },
      // 深度观察监听
      deep: true
    },
    patternoverlaplist: {
      handler: function (val, oldVal) {
        this.doAdd(this.stageList, this.overlap)
      },
      // 深度观察监听
      deep: true
    }
  },
  created () {
    this.PhaseDataModel = new PhaseDataModel()
    this.CrossDiagramMgr = new CrossDiagramMgr()
    this.doAdd(this.stageList, this.overlap)
  },
  methods: {
    getRoad (i) {
      let direction = []
      if (i.direction && i.direction.length > 0) {
        i.direction.map(item => {
          direction.push({
            id: item,
            peddirection: this.getPedPhasePos(i.peddirection),
            color: '#454545'
          })
        })
      } else {
        direction.push({
          id: '',
          color: '#454545',
          peddirection: this.getPedPhasePos(i.peddirection)
        })
      }
      return direction
    },
    getPedPhasePos (i) {
      // 行人相位信息
      let sidewalkPhaseData = []
      if (i) {
        i.forEach((dir, index) => {
          // 行人相位
          if (this.PhaseDataModel.getSidePos(dir)) {
            sidewalkPhaseData.push({
              key: this.CrossDiagramMgr.getUniqueKey('pedphase'),
              phaseid: i.id, // 相位id，用于对应相位状态
              id: dir,
              color: '#454545',
              name: this.PhaseDataModel.getSidePos(dir).name
            })
          }
        })
      }
      return sidewalkPhaseData
    },
    doAdd (stageList, overlap) { // 阶段显示颜色
      let overlapData = overlap.map(item => {
        // 若 patternoverlaplist 中有对应项且带 includedPhases，则用其参与计算的相位；否则用 overlap 的 includedphases
        const overlapPattern =
          Array.isArray(this.patternoverlaplist) &&
          this.patternoverlaplist.find(p => p.id === item.id)
        const includedPhases = overlapPattern &&
          Array.isArray(overlapPattern.includedPhases) &&
          (overlapPattern.includedPhases).length > 0
          ? (overlapPattern.includedPhases)
          : (item.includedphases || [])
        const modifyPhases = overlapPattern &&
          Array.isArray(overlapPattern.modifyphase)
          ? overlapPattern.modifyphase
          : (item.modifyphase !== undefined ? item.modifyphase : [])
        let findIndexs = []
        includedPhases.forEach(i => {
          const findItems = stageList.filter(j => j.phases.includes(i))
          if (findItems.length) findIndexs.push(...findItems.map(m => m.key))
        })
        // 收集所有包含 modifyphase 中相位的阶段 key
        let modifyIndexs = []
        if (modifyPhases.length > 0) {
          modifyPhases.forEach(i => {
            const findItems = stageList.filter(j => j.phases.includes(i))
            if (findItems.length) modifyIndexs.push(...findItems.map(m => m.key))
          })
        }
        findIndexs = Array.from(new Set(findIndexs))
        modifyIndexs = Array.from(new Set(modifyIndexs))
        if (this.cycleChange) {
          const globalParamModel = this.$store.getters.globalParamModel
          let pattern = globalParamModel.getParamsByType('patternList')
          const allCycle = pattern.map(item => item.cycle)
          let cycle = Math.max(...allCycle)
          this.max = cycle
        } else {
          this.max = ''
        }

        // 读取当前 overlap 对应的晚启动 / 早结束时间（单位与 split 一致，overlapPattern 已在上方根据 item.id 取过）
        let lategreen = overlapPattern && typeof overlapPattern.lategreen === 'number'
          ? overlapPattern.lategreen
          : 0
        let leadinggreen = overlapPattern && typeof overlapPattern.leadinggreen === 'number'
          ? overlapPattern.leadinggreen
          : 0

        // 按阶段初始化绿灯 / 红灯时长（单位：split）
        const stageTimeMap = {}
        stageList.forEach(sta => {
          const inOverlap = findIndexs.includes(sta.key) && !modifyIndexs.includes(sta.key)
          stageTimeMap[sta.key] = {
            green: inOverlap ? sta.split : 0, // 重叠阶段默认全绿
            red: inOverlap ? 0 : sta.split, // 非重叠阶段全红（底部红条）
            headRed: 0, // 晚启动（lategreen）拆出来的头部红
            tailRed: 0 // 早结束（leadinggreen）拆出来的尾部红
          }
        })

        // 处理晚启动：从头到尾，优先削减最前面的绿灯，生成 headRed
        let remainLate = lategreen
        if (remainLate > 0) {
          stageList.forEach(sta => {
            if (remainLate <= 0) return
            const cur = stageTimeMap[sta.key]
            if (!cur || cur.green <= 0) return
            const cut = Math.min(cur.green, remainLate)
            cur.green -= cut
            cur.headRed += cut
            remainLate -= cut
          })
        }

        // 处理早结束：从尾到头，优先削减最后面的绿灯，生成 tailRed
        let remainLead = leadinggreen
        if (remainLead > 0) {
          ;[...stageList].reverse().forEach(sta => {
            if (remainLead <= 0) return
            const cur = stageTimeMap[sta.key]
            if (!cur || cur.green <= 0) return
            const cut = Math.min(cur.green, remainLead)
            cur.green -= cut
            cur.tailRed += cut
            remainLead -= cut
          })
        }

        const totalCycle = (this.max ? this.max : this.cycle)

        return {
          ...item,
          peddirection: this.getPedPhasePos(item.peddirection),
          sidewalkPhaseData: this.getPedPhasePos(item.peddirection),
          stageLists: stageList.map(sta => {
            const t = stageTimeMap[sta.key] || { green: 0, red: sta.split, headRed: 0, tailRed: 0 }
            const scale = totalCycle || 1
            const greenWidth = (t.green / scale * 100).toFixed(3) + '%'
            const redWidth = (t.red / scale * 100).toFixed(3) + '%'
            const headRedWidth = (t.headRed / scale * 100).toFixed(3) + '%'
            const tailRedWidth = (t.tailRed / scale * 100).toFixed(3) + '%'
            return {
              ...sta,
              direction: this.getRoad(item),
              headRedWidth,
              greenWidth,
              tailRedWidth,
              redWidth
            }
          })
        }
      })
      this.overlapDatas = overlapData
    }
  }
}
</script>

<style lang="scss" scoped>
.ring-first {
  // margin-top: 1px;
  width: 100%;
  height: 40px;
  .first-1 {
   float: left;
   margin-top: 1px;
// text-align: center;
  }
  .first-2{
   position: absolute;
   color: #333333;
  }
  .ring-nums {
    // float: left;
    // margin-top:7px;
    // margin-left: 5px;
    padding-top: 10px;
    padding-left: 43px;
    font-size: 12px;
    height: 14px;
    font-weight: normal;
    font-stretch: normal;
    // line-height: 22px;
    letter-spacing: 0px;
    color: #333333;//#33333361
  }
  .ring-phase {
    position: relative;
    float: left;
    // margin-left: 5px;
    height: 34px;
    width: 36px;
    z-index: 999;
    background: rgba(30, 96, 12, 0.07);
    // margin-top:1px;
  }
  .ring-phase::after {
    position: absolute;
    display: block;
    content: '';
    height: 0;
    width: 0;
    top: 11px;
    left: 36px;
    border: 5px solid transparent;
    border-left-color: rgba(30, 96, 12, 0.07);
  }
}
</style>
