<template>
  <canvas id="myCanvas" class="canvas-dom"> </canvas>
</template>
        
  <script lang="ts">
import { Search } from "vant";
import { number } from "echarts";
import { getMapInfo } from "@/apis/envmonitor";
import {
  defineComponent,
  nextTick,
  watch,
  onMounted,
  reactive,
  toRefs,
} from "vue";
import { parseImgUrl } from "@/utils";
import { swiper } from "@/utils/swiper";
import { getSpaceType, mapIcon } from "@/utils/mapIcon";

export default defineComponent({
  props: {
    mapData: {
      type: Object,
      default: () => {},
    },
  },
  components: {
    VanSearch: Search,
  },
  setup(props, contx) {
    let ctx: any = {};
    let canvasImageArr: any = {};
    let iconData: any = [];
    const proxyData = reactive({
      mapData: props.mapData, // 地图数据
      iconData: iconData,
      parseImgUrl: parseImgUrl,
      canvasImageArr: canvasImageArr,
      ctx: ctx,
      /**
       * 设置空间的图标
       *
       */
      setSpaceIcon(item: any) {
        // if(item.can)
        if (item.canClick) {
          // debugger
          let typeName: any = getSpaceType(item.roomFuncType);
          item.icon = mapIcon[typeName].icon;
          item.selectIcon = mapIcon[typeName].selectIcon;
          item.backgroundColor = mapIcon[typeName].backgroundColor;
          item.bg = mapIcon[typeName].bg;
          item.icon = parseImgUrl("map-new-icon", item.icon);
          item.selectIcon = parseImgUrl("map-new-icon", item.selectIcon);
        } else {
          item.icon = "";
        }
      },
      // 地图缩放
      scaleCanvas(data: any) {
        proxyData.mapData = data;
        let removeIconArr: any = document.querySelectorAll(".load-icon") || [];
        // removeIconArr.map((item: any) => {
        //   item.remove();
        // });
        proxyData.canvasImageArr = {};
        proxyData.initCanvas(1);
        // proxyData.ctx.clearRect(0, 0, proxyData.mapData.width, proxyData.mapData.height);
      },
      // canvas画图
      initCanvas(type: any = 0) {
        let canvasDom: any = document.querySelector("#myCanvas");
        // canvasDom.style.display = "none";
        let ctx: any = canvasDom.getContext("2d");
        proxyData.ctx = ctx;
        // debugger;
        proxyData.drawDpiBegin(
          canvasDom,
          ctx,
          proxyData.mapData.width,
          proxyData.mapData.height,
          type
        );

        let spaceList: any =
          (proxyData.mapData && proxyData.mapData.spaceList) || [];
        spaceList.map((item: any) => {
          if (item.canClick) {
            let circleArr: any = item.circlePointArr;
            ctx.beginPath();
            ctx.fillStyle = item.fillColor;
            let pointLeftArr: any = [];
            let pointTopArr: any = [];
            item.pointArr.map((childItem: any, index: any) => {
              childItem.left = childItem.left;
              childItem.top = childItem.top;
              if (index == 0) {
                ctx.moveTo(childItem.left, childItem.top);
              } else {
                ctx.lineTo(childItem.left, childItem.top);
              }
              pointLeftArr.push(childItem.left);
              pointTopArr.push(childItem.top);
            });
            ctx.fill();
            ctx.closePath();
            ctx.beginPath();
            if (circleArr && circleArr.length) {
              ctx.fillStyle = item.fillColor;
              ctx.lineTo(circleArr[3].left, circleArr[3].top);
              ctx.bezierCurveTo(
                circleArr[2].left,
                circleArr[2].top,
                circleArr[1].left,
                circleArr[1].top,
                circleArr[0].left,
                circleArr[0].top
              );
            }
            ctx.fill();
            ctx.closePath();

            let min1: any =
              proxyData.MaxAndMin(pointLeftArr)[1] -
              proxyData.MaxAndMin(pointLeftArr)[0];
            let min2: any =
              proxyData.MaxAndMin(pointTopArr)[1] -
              proxyData.MaxAndMin(pointTopArr)[0];
            let min: any = min1 < min2 ? min1 : min2;
            ctx.beginPath();
            ctx.font = "12px serif";
            ctx.textAlign = "center";
            ctx.fillStyle = item.fillColor === "#fff" ? "#000" : "#8995BA";
            let localName: any = item.localName;
            let drutionLef: any = localName ? item.localName["length"] * 12 : 0;
            ctx.fillText(
              item.localName,
              item.logoPointArr[0].left,
              item.logoPointArr[0].top,
              50
            );

            if (item.icon) {
              proxyData.addIcon(item, 1, {
                left: item.logoPointArr[0].left - 50 / 2 + 15,
                top: item.logoPointArr[0].top * 1 + 5,
              });
            }
            ctx.closePath();
          } else {
            ctx.beginPath();
            let img: any = new Image();
            img.src = require("@/assets/svg/bg_disable.png");
            if (type == 0) {
              img.onload = function () {
                item.pointArr.map((item: any, index: any) => {
                  if (index === 0) {
                    ctx.moveTo(item.left, item.top);
                  } else {
                    ctx.lineTo(item.left, item.top);
                  }
                });
                let pat: any = ctx.createPattern(img, "repeat");
                ctx.fillStyle = pat;
                ctx.fill();
                ctx.closePath();
                ctx.lineWidth = 2;
                ctx.strokeStyle = "#DFE3ED";
                ctx.stroke();
              };
            } else {
              item.pointArr.map((item: any, index: any) => {
                if (index === 0) {
                  ctx.moveTo(item.left, item.top);
                } else {
                  ctx.lineTo(item.left, item.top);
                }
              });
              let pat: any = ctx.createPattern(img, "repeat");
              ctx.fillStyle = pat;
              ctx.fill();
              ctx.closePath();
              ctx.lineWidth = 2;
              ctx.strokeStyle = "#DFE3ED";
              ctx.stroke();
            }
          }
        });
        proxyData.drawIcon(ctx, type);
        proxyData.drawDpiEnd(canvasDom, ctx);
      },
      MaxAndMin(arr: any) {
        return [Math.min.apply(null, arr), Math.max.apply(null, arr)];
      },
      // 绑定事件
      bindEvent() {
        let canvasDom: any = document.querySelector("#myCanvas");
        // 点击事件
        canvasDom.addEventListener("click", proxyData.detect);
      },
      // 解决canvas画图模糊的问题
      // 开始画
      drawDpiBegin(
        dom: any,
        context: any,
        width: any,
        height: any,
        type: any = 0
      ) {
        context.save();
        context.clearRect(0, 0, width, height);
        let scaleValue = window.devicePixelRatio;
        dom.setAttribute("width", width * scaleValue);
        dom.setAttribute("height", height * scaleValue);
        dom.style.width = width + "px";
        dom.style.height = height + "px";
        context.scale(scaleValue, scaleValue);
      },
      // 画图介绍
      drawDpiEnd(dom: any, context: any) {
        context.restore();
      },
      // 地图点击事件
      detect(event: any) {
        let canvasDom: any = document.querySelector("#myCanvas");
        let x: any = event.clientX - canvasDom.getBoundingClientRect().left;
        let y: any = event.clientY - canvasDom.getBoundingClientRect().top;
        let spaceList: any =
          (proxyData.mapData && proxyData.mapData.spaceList) || [];
        for (let i = 0; i < spaceList.length; i++) {
          let item: any = spaceList[i];
          let devicePointArr: any = item.devicePointArr;
          let pointArr: any = item.pointArr;
          let iconFlag: any = false;
          devicePointArr.map((dev: any, index: any) => {
            if (
              x >= dev.left &&
              x <= dev.left + 20 &&
              y >= dev.top &&
              y < dev.top + 20
            ) {
              // alert("我被点了!");
              // console.log("我被点了!")
              iconFlag = true;
              console.log(`我被点了设备图标!${index}`);
            }
          });
          if (iconFlag) {
            break;
          }
          let dot: any = {
            x: x,
            y: y,
          };
          let coordinates: any = pointArr;
          coordinates.map((item: any) => {
            item.x = item.left;
            item.y = item.top;
          });
          let flag = proxyData.queryPtInPolygon(dot, coordinates);
          // console.log(flag);
          if (flag) {
            console.log("点击了区域" + item.localName);
            contx.emit("checkSpace", item);
            break;
          }
        }
      },
      queryPtInPolygon(point: any, polygon: any) {
        let p1: any = "";
        let p2: any = "";
        let p3: any = "";
        let p4: any = "";

        p1 = point;
        p2 = { x: 1000000000000, y: point.y };

        let count: any = 0;
        //对每条边都和射线作对比
        for (let i = 0; i < polygon.length - 1; i++) {
          p3 = polygon[i];
          p4 = polygon[i + 1];
          if (checkCross(p1, p2, p3, p4) == true) {
            count++;
          }
        }
        p3 = polygon[polygon.length - 1];

        p4 = polygon[0];
        if (checkCross(p1, p2, p3, p4) == true) {
          count++;
        }

        return count % 2 == 0 ? false : true;

        //判断两条线段是否相交
        function checkCross(p1: any, p2: any, p3: any, p4: any) {
          let v1: any = { x: p1.x - p3.x, y: p1.y - p3.y };
          let v2: any = { x: p2.x - p3.x, y: p2.y - p3.y };

          let v3: any = { x: p4.x - p3.x, y: p4.y - p3.y };
          let v: any = crossMul(v1, v3) * crossMul(v2, v3);

          v1 = { x: p3.x - p1.x, y: p3.y - p1.y };
          v2 = { x: p4.x - p1.x, y: p4.y - p1.y };

          v3 = { x: p2.x - p1.x, y: p2.y - p1.y };
          return v <= 0 && crossMul(v1, v3) * crossMul(v2, v3) <= 0
            ? true
            : false;
        }

        //计算向量叉乘
        function crossMul(v1: any, v2: any) {
          return v1.x * v2.y - v1.y * v2.x;
        }
      },
      loadAllImages(imgUrls: any) {
        let _load: any = function (imgUrl: any) {
          //创建img标签
          let img: any = new Image();
          img.src = imgUrl;
          // img.src = require("@/assets/svg/coffee.svg");
          //跨域选项
          img.setAttribute("crossOrigin", "Anonymous");
          return new Promise((resolve, reject) => {
            //文件加载完毕
            img.onload = function () {
              resolve(img);
            };
          });
        };
        let _loadAll: any = function (imgUrls: any) {
          let loadedImageUrls: any = [];
          for (let i = 0, len = imgUrls.length; i < len; i++) {
            loadedImageUrls.push(_load(imgUrls[i]));
          }
          return loadedImageUrls;
        };
        return Promise.all(_loadAll(imgUrls));
      },
      // 记录需要画的图片
      addIcon(item: any, type: any, iconPerstion: any) {
        let key: any = item.spaceId + "" + type;
        if (proxyData.canvasImageArr[key]) {
          proxyData.canvasImageArr[key].iconPerstion = iconPerstion;
        } else {
          let obj: any = {
            url: item.icon,
            iconPerstion: iconPerstion,
          };
          proxyData.canvasImageArr[key] = obj;
        }
      },
      // 画图标
      drawIcon(ctx: any, type: any = 0) {
        let canvasImageArr: any = proxyData.canvasImageArr;
        let imgUrlArr: any = [];
        let perstionArr: any = [];

        for (let key in canvasImageArr) {
          let item: any = canvasImageArr[key];
          imgUrlArr.push(item.url);
          perstionArr.push(item.iconPerstion);
        }
        if (type == 0) {
          proxyData.loadAllImages(imgUrlArr).then((res: any) => {
            proxyData.iconData = res;
            res.map((icon: any, index: any) => {
              let iconPerstion: any = perstionArr[index];
              iconPerstion.width = 25;
              iconPerstion.height = 15;
              ctx.drawImage(
                icon,
                iconPerstion.left,
                iconPerstion.top,
                iconPerstion.width,
                iconPerstion.height
              );
            });
          });
        } else {
          proxyData.iconData.map((icon: any, index: any) => {
            let iconPerstion: any = perstionArr[index];
            iconPerstion.width = 25;
            iconPerstion.height = 15;
            ctx.drawImage(
              icon,
              iconPerstion.left,
              iconPerstion.top,
              iconPerstion.width,
              iconPerstion.height
            );
          });
        }
      },
      init(data: any) {
        proxyData.mapData = data;
        proxyData.initCanvas();
        proxyData.bindEvent();
      },
    });
    onMounted(() => {});
    return {
      ...toRefs(proxyData),
    };
  },
});
</script>
    <style lang="scss" scoped>
.canvas-box {
  width: 100%;
  height: calc(100% - 80px);
  // overflow-x: hidden;
  // overflow-y: hidden;
}
.com-upload {
  width: 100%;
  height: 100%;
  // overflow: hidden;
}
.space-search {
  position: fixed;
  width: 350px;
  left: 10px;
  top: 50px;
  z-index: 333;
}
</style>
        