<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" @change="getBusinessSpace">
          <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'>
        <span style="margin-right:10px;">当前状态 {{description}}</span>
        <el-button @click="cancel">取消</el-button>
        <el-button @click="removeRelation">清除</el-button>
        <el-button @click="removeAll">清除所有</el-button>
        <el-button @click="addRelation">添加</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, //数据中心-建筑查询
  zoneQueryOutline, // 业务空间查询
  queryDictionaryHead, //空间类型查询
  createSpaceNeighborhood, //创建邻接关系
  querySpaceNeighborhood, // 查询邻接关系
  delSpaceNeighborhood, //删除选中
  delFloorNeighborhood, //删除所有
} from "@/api/scan/request";
import { buildingQuery } from '@/api/object/build';
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
      },
      description: '无'
    }
  },
  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() {
      if (this.scene) {
        this.scene.removeAllRelation()
      }
    },
    //
    cancel() {
      this.scene.removeRelationFlag = false;
      this.scene.createRelateFlag = false;
      this.scene.isAbsorbing = false;
      this.description = '无'
    },
    //
    removeRelation() {
      this.scene.removeRelationFlag = true;
      this.scene.createRelateFlag = false;
      this.scene.isAbsorbing = false;
      this.description = '清除'
    },
    //
    addRelation() {
      this.scene.createRelateFlag = true;
      this.scene.removeRelationFlag = false;
      this.scene.isAbsorbing = true;
      this.description = '添加'
    },
    //
    removeAll() {
      let temp = {
        FloorId: this.buildFloor[1],
        ZoneType: this.zoneType,
        GraphType: this.type
      }
      delFloorNeighborhood(temp, res => {
        this.$message.success('删除成功');
        this.clearRelation();
      })
    },
    canvasClick(item, event) {
      console.log(item);
      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 = '';
          console.log('数据解析异常');
          return;
        }
        this.view.scene = this.scene;
        this.view.fitSceneToView();
        this.scene.isSpaceSelectable = false;
        this.getBusinessSpace();
        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() {
      this.$router.push({ name: 'overView' })
    },
    // 获取项目下建筑
    getBuilding() {
      let pa = {
        cascade: [{ name: 'floor', orders: 'floorSequenceID desc' }],
        orders: "localName asc",
      }
      buildingQuery(pa, res => {
        this.options = res.content.map(t => {
          if (t.floor) {
            t.floor = t.floor.map(item => {
              item.BuildID = item.id;
              item.BuildLocalName = item.localName;
              this.idToFloor[item.id] = 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);
        this.canvasLoading = false;
      })
    },
    // 获取当前分区下的业务空间
    getBusinessSpace() {
      this.canvasLoading = true
      let pa = {
        Filters: `not RoomID isNull`,
        Orders: "createTime desc, RoomID asc",
        PageSize: 1000,
        ZoneType: this.zoneType
      }
      if (this.buildFloor.length && this.buildFloor.length > 1) {
        pa.BuildingId = this.buildFloor[0];
        pa.FloorId = this.buildFloor[1];
      } else {
        this.$message.warning("请选择建筑楼层");
      }
      zoneQueryOutline(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.getRelations();
      })
    },
    // 创建邻接关系
    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;
        }
      }
    },
    "scene.curRemoveItem": {
      handler(n) {
        if (n) {
          let pa = [{
            GraphType: this.type,
            ZoneType: this.zoneType,
            SpaceIdOne: n.startZone,
            SpaceIdTwo: n.endZone
          }]
          delSpaceNeighborhood(pa, res => {
            this.$message.success('删除成功');
          })
        }
      }
    }
  }
}
</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>
