<!-- 电路图编辑器页面 -->
<template>
  <div>
    <div id="components-layout">
      <a-layout>
        <!-- {{tableDefaultData}} -->
        <a-layout-header>
          <a-button type="primary" style="margin-left: 20px" @click="testD"
            >保存</a-button
          >
          <!-- <a-button type="primary" style="margin-left: 20px" @click="testE"
            >载入模板</a-button
          > -->
          <a-button type="primary" style="margin-left: 20px" @click="testH"
            >预览</a-button
          >
          <a-button type="primary" style="margin-left: 20px" @click="deleteImg"
            >删除元器件</a-button
          >
          <!-- <a style="margin-left: 20px" href="https://svgv1.yaolunmao.top">
            <a-button type="primary">1.0版本</a-button>
          </a> -->
          <!-- <a style="margin-left: 20px" href="https://svgedit.yaolunmao.top">
            <a-button type="primary">在线绘图</a-button>
          </a> -->
          <!-- <a
            style="margin-left: 20px"
            href="https://github.com/yaolunmao/vue-webtopo-svgeditor"
          >
            <a-button type="primary">帮助</a-button>
          </a> -->
        </a-layout-header>
        <span v-if="!shrink" @click="exitFullscreen" class="icon-shrink svgfont"
          >&#xe62b;</span
        >
        <a-layout class="pageMain">
          <a-layout-sider class="leftNav">
            <LeftToolBar :svgInfoData="svgInfoData"></LeftToolBar>
          </a-layout-sider>
          <a-layout-content class="centerContain" :class="{ fixed: !shrink }">
            <div
              class="canvas-content"
              id="canvas"
              @mousemove="MouseMove"
              @mousedown="MousedownCanvas"
              @mouseup="MouseupCanvas"
              @dblclick="DblClick"
              @mousewheel="MouseWheel"
            >
              <!--拖动辅助线-->
              <div id="guide-x"></div>
              <div id="guide-y"></div>
              <!-- 画布 -->
              <svg
                version="1.1"
                xmlns="http://www.w3.org/2000/svg"
                xmlns:xlink="http://www.w3.org/1999/xlink"
                style="background-color: #000000"
                width="100%"
                height="100%"
              >
                <defs />
                <filter x="0" y="0" width="1" height="1" id="solid">
                  <feFlood flood-color="rgb(255,255,255)" />
                  <feComposite in="SourceGraphic" />
                </filter>
                <g
                  style="cursor: pointer"
                  v-for="(item, index) in svgLists"
                  :key="index"
                  :id="item.id"
                  :type="item.type"
                  @mousedown="
                    MousedownSvg(
                      item.id,
                      index,
                      item.svgPositionX,
                      item.svgPositionY,
                      $event
                    )
                  "
                  :title="item.title"
                  :transform="
                    'translate(' +
                    item.svgPositionX +
                    ',' +
                    item.svgPositionY +
                    ') rotate(' +
                    item.angle +
                    ') scale(' +
                    item.size +
                    ')'
                  "
                >
                  <SvgComponents
                    :svg_color="item.svgColor"
                    :svgInfoData="svgInfoData"
                    :svgtype="item.type"
                    :text="item.svgText"
                    :size="item.size"
                    :font-size="item.fontSize"
                    :height="item.height"
                  ></SvgComponents>
                </g>
              </svg>
            </div>
          </a-layout-content>
          <a-layout-sider class="rightNav">
            <RightToolBar
              :svgInfo="selectSvgInfo"
              @setTableAttr="setTableAttr"
            ></RightToolBar>
          </a-layout-sider>
        </a-layout>
      </a-layout>
    </div>
  </div>
</template>
<script>
import LeftToolBar from "@/components/LeftToolBar.vue";
import RightToolBar from "@/components/RightToolBar.vue";
import global from "@/global/global.js"; //全局变量
import SvgComponents from "@/components/SvgComponents.vue";
import api from "@/api/site/systemImg";
import { ElMessage } from "element-plus";
export default {
  components: { LeftToolBar, RightToolBar, SvgComponents },
  data() {
    return {
      svgInfoData: [], //接口获取到的组件数据
      shrink: true, //收缩状态  true收缩  false展开
      svgLists: [], //svg列表
      //鼠标位置
      mousePosition: {
        positionX: "",
        positiony: "",
      },
      //辅助线元素
      guideX: "",
      guideY: "",
      CurrentlySelectedToolBar: {},
      selectSvg: {
        ID: "", //要移动的svg
        Index: 0,
        mouseStatus: 0, // 鼠标状态 1按下； 0弹起
        mPositionX: 0, //选中svg时鼠标的x轴坐标
        mPositionY: 0, //选中svg时鼠标的y轴坐标
        pointX: 0, //选中svg时svg的x轴坐标
        pointY: 0, //选中svg时svg的y轴坐标
      },
      selectSvgInfo: "",
      tableDefaultData: [],
      AnalogData: [],
    };
  },
  methods: {
    MouseMove(e) {
      let _this = this;

      if (this.selectSvg.mouseStatus == 0) {
        return;
      }
      const { clientX, clientY } = e;

      let svgID = this.svgLists[this.selectSvg.Index].id;
      //排除当前元素剩下的所有svg元素的列表
      let anyPositionList = this.svgLists.filter(function (list) {
        return list.id != svgID;
      });
      //将要移动的元素坐标设备为鼠标坐标
      let svgPositionX = this.selectSvg.pointX;
      let svgPositionY = this.selectSvg.pointY;
      svgPositionX += clientX - this.selectSvg.mPositionX;
      svgPositionY += clientY - this.selectSvg.mPositionY;
      setTimeout(function () {
        //少于十个像素自动吸附
        //从所有的x坐标列表中查与当前坐标少于10个像素的组件是否存在
        let exitsAdsorbX = anyPositionList.filter(function (list) {
          return (
            -10 < list.svgPositionX - svgPositionX &&
            list.svgPositionX - svgPositionX < 10
          );
        });
        if (exitsAdsorbX.length > 0) {
          svgPositionX = exitsAdsorbX[0].svgPositionX;
        }
        //y轴相同 横向坐标自动吸附
        let exitsAdsorbY = anyPositionList.filter(function (list) {
          return (
            -10 < list.svgPositionY - svgPositionY &&
            list.svgPositionY - svgPositionY < 10
          );
        });
        if (exitsAdsorbY.length > 0) {
          svgPositionY = exitsAdsorbY[0].svgPositionY;
        }
        _this.svgLists[_this.selectSvg.Index].svgPositionX = svgPositionX;
        _this.svgLists[_this.selectSvg.Index].svgPositionY = svgPositionY;
        //从所有的x坐标列表中查当前坐标是否存在
        let exitsNowX = anyPositionList.filter(function (list) {
          return list.svgPositionX === svgPositionX;
        });
        if (exitsNowX.length > 0) {
          _this.guideY.style.setProperty("left", svgPositionX - 1 + "px");
          _this.guideY.style.display = "inline";
        } else {
          _this.guideY.style.display = "none";
        }
        //从所有的y坐标列表中查当前坐标是否存在
        let exitsNowY = anyPositionList.filter(function (list) {
          return list.svgPositionY === svgPositionY;
        });
        if (exitsNowY.length > 0) {
          _this.guideX.style.setProperty("top", svgPositionY + "px");
          _this.guideX.style.display = "inline";
        } else {
          _this.guideX.style.display = "none";
        }
      }, 1);
    },
    MousedownCanvas() {
      // console.log('点击了画布');
    },
    MousedownSvg(id, index, pointX, pointY, e) {
      this.CurrentlySelectedToolBar.Type = global.CurrentlySelectedToolBarType =
        "";
      this.CurrentlySelectedToolBar.Title =
        global.CurrentlySelectedToolBarTitle = "";

      //从数组里面根据index找到当前元素
      this.selectSvg.ID = id;
      this.selectSvg.Index = index;
      this.selectSvg.mouseStatus = 1;
      this.selectSvg.mPositionX = e.clientX;
      this.selectSvg.mPositionY = e.clientY;
      this.selectSvg.pointX = pointX;
      this.selectSvg.pointY = pointY;
      // console.log(this.svgLists[index]);
      this.selectSvgInfo = this.svgLists[index];

      //获取所有g标签 将当前标签追加选中样式
      let gAnyList = document.querySelectorAll("g");
      gAnyList.forEach((g) => {
        g.classList.remove("topo-layer-view-selected");
      });
      document.getElementById(id).classList.add("topo-layer-view-selected");
    },
    MouseupCanvas() {
      this.guideX.style.display = "none";
      this.guideY.style.display = "none";
      if (
        this.CurrentlySelectedToolBar.Title != "" ||
        this.CurrentlySelectedToolBar.Type != ""
      ) {
        return;
      }
      // this.selectSvg.ID = '';
      this.selectSvg.mouseStatus = 0;
    },
    MouseWheel(e) {
      //获取当前选中组件
      let selectSvgInfo = this.selectSvgInfo;
      if (
        selectSvgInfo == undefined ||
        selectSvgInfo == null ||
        selectSvgInfo == ""
      ) {
        return;
      }
      e.preventDefault();
      //判断滚轮方向 -100是往上滑 100是下滑
      let svgZoom = e.deltaY < 0 ? 0.1 : -0.1;
      console.log(e.deltaY);
      selectSvgInfo.size += svgZoom;
      selectSvgInfo.size = parseFloat(selectSvgInfo.size.toFixed(1));
      if (selectSvgInfo.size < 1) {
        selectSvgInfo.size = 1;
      }
    },
    DblClick() {
      //获取所有g标签 清除所有选中样式
      let gAnyList = document.querySelectorAll("g");
      gAnyList.forEach((g) => {
        g.classList.remove("topo-layer-view-selected");
      });
      this.selectSvgInfo = "";
    },
    //保存事件
    testD() {
      var array = this.svgLists;
      array.map((val) => {
        val.siteId = this.$store.state.siteId;
        delete val.id;
      });
      if (this.svgLists.length > 0) {
        //请求保存接口
        api
          .setHookupComponentComplete(array)
          .then((requset) => {
            if (requset.status === "SUCCESS") {
              ElMessage.success("保存成功!");
            } else {
              ElMessage.error(requset.msg);
            }
          })
          .catch(function (error) {
            console.log(error);
          });
      } else {
        ElMessage("请先添加元器件!");
      }
    },
    //载入模板事件
    testE() {
      let _this = this;
      _this.$axios
        .get(window.PLATFROM_CONFIG.ione)
        .then(function (response) {
          console.log(response.data);
          response.data.map((val) => {
            _this.svgLists.push(val);
          });
        })
        .catch(function (error) {
          console.log(error);
        });
      // this.svgLists = this.AnalogData;
    },
    //预览事件
    testH() {
      var msg = "系统可能不会保存您所做的更改。";
      if (confirm(msg) == true) {
        localStorage.setItem("svginfo", JSON.stringify(this.svgLists));
        this.$router.push({
          path: "/Power_diagram",
          name: "power_diagram",
        });
        return true;
      } else {
        return false;
      }
    },
    //设置表格属性
    setTableAttr(id, rowCount, colCount) {
      // console.log(id, rowCount, colCount);

      //根据当前id找到当前表格的index
      let tableIndex = this.svgLists.indexOf(
        this.svgLists.filter((f) => f.id == id)[0]
      );
      if (tableIndex == -1) {
        return;
      }
      let svgType = this.svgLists.filter((f) => f.id == id)[0].type;
      if (svgType != "TableSvg") {
        return;
      }
      let tableData = [];
      for (let r = 0; r < rowCount; r++) {
        let tableColDataList = [];
        for (let c = 0; c < colCount; c++) {
          if (
            this.svgLists[tableIndex].tableData.length >= r + 1 &&
            this.svgLists[tableIndex].tableData[r].cols.length >= c + 1
          ) {
            tableColDataList.push(
              this.svgLists[tableIndex].tableData[r].cols[c]
            );
          } else {
            let tableColData = {
              id: this.$UCore.GenUUid(),
              val: `${r + 1}行${c + 1}列`,
            };
            tableColDataList.push(tableColData);
          }
        }
        let tableRowData = {
          cols: tableColDataList,
        };
        tableData.push(tableRowData);
      }
      console.log(tableData);

      this.svgLists[tableIndex].tableData = tableData;

      let gAnyList = document.querySelectorAll("foreignObject");
      let data = "";
      data += " <table class='.divtable'>";
      for (var j = 0; j < tableData.length; j++) {
        data += "<tr>";
        for (var i = 0; i < tableData[j].cols.length; i++) {
          data +=
            "<td><input id=" +
            tableData[j].cols[i].id +
            " type='text' class='input' value=" +
            tableData[j].cols[i].val +
            " ></td>";
        }
        data += "</tr>";
      }
      data += "</table>";
      gAnyList[0].innerHTML = data;
      document.getElementsByClassName(".divtable")[0].style = `
        position: absolute;
        left: 0;
        top: 0;
        line-height: 20px;
        z-index: 111;
        cursor: pointer;
        font-size: 20px;`;
    },
    //删除元器件事件
    deleteImg() {
      let _this = this;
      let selectSvgInfo = _this.selectSvgInfo;
      //根据当前id找到当前元素的index
      let selectSvgIndex = _this.svgLists.indexOf(
        _this.svgLists.filter((f) => f.id == selectSvgInfo.id)[0]
      );
      _this.svgLists.splice(selectSvgIndex, 1);
    },
  },
  mounted() {
    window.onbeforeunload = function (e) {
      e = e || window.event;
      // 兼容IE8和Firefox 4之前的版本
      if (e) {
        e.returnValue = "关闭提示";
      }
      // Chrome, Safari, Firefox 4+, Opera 12+ , IE 9+
      return "关闭提示";
    };

    let _this = this;

    let canvasdiv = document.querySelector("#canvas");
    _this.guideX = document.querySelector("#guide-x"); //辅助线x轴
    _this.guideY = document.querySelector("#guide-y"); //辅助线y轴

    canvasdiv.addEventListener(
      "dragover",
      function (e) {
        e.preventDefault();
        _this.CurrentlySelectedToolBar =
          global.CurrentlySelectedToolBarItem.array;
      },
      false
    );
    canvasdiv.addEventListener(
      "drop",
      function (e) {
        e.preventDefault();
        if (_this.CurrentlySelectedToolBar.type == "") {
          return;
        }
        //根据类型和鼠标位置创建组件
        let svgItem = JSON.parse(
          JSON.stringify(_this.CurrentlySelectedToolBar)
        );
        svgItem.id = _this.$UCore.GenUUid();
        svgItem.svgPositionX = e.offsetX;
        svgItem.svgPositionY = e.offsetY;

        _this.svgLists.push(svgItem);

        setTimeout(function () {
          //获取所有g标签 将当前标签追加选中样式
          let gAnyList = document.querySelectorAll("g");
          gAnyList.forEach((g) => {
            g.classList.remove("topo-layer-view-selected");
          });
          document
            .getElementById(svgItem.id)
            .classList.add("topo-layer-view-selected");
          _this.selectSvgInfo = svgItem;
        }, 100);
      },
      false
    );
  },
  unmounted() {
    window.onbeforeunload = null;
  },
  created() {
    let _this = this;
    //当前页面监视键盘输入
    document.onkeydown = function (e) {
      //获取当前选中组件
      let selectSvgInfo = _this.selectSvgInfo;
      if (
        selectSvgInfo == undefined ||
        selectSvgInfo == null ||
        selectSvgInfo == ""
      ) {
        return;
      }
      //事件对象兼容
      let e1 = e || window.event || arguments.callee.caller.arguments[0];
      //键盘按键判断:左箭头-37;上箭头-38；右箭头-39;下箭头-40
      if (e1 && e1.keyCode == 37) {
        e.preventDefault();
        selectSvgInfo.svgPositionX -= 1;
      } else if (e1 && e1.keyCode == 38) {
        e.preventDefault();
        selectSvgInfo.svgPositionY -= 1;
      } else if (e1 && e1.keyCode == 39) {
        e.preventDefault();
        selectSvgInfo.svgPositionX += 1;
      } else if (e1 && e1.keyCode == 40) {
        e.preventDefault();
        selectSvgInfo.svgPositionY += 1;
      }
      //ctrl  c
      else if (e1 && e1.ctrlKey && e1.keyCode == 67) {
        e.preventDefault();
        let copySvgInfoStr = JSON.stringify(selectSvgInfo);
        let copySvgInfo = JSON.parse(copySvgInfoStr);
        copySvgInfo.id = _this.$UCore.GenUUid();
        copySvgInfo.svgPositionX = selectSvgInfo.svgPositionX + 10;
        copySvgInfo.svgPositionY = selectSvgInfo.svgPositionY + 10;
        _this.svgLists.push(copySvgInfo);
        _this.selectSvgInfo = copySvgInfo;
        setTimeout(function () {
          //获取所有g标签 将当前标签追加选中样式
          let gAnyList = document.querySelectorAll("g");
          gAnyList.forEach((g) => {
            g.classList.remove("topo-layer-view-selected");
          });
          document
            .getElementById(copySvgInfo.id)
            .classList.add("topo-layer-view-selected");
        }, 100);
      }
      //deleted
      else if (e1 && e1.keyCode == 46) {
        e.preventDefault();
        //根据当前id找到当前元素的index
        let selectSvgIndex = _this.svgLists.indexOf(
          _this.svgLists.filter((f) => f.id == selectSvgInfo.id)[0]
        );
        _this.svgLists.splice(selectSvgIndex, 1);
      }
    };
    //请求接口获取组件---->左侧基础数据
    api
      .gethookupComponentBasics()
      .then((requset) => {
        if (requset.status === "SUCCESS") {
          _this.svgInfoData = requset.data;
        } else {
          ElMessage.error(requset.msg);
        }
      })
      .catch(function (error) {
        console.log(error);
      });

    //请求接口获取组件---->list数据
    setTimeout(() => {
      api
        .getHookupComponentComplete({ siteId: this.$store.state.siteId })
        .then((requset) => {
          if (requset.data.length > 0) {
            _this.AnalogData = requset.data;

            _this.svgLists = JSON.parse(JSON.stringify(_this.AnalogData));
          } else {
            ElMessage.error(requset.msg);
          }
        })
        .catch(function (error) {
          console.log(error);
        });
    }, 1000);
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="less">
::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}
::-webkit-scrollbar-track {
  border-radius: 10px;
  background-color: #f2f2f2;
  box-shadow: 1px 1px 5px #333 inset;
}
::-webkit-scrollbar-thumb {
  border-radius: 10px;
  background-color: #444;
}
#components-layout .ant-layout-header {
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  line-height: 50px;
  height: 50px;
  background: #fff;
  color: rgb(0, 0, 0);
  z-index: 2;
  box-shadow: 1px 1px 5px #ddd;
}
.tdsvg[data-v-025fdfb6] {
  border: 1px solid #ff0;
  white-space: nowrap;
  background: #fff;
  color: #999;
  text-align: center;
  font-size: 16px;
  background-color: #7cfc00;
}
foreignObject {
  width: 0;
  height: 0;
  overflow: visible;
  cursor: pointer;
}

.add-tag .ainput {
  display: inline-block;
  height: 100%;
  padding: 0 32px;
  pointer-events: auto;
  position: absolute;
  left: 0;
  width: 100%;
  caret-color: #426bf2;
  border-style: none;
  color: #ff0;
  background-color: #000;
}
.add-tag {
  color: #333;
  padding: 0;
  position: relative;
}
.pageMain {
  position: absolute;
  left: 0;
  right: 0;
  top: 50px;
  bottom: 0;
  overflow: auto;
}
.leftNav {
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  min-width: unset !important;
  max-width: unset !important;
  width: 260px !important;
  z-index: 1;
  overflow: auto;
}
.centerContain {
  position: absolute;
  left: 260px;
  right: 300px;
  top: 0;
  bottom: 0;
  z-index: 1;
  overflow: auto !important;
  overflow-x: auto !important;
  transition: all 0.3s;
  z-index: 111;

  &.fixed {
    position: fixed;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
  }

  .canvas-content {
    width: 1920px;
    height: 1080px;
  }
  .btns-content {
    position: fixed;
    bottom: 10px;
    right: 320px;
    left: 280px;
    button {
      margin-left: 10px;
    }
  }
}
.rightNav {
  position: absolute;
  right: 0;
  top: 0;
  bottom: 0;
  min-width: unset !important;
  max-width: unset !important;
  width: 300px !important;
  z-index: 1;
  overflow: auto;
}
.icon-shrink {
  position: fixed;
  right: 20px;
  top: 5px;
  font-size: 24px;
  color: #fff;
  cursor: pointer;
  background: #1890ff;
  width: 38px;
  height: 38px;
  line-height: 38px;
  text-align: center;
  border-radius: 50%;
  user-select: none;
  z-index: 1111;
}

#components-layout .ant-layout-sider {
  background: #fff;
  color: rgb(167, 164, 164);
}
#guide-x {
  display: none;
  position: absolute;
  border-top: 1px dashed #55f;
  width: 100%;
  left: 0px;
  top: 500px;
}

#guide-y {
  display: none;
  position: absolute;
  border-left: 1px dashed #55f;
  height: 100%;
  left: 100px;
  top: 0px;
}
#canvas {
  -moz-user-select: none;
  -webkit-user-select: none;
  -ms-user-select: none;
  -khtml-user-select: none;
  user-select: none;
}
.ant-slider {
  margin-bottom: 16px;
}
.topo-layer {
  width: 100%;
  height: 100%;
  position: absolute;
  transform-origin: left top;
  overflow: auto;

  background-image: linear-gradient(
      45deg,
      #ccc 25%,
      transparent 25%,
      transparent 75%,
      #ccc 75%,
      #ccc
    ),
    linear-gradient(
      45deg,
      #ccc 25%,
      transparent 25%,
      transparent 75%,
      #ccc 75%,
      #ccc
    );
  background-size: 20px 20px;
  background-position: 0 0, 10px 10px;
}
.resize-left-top {
  position: absolute;
  height: 10px;
  width: 10px;
  background-color: white;
  border: 1px solid #0cf;
  left: -5px;
  top: -5px;
  cursor: nwse-resize;
}

.resize-left-bottom {
  position: absolute;
  height: 10px;
  width: 10px;
  background-color: white;
  border: 1px solid #0cf;
  left: -5px;
  bottom: -5px;
  cursor: nesw-resize;
}

.resize-right-top {
  position: absolute;
  height: 10px;
  width: 10px;
  background-color: white;
  border: 1px solid #0cf;
  right: -5px;
  top: -5px;
  cursor: nesw-resize;
}

.resize-right-bottom {
  position: absolute;
  height: 10px;
  width: 10px;
  background-color: white;
  border: 1px solid #0cf;
  right: -5px;
  bottom: -5px;
  cursor: nwse-resize;
}

.topo-layer-view-selected {
  outline: 1px solid #0cf;
}
</style>
