<template>
  <div :id="`drawFloor${id}`" class="drawFloor" v-loading="canvasLoading">
    <canvas :id="`floorCanvas${id}`" :width="cadWidth" :height="cadHeight" ref="canvas" tabindex="0"></canvas>
    <div class="operate" v-if="showTools">
      <canvasFun @fit="fit" @savePng="savePng" @saveSvg="saveSvg" @divide="divide" @clearDivide="clearDivide" @scale="scale"
        @changeAbsorb="changeAbsorb" :config="config" ref="canvasFun" @saveJson="saveJson"></canvasFun>
    </div>
  </div>
</template>

<script>
import { DivideFloorScene, FloorView, Opt } from "@saga-web/cad-engine/lib"
import { SColor, SPoint } from "@saga-web/draw/lib";
import canvasFun from "@/components/business_space/newGraphy/canvasFun"
import { floorQueryOutline, floorQueryAndSign } from "@/api/scan/request";
import { EditLineItem } from "@saga-web/cad-engine"
import { mapGetters } from "vuex";
export default {
  components: {
    canvasFun
  },
  data() {
    return {
      drawMainScene: null,
      view: null,
      dataKey: '',
      cadWidth: 800,
      cadHeight: 600,
      canvasLoading: false,
      FloorID: '',
      Outline: [],
      floorData: {},
      config: {
        isEdit: false,
        divide: true
      },
      shadeList: [],
      type: 1, // 当前图展示类型
      scaleItem: null, // 比例尺item
      urlModelId: '', // url中传入的modelid
    };
  },
  props: {
    isEdit: {
      default: false
    },
    showTools: {
      default: false
    },
    id: {
      default: 0
    },
    dialog: {
      default: false
    }
  },
  computed: {
    ...mapGetters("layout", ["projectId", "projects"]),
    projectName() {
      let projectObj = this.projects.find(item => {
        return item.id == this.projectId
      })
      return projectObj ? projectObj.name ? projectObj.name : projectObj.id : this.projectId
    }
  },
  created() {
    this.FloorID = this.$route.query.FloorID;
    this.urlModelId = this.$route.query.modelId
    Opt.sceneMarkColor = new SColor('#00000080');
    if (!this.dialog) {
      this.init();
    }
  },
  mounted() {
    this.cadWidth = document.getElementById(`drawFloor${this.id}`).offsetWidth;
    this.cadHeight = document.getElementById(`drawFloor${this.id}`).offsetHeight;
  },
  methods: {
    //
    init() {
      this.getFloorData();
    },
    // 初始化canvas
    initGraphy(Id, type) {
      // type=1 => id:模型id
      // type=2 => id:floormap
      // type=3 => id:图片的key
      let that = this;
      that.type = type;
      that.clearGraphy()
      that.drawMainScene = new DivideFloorScene();
      that.canvasLoading = true;
      if (type == 1) {
        that.drawMainScene.getFloorData('/modelapi/base-graph/query', { ModelId: Id }).then(res => {
          that.getGraphtSuc(res)
        })
      } else if (type == 2) {
        that.drawMainScene.loadUrl(`/image-service/common/file_get?systemId=revit&key=${Id}`).then(res => {
          that.getGraphtSuc(res)
        })
      } else if (type == 3) {
        that.drawMainScene.loadImg(`/image-service/common/image_get?systemId=dataPlatform&key=${Id}`, res => {
          that.getGraphtSuc(res)
        })
      }
    },
    // 获取底图成功
    getGraphtSuc(res) {
      this.canvasLoading = false;
      if (res == 'error') {
        this.FloorMap = '';
        this.$message.warning('数据解析异常');
        return;
      }
      if (res.Result == 'failure') {
        this.showTools = false;
        this.$message.warning(res.Message);
        return;
      }
      this.view.scene = this.drawMainScene;
      this.view.fitSceneToView();
      this.drawMainScene.isSpaceSelectable = false;

      if (this.type == 3) {
        this.addScaleItem(this.floorData.Properties)
        this.$emit('getGraphSuc');
        if (this.floorData.Properties) {
          const x = this.floorData.Properties.X;
          const y = this.floorData.Properties.Y;
          if (x != 0 || y != 0) {
            this.drawMainScene.imgList[0].moveTo(x, y);
          }
        }
      }

      if (this.$refs.canvasFun) {
        this.view.minScale = this.view.scale;
        this.$refs.canvasFun.everyScale = this.view.scale;
      }
      if (this.floorData.Outline && this.floorData.Outline.length) {
        let newArr = this.floorData.Outline.map(t => {
          return new SPoint(t.X, t.Y);
        })
        this.drawMainScene.addSceneMark(newArr)
      }
    },
    // 获取楼层数据
    getFloorData() {
      let pa = {
        Filters: `FloorID='${this.FloorID}'`
      }
      const temp = this.urlModelId.split('.')[1]
      if (temp && (temp.toLowerCase() == 'png' || temp.toLowerCase() == 'jpg')) { //底图为图片且已经绑定过图片
        floorQueryAndSign(pa, res => {
          this.floorData = res.Content[0];
          if (this.floorData.StructureInfo && this.floorData.StructureInfo.FloorMap) {
            let floorMap = this.floorData.StructureInfo.FloorMap
            this.initGraphy(floorMap, 3)
          }
        })
      } else {
        floorQueryOutline(pa, res => {
          this.floorData = res.Content[0];
          if (this.floorData.StructureInfo && this.floorData.StructureInfo.FloorMap) {
            this.getOtherFloorOutLine();
            let floorMap = this.floorData.StructureInfo.FloorMap
            this.initGraphy(floorMap, 2)
          }
        })
      }
    },
    // 获取绑定该模型id的其他楼层轮廓线
    getOtherFloorOutLine() {
      let modelid = this.floorData.ModelId;
      let pa = {
        Filters: `ModelId='${modelid}'`
      }
      this.shadeList = [];
      floorQueryOutline(pa, res => {
        res.Content.map(t => {
          if (t.FloorID != this.FloorID && t.Outline && t.Outline.length) {
            let line = t.Outline.map(item => {
              return new SPoint(item.X, item.Y);
            })
            this.shadeList.push(line);
          }
        });
        this.drawMainScene.addAllShade(this.shadeList);
        this.$emit('changeSign', res.Content.length > 1);
      });
    },
    // 添加比例尺item 当楼层图为图片类型时 回显比例尺
    addScaleItem(data) {
      this.scaleItem = new EditLineItem(null)
      this.scaleItem.strokeColor = SColor.Red;
      this.drawMainScene.addItem(this.scaleItem)
      if (data && data.Line && data.Line.length == 2) {
        this.scaleItem.line = data.Line;
        this.scaleItem.text = data.Text;
        // todo
        this.scaleItem.pointChange();
      }
    },
    // 清空平面图
    clearGraphy() {
      if (this.view) {
        this.view.scene = null;
        return
      }
      let id = `floorCanvas${this.id}`;
      this.view = new FloorView(id)
    },
    // canvas 获取焦点
    focus() {
      document.getElementById(`floorCanvas${this.id}`).focus()
    },
    // 工具栏操作
    // 适配底图到窗口
    fit() {
      this.view.fitSceneToView()
    },
    // 保存为png
    savePng() {
      this.view.saveImage(`${this.projectName}-${this.buildFloorName}.png`, 'png');
    },
    // 保存为svg
    saveSvg() {
      this.view.saveSceneSvg(`${this.projectName}-${this.buildFloorName}.svg`, 6400, 4800);
    },
    // 保存json
    saveJson() {
      this.view.saveFloorJson(`${this.projectName}-${this.buildFloorName}.json`)
    },
    // 切割划分
    divide() {
      this.drawMainScene.isMarking = true;
    },
    // 清除切割划分
    clearDivide() {
      this.drawMainScene.clearSceneMark()
    },
    // 吸附
    changeAbsorb(isAbsorbing) {
      this.drawMainScene.isAbsorbing = isAbsorbing;
    },
    // 缩放
    scale(val) {
      if (!this.view) {
        return;
      }
      let scale = this.view.scale;
      this.view.scaleByPoint(val / scale, this.cadWidth / 2, this.cadHeight / 2)
    },
  },
  watch: {
    "view.scale": {
      handler(n) {
        if (this.$refs.canvasFun) {
          let s = n * 10 / this.view.minScale
          this.$refs.canvasFun.sliderVal = s > 1000 ? 1000 : s;
        }
      }
    },
    "isEdit": {
      handler(n) {
        this.config.isEdit = n;
      }
    }
  }
};
</script>
<style scoped lang="less">
.drawFloor {
  width: 100%;
  height: 100%;
  position: relative;
  .operate {
    position: absolute;
    left: 50%;
    bottom: 20px;
    transform: translateX(-50%);
    z-index: 99;
  }
}
</style>
