<template>
  <div ref="graphyMain" class="canvasGraphy">
    <div style="width:100%;height:100%;" v-show="type==3" ref="canvasContainer" v-loading="canvasLoading">
      <canvas id="canvas" :width="canvasW" :height="canvasH" ref="canvas"></canvas>
    </div>
    <div v-if="type!=3" class="center" style="height: 400px;padding-top: 315px; box-sizing:border-box;">
      <i class="icon-wushuju iconfont"></i>
      <p>{{type == 1 ? '请选择楼层' : '当前楼层尚无平面图，请去空间管理根据模型生成'}}</p>
    </div>
    <!-- 底部操作按钮 -->
    <el-row v-show="type == 3" class="canvas-actions-box">
      <canvasFun @move="moveCanvas" @fit="fit" @savePng="savePng" @saveSvg="saveSvg" @divide="divide" @clearDivide="clearDivide" @undo="undo"
        @redo="redo" @scale="scale" :isEdit="isEdit" :config="config" ref="canvasFun"></canvasFun>
    </el-row>
    <div v-show="menuShow" id="menu" ref="menu">
      <p @click="getDatails">编辑该标签</p>
      <p @click="clearXY">清除该点位的坐标</p>
      <p @click="noLocate">修改为无法定位到楼层的点位</p>
    </div>
  </div>
</template>

<script>
import canvasFun from "@/components/business_space/newGraphy/canvasFun"
//引擎的引用
import { mapGetters, mapActions } from "vuex";
import {
  updateLocationPoint, //更新点位标签
} from "@/api/scan/request";
import { SGraphyView } from "@saga-web/graphy/lib";
import { LocationPointScene, MarkerItem, SpaceItem } from "@saga-web/cad-engine/lib";
import { SPoint } from "@saga-web/draw/lib";

export default {
  components: {
    canvasFun
  },
  data() {
    return {
      isEdit: false, //是否为编辑态
      view: null, //视图
      scene: null, //场景
      menuShow: false, //右键菜单的显示
      canvasH: 600,
      canvasW: 800,
      type: 1, //1  没有选择楼层， 2没有平面图， 3有平面图
      list: [],
      buildMess: {},
      imageUrl: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABwAAAAlCAYAAABReInxAAAEaElEQVRYhd2XTWhdRRTHf+clgb7XRbCK6MZSiS5SrVRsq6tiX1AI2LV0UejSneJGqaFFiTtxJ+7UgFCLgqJQCC+oFT/eixKhASGBSuHFiIVKb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5lDFOI3FXkKkwYKw9U4ru5q4Xe0gEqMQlSvIGzAqy4C9Tqj/bb7nI3UuiShPdpvEF2PE0rGbI1n0Q3Kv+PWDcYlzzjVrVFec+Ra+ovz5K/o5aIYVaGhQxTzusq7aSrInI7Td/XV0uV1stcT+0geC6hdCY6xijRoG6/Ydm+NbTT5guLtPXu2PT17umIe6YPAX+suNKie6lQbEUaLQ6Q8DBeN3SxvZHwzXvnZo1xjx3gemn3P5HgDE7K4N405OdxUsFTXZX2foYIlsdRGRw8GawH2hYl5p/Awwr890oNw3WuNHczszVLmm4Fbr+YwH+Bv+IBpdT6d7pAAAAAElFTkSuQmCC",
      setFlag: false, //插旗标志
      point: {}, //右侧列表传来的位置标签
      canvasLoading: false, //loading
      markItem: null, // 当前选中的标签item
      config: {
        isEdit: false
      },
    };
  },
  computed: {
    ...mapGetters('layout', ['projectId'])
  },
  created() { },
  mounted() {
    this.resize()
  },
  methods: {
    resize() {
      this.canvasW =
        document.getElementsByClassName("graphy-main")[0].offsetWidth - 2;
      this.canvasH =
        document.getElementsByTagName("body")[0].offsetHeight - 167;
    },
    //获取数据
    getData(data) {
      if (!data.map) {
        this.type = 2;
      } else {
        this.buildMess = data;
        this.type = 3;
      }
    },
    //下载json文件
    getJson(jsonId) {
      let that = this;
      that.clearGraphy()
      that.scene = new LocationPointScene();
      that.canvasLoading = true;
      that.scene.loadUrl(`/image-service/common/file_get?systemId=revit&key=${jsonId}`).then(res => {
        that.canvasLoading = false;
        if (res == 'error') {
          this.floorMap = '';
          this.$message.warning('数据解析异常');
          return;
        }
        that.view.scene = that.scene;
        that.scene.isSpaceSelectable = false;
        //添加标签显示
        that.scene.addMarkerList(that.list);
        //注册标签事件
        that.scene.markerClick(that, that.markClick);
        that.scene.spaceClick(that, that.spaceClick);
        that.view.fitSceneToView();
        that.view.minScale = that.view.scale;
        // that.view.minScale = 0.000001;
        if (that.$refs.canvasFun) {
          that.$refs.canvasFun.everyScale = that.view.scale;
        }
        this.disableRightButton();
      })
    },
    //画点位坐标
    doPoint(list) {
      this.setFlag = false;
      if (this.view) {
        this.view.canvasView.style.cursor = `default`;
      }
      this.list = list.map(t => {
        if (t.X == 0 && t.Y == 0) {
          return undefined;
        } else {
          return {
            Id: t.Id,
            X: t.X,
            Y: t.Y * -1,
            Name: t.Name
          };
        }
      }).filter(item => item);
      this.getJson(this.buildMess.map)
    },
    //右键菜单的编辑该标签
    getDatails() {
      this.menuShow = false;
      this.$emit("getDetails", { Id: this.point.Id });
    },
    //右键的清除该点位的坐标
    clearXY() {
      this.menuShow = false
      this.point.X = 0
      this.point.Y = 0
      this.updatePoint('clearXY')
    },
    //右键的修改为无法定位到楼层的点位
    noLocate() {
      this.menuShow = false
      delete this.point.FloorId
      this.updatePoint('noLocate')
    },
    //创建实例
    createCanvas() {
      if (this.view.scene) {
        this.view.scene.root.children = [];
        this.view = null;
      }
      this.view = new SGraphyView("canvas");
    },
    // 定位
    locationGraphy(point) {
      let centerX = (this.view.width / 2) - point.X * this.view.scale;
      let centerY = (this.view.height / 2) - point.Y * this.view.scale;
      this.view.origin = new SPoint(centerX, centerY)
    },
    //点击按钮
    addPoint(point) {
      
      if (this.point.Id != point.Id) {
        console.log(point)
        this.point = point;
        this.view.canvasView.style.cursor = `url(${this.imageUrl}) 14 33,auto`;
        this.setFlag = true
      }
      else {//再次点击取消插旗
        this.cancelSetFlag();
      }
    },
    //取消插旗状态
    cancelSetFlag() {
      this.point = {};
      this.view.canvasView.style.cursor = `Default`;
      this.setFlag = false;
    },
    //右键菜单
    showRightClick(e) {
      this.menuShow = true
      let el = this.$refs.graphyMain;
      this.$refs.menu.style.left = e.clientX - 245 + "px";
      this.$refs.menu.style.top = e.clientY - 150 + "px";
    },
    //插旗 item - 点击的空间item
    spaceClick(item, event) {
      console.log("click sapce")
      this.menuShow = false;
      if (this.setFlag) {
        this.scene.addMarker({
          Id: this.point.Id,
          Name: this.point.Name,
          X: event[0].x,
          Y: event[0].y
        })
        this.scene.markerClick(this, this.markClick);
        this.point.X = event[0].x
        this.point.Y = -event[0].y
        this.updatePoint('setFlag')
        this.cancelSetFlag()
      }
      this.setFlag = false
    },
    //标签点击事件(包含左键,右键)
    markClick(item, event) {
      console.log("click mark")
      if (event[0].type == 'contextmenu') {
        this.markItem = item;
        this.point = item.data;
        this.showRightClick(event[0])
      } else {
        this.markItem = null;
        this.menuShow = false;
      }
    },
    //更新位置标签
    updatePoint(type) {
      let pa = {
        Content: [this.point]
      }
      if (type == 'noLocate') {
        pa.Projection = ['FloorId']
      }
      //type == clearXY setFlag noLocate
      updateLocationPoint(pa, res => {
        this.$message.success('修改成功');
        if (type == 'clearXY' || type == 'noLocate') {
          this.scene.removeItem(this.markItem);
          this.$emit('resetPoint');
        }
      })
    },
    // 清除canvas
    clearGraphy() {
      if (this.view) {
        this.view.scene = null;
        return
      }
      this.view = new SGraphyView('canvas')
    },
    // 清除默认左右键事件
    disableRightButton() {
      this.$refs.canvas.addEventListener('contextmenu', (e) => {
        e.preventDefault();
      })
      this.$refs.canvas.addEventListener('click', (e) => {
        e.preventDefault();
        this.menuShow = false
      })
    },
    // 工具栏操作
    // 移动底图
    moveCanvas(move) {
      // todo
      let canvas = document.getElementById(`floorCanvas`);
      if (move) {
        canvas.style.cursor = 'move';
      } else {
        canvas.style.cursor = 'default';
      }
    },
    // 适配底图到窗口
    fit() {
      this.view.fitSceneToView()
    },
    // 保存为png
    savePng() {
      this.view.saveImage(`${this.buildMess.code}.png`, 'png');
    },
    // 保存为svg
    saveSvg() {
      this.view.saveSceneSvg(`${this.buildMess.code}.svg`, 6400, 4800);
    },
    // 切割划分
    divide() {
      this.drawMainScene.isMarking = true;
    },
    // 清除切割划分
    clearDivide() {
      this.drawMainScene.clearSceneMark()
    },
    // 撤销
    undo() {

    },
    // 反撤销
    redo() { },
    // 缩放
    scale(val) {
      if (!this.view) {
        return;
      }
      let scale = this.view.scale;
      this.view.scaleByPoint(val / scale, this.canvasW / 2, this.canvasH / 2)
    },
  },
  watch: {
    projectId() {
      this.type = 1
      this.resize()
    },
    "view.scale": {
      handler(n, o) {
        if (this.$refs.canvasFun) {
          let s = n * 10 / this.view.minScale
          this.$refs.canvasFun.sliderVal = s > 1000 ? 1000 : s;
        }
      }
    }
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="less" scoped>
.canvasGraphy {
  position: relative;
  height: 100%;
  .saga-message {
    height: 400px;
    line-height: 400px;
    color: #ccc;
    font-size: 24px;
    text-align: center;
  }
  #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;
  }
  .canvas-actions-box {
    position: absolute;
    bottom: 20px;
    left: 50%;
    transform: translateX(-50%);
    z-index: 999;
  }
}
</style>