import * as service from '@/service'
import apiUrl from '@/service/api.js'
import router from '@/router'
import { compare } from '@/utils/tools'
import * as auth from '@/utils/auth'
import { MessageBox, Alert } from 'element-ui'
import { panelStatus } from '@/utils/common'
import Vue from 'vue'
let isSend = false;
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)
        setUserId(value.customerId)
        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
        }
    },
    SET_CHARTING_LIST(state,value){
        state.chatlist = value.reverse(compare('queryData'))
        state.chartings =value.reverse(compare('queryData'))
    },
    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,
                    id:value[i].userBo.userId
                },
                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,
                    id:value[i].userBo.userId
                },
                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', () => {
            MessageBox('连接被迫断开,重新登录！', '提示', {
              confirmButtonText: '确定',
              type: 'warning'
            }).then(() => {
              window.location.href="/"
            }).catch(() => {
              console.log(2)        
            });
        }).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) => {
        if(isSend){
            isSend = false  
        }else{
            commit('SEND_MESSAGE', [data])
            callback()
        }
      })
      .on('conversations/index', (data, callback) => {
        commit('SET_CHART_LIST', data)
      })
      .on('conversations/friend', (data, callback) => {
        console.log(data)
      })
      .on('messages/index', (data, callback) => {
        if(isSend){
            isSend = false  
        }else{
            commit('CHANGE_ISSELECTMORE',false)
            callback(true)
            data&&commit('ADD_MESSAGE', data)
            !data&&state.messagesPage--
        }
      })
      .on('conversations/show', (data, callback) => {
        let customerId = getUserId()
        let { tempChatlist } = state
        if(data!=null&&data.userBo.primaryBindCustomerId!= customerId){
            let temp = null
            let isNew = true
            const { chartings } = state
            for(let i in state.chatlist){
                if(state.chatlist[i].id == data.id){
                    temp =  Object.assign(state.chatlist[i])
                    isNew = false
                    state.chatlist.splice(i, 1);
                }
            }
            if(isNew){
                 let list = [data].concat(tempChatlist)
                commit('SET_CHART_LIST', list)
            }else{
                let list = [temp].concat(state.chatlist)
                commit('SET_CHARTING_LIST', list)
            }
        }
      })
      .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,
            imageUrl: conversation.imageUrl,
            content: conversation.content,
            createTime: Date.parse(new Date())
        }
        isSend=true
        commit('SEND_MESSAGE', [temp])
    },
    getTranster({ commit, state }, prams){
        let customerId = getUserId()
        let { chartings, selectId } = state
        let customerdeId =null
        for(let tob of chartings){
            if(tob.id==selectId){
                customerdeId = tob.user.id
            }
        }
        return new Promise((resolve, reject) => {
            service.chart.getTransfer({
                userId:customerdeId,
                customerId
            }).then(response=>{
                if(response.code==200){
                    resolve(response.data)
                }else{
                    reject(response)
                }
            }).catch(error => {
              reject(error)
            })
        })
    },
    toTranster({ commit, state }, prams){
        let customerId = getUserId()
        let { chartings, chatlist, selectId } = state
        let tempUserId =null
        for(let tob of chartings){
            if(tob.id==selectId){
                tempUserId = tob.user.id
            }
        }
        prams.userId = tempUserId
        prams.fromCustomerId = customerId
        return new Promise((resolve, reject) => {
            service.chart.toTrensfer(prams).then(response=>{
                if(response.code==200){
                    resolve(response.data)
                    for(let i in chatlist){
                        if(chatlist[i].id == selectId){
                            chatlist.splice(i, 1);
                        }
                    }
                    commit('SET_CHARTING_LIST', chatlist)
                }else{
                    reject(response)
                }
            }).catch(error => {
              reject(error)
            })
        })
    },
    closeTake({ commit, state }, prams){
        let customerId = getUserId()
        let { chartings, chatlist, selectId } = state
        let customerdeId =null
        for(let tob of chartings){
            if(tob.id==selectId){
                customerdeId = tob.user.id
            }
        }
        return new Promise((resolve, reject) => {
            service.chart.closeSession({
                userId:customerdeId,
                customerId
            }).then(response=>{
                if(response.code==200){
                    resolve(response.data)
                    for(let i in chatlist){
                        if(chatlist[i].id == selectId){
                            chatlist.splice(i, 1);
                        }
                    }
                    commit('SET_CHARTING_LIST', chatlist)
                }else{
                    reject(response)
                }
            }).catch(error => {
              reject(error)
            })
        })
    }
  }
}
export default user