<template>
  <div>
    <div class="header" :class="collapse ? 'header1' : ''">
      <!-- 折叠按钮 -->
      <div class="collapse-btn logotitle" @click="collapseChage">
        <!-- <span class="currpath">志为智慧物联集中管控平台</span> -->
        <i class="el-icon-s-fold s-fold" :class="hiddenslderstatus ? '' : 'foldfalse'"></i>
    </div>
      <div class="logo"></div>
      <div class="header-right" v-if="isrouterview">
        <div class="header-user-con">
          <!--< el-select v-model="value" size="small" placeholder="请选择客户" @change="selectTenantId"
          style="width: 3.25rem;" v-if="userinfo.type==0">
          <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
          </el-select> -->
          <div class="btn-info voiceimg" v-if="tenantId == 400">
            <img src="../assets/img/dk.png" alt="" v-if="!vocieStatus" @click="voicfun" />
            <img src="../assets/img/jy.png" alt="" v-else @click="voicfun1" />
          </div>
          <div class="btn-info" v-if="tenantId == 400">
            <el-tooltip placement="bottom">
              <span slot="content">正在开门报警</span>
              <!-- <router-link to="/info"> -->
              <i class="el-icon-message-solid" @click="showbar"></i>
              <!-- </router-link> -->
            </el-tooltip>
            <span class="btn-info-tip" v-if="message"></span>
          </div>
          <div class="ddatetime">
            <div class="rightLine rightspan">
              <span class="iconfont httpicon-shijian"></span>
              <span>{{ time }}</span>
            </div>
            <div class="rightspan">
              <span>{{ date }}</span>
            </div>
          </div>
          <!-- <el-button size="mini" icon="gongyu gy-quanping1" circle @click="fullScreen"></el-button> -->
          <div class="quanping" @click="fullScreen">
            <i class="gongyu gy-quanping1"></i>
          </div>
          <div class="user-avator">
            <img src="../assets/img/img.png" />
          </div>
          <!-- 用户名下拉菜单 -->
          <el-dropdown class="user-name" trigger="click" @command="handleCommand">
            <span class="el-dropdown-link">
              {{ username }}<i class="el-icon-arrow-down arrow-down"></i>
            </span>
            <!-- <span class="el-dropdown-link" @click="loginoutfun">
              <i class="iconfont httpicon-tuichu loginout"></i>
            </span> -->
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="loginout">退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </div>
    </div>
    <audio ref='audio' muted :src='audiosrc' controls="controls" :autoplay="false" class="voice" loop></audio>
    <el-drawer title="" :visible.sync="drawer" custom-class="drawlist" size="100%" :before-close="handleClose"
      :show-close="false">
      <el-row class="marginTop">
        <div class="tablecell">
          <el-table ref="multipleTable" v-if="!activeiconfont" :data="tableData" :border="true" tooltip-effect="dark"
            style="width: 100%" :header-cell-style="rowClass" :cell-style="{ fontSize: '12px' }" stripe height="590">
            <!-- <el-table-column type="selection" width="55">
    				</el-table-column> -->
            <el-table-column prop="name" label="房间名称">
            </el-table-column>
            <el-table-column prop="deviceNum" label="设备名称">
            </el-table-column>
            <el-table-column prop="createAt" label="开门时间">
            </el-table-column>
          </el-table>
          <div class="roomcontent" v-else>
            <div class="roomconli roomconlinomar" v-for="(item, index) in tableData" :key="index">
              <deviceLiT :data="item" :class="item.sharkFlag ? 'my-shark' : ''"></deviceLiT>
            </div>
          </div>
        </div>
        <div class="page pagebtn">
          <el-button type="primary" class="btn" size="mini" @click="handleClose">关闭</el-button>
          <el-pagination @size-change="handleSizeChange" popper-class="headselect" @current-change="handleCurrentChange"
            :current-page="currentPage" :page-sizes="[10, 20, 30, 50, 100, 200]" :page-size="pageSize"
            layout="total,sizes, prev, pager, next, jumper" :total="pageTotal">
          </el-pagination>
        </div>
      </el-row>
    </el-drawer>
  </div>
</template>
<script>
import deviceLiT from "../views/doorMagnetism/common/deviceLi1.vue";
import {
  httpGet,
  httgetaxio,
  httpPostno
} from "../api/index";
import axios from "axios"
import moment from "moment"
export default {
  inject: ['reload'],
  data() {
    return {
      fullscreen: false,
      name: "linxin",
      message: 1,
      isrouterview: true,
      language: "English",
      currentpath: "",
      tagsList: [],
      weather: "",
      time: "00:00",
      date: "2021年11月17日 星期三",
      city: "",
      timer: "",
      timeStatus: true,
      options: [],
      value: '',
      tenantId: '',
      userinfo: {
        type: '1'
      },
      collapse: false,
      unlinedeviceSum: 0,
      activeiconfont: true,
      tableData: [],
      audiosrc: require("../assets/img/ls.mp3"),
      pageSize: 10,
      vocieStatus: true,
      pageTotal: 0,
      currentPage: 1,
      drawer: false,
      prelist: [],
      settime2: null,
      hiddenslderstatus: true
    };
  },
  components: {
    deviceLiT
  },
  beforeCreate() {
    this.$store.commit('getselectoption')
  },
  activated() {
    var _this = this
    if (this.tenantId == 400) {
      this.settime2 = setInterval(function () {
        _this.getalertDevice()
      }, 3000)
    }
  },
  beforeRouteLeave(to, from, next) {
    clearInterval(this.settime2)
    next()
  },
  beforeDestroy() {
    clearInterval(this.settime2)
  },
  watch: {
    $route: {
      // val是改变之后的路由，oldVal是改变之前的val
      handler: function (val, oldVal) {
        this.currentpath = val.meta.title;
      },
      // 深度观察监听
      deep: true,
    },
  },
  created() {
    this.$store.commit('settenantid')
    this.tagsList = this.$store.state.tagsList;
    this.currentpath = this.$route.meta.title;
    // var lan = JSON.parse(sessionStorage.getItem("lange"));
    var userinfo = JSON.parse(localStorage.getItem("info")) || '';
    var tenantId = 1200// JSON.parse(localStorage.getItem("tenantId"))
    this.tenantId = tenantId
    this.value = JSON.stringify(tenantId)
    // if (lan) {
    //   this.language = "English";
    // } else {
    //   this.language = "中文";
    // }
    // this.getTime1();
    // this.city=returnCitySN['cname']
    // this.getTianQi()
    // if (userinfo) {
    //   if (userinfo.type == 0) {
    // httpGet('', this.$api.getConfig).then(res => {
    //   if (res.success) {
    //     this.options = res.data.list
    //     this.$store.commit('getselectoption',res.data.list)
    //   } else {
    //     this.$message.error("获取失败")
    //   }
    // })
    // this.$store.commit('getselectoption')
    //   }
    // }
    this.options = this.$store.state.selectoption
    this.userinfo = userinfo
  },
  computed: {
    username() {
      let username = localStorage.getItem("ms_username");
      return username ? username : this.name;
    },
  },
  mounted() {
    if (document.body.clientWidth < 1500) {
      this.collapseChage();
    }
    var Week = ["日", "一", "二", "三", "四", "五", "六"];
    this.timer = setInterval(() => {
      var myDate = new Date();
      var hours =
        myDate.getHours() > 9 ? myDate.getHours() : "0" + myDate.getHours();
      var minutes =
        myDate.getMinutes() > 9 ?
          myDate.getMinutes() :
          "0" + myDate.getMinutes();
      var year = myDate.getFullYear();
      var month = myDate.getMonth() + 1;
      var day = myDate.getDate();
      var xq = myDate.getDay();
      var datas = moment().format("YYYY-MM-DD HH:mm:ss").split(" ")[1]
      // this.time = hours + ":" + minutes;
      this.time = datas
      this.date =
        year + "年" + month + "月" + day + "日" + " 星期" + Week[xq];
    }, 1000);
    if (this.tenantId == 400) {
      var _this = this
      // this.$refs.audio.play()
      this.getalertDevice()
      this.settime2 = setInterval(function () {
        _this.getalertDevice()
      }, 3000)
    }
  },

  methods: {
    validate(arr1, arr2) {
      if (!arr1 instanceof Array || !arr2 instanceof Array) {
        return true;
      }
      if (arr1.length != arr2.length) {
        return false;
      }
      let arr1Str = JSON.stringify(arr1);
      for (let i = 0; i < arr2.length; i++) {
        if (arr1Str.indexOf(JSON.stringify(arr2[i])) == -1) {
          return false;
        }
      }
      return true;
    },
    unique(arr, u_key) {
      let map = new Map()
      arr.forEach((item, index) => {
        if (!map.has(item[u_key])) {
          map.set(item[u_key], item)
        }
      })
      return [...map.values()]
    },
    poplist(list) {
      var list1 = this.unique(list, 'imei')
      var tt = this.validate(this.prelist, list1)

      if (tt) {

      } else {
        this.prelist = list1
        if (list1.length == 0) {
          this.$refs.audio.pause()
        } else {
          if (!this.vocieStatus) {
            this.$refs.audio.play()
            this.vocieStatus = false
            setTimeout(() => {
              this.$refs.audio.pause()
            }, 10000)
          }
        }
        list1.map(li => {
          setTimeout(() => {
            this.$notify({
              title: li.name,
              offset: 200,
              duration: 2000,
              message: li.createAt + ' 开门警报',
              type: 'warning'
            });
          }, 3000)
        })

      }
    },
    showbar() {
      this.drawer = true
    },
    voicfun() {
      this.$refs.audio.pause()
      this.vocieStatus = true
    },
    voicfun1() {
      this.$refs.audio.play()
      this.vocieStatus = false
    },
    selectTenantId(e) {
      this.tenantId = e
      localStorage.setItem('tenantId', this.tenantId)
      this.$tenantId = e
      // localStorage.removeItem("statisticsDate")
      if (e == 400) {
        this.$store.commit("clearTags");
        this.$router.push(this.$route.path);
      } else {
        this.$store.commit("clearTags");
        this.$router.push(this.$route.path)
      }
      this.reload()
    },
    getTianQi() {
      var data = {
        city: "深圳市",
      };
      httgetaxio(data, "http://wthrcdn.etouch.cn/weather_mini").then((res) => {
        console.log(res);
      });
    },
    getTime1() {
      var Week = ["日", "一", "二", "三", "四", "五", "六"];
      var myDate = new Date();
      var hours =
        myDate.getHours() > 9 ? myDate.getHours() : "0" + myDate.getHours();
      var minutes =
        myDate.getMinutes() > 9 ?
          myDate.getMinutes() :
          "0" + myDate.getMinutes();
      var year = myDate.getFullYear();
      var month = myDate.getMonth();
      var day = myDate.getDate();
      var xq = myDate.getDay();
      this.time = hours + ":" + minutes;
      this.date = year + "年" + month + "月" + day + "日" + " 星期" + Week[xq];
      this.getTime();
    },
    // 获取当前时间
    getTime() {
      var Week = ["日", "一", "二", "三", "四", "五", "六"];
      this.timeStatus = false
      this.timer = setInterval(function () {
        var myDate = new Date();
        var hours =
          myDate.getHours() > 9 ? myDate.getHours() : "0" + myDate.getHours();
        var minutes =
          myDate.getMinutes() > 9 ?
            myDate.getMinutes() :
            "0" + myDate.getMinutes();
        var year = myDate.getFullYear();
        var month = myDate.getMonth();
        var day = myDate.getDate();
        var xq = myDate.getDay();
        this.time = hours + ":" + minutes;
        this.date =
          year + "年" + month + "月" + day + "日" + " 星期" + Week[xq];
        this.timeStatus = true
      }, 1000);
    },

    selectlang() {
      this.$store.commit("selectlanguage", !this.$store.state.lange);
    },
    selectlang1() {
      var data = {
        client_id: "iot-client",
        client_secret: "iot-client",
        grant_type: "refresh_token",
        scope: "all",
        refresh_token: JSON.parse(localStorage.getItem("token")).refresh_token,
      };
      httpGet(data, "/oauth/token").then((res) => {
        if (res.access_token) {
          localStorage.setItem("token", JSON.stringify(res));
        }
      });
    },
    getalertDevice() {
      // if (this.currentPage > this.carouselPage) {
      // 	this.currentPage = 1
      // }
      var data = {
        pageNum: 1,
        pageSize: 1,
        orderType: 'desc',
        orderBy: "createAt",
        q: JSON.stringify({
          lockStatus: 1
        })
      }
      httpPostno(data, this.$api.getList).then(res => {
        if (res.success) {
          this.$store.commit('updatedata', res.data.total);
        }
      })
      var data = {
        pageNum: this.currentPage,
        pageSize: this.pageSize,
        orderType: 'desc',
        orderBy: "createAt",
        q: JSON.stringify({
          operateCode: 1,
          startTime: moment().subtract('days', 0).format('YYYY-MM-DD 00:00:00'),
          endTime: moment().format('YYYY-MM-DD HH:mm:ss'),
        })
      }
      httpPostno(data, this.$api.getReportList).then(res => {
        if (res.success) {
          // if (res.data.total > 0) {

          // } else {
          // 	this.$refs.audio.pause()
          // 	this.vocieStatus = true
          // }
          res.data.list.map(li => {
            li.createAt = moment(li.createAt).format('YYYY/MM/DD HH:mm:ss')
          })
          var time = new Date();
          var list = []
          res.data.list.map(li => {
            var time = moment(time).valueOf()
            var time1 = moment(li.createAt).valueOf()
            li['sharkFlag'] = false
            if (time - time1 < 6000) {
              list.push(li)
              li['sharkFlag'] = true
            }
          })
          this.poplist(list)
          // this.alarmList = res.data.list
          this.unlinedeviceSum = res.data.total
          this.tableData = res.data.list
          this.pageTotal = res.data.total
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    handleClose(done) {
      this.drawer = false
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.getalertDevice()
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.getalertDevice()
      console.log(`当前页: ${val}`);
    },
    // 用户名下拉菜单选择事件
    handleCommand(command) {
      if (command == "loginout") {
        // localStorage.removeItem("ms_username");
        // this.$router.push("/login");
        this.loginoutfun()
      }
    },
    fullScreen() {
      let full = document.fullscreenElement;
      //切换为全屏模式
      if (!full) {
        //文档根节点的方法requestFullscreen,实现全屏模式
        document.documentElement.requestFullscreen();
      } else {
        //变为不是全屏模式->退出全屏模式
        document.exitFullscreen();
      }
    },
    loginoutfun() {
      var data = {}
      httpGet({}, '/oauth/revoke').then(res4 => { })
      this.$router.push("/login");
    },
    // 侧边栏折叠
    collapseChage() {
      this.$store.commit("hadndleCollapse", !this.collapse);
      if (this.hiddenslderstatus) {
          document.documentElement.style.setProperty("--sldebarLeft", "0");
          this.hiddenslderstatus = false
        } else {
          document.documentElement.style.setProperty("--sldebarLeft", "180px");
          this.hiddenslderstatus = true
        }
    },
  },
};
</script>
<style scoped>
.header {
  position: relative;
  box-sizing: border-box;
  width: calc(100% - var(--sldebarLeft));
  height: 50px;
  font-size: 18px;
  left: var(--sldebarLeft);
  color: #fff;
  border-bottom: 1px solid #dcdfe6;
  transition: all 0.5s;
}

.header1 {
  /* left: 100px; */
  width: 100%;
}

.collapse-btn {
  float: left;
  padding: 0 21px;
  cursor: pointer;
  line-height: 50px;
  font-size: 14px;
  color: #333;
}

.collapse-btn:hover {
  background: none;
}

.header .logo {
  float: left;
  width: 250px;
  line-height: 50px;
}

.header-right {
  float: right;
  padding-right: 50px;
}

.header-user-con {
  display: flex;
  height: 50px;
  align-items: center;
}

.btn-fullscreen {
  transform: rotate(45deg);
  margin-right: 5px;
  font-size: 24px;
}

.btn-bell,
.btn-fullscreen {
  position: relative;
  width: 30px;
  height: 30px;
  text-align: center;
  border-radius: 15px;
  cursor: pointer;
}

.btn-bell-badge {
  position: absolute;
  right: 0;
  top: -2px;
  width: 8px;
  height: 8px;
  border-radius: 4px;
  background: #f56c6c;
  color: #fff;
}

.btn-bell .el-icon-bell {
  color: #fff;
}

.user-name {
  margin-left: 10px;
}

.user-avator {
  margin-left: 10px;
}

.user-avator img {
  display: block;
  width: 30px;
  height: 30px;
  border-radius: 50%;
}

.el-dropdown-link {
  /* color: #333; */
  color: #97A8BE;
  cursor: pointer;
}

.el-dropdown-menu__item {
  text-align: center;
}

.loginout {
  font-size: 1.2vw;
  color: #333;
  margin-left: 30px;
}

.currpath {
  color: #59adf7;
}

.ddatetime {
  /* color: var(--custom-color); */
  color: #97A8BE;
  display: flex;
  align-items: center;
  font-size: 14px;
}

.ddatetime .rightLine {
  /* border-right: 1px solid var(--border-color); */
  border-right: 1px solid #97A8BE;
}

.ddatetime .rightspan {
  padding: 0 14px;
  text-align: center;
  vertical-align: middle;
}

.httpicon-shijian {
  font-size: 24px;
  vertical-align: middle;
}

.logotitle {
  font-size: 24px;
  font-weight: 600;
}






.roomcontent {
  width: 90%;
  margin: 0 auto;
  display: flex;
  flex-wrap: wrap;
}

.roomcontent .roomconli {
  display: inline-block;
  cursor: pointer;
  position: relative;
}

.drawlist {
  width: 100%;
  padding: 1.25rem;
  box-sizing: border-box;
  height: 100vh;
  z-index: 999999;
  position: fixed;
  padding: 30px;
  text-align: center;
}

.el-pagination {
  display: inline-block;
  vertical-align: middle;
}

.el-drawer__wrapper {
  z-index: 9999999 !important;
  width: 100%;
  left: 0;
  top: 0;
  background: #fff;
  color: #333;
}

.drawlist .el-drawer__close-btn {
  position: absolute;
  z-index: 9999;
  right: 1.25rem;
  top: 1.25rem;
}

.roomconlinomar .lock .lock-name {
  margin: 0 !important;
}

.pagebtn {
  position: relative;
  text-align: center;
}

/* .pagebtn .btn {
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
  } */

.datatime {
  font-size: 0.875rem;
  margin-right: 0.625rem;
}

.overflowCarousel {
  overflow: hidden;
}

.voice {
  position: fixed;
  top: -100%;
  left: -100%;
  opacity: 0;
}

.voiceimg img {
  width: 1.5vw;
  vertical-align: middle;
  cursor: pointer;
}

.my-shark {
  animation: login-shake 1s 1 ease-in;
}

@keyframes login-shake {
  0% {
    transform: scale(1);
  }

  10%,
  20% {
    transform: scale(0.9) rotate(-3deg);
  }

  30%,
  50%,
  70%,
  90% {
    transform: scale(1.1) rotate(3deg);
  }

  40%,
  60%,
  80% {
    transform: scale(1.1) rotate(-3deg);
  }

  100% {
    transform: scale(1) rotate(0);
  }
}

.el-icon-message-solid {
  font-size: 1.5vw;
  cursor: pointer;
  color: #ff464f;
  vertical-align: text-top;
}

.btn-info-tip {
  position: absolute;
  top: 10px;
  /* .circle(8px); */
  background-color: #ff464f;
}

@media only screen and (max-width: 1080px) {
  .header {
    left: var(--sldebarLeftOne);
    width: 100%;
  }

  .header-right {
    padding-right: 0;
  }
}

.quanping {
  width: 30px;
  height: 30px;
  text-align: center;
  line-height: 30px;
}

.gy-quanping1 {
  font-size: 30px;
  /* color: #333333; */
  color: #97A8BE;
}
.arrow-down{
  margin-left: 5px;
}
.s-fold{
  color: #97A8BE;
  font-size: 20px;
}
.foldfalse{
  transform: rotate(180deg);
  transition: all 0.5s;
}
</style>
