<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.name" @click="_getName(item.element)">
                <Icon :type="item.icon" :size="25" color="#788d9b" />
                <p>{{ item.name }}</p>
              </li>
            </ul>
          </div>
          <div style="text-align: center;border-top: 1px solid #eee; padding:10px 0" @click="_logout">
            <p style="color: #ed3f14;font-size: 14px;cursor: pointer">
              <Icon type="md-power" color="#ed3f14" />&nbsp;
              退出系统
            </p>
          </div>
        </div>

        <div slot="reference">
          <Avatar :src="loginUser" />
          <div class="admin">
            {{ admin }}
          </div>
        </div>
      </el-popover>
    </div>
    <!--个人配置 end-->
    <!--全屏显示 start-->
    <div class="fr menu-hover-class header-setting-width" @click="_toggleScreen">
      <el-tooltip effect="dark" :content="!isExpand ? '全屏' : '退出全屏'" placement="bottom-end">
        <Icon
          :type="!isExpand ? 'ios-expand' : 'ios-contract'"
          size="25"
          style="cursor: pointer;line-height: 50px"
          color="#fff"
        />
      </el-tooltip>
    </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>
    </div>
    <!--皮肤 end-->
    <!--消息通知 start-->
    <div class="fr menu-hover-class header-setting-width">
      <el-popover placement="bottom-end" trigger="click">
        <!--有消息提醒-->
        <div style="width:350px;">
          <Tabs value="inform" class="tabsHidden">
            <!--通知-->
            <TabPane :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">
                  <li v-for="(item, index) in informList" :key="index" @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">
                        <!--{{$formatDateSecond(item.ctime)}}-->
                        <Time :time="item.ctime" :interval="1" />
                      </p>
                    </div>
                  </li>
                </ul>
                <div class="notice-more" @click="_more">
                  <a>查看更多</a>
                </div>
              </div>
            </TabPane>
            <!--消息-->
            <TabPane :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">
                  <li v-for="(item, index) in noticeList" :key="index" @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">
                        <!--{{$formatDateSecond(item.ctime)}}-->
                        <Time :time="item.ctime" :interval="1" />
                      </p>
                    </div>
                  </li>
                </ul>
                <div class="notice-more" @click="_more">
                  <a>查看更多</a>
                </div>
              </div>
            </TabPane>
            <!--待办-->
            <TabPane :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">
                  <li v-for="(item, index) in todoList" :key="index" 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>
            </TabPane>
          </Tabs>
        </div>

        <div slot="reference">
          <el-badge :value="messageCount" :max="99" class="notice-badge">
            <Icon
              v-if="messageCount == 0"
              type="ios-notifications-outline"
              :size="25"
              style="cursor: pointer;line-height: 50px"
              color="#fff"
            />
            <Icon
              v-else
              id="notice-flash"
              type="md-notifications-outline"
              :size="25"
              style="cursor: pointer;line-height: 50px"
              color="#fff"
            />
          </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 { sysSso, sysUser, flowProcess, sysMessage } from '../../api'
import global from '../../api/config'
const schedule = require('node-schedule')
export default {
  data() {
    return {
      loginUser: '',
      admin: '',
      setMenuList: [
        { icon: 'ios-home', name: '我的首页', url: '', element: 'self_home' },
        { icon: 'ios-copy', name: '基本资料', url: '', element: 'self_info' },
        { icon: 'ios-create', name: '修改密码', url: '', element: 'self_psd' },
        { icon: 'ios-lock', name: '锁屏', url: '', element: 'locked' },
        { icon: 'md-pricetags', name: '多标签', url: '', element: 'toggle' }
      ],
      visible: false,
      isExpand: 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',
      themeLink: '',
      path: '',
      // 默认引用皮肤css(蓝色)
      defaultPath: `${global.staticURL}/theme/my-theme/b.less`,
      themeFile: '',
      themeList: [
        { name: 'black_b', element: '#1c2438' },
        { name: 'green_g', element: '#32b16c' },
        { name: 'blue_b', element: '#00a0e9' }
        // { name: 'theme-star', element: '#6600FF' }
      ],
      informUri: `${global.staticURL}/img/notice/email.png`,
      informList: [],
      noticeUri: `${global.staticURL}/img/notice/news.png`,
      noticeList: [],
      todoSum: '', // 待办数量
      todoList: [],
      taskObj: {
        // 我的任务
        count: 0,
        title: '',
        ctime: '',
        uri: ''
      },
      timeLock: null
    }
  },
  mounted() {
    if (global.getLn()) {
      this._getMyAvatar()
      // 刷新消息
      this._refreshNotice()
      // 连接实时推送
      this._connectWs()
      this._workflow()
      this._localStorageSkin()
      // 定时锁屏
      this._timeLock()
      window.addEventListener('mouseup', this._timeLock)
    }
  },
  methods: {
    // 定时锁屏
    _timeLock() {
      clearTimeout(this.timeLock)
      this.timeLock = null
      this.timeLock = setTimeout(() => {
        Store.session('formPath', this.$route.path)
        this.$router.replace('/lock')
        window.removeEventListener('mouseup', this._timeLock, false)
      }, 1800000)
    },
    // 点击菜单
    _getName(data) {
      if (data === 'locked') {
        // 锁屏
        // 记录跳转到锁屏之前的界面
        Store.session('formPath', this.$route.path)
        this.$router.replace('/lock')
        window.removeEventListener('mouseup', this._timeLock, false)
      } else if (data === 'toggle') {
        // 多标签
        this.$store.commit('clearAllTags')
        this._changeTags()
      } else {
        // 其他
        // window.open(global.webURL + '/#/sysmanage?query=' + data, '_blank')
        window.open(global.webURL + '/sys/personal_data/my_home', '_blank')
      }
    },
    // 多标签
    _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')
      }
    },
    _localStorageSkin() {
      // localStorage 保存皮肤css路径
      this.themeLink = document.querySelector('link[name="theme"]')
      const themePath = localStorage.getItem('path')
        ? localStorage.getItem('path')
        : this.defaultPath
      const file = localStorage.getItem('themeFile')
        ? localStorage.getItem('themeFile')
        : 'blank_b'
      this.themeFile = file
      if (themePath) {
        this.themeLink.setAttribute('href', themePath)
      }
      this.$emit('on-skin-change', file)
      // 添加script标签(pageoffice使用)
      const s = document.createElement('script')
      s.type = 'text/javascript'
      s.id = 'po_js_main'
      s.src = global.baseURL + '/print/pageoffice.js'
      document.body.appendChild(s)
    },
    // 皮肤
    _getSkin(themeFile) {
      this.themeFile = themeFile
      const mainTheme = themeFile.substr(-1, 1)
      this.path = `${global.staticURL}/theme/my-theme/${mainTheme}.less`
      this.themeLink.setAttribute('href', this.path)
      // 向父级传递数据，改变皮肤颜色
      this.$emit('on-skin-change', themeFile)
      localStorage.setItem('themeFile', this.themeFile)
      localStorage.setItem('path', this.path)
    },
    // 获取头像
    _getMyAvatar: async function() {
      const 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.$Modal.confirm({
        title: '提示',
        content: '<p>确定要退出系统？</p>',
        onOk: () => this._ok(),
        onCancel: () => (this.visible = true)
      })
    },
    // 确定
    _ok: async function() {
      const result = await sysSso.logout()
      if (result) {
        global.logout()
        this.$store.commit('clearAllTags')
        window.location.href = global.ssoURL
      } else {
        this.$Message.error('退出失败，请重试!')
      }
    },
    // 是否全屏
    _toggleScreen() {
      if (!this.isExpand) {
        const docElm = document.documentElement
        if (docElm.requestFullscreen) {
          docElm.requestFullscreen()
        } else if (docElm.mozRequestFullScreen) {
          docElm.mozRequestFullScreen()
        } else if (docElm.webkitRequestFullScreen) {
          docElm.webkitRequestFullScreen()
        } else if (docElm.msRequestFullscreen) {
          docElm.msRequestFullscreen()
        } else {
        }
        this.isExpand = true
      } else {
        if (document.exitFullscreen) {
          document.exitFullscreen()
        } else if (document.mozCancelFullScreen) {
          document.mozCancelFullScreen()
        } else if (document.webkitCancelFullScreen) {
          document.webkitCancelFullScreen()
        } else if (document.msExitFullscreen) {
          document.msExitFullscreen()
        } else {
        }
        this.isExpand = false
      }
    },
    /** ***************************消息************************************/
    _myTask() {
      this._getName('my_task')
    },
    _more() {
      this._getName('my_notice')
    },
    // 刷新消息数量
    _refreshNotice() {
      this._totalTask()
      this._getNotice()
    },
    // 获取消息数据
    _getNotice: async function() {
      const noticeAll = await sysMessage.list()
      console.log(noticeAll)
      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 = '待办'
      }
    },
    _totalTask: async function() {
      const result = await flowProcess.totalTask()
      if (result) {
        this._task(result, 'read-my-message')
      }
    },
    _task(count, msgLabel) {
      if (msgLabel === undefined) {
        // 监听消息的时候不提示
        this.$Notice.success({
          title: '您有 ' + count + ' 条任务消息，请注意查收！',
          duration: 20
        })
      }
      this.taskObj.title = '我的任务数量：' + count
      this.taskObj.count = count
      this.taskObj.ctime = this.$dateformat(new Date(), 'yyyy-mm-dd HH:MM')
      const todoSum = this.todoSum + count * 1
      this.tabs.todo = '待办 ' + '(' + todoSum + ')'
      this.messageCount = this.allSum + count * 1
      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}/message/ws`)
      const stompClient = Stomp.over(socket)
      stompClient.connect(
        {},
        frame => {
          stompClient.subscribe('/user/topic/message', message => {
            if (message.body !== undefined) {
              const data = JSON.parse(message.body)
              this._refreshNotice()
              this.$Notice.success({
                title: '您有新的消息，请注意查收！',
                duration: 20,
                desc: 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>
