<template>
  <div id="spaceRelation">
    <el-row>
      <el-col :span="0.5">
        <el-button size="small" type="default" icon="el-icon-back" @click="goback"></el-button>
      </el-col>
      <el-col :span="0.5">
        <span style="margin:0 10px;">建筑楼层</span>
        <el-cascader placeholder="请选择建筑楼层" :options="options" v-model="buildFloor" filterable size="small" @change="changeCascader" :props="props">
        </el-cascader>
      </el-col>
      <el-col :span="0.5">
        <span style="margin:0 10px;">业务空间类型</span>
        <el-select placeholder="请选择" v-model="zoneType">
          <el-option v-for="item in tabsList" :key="item.Code" :label="item.Name" :value="item.Code">
          </el-option>
        </el-select>
      </el-col>
      <el-col :span="0.5" style="float:right;" v-show='0'>
        <el-button @click="clearRelation">清除</el-button>
        <el-button type="primary" @click="saveRelation">保存</el-button>
      </el-col>
    </el-row>
    <div class="canvas-container" v-loading="canvasLoading" ref="graphy">
      <div v-show="!FloorMap" style="display:flex;align-items:center;justify-content:center;height:100%;">
        <div class="center" style="flex:1">
          <i class="icon-wushuju iconfont"></i>
          暂无数据
        </div>
      </div>
      <div v-show="FloorMap" class="canvas-box">
        <canvas id="floorCanvas" :width="canvasWidth" :height="canvasHeight" ref="canvas" tabindex="0"></canvas>
        <!-- 底部操作按钮 -->
        <el-row class="canvas-actions-box">
          <canvasFun @fit="fit" @scale="scale" :config="config" ref="canvasFun"></canvasFun>
        </el-row>
      </div>
    </div>
  </div>
</template>
<script>
import {
  buildingQuery, //数据中心-建筑查询
  queryZone, // 业务空间查询
  queryDictionaryHead, //空间类型查询
  createSpaceNeighborhood, //创建邻接关系
  querySpaceNeighborhood, // 查询邻接关系
} from "@/api/scan/request";
import { SColor, SPoint } from "@saga-web/draw/lib";
import { RelationScene, FloorView } from "@saga-web/cad-engine/lib";
import canvasFun from "@/components/business_space/newGraphy/canvasFun"
import floorCascader from "@/components/ledger/lib/floorCascader";
import { colorArr } from "@/utils/spaceColor"
export default {
  components: {
    floorCascader,
    canvasFun
  },
  data() {
    return {
      view: '',
      scene: '',
      canvasWidth: 800,
      canvasHeight: 600,
      canvasLoading: false,
      FloorMap: '',
      options: [],
      buildFloor: [],
      tabsList: [],
      zoneType: 'GeneralZone',
      props: {
        value: 'BuildID',
        label: 'BuildLocalName',
        children: 'Floor'
      },
      idToFloor: {},
      config: {
        isEdit: false,
        divide: false,
        groupSelect: false
      },
    }
  },
  created() {
    //图类型编码
    this.type = this.$route.query.type;
    this.init();
  },
  mounted() {
    this.canvasWidth = this.$refs.graphy.offsetWidth - 20;
    this.canvasHeight = this.$refs.graphy.offsetHeight - 20;
  },
  methods: {
    //初始化
    init() {
      this.getBuilding();
      this.getTypes();
    },
    changeCascader(val) {
      if (val.length > 1) {
        let floor = this.idToFloor[val[1]];
        if (floor.StructureInfo && floor.StructureInfo.FloorMap) {
          this.FloorMap = floor.StructureInfo.FloorMap;
          this.initGraphy();
        } else {
          this.FloorMap = '';
        }
      } else {
        this.FloorMap = '';
      }
    },
    // 保存邻接关系
    saveRelation() {
      let relationList = this.scene.relationList;
      let pa = {
        Content: []
      }
      if (relationList.length) {
        pa.Content = relationList.map(t => {
          return {
            FloorId: this.buildFloor[1],
            GraphType: this.type,
            LocationOne: `${t.startPoint.x},${-t.startPoint.y}`,
            LocationTwo: `${t.lastPoint.x},${-t.lastPoint.y}`,
            SpaceIdOne: t.startZone,
            SpaceIdTwo: t.endZone,
            ZoneType: this.zoneType
          }
        })
      }
      this.createRela(pa)
    },
    clearRelation() {
      console.log(355555555555)
      if (this.scene) {
        this.scene.removeAllRelation()
      }
    },
    canvasClick(item, event) {
      item.selected = false;
    },
    initGraphy() {
      this.clearGraphy()
      this.scene = new RelationScene();
      this.canvasLoading = true;
      this.scene.loadUrl(`/image-service/common/file_get?systemId=revit&key=${this.FloorMap}`).then(res => {
        this.canvasLoading = false;
        if (res == 'error') {
          this.FloorMap = '';
          this.$message.warning('数据解析异常');
          return;
        }
        this.view.scene = this.scene;
        this.view.fitSceneToView();
        this.scene.isSpaceSelectable = false;
        this.scene.createRelateFlag = true;
        this.getBusinessSpace();
        // 绘制关系
        this.getRelations();
        this.view.minScale = this.view.scale;
        if (this.$refs.canvasFun) {
          this.$refs.canvasFun.everyScale = this.view.scale;
        }
      })
    },
    // 清空场景并初始化视图
    clearGraphy() {
      if (this.view) {
        this.view.scene = null;
        return
      }
      this.view = new FloorView('floorCanvas')
    },
    // canvas 获取焦点
    focus() {
      document.getElementById(`floorCanvas`).focus()
    },
    // 适配底图到窗口
    fit() {
      this.view.fitSceneToView()
    },
    // 缩放
    scale(val) {
      if (!this.view) {
        return;
      }
      let scale = this.view.scale;
      this.view.scaleByPoint(val / scale, this.canvasWidth / 2, this.canvasHeight / 2);
    },
    goback() { },
    // 获取项目下建筑
    getBuilding() {
      let pa = {
        Cascade: [{ name: 'floor', Orders: 'SequenceId desc' }],
        Orders: "BuildLocalName asc",
      }
      buildingQuery(pa, res => {
        this.options = res.Content.map(t => {
          if (t.Floor) {
            t.Floor = t.Floor.map(item => {
              item.BuildID = item.FloorID;
              item.BuildLocalName = item.FloorLocalName;
              this.idToFloor[item.FloorID] = item;
              return item;
            })
          } else {
            t.Floor = []
          }
          return t;
        })
      })
    },
    // 业务空间分区类型
    getTypes() {
      let pa = {
        Filters: `parentId='Space'`
      }
      queryDictionaryHead(pa, res => {
        this.tabsList = res.Content.map(t => {
          if (t.Name == "元空间") {
            return undefined;
          }
          return t;
        }).filter(item => item);
      })
    },
    getRelations() {
      let pa = {
        Filters: `FloorId='${this.buildFloor[1]}';GraphType='${this.type}';ZoneType='${this.zoneType}'`
      }
      querySpaceNeighborhood(pa, res => {
        let tempArr = res.Content.map(t => {
          let p1 = t.LocationOne.split(',');
          let p2 = t.LocationTwo.split(',');
          return {
            LocationOne: new SPoint(p1[0], -p1[1]),
            LocationTwo: new SPoint(p2[0], -p2[1]),
            SpaceIdOne: t.SpaceIdOne,
            SpaceIdTwo: t.SpaceIdTwo,
          }
        })
        this.clearRelation();
        this.scene.addAllRelaPoint(tempArr);
      })
    },
    // 获取当前分区下的业务空间
    getBusinessSpace() {
      this.canvasLoading = true
      let pa = {
        zone: this.zoneType,
        data: {
          Filters: ``,
          Orders: "createTime desc, RoomID asc",
          PageSize: 1000
        }
      }
      if (this.buildFloor.length && this.buildFloor.length > 1) {
        pa.data.Filters = `BuildingId='${this.buildFloor[0]}';FloorId='${this.buildFloor[1]}'`
      } else {
        this.$message.warning("请选择建筑楼层");
      }
      queryZone(pa, res => {
        // 所有业务空间
        this.businessSpaceList = res.Content;
        // 已关联元空间的业务空间
        this.BSPRelaISPList = [];
        res.Content.map(t => {
          if (t.Outline && t.Outline.length) {
            this.BSPRelaISPList.push(t)
          }
        })
        // 绘制业务空间
        let tempArr = this.BSPRelaISPList.map((t, i) => {
          if (t.FloorId == this.buildFloor[1] && t.ObjectType == this.zoneType) {
            return {
              RoomLocalName: t.RoomLocalName,
              OutLine: t.Outline,
              RoomID: t.RoomID,
              Color: colorArr[i % colorArr.length],
            }
          } else {
            console.log('internet slow')
            return undefined;
          }
        }).filter(item => item)
        this.scene.removeAllZone();
        this.scene.addZoneList(tempArr);
        // this.scene.click(this, this.canvasClick)
        this.canvasLoading = false;
      })
    },
    // 创建邻接关系
    createRela(param) {
      console.log(param)
      createSpaceNeighborhood(param, res => {
        this.$message.success('创建成功')
      })
    }
  },
  watch: {
    projectId() {
      this.FloorMap = '';
      this.init();
    },
    "view.scale": {
      handler(n) {
        if (this.$refs.canvasFun) {
          let s = n * 10 / this.view.minScale
          this.$refs.canvasFun.sliderVal = s > 1000 ? 1000 : s;
        }
      }
    }
  }
}
</script>
<style lang="less" scoped>
#spaceRelation {
  /deep/ .el-input__inner {
    vertical-align: baseline;
  }
  .canvas-container {
    position: relative;
    width: calc(100% - 22px;);
    height: calc(100% - 64px);
    margin-top: 10px;
    padding: 10px;
    background-color: #fff;
    border: 1px solid #e4e4e4;
    .canvas-box {
      width: 100%;
      height: 100%;
    }
    .canvas-actions-box {
      position: absolute;
      bottom: 20px;
      left: 50%;
      transform: translateX(-50%);
      z-index: 999;
    }
  }
}
</style>