<template>
  <div>
    <div class="im-msg-wrapper" :style="{bottom:!show?'-404px':'0px',width:!show?'200px':'300px'}">
      <div class="im-msg-head" :style="{'background-color':!show?'#fff':'#F2F8FD'}">
        <template v-if="!show">
          <div @click="showContent" class="text-left">
            <img :src="msgIcon">
            <span class="im-title">系统消息</span>
            <span class="im-head-num">
              <Badge :count="messageUnReadNum"></Badge>
            </span>
          </div>
        </template>
        <template v-else>
          <Row>
            <Col span="8" class="text-left"><img :src="msgIcon" style="margin-right:10px;">系统消息</Col>
            <Col span="12" class="text-right">
              <a class="im-head-closebtn" @click="readAllMessage">全设为已读</a>
            </Col>
            <Col span="4" class="text-right">
              <a class="im-head-closebtn" @click="showContent">收起</a>
            </Col>
          </Row>
        </template>
      </div>
      <div class="im-msg-body">
        <Tabs @on-click="handleClickTab">
          <TabPane :label="messageUnReadNum>0?label.info:'待办事项'" name="info">
          <!-- <TabPane :label="'待办事项'" name="info"> -->
            <ul class="im-msg-content" v-if="messageList.length>0">
              <Scroll :on-reach-bottom="handleReachBottom" :height="height">
                <template v-for="(item,index) in messageList">
                  <li class="msg-item" :class="{'is-read':item.issee==1}" :key="index" @click="readTurnTo(item,'info')">
                    <h4>
                      <span class="msg-date">{{item.create_time}}</span>
                      <a href="javascript:;">详情</a>
                    </h4>
                    <p class="msg-content">{{item.message_content}}</p>
                  </li>
                </template>
                <li class="msg-item text-center" style="border-bottom:none" v-if="noMore.info">没有更多了</li>
              </Scroll>
            </ul>
            <div class="text-center no-data" v-else>暂无待办事项</div>
          </TabPane>
        </Tabs>
      </div>
    </div>
  </div>
</template>

<script>
import socket from '@/libs/socket'
import { mapGetters, mapMutations } from 'vuex'
import { messageRead, messageList } from '@/api/message'
import store from 'store'
const msgIcon = require('@/assets/images/msg.png')
export default {
  name: 'message',
  data () {
    return {
      msgIcon,
      tabName: 'info',
      show: false,
      height: 400,
      typeMap: { 2: 'info', 1: 'notice', 3: 'warning' },
      typeMaps: { 'notice': 1, 'info': 2, 'warning': 3 },
      descMap: { info: '待办事项', notice: '进度提醒', warning: '预警消息' },
      noticeMap: { info: '你收到一条新的待办事项', notice: '你收到一条新的进度提醒', warning: '你收到一条新的预警信息' },
      noMore: {
        info: false,
        notice: false,
        warning: false
      },
      label: {
        info: (h) => {
          return h('div', [
            h('span', '待办事项'),
            h('Badge', {
              props: {
                dot: true
              }
            })
          ])
        },
        notice: (h) => {
          return h('div', [
            h('span', '进度提醒'),
            h('Badge', {
              props: {
                dot: true
              }
            })
          ])
        },
        warning: (h) => {
          return h('div', [
            h('span', '预警消息'),
            h('Badge', {
              props: {
                dot: true
              }
            })
          ])
        }
      },
    }
  },
  created () {
    // 其它页面未调用再调用改接口
    if (this.messageList.length === 0) {
      this.getMessageList()
    }
    // 未连接
    if (!socket.connected) {
      socket.open()
    }
    socket.emit('login', store.get('userinfo').user_id)
  },
  computed: {
    ...mapGetters(['messageList', 'messageUnReadNum'])
    // ...mapGetters(['messageList', 'messageUnReadNum', 'infoUnReadNum', 'noticeUnReadNum', 'warningUnReadNum'])
  },
  methods: {
    ...mapMutations(['addNewMsg', 'setUnRead', 'addAllMessage', 'setAllRead', 'addMoreMsg']),
    showContent () {
      this.show = !this.show
    },
    // 跳转
    turnTo (row, type) {
      if (row.message_type != 5 || row.message_type != 8 || row.message_type != 11 || row.message_type != 14 || row.message_type != 29 || row.message_type != 31) {
        this.$router.push({ name: row.name, query: JSON.parse(row.query) })
      } else {
        this.$Message.success('订单提示')
      }
      // let routeData = this.$router.resolve({
      //   name: item.name, query: JSON.parse(item.query)
      // })
      // window.open(routeData.href, '_blank')
    },
    readTurnTo (item, type) {
      if (item.issee == 1) {
        this.turnTo(item, type)
        return
      }
      messageRead({ ids: item.id }).then(res => {
        if (res.code === 1) {
          this.setUnRead(item)
          this.turnTo(item, type)
        }
      })
    },
    _reachBottomMsg () {
      const message = this.messageList
      if (message.length === 0) {
        return
      }
      // min_id最小数据
      messageList({ min_id: message[message.length - 1].id }).then(res => {
        if (res.code === 1 && res.data.list.length > 0) {
          this.addMoreMsg(res.data.list)
        } else {
          this.noMore[this.tabName] = true
        }
      })
    },
    // 滚动加载
    handleReachBottom () {
      return new Promise(resolve => {
        this._reachBottomMsg()
        resolve()
      })
    },
    // 获取所有未读信息
    getMessageList () {
      messageList({ min_id: '' }).then(res => {
        if (res.code === 1) {
          this.addAllMessage(res.data)
        }
      })
    },
    // 全部已读
    readAllMessage () {
      messageRead({ ids: '' }).then(res => {
        if (res.code === 1) {
          this.setAllRead()
        }
      })
    },
    // tab切换
    handleClickTab (name) {
      this.tabName = name
    }
  },
  mounted () {
    // 收到一条推送
    socket.on('newMsg', (res) => {
      this.$Notice.warning({
        title: res
      })
      this.getMessageList()
    })
    socket.on('update_online_count', (msg) => {
    })
    socket.on('reconnect_attempt', () => {
      // 重连使用polling优先
      socket.io.opts.transports = ['polling', 'websocket']
    })
    socket.on('reconnecting', () => {
      socket.emit('login', store.get('userinfo').user_id)
    })
    socket.on('reconnect_error', () => {
      console.log('reconnect_error')
    })
  },
  beforeDestroy () {
    socket.close()
  }
}
</script>
<style lang="less" scoped>
.im-msg-wrapper {
  position: fixed;
  z-index: 1000;
  right: 10px;
  bottom: -400px;
  height: 440px;
  width: 200px;
  background-color: #fff;
  box-shadow: 0 0 30px 0 rgba(0, 0, 0, 0.45);
  transition: all 0.2s linear 0s;
  .im-msg-head {
    color: #333;
    font-weight:400;
    height: 36px;
    line-height: 36px;
    padding: 0 10px;
    border-bottom: 1px solid #eee;
    cursor: pointer;
    background-color: #F2F8FD;
    .im-title {
      padding: 0 10px;
    }
    a{
      color: #333;
    }
  }
  .im-msg-body {
    /deep/.ivu-tabs > .ivu-tabs-bar .ivu-tabs-tab {
      margin-right: 0;
      border-radius: 0;
      background: #fff;
      color: #999;
      width: 33.3%;
      font-size: 14px;
      padding: 6px 18px;
    }
    /deep/ .ivu-scroll-loader{
      height: 0;
    }
    .im-msg-content {
      list-style: none;
      height: 400px;
      padding-bottom: 50px;
    }
    .msg-item {
      padding: 5px 6px;
      border-bottom: 1px solid #E6E6E6;
      &:last-child {
        margin-bottom: 40px;
      }
      .msg-date {
        margin-right: 10px;
        font-size: 14px;
        font-family:'MicrosoftYaHei-Bold';
        font-weight:bold;
      }
      p {
        font-size: 14px;
      }
      a{
        color: #333;
      }
      h4{
        margin: 5px 0;
      }
    }
    /deep/ .ivu-badge-dot {
      top: -11px;
      right: -14px;
    }
    /deep/ .ivu-scroll-container {
      overflow-y: auto;
    }
    .no-data {
      padding-top: 170px;
    }
    .is-read {
      color: #ccc !important;
      a {
        color: #ccc !important;
      }
    }
    .msg-content {
      cursor: pointer;
    }
  }
}
</style>
<style>
.im-msg-wrapper .ivu-tabs-bar{
 border-bottom: 2px solid #E6E6E6;
}
.im-msg-wrapper .ivu-tabs-ink-bar {
  display: none !important;
}
.im-msg-wrapper .ivu-tabs-nav{
  width: 100%;
}
.im-msg-wrapper .ivu-tabs-nav::after{
content: "";
transition: all 0.2s linear 0s;
}
.im-msg-wrapper .ivu-tabs-nav .ivu-tabs-tab-active::after,.line::after {
  content: "";
  width: 30px;
  height: 3px;
  background: #5389FF;
  right: 50%;
  bottom: 0;
  margin-right: -15px;
  position: absolute;
}
.im-msg-wrapper .ivu-tabs-tab-active{
  color: #4F81FF !important;
}
.im-msg-wrapper .ivu-tabs-nav .ivu-tabs-tab:hover{
  background-color: #fff  !important;
}
</style>
