<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="breadcrumb-container" v-if="topNav"/>


    <div class="right-menu">
      <template v-if="device!=='mobile'">
        <div class="right-menu-item hover-effect">
            <el-badge v-if="msgCount>0" :value="msgCount" :max="99" class="dot">
            </el-badge>

          <div class="msg" @click="openMsg()"><i class="el-icon-message-solid"></i> </div>

        </div>

        <!-- <search id="header-search" class="right-menu-item" />

        -->
        <screenfull id="screenfull" class="right-menu-item hover-effect" />

        <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="logImg" 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 @click.native="setting = true">
            <span>布局设置</span>
          </el-dropdown-item>
          <el-dropdown-item divided @click.native="logout">
            <span>退出登录</span>
          </el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
    </div>
     <el-drawer
      :append-to-body="true"
      size="35%"
      title="消息中心"
      :with-header="false"
        :title="msg.title" :visible.sync="msg.open"
        >
          <msg    ref="msg"  @update-count="getMsgCount" />
      </el-drawer>

  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import Breadcrumb from '@/components/Breadcrumb'
import TopNav from '@/components/TopNav'
import Hamburger from '@/components/Hamburger'
import Screenfull from '@/components/Screenfull'
import SizeSelect from '@/components/SizeSelect'
import Search from '@/components/HeaderSearch'

import msg from "@/views/crm/components/msg";
import { getMsg,getMsgList,getMsgCount,setRead } from "@/api/crm/msg";

export default {
  components: {
    Breadcrumb,
    TopNav,
    Hamburger,
    Screenfull,
    SizeSelect,
    Search,
    msg
  },
  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
      }
    }
  },
  data() {
    return {
      msgCount:0,
      previousMsgCount: 0, // 保存上一次的消息计数
      msg:{
        open:false,
        title:'通知消息'
      },
      msgPollingTimer: null, // 轮询定时器
    }
  },
  created() {
    this.getMsgCount();
    // 启动消息轮询，每30秒检查一次新消息
    this.startMsgPolling();
  },
  beforeDestroy() {
    // 组件销毁前清除定时器
    this.stopMsgPolling();
  },
  methods: {
    startMsgPolling() {
      // 清除已存在的定时器
      if (this.msgPollingTimer) {
        clearInterval(this.msgPollingTimer);
      }

      // 设置定时器，每30秒获取一次消息计数
      this.msgPollingTimer = setInterval(() => {
        this.getMsgCount();
      }, 30000); // 30秒轮询一次
    },
    stopMsgPolling() {
      if (this.msgPollingTimer) {
        clearInterval(this.msgPollingTimer);
        this.msgPollingTimer = null;
      }
    },
    getMsgCount(){
      getMsg().then(response => {
        // 计算所有未读消息总数
        let totalCount = 0;
        response.counts.forEach(item => {
          totalCount += item.total;
        });

        // 保存旧的消息计数
        this.previousMsgCount = this.msgCount;
        // 更新消息计数
        this.msgCount = totalCount;

        // 如果消息计数增加了，显示通知弹框
        if (this.msgCount > this.previousMsgCount && this.msgCount > 0) {
          this.$notify({
            title: '提示',
            message: '您有'+this.msgCount+"条消息通知",
            position: 'top-right',
            type: 'info'
          });
        }

      }).catch(error => {
        console.error("获取消息计数失败:", error);
      });
    },
    openMsg(){
      console.log(11);
      this.msg.open=true;
      // 每次打开消息界面时刷新数据
      if (this.$refs.msg) {
        this.$refs.msg.getMsg();
      }
      // 打开消息后重新获取消息计数来更新角标
      this.getMsgCount();
    },
    toggleSideBar() {
      this.$store.dispatch('app/toggleSideBar')
    },
    async logout() {
      this.$confirm('确定注销并退出系统吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$store.dispatch('LogOut').then(() => {
          location.href = '/index';
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.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;
  }

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

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

    &:focus {
      outline: none;
    }

    .right-menu-item {

      position: relative;
      display: inline-block;
      padding: 0 8px;
      height: 100%;
      font-size: 18px;
      color: #5a5e66;
      vertical-align: text-bottom;
      .msg{
        text-align: center;
        width:40px;
      }
       .dot{
          position: absolute;
          right:0px;
          top:0px;

        }

      &.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;
        }
      }
    }
  }
}

</style>

