<template>
  <div class="com-upload">
    <div class="file-upload">
      <div class="file-upload-text">上传文件</div>
      <input
        class="file-upload-input"
        id="upfile"
        type="file"
        webkitdirectory
        @change="getFile"
      />
    </div>

    <canvas id="myCanvas" width="10000" height="10000">
      Canvas画正多边形
    </canvas>
  </div>
</template>
  
<script lang="ts">
import { saveMapPointInfo } from "@/apis/envmonitor";
import { number } from "echarts";
import { Toast } from "vant";
import { defineComponent, nextTick, onMounted, reactive, toRefs } from "vue";

export default defineComponent({
  components: {},
  setup() {
    let allObj: any = [];
    let spaceArr: any = [];
    let floorObj: any = {};
    const proxyData = reactive({
      allObj: allObj,
      floorObj: floorObj,
      spaceArr: spaceArr,
      // canvas画图
      initCanvas() {
        let canvasDom: any = document.querySelector("#myCanvas");
        let ctx: any = canvasDom.getContext("2d");
        let dots: any = proxyData.allObj.objArr;
        console.log(proxyData.allObj.objArr);
        for (let key in dots) {
          let item = dots[key];
          console.log(item);
          ctx.lineWidth = 1;
          ctx.fillStyle = "#cfefef";
          ctx.beginPath();
          let circleArr: any = [];
          for (let i = 0; i < item.length; i++) {
            item[i].left = item[i].left;
            item[i].top = item[i].top;
            if (item[i].type === "circle") {
              circleArr.push(item[i]);
            } else {
              if (!item[i].type) {
                ctx.lineTo(item[i].left, item[i].top);
              }
            }
          }
          if (circleArr && circleArr.length) {
            ctx.lineTo(circleArr[0].left, circleArr[0].top);
            ctx.bezierCurveTo(
              circleArr[1].left,
              circleArr[1].top,
              circleArr[2].left,
              circleArr[2].top,
              circleArr[3].left,
              circleArr[3].top
            );
          } else {
            ctx.lineTo(item[0].left, item[0].top);
          }
          ctx.fill();
          ctx.closePath();
          ctx.strokeStyle = "red"; //填充边框颜色
          ctx.stroke();
          // canvasDom.addEventListener("click", function (e: any) {
          //   const canvasInfo = canvasDom.getBoundingClientRect();
          //   console.log(e);
          //   console.log(canvasInfo);
          //   console.log(ctx.isPointInPath(e.layerX, e.layerY));
          // });
        }
      },
      getFile(e: any) {
        console.log(e.target.files);
        let files: any = e.target.files;
        for (let i = 0; i < files.length; i++) {
          let fileSelect: any = files[i];
          let name: any = fileSelect.name;
          name = name.split(".")[0];
          let reader: any = new FileReader();
          if (typeof FileReader === "undefined") {
            console.log("您的浏览器不支持FileReader接口");
            return;
          }
          reader.readAsText(fileSelect, "gb2312"); //注意读取中文的是用这个编码，不是utf-8
          reader.onload = function () {
            let result: any = reader.result;
            proxyData.handPoint(result, name);
            if (i === files.length - 1) {
              // 处理数据的高度问题(因为取点的图是y是从下面开始获取的 )
              proxyData.formSpaceData();
              proxyData.floorObj.spaceList = proxyData.spaceArr;
              proxyData.saveMapPointInfo();
            }
          };
        }
      },
      // 地图数据处理结果保存
      saveMapPointInfo() {
        console.log("数据格式化---");
        console.log(proxyData.floorObj);
        Toast.loading({
          duration: 0, // 持续展示 toast
          forbidClick: true,
          message: "正在上传...",
        });
        saveMapPointInfo(proxyData.floorObj)
          .then((res: any) => {
            if (res.result == "success") {
            }
            Toast.clear();
          })
          .catch(() => {
            Toast.clear();
          });
      },
      // 数据格式化
      formSpaceData() {
        proxyData.spaceArr.map((item: any) => {
          item.devicePoint.map((dev: any) => {
            dev.left = dev.left * 1;
            dev.top = proxyData.floorObj.height - dev.top;
            // dev.top = dev.top;
          });
          item.logoPointArr.map((dev: any) => {
            dev.left = dev.left * 1;
            dev.top = proxyData.floorObj.height - dev.top;
            // dev.top = dev.top;
          });
          item.pointArr.map((dev: any) => {
            dev.left = dev.left * 1;
            dev.top = proxyData.floorObj.height - dev.top;
            // dev.top = dev.top;
          });
          item.circlePoint.map((dev: any) => {
            dev.left = dev.left * 1;
            dev.top = proxyData.floorObj.height - dev.top;
            // dev.top = dev.top;
          });
          item.detailPoint.map((dev: any) => {
            dev.left = dev.left * 1;
            dev.top = proxyData.floorObj.height - dev.top;
            // dev.top = dev.top;
          });
        });
      },
      handPoint(result: any, name: any) {
        result = result.replace(/\"/g, "");
        let nameArr: any = name.split("-");
        let arr: any = result.split(/[(\r\n)\r\n]+/);
        if (nameArr && nameArr[0] == "L") {
          arr.map((item: any) => {
            if (item) {
              let itemArr: any = item.split(",");
              let obj: any = {
                width: itemArr[0] ? itemArr[0] * 1 : 0,
                height: itemArr[1] ? itemArr[1] * 1 : 0,
              };
              console.log(obj);
              if (obj.width && obj.height) {
                proxyData.floorObj.width = obj.width;
                proxyData.floorObj.height = obj.height;
                proxyData.floorObj.floorId = nameArr[1];
              }
            }
          });
        } else {
          if (nameArr[0]) {
            let pointObj: any = {
              spaceId: nameArr[1] ? nameArr[1].toString() : "",
              localName: nameArr[0] ? nameArr[0].toString() : "",
              canClick: nameArr[2] && nameArr[2] == "unc" ? false : true,
              pointArr: [],
              devicePoint: [],
              circlePoint: [],
              detailPoint: [],
              logoPointArr: [],
            };

            arr.map((item: any, index: any) => {
              if (item) {
                let itemArr: any = item.split(",");
                let obj: any = {
                  left: itemArr[0],
                  top: itemArr[1],
                };
                if (pointObj.canClick && nameArr[2] && nameArr[2] == "c") {
                  pointObj.circlePoint.push(obj);
                } else if (
                  !pointObj.canClick &&
                  nameArr[2] &&
                  nameArr[2] == "c"
                ) {
                  pointObj.circlePoint.push(obj);
                } else {
                  if (index < 1) {
                    pointObj.devicePoint.push(obj);
                  } else if (index < 2) {
                    pointObj.logoPointArr.push(obj);
                  } else if (index < 3) {
                    pointObj.detailPoint.push(obj);
                  } else {
                    pointObj.pointArr.push(obj);
                  }
                }
              }
            });

            let flag: any = false;
            proxyData.spaceArr.map((item: any) => {
              if (nameArr[1] && item.spaceId === nameArr[1]) {
                item.circlePoint = pointObj.circlePoint;
                flag = true;
              } else {
                if (item.spaceId === nameArr[0]) {
                  item.logoPointArr = pointObj.logoPointArr;
                  item.devicePoint = pointObj.devicePoint;
                  item.pointArr = pointObj.pointArr;
                  flag = true;
                }
              }
            });
            if (!flag) {
              proxyData.spaceArr.push(pointObj);
            }
          }
        }
      },
      // 处理坐标
      handleStr(mapstr: any) {
        let maparr: any = mapstr.split("<DIV ");
        //console.log("maparr", maparr);
        let _this: any = proxyData;
        let allDiv: any = [];
        let objArr: any = {};
        let allObj: any = {};
        //debugger;
        maparr.map((item: any) => {
          let divobj: any = {};
          let divarr: any = item.split(" ");
          //console.log("divarr", divarr);
          divarr.map(function (item: any) {
            if (item.indexOf("id=") > -1) {
              let idarr: any = item.split("=");
              // debugger;
              let idstr: any = idarr[1];
              divobj.id = idstr;
              // console.log("idstr", idstr);
              return;
            }
          });

          divobj.height = proxyData.getNum(item, "HEIGHT");
          divobj.width = proxyData.getNum(item, "WIDTH");
          divobj.left = proxyData.getNum(item, "LEFT");
          divobj.top = proxyData.getNum(item, "TOP");
          let title: any = proxyData.getNum(item, "title");
          let titleArr: any = title.split("-");
          divobj.spaceId = titleArr[0];
          divobj.order = titleArr[1] * 1;
          if (titleArr[2] && titleArr[2] === "c") {
            divobj.type = "circle";
          }
          if (divobj.width) {
            allDiv.push(divobj);
          }
        });

        allDiv.map((item: any) => {
          if (item.spaceId) {
            if (objArr[item.spaceId]) {
              objArr[item.spaceId].push(item);
            } else {
              objArr[item.spaceId] = [item];
            }
          } else {
            allObj.width = item.width;
            allObj.height = item.height;
          }
        });
        for (let key in objArr) {
          objArr[key].sort(proxyData.sortab("order"));
        }
        proxyData.allObj.objArr = objArr;
        // 画图
        proxyData.initCanvas();
        console.log(JSON.stringify(proxyData.allObj.objArr));
      },
      sortab(data: any) {
        return function (obj1: any, obj2: any) {
          var value1 = obj1[data];
          var value2 = obj2[data];
          if (value2 < value1) {
            return 1;
          } else if (value2 > value1) {
            return -1;
          } else {
            return 0;
          }
        };
      },
      getNum(str: any, param: any) {
        //debugger;
        let paindex: any = str.indexOf(param);
        // console.log(str);
        if (paindex > -1) {
          if (param === "title") {
            let palength: any = param.length;
            let otherstr: any = str.substr(paindex + palength);
            let pxindex: any = otherstr.indexOf("#");
            // debugger
            let numstr: any = otherstr.substr(0, pxindex);
            // console.log(numstr);
            let arr: any = numstr.split("=");
            let tempStr: any = arr[1];
            if (tempStr) {
              tempStr = tempStr.substr(1, tempStr.length);
            }
            // console.log(tempStr);
            return tempStr;
          } else {
            let palength: any = param.length;
            let otherstr: any = str.substr(paindex + palength);
            //   console.log(otherstr)
            let pxindex: any = otherstr.indexOf("px");
            let numstr: any = otherstr.substr(0, pxindex);
            numstr = numstr.replace(/:/, "");
            return numstr ? Number(numstr) : "";
          }
        }
        return "";
      },
    });
    nextTick(() => {});
    onMounted(() => {});
    return {
      ...toRefs(proxyData),
    };
  },
});
</script>
  <style lang="scss" scoped>
.home {
  .child-view {
    position: absolute;
    width: 100%;
    transition: all 0.8s cubic-bezier(0.55, 0, 0.1, 1);
  }

  .slide-left-enter,
  .slide-right-leave-active {
    opacity: 0;
    -webkit-transform: translate(50px, 0);
    transform: translate(50px, 0);
  }

  .slide-left-leave-active,
  .slide-right-enter {
    opacity: 0;
    -webkit-transform: translate(-50px, 0);
    transform: translate(-50px, 0);
  }
}
</style>
  