<template>
  <el-drawer title="关联的业务空间" :visible.sync="drawer" :direction="direction" :before-close="handleClose" size="20%" custom-class="room-count">
    <div class="drawer-body" :style="{height:drawerBodyHeight}">
      <div class="default-zone zone">
        <p>默认业务空间</p>
        <div v-if="!(readonly&&!zoneList.GeneralZone.length)">
          <div v-for="(item,index) in zoneList.GeneralZone" :key="item.RoomID" class="zoneItem"
            :title="`${item.BuildLocalName}-${item.FloorLocalName}-${item.RoomLocalName || item.RoomName}`">
            {{item.BuildLocalName}}-{{item.FloorLocalName}}-{{item.RoomLocalName || item.RoomName}}
            <i size="mini" class="el-icon-delete" title="删除" @click="deleteZoneItem('GeneralZone',index)" v-if="!readonly"></i>
          </div>
          <div class="zoneItem" style="border:none;padding:0;" v-if="!readonly">
            <el-cascader placeholder="请选择" v-model="GeneralVal" :options="option.GeneralZone" :props="props" filterable @expand-change="expandChange"
              @change="change" style="width:100%;">
            </el-cascader>
          </div>
        </div>
        <div v-else class="center">
          <i class="icon-wushuju iconfont"></i>
          暂无数据
        </div>
      </div>
      <div class="tenant-zone zone">
        <p>租户业务空间</p>
        <div v-if="!(readonly&&!zoneList.TenantZone.length)">
          <div v-for="(item,index) in zoneList.TenantZone" :key="item.RoomID" class="zoneItem"
            :title="`${item.BuildLocalName}-${item.FloorLocalName}-${item.RoomLocalName || item.RoomName}`">
            {{item.BuildLocalName}}-{{item.FloorLocalName}}-{{item.RoomLocalName || item.RoomName}}
            <i size="mini" class="el-icon-delete" title="删除" @click="deleteZoneItem('TenantZone',index)" v-if="!readonly"></i>
          </div>
          <div class="zoneItem" style="border:none;padding:0;" v-if="!readonly">
            <el-cascader placeholder="请选择" v-model="TenantVal" :options="option.TenantZone" :props="props" filterable
              @expand-change="expandChangeTenantZone" @change="changeTenantZone" style="width:100%;">
            </el-cascader>
          </div>
        </div>
        <div v-else class="center">
          <i class="icon-wushuju iconfont"></i>
          暂无数据
        </div>
      </div>
    </div>
    <div class="btn" v-if="!readonly">
      <el-button type="primary" @click="save">保存</el-button>
    </div>
  </el-drawer>
</template>
<script>
import {
  tnRelateTenantZone, //关联租户空间
  tnRelateGeneralZone, //关联默认空间
  tnRelateOneZone,// 关联业务空间
  delTnRelateZone, // 删除关系业务空间与租户
  buildingQuery, //建筑查询
  queryParentZone, //业务空间查询GeneralZone-TenantZone
} from '@/api/scan/request'
import { mapGetters } from "vuex";
export default {
  data() {
    return {
      drawer: false,
      direction: 'rtl',
      zoneList: {
        GeneralZone: [],
        TenantZone: []
      },
      option: {
        GeneralZone: [],
        TenantZone: []
      },
      props: {
        children: 'Floor'
      },
      GeneralVal: [],
      TenantVal: [],
      curTenantId: '',
      drawerBodyHeight: ''
    }
  },
  props: {
    readonly: {
      default: true
    }
  },
  computed: {
    ...mapGetters("layout", ["projectId"])
  },
  watch: {
    projectId() {
      this.init();
    }
  },
  mounted() {
    this.drawerBodyHeight = document.body.clientHeight - 152 + 'px'
  },
  created() {
    this.init();
  },
  methods: {
    init() {
      this.getBuilding()
    },
    getBuilding() {
      let pa = {
        Cascade: [{ Name: 'floor', Orders: 'FloorSequenceID desc' }],
        Order: 'BuildLocalName asc'
      }
      buildingQuery(pa, res => {
        this.option.GeneralZone = res.Content.map(build => {
          build.value = build.BuildID;
          build.label = build.BuildLocalName;
          if (build.Floor) {
            build.Floor = build.Floor.map(floor => {
              floor.value = floor.FloorID;
              floor.label = floor.FloorLocalName;
              floor.Floor = [];
              return floor;
            });
            build.Floor.unshift({ value: 'noknowFloor', label: '未明确楼层', Floor: [] })
          }
          return build;
        })
        this.option.GeneralZone.unshift({ value: 'noknowBuild', label: '未明确建筑', Floor: [] });
        this.option.TenantZone = JSON.parse(JSON.stringify(this.option.GeneralZone));
      })
    },
    expandChange(val) {
      this.middleware(val, "GeneralZone")
    },
    expandChangeTenantZone(val) {
      this.middleware(val, "TenantZone")
    },
    middleware(val, type) {
      let filters = '';
      if (val[0] == 'noknowBuild') { //未明确建筑
        filters = `buildingId isNull`
        this.getZone(filters, type, val)
      } else if (val[1]) {
        if (val[1] == "noknowFloor") {
          filters = `buildingId='${val[0]}';floorId isNull`
        } else {
          filters = `buildingId='${val[0]}';floorId='${val[1]}'`
        }
        this.getZone(filters, type, val)
      }
    },
    getZone(filters, type, selected) {
      if (!filters) return;
      let params = {
        Cascade: [{ Name: 'building' }, { Name: 'floor' }],
        Filters: `${filters};ObjectType='${type}'`,
        Orders: "RoomID asc",
        PageSize: 1000,
        Projection: ["RoomID", "RoomLocalName", "RoomName", "ObjectType", "BuildingId", "FloorId"]
      }
      queryParentZone(params, res => {
        if (res.Content.length) {
          let tempArr = res.Content.map(t => {
            t.BuildLocalName = t.Building ? t.Building.BuildLocalName : '未明确建筑';
            t.FloorLocalName = t.Floor ? t.Floor.FloorLocalName : '未明确楼层';
            delete t.Floor;
            t.value = JSON.parse(JSON.stringify(t));
            t.label = t.RoomLocalName || t.RoomName;
            return t;
          })
          if (selected.length == 1) {
            this.option[type][0].Floor = tempArr;
          } else {
            for (let i = 0; i < this.option[type].length; i++) {
              if (this.option[type][i].value == selected[0]) {
                for (let j = 0; j < this.option[type][i].Floor.length; j++) {
                  if (this.option[type][i].Floor[j].value == selected[1]) {
                    this.option[type][i].Floor[j].Floor = tempArr;
                  }
                }
              }
            }
          }
        }
      })
    },
    change(val) {
      let zoneObj = val[val.length - 1];
      if (zoneObj.BuildLocalName == '未明确建筑') {
        zoneObj.FloorLocalName = ''
      }
      if (this.zoneList.GeneralZone.findIndex((item) => (item.RoomID == zoneObj.RoomID)) == -1) {
        this.zoneList.GeneralZone.push(zoneObj);
        this.relateGeneral('GeneralZone', zoneObj.RoomID)
      } else {
        this.$message.warning('已有业务空间，请重新选择')
      }
      this.GeneralVal = [];
    },
    changeTenantZone(val) {
      let zoneObj = val[val.length - 1];
      if (zoneObj.BuildLocalName == '未明确建筑') {
        zoneObj.FloorLocalName = ''
      }
      if (this.zoneList.TenantZone.findIndex((item) => (item.RoomID == zoneObj.RoomID)) == -1) {
        this.zoneList.TenantZone.push(zoneObj);
        this.relateGeneral('TenantZone', zoneObj.RoomID)
      } else {
        this.$message.warning('已有业务空间，请重新选择')
      }
      this.TenantVal = [];
    },
    showDrawer(tenant) {
      this.curTenantId = tenant.TenantID;
      if (tenant.ZoneGeneraltList) {
        this.zoneList.GeneralZone = tenant.ZoneGeneraltList.map(t => {
          if (t.Building) {
            t.BuildLocalName = t.Building.BuildLocalName || t.Building.BuildName;
          } else {
            t.BuildLocalName = '未明确建筑'
          }
          if (t.Floor) {
            t.FloorLocalName = t.Floor.FloorLocalName || t.Floor.FloorName;
          } else {
            t.FloorLocalName = '未明确楼层'
          }
          if (t.BuildLocalName == '未明确建筑') {
            t.FloorLocalName = ''
          }
          return t;
        });
      } else {
        this.zoneList.GeneralZone = [];
      }
      if (tenant.ZoneTenantList) {
        this.zoneList.TenantZone = tenant.ZoneTenantList.map(t => {
          if (t.Building) {
            t.BuildLocalName = t.Building.BuildLocalName || t.Building.BuildName;
          } else {
            t.BuildLocalName = '未明确建筑'
          }
          if (t.Floor) {
            t.FloorLocalName = t.Floor.FloorLocalName || t.Floor.FloorName;
          } else {
            t.FloorLocalName = '未明确楼层'
          }
          if (t.BuildLocalName == '未明确建筑') {
            t.FloorLocalName = ''
          }
          return t;
        });
      } else {
        this.zoneList.TenantZone = [];
      }
      this.drawer = true;
    },
    handleClose(done) {
      this.zoneList.GeneralZone = [];
      this.zoneList.GeneralZone = [];
      this.$emit('refresh');
      done();
    },
    // 删除
    deleteZoneItem(type, index) {
      let pa = {
        type: type,
        data: [
          {
            SpaceID: this.zoneList[type][index].RoomID,
            TenantID: this.curTenantId
          }
        ]
      }
      this.zoneList[type].splice(index, 1);
      delTnRelateZone(pa, res => { })
    },
    // 关联默认空间
    relateGeneral(type, SpaceId) {
      let pa = {
        type: type,
        data: {
          Content: [
            {
              SpaceId: SpaceId,
              TenantID: this.curTenantId
            }
          ]
        }
      }
      tnRelateOneZone(pa, res => { })
    },
    save() {
      this.$emit('refresh');
      this.drawer = false;
    }
  }
}
</script>
<style lang="less" scoped>
.room-count {
  .drawer-body {
    position: relative;
    padding: 10px 10px 30px;
    overflow-y: auto;
    .zone {
      padding: 6px 14px 22px;
      box-shadow: 0 0 3px #cacaca;
      p {
        margin-bottom: 4px;
      }
      .zoneItem {
        position: relative;
        padding: 2px 34px 2px 10px;
        border: 1px solid #ccc;
        border-radius: 4px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        i {
          position: absolute;
          right: 10px;
          top: 50%;
          transform: translateY(-50%);
          cursor: pointer;
        }
      }
      .zoneItem + .zoneItem {
        margin-top: 6px;
      }
    }
    .zone + .zone {
      margin-top: 10px;
    }
  }
  .btn {
    position: absolute;
    width: calc(100% - 20px);
    bottom: 20px;
    right: 20px;
    text-align: right;
  }
}
</style>