<template>
  <div class="wrapper" v-if="!onlySeeRed">
    <div class="list-box" ref="chatListBox" @scroll="getMore">
      <div class="loading" v-show="!isAjax">{{ list.length ? loadingMsg : '还没有评论' }}</div>
      <div id="chatList" class="list" ref="chatList">
        <div class="item" v-for="item in list" :key="item.id" :data-chatid="item.id">
          <chat-item :info="item"></chat-item>
        </div>
      </div>
    </div>
    <transition name="move-bottom">
      <div class="chat-unread" v-show="unreadChatNum">
        <span @click="_scrollBottom">{{ unreadChatNum }}条消息未读</span>
      </div>
    </transition>
    <transition name="move-left">
      <div class="chat-reply" v-show="replyChatId">
        <span class="title" @click="_scrollReply">有人提到了我</span>
        <span class="close" @click="_closeReply">x</span>
      </div>
    </transition>
  </div>
  <div class="wrapper" v-else>
    <div class="list-box" ref="chatListBox">
      <div id="chatList" class="list" ref="chatList">
        <div class="loading" v-if="redList.length == 0">暂无数据</div>
        <div class="item" v-for="item in redList" :key="item.id" :data-chatid="item.id">
          <chat-item :info="item"></chat-item>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getChatList } from '@/plugins/API/apiAll';
import { mapGetters } from 'vuex';
import chatItem from './chatItem/index';
export default {
  name: 'chat-list',
  components: {
    chatItem
  },
  data() {
    return {
      isAjax: true,
      loadingMsg: '',
      page: 1,
      num: 50,
      list: [],
      redList: [],
      unreadChatNum: 0,
      replyChatId: ''
    };
  },
  computed: {
    ...mapGetters({
      userInfo: 'userInfo',
      channelInfo: 'channelInfo',
      onlySeeRed: 'onlySeeRed'
    })
  },
  mounted() {
    this.$Bus.$on('bus-addChat', this.addChat);
    this.$Bus.$on('bus-delChat', this.delChat);
    this.getChatList();
  },
  methods: {
    getMore() {
      const chatListBoxDom = this.$refs.chatListBox;
      const chatListDom = this.$refs.chatList;
      if (chatListBoxDom && chatListDom) {
        const boxHeight = chatListBoxDom.clientHeight;
        const boxScrollTop = chatListBoxDom.scrollTop;
        const listHeigth = chatListDom.clientHeight;
        if (boxScrollTop <= 100) {
          this.getChatList();
        }
        if (listHeigth - boxHeight - boxScrollTop < 250) {
          this.unreadChatNum = 0;
        }
      }
    },
    async getChatList() {
      if (!this.isAjax) {
        return false;
      }
      this.isAjax = false;
      this.loadingMsg = '加载中...';

      const res = await getChatList({
        uin: this.channelInfo.uin,
        channelId: this.channelInfo.id,
        page: this.page,
        num: this.num
      });

      if (res.code === 200 && res.errorCode === 0) {
        const list = res.data || [];
        const firstLi =
          document.querySelector('#chatList') && document.querySelector('#chatList').children[0];
        list.forEach(item => {
          this.addChat(item, true);
        });
        this.$nextTick(() => {
          if (this.page === 1) {
            this._scrollBottom();
          } else {
            const chatListBoxDom = this.$refs.chatListBox;
            if (chatListBoxDom && firstLi) {
              chatListBoxDom.scrollTop = firstLi.offsetTop;
            }
          }
          if (list.length < 50) {
            this.isAjax = false;
            this.loadingMsg = '已加载所有评论';
          } else {
            this.page++;
            this.isAjax = true;
            this.loadingMsg = '下拉加载更多';
          }
        });
      } else {
        this.isAjax = true;
        this.loadingMsg = '';
      }
    },
    addRedList(obj, order) {
      this.redList = this.redList.filter(x => {
        return Number(x.id) !== Number(obj.id);
      });
      if (order) {
        this.redList.unshift(obj);
      } else {
        this.redList.push(obj);
      }
    },
    delRedList(id) {
      this.redList = this.redList.filter(x => {
        return Number(x.id) !== Number(id);
      });
    },
    addChat(obj, order = false) {
      const chatObj = obj;
      const redType = [3, 8]; // msgType红包类型
      this.list = this.list.filter(x => {
        return Number(x.id) !== Number(chatObj.id);
      });
      if (redType.indexOf(Number(chatObj.msgType)) !== -1) {
        chatObj.showTime = true;
        this.addRedList(chatObj, order);
      }
      if (this.list.length) {
        const newTime = chatObj.addTime;
        const prevTime = order ? this.list[0].addTime : this.list[this.list.length - 1].addTime;
        if (Math.abs(newTime - prevTime) > 600) {
          chatObj.showTime = true;
        }
      }
      if (order) {
        this.list.unshift(chatObj);
      } else {
        this.list.push(chatObj);
        this._chatReplay(chatObj);
        this._scrollKeep();
      }
      if (this.list.length > 250) {
        this.list.splice(50, 100);
      }
    },
    delChat(id) {
      this.list = this.list.filter(x => {
        return Number(x.id) !== Number(id);
      });
      this.delRedList(id);
    },
    _scrollKeep() {
      const chatListBoxDom = this.$refs.chatListBox;
      const chatListDom = this.$refs.chatList;
      if (chatListBoxDom && chatListDom) {
        const boxHeight = chatListBoxDom.clientHeight;
        const boxScrollTop = chatListBoxDom.scrollTop;
        const listHeigth = chatListDom.clientHeight;
        if (boxHeight + boxScrollTop > listHeigth - 250) {
          this.$nextTick(() => {
            chatListBoxDom.scrollTop = this.$refs.chatList.clientHeight;
          });
        } else {
          this.unreadChatNum++;
        }
      }
    },
    _scrollBottom() {
      const chatListBoxDom = this.$refs.chatListBox;
      const chatListDom = this.$refs.chatList;
      if (chatListBoxDom && chatListDom) {
        const listHeigth = chatListDom.clientHeight;
        chatListBoxDom.scrollTop = listHeigth;
      }
    },
    _chatReplay(obj) {
      if (this.replyChatId || !obj.replyOpenUid) {
        return false;
      }
      if (obj.replyOpenUid === this.userInfo.openUid) {
        this.replyChatId = obj.id;
      }
    },
    _scrollReply() {
      const id = this.replyChatId;
      const el = document.querySelectorAll(`[data-chatid="${id}"]`)[0];
      if (!el) {
        this._scrollBottom();
        return false;
      }
      const scrollTop = el.offsetTop;
      this.$refs.chatListBox.scrollTop = scrollTop;
      this._closeReply();
    },
    _closeReply() {
      this.replyChatId = '';
    }
  },
  watch: {
    onlySeeRed() {
      this.$nextTick(() => {
        this._scrollBottom();
      });
    }
  },
  beforeDestroy() {
    this.$Bus.$off('bus-addChat', this.addChat);
    this.$Bus.$off('bus-delChat', this.delChat);
  }
};
</script>

<style lang="less" scoped>
.wrapper {
  position: relative;
  height: 100%;
}
.list-box {
  position: relative;
  z-index: 0;
  height: 100%;
  width: 100%;
  overflow-y: auto;
  .loading {
    height: 0.3rem;
    line-height: 0.3rem;
    text-align: center;
    color: #858587;
    font-size: 0.14rem;
  }
  .list {
    position: relative;
    .item {
      padding: 0.05rem 0.1rem;
    }
  }
}
.chat-unread {
  position: absolute;
  bottom: 0.1rem;
  left: 0;
  z-index: 1;
  width: 100%;
  text-align: center;
  span {
    padding: 0.03rem 0.1rem;
    background-color: var(--main-color);
    border-radius: 0.3rem;
    font-size: 0.12rem;
    color: #fff;
  }
}
.chat-reply {
  position: absolute;
  bottom: 0.1rem;
  left: 0.1rem;
  z-index: 1;
  padding: 0.03rem 0.05rem;
  background-color: var(--main-color);
  border-radius: 0.03rem;
  .title {
    color: #fff;
    font-size: 0.14rem;
  }
  .close {
    display: inline-block;
    vertical-align: top;
    margin-left: 0.03rem;
    font-size: 0.16rem;
    color: #333;
    cursor: pointer;
  }
}
</style>
