<template>
    <div class="msg-count-tips" v-if="totalMsgCount > 0"> 
      <span :style="tipsStyles">{{totalMsgCount}}</span>
    </div>
</template>

<script>
import msgApi from "../../api/message.js";
import {mapGetters, mapMutations, mapActions} from "vuex";

export default {
  props: ['groupId', 'position', 'needReload'],
  data: () => ({   
    useStore: true,
    allTypeMsgCounts: {}
  }),
  created() {
    let self = this;
    window.removeListener("reloadMsgCounts");
    window.addListener("reloadMsgCounts", self.reloadMsgCounts, false);
  },
  mounted(){
    this.useStore = this.$store !== undefined;
    if(!this.needReload) return false;

    if(!this.useStore && Object.keys(this.allTypeMsgCounts) === 0){
      this.loadTaskMsg();
      return;
    }

    if(this.useStore && (!this.getMsgInfos() || Object.keys(this.getMsgInfos()).length === 0)){
      this.loadMsgsByGroup(this.groupId);
      return;
    }
  },
  computed: {
    totalMsgCount(){
      let total = 0;
      if(this.useStore){
        total = this.getMsgCounts(this.groupId);
      }else{
        total = this.getMsgCountByGroup(this.allTypeMsgCounts, this.groupId);
      }
      return total > 99 ? '...' : total;
    },

    tipsStyles(){
      let self = this;
      let offset = $.extend({top:0, left:0}, self.position); 
      return {
        position: "relative",
        top: offset.top + "px",
        left: offset.left + "px",
      }
    },

    ...mapGetters(['getMsgInfos', 'getMsgCounts'])
  },
  watch: {

  },
  methods: {
    ...mapActions(['loadMsgsByGroup', 'ignoreMsgCount']),

    loadTaskMsg(){
      let self = this;
      msgApi.getMessages("", function(result) {
        if (!result || !result.MsgCounts) return;
        self.allTypeMsgCounts = result.MsgCounts;
      });
    },

    reloadMsgCounts(){
      let self = this;
      if(self.useStore){
        self.loadMsgsByGroup(self.groupId);
        return;
      }
      self.loadTaskMsg();
      return;
    },

    getMsgCountByGroup(msgCounts, groupId){
      if(!msgCounts || msgCounts.length == 0){
        return 0;
      }
      if(!groupId){           
        let total = 0;
        for (let item in msgCounts) {
          total += msgCounts[item];
        }
        return total;
      }
      for (let item in msgCounts) {
        if(item === groudId)
          return msgCounts[item];
      }
      return 0;
    },
  }
};
</script>
<style lang="less" scoped>
  .msg-count-tips{
    position: absolute;
    top:0;
    left:0;
    span {
      display: inline-block;
      width: 18px;
      height: 18px;
      line-height: 16px;
      font-size: 12px;
      background: rgb(244, 53, 48);
      color: #fff;
      border-radius: 50%;
      text-align: center;
      cursor: pointer;
    }
  }
</style>