<template>
  <el-dialog title="批量关联资产" :visible.sync="dialog.linkAssets" width="700px">
    <el-row>
      <span class="condition-title">设备类型：</span>
      <el-select v-model="deviceType" filterable size="small" @change="handleChangeDevice" style="width:350px;">
        <el-option  v-for="item in deviceTypeList" :key="item.Category" :label="item.CategoryName" :value="item.Category"></el-option>
      </el-select>
    </el-row>
    <el-row style="margin-top:30px;">
      <span class="condition-title">建筑楼层：</span>
      <el-cascader :options="bfoptions" v-model="buildFloor" filterable size="small" @change="handleChangeBf" style="width:350px;"></el-cascader>
    </el-row>
    <el-row style="margin-top:30px;"  v-show="spaceShow">
      <span class="condition-title">分区类型：</span>
      <el-select v-model="zone" filterable size="small" @change="handleChangeZone" style="width:350px;">
        <el-option  v-for="item in zoneList" :key="item.Code" :label="item.Name" :value="item.Code"></el-option>
      </el-select>
    </el-row>
    <el-row style="margin-top:30px;" v-show="spaceShow && zone != 'all' && zone != 'noKnow'">
      <span class="condition-title">空间实例：</span>
      <el-select v-model="space" multiple filterable collapse-tags style="width:350px;" placeholder="请选择">
        <el-option v-for="item in spaceList" :key="item.value" :label="item.label" :value="item.value">
        </el-option>
      </el-select>
    </el-row>
    <span slot="footer" class="dialog-footer">
      <el-button @click="handleClickClose">取 消</el-button>
      <el-button type="primary" @click="toLinkAssets">确 认</el-button>
    </span>
  </el-dialog>
</template>
<script>

import { floorQuery, buildingQuery, queryDictionaryHead, queryZone, TypePartsDie } from '@/api/scan/request'

import { mapGetters } from "vuex"
export default {
  props: {
    dialog: {
      type: Object,
      default: function () {
        return {
          linkAssets: false
        };
      }
    }
  },
  computed: {
    ...mapGetters("layout", ["projectId", "secret", "userId"])
  },
  data() {
    return {
      bfoptions: [], //建筑楼层列表
      buildFloor: ['all'], //选择的建筑楼层
      deviceTypeList: [], //未关联资产的设备或部件列表
      deviceType: '', //选择的设备类型
      zone: 'all', //空间分区
      zoneList: [], //空间分区列表
      spaceList: [], //空间实例列表
      space: [], //选择的空间实例
      spaceShow: false
    };
  },
  created() {
    this.getPartsDieType() //获取未关联资产的设备或部件类型
    this.getBuildFloorData() //获取建筑楼层数据
    this.getSpaceData() //获取分区类型数据
  },
  mounted() { },
  methods: {
    //获取未关联资产的设备或部件类型
    getPartsDieType() {
      TypePartsDie(res => {
        this.deviceTypeList = res.Content.filter(item => {
          return item.CategoryName
        })
      })
    },
    //获取建筑楼层数据
    getBuildFloorData() {
      let data, buildParams = {
        PageNumber: 1,
        PageSize: 1000,
        Projection: [
          "BuildID",
          "BuildLocalName"
        ]
      }, floorParams = {
        Orders: "FloorSequenceID desc",
        PageNumber: 1,
        PageSize: 1000,
        Projection: [
          "BuildID",
          "FloorID",
          "FloorLocalName",
          "FloorSequenceID"
        ]
      }
      let promise1 = new Promise((resolve, reject) => {
        buildingQuery(buildParams, res => {
          resolve(res)
        })
      })
      let promise2 = new Promise((resolve, reject) => {
        floorQuery(floorParams, res => {
          resolve(res)
        })
      })
      Promise.all([promise1, promise2]).then(values => {
        let builData = values[0].Content, floorData = values[1].Content
        data = builData.map(build => {
          return {
            value: build.BuildID,
            label: build.BuildLocalName
          }
        })
        data.unshift({
          value: "all",
          label: "全部"
        }, {
            value: "noKnow",
            label: "不在建筑内"
          })
        data.forEach(build => {
          floorData.forEach(floor => {
            if (build.value == floor.BuildID && floor.FloorID && floor.FloorLocalName) {
              if (build.children) {
                build.children.push({
                  value: floor.FloorID,
                  label: floor.FloorLocalName,
                  FloorSequenceID: floor.FloorSequenceID
                })
              } else {
                build.children = []
                build.children.push({
                  value: "all",
                  label: "全部"
                }, {
                    value: 'noKnow',
                    label: "不在楼层内"
                  }, {
                    value: floor.FloorID,
                    label: floor.FloorLocalName,
                    FloorSequenceID: floor.FloorSequenceID
                  })
              }
            }
          })
        })
        this.bfoptions = data
      })
    },
    //获取空间分区数据
    getSpaceData(){
      let params = {
        Filters: "parentId = 'Space'",
        PageNumber: 1,
        PageSize: 1000,
        Projection: [ "Code", "Name" ]
      }
      queryDictionaryHead(params, res => {
        this.zoneList = res.Content
        this.zoneList.unshift({
          Name: '全部',
          Code: 'all'
        })
        this.zoneList.push({
          Name: '不在任何业务空间内',
          Code: 'noKnow'
        })
      })
    },
    // 修改设备类型
    handleChangeDevice(val) {
      this.zoneListIsShow()
    },
    // 修改建筑楼层
    handleChangeBf(val) {
      this.zoneListIsShow()
    },
    //判断是否显示空间分区选择
    zoneListIsShow(){
      let lastVal = this.buildFloor.slice(-1)[0]
      if(!lastVal || lastVal == 'noKnow' || this.buildFloor[0] == 'all' || this.deviceType.length != 4) {
        this.spaceShow = false
      } else {
        this.spaceShow = true
      }
    },
    //修改分区类型
    handleChangeZone() {
      // 重置空间实例选择
      this.space = []
      this.spaceList = []

      this.handleChangeSpaceItem()
    },
    // 获取空间实例
    handleChangeSpaceItem() {
      if(this.zone != 'all' && this.zone != 'noKnow') {
        let nodes = []
        let recursionGetData = (pageNum, zone) => {
          pageNum = pageNum ? pageNum : 1
          let params = {
            zone: zone,
            data: {
              Orders: "CreateTime desc, RoomID asc",
              PageNumber: pageNum,
              PageSize: 1000,
              Projection: ["RoomID", "RoomName", "RoomLocalName", "CreateTime"]
            },
          }
          if(this.spaceShow) {
            if(this.buildFloor.length == 2 && this.buildFloor[1] != 'all') {
              params.data.Filters = `buildingId='${this.buildFloor[0]}';floorId='${this.buildFloor[1]}'`
            } else {
              params.data.Filters = `buildingId='${this.buildFloor[0]}'`
            }
          }
          queryZone(params, res => {
            nodes = nodes.concat(res.Content.map(item => ({
              value: item.RoomID,
              label: item.RoomLocalName?item.RoomLocalName:item.RoomName
            })))
            if (res.Total / (res.PageSize * res.PageNumber) > 1) {
              recursionGetData(res.PageNumber + 1, zone)
            } else {
              this.spaceList = nodes
            }
          })
        }
        recursionGetData(1, this.zone)
      }
    },
    // 点击取消关闭弹窗
    handleClickClose() {
      this.dialog.linkAssets = false
    },
    // 批量关联资产详情页
    toLinkAssets() {
      let query = {}
      // 校验必填项
      if(!this.deviceType) {
        this.$message.info('请选择设备类型！')
        return false
      } else if (!this.buildFloor.length) {
        this.$message.info('请选择建筑楼层！')
        return false
      }
      if(this.spaceShow) { //选择了空间
        if(this.zone == 'all'){//全部空间
          query = {
            deviceType: this.deviceType,
            buildFloor: this.buildFloor
          }
        } else if (this.zone == 'noKnow'){//不在空间内
          query = {
            deviceType: this.deviceType,
            buildFloor: this.buildFloor,
            spaceList: this.zone
          }
        } else {
          if(this.space.length){//选择了具体的空间实例
            query = {
              deviceType: this.deviceType,
              buildFloor: this.buildFloor,
              spaceList: this.space
            }
          } else {
            this.$message.info('请选择空间实例！')
            return false
          }
        }
      } else {
        query = {
          deviceType: this.deviceType,
          buildFloor: this.buildFloor
        }
      }
      this.$router.push({
        name: "batchlinkAssets",
        params: query
      })
    }
  },
  watch: {
    
  }
};
</script>

<style lang="less" scoped>
  .condition-title{
    width: 100px;
    display: inline-block;
    text-align: right;
    margin-left: 10px;
    margin-right: 12px;
    color: #999999;
    font-size: 14px;
    vertical-align: top;
  }
  /deep/ .el-dialog__body {
    max-height: 420px;
    overflow-y: auto;
  }
</style>
