<template>
  <!-- 拓扑图demo -->
  <el-container>
    <el-aside width="200px" class="el-scrollbar">
      <div title="查询">
        <el-button size="mini" @click="queryGraphy" icon="el-icon-search">查询</el-button>
      </div>
      <div title="保存">
        <el-button size="mini" @click="saveGraphy" icon="el-icon-notebook-2">保存</el-button>
      </div>
      <div title="划线">
        <el-button size="mini" @click="drawline" icon="el-icon-edit">连线</el-button>
      </div>
      <!-- <div title="适配底图">
        <el-button size="mini" @click="fitClick" icon="el-icon-crop">适配底图</el-button>
      </div> -->
      <div>
        <div v-for="(t,i) in equipList" :key="t.ID" @click="additem(i)" class="equip" title="添加item">
          <img :src="t.ImgSource" />
        </div>
      </div>
      <div>
        <p>使用说明:</p>
        <p>双击连线添加折点</p>
        <p>alt+左键删除折点</p>
      </div>
    </el-aside>
    <el-main>
      <div ref="graphy" v-loading="loading" element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.8)" style="height: 100%">
        <canvas id="bg" :width="canvasWidth" :height="canvasHeight" ref="canvas" tabindex="0"></canvas>
        <div v-show="menuShow" id="menu" ref="menu">
          <p @click="editName">编辑名称</p>
          <p @click="deleteItem">删除</p>
        </div>
      </div>
    </el-main>
    <el-dialog title="编辑名称" :visible.sync="dialogVisible" width="300px">
      <span>请输入名称:</span>
      <el-input v-model="itemName" placeholder="请输入内容"></el-input>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="saveName">确 定</el-button>
      </span>
    </el-dialog>
  </el-container>
</template>
<script>

import { TopoScene, TopoView, RelationItem, EquipItem } from "@saga-web/topology/lib";
import { topoCreate, topoQuery } from "@/api/topo";
export default {
  data() {
    const that = this;
    return {
      view: null,
      scene: null,
      loading: false,
      canvasWidth: 800,
      canvasHeight: 800,
      menuShow: false,
      dialogVisible: false,
      itemName: '',
      img1: 'data:image/jpeg;base64,[encoded data, 8308 characters]',
      img2: 'data:image/jpeg;base64,[encoded data, 101284 characters]',
      img3: 'data:image/jpeg;base64,[encoded data, 23580 characters]',
      equipList: [
        {
          Id: this.uuid(),
          Size: {
            Width: 122,
            Height: 85
          },
          Pos: {},
          img: require('./1.jpg'),
          ImgSource: this.img1,
          Name: '测试1',
          AnchorList: [{ Pos: { X: -61, Y: 0 }, Id: this.uuid() }, { Pos: { X: 61, Y: 0 }, Id: this.uuid() }]
        },
        {
          Id: this.uuid(),
          Size: {
            Width: 145,
            Height: 89
          },
          Pos: {},
          img: require('./2.jpg'),
          ImgSource: this.img2,
          Name: '测试2',
          AnchorList: [{ Pos: { X: 0, Y: -44 }, Id: this.uuid() }, { Pos: { X: -72, Y: 0 }, Id: this.uuid() }, { Pos: { X: 72, Y: 0 }, Id: this.uuid() }]
        },
        {
          Id: this.uuid(),
          Size: {
            Width: 106,
            Height: 60
          },
          Pos: {},
          Name: '测试3',
          img: require('./3.jpg'),
          ImgSource: this.img3,
          AnchorList: [{ Pos: { X: 0, Y: 30 }, Id: this.uuid() }, { Pos: { X: -53, Y: 0 }, Id: this.uuid() }, { Pos: { X: 53, Y: 0 }, Id: this.uuid() }]
        }
      ],
      timer: '',
    }
  },
  mounted() {
    this.canvasWidth = this.$refs.graphy.offsetWidth;
    this.canvasHeight = this.$refs.graphy.offsetHeight;
    this.createGraphy();
    document.onkeydown = E => {
      console.log(E)
    }
    window.onresize = () => {
      this.canvasWidth = this.$refs.graphy.offsetWidth;
      this.canvasHeight = this.$refs.graphy.offsetHeight;
    }
    this.disableRightButton()
  },
  beforeCreate() {
    // 读取文件
    FileReader.prototype.reading = function ({ encode } = pms) {
      let bytes = new Uint8Array(this.result);    //无符号整型数组
      let text = new TextDecoder(encode || 'UTF-8').decode(bytes);
      return text;
    };
    /* 重写readAsBinaryString函数 */
    FileReader.prototype.readAsBinaryString = function (f) {
      if (!this.onload)       //如果this未重写onload函数，则创建一个公共处理方式
        this.onload = e => {  //在this.onload函数中，完成公共处理
          let rs = this.reading();
          console.log(rs);
        };
      this.readAsArrayBuffer(f);  //内部会回调this.onload方法
    };
  },
  created() {
    this.equipList.forEach((t, i) => {
      t.ImgSource = this[`img${i + 1}`]
    })
  },
  methods: {
    createGraphy() {
      this.clearGraphy();
      this.scene = new TopoScene()
      this.view.scene = this.scene;
      this.scene.callback = this.equipClick
    },
    // 清除canvas
    clearGraphy() {
      if (this.view) {
        this.view.scene = null;
        return
      }
      this.view = new TopoView('bg');
      this.setTimer()
    },
    fitClick() {
      this.view.fitSceneToView();
    },
    additem(i) {
      let equipdata = this.equipList[i]
      this.scene.createItem(equipdata);
    },
    drawline() {
      if (this.scene.lineType) {
        this.scene.lineType = 0;
        console.log('change')
        return
      }
      this.scene.lineType = 1;
    },
    // 清除默认左右键事件
    disableRightButton() {
      this.$refs.canvas.addEventListener('contextmenu', (e) => {
        e.preventDefault();
      })
      this.$refs.canvas.addEventListener('click', (e) => {
        e.preventDefault();
        this.menuShow = false
      })
    },
    equipClick(item, e) {
      this.curItem = item;
      this.menuShow = true
      let el = this.$refs.menu;
      el.style.left = e[0].clientX - 445 + "px";
      el.style.top = e[0].clientY - 90 + "px";
    },
    //
    editName() {
      this.menuShow = false
      this.dialogVisible = true
      this.itemName = this.curItem.name;
    },
    //
    deleteItem() {
      this.menuShow = false
      if (this.curItem) {
        this.scene.removeItem(this.curItem)
      }
    },
    //
    saveName() {
      this.curItem.name = this.itemName
      this.curItem = null;
      this.dialogVisible = false
    },
    //
    cancel() {
      this.dialogVisible = false
      this.itemName = '';
    },
    setTimer() {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      this.timer = setTimeout(() => {
        this.viewUpdate()
        this.setTimer();
      }, 500)
    },
    viewUpdate() {
      if (this.view) {
        this.view.update()
      }
    },
    uuid(len, radix) {
      var chars = '0123456789abcdef'.split('');
      var uuid = [],
        i;
      radix = radix || chars.length;
      if (len) {
        for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
      } else {
        var r;
        uuid[8] = uuid[13] = uuid[18] = uuid[23] = '';
        uuid[14] = '4';
        for (i = 0; i < 32; i++) {
          if (!uuid[i]) {
            r = 0 | Math.random() * 16;
            uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
          }
        }
      }
      return uuid.join('');
    },
    // 保存平面图
    saveGraphy() {
      // Eq1101080004f146d36579ba423f98ce101941b6df33//Eq1101080004c20dd92deaa44bc5ac7cd40c0cb15549//Eq110108000479471cef9d7446f38481d06c0015cb96
      let graphyID = this.uuid()
      let pa = {
        Content: [{
          Type: 'eq2sp_for',
          Name: '测试图名称',
          Id: graphyID,
          NodeList: [],
        }]
      }
      pa.Content[0].NodeList = [];
      pa.Content[0].RelationList = [];
      if (this.scene && this.scene.root.children.length) {
        let tempRelatList = [], tempAnchorList = []
        this.scene.root.children.forEach(item => {
          if (item instanceof RelationItem) {
            tempRelatList = item.pointList.map(t => {
              return { X: t.x, Y: t.y }
            })
            pa.Content[0].RelationList.push({
              Id: this.uuid(),
              PointList: tempRelatList,
              Anchor1Id: item.Anchor1.data.Id,
              Anchor2Id: item.Anchor2.data.Id,
              Node1Id: item.Anchor1.parent.data.Id,
              Node2Id: item.Anchor2.parent.data.Id,
              GraphId: graphyID
            })
          } else if (item instanceof EquipItem) {
            tempAnchorList = item.data.AnchorList.map(t => {
              return {
                GraphId: graphyID,
                Id: t.Id,
                NodeId: item.data.Id,
                Pos: t.Pos
              }
            })
            let point = item.mapToScene(item.data.Pos.X, item.data.Pos.Y)
            pa.Content[0].NodeList.push({
              AttachId: 'Eq1101080004f146d36579ba423f98ce101941b6df33',
              GraphId: graphyID,
              AnchorList: tempAnchorList,
              Id: item.data.Id,
              Pos: {
                X: point.x,
                Y: point.y,
              },
              Size: item.data.Size,
              GraphId: graphyID,
              Type: 'eq'
            })
          }
        })
      }
      topoCreate(pa, res => {
        console.log(res)
      })
    },
    //查询
    queryGraphy() {
      console.log(this.scene)
      topoQuery({ type: 'eq2sp_for' }, res => {
        console.log(res.Content[0])
        // this.scene.loadData({
        // equipList: res.Content[0].NodeList,
        // relationList: res.Content[0].RelationList,
        // })
        // this.view.fitSceneToView()
      })
    }
  },
}
</script>
<style lang="less" scoped>
.el-container {
  background: #fff;

  /deep/ textarea.el-textarea__inner {
    width: 100%;
    height: 100% !important;
  }

  .el-aside {
    padding: 10px;
    border: 1px solid #e4e4e4;
    .equip {
      width: 150px;
      height: 75px;
      margin-bottom: 10px;
      text-align: right;
      img {
        width: 100%;
        height: 100%;
      }
    }
  }

  .el-aside > div {
    margin: 10px auto;
    text-align: right;
  }

  .el-main {
    position: relative;
    padding: 10px !important;
    border: 1px solid #e4e4e4;
    border-left: none;
    #menu {
      width: 200px;
      z-index: 88;
      overflow: hidden;
      box-shadow: 0 1px 1px #888, 1px 0 1px #ccc;
      position: absolute;
      background-color: #fff;
    }
    #menu p {
      width: 100%;
      padding-left: 5px;
      overflow: hidden;
      height: 35px;
      line-height: 35px;
      font-size: 14px;
      margin: 0;
      text-align: left;
      cursor: pointer;
    }
    #menu p:hover {
      background-color: aqua;
    }
  }

  input[type="file"] {
    display: none;
  }
}
</style>