<template>
  <div id="graphy" ref="graphy">
    <div v-show="!FloorMap">
      <div class="center" style="height: 400px;padding-top:182px;box-sizing:border-box;">
        <i class="icon-wushuju iconfont"></i>
        暂无数据
      </div>
    </div>
    <div class="canvas-box" v-show="FloorMap" v-loading="canvasLoading">
      <canvas id="floorCanvas" :width="canvasWidth" :height="canvasHeight" ref="canvas" tabindex="0"></canvas>
      <!-- 初始两个按钮 -->
      <el-row class="buttons-box">
        <div>
          <el-autocomplete popper-class="my-autocomplete" v-model="search" :fetch-suggestions="querySearch" placeholder="输入平面图中已有的业务空间名称进行查找"
            width="180px" @select="handleSelect">
            <i class="el-icon-search el-input__icon" slot="suffix" @click="handleSelect"></i>
            <template slot-scope="{ item }">
              <div class="name" style="position: relative;">
                {{ item.RoomLocalName | cutString(8) }}
                <span class="addr" style="position: absolute;right:10px;color:#409EFF;">定位</span>
              </div>
            </template>
          </el-autocomplete>
        </div>
        <div class="button-group">
          <!-- 默认操作模式 -->
          <div v-show="type==1">
            <el-button @click="editGraphy">编辑平面图</el-button>
          </div>
          <!-- 点击已经关联的业务空间 -->
          <div v-show="type==2">
            <el-button type="primary" plain>重新划分业务空间</el-button>
            <el-button type="primary" @click="editeSpaceDetail">编辑空间详情</el-button>
            <el-button plain @click="cancelGraphy">取 消</el-button>
          </div>
          <!-- 点击未关联的业务空间 -->
          <div v-show="type==3">
            <el-button plain @click="createNewZone">创建新的业务空间</el-button>
            <el-button type="primary" @click="lookUnrelatBSpace(true)">从未关联平面图的业务空间中选择</el-button>
            <el-button plain @click="cancelGraphy">取 消</el-button>
          </div>
          <!-- 重新划分业务空间 -->
          <div v-show="type==4">
            <el-button plain @click="cancelGraphy">取 消</el-button>
            <el-button type="primary">保存</el-button>
          </div>
        </div>
        <div style="position: absolute;right: 0;">
          <el-button type="text" @click="lookUnrelatBSpace(false)">未关联平面图的业务空间 {{num}} 条</el-button>
        </div>
      </el-row>
      <!-- 底部操作按钮 -->
      <el-row 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" ref="canvasFun"></canvasFun>
      </el-row>
    </div>
    <!--  -->
    <!-- 未关联元空间的业务空间 -->
    <unRelateBSP ref="unRelateBSP" :tableData="BSPUnrelaISPList" :isAction="isAction" @createFromUnrelated="createFromUnrelated"></unRelateBSP>
    <!-- 创建新的业务空间 -->
    <createBSP ref="createBSP" @createRoom="createRoom"></createBSP>
  </div>
</template>
<script>
import canvasFun from "./canvasFun"
import { mapGetters, mapActions } from "vuex";
import { SGraphyView } from "@sybotan-web/graphy/lib";
import { DivideFloorScene, } from "cad-engine"
import { SColor, SPoint } from "@sybotan-web/draw/lib";
import { SpaceItem } from "cad-engine/lib/items/SpaceItem";
import { ZoneItem } from "cad-engine/lib/items/ZoneItem";
import unRelateBSP from "./unRelateBSP";
import createBSP from "./createBSP";
import {
  countZone,
  queryZone,
  updateZone,
  createZone,
  createRelateInZoneAndISp
} from "@/api/scan/request"
const colorArr = [
  "#F9C3C3",
  "#FFD1BF",
  "#FFF3BF",
  "#D8F7C6",
  "#C6F2F6",
  "#DCE3C0",
  "#FAE6C9",
  "#E3D7F7",
  "#C4CBF8",
  "#DEC3F6"
];
//  BSP => 业务空间
export default {
  components: {
    canvasFun,
    unRelateBSP,
    createBSP
  },
  data() {
    return {
      canvasWidth: 800,
      canvasHeight: 600,
      type: 1, // 默认操作模式
      search: '',//搜索
      num: 0, // 未关联空间的业务空间条数
      buildFloor: [],
      FloorMap: '',
      tab: {},
      isEdit: false,
      canvasLoading: false,
      view: null,
      scene: null,
      Outline: [], // 当前选中的多个空间组成的轮廓线->三维数组
      businessSpaceList: [], // 所有业务空间
      BSPUnrelaISPList: [], // 未关联元空间的业务空间
      BSPRelaISPList: [], // 已关联元空间的业务空间
      // 未关联元空间的业务空间弹窗
      isAction: false,
      curOutline: [],
      BIMIDToSID: {}, //bimid映射元空间id
    }
  },
  computed: {
    ...mapGetters('layout', ['projectId'])
  },
  created() {
  },
  mounted() {
    this.canvasWidth = this.$refs.graphy.offsetWidth;
    this.canvasHeight = this.$refs.graphy.offsetHeight;
  },
  methods: {
    // 初始化
    init() {
      this.type = 1;
      // 获取当前分区下的业务空间
      this.getBusinessSpace();
      // 获取未关联平面图的业务空间统计
      this.getUnrelateCount();
      // 获取当前楼层的元空间
      this.getFloorISpace();
    },
    // 获取当前楼层的元空间
    getFloorISpace() {
      let pa = {
        zone: 'Ispace',
        data: {
          Filters: `FloorId='${this.buildFloor[1]}'`,
          PageSize: 1000
        }
      }
      queryZone(pa, res => {
        this.BIMIDToSID = {}
        res.Content.map(t => {
          this.BIMIDToSID[t.BIMID.split(":")[1]] = t.RoomID;
        })
      })
    },
    // 搜索
    querySearch(queryString, cb) {
      var restaurants = this.BSPRelaISPList;
      var results = queryString ?
        restaurants.filter(this.createFilter(queryString)) :
        restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    // 过滤器
    createFilter(queryString) {
      return restaurant => {
        return restaurant.RoomLocalName.indexOf(queryString) > -1;
      };
    },
    // 查询选中
    handleSelect(BSP) {
      console.log(arguments)
    },
    // 父组件调用
    getData(buildFloor, FloorMap, tab) {
      this.buildFloor = buildFloor;
      this.FloorMap = FloorMap;
      this.tab = tab;
      console.log(arguments)
      this.init();
    },
    // 获取未关联平面图的业务空间统计
    getUnrelateCount() {
      let pa = {
        data: {
          Filters: `BuildingId='${this.buildFloor[0]}';FloorId='${this.buildFloor[1]}';Outline isNull`
        },
        zone: this.tab.code
      }
      countZone(pa, res => {
        this.num = res.Count
      })
    },
    // 获取未绑定业务空间的元空间
    getISPSPUnrelaBSP() {

    },
    // 获取底图
    getGraphy() {
      let that = this;
      that.clearGraphy()
      that.view = new SGraphyView('floorCanvas')
      that.scene = new DivideFloorScene();
      that.canvasLoading = true;
      that.scene.loadUrl(`/image-service/common/file_get?systemId=revit&key=${this.FloorMap}`).then(() => {
        that.canvasLoading = false;
        that.view.scene = that.scene;
        let tempArr = this.BSPRelaISPList.map((t, i) => {
          return {
            RoomLocalName: t.RoomLocalName,
            OutLine: t.Outline,
            RoomID: t.RoomID,
            Color: new SColor(colorArr[i % colorArr.length]),
          }
        })
        that.scene.addZoneList(tempArr);
        that.scene.click(that, that.canvasClick)
        that.view.fitSceneToView();
      })
    },
    // 获取当前分区下的业务空间
    getBusinessSpace() {
      this.isLoading = true
      let pa = {
        zone: this.tab.code,
        data: {
          Filters: ``,
          Orders: "createTime desc, RoomID asc",
          PageSize: 500
        }
      }
      if (this.buildFloor.length && this.buildFloor.length > 1) {
        pa.data.Filters = `BuildingId='${this.buildFloor[0]}';FloorId='${this.buildFloor[1]}'`
      }
      queryZone(pa, res => {
        // 所有业务空间
        this.businessSpaceList = res.Content;
        // 未关联元空间的业务空间
        this.BSPUnrelaISPList = [];
        // 已关联元空间的业务空间
        this.BSPRelaISPList = [];
        res.Content.map(t => {
          if (t.Outline && t.Outline.length) {
            this.BSPRelaISPList.push(t)
          } else {
            this.BSPUnrelaISPList.push(t)
          }
        })
        // 获取底图
        this.getGraphy();
        this.isLoading = false;
      })
    },
    // canvas点击事件
    canvasClick(item, event) {
      console.log(arguments)
      if (item instanceof SpaceItem) {
        this.type = 3;
      }
      if (item instanceof ZoneItem) {
        this.type = 2;
      }
    },
    // 编辑平面图
    editGraphy() {
      this.type = 3;
    },
    // 查看未关联的业务空间--flag--查看-or-选择
    lookUnrelatBSpace(flag) {
      this.isAction = flag;
      let arr = this.scene.getSelectedSpaces();
      if (flag && !arr.length) {
        this.$message.warning('请至少选择一个空间');
        return;
      }
      this.$refs.unRelateBSP.showDialog();
    },
    // 取消(所有取消公用)
    cancelGraphy() {
      this.type = 1;
      this.init();
    },
    // 批量创建业务空间
    groupCreateBSpace() {
      let text = []
      let Spaces = this.scene.spaceList.map(t => {
        text.push(t.data.Name)
        return {
          RoomLocalName: t.data.Name,
          Outline: [t.data.OutLine]
        }
      });
      console.log(Spaces)
      console.log(this.scene.spaceList)
      // return
      this.$confirm(
        "<p>确定根据未关联业务空间的空间批量创建业务空间</p>" +
        "<p>涉及的空间：</p>" +
        "<p style='line-height:20px;max-height:60px;overflow-y:auto;'>" +
        text.toString() +
        "</p>",
        "提示", {
        dangerouslyUseHTMLString: true,
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
      ).then(() => {
        console.log()
        let pa = {
          zone: this.zoneCode,
          data: {
            Content: Spaces
          }
        }
        createZone(pa, res => {

        })
      }).catch(() => {
        this.$message({
          type: "info",
          message: "已取消批量创建"
        });
      });
    },
    // 创建新的业务空间
    createNewZone() {
      let arr = this.scene.getSelectedSpaces();
      if (arr.length) {
        let tempArr = [];
        arr.map(t => {
          tempArr.push(t.data.Name);
        })
        this.$refs.createBSP.showDialog(tempArr.toString());
      } else {
        this.$message.warning('请至少选择一个空间');
      }
    },
    // 创建新的业务空间-弹窗返回确认创建
    createRoom(val) {
      let arr = this.scene.getSelectedSpaces();
      let zoneObj = { Outline: [] }, IspaceIdList = [];
      arr.map(t => {
        zoneObj.Outline.push(t.data.OutLine);
        IspaceIdList.push(this.BIMIDToSID[t.data.SourceId])
      })
      zoneObj.RoomLocalName = val;
      zoneObj.BuildingId = this.buildFloor[0];
      zoneObj.FloorId = this.buildFloor[1];
      let pa = {
        zone: this.tab.code,
        data: {
          Content: [zoneObj]
        }
      }
      createZone(pa, res => {
        let params = {
          SpaceId: res.EntityList[0].RoomID,
          IspaceIdList: IspaceIdList
        }
        createRelateInZoneAndISp(params, res => {
          this.$message.success('创建成功');
          this.init();
        })
      })
    },
    // 从未关联平面图的业务空间中选择--按钮返回关联信号
    createFromUnrelated(BSP) {
      BSP.Outline = []
      let arr = this.scene.getSelectedSpaces();
      arr.map(t => {
        BSP.Outline.push(t.data.OutLine);
      })
      let pa = {
        zone: BSP.ObjectType,
        data: {
          Content: [BSP],
          Projection: ['Outline']
        }
      }
      updateZone(pa, res => {
        this.$message.success('更新成功');
        this.init();
      })
    },
    // 编辑空间详情
    editeSpaceDetail() {
      let arr = this.scene.getSelectedSpaces();
      console.log(arr)
      // this.$router.push({
      //   path: "/ledger/spaceDetail",
      //   query: { RoomID: infos.RoomID, zone: this.zoneCode, isMyTab: 2 }
      // })
    },
    // canvas 获取焦点
    focus() {
      document.getElementById(`floorCanvas`).focus()
    },
    // 清除canvas
    clearGraphy() {
      if (this.view) {
        this.view = null;
        this.scene.root.children = null;
        this.scene = null;
      }
    },
    // 工具栏操作
    // 移动底图
    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.floor}.png`, 'png');
    },
    // 保存为svg
    saveSvg() {
      this.view.saveSceneSvg(`${this.floor}.png`, 6400, 4800);
    },
    // 切割划分
    divide() {
      this.drawMainScene.isMarking = true;
    },
    // 清除切割划分
    clearDivide() {
      this.drawMainScene.clearSceneMark()
    },
    // 撤销
    undo() {

    },
    // 反撤销
    redo() { },
    // 缩放
    scale(val) {
      let scale = this.view.scale
      this.view.scaleByPoint(val / scale, this.cadWidth / 2, this.cadHeight / 2)
    },
  },
  filters: {
    cutString: function (str, len) {
      //length属性读出来的汉字长度为1
      if (!!str && typeof str == "string" && str.length > len) {
        return str.substring(0, len) + "...";
      } else {
        return str || "--";
      }
    }
  },
  watch: {
    projectId() {
      this.FloorMap = '';
      this.tab = {};
    }
  }
}
</script>
<style lang="less" scoped>
#graphy {
  position: relative;
  width: 100%;
  height: calc(100% - 56px);
  .canvas-box {
    width: 100%;
    height: 100%;
  }
  .buttons-box {
    position: absolute;
    top: 0;
    width: 100%;
    z-index: 999;
    & > div {
      float: left;
    }
    /deep/ .el-autocomplete {
      display: block;
      width: 320px;
      margin-right: 10px;
    }
    .button-group button {
      display: block;
      float: left;
    }
    .my-autocomplete {
      li {
        line-height: normal;
        padding: 7px;
        .name {
          text-overflow: ellipsis;
          overflow: hidden;
        }
        .addr {
          font-size: 12px;
          color: #b4b4b4;
        }
        .highlighted .addr {
          color: #ddd;
        }
      }
    }
  }
  .canvas-actions-box {
    position: absolute;
    bottom: 20px;
    left: 50%;
    transform: translateX(-50%);
    z-index: 999;
  }
}
</style>