<template lang="html">
  <div class="crossHintBox" :id="uuid" :ref="uuid" :class="isSmall">
    <div
      ref="crossHintRef"
      style="width:100%;height:100%;position: absolute;"
      :style="crossHintBoxStyle"
      @wheel="handleWheel"
      v-drag="type !== 'planSend'"
    >
      <!-- <canvas id="canvasRef"></canvas> -->
      <div class="cross_center" :style="centerStyle">
        <div class="dirList" :key="refreshDirList">
          <div
            class="dirLane"
            v-for="(d, di) in dirList"
            :style="getLaneStyle(d)"
            :class="getDirClass(d)"
          >
            <!-- <span v-if="dirLampGroupMap[d.dir]">{{
              dirLampGroupMap[d.dir]["20"]
            }}</span> -->
            <img
              :style="{
                backgroundColor:
                  dirLampGroupMap &&
                  dirLampGroupMap[d.dir] &&
                  dirLampGroupMap[d.dir]['20']
                    ? personColorObj[dirLampGroupMap[d.dir]['20']]
                    : '',
              }"
              style="position: absolute;width: 90%;left: 5%;"
              v-if="d.isPersonCross"
              src="../../../../../assets/images/planMange/person-cross.svg"
              alt=""
            />
            <!--出口-->
            <div class="lane_in" :id="'laneIn' + d.dir">
            </div>
            <!--进口-->
            <div class="lane_out" style="width:100%">
              <div
                class="lane_img"
                v-for="(ld, li) in d.laneList"
                :key="li"
                :class="{ active: setActiveClass(ld.id) }"
              >
                <img
                  style="width: 100%;"
                  v-if="ld.laneType === 2 || ld.laneType === 3"
                  :src="
                    require('../../../../../assets/images/planMange/laneType-' +
                      ld.laneType +
                      '.svg')
                  "
                  alt
                />

                <img
                  :src="getLaneActiveImg(ld)"
                  v-else-if="setActiveClass(ld.id)"
                />
                <img :src="getLaneImg(ld)" v-else-if="ld.direction" />
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { createGuid } from "@/common/js/utils.js";
import { mapState } from "vuex";
import {
  api_getCrossData,
  api_getLightByLane,
  api_getLanesByLight,
} from "@/common/api/planManage.js";
import {px2vw} from "@/utils/tools";

export default {
  name: 'CrossHint',
  components: {},
  props: [
    "crossData",
    "type",
    "crossHintClickPhase",
    "isSmall",
    "websocketDataProp",
    "hasWs",
  ],
  data() {
    return {
      heatmapInstance: null,
      dirRefresh: false,
      customCross: "",
      atlaScaleNum: 1.1,
      refreshDirList: false,
      crossId: "",
      uuid: createGuid(),
      centerStyle: {},
      dirMaxWidth: 0,
      activeDir: [],
      dirList: [
        {
          dir: "1",
          laneList: [],
        },
        {
          dir: "2",
          laneList: [],
        },
        {
          dir: "3",
          laneList: [],
        },
        {
          dir: "4",
          laneList: [],
        },
        {
          dir: "5",
          laneList: [],
        },
        {
          dir: "6",
          laneList: [],
        },
        {
          dir: "7",
          laneList: [],
        },
        {
          dir: "8",
          laneList: [],
        },
      ],
      laneAcive: "",
      planConfigChooseList: [],
      ledChooseList: [],
      dirClass: {
        "1": "north",
        "2": "northeast",
        "3": "east",
        "4": "southeast",
        "5": "south",
        "6": "southwest",
        "7": "west",
        "8": "northwest",
      },
      dirLampGroupMap: {},
      personColorObj: {
        green: "#08bf08",
        red: "red",
        yellow: "yellow",
        greenFlash: "#057d09",
        redFlash: "#750505",
        yellowFlash: "#797907",
      },
    };
  },
  created() {},
  mounted() {
    window.addEventListener("resize", () => {
      if (this.heatmapInstance) {
        this.heatmapInstance.setData({ max: 10, data: [] });
      }
      this.getHeat();
    });
    this.getHeat();
    this.initPop();
    // return;
    if (this.crossHintClickPhase) {
      this.ledChooseList = [];
      this.crossHintClickPhase.list.forEach((item) => {
        if (item.lightsId) {
          item.id = item.lightsId;
          this.ledChooseList.push({ ...item, id: item.lightsId });
          this.setPlanConfig("led", item, this.crossHintClickPhase.dir);
        } else if (item.type === "person") {
          this.setPlanConfig("person", item, item.dir);
        }
      });
    }
  },
  computed: {
    crossHintBoxStyle() {
      return {
        transform: `scale(${this.atlaScaleNum})`,
      };
    },
  },
  watch: {
    websocketDataProp: {
      handler(n) {
        this.websocketData = n;
        this.activePhaseId = this.websocketData.phaseId;
        this.runMode = this.websocketData.runMode;
      },
      deep: true,
    },
    crossData() {
      this.$nextTick(() => {
        this.initPop();
      });
    },
    type() {
      this.$nextTick(() => {
        this.initPop();
      });
    },
  },
  destroyed() {},
  methods: {
    getPx(px) {
      let screenHeight =
        window.innerHeight ||
        document.documentElement.clientHeight ||
        document.body.clientHeight;
      return Math.floor(screenHeight / (937 / px));
    },
    getHeat() {
    },
    /**
     * 鼠标滚动事件按ctrl加滚轮控制缩放
     */
    handleWheel(e) {

    },
    isNull(str) {
      return str != "" || str != undefined || str;
    },
    getLaneImg(item) {
      let direction = item.direction;
      let srcUrl = "white-" + direction;
      srcUrl += ".svg";
      if (direction > 0) {
        let str = require("@/assets/images/planMange/arrow/" + srcUrl);
        return str;
      } else {
        return "";
      }
    },
    /**@argument
     * 渲染方向图片
     */
    getSendLaneImg(item, paranItem, isNoCrossLamp) {
      // let phaseDist = {
      //   1: "1",
      //   5: "1",
      //   6: "1",
      //   10: "1",
      //   14: "1",
      //   16: "1",
      //   7: "2",
      //   8: "2",
      //   2: "2",
      //   9: "2",
      //   12: "2",
      //   13: "2",
      //   15: "2",
      //   18: "2",
      //   3: "3",
      //   4: "1",
      // };
      //1左转 2直行 3右转
      let phaseDist = {
        1: "1",
        2: "2",
        3: "3",
        4: "2",
        5: "2",
        6: "2",
        7: "2",
        8: "1",
        9: "1",
        10: "2",
      };
      let dirType = paranItem.dir;
      let direction = item.direction || "";
      if (isNoCrossLamp == "1") {
        direction = "4";
      }
      if (direction == 0 || !direction) {
        return "";
      }
      let srcUrl = "phase_lane_" + direction;
      const obj = {
        1: "1",
        2: "3",
        3: "3",
        4: "5",
        5: "5",
        6: "7",
        7: "7",
        8: "1",
      };
      let dirLampGroupMap =
        this.dirLampGroupMap ||
        {
          // "1": { "1": "red", "3": "green", "20": "red" },
          // "3": { "2": "red", "3": "green" },
          // "7": { "2": "green", "3": "red" },
          // "1": {
          //   "1": "green",
          //   "2": "green",
          //   "3": "green",
          // },
          // "2": {
          //   "1": "red",
          //   "2": "red",
          //   "3": "red",
          //   "20": "green",
          // },
          // "4": {
          //   "1": "green",
          //   "2": "green",
          //   "3": "green",
          // },
          // "6": {
          //   "1": "red",
          //   "2": "red",
          //   "3": "red",
          //   "20": "green",
          // },
        };
      for (const key in obj) {
        if (!dirLampGroupMap[obj[key]]) {
          dirLampGroupMap[obj[key]] = dirLampGroupMap[key] || {};
        }
      }
      let dirMap = dirLampGroupMap[dirType] || {};
      let color = dirMap[phaseDist[direction]] || "";
      color = color.trim();
      if (color) {
        color = color.replace("lightsOut", "");
        color = color == "greenFlash" ? "drakGreen" : color;
        color = color == "yellowFlash" ? "yellow" : color;
        color = color == "redFlash" ? "red" : color;

        if (color) {
          srcUrl = srcUrl + "_" + color;
        }
      } else {
        //  如果 改 车道灯 没有获取到颜色值
        // 判断 是否 5 为有颜色 否
        // 如果有 在直接赋值 并且为左转 及灯态方向 为1
        // 如果没有值  在判断
        let colorAll = "";
        let allLampGroup = dirMap["5"];
        if (allLampGroup != undefined && allLampGroup["5"] != null) {
          if (direction != 3) {
            colorAll = allLampGroup;
          }
        } else {
          if (dirMap[direction] != undefined) {
            colorAll = dirMap[direction];
          } else if (direction == 1) {
            colorAll = dirMap["1"];
          } else if (direction == 3 && this.isNull(dirMap[direction])) {
            // colorAll = "green";
          }
        }
        colorAll = colorAll == "greenFlash" ? "drakGreen" : colorAll;
        colorAll = colorAll == "lightsOut" ? "" : colorAll;
        colorAll = colorAll == "yellowFlash" ? "yellow" : colorAll;
        colorAll = colorAll == "redwFlash" ? "red" : colorAll;
        if (colorAll) {
          srcUrl = srcUrl + "_" + colorAll;
        }
      }
      srcUrl += ".png";
      let str = require("@/assets/images/crossDirImgs/" + srcUrl);
      return str;
    },
    getCanvasLine() {
      // 获取div元素和canvas元素
      let div1 = document.querySelectorAll(`.dirLane.northwest`)[0];
      let div2 = document.querySelectorAll(".dirLane.northeast")[0];
      let div3 = document.querySelectorAll(".dirLane.south")[0];
      let canvas = document.getElementById("canvasRef");
      // 设置canvas的宽度和高度与窗口一致
      canvas.width = window.innerWidth;
      canvas.height = window.innerHeight;

      // 获取canvas的2D上下文
      let ctx = canvas.getContext("2d");

      // 获取div元素的位置和大小信息
      let div1Rect = div1?.getBoundingClientRect();
      let div2Rect = div2?.getBoundingClientRect();
      let div3Rect = div3?.getBoundingClientRect();
      if (div1Rect && div2Rect && div3Rect) {
        // 计算连接线的起点和终点坐标
        let startX1 = div1Rect.right;
        let startY1 = div1Rect.bottom;
        let endX1 = div2Rect.left;
        let endY1 = div2Rect.bottom;

        let startX2 = div2Rect.right;
        let startY2 = div2Rect.bottom;
        let endX2 = div3Rect.right;
        let endY2 = div3Rect.top;

        let startX3 = div3Rect.left;
        let startY3 = div3Rect.top;
        let endX3 = div1Rect.left;
        let endY3 = div1Rect.bottom;

        // 绘制连接线
        ctx.beginPath();
        ctx.moveTo(startX1, startY1);
        ctx.lineTo(endX1, endY1);
        ctx.moveTo(startX2, startY2);
        ctx.lineTo(endX2, endY2);
        ctx.moveTo(startX3, startY3);
        ctx.lineTo(endX3, endY3);
        ctx.strokeStyle = "blue";
        ctx.lineWidth = 2;
        ctx.stroke();
      }
    },
    setLedActiveClass(val) {
      return (
        this.ledChooseList.length &&
        this.ledChooseList.find((item) => val === item.id)
      );
    },
    setPersonActiveClass(val) {
      return (
        this.ledChooseList.length &&
        this.ledChooseList.find(
          (item) => val == item.dir && item.type === "person"
        )
      );
    },
    setActiveClass(val) {
      return (
        this.planConfigChooseList.length &&
        this.planConfigChooseList.find((item) => val === item.id)
      );
    },
    setPlanConfig(type, data, dir) {

    },
    initPop() {
      let crossData = this.crossData;
      let type = this.type;
      this.crossId = crossData.crossId || crossData.nodeId || crossData.id;
      if (!this.crossId) {
        console.error("路口自定义----路口没有id");
        return false;
      }
      let uuid = this.uuid;
      this.laneAcive = "";
      this.activeDir = [];
      this.$nextTick(() => {
        const w = this.$refs[uuid].clientWidth;
        let width = w * 0.33;
        this.centerStyle.width = this.px2vw(width) + "vw";
        this.centerStyle.height = this.px2vw(width) + "vw";
        this.dirMaxWidth = width;
      });
      this.getCrossDirLane();
    },
    // setNumber() {
    //   let flag = false;
    //   const arr = [
    //     ["1", "3", "5", "7"],
    //     ["3", "5", "7"],
    //     ["1", "3", "7"],
    //     ["1", "5", "7"],
    //     ["1", "3", "5"],
    //     ["1"],
    //     ["3"],
    //     ["5"],
    //     ["7"],
    //   ];
    //   arr.forEach((item) => {
    //     if (this.activeDir.toString() === item.sort().toString()) {
    //       flag = true;
    //     }
    //   });
    //   return flag;
    // },
    crossInclude() {
      const arr = ["2", "4", "6", "8"];
      let flag = this.activeDir.some(function(element) {
        return arr.includes(element);
      });
      return flag;
    },
    // Y ["2", "5", "8"][("1", "4", "6")][("3", "6", "8")][("2", "4", "7")];
    getLaneStyle(item) {
      let dirMaxWidth = this.dirMaxWidth;
      let w = dirMaxWidth * (this.crossInclude() ? 0.56 : 1);
      // let w = dirMaxWidth * 0.4;
      let h = dirMaxWidth * 1;
      let left, top, bottom, right, r, ya, yb, yc;
      r = 45;
      // 行内样式不支持px转rem 需要手动转
      let dir = item.dir;
      if (dir == "1") {
        left = (dirMaxWidth - w) / 2;
        return {
          width: this.px2vw(w) + "vw",
          height: this.px2vw(h) + "vw",
          transform: "rotate(180deg)",
          top: -this.px2vw(h) + "vw",
          left: this.px2vw(left) + "vw",
        };
      } else if (dir == "2") {
        h = h + 50;
        left = dirMaxWidth;
        top = h;
        yc = w;
        yb = Math.sin((r * Math.PI) / 180) * yc; //  高度

        ya = Math.cos((r * Math.PI) / 180) * yc; //小三角宽度

        left = left - ya * 0.06525;
        top = top - yb;
        return {
          width: this.px2vw(w) + "vw",
          height: this.px2vw(h) + "vw",
          transform: "rotate(225deg)",
          top: -this.px2vw(top) + "vw",
          left:
            this.customCross === "Y4"
              ? this.px2vw(left) - 0.15 + "vw"
              : this.px2vw(left) + "vw",
        };
      } else if (dir == "3") {
        top = 0;
        //left = dirMaxWidth + w * .75;
        left = h + (dirMaxWidth - w) / 2;
        return {
          width: this.px2vw(w) + "vw",
          height: this.px2vw(h) + "vw",
          transform: "rotate(270deg)",
          top: -this.px2vw(top) + "vw",
          left:
            this.customCross === "Y3"
              ? this.px2vw(left) - 0.1 + "vw"
              : this.px2vw(left) + "vw",
        };
      } else if (dir == "4") {
        h = h + 50;
        left = dirMaxWidth;
        top = h;

        yc = w;

        yb = Math.sin((r * Math.PI) / 180) * yc; //  高度

        ya = Math.cos((r * Math.PI) / 180) * yc; //小三角宽度

        left = left - ya * 0.06525;
        top = top - yb;

        return {
          width: this.px2vw(w) + "vw",
          height: this.px2vw(h) + "vw",
          transform: "rotate(315deg)",
          bottom: -this.px2vw(top) + "vw",
          left:
            this.customCross === "Y4"
              ? this.px2vw(left) - 0.15 + "vw"
              : this.px2vw(left) + "vw",
        };
      } else if (dir == "5") {
        top = h;
        left = (dirMaxWidth - w) / 2;
        return {
          width: this.px2vw(w) + "vw",
          height: this.px2vw(h) + "vw",
          transform: "rotate(0deg)",
          bottom: -this.px2vw(top) + "vw",
          left: this.px2vw(left) + "vw",
        };
      } else if (dir == "6") {
        h = h + 50;
        left = -(dirMaxWidth - w) / 2;
        top = h;

        yc = w;

        yb = Math.sin((r * Math.PI) / 180) * yc; //  高度

        ya = Math.cos((r * Math.PI) / 180) * yc; //小三角宽度

        left = left - ya * (0.06525 * 12);
        top = top - yb;

        return {
          width: this.px2vw(w) + "vw",
          height: this.px2vw(h) + "vw",
          transform: "rotate(45deg)",
          bottom: -this.px2vw(top) + "vw",
          left:
            this.customCross === "Y3"
              ? this.px2vw(left) + 0.15 + "vw"
              : this.px2vw(left) + "vw",
        };
      } else if (dir == "7") {
        top = 0;
        left = -h + (dirMaxWidth - w) / 2;
        return {
          width: this.px2vw(w) + "vw",
          height: this.px2vw(h) + "vw",
          transform: "rotate(90deg)",
          top: -this.px2vw(top) + "vw",
          left:
            this.customCross === "Y4"
              ? this.px2vw(left) + 0.1 + "vw"
              : this.px2vw(left) + "vw",
        };
      } else if (dir == "8") {
        h = h + 50;
        left = -(dirMaxWidth - w) / 2;
        top = h;

        yc = w;

        yb = Math.sin((r * Math.PI) / 180) * yc; //  高度

        ya = Math.cos((r * Math.PI) / 180) * yc; //小三角宽度

        left = left - ya * (0.06525 * 12);
        top = top - yb;

        return {
          width: this.px2vw(w) + "vw",
          height: this.px2vw(h) + "vw",
          transform: "rotate(135deg)",
          top: -this.px2vw(top) + "vw",
          left:
            this.customCross === "Y3"
              ? this.px2vw(left) + 0.15 + "vw"
              : this.px2vw(left) + "vw",
        };
      }
    },
    getBusData() {
    },
    //获取路口方向跟车道
    getCrossDirLane(val) {
      const activeDir = [];
      let allDir = ["1", "2", "3", "4", "5", "6", "7", "8"];
      let param = {
        crossId: this.crossId,
      };
      api_getCrossData(param).then((res) => {
        const obj = {
          1: "1",
          2: "3",
          3: "3",
          4: "5",
          5: "5",
          6: "7",
          7: "7",
          8: "1",
        };
        const data = res.data.content;
        const result = this.dirList.map((item) => {
          const temp =
            data.dirList.find((subitem) => {
              subitem.dir = String(subitem.dir);
              return subitem.dir === item.dir;
            }) || null;

          if (temp) {
            const dir = this.isSmall ? obj[temp.dir] : item.dir;
            temp.dir = dir;
            activeDir.push(dir);
            allDir = this.replaceArrayTarget(allDir,dir)
            return temp;
          }
          return { dir: item.dir, laneList: [] };
        });
        this.activeDir = activeDir;
        this.dirList = result;
      });
    },
    replaceArrayTarget(arr, t){
      let index = arr.indexOf(t);
      if(index === -1) {
        return arr;
      } else {
        arr.splice(index, 1);
        return arr;
      }
    },
    getLaneActiveImg(item) {
      let direction = item.direction;
      let srcUrl = "white-active-" + direction;
      srcUrl += ".svg";
      if (direction > 0) {
        let str = require("@/assets/images/planMange/arrow/" + srcUrl);
        return str;
      } else {
        return "";
      }
    },
    //根据车道配置保存需要的数据
    getLaneDatas() {
      let crossId = this.crossId;
      let activeDir = this.activeDir;
      let dirList = this.dirList;
      let datas = [];
      dirList.forEach((item) => {
        let dir = item.dir;
        if (activeDir.indexOf(dir) > -1) {
          let json = {
            dir: dir,
            crossId: crossId,
            ...item,
          };
          datas.push(json);
        }
      });
      return datas;
    },
    getDirClass(d) {
      let activeDir = this.activeDir;
      let type = this.type;
      let laneAcive = this.laneAcive;
      let json = {
        [this.dirClass[d.dir]]: true,
        active: activeDir.indexOf(d.dir) > -1,
        isLane: activeDir.indexOf(d.dir) == -1,
        isDNXB: true,
        laneActive: laneAcive == d.dir,
      };
      return json;
    },
    px2vw(px) {
      let vw = px2vw(px);
      return vw;
    },
  },
};
</script>

<style lang="less" scoped>
.crossHintBox {
  width: 100%;
  height: 100%;
  position: relative;
  overflow: hidden;
  .cross_center {
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    position: absolute;
    background: #20272b;
    background-size: 100% 100% !important;
    .dirList{
      position: relative;
      width: 100%;
      height: 100%;

    }
    .center-txt {
      position: absolute;
      /* z-index: 9999999; */
      color: #fff;
      font-size: 25px;
      /* text-align: center; */
      width: 100%;
      height: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
  .isLane {
    .lane_out {
      border-top: none !important;
    }
  }
  .lane_out {
    border-top: 2px solid #fff !important;
    margin-top: 30px !important;
    .lane_img {
      position: relative;
      padding-top: 30%;
      .planSend-arrow {
        height: 0.4458rem;
        max-width: 100%;
        // max-height: 50px !important;
        width: auto !important;
      }
      // border-right: 1px solid #fff;
      &::before {
        /* prettier-ignore */
        width: 2Px;
        height: 100%;
        content: "";
        position: absolute;
        z-index: 1000;
        right: 0;
        top: 0;
        background-image: url("../../../../../assets/images/planMange/laneType-1.svg");
        // background-size: 100% 100%;
        background-repeat: repeat-y;
      }
      &:nth-last-child(1) {
        border-right: none;
        &::before {
          display: none;
        }
      }
    }
  }
  .person-led {
    .active {
      img {
        border: 1px solid #0089ff;
      }
    }
  }
  .lane_in {
    // border-top: 2px solid #fff !important;
    border-right: 2px solid #ffeb3b !important;
    margin-top: 30px;
    padding: 0 6px;
    display: flex;
    justify-content: flex-end;
    .lane_img {
      &.active {
        img {
          border: 1px solid #0089ff;
        }
      }
    }
    img {
      transform: rotate(180deg);
      margin-top: 35px;
      flex: 1;
      width: 100%;
      max-height: 50%;
    }
  }
}
</style>
