<template>
  <div class="wrapper">
    <div class="container" :class="skin">
      <TheHeader :lists="lists" :mine="mine" :store="store" :brief="brief"></TheHeader>
      <div class="vue-im" ref="imdrag" v-show="!miniVisible">

        <Contacts
          :need-ref="needRef"
          v-show="currentTab === 'user' && !brief"
          @on-view-members="handleViewGroupMembers"
          @on-add-group="handleAddNewGroup"
          :groups-list="groupsList"
          :friends-list="lists"
          :members-list="membersList"
          :store="store"/>

        <div class="im-chat-wrapper" v-show="currentTab === 'chat'">
          <ChatList :store="store"/>
          <ChatBox
            :mine="mine"
            :ext="ext"
            :max-size="maxSize"
            :history="history"
            :upload-name="uploadName"
            :store="store"/>
        </div>
      </div>
      <audio v-if="voice" :src="voice" ref="voice"></audio>
    </div>
  </div>
</template>

<script>
  import ChatList from '@/components/ChatList/ChatList.vue'
  import ChatBox from '@/components/ChatBox/ChatBox.vue'
  import Contacts from '@/components/Contacts/Contacts'
  import TheHeader from '@/components/Header/TheHeader'
  import { device, typeOf } from '@/utils/utils'
  import storage from '@/utils/storage'
  import IMStore from '@/store/store'
  import {list,newList,getMine,getHistory,getChatlog,setOnlineStatus} from '@/api/webim/index'


  export default {
    name: 'vue-im',
    props: {
      history: {
        type: Object,
        default () {
          return {
            total: 0,
            size: 10,
            records: []
          }
        }
      },
      lists: {
        type: Array,
        default () {
          return []
        }
      },
      unReadList: {
        type: Array,
        default () {
          return []
        }
      },
      groupsList: {
        type: Array,
        default () {
          return []
        }
      },
      mine: {
        type: Object,
        required: true
      },
      voice: {
        type: String,
        default: require('@/assets/default.mp3')
      },
      ext: {
        type: Array,
        default () {
          return []
        }
      },
      uploadName: {
        type: String,
        default: 'image'
      },
      membersList: {
        type: Array,
        default () {
          return []
        }
      },
      maxSize: Number,
      brief: {
        type: Boolean,
        default: false
      },
      chat: {
        type: Object,
        default () {
          return {}
        }
      }
    },
    data () {
      const store = new IMStore(this)
      return {
        miniVisible: this.mini,
        historyVisible: false,
        store,
        needRef:false
      }
    },
    created () {
      this.getMine()
      this.fetchUserList()
    },
    methods: {
      //---------------websocket start
      initWebSocket: function () {
        // WebSocket与普通的请求所用协议有所不同，ws等同于http，wss等同于https
        this.websock = new WebSocket("ws://192.168.1.22:8081/websocket/"+this.mine.id);
        this.websock.onopen = this.websocketonopen;
        this.websock.onerror = this.websocketonerror;
        this.websock.onmessage = this.websocketonmessage;
        this.websock.onclose = this.websocketclose;
      },
      websocketonopen: function () {
        console.log("WebSocket连接成功");
      },
      websocketonerror: function (e) {
        console.log("WebSocket连接发生错误");
      },
      websocketonmessage: function (e) {
        console.log(e.data);
        // debugger
        this.message = eval('(' + e.data + ')');
        if(this.message.chatlogType=="onlineNotice") {
          this.$nextTick(()=>{
            this.needRef = true;
            this.fetchUserList()
          })
        }else{
        this.getMessage(this.message);
        }
      },
      websocketclose: function (e) {
        this.websock.close()
        console.log("connection closed");
        this.setOnlineStatus('offline')
      },
      //---------------websocket end
      getMine(){
        const self = this
        getMine().then(function (response) {
          let mine = response.data
          self.mine = mine
        })
      },
      setOnlineStatus(sta){
        const self = this
        setOnlineStatus(sta)
      },
      getHistory(id){
        const self = this
        getChatlog(id).then(function (response) {
          let history = response.data
          // debugger
          const localData = storage.readData('iminfo')
          let currentChat = storage.readData('currentChat')
          if (currentChat && currentChat.hostId === id) {
            self.store.commit('setCurrentChat', currentChat)
          } else {
            self.store.commit('setCurrentChat', null)
          }
          if (self.brief && self.chat && self.chat.id) {
            self.chat.type = self.chat.type || 'friend'
            currentChat = self.chat
            self.store.commit('updateUserInfoCenter', self.chat)
            self.store.commit('setCurrentChat', self.chat)
            self.store.commit('setCurrentTab', 'chat')
          }
          let tempData = {
            avatar: self.mine.avatar,
            id: self.mine.id,
            username: self.mine.username
          }
          if (localData && localData.id === self.mine.id) {
            tempData.history = localData.history
            tempData.chatList = localData.chatList
          } else {
            tempData.history = {}
            tempData.chatList = []
          }
          storage.saveData('iminfo', tempData)
          let chatLogsList = tempData.chatList
          if (currentChat !== null && currentChat !== undefined) {
            const flag = chatLogsList.find(item => {
              return item.id == currentChat.id.toString()
            })
            if (!flag) {
              chatLogsList.unshift(currentChat)
            }
          }
          self.store.commit('setLocalHistory', tempData.history)
          self.store.commit('updateChatLogsList', chatLogsList)
          self.history=history
        })
      },
      fetchUserList () {
        const self = this
        list().then(function (response) {
          // debugger
            let lists = response.data
            self.lists = lists
          })
      },
      initIM () {
        if (!this.mine || !this.mine.id) {
          return
        } else {
          this.store.states.mine = this.mine
          this.store.commit('updateUserInfoCenter', this.mine)

          this.getHistory(this.mine.id)
        }
        this.setOnlineStatus('online')
        this.initWebSocket()
      },
      emitSend (message) {
        this.$emit('on-send', message)
      },
      getMessage (message) {
        if(message.chatlogType=="file"){
          message.content=eval('(' + message.content + ')')
        }
        this.handleVoice()
        this.store.commit('getNewMsg', message)
        message.username = message.sendername
        message.id = message.sender
        message.count = this.store.states.newMsgLists[message.id].length
        if (this.store.states.currentChat === null) {
          this.store.commit('setCurrentChat', message)
        }
        // this.store.commit('updateUserInfoCenter', message)
        this.store.commit('updateChatLogsList', message)
        this.store.commit('updateLocalHistory', message)
      },
      // 控制消息提示音
      handleVoice () {
        if (!this.voice) return
        const IE = device()
        if (IE && IE < 9) return
        this.$refs.voice.play()
      },
      handleViewGroupMembers (contact) {
        this.$emit('on-view-members', contact)
      },
      handleAddNewGroup (group) {
        this.$emit('on-add-group', group)
      },
      handleHistoryVisible (chat) {
        this.$emit('on-view-history', chat)
      },
      handlePageChange (page) {
        this.$emit('on-page-change', page)
      },
      handleChatChange (item) {
      }
    },
    components: {
      ChatBox,
      TheHeader,
      ChatList,
      Contacts
    },
    watch: {
      mine: {
        handler () {
          this.initIM()
        },
        deep: true
      },
      unReadList: {
        handler (newV) {
          if (typeOf(newV) === 'array') {
            newV.forEach(item => {
              this.getMessage(item)
            })
          } else {
            this.getMessage(newV)
          }
        }
      },
      lists: {
        handler (newV) {
          this.store.commit('setUserInfoCenter', newV)
        },
        deep: true
      },
      groupsList: {
        handler (newV) {
          this.store.commit('setUserInfoCenter', newV)
        },
        deep: true
      },
      chat: {
        handler: function () {
          if (this.brief && this.chat && this.chat.id) {
            this.chat.type = this.chat.type || 'friend'
            this.store.commit('updateUserInfoCenter', this.chat)
            this.store.commit('setCurrentChat', this.chat)
            this.store.commit('setCurrentTab', 'chat')
          }
        },
        deep: true
      }
    },
    mounted () {
      this.initIM()
      const skin = storage.getItem('im-skin')
      if (skin && skin !== this.skin) {
        this.store.commit('setSkin', skin)
      }
    },
    computed: {
      skin () {
        return this.store.states.skin
      },
      currentTab () {
        return this.store.states.currentTab
      }
    }
  }
</script>
<style lang="scss">
  .wrapper {
    /*width: 100%;*/
    height: 100%;
    margin: 12px;
    background: #fff;
    padding: 20px;
  ::-webkit-scrollbar {
    width: 5px;
    height: 12px;
    -webkit-border-radius: 40%;
  }
  ::-webkit-scrollbar-thumb {
    background: #c3c3c3;
    -webkit-border-radius: 12px;
  }
  .container {
    width: 100%;
    height: 100%;
  }
  .vue-im {
    display: flex;
    justify-content: space-between;
    width: 100%;
    min-width: 800px;
    height: calc(100% - 61px);
    min-height: 540px;
    box-shadow: 0 2px 2px 0 rgba(0,0,0,.14), 0 3px 1px -2px rgba(0,0,0,.2), 0 1px 5px 0 rgba(0,0,0,.12);
  }
  .im-chat-wrapper {
    display: flex;
    text-justify: space-between;
    width: 100%;
  }
  .brief {
    width: 60%;
  }
  .mini {
    position: fixed;
    bottom: 30px;
    right: 40px;
    cursor: pointer;
    width: 36px;
    height: 36px;
    border-radius: 5px;
    padding: 5px;
    box-shadow: 0 2px 2px 0 rgba(0,0,0,.14), 0 3px 1px -2px rgba(0,0,0,.2), 0 1px 5px 0 rgba(0,0,0,.12);
  img {
    width: 100%;
    height: 100%;
  }
  }
  }
  @keyframes twinkle {
    0% {opacity: 1}
    25% {opacity: 0}
    50% {opacity: 1}
    75% {opacity: 0}
    100% {opacity: 1}
  }
</style>
<style scoped>
  @import '/static/dist/vue-im.min.css';
  @import 'https://cdn.bootcss.com/font-awesome/4.7.0/css/font-awesome.min.css';
</style>
