<template>
  <div>
    <!--个人配置 start-->
    <div class="fr fr-admin menu-hover-class">
      <el-popover
        v-model="visible"
        placement="bottom-end"
        trigger="click"
      >
        <div style="width: 300px;">
          <div style="margin:10px;">
            <ul class="set-menu">
              <li v-for="item in setMenuList" :key="item.id" @click="_getName(item)">
                <i class="iconfont" :class="item.icon" style="color:#788d9b;font-size: 25px" />
                <p style="font-size: 12px;padding-top:5px;color:#788d9b;">
                  {{ item.name }}
                </p>
              </li>
            </ul>
          </div>
          <div style="text-align: center;border-top: 1px solid #eee; padding:10px 0" @click="_logout">
            <p style="font-size: 14px;cursor: pointer" class="red-color">
              退出系统
            </p>
          </div>
        </div>
        <div slot="reference">
          <img :src="loginUser" style="line-height: 20px" class="admin-avatar">
          <div class="admin">
            {{ admin }}
          </div>
        </div>
      </el-popover>
    </div>
    <!--个人配置 end-->
    <!--全屏显示 start-->
    <div class="fr menu-hover-class header-setting-width" @click="_toggleScreen">
      <i
        class="el-icon-rank header-common-line-height"
      />
    </div>
    <!--全屏显示 end-->
    <!--皮肤 start-->
    <div class="fr menu-hover-class header-setting-width">
      <!--<el-popover placement="bottom-end" trigger="click">-->
      <!--<div>-->
      <!--<ul class="skin-item">-->
      <!--<li v-for="(item, index) in themeList" :key="index" :name="item.name" @click="_getSkin(item.name)">-->
      <!--<Row type="flex" justify="center" align="middle">-->
      <!--<span>-->
      <!--<Icon size="22" :type="item.name=== themeFile?'md-heart':'md-heart-outline'" :color="item.element" />-->
      <!--</span>-->
      <!--</Row>-->
      <!--</li>-->
      <!--</ul>-->
      <!--</div>-->
      <!--<div slot="reference">-->
      <!--<Icon type="ios-shirt-outline" size="25" color="#fff" style="cursor: pointer;line-height: 50px" />-->
      <!--</div>-->
      <!--</el-popover>-->
      <topTheme />
    </div>
    <!--皮肤 end-->
    <!--消息通知 start-->
    <div class="fr menu-hover-class header-setting-width">
      <el-popover placement="bottom-end" trigger="click">
        <!--有消息提醒-->
        <div style="width:350px;">
          <el-tabs v-model="activeName" style="padding-left: 10px">
            <!--通知-->
            <el-tab-pane :label="tabs.inform" name="inform">
              <div v-if="informList.length == 0" style="position: relative;height: 350px;">
                <img :src="noNewsUri" class="no-news-class">
              </div>
              <div v-else>
                <ul class="inform-item" style="overflow-y:auto">
                  <li v-for="item in informList" :key="item.id" @click="_more">
                    <div class="inform-item-avatar">
                      <span><img :src="informUri"></span>
                    </div>
                    <div class="inform-item-cont">
                      <p class="inform-item-descript" style="font-weight: bold">
                        {{ item.title }}
                      </p>
                      <p class="inform-item-descript">
                        {{ item.content }}
                      </p>
                      <p class="inform-item-time">
                        <Time :time="item.ctime" :interval="1" />
                      </p>
                    </div>
                  </li>
                </ul>
                <div class="notice-more" @click="_more">
                  <a>查看更多</a>
                </div>
              </div>
            </el-tab-pane>
            <!--消息-->
            <el-tab-pane :label="tabs.news" name="news">
              <div v-if="noticeList.length == 0" style="position: relative;height: 350px;">
                <img :src="noNewsUri" class="no-news-class">
              </div>
              <div v-else>
                <ul class="inform-item" style="overflow-y:auto">
                  <li v-for="item in noticeList" :key="item.id" @click="_more">
                    <div class="inform-item-avatar">
                      <span><img :src="noticeUri"></span>
                    </div>
                    <div class="inform-item-cont">
                      <p class="inform-item-descript" style="font-weight: bold">
                        {{ item.title }}
                      </p>
                      <p class="inform-item-descript">
                        {{ item.content }}
                      </p>
                      <p class="inform-item-time">
                        <Time :time="item.ctime" :interval="1" />
                      </p>
                    </div>
                  </li>
                </ul>
                <div class="notice-more" @click="_more">
                  <a>查看更多</a>
                </div>
              </div>
            </el-tab-pane>
            <!--待办-->
            <el-tab-pane :label="tabs.todo" name="todo">
              <div v-if="todoList.length == 0" style="position: relative;height: 350px;">
                <img :src="noNewsUri" class="no-news-class">
              </div>
              <div v-else>
                <ul class="inform-item" style="overflow-y:auto">
                  <li v-for="item in todoList" :key="item.id" style="padding:12px 15px" @click="_myTask">
                    <div class="inform-item-cont" style="width:100%">
                      <p class="inform-item-descript">
                        {{ item.title }}
                      </p>
                    </div>
                  </li>
                </ul>
                <div class="notice-more" @click="_myTask">
                  <a>查看更多</a>
                </div>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>

        <div slot="reference">
          <el-badge :value="messageCount" :max="99" class="notice-badge">
            <i
              v-if="messageCount == 0"
              class="el-icon-bell header-common-line-height"
            />
            <i
              v-else
              id="notice-flash"
              class="el-icon-bell header-common-line-height"
            />
          </el-badge>
        </div>
      </el-popover>
    </div>
    <!--消息通知 end-->
  </div>
</template>
<script>
import Store from 'store2'
import SockJS from 'sockjs-client'
import Stomp from 'webstomp-client'
import screenfull from 'screenfull'
import { sysSso, sysUser, flowProcess, sysMessage } from '../../api'
import global from '../../api/config'
import topTheme from './topTheme'
const schedule = require('node-schedule')
export default {
  components: { topTheme },
  data() {
    return {
      // defaultColor: '#409EFF',
      activeName: 'inform',
      loginUser: '',
      admin: '',
      setMenuList: [
        {
          icon: 'pt-home-outline',
          name: '我的首页',
          url: '/sys/personal_data/my_home',
          element: 'self_home'
        },
        {
          icon: 'pt-man',
          name: '基本资料',
          url: '/sys/personal_data/base_info',
          element: 'self_info'
        },
        {
          icon: 'pt-posting',
          name: '修改密码',
          url: '/sys/personal_data/password_edit',
          element: 'self_psd'
        },
        { icon: 'pt-locked', name: '锁屏', url: '', element: 'locked' },
        {
          icon: 'pt-star',
          name: '多标签',
          url: '',
          element: 'toggle'
        }
      ],
      visible: false,
      imgUri: global.staticURL + '/img/notice/notice.png',
      noImgUri: global.staticURL + '/img/notice/no-notice.png',
      noNewsUri: global.staticURL + '/img/notice/no-news.png',
      tabs: { inform: '通知', news: '消息', todo: '待办' },
      allSum: '',
      messageCount: '0',
      dotCount: '3',
      informUri: global.staticURL + '/img/notice/email.png',
      informList: [],
      noticeUri: global.staticURL + '/img/notice/news.png',
      noticeList: [],
      todoSum: '', // 待办数量
      todoList: [],
      taskObj: {
        // 我的任务
        count: 0,
        title: '',
        ctime: '',
        uri: ''
      }
    }
  },
  // 监听消息的数量的变化
  computed: {
    msgNum() {
      return this.$store.state.msgNum
    }
  },
  watch: {
    msgNum: {
      handler: function(val, oldVal) {
        this._refreshNotice()
      },
      immediate: true
    }
  },
  mounted() {
    if (global.getLn()) {
      this._getMyAvatar()
      // 刷新消息
      this._refreshNotice()
      // 连接实时推送
      this._connectWs()
      this._workflow()
    }
  },
  methods: {
    // 点击菜单
    _getName(data) {
      if (data.element === 'locked') {
        // 锁屏
        this.$store.commit('setLock')
        setTimeout(() => {
          this.$router.push('/lock')
        }, 100)
      } else if (data.element === 'toggle') {
        // 多标签
        this.$store.commit('clearAllTags')
        this._changeTags()
      } else {
        // 其他
        // window.open(global.webURL + '/#/sysmanage?query=' + data, '_blank')
        this._goto(data.url)
      }
    },
    // 多标签
    _changeTags: function() {
      const navTags = Store.get('navTags')
      if (navTags === 'true') {
        // 关闭标签
        this.$emit('on-result-change', 'navTags-false')
        Store.set('navTags', 'false')
      } else {
        // 打开标签
        this.$emit('on-result-change', 'navTags-true')
        Store.set('navTags', 'true')
      }
    },
    // 获取头像
    _getMyAvatar: async function() {
      // 缓存个人信息
      const userInfo = global.getUserInfo()
      let result = ''
      if (userInfo) {
        result = userInfo
      } else {
        result = await sysUser.getUserInfo()
        global.setUserInfo(result)
      }
      this.admin = result.username
      if (result.avatar === undefined) {
        this.loginUser = global.staticURL + '/img/loginUser.jpg'
      } else {
        this.loginUser =
          global.baseURL + '/base/v1/company/logo?key=' + result.avatar
      }
    },
    // 退出
    _logout: function() {
      this.visible = false
      this.$confirm('确定要退出系统?', '提示', { type: 'warning' })
        .then(() => {
          this._ok()
        })
        .catch(() => {
          this.visible = true
        })
    },
    // 确定
    _ok: async function() {
      const result = await sysSso.logout()
      if (result) {
        global.logout()
        this.$store.commit('clearAllTags')
        // window.location.href = global.ssoURL
        this.$router.push('/login')
      } else {
        this.$message.error('退出失败，请重试!')
      }
    },
    // 是否全屏
    _toggleScreen() {
      if (!screenfull.enabled) {
        // 如果不允许进入全屏，发出不允许提示
        this.$message({
          message: '不支持全屏',
          type: 'warning'
        })
        return false
      }
      screenfull.toggle()
    },
    /** ***************************消息************************************/
    _myTask() {
      this._goto('/sys/workflow/flow_task')
    },
    _more() {
      this._goto('/sys/message_manage/my_message')
    },
    _goto(route) {
      this.$router.push(route)
    },
    // 刷新消息数量
    _refreshNotice() {
      this._getNotice()
    },
    // 获取消息数据
    _getNotice: async function() {
      const noticeAll = await sysMessage.list()
      if (noticeAll.sum === undefined) {
        this.allSum = ''
        this.messageCount = 0
      } else {
        this.allSum = noticeAll.sum
        this.messageCount = noticeAll.sum
      }
      // 通知
      if (noticeAll.informList !== undefined) {
        this.informList = noticeAll.informList.list
        this.tabs.inform = '通知 ' + '(' + noticeAll.informList.sum + ')'
      } else {
        this.informList = []
        this.tabs.inform = '通知'
      }
      // 消息
      if (noticeAll.noticeList !== undefined) {
        this.noticeList = noticeAll.noticeList.list
        this.tabs.news = '消息 ' + '(' + noticeAll.noticeList.sum + ')'
      } else {
        this.noticeList = []
        this.tabs.news = '消息'
      }
      // 待办
      if (noticeAll.todoList !== undefined) {
        this.todoList = noticeAll.todoList.list
        this.todoSum = noticeAll.todoList.sum
        this.tabs.todo = '待办 ' + '(' + noticeAll.todoList.sum + ')'
      } else {
        this.todoList = []
        this.tabs.todo = '待办'
      }

      this._totalTask()
    },
    _totalTask: async function() {
      const result = await flowProcess.totalTask()
      if (result) {
        this._task(result, 'read-my-message')
      }
    },
    _task(count, msgLabel) {
      if (msgLabel === undefined) {
        // 监听消息的时候不提示
        this.$notify({
          title: '您有 ' + count + ' 条任务消息，请注意查收！'
        })
      }
      this.taskObj.title = '我的任务数量：' + count
      this.taskObj.count = count
      this.taskObj.ctime = this.$dateformat(new Date(), 'yyyy-mm-dd HH:MM')
      const todoSum = this.todoSum + Number(count)
      this.tabs.todo = '待办 ' + '(' + todoSum + ')'
      this.messageCount = Number(this.allSum) + Number(count)
      console.log('total==', this.messageCount, count)
      if (this.todoList.length === 0) {
        this.todoList.splice(0, 0, this.taskObj) // 添加到数组最头上
      } else if (this.todoList[0].count === undefined) {
        // 没有数据
        this.todoList.splice(0, 0, this.taskObj) // 添加到数组最头上
      } else {
        // 已有数据
        this.todoList.splice(0, 1) // 删除第一项
        this.todoList.splice(0, 0, this.taskObj) // 添加到数组最头上
      }
    },
    _connectWs: function() {
      const socket = new SockJS(global.baseURL + '/ws')
      const stompClient = Stomp.over(socket)
      stompClient.connect(
        {},
        frame => {
          stompClient.subscribe('/sys-user/topic/message', message => {
            if (message.body !== undefined) {
              const data = JSON.parse(message.body)
              this._refreshNotice()
              this.$notify({
                title: '您有新的消息，请注意查收！',
                message: data.content + ',【 发件人：' + data.sender + ' 】'
              })
            }
          })
        },
        error => {
          console.log('---ws---', error)
        }
      )
    },
    _workflow() {
      const that = this
      // 工作流消息定时任务
      // https://www.npmjs.com/package/node-schedule
      that._totalTask()
      schedule.scheduleJob({ minute: 5 }, function() {
        that._totalTask()
      })
    }
    /** ***************************消息************************************/
  }
}
</script>
