import * as service from '@/service'
import io from 'socket.io-client';
import apiUrl from '@/service/api.js'
import { compare } from '@/utils/tools'
import { setToken, getToken, emojis } from '@/utils/auth'
import { panelStatus } from '@/utils/common'
import Vue from 'vue'
const now = new Date();
const user = {
  state: {
    name: 'ratel',
    userInfo:{},
    wsObject:null,
    img: 'static/images/UserAvatar.jpg',
    whichPane:panelStatus.CHART,
    messagesPage:1,
    messagesPer:30,
    chatlist: [],
    chartings:[],
    searchChatlist:[],
    tempSearchChatlist:[],
    tempChatlist:[],
    emojis,
    isSelectMore:false,
    selectId: 1,
    selectFriendId: 0
  },

  mutations: {
    USER_LOGIN(state, value){
        setToken(value.token)
        state.userInfo = value
    },
    CHANGE_CONVERSATIONPANEL(state, value){
        if(panelStatus.CHART==value){
            state.chartings = state.chatlist
            state.whichPane = panelStatus.CHART
        }else{
            state.chartings = []
            state.whichPane =  panelStatus.SEARCH
            state.whichPane = value
        }
    },
    CHANGE_ISSELECTMORE(state,value){
        state.isSelectMore = value
    },
    SET_WXOBJECT(state, value){
        state.wsObject = value
    },
    SELECT_SEESION (state, value) {
        state.selectId = value.id
    },
    SET_SEARCHCHART_LIST(state, value){
        state.tempSearchChatlist = value
        let tempList = []
        for(let i in value){
            let temp = [{
              content: value[i].content||'',
              date:  value[i].lastUpdateTime
            }]
            tempList.push({
                id: value[i].id, 
                user: {
                    name: value[i].userBo.nickname,
                    img: value[i].userBo.avatar
                },
                page: 1,
                rows: 30,
                messages: temp,
                queryData:value[i].lastUpdateTime,
                index: i 
            })
        }
        state.searchChatlist = tempList.sort(compare('queryData'))
        state.chartings = tempList.sort(compare('queryData'))
    },
    SET_CHART_LIST(state, value){
        state.tempChatlist = value
        let tempList = []
        for(let i in value){
            let temp = [{
              content: value[i].content||'',
              date:  value[i].lastUpdateTime
            }]
            tempList.push({
                id: value[i].id, 
                user: {
                    name: value[i].userBo.nickname,
                    img: value[i].userBo.avatar
                },
                page: 1,
                rows: 30,
                messages: temp,
                queryData:value[i].lastUpdateTime,
                index: i 
            })
        }
        state.chatlist = tempList.reverse(compare('queryData'))
        state.chartings =tempList.reverse(compare('queryData'))
    },
    ADD_MESSAGE(state, value){
        let { chatlist, selectId } = state
        for(let c in chatlist){
            if(chatlist[c].id==selectId){
                 let temp = value == null?[]:value.sort(compare('createTime')) 
                 chatlist[c].messages = [...temp, ...chatlist[c].messages]
            }
        }
    },
    SEND_MESSAGE(state, value){
        let { chatlist, selectId } = state
        for(let c in chatlist){
            if(chatlist[c].id==selectId){
                 let temp = value == null?[]:value.sort(compare('createTime')) 
                 chatlist[c].messages = [...chatlist[c].messages, ...temp]
            }
        }
    }
  },

  actions: {
    login:({ commit }, value)=>{
        return new Promise((resolve, reject) => {
            service.login(value).then(response=>{
                if(response.code==200){
                    commit('USER_LOGIN', response.data)
                    resolve(response.data)
                }else{
                    reject(response)
                }
            }).catch(error => {
              reject(error)
            })
      })
    },
    init ({ commit, state }) {
      state.wsObject.emit('appevent', {
        eventType: 'conversations/index'
      })
    },
    connect({ dispatch, commit, state }) {
      const wsClient = io(apiUrl.wsUrl, { autoConnect: false, transports: ['websocket'] })
      commit('SET_WXOBJECT', wsClient)
      if (wsClient.disconnected) {
        // commit('init', account)
        wsClient.io.opts.query = {
          token: getToken(),
          version: 2.0
        }
        wsClient.on('connect', () => {
          // Common.wsClient = wsClient
          console.log("connect")
          // commit('login')
          dispatch('connected')
          // storage.set('account', state)
        }).on('connect_error', () => {
          console.log("connect_error")
        }).on('disconnect', () => {
          // if (Common.wsClient) Common.wsClient = null
          console.log("disconnect")
        }).on('reconnect_attempt', () => {
          // if (Common.wsClient) Common.wsClient.io.opts.transports = ['polling', 'websocket'];
        })
        wsClient.open()
      }
      dispatch("init")
    },
    connected({ state, commit }) {
      state.wsObject
      .on('messages/message', (data, callback) => {
        commit('SEND_MESSAGE', [data])
        callback()
      })
      .on('conversations/index', (data, callback) => {
        console.log(data)
        commit('SET_CHART_LIST', data)
      })
      .on('conversations/friend', (data, callback) => {
        console.log(data)
      })
      .on('messages/index', (data, callback) => {
        console.log(45454545454545454)
        commit('CHANGE_ISSELECTMORE',false)
        callback(true)
        data&&commit('ADD_MESSAGE', data)
        !data&&state.messagesPage--

      })
      .on('conversations/show', (data, callback) => {
        const tempChatlist = state.tempChatlist
        for(let j in tempChatlist){
            if(tempChatlist[j].id==data.id){
                let tempMessages = [...tempChatlist[j].messages]
                tempChatlist[j] = data
                tempChatlist[j].messages= tempMessages
            }
        } 
        commit('SET_CHART_LIST', tempChatlist)
      })
      .on('conversions/search', (data, callback) => {
        callback()
        commit('SET_SEARCHCHART_LIST', data)
      })
    },
    selectSession({ dispatch, commit, state }, conversation) {
        if(state.selectId==conversation.id)return 
        let parm = {}
        if(state.whichPane == panelStatus.SEARCH){
            let temp = true
            for(let i in state.chatlist){
                if(state.chatlist[i].id == conversation.id){
                    state.chatlist.splice(i, 1);
                    temp = false
                }
            }
            conversation.lastUpdateTime = Date.parse( new Date())
            state.chatlist = [conversation].concat(state.chatlist)
            commit('CHANGE_CONVERSATIONPANEL', panelStatus.CHART)
            parm = {
                conversationId:conversation.id,
                page: 1,
                rows: 30
            }
            dispatch('selectMessage', parm)
        }
        if(state.whichPane == panelStatus.CHART){
            for(let obj of state.chatlist){
                if(obj.id == conversation.id){
                    parm = {
                        conversationId:conversation.id,
                        page: obj.page,
                        rows: obj.rows
                    }
                    if(obj.messages.length<2){
                        obj.messages = []
                        dispatch('selectMessage', parm)
                    }
                }
            }
        }
        
        commit('SELECT_SEESION', conversation)
    },
    selectMessage({ commit, state }, message){
        commit('CHANGE_ISSELECTMORE',true)
        state.wsObject.emit('appevent', {
            eventType: 'messages/index',
            message
        })
    },
    moreMessage({ dispatch, commit, state }, message){
        let id  = state.selectId
        let parms = {}
        for(let i in state.chatlist){
            if(state.chatlist[i].id == id){
                parms = {
                    conversationId:id,
                    page: ++state.chatlist[i].page,
                    rows: state.chatlist[i].rows
                }
            }
        }
        dispatch('selectMessage', parms)
    },
    changeChartPanel({ commit, state }){
        commit('CHANGE_CONVERSATIONPANEL', panelStatus.CHART)
    },
    searchSession({ commit, state }, keyword) {
        commit('CHANGE_CONVERSATIONPANEL', panelStatus.SEARCH)
        state.wsObject.emit('appevent', {
            eventType: 'conversions/search',
            message: { keyword }
        })
    },
    sendMessage({ commit, state }, conversation){
        state.wsObject.emit('appevent', {
            eventType: 'messages/create',
            message: {
              conversationId: conversation.id,
              type: conversation.type,
              content: conversation.content,
              imageUrl: conversation.imageUrl
            },
        },(data) => {
          console.log(data);
          console.log('这个socket发送成功了！');
        })
        let temp = {
            conversationId:conversation.id,
            type: conversation.type,
            isSend:1,
            content: conversation.content,
            createTime: Date.parse(new Date())
        }
        commit('SEND_MESSAGE', [temp])
    },
    search: ({ commit }, value) => {
        setTimeout(() => {
                commit('search', value)
        }, 100)
    },
    // selectSession: ({ commit }, value) => commit('selectSession', value),
    selectFriend: ({ commit }, value) => commit('selectFriend', value),
    // sendMessage: ({ commit }, msg) => commit('sendMessage', msg),
    send: ({ commit }) => commit('send'),
    initData: ({ commit }) => commit('initData')
  }
}
export default user