<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-show="showTools">
      <canvasFun @fit="fit" @savePng="savePng" @saveSvg="saveSvg" @scale="scale" @saveJson="saveJson" :config="config" ref="canvasFun"></canvasFun>
    </div>
  </div>
</template>

<script>
import { DivideFloorScene, FloorView } from "@saga-web/cad-engine/lib"
import { SColor, SPoint } from "@saga-web/draw/lib";
import canvasFun from "@/components/business_space/newGraphy/canvasFun"
import { queryEquip } from "@/api/object/equip";
import { mapGetters } from "vuex";
export default {
  components: {
    canvasFun
  },
  data() {
    return {
      drawMainScene: null,
      view: null,
      dataKey: '',
      cadWidth: 800,
      cadHeight: 600,
      canvasLoading: false,
      modelId: '',
      FloorID: '',
      Outline: [],
      deviceList: [],
      buttonContent: "",
      showTools: false,
      config: {
        isEdit: false
      }
    };
  },
  props: {
    isEdit: {
      default: false
    },
    id: {
      default: 0
    },
    dialog: {
      default: false
    },
    isLight:{
      type: Boolean,
      default: false
    },
    CurrentModelId: String,
    modelName: String, //模型文件夹和模型文件名称
  },
  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() { },
  mounted() {
    this.cadWidth = document.getElementById(`drawFloor${this.id}`).offsetWidth;
    this.cadHeight = document.getElementById(`drawFloor${this.id}`).offsetHeight;
  },
  methods: {
    initGraphy(ModelId) {
      this.modelId = ModelId;
      this.clearGraphy()
      this.drawMainScene = new DivideFloorScene();
      this.canvasLoading = true;
      this.drawMainScene.getFloorData('/revit-algorithm/base-graph/query', { ModelId: ModelId }).then(res => {
        // console.log(this)
        this.getGraphtSuc(res);
      })
    },
    getSelectedSpaces() {//获取选中区域
      if (this.view && this.view.scene) {
        let list = this.view.scene.getSelectedSpaces();
        if (list.length) {
          return list
        } else {
          return []
        }
      } else {
        return []
      }
    },
    // 清空平面图
    clearGraphy() {
      if (this.view) {
        this.view.scene = null;
        return
      }
      let id = `floorCanvas${this.id}`;
      this.view = new FloorView(id)
    },
    canvasClick(item, eventObj) {//点击平面图事件
      this.$emit("changeButtonContent",this.drawMainScene.getSelectedSpaces().length?"通过模型空间创建":"通过模型创建")
    },
    getGraphtSuc(res) {
      this.showTools = true;
      this.canvasLoading = false;
      if (res.Result == 'failure') {
        this.showTools = false;
        this.$message.warning(res.Message);
        return;
      }
      this.view.scene = this.drawMainScene;
      if(this.isLight){//高亮显示未验证的区块
        this.deviceList = []
        this.highLightPoint()
      }
      this.view.fitSceneToView();
      this.drawMainScene.click(this, this.canvasClick);
      if (this.$refs.canvasFun) {
        this.view.minScale = this.view.scale;
        this.$refs.canvasFun.everyScale = this.view.scale;
      }
    },
    //高亮未完成验证的区块
    async highLightPoint() {
      await this.getUnverificationDevice()
      this.view.scene.spaceList.forEach(item => {
        for(let deviceItem of this.deviceList) {
          if(deviceItem.locationJson && item.contains(deviceItem.locationJson.x, -deviceItem.locationJson.y)){//注：坐标体系不同,Y坐标取反
            item.highLightFlag = true
            break
          }
        }
      })
    },
    //获取模型下未验证的设备
    getUnverificationDevice(pageNum) {
      return new Promise((resolve) => {
        pageNum = pageNum ? pageNum : 1
        let params = {
          filters: `taskState isNull;modelId='${this.CurrentModelId}'`,
          orders: "createTime desc, id asc",
          projection: ["id", "bimId", "bimLocation", "locationJson"],
          pageNumber: pageNum,
          pageSize: 1000
        }
        queryEquip(params, res => {
          this.deviceList = res.content
          resolve();
        });
      });
      // queryEquip(params, res => {
      //   this.deviceList = this.deviceList.concat(res.Content)
      //   if (res.Total / (res.PageSize * res.PageNumber) > 1) {
      //     this.getUnverificationDevice(res.PageNumber + 1)
      //   } else { }
      // });
    },
    // canvas 获取焦点
    focus() {
      document.getElementById(`floorCanvas${this.id}`).focus()
    },
    // 工具栏操作
    // 适配底图到窗口
    fit() {
      this.view.fitSceneToView()
    },
    // 保存为png
    savePng() {
      this.view.saveImage(`${this.projectName}-${this.modelName}.png`, 'png');
    },
    // 保存为svg
    saveSvg() {
      this.view.saveSceneSvg(`${this.projectName}-${this.modelName}.svg`, 6400, 4800);
    },
    saveJson() {
      this.view.saveFloorJson(`${this.projectName}-${this.modelName}.json`)
    },
    // 缩放
    scale(val) {
      if (!this.view) {
        return;
      }
      let scale = this.view.scale;
      this.view.scaleByPoint(val / scale, this.cadWidth / 2, this.cadHeight / 2);
    }
  },
  watch: {
    isLight: {
      handler(newValue, oldValue) {
        if(newValue){//高亮显示未验证的区块
          this.deviceList = []
          this.highLightPoint()
        } else {
          this.view.scene.spaceList.forEach(item => {
            item.highLightFlag = false
          })
        }
      }
    },
    CurrentModelId: {
      handler(newName, oldName) {
        if (newName) {
          this.initGraphy(newName)
        }
      },
      immediate: true,
    },
    "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>
