<template>
  <div>
    <div class="container">
      <div class="handle-box">
        <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" 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 v-model="query.openType" size="small" placeholder="开门方式" class="handle-select mr10" clearable>
          <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="9"></el-option>
          <el-option key="11" label="其它开锁" value="100"></el-option>
        </el-select>
        <el-button type="primary" icon="el-icon-search" size="small" @click="handleSearch">搜索</el-button>
        <el-button size="small" type="primary" icon="el-icon-search" @click="resetAll">重置</el-button>
        <el-button type="primary" icon="el-icon-download" size="small" @click="exportFun">导出</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 == 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, prev, pager, next" :current-page="$store.state.currentPage"
          :page-size="query.pageSize" :total="pageTotal" @current-change="handlePageChange"></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 moment from "moment"
  export default {
    name: "warningLog",
    data() {
      return {
        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: [],
      };
    },
    props: ['roomId'],
    created() {
      // httpPost({
      //     package: 1
      // }, this.$api.getDeviceItems).then((res) => {
      //     this.$store.commit("deviceFun", res.data.list);
      // });
      // this.getalllist();
    },
    mounted() {
      // this.getlockAlert();
      this.getcard();
    },
    methods: {
      resetAll() {
        this.query = {
          openType: "",
          operateName: "",
          operModul: "",
          datePicker: ['', ''],
          name:""
        }
        this.handleSearch()
      },
      exportFun() {
        var data = {
          orderBy: "open_time desc",
          q: JSON.stringify({
            deviceNum: this.roomId,
            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 array = uniqueArray(res.data, "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: 1,
          pageSize: 10,
          orderBy: "open_time desc",
          q: JSON.stringify({
            deviceNum: this.roomId,
            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);
            li.roomName = li.roomName;
            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') {
            myObj[key] = obj[key]
          }
        }
        return JSON.stringify(myObj);
      },

      // 触发搜索按钮
      handleSearch() {
        this.openRoom = false
        var data = {
          pageNum: 1,
          pageSize: 10,
          orderBy: "open_time desc",
          q: this.searchParaProcess({
            deviceNum: this.roomId,
            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);
            li.roomName = li.roomName;
            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;
          });
        });
        //   this.$set(this.query, "pageIndex", 1);
      },
      // 分页导航
      handlePageChange(val) {
        this.$store.commit("increment", val);
        var data = {
          pageNum: val,
          pageSize: 10,
          orderBy: "open_time desc",
          q: this.searchParaProcess({
            deviceNum: this.roomId,
            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);
            li.roomName = li.roomName;
            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;
          });
        });
      },
    },
  };
</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;
  }
</style>
