<template>
  <div>
    <div class="container">
      <div class="handle-box">
        <selectoption></selectoption>
        <el-cascader :options="options" size="small" :props="{ checkStrictly: true }" v-model="query.operateName"
          @change="checkNode" :clearable="true">
        </el-cascader>
        <el-input v-model="query.cardName" size="small" placeholder="账号" class="handle-input mr10 wRem3" :clearable="true">
        </el-input>
        <el-date-picker v-model="query.datePicker[0]" class="wRem3" size="small" type="datetime" placeholder="选择开始日期时间"
          default-time="00:00:00">
        </el-date-picker>
        <el-date-picker v-model="query.datePicker[1]" class="wRem3" size="small" type="datetime" placeholder="选择结束日期时间"
          default-time="00:00:00">
        </el-date-picker>
        <el-select size="small" v-model="query.openType" placeholder="开门方式" clearable class="handle-select mr10">
          <el-option key="5" label="蓝牙开锁" :value="5"></el-option>
          <el-option key="6" label="NB开锁" :value="6"></el-option>
        </el-select>
        <el-button size="small" type="primary" icon="el-icon-search" @click="handleSearch" style="background: #FA8E00; border: none;">搜索</el-button>
        <el-button size="small" type="primary" icon="el-icon-search" @click="resetAll" style="background: #FA8E00; border: none;">重置</el-button>
        <el-button size="small" type="primary" icon="el-icon-download" @click="exportFun" style="background: #FA8E00; border: none;">导出</el-button>
      </div>
      <el-table :data="logList" stripe style="width: 100%" height="500">
        <el-table-column prop="deviceNum" label="设备号" width="250">
        </el-table-column>
        <el-table-column prop="name" label="账号" width="180">
        </el-table-column>
        <el-table-column prop="roomName" label="房间号"> </el-table-column>
        <el-table-column label="开锁方式" prop="openType"></el-table-column>
        <el-table-column prop="createAt" label="开锁时间" width="250">
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination background layout="total,sizes, prev, pager, next" :current-page="pageNum"
          :page-size="pageSize" :total="pageTotal" @current-change="handlePageChange"  @size-change="handleSizeChange"></el-pagination>
      </div>
    </div>
    <el-dialog title="选择房间" :visible.sync="openRoom" width="30%" :before-close="handleClose">
      <el-tree :data="options" show-checkbox node-key="id" ref="tree" @check-change="handleCheckChange"
        :props="defaultProps"></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="openRoom = false">取 消</el-button>
        <el-button type="primary" @click="handleSearch">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import {
    httpGet,
    httpPost,
    download
  } from "../api";
  import {
    getLocalTime,
    ztreeToElementTree,
    ztreeToElementTree3,
    uniqueArray,
  } from "../utils/index";
  import XLSX from "xlsx";
  import utils from "../utils/util.js";
  import moment from "moment"
  export default {
    inject: ['reload'],
    name: "warningLog",
    data() {
      return {
        pageSize:20,
        pageNum:1,
        defaultProps: {
          children: "children",
          label: "name",
        },
        config: {
          header: ["设备号", "开锁方式", "开锁时间"],
          data: [
            ["", "", "", ""]
          ],
          rowNum: 7, //表格行数
          headerHeight: 35,
          headerBGC: "#0f1325", //表头
          oddRowBGC: "#0f1325", //奇数行
          evenRowBGC: "#171c33", //偶数行
          index: false,
          columnWidth: [200, 200, 200, 200],
          align: ["center"],
        },
        query: {
          openType: 5,
          operateName: "",
          operModul: "",
          datePicker: ['', ''],
          cardName:""
        },
        query1: {
          openType: "",
          operateName: "",
          operModul: "",
        },
        activeName: "first",
        tableData: [],
        tableData1: [],
        multipleSelection: [],
        delList: [],
        editVisible: false,
        pageTotal: 0,
        pageTotal1: 0,
        form: {},
        idx: -1,
        id: -1,
        logList: [],
        options: [],
        selectRoomId: "",
        openRoom: false,
        selectkey: [],
        userInfo: {
          type: ''
        },
        checkNodeId:[]
      };
    },
    beforeCreate() {
      // var tenantId = JSON.parse(localStorage.getItem('tenantId'))
      // if (tenantId == 400) {
      //   this.$store.commit('defaultsettenantid')
      // }
    },
    created() {
      this.userInfo = JSON.parse(localStorage.getItem('info'))
      var data = {
        package: 1,
        q: JSON.stringify({
          lockType: 1
        })
      }
      httpPost(data, this.$api.getDeviceItems).then((res) => {
        this.$store.commit("deviceFun", res.data.list);
      });
      this.getalllist();
      // this.selectoption=JSON.parse(localStorage.getItem('selectoption'))
      // this.selectoptionValue=localStorage.getItem('tenantId')
    },
    mounted() {
      // this.getlockAlert();
      this.getcard();
    },
    methods: {
      // 选择房源
      checkNode(e) {
        this.checkNodeId = e
        var options = this.options
        var arr = this.getId(options, e[e.length - 1])
        var listarr = [arr[0]]
        var obj = this.getNodeId(listarr)
        this.checkNodeId = obj
      },
      getParentId(list, id) {
        for (let i in list) {
          if (list[i].id == id) {
            return [list[i]]
          }
          if (list[i].children) {
            let node = this.getParentId(list[i].children, id);
            if (node !== undefined) {
              return node.concat(list[i])
            }
          }
        }
      },
      getId(list, id) {
        for (let i in list) {
          if (list[i].id == id) {
            return [list[i]]
          }
          if (list[i].children) {
            let node = this.getParentId(list[i].children, id);
            if (node !== undefined) {
              return node;
            }
          }
        }
      },
      getNodeId(list, newNodeId = []) {
        for (let i in list) {
          newNodeId.push(list[i].id)
          if (list[i].children) {
            this.getNodeId(list[i].children, newNodeId);
          }
        }
        return newNodeId;
      },
      resetAll() {
        this.query = {
          openType: 5,
          operateName: "",
          operModul: "",
          datePicker: ['', ''],
          cardName:""
        }
        this.handleSearch()
      },
      // selectTenantId(e) {
      //   localStorage.setItem('tenantId', e)
      //   this.reload()
      // },
      exportFun() {
        var data = {
          orderBy: "open_time desc",
          q: JSON.stringify({
            roomId: this.selectRoomId,
            openType: this.query.openType,
          }),
        };
        download(data, this.$api.export).then((res) => {
          const link = document.createElement("a");
          let blob = new Blob([res], {
            type: "application/vnd.ms-excel"
          });
          var objectUrl = URL.createObjectURL(blob);
          link.href = objectUrl;
          link.download = "开锁记录.xlsx";
          link.click();
          URL.revokeObjectURL(objectUrl);
        });
      },
      handleCheckChange(data, checked, node) {
        if (checked) {
          this.selectRoomId = data.id;
          this.query.operateName = data.name
          this.$refs.tree.setCheckedKeys([data.id]);
        } else {
          if (this.checkedId == data.id) {
            this.$refs.tree.setCheckedKeys([data.id]);
          }
        }
      },
      handleClose(done) {
        this.openRoom = false;
      },
      // 打开房间选择列表
      openRoomlist() {
        this.openRoom = true;
      },
      handleChange(value) {
        console.log(value);
        this.selectRoomId = value[value.length - 1];
      },
      //获取房源筛选列表
      getalllist() {
        var data = {};
        httpGet(data, this.$api.getTree).then((res) => {
          var list = res.data.sort((pre, cur) => pre.id - cur.id)
          var array = uniqueArray(list, "id");
          this.options = ztreeToElementTree(array, {});
        });
      },
      timestampToTime(cjsj) {
        if (cjsj.toString().length == 10) {
          cjsj = cjsj * 1000;
        }
        var date = new Date(cjsj); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
        var Y = date.getFullYear() + "-";
        var M =
          (date.getMonth() + 1 < 10 ?
            "0" + (date.getMonth() + 1) :
            date.getMonth() + 1) + "-";
        var D =
          (date.getDate() < 10 ? "0" + date.getDate() : date.getDate()) + " ";
        var h =
          (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":";
        var m =
          (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()) +
          ":";
        var s =
          date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
        return Y + M + D + h + m + s;
      },
      getOpenType(openType) {
        var str = "";
        switch (openType) {
          case 1:
            str = "指纹开锁";
            break;
          case 2:
            str = "数字键盘开锁";
            break;
          case 3:
            str = "NFC开锁";
            break;
          case 4:
            str = "机械钥匙开锁";
            break;
          case 5:
            str = "蓝牙开锁";
            break;
          case 6:
            str = "NB开锁";
            break;
          case 7:
            str = "身份证";
            break;
          case 8:
            str = "无线钥匙开锁";
            break;
          case 9:
            str = "人脸开锁";
            break;
          case 10:
            str = "离线卡开锁";
            break;
          default:
            str = "其它开锁";
            break;
        }
        return str;
      },

      screenRoomName(id) {
          var name = utils.findIndexArray(this.options, id, [])
          var path = ''
          if (name) {
            path = name.join('/')
          }
          return path
      },
      screenRoomNameOne(imei){
         return this.$store.state.deviceList.filter(item=>item.imei==imei)[0]
      },
      getcard() {
        let operUrl="",q={}
        if(this.query.openType==5){
          operUrl="/v1/device/send/bleCommand"
          var roomid=this.checkNodeId.length>0?this.checkNodeId.splice(this.checkNodeId.length-1,1):[]
          q= this.searchParaProcess({
            operRequ: "bleUnlockRecord",
            roomIds:roomid,
            startTime: this.query.datePicker[0],
            endTime:this.query.datePicker[1],
            // operUrl:operUrl,
            request:[this.query.cardName],
          })
        }else if(this.query.openType==6){
          operUrl="/v1/device/isp/openLock"
          var roomid=this.checkNodeId.length>0?this.checkNodeId.splice(this.checkNodeId.length-1,1):[]
          q= this.searchParaProcess({
            // openType: this.query.openType,
            roomIds:roomid,
            startTime: this.query.datePicker[0],
            endTime:this.query.datePicker[1],
            operUrl:operUrl,
            request:[this.query.cardName],
          })
        }
        var data1 = {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          orderType: "desc",
          orderBy:"createAt",
          q: q,
        };
        httpPost(data1, this.$api.getOperateList).then((res) => {
          var data = [];
          res.data.list.map((li, index) => {
            var operRequ=JSON.parse(li.operRequ).param[0]
            var str = this.getOpenType(this.query.openType);
            // var compli = this.comparison(operRequ.data.deviceNum);
            let path="",compli=""
            if(operRequ.hasOwnProperty("data")){
              path=this.screenRoomName(operRequ.data.roomId)
              li.roomName = path?path:operRequ.data.roomName?operRequ.data.roomName:'';
              li.roomId = operRequ.data.roomId;
              li.name=operRequ.data.cardName
              li.deviceNum=operRequ.data.lockerId?operRequ.data.lockerId:operRequ.data.deviceNum;
            }else{
              li.roomName = operRequ.roomName
              li.name=operRequ.cardName
              li.deviceNum=operRequ.deviceNum || operRequ.imei
            }
            li.openType=str
            li.createAt = moment(li.createAt).format("YYYY-MM-DD HH:mm:ss");
            var str = [li.deviceNum, str, li.createAt];
            data.push(str);
          });
          this.devicestatus = false;
          this.pageTotal = res.data.total;
          this.$nextTick(() => {
            this.config.data = data;
            this.logList = res.data.list;
            this.devicestatus = true;
          });
        });
      },
      comparison(deviceNum) {
        var deviceList = this.$store.state.deviceList;
        deviceList.some((item, index) => {
          if (item.deviceNum == deviceNum) {
            return item;
          }
        });
      },
      comparisonOne(deviceNum) {
        var deviceList = this.$store.state.deviceList;
        deviceList.some((item, index) => {
          if (item.imei == deviceNum) {
            return item;
          }
        });
      },
      //门锁报警同步刷新
      getlockAlert() {
        httpGet("", this.$api.getOperateList).then((res) => {});
      },
      searchParaProcess(obj) {
        var myObj = new Object();
        for (var key in obj) {
          if (obj[key] != "" && obj[key] != 'Invalid date' && obj[key] != null) {
            myObj[key] = obj[key]
          }
        }
        return JSON.stringify(myObj);
      },
      // 触发搜索按钮
      handleSearch() {
        this.pageNum=1
        this.openRoom = false
        let operUrl="",q={}
        if(this.query.openType==5){
          operUrl="/v1/device/send/bleCommand"
          var roomid=this.checkNodeId.length>0?this.checkNodeId.splice(this.checkNodeId.length-1,1):[]
          q= this.searchParaProcess({
            operRequ: "bleUnlockRecord",
            roomIds:roomid,
            startTime: this.query.datePicker[0],
            endTime:this.query.datePicker[1],
            // operUrl:operUrl,
            request:[this.query.cardName],
          })
        }else if(this.query.openType==6){
          operUrl="/v1/device/isp/openLock"
          var roomid=this.checkNodeId.length>0?this.checkNodeId.splice(this.checkNodeId.length-1,1):[]
          q= this.searchParaProcess({
            // openType: this.query.openType,
            roomIds:roomid,
            startTime: this.query.datePicker[0],
            endTime:this.query.datePicker[1],
            operUrl:operUrl,
            request:[this.query.cardName],
          })
        }
        var data = {
          pageNum: 1,
          pageSize: this.pageSize,
          orderType: "desc",
          orderBy:"createAt",
          q: q
        };
        httpPost(data, this.$api.getOperateList).then((res) => {
          var data = [];
          res.data.list.map((li, index) => {
            var operRequ=JSON.parse(li.operRequ).param[0]
            var str = this.getOpenType(this.query.openType);
            let path="",compli=""
            if(operRequ.hasOwnProperty("data")){
              path=this.screenRoomName(operRequ.data.roomId)
              li.roomName = path?path:operRequ.data.roomName?operRequ.data.roomName:'';
              li.roomId = operRequ.data.roomId;
              li.name=operRequ.data.cardName
              li.deviceNum=operRequ.data.lockerId?operRequ.data.lockerId:operRequ.data.deviceNum;
            }else{
              li.roomName = operRequ.roomName
              li.name=operRequ.cardName
              li.deviceNum=operRequ.deviceNum || operRequ.imei
            }
            li.openType=str
            li.createAt = moment(li.createAt).format("YYYY-MM-DD HH:mm:ss");
            var str = [li.deviceNum, str, li.createAt];
            data.push(str);
          });
          this.devicestatus = false;
          this.pageTotal = res.data.total;
          this.$store.commit("increment", 1);
          this.$nextTick(() => {
            this.config.data = data;
            this.logList = res.data.list;
            this.devicestatus = true;
          });
        });
        //   this.$set(this.query, "pageIndex", 1);
      },
      // 分页导航
      handlePageChange(val) {
        this.pageNum=val
        this.getcard()
      },
      handleSizeChange(val){
        this.pageSize=val
        this.getcard()
      }
    },
  };
</script>

<style scoped>
  .handle-box {
    margin-bottom: 20px;
  }

  .handle-select {
    width: 120px;
  }

  .handle-input {
    width: 300px;
    display: inline-block;
  }

  .table {
    width: 100%;
    font-size: 14px;
  }

  .red {
    color: #ff0000;
  }

  .mr10 {
    margin-right: 10px;
  }

  .table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
  }

  .width100 {
    width: 100px;
  }
  .width150{
    width: 150px;
  }
  .width200 {
    width: 200px;
  }
</style>
