<template>
  <div class="navbar">
    <hamburger id="hamburger-container" :is-active="sidebar.opened" class="hamburger-container"
               @toggleClick="toggleSideBar"/>

    <breadcrumb id="breadcrumb-container" class="breadcrumb-container" v-if="!topNav"/>
    <top-nav id="topmenu-container" class="topmenu-container" v-if="topNav"/>

    <div class="right-menu">
      <!--      <template v-if="device!=='mobile'">-->
      <!--        <search id="header-search" class="right-menu-item" />-->

      <!--        <el-tooltip content="源码地址" effect="dark" placement="bottom">-->
      <!--          <ruo-yi-git id="ruoyi-git" class="right-menu-item hover-effect" />-->
      <!--        </el-tooltip>-->

      <!--        <el-tooltip content="文档地址" effect="dark" placement="bottom">-->
      <!--          <ruo-yi-doc id="ruoyi-doc" class="right-menu-item hover-effect" />-->
      <!--        </el-tooltip>-->

      <!-- 消息中心 -->
<!--      <span v-show="alarmIconShow">-->
<!--        <span v-if="isMessage" key="1">-->
<!--          <el-tooltip content="告警消息" placement="bottom">-->
<!--            <a href='javascript:;' @click="showAlarm">-->
<!--              <svg-icon icon-class="notice" class="right-menu-item1 hover-effect1"/>-->
<!--            </a>-->
<!--          </el-tooltip>-->
<!--        </span>-->
<!--        <span v-else key="2">-->
<!--          <el-tooltip content="告警消息" placement="bottom">-->
<!--            <svg-icon icon-class="notice_none" class="right-menu-item1 hover-effect1"/>-->
<!--          </el-tooltip>-->
<!--        </span>-->
<!--      </span>-->


      <el-tooltip content="全屏" placement="bottom">
        <screenfull id="screenfull" class="right-menu-item hover-effect"/>
      </el-tooltip>
      <!--        <el-tooltip content="布局大小" effect="dark" placement="bottom">-->
      <!--          <size-select id="size-select" class="right-menu-item hover-effect" />-->
      <!--        </el-tooltip>-->

      <!--      </template>-->

      <el-dropdown class="avatar-container right-menu-item hover-effect" trigger="click">
        <div class="avatar-wrapper">
          <img src="@/assets/img1.jpg" class="user-avatar">
          <i class="el-icon-caret-bottom"/>
        </div>
        <el-dropdown-menu slot="dropdown">
          <router-link to="/user/profile">
            <el-dropdown-item>个人中心</el-dropdown-item>
          </router-link>
          <el-dropdown-item divided @click.native="logout">
            <span>退出登录</span>
          </el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
    </div>
    <el-dialog :title="title" :visible.sync="open" width="750px" append-to-body>
      <div style="padding-top: 10px">
        <vxe-table
          ref="xTable"
          align="center"
          :loading="loading"
          class="mytable-style"
          auto-resize
          border
          resizable
          export-config
          highlight-current-row
          show-overflow
          max-height="700"
          :data="alarmList"
        >
          <vxe-table-column field="alarmContent" title="告警内容"/>
          <vxe-table-column field="createTime" title="时间" width="200px"/>
          <vxe-table-column title="操作" width="100px">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-reading"
                @click="readDone(scope.row)"
              >查收
              </el-button>
            </template>
          </vxe-table-column>
        </vxe-table>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {mapGetters} from 'vuex'
import Breadcrumb from '@/components/Breadcrumb'
import TopNav from '@/components/TopNav'
import Hamburger from '@/components/Hamburger'
import {removeToken} from "@/utils/auth";
import Screenfull from '@/components/Screenfull'
import XEUtils from 'xe-utils'
import moment from "moment";
import {userinfoDecrypt, userinfoEncrypt} from "@/utils/smutil";
import {debounce} from "lodash";
// import SizeSelect from '@/components/SizeSelect'
// import Search from '@/components/HeaderSearch'
// import RuoYiGit from '@/components/RuoYi/Git'
// import RuoYiDoc from '@/components/RuoYi/Doc'

export default {
  data() {
    return {
      intervalId: null,
      isMessage: false,
      alarmIconShow: false,
      title: '告警消息',
      loading: false,
      alarmList: null,
      // 是否显示弹出层
      open: false,
      message: 2
    }
  },
  components: {
    Breadcrumb,
    TopNav,
    Hamburger,
    Screenfull,
    // SizeSelect,
    // Search,
    // RuoYiGit,
    // RuoYiDoc
  },
  created() {
    this.getCurrentUser()
    // this.intervalId = setInterval(this.myFunction, 3000); // 设置初始定时器
  },
  destroyed() {
    // clearInterval(this.intervalId)
  },
  computed: {
    ...mapGetters([
      'sidebar',
      'avatar',
      'device'
    ]),
    setting: {
      get() {
        return this.$store.state.settings.showSettings
      },
      set(val) {
        this.$store.dispatch('settings/changeSetting', {
          key: 'showSettings',
          value: val
        })
      }
    },
    topNav: {
      get() {
        return this.$store.state.settings.topNav
      }
    }
  },
  methods: {
    // myFunction() {
    //   // 在这里执行你的代码逻辑
    //   this.$axios.get('/sysUserController/establishHeart').then((res) => {
    //   })
    // },
    async getCurrentUser() {
      var user;
      await this.$axios.get('/sysUserController/getCurrentUser').then((res) => {
        user = res.data.sysUser
        // 用户信息+菜单权限加密存储
        let encryptUserInfo = userinfoEncrypt(JSON.stringify(res.data))
        localStorage.setItem('active', encryptUserInfo)
        if (user.lastUpdatePwdTime == null) {
          this.$message({
            type: 'warning',
            message: '需要修改初始密码!'
          });
          this.$router.push("/user/profile")
        } else {
          var dateBegin = new Date(user.lastUpdatePwdTime);
          var dateEnd = new Date();
          var dateDiff = dateEnd.getTime() - dateBegin.getTime(); //时间差的毫秒数
          var dayDiff = Math.floor(dateDiff / (24 * 3600 * 1000)); //计算出相差天数
          if (dayDiff >= 30) {
            this.$message({
              type: 'warning',
              message: '密码超过30天需要修改!'
            })
            this.$router.push("/user/profile")
          }
        }
      }).catch((error) => {
        this.$message.error('获取当前用户数据出错' + error)
      })


      // 检测用户密码是否符合要求
      await this.$axios.get('/sysUserController/validatePasswordRule').then((res) => {
        if (res.data != 'true'){
          this.$message({
            type: 'warning',
            message: '密码规则不符合当前系统设定，请重新修改密码!'+res.data
          })
          this.$router.push("/user/profile")
        }
      }).catch((error) => {
        this.$message.error('检测密码规则出错' + error)
      })

      // let sysTime
      // let lk
      // await this.$axios.get('/sysPolicyController/getLicenseKey').then((res) => {
      //   sysTime = res.data.sysTime
      //   lk = res.data.lk
      // }).catch((error) => {
      // })
      // // 获取角色是否系统管理员
      // const searchParams = {
      //   userId: user.id,
      //   sysTime: sysTime,
      //   lk: lk
      // }
      // await this.$axios.get('/sysUserController/getUserRole', {params: searchParams}).then((res) => {
      //   let userRole = res.data
      //   if (userRole.roleId == 1) {
      //     // this.getAlarmData()
      //     // 系统管理员角色显示告警图标
      //     this.alarmIconShow = true
      //     // this.getAlarmData()
      //
      //     // 取消定时刷新告警，无法实现用户非活动状态超时登出
      //     // // 增加定时每分钟获取告警消息
      //     // this.interval = setInterval(() => {
      //     //   if (!this.open){
      //     //     // 窗口关闭可以调用自动查询
      //     //     this.getAlarmData()
      //     //   }
      //     // }, 60000000)
      //   } else {
      //     this.alarmIconShow = false
      //   }
      //
      // }).catch((error) => {
      //   // this.$message.error(error)
      // })
    },
    /**
     * 删除提交
     */
    readDone: debounce(async function (row) {
      const param = {
        id: row.id
      }
      await this.$axios.post('/sysAlarmController/readDone', param).then((res) => {
        if (res.code == 0) {
          this.$message({
            type: 'success',
            message: '查收成功!'
          });
          this.$refs.xTable.remove(row)
        } else {
          this.$message({
            type: 'error',
            message: res.data
          });
        }
      }).catch((error) => {
        this.$message({
          type: 'error',
          message: '查收失败!'
        });
      })
    }, 1000),
    // 取消按钮
    cancel() {
      this.getAlarmData()
      this.open = false
    },
    async getAlarmData() {
      this.loading = true
      // 查询告警消息
      await this.$axios.get('/sysAlarmController/getAll').then((res) => {
        this.alarmList = res.data
        if (res.data.length > 0) {
          // 改变消息图标
          this.isMessage = true;
        } else {
          this.isMessage = false;
        }
        this.loading = false
      }).catch((error) => {
        this.loading = false
        // this.$message.error(error)
      })
    },
    showAlarm() {
      this.open = true
    },
    toggleSideBar() {
      this.$store.dispatch('app/toggleSideBar')
    },
    async logout() {
      this.$axios.post(
        '/logout', {}
      ).then((res) => {
        this.$message.success(res.data)
        removeToken()
        //注销返回自己的登录页
        this.$router.push(`/login?redirect=${this.$route.fullPath}`)
      })

      // this.$confirm('确定注销并退出系统吗？', '提示', {
      //   confirmButtonText: '确定',
      //   cancelButtonText: '取消',
      //   type: 'warning'
      // }).then(() => {
      //   this.$store.dispatch('LogOut').then(() => {
      //     location.href = '/index';
      //   })
      // }).catch(() => {});
    }
  }
}
</script>

<style lang="scss" scoped>
.right-menu-item1 {
  position: relative;
  top: -15px;
  font-size: 18px;
}

.item {
  margin-tip: 5px;
  margin-right: 15px;
}

.navbar {
  height: 50px;
  overflow: hidden;
  position: relative;
  background: #fff;
  box-shadow: 0 1px 4px rgba(0, 21, 41, .08);

  .hamburger-container {
    line-height: 46px;
    height: 100%;
    float: left;
    cursor: pointer;
    transition: background .3s;
    -webkit-tap-highlight-color: transparent;

    &:hover {
      background: rgba(0, 0, 0, .025)
    }
  }

  .breadcrumb-container {
    float: left;
  }

  .topmenu-container {
    position: absolute;
    left: 50px;
  }

  .errLog-container {
    display: inline-block;
    vertical-align: top;
  }

  .right-menu {
    float: right;
    height: 100%;
    line-height: 50px;

    &:focus {
      outline: none;
    }

    .right-menu-item {
      display: inline-block;
      padding: 0 8px;
      height: 100%;
      font-size: 18px;
      color: #5a5e66;
      vertical-align: text-bottom;

      &.hover-effect {
        cursor: pointer;
        transition: background .3s;

        &:hover {
          background: rgba(0, 0, 0, .025)
        }
      }
    }

    .avatar-container {
      margin-right: 30px;

      .avatar-wrapper {
        margin-top: 5px;
        position: relative;

        .user-avatar {
          cursor: pointer;
          width: 40px;
          height: 40px;
          border-radius: 10px;
        }

        .el-icon-caret-bottom {
          cursor: pointer;
          position: absolute;
          right: -20px;
          top: 25px;
          font-size: 12px;
        }
      }
    }

    .right-menu-item1 {

      height: 100%;
      width: 27px;
      font-size: 18px;
      color: #5a5e66;
      vertical-align: text-bottom;
      top: 0px;

      &.hover-effect1 {
        cursor: pointer;
        transition: background .3s;

        &:hover {
          background: rgba(0, 0, 0, .025)
        }
      }
    }
  }
}
</style>
