<template>
  <div id="manageTenantZone">
    <!-- 数据字典设备类型 -->
    <el-row>
      <el-button size="small" type="default" icon="el-icon-back" @click="goback"></el-button>
      <div style="display:inline-block;margin:10px 0 0 10px;">
        <label style="margin-right:10px;">业务空间类型</label>
        <el-badge :is-dot="onlyRead&&options.length>1">
          <el-select v-model="value" placeholder="请选择" @change="getTnRelatFloor">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-badge>
      </div>
    </el-row>
    <el-row class="main-container">
      <el-col :span="3" class="main-left">
        <div style="padding:10px;border-bottom:1px solid #e4e4e4;">
          <el-input :placeholder="`请输入租户名称`" @keyup.enter.native="getTenant" v-model="keyWord">
            <i slot="suffix" class="el-input__icon el-icon-search" @click="getTenant"></i>
          </el-input>
        </div>
        <div style="overflow-y:auto;height: calc(100% - 53px);">
          <div v-for="(item,i) in tenantList" :key="item.TenantID" :class="{'tenantItem':true, 'active':item.active}"
               @click="tenantChange(i)">
            {{ item.TenantLocalName || item.TenantName }}
          </div>
        </div>
      </el-col>
      <el-col :span="21" style="height:100%;">
        <div style="height:52px;border-bottom:1px solid #e4e4e4;">
          <div v-if="onlyRead===true||onlyRead==='true'">
            <div v-for="(bd,i) in allBuilding" :key="bd.BuildID" :class="{'building':true,'active':bd.active}"
                 @click="changeBuildSelect(i)">
              {{ bd.BuildLocalName || bd.BuildName }}
            </div>
          </div>
          <div v-else style="line-height: 52px;padding:0 10px;">
            <label style="margin-right:10px;">所属建筑</label>
            <el-select v-model="buildSelect" placeholder="请选择" @change="changeBuildSelect">
              <el-option v-for="(item,i) in allBuilding" :key="item.BuildID"
                         :label="item.BuildLocalName || item.BuildName" :value="i">
              </el-option>
            </el-select>
            <div style="float:right;">
              <el-button size="small" type="default" @click="editCanvas" v-if="!isEdit">编辑</el-button>
              <el-button size="small" type="default" @click="cancel" v-if="isEdit">取消</el-button>
              <el-button size="small" type="primary" @click="save" v-if="isEdit">确认</el-button>
            </div>
          </div>
        </div>
        <div class="canvas-container" ref="graphy" v-loading="canvasLoading">
          <div class="floor-container" v-show="floorList.length">
            <div class="before" @click="toBefore">
              <div><i class="el-icon-caret-top"></i></div>
            </div>
            <div class="floor">
              <div v-for="(fl,i) in floorList" :key="fl.id" :class="{'active':fl.active,'textParent':true}"
                   @click="floorChange(i)">
                <div class="text" :title="fl.FloorLocalID || fl.FloorLocalName">
                  {{ fl.FloorLocalID || fl.FloorLocalName }}
                  <span v-if="fl.Count">{{ fl.Count > 9 ? '9+' : fl.Count }}</span>
                </div>
              </div>
            </div>
            <div class="after" @click="toNext">
              <div><i class="el-icon-caret-bottom"></i></div>
            </div>
            <div class="border"></div>
          </div>
          <canvas id="floorCanvas" :width="canvasWidth" :height="canvasHeight" v-show="hasMap"></canvas>
          <div class="canvas-fun" v-show="hasMap">
            <canvasFun @scale="scale" @fit="fit" @savePng="savePng" @saveSvg="saveSvg" @saveJson="saveJson"
                       :config="config"
                       @groupSelect="groupSelect" ref="canvasFun">
            </canvasFun>
          </div>
          <div class="center" v-show="!hasMap">
            <i class="icon-wushuju iconfont"></i>
            暂无数据
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>
<script>
import canvasFun from "@/components/business_space/newGraphy/canvasFun";
import { mapGetters } from "vuex";
import { SColor, SPoint } from "@saga-web/draw/lib";
import { DivideFloorScene, SpaceItem, ZoneItem, FloorView, Opt } from "@saga-web/cad-engine/lib";
import { colorArr } from "@/utils/spaceColor"
import {
  // buildingQuery,
  queryTnRelateFloor,
  queryRentTableData,
  tnRelateZone,
  zoneQueryOutline
} from '@/api/scan/request'
import { buildingQuery } from '@/api/object/build';

export default {
  data() {
    return {
      options: [{ value: 'GeneralZone', label: '默认分区' }, { value: 'TenantZone', label: '租户分区' }],
      value: 'TenantZone',
      tenantList: [],
      floorList: [],
      canvasWidth: 800,
      canvasHeight: 800,
      onlyRead: false,
      allBuilding: [],
      buildSelect: 0,
      activeFloor: 0,
      activeTentanIndex: 0,
      canvasLoading: false,
      isEdit: false,
      view: '',
      scene: '',
      config: {
        isEdit: false,
        groupSelect: true
      },
      hasMap: true,
      keyWord: '', // 查询租户名称
      Cascade: {
        GeneralZone: 'zoneGeneraltList',
        TenantZone: 'zoneTenantList'
      }
    }
  },
  components: {
    canvasFun
  },
  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
    },
    buildFloorName() {
      let buildObj = this.allBuilding[this.buildSelect],
        floorObj = this.floorList[this.activeFloor];
      console.log(buildObj, floorObj)
      return `${buildObj.BuildLocalName ? buildObj.BuildLocalName :
        buildObj.BuildName ? buildObj.BuildName : ""}-${floorObj.FloorLocalID ?
        floorObj.FloorLocalID : floorObj.FloorLocalName ? floorObj.FloorLocalName : FloorName}`
    },
  },
  created() {
    this.onlyRead = this.$route.query.onlyRead;
    this.init();
    Opt.sceneMarkColor = new SColor('#ffffff');
  },
  mounted() {
    this.canvasWidth = this.$refs.graphy.offsetWidth;
    this.canvasHeight = this.$refs.graphy.offsetHeight;
  },
  methods: {
    init() {
      this.getTenant();
    },
    // 返回
    goback() {
      this.$router.push({ name: 'rentlist', query: { onlyRead: this.onlyRead } })
    },
    // 适配底图到窗口
    fit() {
      if (this.scene.sceneMark) {
        this.view.fitItemToView([this.scene.sceneMark])
        return
      }
      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);
    },
    // 保存为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`)
    },
    // 框选
    groupSelect() {
      this.scene.isRectSelection = 2;
    },
    // 上一个
    toBefore() {
      if (this.activeFloor > 0) {
        let index = this.activeFloor - 1;
        this.floorChange(index)
      }
    },
    // 下一个
    toNext() {
      if (this.activeFloor < this.floorList.length - 1) {
        let index = this.activeFloor + 1;
        this.floorChange(index)
      }
    },
    // 建筑修改
    changeBuildSelect(val) {
      this.allBuilding.map(t => {
        t.active = false;
      })
      this.allBuilding[val].active = true;
      if (this.allBuilding[val].Floor && this.allBuilding[val].Floor.length) {
        this.floorList = this.allBuilding[val].Floor
        this.floorChange(0);
      } else {
        this.floorList = []
      }
    },
    // 租户修改
    tenantChange(index) {
      this.tenantList.map(t => {
        t.active = false;
      })
      this.curTenantId = this.tenantList[index].TenantID;
      this.tenantList[index].active = true;
      this.activeTentanIndex = index;
      this.tenantChangeInflu(index);
    },
    // 租户更改引起的修改
    tenantChangeInflu(i) {
      if (this.onlyRead === true || this.onlyRead === 'true') { // 只读模式-对空间类型处理
        let g = this.tenantList[i].ZoneGeneraltList;
        let t = this.tenantList[i].ZoneTenantList;
        let gFlag = g && g.length;
        let tFlag = t && t.length;
        if (gFlag) {
          if (tFlag) {
            this.options = [{ value: 'GeneralZone', label: '默认分区' }, { value: 'TenantZone', label: '租户分区' }]
            this.value = 'TenantZone';
          } else {
            this.options = [{ value: 'GeneralZone', label: '默认分区' }];
            this.value = 'GeneralZone';
          }
        } else {
          if (tFlag) {
            this.options = [{ value: 'TenantZone', label: '租户分区' }];
            this.value = 'TenantZone';
          } else {
            this.options = [];
            this.value = '';
          }
        }
      }
      this.getTnRelatFloor();
    },
    // 楼层修改
    floorChange(index) {
      this.floorList.map(t => {
        t.active = false;
      })
      this.activeFloor = index;
      this.floorList[index].active = true;
      this.getGraphy(index)
    },
    // canvas点击事件
    canvasClick(item, event) {
      if (!this.isEdit) {
        item.selected = false;
      }
    },
    // 编辑
    editCanvas() {
      this.isEdit = true;
      this.config.isEdit = true;
      this.scene.zoneList.map(t => {
        t.selected = t.highLightFlag;
        t.transparency = 20;
        t.highLightFlag = false;
      })
    },
    // 取消
    cancel() {
      this.isEdit = false;
      this.config.isEdit = false;
      this.scene.clearZoneSelection();
      this.getBusinessSpace();
    },
    // 清除canvas
    clearGraphy() {
      if (this.view) {
        this.view.scene = null;
        return
      }
      this.view = new FloorView('floorCanvas')
    },
    // 获取列表
    getTenant() {
      let pa = {
        cascade: [
          { name: 'zoneTenantList' },
          // , Cascade: [{ Name: 'building' }, { Name: 'floor' }]
          { name: 'zoneGeneraltList' }
        ],
        orders: "id asc",
        pageSize: 1000
      }
      if (this.keyWord) {
        pa.filters = `localName contain '${this.keyWord}'`
      }
      queryRentTableData(pa, res => {
        this.tenantList = res.content.map(t => {
          t.active = false;
          return t;
        })
        if (this.tenantList.length) {
          this.tenantChange(0)
        }
      })
    },
    // 获取业务空间
    getBusinessSpace() {
      let buildid = this.floorList[this.activeFloor].BuildID;
      let floorid = this.floorList[this.activeFloor].FloorID;
      let TenantID = this.tenantList[this.activeTentanIndex].TenantID
      if (buildid && floorid && this.value) {
        this.canvasLoading = true
        let pa = {
          Filters: `not RoomID isNull`,
          Orders: "createTime desc, RoomID asc",
          PageSize: 1000,
          ZoneType: this.value,
          BuildingId: buildid,
          FloorId: floorid
        }
        this.canvasLoading = false;
        let promise1 = new Promise((resolve) => {
          zoneQueryOutline(pa, res => {
            resolve(res);
          })
        })
        let pa2 = {
          cascade: [
            { name: this.Cascade[this.value], filters: `floorId='${floorid}'` }
          ],
          filters: `id='${TenantID}'`
        }
        let promise2 = new Promise((resolve) => {
          queryRentTableData(pa2, res => {
            resolve(res);
          })
        })
        Promise.all([promise1, promise2]).then(response => {
          let res1 = response[0];
          let res2 = response[1];
          let key = 'Z' + this.Cascade[this.value].substring(1);
          let relationList = res2.content[0][key] || [];
          this.businessSpaceList = res1.Content;
          // 已关联元空间的业务空间
          this.BSPRelaISPList = [];
          res1.Content.map(t => {
            if (t.Outline && t.Outline.length) {
              this.BSPRelaISPList.push(t)
            }
          })
          // 绘制业务空间
          let tempArr = this.BSPRelaISPList.map((t, i) => {
            if (t.FloorId == this.floorList[this.activeFloor].FloorID && t.ObjectType == this.value) {
              return {
                RoomLocalName: t.RoomLocalName,
                OutLine: t.Outline,
                RoomID: t.RoomID,
                Color: colorArr[i % colorArr.length],
                HighLightFlag: relationList.findIndex((item) => (item.RoomID == t.RoomID)) > -1,
                Transparency: relationList.findIndex((item) => (item.RoomID == t.RoomID)) > -1 ? 20 : 1
              }
            } else {
              return undefined;
            }
          }).filter(item => item)
          this.scene.removeAllZone();
          this.scene.addZoneList(tempArr);
          this.scene.click(this, this.canvasClick);
        })
      }
    },
    // 初始化底图
    getGraphy(index) {
      if (this.floorList[index].StructureInfo && this.floorList[index].StructureInfo.FloorMap) {
        let floorMap = this.floorList[index].StructureInfo.FloorMap;
        this.clearGraphy();
        this.scene = new DivideFloorScene();
        this.hasMap = true;
        this.canvasLoading = true;
        this.scene.loadUrl(`/image-service/common/file_get?systemId=revit&key=${floorMap}`).then(res => {
          if (res == 'error') {
            console.log('数据解析异常');
            this.hasMap = false;
            this.canvasLoading = false;
            return;
          }
          this.view.scene = this.scene;
          if (this.floorList[index].Outline) {
            let newArr = this.floorList[index].Outline.map(t => {
              return new SPoint(t.X, t.Y);
            })
            this.scene.addSceneMark(newArr)
          }
          this.scene.isSpaceSelectable = false;
          // 绘制业务空间
          this.getBusinessSpace();
          this.fit();
          this.view.minScale = this.view.scale;
          if (this.$refs.canvasFun) {
            this.$refs.canvasFun.everyScale = this.view.scale;
          }
        })
      } else {
        this.hasMap = false;
      }
    },
    // 查询租户关联的业务空间所在建筑楼层,分区修改也会触发
    getTnRelatFloor() {
      if (this.value) {
        let pa = {
          objectType: this.value,
          tenantId: this.curTenantId
        }
        queryTnRelateFloor(pa, res => {
          this.allBuilding = res.content.map(t => {
            t.active = false;
            if (t.floor) {
              t.floor.map(item => {
                item.active = false;
              })
            }
            return t;
          });
          if (this.onlyRead === true || this.onlyRead === 'true') {
            this.allBuilding = this.allBuilding.filter(item => item.count > 0)
            this.allBuilding.map(t => {
              if (t.floor) {
                t.floor = t.floor.filter(item => item.count > 0)
              }
            })
          }
          if (this.allBuilding.length) {
            this.changeBuildSelect(this.buildSelect);
          }
        })
      } else {
        this.hasMap = false;
        this.canvasLoading = false;
        this.allBuilding = [];
        this.floorList = [];
      }
    },
    // 保存关系
    save() {
      let arr = this.scene.getSelectedZone();
      let pa = {
        data: {
          SpaceIdList: [],
          FloorId: this.floorList[this.activeFloor].FloorID,
          TenantId: this.curTenantId
        },
        type: this.value
      }
      pa.data.SpaceIdList = arr.map(t => {
        return t.data.RoomID;
      })
      tnRelateZone(pa, res => {
        this.isEdit = false;
        this.config.isEdit = false;
        this.$message.success('关联成功');
        this.getTnRelatFloor();
      })
    },
  },
  watch: {
    projectId() {
      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.isRectSelection": {
      handler(n) {
        if (!n) {
          this.$refs.canvasFun.active = '';
        }
      }
    },
  }
}
</script>
<style lang="less" scoped>
@normal-border-color: #e4e4e4;
@normal-border-active-color: #e8e8e8;
#manageTenantZone {
  height: 100%;

  .main-container {
    margin-top: 10px;
    background: #fff;
    border: 1px solid @normal-border-color;
    height: calc(100% - 53px);
    overflow: hidden;

    .main-left {
      height: 100%;
      border-right: 1px solid @normal-border-color;

      .tenantItem {
        border-bottom: 1px solid @normal-border-color;
        text-align: center;
        line-height: 40px;
        color: #2b2b2b;
        cursor: pointer;

        &.active {
          background-color: @normal-border-active-color;
        }
      }
    }
  }

  .building {
    display: inline-block;
    margin: 7px 10px;
    border: 1px solid @normal-border-color;
    color: #2b2b2b;
    border-radius: 28px;
    padding: 4px 16px;
    cursor: pointer;

    &.active {
      border: 1px solid #409eff;
      color: #409eff;
    }
  }

  .canvas-container {
    position: relative;
    width: 100%;
    height: calc(100% - 53px);
    display: flex;
    align-items: center;
    justify-content: center;

    .floor-container {
      position: absolute;
      width: 60px;
      height: 260px;
      top: 20px;
      left: 20px;
      z-index: 2;
      background-color: #fff;

      .before,
      .after {
        div {
          width: 52px;
          height: 23px;
          margin: 0 auto;
          text-align: center;
          font-size: 24px;
          line-height: 1;
          color: #2b2b2b;
          border: 1px solid @normal-border-color;
          cursor: pointer;
        }
      }

      .floor {
        position: relative;
        height: 210px;
        overflow-y: auto;

        &::-webkit-scrollbar {
          display: none;
        }

        .textParent {
          cursor: pointer;

          &.active {
            background-image: url(~@/assets/image/floorBG.png);

            div.text {
              border: none;
            }
          }

          div.text {
            position: relative;
            width: 54px;
            height: 30px;
            line-height: 30px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            text-align: center;
            color: #2b2b2b;
            margin: 0 auto;
            padding: 0 10px;
            box-sizing: border-box;

            &:hover {
              background-color: #409eff1a;
            }

            b {
              font-weight: normal;
            }

            span {
              position: absolute;
              display: block;
              height: 10px;
              border-radius: 14px;
              line-height: 10px;
              text-align: center;
              top: 0;
              right: -2px;
              color: #fff;
              background-color: #f56c6c;
              padding: 5px;
              font-size: 12px;
              transform: scale(0.7, 0.7);
            }
          }
        }
      }

      div.border {
        position: absolute;
        width: 52px;
        height: 100%;
        left: 50%;
        top: 0;
        z-index: -1;
        transform: translateX(-50%);
        border-left: 1px solid @normal-border-color;
        border-right: 1px solid @normal-border-color;
      }
    }

    .canvas-fun {
      position: absolute;
      bottom: 20px;
      left: 50%;
      z-index: 3;
      transform: translateX(-50%;);
    }
  }
}
</style>
