<template>
  <div id="relatedSpace">
    <div class="condition">
      <div class="header">
        <el-button style="float:left;" size="small" type="default" icon="el-icon-back" @click="goBack"></el-button>
        <div class="edit-tool" v-if="!(cenoteObj.onlyRead == 'true')">
          <el-button v-if="isMyTab == 2" size="small" style="float:right" @click="dialogVisible = true">添加</el-button>
          <div v-else>
            <el-button v-show="!isEdit" @click="changeEditType" size="small" style="float:right">编辑</el-button>
            <el-button v-show="isEdit" size="small" @click="saveEdit" style="float:right">保存</el-button>
            <el-button v-show="isEdit" size="small" @click="cancelEdit" style="float:right">取消</el-button>
          </div>
          <addSpaceDialog :dialogVisible.sync="dialogVisible" ref="addSpaceDialog" @refresh="refresh"
                          :params="cenoteObj" :spaceType="spaceType"
                          :floorType="floorType"></addSpaceDialog>
        </div>
        <el-badge :is-dot="showSpaceDot" style="margin-left:15px;">
          <label style="line-height:32px;">业务空间类型:</label>
          <el-cascader v-model="space" placeholder="请选择业务空间" :props="{value:'code',label:'name',children:'zoneType'}"
                       :options="spaceList"
                       @change="changeSpace" style="margin-left:15px;"></el-cascader>
        </el-badge>
      </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 v-show="isMyTab == 1" class="data-item">
        <el-badge :is-dot="showBuildDot">
          <label style="line-height:32px;padding: 0 10px;">所属建筑:</label>
          <el-select v-model="building" placeholder="请选择建筑" @change="changeBuilding" v-loading="buildingLoading">
            <el-option v-for="item in buildingList" :key="item.value"
                       :label="item.localName || item.name"
                       :value="item.id"></el-option>
          </el-select>
        </el-badge>
        <el-switch v-if="!(cenoteObj.onlyRead == 'true')" style="margin-left:15px;" v-model="isAI" @change="handleChangeAI"
                   active-text="打开AI">
        </el-switch>
        <div style="height:calc(100% - 42px);margin:10px 0 0 0;width:100%;">
          <el-row
            style="height:100%;margin:0;width:55%;position:relative;display:inline-block;border:1px solid #e4e4e4;">
            <el-col :span="4" style="height:100%;border-right:1px solid #e4e4e4;">
              <el-scrollbar style="height:100%;">
                <div class="floor" style="height:100%;text-align:center;">
                  <span class="floor-item" style="border-bottom:1px solid #e4e4e4;">楼 层</span>
                  <div v-if="building" v-loading="buildingLoading">
                    <span class="floor-item" @click="changeFloor(item)"
                          :class="{floorItemChoose:(item.id == floor)}"
                          v-for="item in buildingObj.floor" :key="item.id">{{ item.localName }}</span>
                  </div>
                </div>
              </el-scrollbar>
            </el-col>
            <el-col :span="20" style="height:100%;position:relative;">
              <cenote-graphy ref="cenotegraphy" :buildFloorName="buildFloorName"></cenote-graphy>
            </el-col>
          </el-row>
          <div class="elevation-box">
            <elevation-map ref="elevationMap" :onlyRead="cenoteObj.onlyRead=='true'" :isEdit="isEdit" :isAI="isAI"
                           @elevationChecked="handleCheckedSpace"
                           @elevationUncheck="handleUncheckSpace"
                           :params="{buildingId: building, objectType: ObjectType, shaftId: $route.query.ShaftId}">
            </elevation-map>
          </div>
        </div>

      </div>
      <div v-show="isMyTab == 2" class="data-item">
        <related-spaceList :space="ObjectType" :buildingList="buildingList" :spaceType="spaceType"
                           :floorType="floorType" ref="relatedSpacelist">
        </related-spaceList>
      </div>
    </div>
  </div>
</template>

<script>
import spaceSelect from "@/components/ledger/lib/spaceSelect";
import relatedSpaceList from "@/components/ledger/cenote/relatedSpaceList";
import elevationMap from "@/components/ledger/cenote/elevationMap";
import addSpaceDialog from '@/components/ledger/cenote/dialog/addSpaceDialog';
import {
  queryAllZoneType,
  shaftSpaceTypeQuery,
  shaftSpaceBuildingQuery,
  verticalSpace
} from '@/api/scan/request';
import cenoteGraphy from '@/components/ledger/lib/cenoteGraphy'
import { mapGetters } from 'vuex'
import { buildingQuery } from '@/api/object/build';

export default {
  data() {
    return {
      isMyTab: 1,//默认平面图
      isEdit: false,//是否正在编辑
      building: '',//当前建筑id
      buildingObj: {},//当前建筑obj
      buildingList: [],
      space: [],//当前业务空间
      ObjectType: '',//业务空间code
      spaceList: [],//空间list
      floor: '',//当前楼层
      dialogVisible: false,//添加空间弹窗
      spaceType: {},//空间种类
      floorType: {},//子组件楼层信息
      buildingLoading: false,//左侧列表加载
      // showSpaceDot: false,//空间提示红点
      // showBuildDot: false,//楼层提示红点
      isAI: true,//是否打开AI
      buildFloorName: '', //建筑楼层名称
    }
  },
  computed: {
    cenoteObj() {
      return this.$route.query;
    },
    showSpaceDot() {
      return this.spaceList.length > 1 && this.cenoteObj.onlyRead == 'true' ? true : false;
    },
    showBuildDot() {
      return this.buildingList.length > 1 && this.cenoteObj.onlyRead == 'true' ? true : false;
    },
    ...mapGetters("layout", ["projectId"])
  },
  props: {},
  components: {
    spaceSelect,
    relatedSpaceList,
    addSpaceDialog,
    cenoteGraphy,
    elevationMap
  },
  created() {
    this.isAI = this.$route.query.onlyRead == 'true' ? false : true;
    this.getSpaceData();
  },
  methods: {
    //获取空间信息
    getSpaceData() {
      if (this.cenoteObj.onlyRead == 'true') {
        let pa = {
          shaftId: this.$route.query.ShaftId
        }
        shaftSpaceTypeQuery(pa, res => {
          this.spaceList = res.content.map(item => {
            return { code: item.objectType, name: item.objectTypeName };
          });
          this.showDefaultSpace();
        });
      } else {
        let params1 = {},
        //Cascade: [{ Name: 'zoneType', Filters: `ProjectId='${this.projectId}'` }]
            params2 = {shaftId: this.$route.query.ShaftId};
        let promise1 = new Promise((resolve, reject) => {
          queryAllZoneType(params1, res => {
            resolve(res)
          })
        })
        let promise2 = new Promise((resolve, reject) => {
          shaftSpaceTypeQuery(params2, res => {
            resolve(res)
          })
        })
        Promise.all([promise1, promise2]).then(values => {
          let val1 = values[0], val2 = values[1]
          this.spaceList = val1.content.map(t => {
            if (t.name != "元空间") {
              this.spaceType[t.code] = t.name;
            }
            return t;
          });
          if (val2.content.length) {
            this.space = [val2.content[0].objectType];
          } else {
            this.space = this.spaceList.find((item) => {
              return item.code == "GeneralZone"
            }) ? ["GeneralZone"] : [this.spaceList[0].code];
          }
          this.ObjectType = this.space[0];
          //加载楼层信息
          this.loadBuildingData();
        })
      }
    },
    //默认显示默认分区，无默认分区显示第一个分区
    showDefaultSpace() {
      if (this.spaceList.length && this.cenoteObj.onlyRead == 'true') {
        this.space = this.spaceList.find((item) => {
          return item.Code == "GeneralZone"
        }) ? ["GeneralZone"] : [this.spaceList[0].Code];
        this.ObjectType = this.space[0];
      }
      //处理空间类型
      this.spaceList.map(item => {
        if (item.Name != "元空间") {
          this.spaceType[item.Code] = item.Name;
        }
      });
      //加载楼层信息
      this.loadBuildingData();
    },
    //获取楼层信息
    loadBuildingData() {
      if (this.cenoteObj.onlyRead == 'true') {
        let param = {
          ShaftId: this.$route.query.ShaftId,
          ObjectType: this.ObjectType
        };
        this.buildingLoading = true;
        shaftSpaceBuildingQuery(param, res => {
          this.buildingLoading = false;
          this.buildingList = res.content;
          this.buildingList = this.buildingList.map(item => {
						debugger
            item.floor = item.floorList;
            item.BuildID = item.BuildingId;
            item.BuildLocalName = item.BuildingLocalName;
            if (item.Floor) {
              item.Floor = item.Floor.map(item => {
                item.FloorID = item.FloorId;
                item.FloorLocalName = item.FloorLocalName;
                return item;
              })
            }
            return item;
          })
          this.handleBuildingData();
        });
      } else {
        let param = {
          cascade: [
            {
              name: "floor",
              orders: "floorSequenceId desc, name asc",
            }
          ]
        };
        buildingQuery(param, res => {
          this.buildingList = res.content;
          this.handleBuildingData();
        });
      }
    },
    //处理建筑楼层数据
    handleBuildingData() {
      if (this.isMyTab == 2) {
        this.$refs.relatedSpacelist.setFloorData(this.buildingList);
      }
      if (this.buildingList.length) {
        this.changeBuilding(this.buildingList[0].id);
      } else {
        this.buildingList = [];
        this.building = '';
        this.floor = '';
      }
      this.buildingList.map(item => {
        if (item.id && item.localName) {
          this.floorType[item.id] = item.localName;
          if (item.floor instanceof Array) {
            item.floor.map(f => {
              if (f.id && f.localName) {
                this.floorType[f.id] = f.localName;
              }
            })
          }
        }
      });
    },
    //计算 和当前竖井有关联的空间的垂直交通关系
    calculateRelation() {
      if (this.isAI && this.building && this.ObjectType && this.cenoteObj.ShaftId) {
        let params = {
          buildingId: this.building,
          objectType: this.ObjectType,
          shaftId: this.cenoteObj.ShaftId,
        }
        verticalSpace(params, res => {
          console.log(res)
        })
      }
    },
    //改变AI开关
    handleChangeAI(val) {
      this.calculateRelation();
    },
    //更改业务空间类型
    changeSpace(val) {
      this.ObjectType = val[0];
      this.floor = '';
      this.buildingList = [];
      this.building = '';
      this.changeFloor({ id: '' });
      this.loadBuildingData();
      this.calculateRelation();
    },
    //更换建筑
    changeBuilding(bid) {
      this.buildingObj = {};
      this.building = bid;
      this.buildingList.map(item => {
        if (item.id == bid) {
          this.buildingObj = item;
          if (item.floor && item.floor.length) {
            this.changeFloor(item.floor[0]);
          }
        }
      })
      this.calculateRelation();
    },
    //更换楼层
    changeFloor(floorObj) {
      this.buildFloorName = `${this.buildingObj.localName || this.buildingObj.name || ""}-${floorObj.localName || floorObj.name || ""}`
      this.floor = floorObj.id;
      let buildfloor = [this.building, floorObj.id]
      this.$refs.cenotegraphy.getFloorMap(buildfloor, this.ObjectType)
    },
    //平面图选中空间,立面图对应选中
    handleCheckedSpace(RoomID) {
      this.$refs.cenotegraphy.canvasChecked(RoomID);
    },
    //平面图取消选中空间,立面图对应取消选中
    handleUncheckSpace(RoomID) {
      this.$refs.cenotegraphy.canvasUncheck(RoomID);
    },
    // 编辑
    changeEditType() {
      this.isEdit = true;
      this.$refs.cenotegraphy.edit();
    },
    //取消编辑
    cancelEdit() {
      this.isEdit = false;
      this.$refs.cenotegraphy.cancelEdit();
    },
    //保存编辑
    saveEdit() {
      this.isEdit = false;
      this.$refs.cenotegraphy.saveEdit();
      // 走保存接口，然后回调渲染
      this.$refs.elevationMap.savaEdit();
    },
    //更换列表或平面图
    changeRadio(val) {
      if (val == 2) {
        this.spaceList.unshift({ code: '', name: '全部' });
      }
      if (val == 1) {
        if (this.spaceList.length > 0) {
          this.spaceList.shift();
        }
      }
      if (this.spaceList.length) {
        this.changeSpace(this.spaceList[0].code);
        this.space = [this.spaceList[0].code]
      }
      this.isMyTab = val;
    },
    //返回
    goBack() {
      this.$router.push({
        name: 'cenotelist'
      })
    },
    //更新
    refresh() {
      this.$refs.relatedSpacelist.getSpaceList();
      this.dialogVisible = false;
    }
  },
  watch: {
    isEdit: {
      handler(val) {
        // this.$refs.cenotegraphy.setSelectAble(val);
      }
    },
    projectId: {
      handler(val) {
        this.goBack();
      }
    }
  }
}
</script>

<style lang="less" scoped>
.condition {
  position: relative;
  padding: 10px;
  display: flex;
  height: calc(100% - 22px);
  flex-direction: column;
  border: 1px solid #dfe6ec;
  background: #fff;

  .header {
    padding-bottom: 10px;
    border-bottom: 1px solid #e4e4e4;

    span {
      line-height: 33px;
      margin-left: 15px;
    }

    /deep/ .buildFloor {
      line-height: 32px;
    }
  }

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

      /deep/ .el-tabs__item.is-top {
        border-top: 2px solid transparent;

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

    .deleBtn {
      float: left;
      width: 200px;
      text-align: right;
      height: 40px;
      border-bottom: 1px solid #e4e7ed;
    }
  }
}

.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;
  }
}

.data-item {
  height: calc(100% - 44px);
  padding: 10px 0px;
  box-sizing: border-box;

  /deep/ .is-horizontal {
    display: none;
  }

  .elevation-box {
    height: 100%;
    width: calc(45% - 14px);
    margin-left: 10px;
    display: inline-block;
    box-sizing: border-box;
    border: 1px solid #e4e4e4;
    overflow: auto;
  }
}

.floor-item {
  padding: 10px 10px;
  display: block;
  margin: 0px;
  cursor: pointer;
}

.floorItemChoose {
  background: #e4e4e4;
}

/deep/ .el-scrollbar__wrap {
  overflow-x: hidden;
}
</style>
