<template>
  <div class="green-wave" ref="greenWave">
    <canvas id="waveCanvas"></canvas>
    <div class="wave-item" v-for="item in waveData" :key="item.crossId" style="width: 100%">
      <i class="item-icon"></i>
      <div class="item-title">
        <p>{{ item.crossName }}</p>
        <p class="speed" v-if="item.speed || item.speed === 0">
          {{ item.speed }}km/h
        </p>
      </div>
      <div class="wave-phase-box">
        <div :class="{ coordPhaseNo: phase.isCoordinate === 1 }" class="wave-phase"
          v-for="phase in item.greenwavePhaseList" :key="phase.id" :style="{
      flex: phase.seconds / item.allCyclelen,
      display: phase.seconds === 0 ? 'none' : 'inline-block',
    }">
          <p>{{ phase.phaseNo }}</p>
        </div>
      </div>
    </div>
    <div class="time-run-dash" id="time-run-dash" v-if="contentData.areaDetailFlag">
      <div class="dash-line"></div>
      <div class="dash-secend">{{ contentData.pointerSecond }}s</div>
    </div>
    <div class="time-line" v-if="contentData.areaDetailFlag">
      <!--      <div-->
      <!--          class="line-pointer"-->
      <!--          :style="{-->
      <!--          left:-->
      <!--            (770 / contentData.cycle) * contentData.pointerSecond - 10 + 'px',-->
      <!--        }"-->
      <!--      >-->
      <span style="position: absolute" :style="{
      left:
        (770 / contentData.cycle) * contentData.pointerSecond - 10 + 'px',
    }" class="pointer-second"></span>
      <!--      </div>-->
      <span class="cycle-left">0s</span>
      <span class="cycle">{{ contentData.cycle }}s</span>
    </div>
  </div>
</template>

<script>
import wsMixins from "@/common/mixin/wsMixins.js";

export default {
  mixins: [wsMixins],
  data() {
    return {
      waveOldData: {},
      timeInterval: null,
      timeAllKey: [
        "greenTime",
        "greenFlashTime",
        "yellowTime",
        "yellowFlash",
        "redTime",
        "redFlashTime",
      ],
      waveCoordPhaseData: [
        { second: 85, forward: 18, reverse: 20, width: 20 },
        { second: 85, forward: 38, reverse: 20, width: 20 },
      ],
      waveData: [
        // { title: "相城大道与朱径支路交叉口", phaseData: [], speed: 52 },
        // { title: "相城大道与路交叉口", phaseData: [], speed: 52 },
      ],
      schemeId: null,
      //   allCyclelen: 0,
    };
  },
  props: ["contentData"],
  beforeDestroy() {
    if (this.timeInterval) {
      clearInterval(this.timeInterval);
      this.timeInterval = null;
    }
  },
  watch: {
    websocketData: {
      handler(n) {
        this.schemeId = this.websocketData.schemeId;
      },
      deep: true,
    },
    // 更新周期线
    contentData: {
      handler() {
        if (document.getElementsByClassName("wave-phase-box").length) {
          document.getElementById('time-run-dash').style.left = `${(document.getElementsByClassName("wave-phase-box")[0].getBoundingClientRect().width / this.contentData.cycle) *
            this.contentData.pointerSecond -
            10
            }px`
        }
      },
      deep: true
    }
  },
  mounted() {
    console.log("contentData", this.contentData);
    this.getCrossWs(); //赋值第一路口的crossId
    this.timeInterval = setInterval(() => {
      if (this.contentData.pointerSecond < this.contentData.cycle) {
        ++this.contentData.pointerSecond;
      } else {
        this.contentData.pointerSecond = 0;
      }
    }, 1000);
    this.getData();
  },

  computed: {
  },
  methods: {
    setItemHeight() {
      const boxHeight = this.$refs.greenWave.offsetHeight;
      const divs = document.getElementsByClassName("wave-phase-box");
      const divs2 = document.getElementsByClassName("wave-item");
      let sum = 0;
      for (const obj of this.waveData) {
        sum += obj.distanceToNextCross;
      }
      this.waveData.forEach((item, i) => {
        // divs[i].style.height =
        //     (item.distanceToNextCross / sum) * boxHeight + "px";
        // divs2[i].style.height =
        //     (item.distanceToNextCross / sum) * boxHeight + "px";
        // console.log((item.distanceToNextCross / sum) * boxHeight);
      });
      this.contentData.forwardGreenwaveList.forEach((item) => {
        item.offsetToEnd = item.offsetToStart + this.contentData.forwardWidth;
      });
      this.$nextTick(() => {
        document.getElementById("waveCanvas").style.left = `${document.getElementById("greenWaveDialog").getBoundingClientRect()
          .left * -1
          }px`;
        document.getElementById("waveCanvas").style.top = `${document.getElementById("greenWaveDialog").getBoundingClientRect()
          .top * -1
          }px`;
      });
      setTimeout(() => {
        this.setGreenWaveLine();
      }, 1000);
    },

    setGreenWaveLine() {
      const canvas = document.getElementById("waveCanvas");
      // 设置canvas的宽度和高度与窗口一致
      canvas.width = window.innerWidth;
      canvas.height = window.innerHeight;
      // const divs = document.getElementsByClassName("coordPhaseNo");
      const divs = document.getElementsByClassName("wave-phase-box");
      const ctx = canvas.getContext("2d");
      // debugger
      this.drawLine("f", divs, ctx); //正向
      this.drawLine("fw", divs, ctx); //带宽
      this.drawLine("r", divs, ctx); //反向
      this.drawLine("rw", divs, ctx);
    },
    drawLine(type, divs, ctx) {
      for (let i = 0; i < divs.length; i++) {
        let startDiv = divs[i];
        let endDiv = null;
        if (i === divs.length - 1) {
          endDiv = divs[divs.length - 1];
        } else {
          endDiv = divs[i + 1];
        }
        console.log("draw line...", startDiv, endDiv);
        // 获取 div 元素的位置和大小信息
        const startDivRect = startDiv.getBoundingClientRect();
        const endDivRect = endDiv.getBoundingClientRect();
        let data = this.contentData.forwardGreenwaveList;
        if (type === "r" || type === "rw") {
          data = this.contentData.forwardGreenwaveList;
          // data = this.contentData.reverseGreenwaveList;
        }
        if (data) {
          const startXEachSecondW = startDivRect.width / this.contentData.cycle;
          console.log(
            "startXEachSecondW",
            startXEachSecondW,
            data[i].offsetToStart
          );
          const startX =
            startDivRect.left + startXEachSecondW * data[i].offsetToStart;
          const startY = startDivRect.top;
          const endXEachSecondW = endDivRect.width / this.contentData.cycle;
          const endX =
            endDivRect.left +
            endXEachSecondW *
            data[i === divs.length - 1 ? divs.length - 1 : i + 1]
              .offsetToStart;
          const endY = endDivRect.top;
          if (type === "f" || type === "r") {
            ctx.moveTo(startX, startY);
            ctx.lineTo(endX, endY);
          } else if (type === "fw") {
            ctx.moveTo(
              startDivRect.left + startXEachSecondW * data[i].offsetToEnd,
              startY
            );
            ctx.lineTo(
              endX + endXEachSecondW * this.contentData.forwardWidth,
              endY
            );
          } else if (type === "rw") {
            ctx.moveTo(
              startX - startXEachSecondW * this.contentData.reverseWidth,
              startY
            );
            ctx.lineTo(
              endX - endXEachSecondW * this.contentData.reverseWidth,
              endY
            );
          }
        }
      }
      ctx.strokeStyle = "#A6A6A6";
      ctx.lineWidth = 2;
      ctx.stroke();
    },
    getData() {
      this.waveData = this.contentData.greenwaveCrossList.map((item) => {
        item.allCyclelen = 0;
        item.greenwavePhaseList.forEach((phase) => {
          item.allCyclelen += phase.seconds;
        });
        return item;
      });
      this.waveOldData = JSON.parse(JSON.stringify(this.waveData));
      this.$nextTick(() => {
        this.setItemHeight();
      });
    },
    setSecondsData(datas, val) {
      const data = JSON.parse(JSON.stringify(datas));
      const dataIndex = data.length - 1;
      let index = 0;
      function contrastFun() {
        if (data[index].seconds >= val) {
          data[index].seconds -= val;
          data.push({
            seconds: val,
            isCoordinate: data[index].isCoordinate,
            phaseNo: data[index].phaseNo,
          });
        } else {
          val -= data[index].seconds;
          data.push({
            seconds: data[index].seconds,
            isCoordinate: data[index].isCoordinate,
            phaseNo: data[index].phaseNo,
          });
          data[index].seconds = 0;
          ++index;
          if (index <= dataIndex) {
            contrastFun();
          }
        }
      }
      if (index <= dataIndex) {
        contrastFun();
      }
      return data;
    },
  },
};
</script>

<style lang="less" scoped>
.green-wave {
  //margin: 30px 30px 60px 0;
  //height: 250px;
  height: calc(100% - 410px);
  display: flex;
  flex-direction: column;
  position: relative;

  #waveCanvas {
    position: fixed;
    left: 0;
    top: 0;
    z-index: 9999;
    //width: 100%;
    //height: 100%;
    pointer-events: none;
  }

  .time-run-dash {
    position: absolute;
    padding-left: 196px;
    height: 100%;
    width: 206px;

    .dash-line {
      height: calc(100% - 20px);
      width: 23px;
      background-image: url("../../../../assets/images/signal/line-pointer.png");
      background-size: 100% 100%;
    }

    .dash-secend {
      height: 23px;
      line-height: 23px;
      width: 20px;
      background-color: #0f2645;
    }
  }

  .time-line {
    position: relative;
    width: calc(100% - 200px);
    margin-left: 196px;
    border-top: 2px solid #305c81;
    height: 20px;
    display: flex;
    align-items: center;

    .cycle {
      position: absolute;
      right: 0;
      bottom: 0px;
    }

    .cycle-left {
      position: absolute;
      left: 0;
      bottom: 0px;
    }

    .line-pointer {
      position: absolute;
      left: 400px;
      bottom: 20px;
      width: 24px;
      //height: 300px;
      height: 240px;
    }

    .pointer-second {
      position: absolute;
      bottom: -20px;
      min-width: 40px;
    }
  }

  .wave-item {
    flex: 1;
    height: 30px;
    display: flex;
    align-items: center;
    width: 100%;
    // &:nth-child(2) {
    //   height: 105Px;
    // }
    // &:nth-child(3) {
    //   height: 164Px;
    // }

    .item-icon {
      margin-top: -5px;
      display: inline-block;
      width: 18px;
      height: 17px;
      background: url("../../../../assets/images/dialogImg/wave-icon.png") no-repeat;
      background-size: 100% 100%;
    }

    .item-title {
      position: relative;
      width: 180px;
      margin: -5px 6px 0 6px;
      color: #c1c6ce;
    }

    .speed {
      position: absolute;
      top: 22px;
      color: #389fff;
      width: 100%;
      letter-spacing: 1px;
      text-align: center;
    }

    .wave-phase-box {
      display: flex;
      width: calc(100% - 170px);
    }

    .wave-phase {
      height: 5px;
      border-radius: 10px;
      margin-right: 5px;
      background: #fb5951;

      &.coordPhaseNo {
        background: #32ab3f;
      }

      p {
        margin-top: -20px;
        text-align: center;
      }
    }
  }
}
</style>
