<!-- 电路图编辑器页面 -->
<template>
  <div style="padding: 0px 10px 10px">
    <div id="components-layout">
      <el-container>
        <!-- {{tableDefaultData}} -->
        <el-header style="position: relative">
          <el-dialog
            :close-on-click-modal="false"
            :visible.sync="addSvgVisible"
            title="模拟添加组件"
            width="40%"
          >
            <el-form :model="testAddSvg" label-width="80px">
              <el-form-item label="类型">
                <el-input
                  v-model="testAddSvg.type"
                  placeholder="请输入组件类型"
                />
              </el-form-item>
              <el-form-item label="标题">
                <el-input
                  v-model="testAddSvg.title"
                  placeholder="请输入组件标题"
                />
              </el-form-item>
              <el-form-item label="svg代码">
                <el-input
                  v-model="testAddSvg.template"
                  placeholder="请输入svg代码"
                />
              </el-form-item>
              <el-form-item label="默认颜色">
                <input type="color" v-model="testAddSvg.default_attr.color" />
              </el-form-item>
              <el-form-item label="预览图像">
                <el-input
                  v-model="testAddSvg.priview_img"
                  placeholder="请输入预览图像地址"
                />
              </el-form-item>
              <el-form-item label="绘制方式">
                <el-select
                  v-model="testAddSvg.panel_class"
                  clearable
                  placeholder="请选择绘制方式"
                >
                  <el-option
                    v-for="item in way"
                    :key="item.label"
                    :label="item.label"
                    :value="item.label"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="创建类型">
                <el-select
                  v-model="testAddSvg.create_type"
                  clearable
                  placeholder="请选择创建类型"
                >
                  <el-option
                    v-for="item in type"
                    :key="item.label"
                    :label="item.label"
                    :value="item.label"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
              <el-button size="mini" type="primary" @click="addSvgHandleOk"
                >确 定</el-button
              >
            </span>
          </el-dialog>

          <el-button
            size="mini"
            type="primary"
            @click="dialogMenu = true"
            icon="el-icon-plus"
            >新增图纸</el-button
          >
          <el-button
            type="primary"
            size="mini"
            @click="showAddSvgModal"
            icon="el-icon-plus"
          >
            添加组件
          </el-button>
          <el-button
            size="mini"
            type="primary"
            @click="testA"
            icon="el-icon-upload2"
            >载入模板</el-button
          >
          <!-- <el-button size="mini" type="primary" @click="testB">模板2</el-button> -->
          <el-button
            size="mini"
            type="primary"
            @click="testH"
            icon="el-icon-view"
            >预览</el-button
          >

          <el-button
            size="mini"
            type="primary"
            @click="exportSvg"
            icon="el-icon-download"
            >导出svg</el-button
          >

          <el-button
            size="mini"
            type="primary"
            @click="exportData"
            icon="el-icon-download"
            >导出数据</el-button
          >
          <el-button
            size="mini"
            type="primary"
            @click="saveData"
            icon="el-icon-check"
            >保存</el-button
          >
          <el-button
            style="position: absolute; top: 0px; right: 0px"
            size="mini"
            type="primary"
            @click="$emit('exit')"
            icon="el-icon-refresh-left"
            >返回</el-button
          >
          <!-- <el-button size="mini" type="primary" @click="ceshi">测试</el-button> -->
          <!-- <el-button size="mini" type="primary" @click="addData"
            >新增</el-button
          > -->
        </el-header>
        <el-container class="pageMain">
          <!-- <a-layout> -->
          <el-aside width="260px">
            <LeftToolBar
              ref="LeftToolBar"
              :svgInfoData="svgInfoData"
              :parameters="parameters"
              @testA="testA"
              @backgroundSRC="backgroundSRC"
              @sendData="sendData"
              :treeData="treeData"
            ></LeftToolBar>
          </el-aside>
          <el-main class="centerContain">
            <div
              ref="canvas"
              id="canvas"
              class="canvansDiv"
              :style="'transform: scale(' + scaleValue + ')'"
              @mousemove="MouseMove"
              @mousedown="MousedownCanvas"
              @mouseup="MouseupCanvas"
              @dblclick="DblClick"
              @mousewheel.prevent="MouseWheel"
            >
              <!--拖动辅助线-->
              <div
                id="guide-x"
                ref="guidex_dom"
                :style="'border-top: ' + 1 / scaleValue + 'px dashed #55f'"
              ></div>
              <div
                id="guide-y"
                ref="guidey_dom"
                :style="'border-left: ' + 1 / scaleValue + 'px dashed #55f'"
              ></div>
              <!-- 画布 -->
              <svg
                version="1.1"
                xmlns="http://www.w3.org/2000/svg"
                xmlns:xlink="http://www.w3.org/1999/xlink"
                style="background-color: #000"
                width="100%"
                height="100%"
                ref="svg_dom_ref"
                id="svg_container"
                class="focal"
              >
                <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="item.id"
                  :id="item.id"
                  :class="
                    selectSvgInfo.id == item.id
                      ? 'topo-layer-view-selected'
                      : ''
                  "
                  @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
                    :component_prop="item"
                    :component_type="item.type"
                    :svgInfoData="svgInfoData"
                  ></SvgComponents>
                  <!-- :component_template="
                      svgInfoData.filter((f) => f.type == item.type)[0].template
                    " -->
                </g>
              </svg>
            </div>
            <div class="zoonStyle">
              <span> 缩放： </span>
              <el-slider
                v-model="value1"
                :min="0.1"
                :max="2"
                :step="0.1"
                @change="scaleValueChange"
                style="width: 200px"
              />
            </div>
          </el-main>
          <el-aside width="300px">
            <RightToolBar
              :svgInfo="selectSvgInfo"
              :svgListsInfo="svgLists"
              ref="RightToolBar"
              @svgDrag="svgDrag"
              @setTableAttr="setTableAttr"
              @setTableAttrTree="setTableAttrTree"
              @setTableAttrStatus="setTableAttrStatus"
              @setTableAttrUID="setTableAttrUID"
              @setTableAttrDisplay="setTableAttrDisplay"
            ></RightToolBar>
          </el-aside>
        </el-container>
      </el-container>
    </div>
    <el-dialog
      title="新增图纸"
      :visible.sync="dialogMenu"
      width="380px"
      :before-close="handleClose"
      :close-on-click-modal="false"
    >
      <el-form ref="form" :inline="true">
        <el-form-item label="图纸名称:">
          <el-input
            v-model="addname"
            placeholder="请输入图纸名称"
            clearable
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="addQuery">确 定</el-button>
      </span>
    </el-dialog>
    <!-- <el-dialog
      title="新增"
      :visible.sync="dialogVisible"
      width="20%"
      :before-close="handleClose"
      :close-on-click-modal="false"
    >
      <el-form ref="form" :model="formData" label-width="80px">
        <el-form-item label="项目名称:">
          <el-input v-model="formData.name" placeholder="项目名称"></el-input>
        </el-form-item>
        <el-form-item label="id:">
          <el-input
            placeholder="请输入id"
            v-model="formData.id"
          >
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addFn"
          >确 定</el-button
        >
      </span>
    </el-dialog> -->
  </div>
</template>
<script>
import LeftToolBar from "@/components/LeftToolBar.vue";
import RightToolBar from "@/components/RightToolBar.vue";
import SvgComponents from "@/components/SvgComponents.vue";
import jquery from "jquery";
import "jquery.panzoom";
import "@/styles/subjx.css";
import "@/utils/subjx.js";
import {
  find,
  add,
  queryPage,
  addPage,
} from "@/api/configuration/configuration.js";
import { forEach } from "element-resize-detector/src/collection-utils";
import ItemVue from "@/layout/components/Navbar/Item.vue";
export default {
  components: { LeftToolBar, RightToolBar, SvgComponents },
  props: {
    params: {
      type: [Object, Array],
      default: undefined,
    },
  },
  data() {
    return {
      addname: "",
      dialogMenu: false,
      value1: 1,
      dialogVisible: false,
      testAddSvg: {
        type: "testAddSvg",
        title: "测试新增组件",
        panel_class: "",
        template:
          '<path :fill="prop_data.svgColor" :stroke="prop_data.svgColor" stroke-width="5" style="pointer-events:inherit" d="m143.72081869586242,163.35565803158485 c14.617751633754164,-41.93617271978648 71.89058180534832,0 0,53.91793635401125 c-71.89058180534832,-53.91793635401125 -14.617751633754164,-95.85410907379776 0,-53.91793635401125 z"  fill-opacity="1" stroke-opacity="1" transform="translate(-145,-180)"></path>',
        props: ["prop_data"],
        default_attr: {
          color: "#FF0000",
        },

        create_type: "",
        priview_img: "https://svg.yaolunmao.top/test.png",
      },
      way: [
        {
          id: 0,
          value: "选项1",
          label: "draggable",
        },
        {
          id: 1,
          value: "选项2",
          label: "draw",
        },
      ],
      type: [
        {
          id: 0,
          value: "选项1",
          label: "draggable",
        },
        {
          id: 1,
          value: "选项2",
          label: "click",
        },
      ],
      parameters: {},
      addSvgVisible: false,
      versionModelVisible: false,
      svgInfoData: [], //接口获取到的组件数据
      shrink: true, //收缩状态  true收缩  false展开
      svgLists: [], //svg列表
      treeData: [],
      //鼠标位置
      mousePosition: {
        positionX: "",
        positiony: "",
      },
      selectSvg: {
        ID: "", //要移动的svg
        Index: 0,
        mPositionX: 0, //选中svg时鼠标的x轴坐标
        mPositionY: 0, //选中svg时鼠标的y轴坐标
        pointX: 0, //选中svg时svg的x轴坐标
        pointY: 0, //选中svg时svg的y轴坐标
      },
      formData: {
        id: "",
        name: "",
      },
      mouseStatus: 0, // 鼠标状态 1按下； 0弹起
      selectSvgInfo: "",
      clickType: "", //鼠标点击行为
      scaleValue: 1, //缩放倍数
    };
  },
  methods: {
    //查询组态图元数据
    query() {
      find().then((res) => {
        // console.log(JSON.parse(res.data.json));
        let jsonData = JSON.parse(res.data.json);
        this.svgInfoData = jsonData;
      });
    },
    queryData() {
      // console.log(123, this.parameters);
      let data = {
        pid: this.parameters.id,
        pageNum: 1,
        pageSize: 100000,
      };
      queryPage(data).then((res) => {
        this.treeData = res.data.records;
      });
    },
    //新增项目弹窗
    addData() {
      this.formData = {
        name: "",
        id: "",
      };
      this.dialogVisible = true;
    },
    //新增项目确认
    //弹窗关闭
    handleClose() {
      this.dialogMenu = false;
      this.addname = "";
    },
    // 新增图纸
    addQuery() {
      if (this.addname.length == 0) {
        return this.$message("请输入新增页名称");
      }
      this.$refs.LeftToolBar.addname = this.addname;
      this.$refs.LeftToolBar.addQuery();
      this.handleClose();
    },
    //新增图元弹窗
    showAddSvgModal() {
      this.addSvgVisible = true;
    },
    //新增图元确定
    addSvgHandleOk() {
      // this.svgInfoData[this.svgInfoData.length] = this.testAddSvg;
      this.svgInfoData.push(this.testAddSvg);
      let form = new FormData();

      const blob = new Blob([JSON.stringify(this.svgInfoData)], {
        type: "application/json",
      });
      form.append("multipartFile", blob);
      // console.log(form);
      this.$confirm("是否确认新增?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          add(form).then((res) => {
            if (res.code == "A0000") {
              this.$message({
                message: res.message,
                type: "success",
              });
            }
            this.addSvgVisible = false;
            this.query();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消新增",
          });
        });
    },
    versionModelHandleOk() {
      this.versionModelVisible = false;
    },
    exportSvg() {
      let exportStr = document.querySelector("#svg_container").outerHTML;
      exportStr = exportStr
        .replace('width="100%"', 'width="1920"')
        .replace('height="100%"', 'height="1080"');
      let datastr = "data:text;charset=utf-8," + encodeURIComponent(exportStr);
      let download = document.createElement("a");
      download.setAttribute("href", datastr);
      download.setAttribute("download", "download.html");
      download.click();
      download.remove();
      // console.log(exportStr);
    },
    exportData() {
      // localStorage.setItem("svginfo", JSON.stringify(this.svgLists));
      let datastr =
        "data:text/json;charset=utf-8," +
        encodeURIComponent(JSON.stringify(this.svgLists));
      let download = document.createElement("a");
      download.setAttribute("href", datastr);
      download.setAttribute("download", "download.json");
      download.click();
      download.remove();
      // console.log(JSON.stringify(this.svgLists));
    },
    async saveData() {
      await this.$refs.LeftToolBar.position();
      let form = new FormData();
      // console.log(
      //   "🚀 ~ file: CircuitEdit.vue:480 ~ blob ~ JSON.stringify(this.$refs.LeftToolBar.dataTree:",
      //   JSON.stringify(this.$refs.LeftToolBar.dataTree)
      // );
      let blob = new Blob([JSON.stringify(this.$refs.LeftToolBar.dataTree)], {
        type: "application/json",
      });
      form.append("multipartFile", blob);
      form.append("name", this.parameters.name);
      form.append("pid", this.parameters.id);

      await addPage(form).then((res) => {
        if (res.type == "application/json") {
          this.$message({
            message: "保存成功!",
            type: "success",
          });
          this.$emit("exit");
        }
      });
    },
    // ceshi() {
    //   this.$refs.LeftToolBar.list.path=JSON.stringify(this.svgLists);
    // },
    MouseMove(e) {
      let _this = this;
      if (this.clickType == "draggable") {
        if (this.mouseStatus == 0) {
          return;
        }
        const { clientX, clientY } = e;
        // console.log(e.offsetX,e.offsetY);
        // let svgID = this.svgLists[this.selectSvg.Index].id;
        let svgID = this.selectSvg.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) / this.scaleValue;
        svgPositionY += (clientY - this.selectSvg.mPositionY) / this.scaleValue;
        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.$refs.guidey_dom.style.setProperty(
              "left",
              svgPositionX - 1 / _this.scaleValue + "px"
            );
            _this.$refs.guidey_dom.style.display = "inline";
          } else {
            _this.$refs.guidey_dom.style.display = "none";
          }
          //从所有的y坐标列表中查当前坐标是否存在
          let exitsNowY = anyPositionList.filter(function (list) {
            return list.svgPositionY === svgPositionY;
          });
          if (exitsNowY.length > 0) {
            _this.$refs.guidex_dom.style.setProperty(
              "top",
              svgPositionY - 1 / _this.scaleValue + "px"
            );
            _this.$refs.guidex_dom.style.display = "inline";
          } else {
            _this.$refs.guidex_dom.style.display = "none";
          }
        }, 1);
      } else if (this.clickType == "click") {
        if (this.mouseStatus == 0) {
          return;
        }
        this.selectSvgInfo.mPoint.endX = e.offsetX;
        this.selectSvgInfo.mPoint.endY = e.offsetY;
      }
    },
    MousedownCanvas(e) {
      if (this.clickType == "draggable") {
        return;
      }
      if (
        this.$store.state.webtop.CurrentlySelectedToolBar &&
        this.$store.state.webtop.CurrentlySelectedToolBar.CreateType == "click"
      ) {
        //根据类型和鼠标位置创建组件
        let svg_id = this.$UCore.GenUUid();
        let svgItem = {
          id: svg_id,
          title: this.$store.state.webtop.CurrentlySelectedToolBar.Title,
          type: this.$store.state.webtop.CurrentlySelectedToolBar.Type,
          typeName: this.$store.state.webtop.CurrentlySelectedToolBar.TypeName,
          svgColor: this.$store.state.webtop.CurrentlySelectedToolBar.Color,
          svgPositionX: e.offsetX,
          svgPositionY: e.offsetY,
          mPoint: {
            startX: e.offsetX,
            startY: e.offsetY,
            endX: e.offsetX,
            endY: e.offsetY,
          },
          size: 1,
          angle: 0,
          //translate:`translate(${this.mousePosition.positionX},${this.mousePosition.positionY})`
        };
        this.svgLists.push(svgItem);
        this.selectSvgInfo = svgItem;
        this.mouseStatus = 1;
        this.clickType = "click";
      }
    },
    MousedownSvg(id, index, pointX, pointY, e) {
      this.svgDrag(id);
      this.$store.dispatch("webtop/clearCurrentlySelectedToolBarAction", null);
      //从数组里面根据index找到当前元素
      this.selectSvg.ID = id;
      this.selectSvg.Index = index;
      this.mouseStatus = 1;
      this.selectSvg.mPositionX = e.clientX;
      this.selectSvg.mPositionY = e.clientY;
      this.selectSvg.pointX = pointX;
      this.selectSvg.pointY = pointY;
      this.selectSvgInfo = this.svgLists[index];

      // console.log(this.selectSvgInfo);
      if (this.selectSvgInfo.type == "TextbandinSvg" ) {
        this.$refs.RightToolBar.handleMonitoringTextbandinSvgClick(
          this.selectSvgInfo.lineId
        );
    
      }
      if (
        this.selectSvgInfo.type == "WireBreakOnSvg" ||
        this.selectSvgInfo.type == "WireBreakOffSvg" ||
        this.selectSvgInfo.type == "CircuitBreakerSvg"
      ) {
        if (this.selectSvgInfo.svgColor == "#00FF00") {
          this.selectSvgInfo.status = 0;
        } else if (this.selectSvgInfo.svgColor == "#FF0000") {
          this.selectSvgInfo.status = 1;
        }
      }
      this.$refs.RightToolBar.selectSvg = this.selectSvgInfo;
      this.clickType = "draggable";
    },
    // svg拖拽插件
    svgDrag(id) {
      // jquery(".removeID").remove();
      // setTimeout(() => {
      //   // 添加伸缩框
      //   jquery(`#${id}`).addClass("drag-svg");
      //   window.Subjx(".drag-svg").drag({
      //     container: "#svg-container",
      //     snap: {
      //       x: 1,
      //       y: 1,
      //       angle: 1,
      //     },
      //   });
      // }, 0);
    },
    MouseupCanvas() {
      if (this.mouseStatus == 0) {
        return;
      }
      this.$refs.guidex_dom.style.display = "none";
      this.$refs.guidey_dom.style.display = "none";
      // if (this.$store.state.webtop.CurrentlySelectedToolBar.Type != '') {
      //   return;
      // }
      // this.selectSvg.ID = '';
      this.mouseStatus = 0;
      // this.clickType = '';
      if (this.clickType == "draggable") {
        this.clickType = "";
      }
      if (this.clickType == "click") {
        if (
          this.selectSvgInfo.mPoint.startX == this.selectSvgInfo.mPoint.endX &&
          this.selectSvgInfo.mPoint.startY == this.selectSvgInfo.mPoint.endY
        ) {
          //根据当前id找到当前元素的index
          let selectSvgIndex = this.svgLists.indexOf(
            this.svgLists.filter((f) => f.id == this.selectSvgInfo.id)[0]
          );
          this.svgLists.splice(selectSvgIndex, 1);
          this.selectSvg = {};
          this.selectSvgInfo = {};
        }
      }
      // this.$store.state.webtop.CurrentlySelectedToolBar = {};
    },
    MouseWheel(e) {
      //获取当前选中组件
      if (this.selectSvgInfo == "") {
        this.value1 = e.deltaY < 0 ? this.value1 + 0.1 : this.value1 - 0.1;

        this.scaleValue = this.value1;
        return;
      }

      let selectSvgInfo = this.selectSvgInfo;
      if (
        selectSvgInfo == undefined ||
        selectSvgInfo == null ||
        selectSvgInfo == ""
      ) {
        return;
      }
      // e.preventDefault();
      // //判断滚轮方向 -100是往上滑 100是下滑
      // let svgZoom = e.deltaY < 0 ? 0.1 : -0.1;
      // selectSvgInfo.size += svgZoom;
      // selectSvgInfo.size = parseFloat(selectSvgInfo.size.toFixed(1));
      // if (selectSvgInfo.size < 1) {
      //   selectSvgInfo.size = 1;
      // }
    },
    DblClick() {
      jquery(".removeID").remove();
      this.selectSvgInfo = "";
      this.$store.dispatch("webtop/clearCurrentlySelectedToolBarAction", null);
      this.$refs.RightToolBar.selectSvg = {};
    },
    testA(val) {
      // console.log(val, "===============");
      let _this = this;
      //载入模板
      this.$axios
        .get(`/webtopo-svgeditor/${val == "" ? "example" : val}.json`)
        .then(function (response) {
          _this.svgLists = response.data;
          _this.$refs.RightToolBar.data = _this.svgLists;
          _this.svgLists.forEach((item) => {
            if (
              item.type == "WireBreakOnSvg" ||
              item.type == "WireBreakOffSvg" ||
              item.type == "CircuitBreakerSvg"
            ) {
              _this.selectSvgInfo = item;
              if (_this.selectSvgInfo.svgColor == "#00FF00") {
                _this.selectSvgInfo.status = 0;
              } else if (_this.selectSvgInfo.svgColor == "#FF0000") {
                _this.selectSvgInfo.status = 1;
              }
              // _this.modifystate();
              _this.$refs.RightToolBar.selectSvg = _this.selectSvgInfo;
              // _this.modifystate();
            }
          });
        })
        .catch(function (error) {
          // console.log(error);
        });
    },
    // testB() {
    //   let _this = this;
    //   //载入模板
    //   this.$axios
    //     .get("/webtopo-svgeditor/example.json")
    //     .then(function (response) {
    //       _this.svgLists = response.data;
    //     })
    //     .catch(function (error) {
    //       console.log(error);
    //     });
    // },
    testH() {
      // console.log(this.svgLists);

      // this.svgLists.forEach(item=>{
      //   if(item.type=="TextSvg"){
      //     item.title = item.title.replace('###',"111")
      //   }
      // })
      // console.log(this.svgLists);
      localStorage.setItem("svginfo", JSON.stringify(this.svgLists));
      // this.$router.push({
      //   path: "/CircuitPreview",
      //   name: "CircuitPreview",
      // });
      this.$emit("open", this.$refs.LeftToolBar.list.id);
    },
    setTableAttrUID(val) {
      // console.log(val,'===================');
      if (
        this.selectSvgInfo.typeName == "文字" &&
        this.selectSvgInfo.type == "TextSvg"
      ) {
        this.selectSvgInfo.UID = val;
        // this.selectSvgInfo.UID = val;
        // console.log(this.selectSvgInfo);
      }
    },
    //修改断路器及电线开关状态
    modifystate() {
      if (
        this.selectSvgInfo.type == "WireBreakOnSvg" ||
        this.selectSvgInfo.type == "WireBreakOffSvg"
      ) {
        if (this.selectSvgInfo.status == 0) {
          this.selectSvgInfo.type = "WireBreakOnSvg";
          this.svgLists.splice(
            this.svgLists.findIndex(
              (item) => item.id === this.selectSvgInfo.id
            ),
            1
          );
          this.selectSvgInfo.svgColor = "#00FF00";
          this.selectSvgInfo.typeName = "电线开关-连接";
          this.selectSvgInfo.title = "电线开关-连接";
          setTimeout(() => {
            this.svgLists.push(this.selectSvgInfo);
          }, 100);
        } else {
          this.selectSvgInfo.type = "WireBreakOffSvg";
          this.svgLists.splice(
            this.svgLists.findIndex(
              (item) => item.id === this.selectSvgInfo.id
            ),
            1
          );
          this.selectSvgInfo.svgColor = "#FF0000";
          this.selectSvgInfo.typeName = "电线开关-断开";
          this.selectSvgInfo.title = "电线开关-断开";
          setTimeout(() => {
            this.svgLists.push(this.selectSvgInfo);
          }, 100);
        }
      } else if (this.selectSvgInfo.type == "CircuitBreakerSvg") {
        if (this.selectSvgInfo.status == 0) {
          this.selectSvgInfo.svgColor = "#00FF00";
        } else if (this.selectSvgInfo.status == 1) {
          this.selectSvgInfo.svgColor = "#FF0000";
        }
      }
    },
    setTableAttrStatus(val) {
      // console.log(val, "========================");
      if (
        this.selectSvgInfo.type == "WireBreakOnSvg" ||
        this.selectSvgInfo.type == "WireBreakOffSvg" ||
        this.selectSvgInfo.type == "CircuitBreakerSvg"
      ) {
        this.selectSvgInfo.status = val;
        this.modifystate();
      }
    },
    setTableAttrDisplay(val) {
      if (val == false) {
        this.svgLists.splice(
          this.svgLists.findIndex((item) => item.id === this.selectSvgInfo.id),
          1
        );
      } else if (val == true) {
        this.svgLists.push(this.selectSvgInfo);
      }
    },
    setTableAttrTree(val) {
      this.selectSvgInfo = val;
    },
    //设置表格属性
    setTableAttr(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);
      }
      this.svgLists[tableIndex].tableData = tableData;
    },
    scaleValueChange(newValue) {
      this.scaleValue = newValue;
      document.getElementById("canvas").style.width = "100%";
      document.getElementById("canvas").style.height = "100%";
    },
    // svg添加背景图片
    backgroundSRC(src) {
      document.getElementById(
        "svg_container"
      ).style.backgroundImage = `url(${src})`;
      document.getElementById(
        "svg_container"
      ).style.backgroundSize = `100% 100%`;
      // .focal{
      //   background: url("../assets/bg.png");
      // }
    },
    sendData(data) {
      this.svgLists = data;
    },
  },
  mounted() {
    let _this = this;

    _this.$refs.RightToolBar.selectSvg = {};

    this.$nextTick(() => {
      _this.queryData();
      this.query();
      let canvasdiv = _this.$refs.canvas;
      canvasdiv.addEventListener(
        "dragover",
        function (e) {
          e.preventDefault();
        },
        false
      );
      canvasdiv.addEventListener(
        "drop",
        function (e) {
          e.preventDefault();
          if (
            _this.$store.state.webtop.CurrentlySelectedToolBar.Type == "" ||
            _this.$store.state.webtop.CurrentlySelectedToolBar.CreateType !=
              "draggable"
          ) {
            return;
          }
          jquery(".removeID").remove();
          jquery(`#${_this.svgLists.id}`).removeClass("drag-svg");
          let eChartsOption =
            _this.$store.state.webtop.CurrentlySelectedToolBar.EChartsOption;
          // console.log(eChartsOption);

          //根据类型和鼠标位置创建组件
          let svgItem = {
            id: _this.$UCore.GenUUid(),
            title: _this.$store.state.webtop.CurrentlySelectedToolBar.Title,
            type: _this.$store.state.webtop.CurrentlySelectedToolBar.Type,
            display: _this.$store.state.webtop.CurrentlySelectedToolBar.Display,
            typeName:
              _this.$store.state.webtop.CurrentlySelectedToolBar.TypeName,
            svgColor: _this.$store.state.webtop.CurrentlySelectedToolBar.Color,
            svgPositionX: e.offsetX,
            svgPositionY: e.offsetY,
            echartsOption: eChartsOption ? JSON.parse(eChartsOption) : "",
            list: _this.$store.state.webtop.CurrentlySelectedToolBar.List
              ? JSON.parse(
                  _this.$store.state.webtop.CurrentlySelectedToolBar.List
                )
              : "",
            tableHeader: _this.$store.state.webtop.CurrentlySelectedToolBar
              .TableHeader
              ? _this.$store.state.webtop.CurrentlySelectedToolBar.TableHeader
              : "",
            size: 1,
            angle: 0,
            //translate:`translate(${this.mousePosition.positionX},${this.mousePosition.positionY})`
          };

          _this.svgLists.push(svgItem);
          _this.selectSvgInfo = svgItem;
          if (
            _this.selectSvgInfo.type == "WireBreakOnSvg" ||
            _this.selectSvgInfo.type == "WireBreakOffSvg" ||
            _this.selectSvgInfo.type == "CircuitBreakerSvg"
          ) {
            if (_this.selectSvgInfo.svgColor == "#00FF00") {
              _this.selectSvgInfo.status = 0;
            } else if (_this.selectSvgInfo.svgColor == "#FF0000") {
              _this.selectSvgInfo.status = 1;
            }
          }
          _this.$refs.RightToolBar.selectSvg = _this.selectSvgInfo;

          setTimeout(() => {
            // jquery(`#${svgItem.id}`).addClass("drag-svg");
            // window.Subjx(".drag-svg").drag({
            //   container: "#svg-container",
            //   snap: {
            //     x: 1,
            //     y: 1,
            //     angle: 1,
            //   },
            // });
          }, 50);
        },
        false
      );
    });
  },
  created() {
    this.parameters = this.params; //this.$route.params;
    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;
      }
      //deleted
      else if (e1 && e1.keyCode == 46) {
        jquery(".removeID").remove();
        e.preventDefault();
        //根据当前id找到当前元素的index
        let selectSvgIndex = _this.svgLists.indexOf(
          _this.svgLists.filter((f) => f.id == selectSvgInfo.id)[0]
        );
        _this.svgLists.splice(selectSvgIndex, 1);
      }
    };

    //请求接口获取组件
    // this.$axios
    //   .get("/webtopo-svgeditor/InterfaceReturn.json")
    //   .then(function (response) {
    //     console.log(JSON.stringify(response.data), "1234567890");
    //     // _this.svgInfoData = response.data;
    //     // localStorage.setItem("svgInfoData", JSON.stringify(response.data));
    //     // console.log(response.data);
    //     // let json = JSON.stringify(_this.svgInfoData);
    //     // let form = {
    //     //   jsonFile: JSON.stringify(_this.svgInfoData),
    //     // };
    //     let form = new FormData();
    //     const blob = new Blob([JSON.stringify(response.data)], {type: 'application/json'});
    //     form.append("multipartFile", blob);
    //     // console.log(form);

    //     add(form).then((res) => {});
    //   })
    //   .catch(function (error) {
    //     // console.log(error);
    //   });
  },
  watch: {
    svgLists: {
      deep: true,
      handler(val) {
        this.$refs.LeftToolBar.list.path = JSON.stringify(val);
      },
    },
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="less">
::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}
::-webkit-scrollbar-track {
  background-color: #f2f2f2;
  border-radius: 10px;
  box-shadow: 1px 1px 5px #333 inset;
}
::-webkit-scrollbar-thumb {
  background-color: #444;
  border-radius: 10px;
}
#components-layout .ant-layout-header {
  position: absolute;
  top: 0;
  right: 0;
  left: 0;
  z-index: 2;
  height: 50px;
  line-height: 50px;
  color: rgb(0, 0, 0);
  background: #fff;
  box-shadow: 1px 1px 5px #ddd;
}
.pageMain {
  position: absolute;
  top: 50px;
  right: 0;
  bottom: 0;
  left: 0;
  overflow: auto;
}
.centerContain {
  top: 0;
  right: 300px;
  bottom: 0;
  // position: absolute;
  left: 260px;
  z-index: 1;
  z-index: 111;
  overflow: auto !important;
  overflow-x: auto !important;
  transition: all 0.3s;

  &.fixed {
    position: fixed;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
  }
  .canvansDiv {
    width: 1920px;
    height: 1080px;
    -moz-user-select: none;
    -webkit-user-select: none;
    -ms-user-select: none;
    -khtml-user-select: none;
    user-select: none;
    transform-origin: left top;
  }
  .canvas-content {
    width: 1920px;
    height: 1080px;
    -moz-user-select: none;
    -webkit-user-select: none;
    -ms-user-select: none;
    -khtml-user-select: none;
    user-select: none;
  }
  .btns-content {
    position: fixed;
    right: 320px;
    bottom: 10px;
    left: 280px;
    button {
      margin-left: 10px;
    }
  }
}

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

#guide-y {
  position: absolute;
  top: 0;
  left: 0;
  display: none;
  height: 100%;
}
.ant-slider {
  margin-bottom: 16px;
}
.topo-layer {
  position: absolute;
  width: 100%;
  height: 100%;
  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-position: 0 0, 10px 10px;
  background-size: 20px 20px;
  transform-origin: left top;
}
.resize-left-top {
  position: absolute;
  top: -5px;
  left: -5px;
  width: 10px;
  height: 10px;
  cursor: nwse-resize;
  background-color: white;
  border: 1px solid #0cf;
}

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

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

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

.topo-layer-view-selected {
  outline: 1px solid #0cf;
}
.zoonStyle {
  position: fixed;
  bottom: 4px;
  z-index: 99;
  display: flex;
  align-items: center;
  color: #338484;
}
</style>
