<!--
  revit业务空间
 -->
<template>
  <div id="businessSpace">
    <!-- 空间属于多个建筑楼层 -->
    <roomInFloorDialog ref="roomInFloorDialog" @relaSuc="relaSuc"></roomInFloorDialog>
    <!--------- 页面头部   -------------->
    <div class="saga-title" v-show="!needCalculate">
      <div class="saga-build-mess">
        <div style="margin-left: 10px;float: left;">
          <span style="color: #999999;font-size: 14px;margin-right: 12px;">建筑楼层</span>
          <el-cascader :options="options" @change="changeCascader" placeholder="请选择建筑楼层" ref="cascaderAddr"
                       v-model="buildFloorSelectd">
            <template slot-scope="{ node, data }">
              <span>{{ data.label }}</span>
              <i class="el-icon-warning-outline" v-if="data.count" style="color:red;margin-right:10px;"></i>
            </template>
          </el-cascader>
        </div>
        <input type="hidden" v-model="zoneItemID">
      </div>
      <div class="saga-build-tab">
        <el-radio-group v-model="isMyTab" @change="changeRadio" style="width: 136px;">
          <el-radio-button label="1">平面图</el-radio-button>
          <el-radio-button label="2" class="space-own-radio" style="width: 68px;">列表</el-radio-button>
        </el-radio-group>
      </div>
      <div class="saga-build-tips" v-if="mutiCount>0" @click="getTips">有{{ mutiCount }}个空间同时属于多个建筑楼层，点击处理</div>
    </div>
    <div class="saga-business-sapce-main" v-show="!needCalculate">
      <el-row class="spaceTypes">
        <div class="types">
          <el-tabs v-model="activeName" type='card' @tab-click="tabClick">
            <template v-for="(item,index) in tabsList">
              <el-tab-pane :name="item.code" :key="index">
                <span slot="label"><i class="el-icon-warning-outline" v-if="item.count>0"  
                                      style="color:red;margin-right:10px;"></i>{{ item.name }}</span>
              </el-tab-pane>
            </template>
          </el-tabs>
        </div>
      </el-row>
      <div v-show="isMyTab == 1" style="width:100%;height:100%">
        <graphy @getSp="checkSpace" @dimension="checkSpace" @businessDetails="getBuinessDetails" ref="graphy"
                @copyID="copyID"
                @updateState="updateStateSuc"></graphy>
      </div>
      <div v-show="isMyTab == 2">
        <handsontable-main @lookEqu="lookEqu" ref="handsontable" :zoneCode="activeName" :otherType="otherType"
                           :id="`handsontable${activeName}`">
        </handsontable-main>
      </div>
      <div class="infectedTips" v-show="isMyTab==1&&infectedTotal>0">
        <p>因底图变化而受影响的业务空间{{ infectedTotal.toString() }}个<span
          v-show="buildFloorSelectd.length>1">，本层受影响的业务空间{{ infectedCurfloor.toString() }}个</span></p>
      </div>
    </div>
    <div v-show="needCalculate"
         style="display:flex;align-items:center;justify-content:center;height:100%;background-color:#fff;">
      <div class="center" style="flex:1">
        <i class="iconfont icon-jianzhu" style="font-size:50px;"></i>
        <p style="margin:10px 0;">空间关系已发生变化，请更新关系后再使用业务空间台账</p>
        <p style="margin:10px 0;">前往【全部关系总览】中重新计算“建筑下的空间”“楼层下的空间”关系</p>
        <el-button @click="jumpToAllRelation">立即跳转</el-button>
      </div>
    </div>
  </div>
</template>
<script>
// import noModelDialog from "@/components/business_space/dialogs/noModelDialog";
// import influenceDialog from "@/components/business_space/dialogs/influenceDialog";
// import detailsDialog from "@/components/business_space/dialogs/detailsDialog";
// import notRelated from "@/components/business_space/dialogs/notRelated";
// import facilityDialog from "@/components/business_space/dialogs/facilityDialog";
// import graphy from "@/components/business_space/graphy/business";
import graphy from "@/components/business_space/newGraphy/graphy";
import roomInFloorDialog from "@/components/business_space/newAddDialogs/roomInFloorDialog";
import handsontableMain from "@/components/business_space/business/handsontable";
import {
  // getDataDictionary,
  getrelationTypeProject,
  getSpaceBdFlCount,
  queryAllZoneType,
  queryBFloorWithState,
  zoneCount
} from "@/api/scan/request";
import { getDataDictionary } from "@/api/dict";

import floorCascader from "@/components/ledger/lib/floorCascader";
import { mapGetters } from "vuex";

export default {
  components: {
    graphy,
    handsontableMain,
    roomInFloorDialog,
    floorCascader,
  },
  computed: {
    ...mapGetters('layout', ['projectId', 'userId', 'secret'])
  },
  data() {
    return {
      floor: {
        influence: false, //受影响的业务空间弹窗
        details: false, //详情弹窗
        notRelated: false,
        facility: false
      },
      param: {
        ProjId: this.projectId, //项目id
        UserId: this.userId, //用户id
        secret: this.secret
      },
      buildMess: {
        name: "--",
        code: "",
        selectd: [],
        map: "",
        isChild: true,
        buildName: "--",
        buildCode: ""
      },
      isMyTab: 1,
      activeName: "0",
      tabsList: [],
      activeTabType: {
        "code": "GeneralZone",
        "name": "默认分区",
        "rel_type": "99"
      },
      options: [], //建筑楼层级联下拉
      floorToMap: {}, //楼层及其对应的模型图
      FloorMap: "", //当前选中的楼层对象
      zoneItemID: '',
      buildFloorSelectd: [''], //当前所选的建筑楼层
      childBackParam: {},
      needCalculate: false, // 关系是否需要计算
      mutiCount: 0,
      infectedTotal: 0,
      infectedCurfloor: 0,
      otherType: ''
    };
  },
  created() {
    this.getRelations()
    this.childBackParam = this.$route.params;
  },
  mounted() {
  },
  methods: {
    // 初始化
    init() {
      this.getTypes()
      this.getBuilding()
      this.getMutiCount()
      this.getInfected();
    },
    // 获取项目下建筑
    getBuilding() {
      queryBFloorWithState({}, res => {
        this.options = res.content.map(t => {
          t.value = t.id;
          t.label = t.localName || t.localId;
          t.count = 0;
          if (t.floor) {
            t.children = t.floor.map(item => {
              item.value = item.id;
              item.label = item.localName || item.name;
              item.buildName = t.localName || t.name;
              this.floorToMap[item.id] = item;
              if (item.count > 0) {
                t.count++;
              }
              return item;
            })
            t.children.unshift({ value: "all", label: "全部" }, { value: 'noKnow', label: "未明确楼层" })
          } else {
            t.children = []
          }
          return t;
        })
        this.options.unshift({ value: "all", label: "全部" }, { value: "noKnow", label: "未明确建筑" })
        if (this.childBackParam.buildFloorSelectd) {
          this.buildFloorSelectd = this.childBackParam.buildFloorSelectd;
        }
        if (this.childBackParam.zone) {
          this.changeCascader(this.buildFloorSelectd);
        }
      })
    },
    // 获取受影响统计
    getInfected(floor) {
      let pa = {
        filters: `ftate=1`
      }
      if (floor) {
        pa.filters += `;floorId="${floor}"`
      }
      zoneCount(pa, res => {
        if (floor) {
          this.infectedCurfloor = res.count
        } else {
          this.infectedTotal = res.count
        }
      })
    },
    // 切换平面图和列表
    changeRadio(val) {
      this.changeGraphyOrTable(val)
    },
    // 获取tabs的列表
    getTypes(floorid) {
      let pa = {
        // Cascade: [{ Name: 'zoneType' }]
      }
      if (floorid) {
        pa.floorId = floorid
      }
      queryAllZoneType(pa, res => {
        this.tabsList = res.content.map(t => {
          if (t.name == "元空间") {
            return undefined;
          }
          return t;
        }).filter(item => item);
        if (this.childBackParam.zone) {
          this.activeName = this.childBackParam.zone;
          this.buildFloorSelectd = this.childBackParam.buildFloorSelectd;
          this.isMyTab = this.childBackParam.isMyTab;
          this.otherType = this.childBackParam.otherType;
        } else if (this.activeName == '0') {
          this.activeName = 'GeneralZone';
        }
      })
    },
    // 获取多建筑楼层统计
    getMutiCount() {
      getSpaceBdFlCount({}, res => {
        this.mutiCount = res.count;
        if (this.mutiCount > 0) {
          this.getTips();
        }
      })
    },
    // 获取关系是否需要计算
    getRelations() {
      let pa = {
        Filters: `RelationType in ["bd2sp","fl2sp"];ComputationalState>1`
      }
      // 后台暂无接口提供 todo
      // getrelationTypeProject(pa, res => {
      //   if (res.Content.length) {
      //     this.needCalculate = true;
      //   } else {
      //     this.needCalculate = false;
      this.init()
      //   }
      // })
    },
    // 通过选中的tab-Code 获取选中的tab的所有数据
    getItemForType() {
      let data = {}
      this.tabsList.map(item => {
        if (item.code == this.activeName) {
          data.code = item.code;
          data.name = item.name;
        }
      })
      return data
    },
    // 点击tab
    tabClick(val) {
      this.changeGraphyOrTable(this.isMyTab)
    },
    //修改所选建筑楼层
    changeCascader(val) {
      this.buildFloorSelectd = val;
      this.$nextTick(() => {
        let node = this.$refs['cascaderAddr'].getCheckedNodes()
        let name = node[0].pathLabels
        name = name.join(' ')
        localStorage.setItem('buildingFloor', name)
      })
      // 如果选择的是全部或者未明确
      if (val.indexOf('noKnow') > -1 || val.indexOf('all') > -1) {
        this.getTypes()
        this.isMyTab = 2;
        this.FloorMap = {}
      } else {
        // 选择的是具体某个楼层
        if (!this.floorToMap[val[1]].infos || !this.floorToMap[val[1]].infos.floorMap) {
          this.isMyTab = 2;
        }
        this.getTypes(val[1]);
        this.FloorMap = this.floorToMap[val[1]];
      }
      this.changeGraphyOrTable(this.isMyTab)
    },

    // 判断切换至图还是表
    changeGraphyOrTable(num) {
      this.activeTabType = this.getItemForType()
      if (!this.buildFloorSelectd[0]) {
        this.$message.warning('请选择建筑楼层')
        return
      }
      if (num == 2) {
        this.initMessage();
      } else {
        this.getInfected(this.buildFloorSelectd[1]);
        /// 
        this.$refs.graphy.getData(this.buildFloorSelectd, this.FloorMap, this.activeTabType);
        this.childBackParam = {}
      }
    },
    // 触发获取表头-获取初始化信息点
    initMessage() {
      let params = {
        orders: "sort asc, name desc",
        pageNumber: 1,
        pageSize: 1000,
        type: this.activeName
      }
      getDataDictionary(params, res => {
        this.$refs.handsontable.getHeader(res.content, this.buildFloorSelectd);
      })
    },
    checkSpace(list, build, graphyId) {
      this.floor.notRelated = true;
      this.$refs.notRelated.getIdList(list, build, graphyId, this.activeTabType);
      this.$refs["graphy"].getHasSpace();
    },
    changeShow() {
      this.floor.dialogVisible = true;
      console.log(this.buildMess, 'buildMess')
    },
    //成功关联平面图
    createSuccess() {
      this.$refs["graphy"].getHasSpace();
      this.$refs["graphy"].clearDimension();
      this.floor.notRelated = false;
    },
    //成功删除业务空间
    delSuccess() {
      this.floor.details = false;
      this.$refs["graphy"].getHasSpace();
      this.$refs["graphy"].clearDimension();
    },
    //查看业务空间详情
    getBuinessDetails(list) {
      this.floor.details = true;
      this.$refs.details.getData(list, this.buildMess);
    },
    lookEqu(infos) {
      infos.id = infos.id
      infos.name = infos.localName
      this.floor.facility = true
      this.$refs.facility.getData(infos, this.buildMess)
    },
    copyID(val) {
      this.$refs.handsontable.zoneItemID = val;
    },
    // 空间属于多个建筑楼层
    getTips() {
      this.$refs.roomInFloorDialog.showDialog();
    },
    // 跳转至关系总览
    jumpToAllRelation() {
      this.$router.push({ name: 'overView' })
    },
    relaSuc() {
      this.init();
    },
    // 受影响业务空间确认成功回调
    updateStateSuc() {
      this.getBuilding()
      this.getTypes(this.buildFloorSelectd[1]);
      this.infectedTotal--;
      this.infectedCurfloor--;
    }
  },
  watch: {
    floor: {
      deep: true,
      handler: function () {
        if (this.floor.notRelated) {
          this.$refs["graphy"].clearDimension();
        }
      }
    },
    projectId() {
      this.init()
    }
  }
};
</script>

<style lang="less">
#businessSpace {
  position: relative;
  display: flex;
  flex-direction: column;

  .space-own-radio {
    .el-radio-button__inner {
      padding: 9px 21px;
    }
  }

  .el-dialog__body {
    max-height: 600px;
    overflow-y: auto;
  }

  .saga-title {
    height: 54px;
    background-color: #fff;
    font-size: 14px;
    position: relative;
    line-height: 54px;
    margin-bottom: 10px;
    border: 1px solid #dfe6ec;

    .saga-build-mess {
      // position: absolute;
      // left: 10px;
      width: 500px;
      margin-left: 10px;

      i {
        padding-right: 5px;
      }

      p {
        float: left;
      }

      .saga-btn {
        float: left;
        height: 40px;
        line-height: 40px;
        padding: 0 10px;
      }
    }

    .saga-build-tab {
      position: absolute;
      left: 50%;
      transform: translateX(-50%);

      .tab-main {
        float: left;
        width: 120px;
        padding: 0 5px;
        margin: 5px 0;
        border: 1px solid #ccc;
        background-color: #fff;
        height: 30px;
        box-sizing: border-box;
        text-align: center;
        cursor: pointer;
        overflow: hidden;

        i {
          font-size: 18px;
          padding-right: 10px;
          float: left;
          line-height: 30px;
          margin-left: 10px;
        }

        span {
          line-height: 30px;
          float: left;
        }
      }

      .tab-active {
        background-color: #409eff;
        color: #fff;
      }
    }

    .saga-build-tips {
      float: right;
      margin-right: 10px;
      font-size: 12px;
      color: #409eff;
      cursor: pointer;
    }
  }

  .saga-business-sapce-main {
    overflow: hidden;
    height: 100%;
    background: #fff;
    // padding: 10px;
    /deep/ .el-tabs__item.is-top {
      border-top: 2px solid transparent;

      &.is-active {
        border-top: 2px solid #409eff;
      }
    }

    .infectedTips {
      position: absolute;
      bottom: 0px;
      box-sizing: border-box;
      width: 100%;
      padding: 0 20px;
      line-height: 40px;
      background: #ec808d;
      color: #fff;
      z-index: 9;
    }
  }

  .spaceTypes {
    padding: 10px 10px 0;

    .types {
      float: left;
      width: 100%;
      // width: calc(100% - 200px);
    }

    .groupAdd {
      float: left;
      width: 200px;
      text-align: right;
      height: 40px;
      border-bottom: 1px solid #e4e7ed;
    }
  }
}
</style>
