<template>
  <div class="my-2 mx-2">
    <el-cascader :options="optionsOne" size="small" :props="{ checkStrictly: true }" class="width-200-px my-2 mr-2"
      @change="checkNode" :clearable="true" ref="cascader">
    </el-cascader>
    <el-select v-model="search.buildingId" @change="searchRoom($event, 'unit')" size="small" clearable
      placeholder="请选择楼栋">
      <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
      </el-option>
    </el-select>
    <el-select v-model="search.unitId" @change="searchRoom($event, 'floor')" size="small" clearable placeholder="请选择单元">
      <el-option v-for="item in options2" :key="item.value" :label="item.label" :value="item.value">
      </el-option>
    </el-select>
    <el-select v-model="search.floorId" size="small" placeholder="请选择楼层" clearable>
      <el-option v-for="item in options3" :key="item.value" :label="item.label" :value="item.value">
      </el-option>
    </el-select>
    <el-input v-model="search.roomName" size="small" placeholder="房间名称" clearable
      class="width-200-px my-2 mr-2"></el-input>
    <el-button type="primary" size="small" @click="getBYRoom">搜 索</el-button>
    <el-button type="primary" size="small" @click="resetSearch">重置搜索</el-button>
    <!--      <el-button type="primary" size="small" @click="pushDeviceMethods">推送设备</el-button>-->
    <el-button type="primary" size="small" @click="byListRoomMethods">同步房源</el-button>

    <el-table :data="tableData" border stripe class="table" ref="multipleTable" height="600"
      header-cell-class-name="table-header" @selection-change="handleSelectionChange" empty-text="无">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="id" label="ID"></el-table-column>
      <el-table-column prop="roomId" label="roomID"></el-table-column>
      <el-table-column prop="did" label="did"></el-table-column>
      <el-table-column prop="storeName" label="门店名称"></el-table-column>
      <el-table-column prop="buildingName" label="楼栋名称"></el-table-column>
      <el-table-column prop="unitName" label="单元名称"></el-table-column>
      <el-table-column prop="floorName" label="楼层名称"></el-table-column>
      <el-table-column prop="roomName" label="房间名称"></el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <!--            <el-button type="text" @click="pushDeviceMethods(scope.$index, scope.row)">推送设备</el-button>-->
          <el-button type="text" @click="addDevice(scope.$index, scope.row)">绑定设备</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination @size-change="handleSizeChange" @current-change="handlePageChange" :current-page="pageNum"
        :page-sizes="[100, 200, 300, 400, 500]" :page-size="pageSize" :layout="paginationConfig" :total="pageTotal">
      </el-pagination>
    </div>

    <!--        添加设备弹窗-->
    <el-dialog title="编辑" :visible.sync="editVisible" width="30%">
      <el-form ref="form" :model="form" label-width="100px">
        <el-form-item label="设备">
          <el-autocomplete class="inline-input" v-model="form.did" :fetch-suggestions="querySearch" placeholder="请选择设备"
            @select="selectDevice"></el-autocomplete>
          <!-- <el-select v-model="form.did" size="middle" placeholder="请选择设备" @change="selectDevice">
            <el-option v-for="item in deviceList" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select> -->
        </el-form-item>
        <el-form-item label="选择房间">
          <el-cascader :options="options" size="middle" :props="{ checkStrictly: true }" @change="checkNodeOne"
            v-model="form.roomId" clearable>
          </el-cascader>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editVisible = false" size="small">取 消</el-button>
          <el-button type="primary" @click="addDeviceMethods" size="small">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { httpPost } from "../../api";
import utils from "../../utils/util";
export default {
  name: "byRoom",
  data() {
    return {
      manufacturerList: [{//设备类型选择
        "label": "GX1000_lock",
        "productID": "GX1000_LOCK",
        "value": 101
      }, {
        "label": "ZG_lock",
        "productID": "ZG_LOCK",
        "value": 201
      }, {
        "label": "ZG_ble_lock",
        "productID": "ZG_LOCK",
        "value": 221
      }, {
        "label": "YS_LOCK",
        "productID": "YS_LOCK",
        "value": 701
      }],
      editVisible: false,//添加设备弹窗显示控制
      paginationConfig: 'total, sizes, prev, pager, next, jumper',
      pageNum: 1,//页码
      pageSize: 100,//每页数量
      pageTotal: 0,//总数量
      tableData: [],//设备列表
      options: [],
      options2: [],
      options3: [],
      search: {
        deviceNum: '',//设备名称
        roomName: '',//房间名称
        storeId: 's202201280338',
        unitId: '',
        floorId: '',
        buildingId: ''
      },
      form: {//添加设备参数
        did: '',//设备id
        roomId: '',//房间id
      },
      deviceList: [],
      roomList: [],
      selctRoom: { roomId: '' },
      updateStstus: false,
      optionsOne: []
    }
  },
  mounted() {
    this.searchRoom('', 'building')
    this.getBYRoom()
    this.getDeviceList()
  },
  methods: {
    // 重置搜索
    resetSearch() {
      this.search = {
        deviceNum: '',//设备名称
        roomName: '',//房间名称
        storeId: 's202201280338',
        unitId: '',
        floorId: '',
        buildingId: ''
      }
    },
    querySearch(queryString, cb) {
      var deviceList = this.deviceList;
      var results = queryString ? deviceList.filter(this.createFilter(queryString)) : deviceList;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (deviceList) => {
        return (deviceList.value.toLowerCase().indexOf(queryString.toLowerCase()) !== -1);
      };
    },
    // 搜索房间
    searchRoom(e, key) {
      console.log(e, key)
      let data = {
        code: "by/roomField",
        data: {
          field: key
        }
      }
      httpPost(data, this.$api.sendCommand).then(res => {
        if (res.success) {
          if (key == 'store') {
            // res.data.map(li=>{
            //   li.label = li.storeName
            //   li.value = li.storeId
            // })
            // this.options = res.data
          } else if (key == 'building') {
            res.data.map(li => {
              li.label = li.buildingName
              li.value = li.buildingId
            })
            this.options = res.data
          } else if (key == 'unit') {
            res.data.map(li => {
              li.label = li.unitName
              li.value = li.unitId
            })
            this.options2 = res.data
          } else if (key == 'floor') {
            res.data.map(li => {
              li.label = li.floorName
              li.value = li.floorId
            })
            this.options3 = res.data
          }
        }
      })
    },
    // 同步房源
    byListRoomMethods() {
      let data = {
        code: "by/byListRoom",
        data: {
          pageNum: this.pageNum,
          pageSize: 500
        }
      }
      httpPost(data, this.$api.sendCommand).then(res => {
        if (res.success) {
          this.getBYRoom()
        }
      })
    },
    // 获取设备列表
    async getDeviceList() {
      let data = {
        code: "lockDevice/list",
        data: {
          pageNum: this.pageNum,
          pageSize: 500
        }
      }
      httpPost(data, this.$api.sendCommand).then(res => {
        if (res.success) {
          res.data.list.map(li => {
            li.label = li.deviceNum
            li.value = li.deviceNum
          })
          this.deviceList = res.data.list
        }
      })
    },
    // 选择绑定设备
    selectDevice(e) {
      // this.determineMethods('did',e)
    },
    // 绑定设备
    addDevice(index, row) {
      this.selctRoom = row
      this.editVisible = true
      this.determineMethods('roomId', row.roomId)
    },
    // 判断是否有绑定设备
    determineMethods(key, id) {
      let data = {
        code: "by/roomLockList",
        data: {
          pageNum: 1,
          pageSize: 500,
          para: {
            [key]: id
          }
        }
      }
      httpPost(data, this.$api.sendCommand).then(res => {
        if (res.success) {
          if (res.data.list.length > 0) {
            this.form.did = res.data.list[0].did
            this.form.roomId = res.data.list[0].roomId
            this.updateStstus = true
            this.$message.error('该房间/设备已绑定')
          }
        }
      })
    },
    // 获取泊寓房源
    async getBYRoom() {
      let content = []
      let results = await this.getRoomList();
      this.pageTotal = results.total
      this.tableData = results.list
      content = content.concat(results.list);
      if (results) {
        content = content.concat(results.list);
        // let total = results.total;//获取总条数
        // let page = Math.ceil(total / this.pageSize);//计算需要多少页
        // if (page > 1) {
        //   for (let i = 2; i <= page; i++) {
        //     this.pageNum = i;//更改页码
        //     let newResults = await this.getRoomList();
            //将第2、3、4...页数据放入content数组中
            // content = content.concat(newResults.list);
          // }
        // }
        await this.processingData(content)
      }
    },
    async getRoomList() {
      let para = {
        storeId: this.search.storeId,
        buildingId: this.search.buildingId,
        unitId: this.search.unitId,
        floorId: this.search.floorId,
        roomName: this.search.roomName,
      }
      let paraObject = utils.validObject(para)
      let data = {
        code: "by/listRoom",
        data: {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          para: paraObject
        }
      }
      return httpPost(data, this.$api.sendCommand).then(res => {
        if (res.success) {
          return res.data
        }
      })
    },
    async processingData(data) {
      this.roomList = data
      data.map(li => {
        li.label = li.roomName
        li.value = li.roomId
      })
      let arr = await this.unique(data, 'storeId')
      let arr1 = await this.unique(data, 'buildingId')
      let arr2 = await this.unique(data, 'unitId')
      let arr3 = await this.unique(data, 'floorId')
      let result = await this.mergeData(arr3, data, 'floorId', 'floorName')
      let result1 = await this.mergeData(arr2, result, 'unitId', 'unitName')
      let result2 = await this.mergeData(arr1, result1, 'buildingId', 'buildingName')
      let result3 = await this.mergeData(arr, result2, 'storeId', 'storeName')
      this.optionsOne = result3
    },
    async mergeData(arr, arr1, key, label) {
      let result = []
      arr.map(li => {
        let result1 = arr1.filter(item => item[key] == li[key])
        let obj = {
          label: li[label],
          value: li[key],
          buildingId: li.buildingId,
          buildingName: li.buildingName,
          floorId: li.floorId,
          floorName: li.floorName,
          roomId: li.roomId,
          roomName: li.roomName,
          storeId: li.storeId,
          storeName: li.storeName,
          unitId: li.unitId,
          unitName: li.unitName,
          children: result1
        }
        result.push(obj)
      })
      return result
    },
    async unique(arr, attrName) {
      const res = new Map();
      return arr.filter((a) => !res.has(a[attrName]) && res.set(a[attrName], 1));
    },
    async check(data, list) {
      data.forEach((item) => {
        if (item.children && item.children.length > 0) {
          this.check(item.children, list);
        } else {
          list.push(item);
        }
      });
      return list;
    },
    // 搜索选择房源
    async checkNode(e) {
      if (e.length < 4) {
        this.$message.error('请选择到楼层')
      }
      if (e.length == 4) {
        let tableData = []
        this.roomList.map(li => {
          if (li.floorId == e[e.length - 1]) {
            tableData.push(li)
          }
        })
        this.tableData = tableData
      }
      if (e.length == 5) {
        let tableData = []
        this.roomList.map(li => {
          if (li.roomId == e[e.length - 1]) {
            tableData.push(li)
          }
        })
        this.tableData = tableData
      }
    },
    // 添加设备选择房源
    checkNodeOne(e) {
      if (e[0].length < 5) {
        this.$message.error('请选择房间')
      } else {
        this.form.roomId = e[e.length - 1]
        // this.determineMethods('roomId',e[e.length-1])
      }
    },
    //   搜索
    searchMethods() {
    },
    //   推送设备
    pushDeviceMethods() { },
    //   添加设备
    addDeviceMethods() {
      if (this.form.did == '') {
        this.$message.error('请选择设备')
      } else if (this.form.roomId == '') {
        this.$message.error('请选择房间')
      } else {
        if (!this.updateStstus) {
          let data = {
            code: "by/addDevice",
            data: {
              did: this.form.did,
              roomId: this.form.roomId[0]
            }
          }
          httpPost(data, this.$api.sendCommand).then(res => {
            if (res.success) {
              this.editVisible = false
              this.$message.success('添加成功')
              this.form = {
                did: '',
                roomId: ''
              }
              this.updateStstus = false
            } else {
              let message = res.msg ? res.msg : res.message
              this.$message.error(`更新失败: ${message}`)
            }
          })
        } else {
          let data = {
            code: "by/updateDevice",
            data: {
              did: this.form.did,
              roomId: this.form.roomId
            }
          }
          httpPost(data, this.$api.sendCommand).then(res => {
            if (res.success) {
              this.editVisible = false
              this.$message.success('更新成功')
              this.form = {
                did: '',
                roomId: ''
              }
              this.updateStstus = false
            } else {
              let message = res.msg ? res.msg : res.message
              this.$message.error(`更新失败: ${message}`)
            }
          })
        }
      }
    },
    //   选择设备列表
    handleSelectionChange(val) {
      console.log(val)
    },
    // 设备每页数量
    handleSizeChange(val) {
      this.pageSize = val
      this.getBYRoom()
    },
    // 选择页码
    handlePageChange(val) {
      this.pageNum = val
      this.getBYRoom()
    }
  }
}
</script>

<style scoped>
.width-200-px {
  width: 200px;
}
</style>
