<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.name" 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" clearable
          placeholder="选择开始日期时间" default-time="00:00:00">
        </el-date-picker>
        <el-date-picker v-model="query.datePicker[1]" class="wRem3" size="small" type="datetime" clearable
          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="0" label="全部" :value="0"></el-option>
          <el-option key="1" label="指纹开锁" :value="1"></el-option>
          <el-option key="2" label="数字键盘开锁" :value="2"></el-option>
          <el-option key="3" label="NFC开锁" :value="3"></el-option>
          <el-option key="4" label="机械钥匙开锁" :value="4"></el-option>
          <!-- <el-option key="5" label="蓝牙开锁" :value="5"></el-option> -->
          <el-option key="6" label="NB开锁" :value="6"></el-option>
          <el-option key="7" label="身份证" :value="7"></el-option>
          <el-option key="8" label="无线钥匙开锁" :value="8"></el-option>
          <el-option key="9" label="人脸开锁" :value="9"></el-option>
          <el-option key="10" label="离线卡开锁" :value="10"></el-option>
          <el-option key="11" label="离线密码开锁" :value="11"></el-option>
          <el-option key="12" label="门卡试错开锁" :value="12"></el-option>
          <el-option key="100" label="其它开锁" :value="100"></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>
        <el-button size="small" @click="getlockAlert" v-if="userInfo.type==0">同步更新</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="userTelephone" label="账号" width="180">
        </el-table-column>
        <el-table-column prop="roomName" label="房间号"> </el-table-column>
        <el-table-column label="开锁方式">
          <template #default="scope">
            <span v-if="scope.row.openType == 1">指纹开锁</span>
            <span v-if="scope.row.openType == 2">密码开锁</span>
            <span v-if="scope.row.openType == 3">NFC开锁</span>
            <span v-if="scope.row.openType == 4">机械钥匙开锁</span>
            <span v-if="scope.row.openType == 5">蓝牙开锁</span>
            <span v-if="scope.row.openType == 6">NB开锁</span>
            <span v-if="scope.row.openType == 7">身份证</span>
            <span v-if="scope.row.openType == 8">无线钥匙开锁</span>
            <span v-if="scope.row.openType == 9">人脸开锁</span>
            <span v-if="scope.row.openType == 10">离线卡开锁</span>
            <span v-if="scope.row.openType == 11">离线密码开锁</span>
            <span v-if="scope.row.openType == 12">门卡试错开锁</span>
            <span v-if="scope.row.openType == 100">其它开锁</span>
          </template>
        </el-table-column>
        <el-table-column prop="openTime" 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,downloadPost
  } 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: "UnlockRecord",
    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: "",
          operateName: "",
          operModul: "",
          datePicker: ['', ''],
          name: ''
        },
        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() {
      if (this.$route.params.datePicker) {
        this.query.datePicker = this.$route.params.datePicker
      }
      if (this.$route.params.type) {
        this.query.openType = JSON.parse(this.$route.params.type)
      }
      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();
      document.addEventListener('keydown', this.keyDown)
      this.getcard();
    },
    methods: {
      keyDown(e) {
        //如果是回车则执行登录方法
        if (e.keyCode == 13) {
          if (this.$route.name == 'UnlockRecord') {
            if (!this.drawer) {
              this.handleSearch();
            }
          }
        }
      },
      // 选择房源
      checkNode(e) {
        // this.checkNodeId = e[e.length-1]
        if(e.length>0){
          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
        }else{
          this.checkNodeId=[]
        }
      },
      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: "",
          operateName: "",
          operModul: "",
          datePicker: ['', ''],
          name: ""
        }
        this.checkNodeId = []
        this.handleSearch()
      },
      exportFun() {
        var data = {
          orderBy: "open_time desc",
          q: this.searchParaProcess({
            roomIds: this.checkNodeId,
            openType: this.query.openType,
            startTime: moment(this.query.datePicker[0]).format("X"),
            endTime: moment(this.query.datePicker[1]).format("X"),
            name: this.query.name
          }),
        };
        if(data.q=='{}') delete data.q
        downloadPost(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) {
        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;
      },

      getcard() {
        var data1 = {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          orderBy: "open_time desc",
          q: this.searchParaProcess({
            roomIds: this.checkNodeId,
            openType: this.query.openType,
            startTime: moment(this.query.datePicker[0]).format("X"),
            endTime: moment(this.query.datePicker[1]).format("X"),
            name: this.query.name
          }),
        };
        httpPost(data1, this.$api.getOpenRecord).then((res) => {
          var data = [];
          res.data.list.map((li, index) => {
            var str = this.getOpenType(li.openType);
            var compli = this.comparison(li.deviceNum);
            var name = utils.findIndexArray(this.options, li.roomId, [])
            var path = ''
            if (name) {
              path = name.join('/')
              li.roomName = path
            }
            li.roomId = li.roomId;
            li.openTime = this.timestampToTime(li.openTime);
            var str = [li.deviceNum, str, li.openTime];
            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;
          }
        });
      },
      //门锁报警同步刷新
      getlockAlert() {
        httpGet("", this.$api.getOpenRecordList).then((res) => {});
      },
      searchParaProcess(obj) {
        var myObj = new Object();
        for (var key in obj) {
          if (obj[key] != "" && obj[key] != 'Invalid date' && obj[key] != []) {
            myObj[key] = obj[key]
          }
        }
        return JSON.stringify(myObj);
      },
      // 触发搜索按钮
      handleSearch() {
        this.pageNum = 1
        this.openRoom = false
        var data = {
          pageNum: 1,
          pageSize: this.pageSize,
          orderBy: "open_time desc",
          q: this.searchParaProcess({
            roomIds: this.checkNodeId,
            openType: this.query.openType,
            startTime: moment(this.query.datePicker[0]).format("X"),
            endTime: moment(this.query.datePicker[1]).format("X"),
            name: this.query.name
          }),
        };
        httpPost(data, this.$api.getOpenRecord).then((res) => {
          var data = [];
          res.data.list.map((li, index) => {
            var str = this.getOpenType(li.openType);
            var compli = this.comparison(li.deviceNum);
            var name = utils.findIndexArray(this.options, li.roomId, [])
            var path = ''
            if (name) {
              path = name.join('/')
              li.roomName = path
            }
            li.roomId = li.roomId;
            li.openTime = this.timestampToTime(li.openTime);
            var str = [li.deviceNum, str, li.openTime];
            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;
          });
        });
      },
      // 分页导航
      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>
