<template>
  <el-dialog title="批量关联资产" :visible.sync="dialog.linkAssets" @open="handleOpenReset" 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.classCode" :label="item.name"
                   :value="item.classCode"></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 { zoneQuery, TypePartsDie } from '@/api/scan/request'
import { queryPhysicsAllType } from '@/api/dict'
import { buildingQuery } from '@/api/object/build'
import { floorQuery } from '@/api/object/floor'

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: {
    //打开弹窗回调,初始化选择
    handleOpenReset() {
      this.deviceType = ''
      this.buildFloor = ['all']
      this.zone = 'all'
      this.space = []
      this.spaceShow = false
    },
    //获取未关联资产的设备或部件类型
    getPartsDieType() {
      let _this = this
      TypePartsDie(res => {
        _this.deviceTypeList = res.content
      })
    },
    //获取建筑楼层数据
    getBuildFloorData() {
      let data, buildParams = {
        pageNumber: 1,
        pageSize: 1000,
        orders: "localName asc",
        projection: [
          "id",
          "localName"
        ]
      }, floorParams = {
        orders: "floorSequenceId desc",
        pageNumber: 1,
        pageSize: 1000,
        projection: [
          "buildingId",
          "id",
          "localName",
          "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.id,
            label: build.localName
          }
        })
        data.unshift({
          value: "all",
          label: "全部"
        }, {
          value: "noKnow",
          label: "不在建筑内"
        })
        data.forEach(build => {
          floorData.forEach(floor => {
            if (build.value == floor.buildingId && floor.id && floor.localName) {
              if (build.children) {
                build.children.push({
                  value: floor.id,
                  label: floor.localName,
                  FloorSequenceID: floor.floorSequenceId
                })
              } else {
                build.children = []
                build.children.push({
                  value: "all",
                  label: "全部"
                }, {
                  value: 'noKnow',
                  label: "不在楼层内"
                }, {
                  value: floor.id,
                  label: floor.localName,
                  FloorSequenceID: floor.floorSequenceId
                })
              }
            }
          })
        })
        this.bfoptions = data
      })
    },
    //获取空间分区数据
    getSpaceData() {
      let params = {
        type: "space"
      }
      queryPhysicsAllType(params, res => {
        this.zoneList = res.content.filter(item => {
          if (item.name !== item.aliasName) {
            item.name = `${item.name}(${item.aliasName})`
          }
          if (item.code != 'Ispace') {
            return item
          }
        })
        this.zoneList.unshift({
          name: '全部',
          code: 'all'
        })
        this.zoneList.push({
          name: '不在任何业务空间内',
          code: 'noKnow'
        })
      })
    },
    // 修改设备类型
    handleChangeDevice(val) {
      this.zoneListIsShow()
    },
    // 修改建筑楼层
    handleChangeBf(val) {
      this.zoneListIsShow()
      // 重置空间实例选择
      this.space = []
      this.spaceList = []
      this.handleChangeSpaceItem()
    },
    //判断是否显示空间分区选择
    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 = {
            Orders: "CreateTime desc, id asc",
            PageNumber: pageNum,
            PageSize: 1000,
            Projection: ["id", "RoomName", "RoomLocalName", "CreateTime"],
            ZoneType: zone
          }
          if (this.spaceShow) {
            if (this.buildFloor.length == 2 && this.buildFloor[1] != 'all') {
              pa.BuildingId = this.buildFloor[0];
              pa.FloorId = this.buildFloor[1];
            } else {
              pa.BuildingId = this.buildFloor[0];
            }
          }
          zoneQuery(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.space.length) {//选择了具体的空间实例
            query = {
              deviceType: this.deviceType,
              buildFloor: this.buildFloor,
              spaceList: this.space
            }
          } else {
            query = {
              deviceType: this.deviceType,
              buildFloor: this.buildFloor,
              spaceList: this.zone //(包含具体的业务空间分区和不在任何分区两种情况)
            }
          }
        }
      } 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>
