<!-- 聊天列表 -->
<template>
  <div class="left-user">
      <div class="left-top-search">
            <el-input prefix-icon="el-icon-search" size="mini" id="filter-users" v-model="filterText" class="inline-block" placeholder="搜索" @input="filterUserChange"/>
        </div>
        <div class="user-list" v-if="pageType === '1'">
            <div class="user-list-title">
                <span>好友列表</span>
            </div>
            <ul id="allUserList" class="padding-0 mg-0 border-bottom">
                <li :class="['border-bottom','name-li',item.isOnline ? '':'unlive',item.isClick ? 'active':'']" v-for="(item,index) in allUsersShowData" :key="index" @click="getChart(0,item)">
                    <img :src="item.user.avatarImageUrl ? item.user.avatarImageUrl : require('../../../static/avatar.jpg')"/>
                    <div :class="item.hasUnReadLog ? 'message-circle':''"></div>
                    <div class="name-content">
                            <div>
                                <span class="name ellipse inline-block">{{item.user.userName}}</span>
                                <span class="time">{{getChatTimeAndContent(item.lastChat,false).createdTime}}</span>
                            </div>
                            <div class="content ellipse" v-html="getChatTimeAndContent(item.lastChat,false).content"></div>
                        </div>
                </li>
            </ul>
        </div>
        <div class="group-list">
            <div class="user-list-title bd-top">
                <span>群组列表</span>
                <el-dropdown class="dropdown add-icon pull-right" @command="command">
                    <span>
                        <div class="iconfont icon-xinzeng cursor" id="dLabel" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"></div>
                    </span>
                    <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item command="addGroup">加入群</el-dropdown-item>
                        <el-dropdown-item command="createGroup" v-if="pageType === '1'">创建群</el-dropdown-item>
                    </el-dropdown-menu>
                </el-dropdown>
            </div>
            <ul id="allChatGroupList" class="padding-0 mg-0">
                <li :class="['border-bottom',item.isClick ? 'active':'','name-li']" v-for="(item,index) in allGroupsShowData" :key="index" @click="getChart(1,item)">
                    <div>
                        <div class="group-img">{{item.groupName.substring(0,1)}}</div>
                        <div class="message-circle" v-show="item.hasUnReadLog"></div>
                    </div>
                    <div class="name-content">
                        <div>
                            <span class="title-name name ellipse inline-block">{{item.groupName}}</span>
                            <span class="time">{{getChatTimeAndContent(item.lastChat,true).createdTime}}</span>
                        </div>
                        <div class="content ellipse" v-html="getChatTimeAndContent(item.lastChat,true).content"></div>
                    </div>
                </li>
            </ul>
        </div>
  </div>
</template>

<script>
import {setReadMsg} from '../../api/api.js'
export default {
  name: '',
  mixins: [],
  components: {},
  props: {
    myUserId: {
      type: String,
      default: ''
    },
    pageSize: {
      type: String,
      default: 'big'
    },
    allUserGroups: {
      Object,
      default: () => {}
    },
    clickItem: {
      Object,
      default: () => {}
    },
    pageType: {
      String,
      default: '1'
    }
  },
  data () {
    return {
      allUsers: [],
      allGroups: [],
      allUsersShowData: [],
      allGroupsShowData: [],
      mySelfData: {},
      filterText: ''
    }
  },
  watch: {
    allUserGroups: {
      handler (val, oldVal) {
        if (val.allGroups || val.allUsers) {
          if (val.allGroups) {
            this.setGroupListDiv()
          }
          if (this.allUserGroups.allUsers) {
            this.allUsers = JSON.parse(JSON.stringify(this.allUserGroups.allUsers))
            this.dealAllUserForList()
          }
          this.filterUserChange(this.filterText)
        }
      },
      deep: true,
      immediate: true
    }
  },
  computed: {},
  created () {},
  mounted () {
  },
  methods: {
    setGroupListDiv () {
      let obj = {}
      if (this.allUserGroups.allGroups && this.pageType === '1') {
        obj = this.allUserGroups.allGroups.find(res => {
          return res.groupType === 'Simple'
        })
      } else if (this.allUserGroups.allGroups && this.pageType === '2') {
        obj = this.allUserGroups.allGroups.find(res => {
          return res.groupType === 'RIS'
        })
      }
      if (obj && obj.groups) {
        this.allGroups = JSON.parse(JSON.stringify(obj.groups))
        this.allGroupsShowData = this.allGroups
      }
    },
    changeGroups (data) {
      if (data.type === 0) { // 新增
        let obj = data.changeGroup
        if (obj.groupType === Number(this.pageType)) {
          obj.isClick = true
          this.allGroups.unshift(data.changeGroup)
        }
        this.filterUserChange(this.filterText)
        this.getChart(1, obj)
      } else if (data.type === 1 && data.changeGroup.groupId === this.clickItem.id) { // 修改
        // 是当前点击的组并且打开了群管理。需要重新刷新一下群管理数据
        this.$emit('changeGroupSetting')
      } else if (data.type === 2 && data.changeGroup.groupType === Number(this.pageType)) { // 删除
        let index = this.allGroups.findIndex(v => {
          return data.changeGroup.groupId === v.groupId
        })
        this.allGroups.splice(index, 1)
        this.filterUserChange(this.filterText)
        if (this.clickItem.id === data.changeGroup.groupId) {
          this.$emit('changeGroupDelete')// 如果删除的组是正在展示的组，那就清空显示的东西
        }
      }
    },
    getChart (type, val) {
      // 把被点击的人存下来,并设置点击样式
      let clickItem = {
        type,
        id: type === 0 ? val.user.id : val.groupId,
        name: type === 0 ? val.user.userName : val.groupName,
        avatar: type === 0 ? val.user.avatarImageUrl : null
      }
      this.$emit('update:clickItem', clickItem)// 更新clickItem
      window.localStorage.setItem('clickItem', JSON.stringify(clickItem))
      this.setActive(clickItem)
      this.$nextTick(() => {
        if (val.hasUnReadLog) { // 又未读消息就设置已读
          this.setReadMsgToAPI().then(res => {
            this.$set(val, 'hasUnReadLog', false)
          })
        }
      })

      this.$emit('chatClick')
    },
    setActive (clickItem) {
      if (clickItem.type === 0) { // 单聊
        for (const v of this.allUsers) {
          if (v.user.id === clickItem.id) {
            this.$set(v, 'isClick', true)
            // v.isClick = true
          } else {
            // v.isClick = false
            this.$set(v, 'isClick', false)
          }
        }
        for (const v of this.allGroups) {
        //   v.isClick = false
          this.$set(v, 'isClick', false)
        }
      } else { // 群组
        for (const v of this.allUsers) {
        //   v.isClick = false
          this.$set(v, 'isClick', false)
        }
        for (const v of this.allGroups) {
          if (v.groupId === clickItem.id) {
            // v.isClick = true
            this.$set(v, 'isClick', true)
          } else {
            // v.isClick = false
            this.$set(v, 'isClick', false)
          }
        }
      }
    },
    appendCircle (type, id) {
      // 添加未读红色点
      if (type === 'user') { // 个人
        for (let i = 0; i < this.allUsers.length; i++) {
          let item = this.allUsers[i]
          if (item.user.id === id) {
            item.hasUnReadLog = true// 设置红色标点
            break
          }
        }
      } else { // 群
        for (let i = 0; i < this.allGroups.length; i++) {
          let item = this.allGroups[i]
          if (item.groupId === id) {
            item.hasUnReadLog = true// 设置红色标点
            break
          }
        }
      }
      this.sortList(type, id)
    },
    sortList (type, id) {
      if (type === 'user') { // 个人
        for (let i = 0; i < this.allUsers.length; i++) {
          let item = this.allUsers[i]
          if (item.user.id === id) {
            this.allUsers.splice(i, 1)
            this.allUsers.unshift(item)// 把对话框前移
            break
          }
        }
      } else { // 群
        for (let i = 0; i < this.allGroups.length; i++) {
          let item = this.allGroups[i]
          if (item.groupId === id) {
            this.allGroups.splice(i, 1)
            this.allGroups.unshift(item)// 把对话框前移
            break
          }
        }
      }
      this.filterUserChange(this.filterText)
    },
    command (val) {
      if (val === 'addGroup') { // 加入群
        this.$emit('addGroup')
      } else if (val === 'createGroup') { // 创建群
        this.$emit('createGroup')
      }
    },
    getChatTimeAndContent (lastChat, flag) { // flag:false单聊。true:群聊
      let obj = {
        createdTime: '',
        content: ''
      }
      if (lastChat) {
        if (lastChat.createdTime) {
          let dayType = this.$chatUtils.judgeTime(lastChat.createdTime)
          if (dayType === 0) {
            obj.createdTime = lastChat.createdTime.substring(11, 16)
          } else if (dayType === 1) {
            obj.createdTime = '昨天'
          } else if (dayType === 2) {
            obj.createdTime = '前天'
          } else {
            obj.createdTime = lastChat.createdTime.substring(0, 10)
          }
        }
        if (lastChat.chatType || lastChat.chatType === 0) {
          if (flag && lastChat.chatType !== 5) { // 群消息，需要添加发送人名字
            if (lastChat.sendUserId) {
              let item = this.allUsers.find(res => {
                return res.user.id === lastChat.sendUserId
              })
              obj.content = item.user.userName + ':'
            } else {
              obj.content = lastChat.sendUser.userName + ':'
            }
          } else if (flag && lastChat.chatType === 3) {
            obj.content = '群消息:'
          }
          if (lastChat.chatType === 1) {
            obj.content += '[图片]'
          } else if (lastChat.chatType === 2) {
            obj.content += '[文件]'
          } else if (lastChat.chatType === 3) {
            obj.content += '[评论]'
          } else if (lastChat.chatType === 4) {
            obj.content += '[语音]'
          } else {
            obj.content += lastChat.content
          }
        }
      }
      return obj
    },
    dealAllUserForList () { // 筛选出自己和其他人的数据
      this.allUsersShowData = []
      this.allUsers.forEach(el => {
        if (el.user.id !== this.myUserId) {
          this.allUsersShowData.push(el)
        }
      })
    },
    onlineUserChange (data) {
      // 先全置为下线
      for (let val of this.allUsersShowData) {
        this.$set(val, 'isOnline', false)
      }
      // 设置上线的人
      for (let item of data.onlineUsers) {
        for (let val of this.allUsersShowData) {
          if (item === val.user.id) {
            this.$set(val, 'isOnline', true)
            this.sortList('user', item)
          }
        }
      }
      this.$forceUpdate()
    },
    async setReadMsgToAPI () { // 设置已读
      let params = {
        userId: this.myUserId,
        otherId: this.clickItem.id,
        type: this.clickItem.type,
        // eslint-disable-next-line no-undef
        startTime: this.$dayjs().format('YYYY-MM-DD HH:mm:ss'),
        pageSize: 0
      }
      await setReadMsg(params)
    },
    updateLastMsg (type, id, message) {
      if (type === 'user') {
        let obj = this.allUsers.find(res => {
          return res.user.id === id
        })
        if (obj) {
          obj.lastChat = {
            chatReceiveType: message.chatReceiveType,
            chatType: message.chatType,
            content: message.content,
            createdTime: message.createdTime,
            id: message.messageId,
            receiveUserId: message.groupId,
            sendUserId: message.sendUser.id
          }
        }
      } else {
        let obj = this.allGroups.find(res => {
          return res.groupId === id
        })
        if (obj) {
          obj.lastChat = {
            chatReceiveType: message.chatReceiveType,
            chatType: message.chatType,
            content: message.content,
            createdTime: message.createdTime,
            id: message.messageId,
            receiveUserId: message.groupId,
            sendUserId: message.sendUser.id
          }
        }
      }
    },
    filterUserChange (val) {
      this.allGroupsShowData = this.allGroups.filter(el => {
        return el.groupName.indexOf(val) > -1
      })
      this.allUsersShowData = this.allUsers.filter(el => {
        return el.user.userName.indexOf(val) > -1 && el.user.id !== this.myUserId
      })
    }
  },
  beforeDestroy () {},
  destroyed () {},
  beforeUpdate () {},
  updated () {}
}
</script>
<style lang='scss' scoped>
.left-user{
    width: 300px;
    height: 100%;
    background: #fff;
    border-right:1px solid rgba(0,0,0,0.2);
    display: flex;
    flex-direction: column;
    .left-top-search{
        text-align: center;
        border-bottom: 1px solid rgba(0,0,0,0.2);
        padding: 5px;
        height: 44px;
        line-height: 44px;
        // .my-avatar-name{
        //     width: 54px;
        //     height: 44px;
        //     display: flex;
        //     flex-direction: column;
        //     align-items: center;
        //     justify-content: space-evenly;
        //     float: left;
        // }
        // .my-avatar-name img{
        //     width: 28px;
        //     border-radius: 5px;
        // }
        // .my-avatar-name span{
        //     font-size: 12px;
        //     line-height: 12px;
        // }
    }
    .user-list,.group-list{
        height: calc(50% - 28px);
        flex: 1;
    }
    .user-list,.group-list{

        .user-list-title{
            height: 23px;
            box-sizing: content-box;
            padding: 15px;
            line-height: 23px;
            border-bottom: 1px solid #EBEBEB;
            background: rgba(242, 243, 245, 1);
        }
        ul{
            height: calc(100% - 55px);
            overflow: auto;
            padding:0px;
            li{
                padding: 12px 14px;
                cursor: pointer;
                img{
                    width: 44px;
                    height:44px;
                    margin-right: 10px;
                    border-radius: 5px;
                }
            }
            .unlive .name,.unlive .content{
                color: #999999!important;
            }
            .name-li{
                position: relative;
                display: flex;
                align-items: center;
                > .name-content{
                    width: calc(100% - 54px);
                    line-height: 19px;
                    height: 38px;
                }
                .name{
                    color: #1D2129;
                    font-weight: 600;
                    width: calc(100% - 67px);
                }
                .time{
                    font-size: 12px;
                    float: right;
                    color: #86909C;
                    min-width: 62px;
                    text-align: right;
                }
                .content{
                    color: #4E5969;
                    font-size: 12px;
                }
            }
            .border-bottom{
                border-bottom: 1px solid #ddd;
            }
        }
    }
    .active{
        background: rgba(255, 125, 0, 0.08);
    }
    .active::before{
        content: "";
        display: block;
        position: absolute;
        top: 0;
        left: 0px;
        width: 4px;
        height: 67px;
        background: #FF7D00;
    }
    .title-name{
        display: inline-block;
        width: 160px;
        word-break: keep-all;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }
    .message-circle{
        width: 10px;
        height: 10px;
        border-radius: 5px;
        background-color: #fd5252;
        position: absolute;
        top: 10px;
        left: 50px;
    }

    /deep/ .el-input--mini .el-input__inner{
        background: rgba(242, 243, 245, 1);
        border: 1px solid rgba(0,0,0,0.2);
    }
    .group-img{
        width: 44px;
        height: 44px;
        text-align: center;
        line-height: 44px;
        background: #FF7D00;
        float: left;
        border-radius: 20%;
        margin-right: 10px;
        font-size: 20px;
        font-weight: bold;
        color: #fff;
    }
}
</style>
