import * as service from '@/service'
// import io from 'socket.io-client';
import apiUrl from '@/service/api.js'
import router from '@/router'
import { compare, singel } from '@/utils/tools'
import { 
    setToken, getToken, setUserId, 
    getUserId, emojis, setUserInfo,
    getUserInfo
 } 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 = {
  namespaced: true,
  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){
        setUserInfo(value)
        setToken(value.token)
        setUserId(value.customerId)
        state.userInfo = value
    },
    SET_USERINFO(state, value){
        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 = singel(value.reverse(compare('queryData')))
        state.chartings = singel(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&&value[i].userBo.nickname,
                    img: value[i].userBo.avatar,
                    conRemark:value[i].userBo.conRemark,
                    remark:value[i].devicesBo&&value[i].devicesBo.remark,
                    id:value[i].userBo.userId
                },
                unReadTotal:value[i].unReadTotal,
                page: 1,
                rows: 30,
                messages: temp,
                queryData:value[i].lastUpdateTime,
                index: i 
            })
        }
        state.searchChatlist = singel(tempList.sort(compare('queryData')))
        state.chartings = singel(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,
                    conRemark:value[i].userBo.conRemark,
                    remark:value[i].devicesBo&&value[i].devicesBo.remark,
                    id:value[i].userBo.userId
                },
                unReadTotal:value[i].unReadTotal,
                page: 1,
                rows: 30,
                messages: temp,
                queryData:value[i].lastUpdateTime,
                index: i 
            })
        }
        state.chatlist =  singel(tempList.reverse(compare('queryData'))) 
        state.chartings =  singel(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, ...chatlist[c].messages]
                chatlist[c].messages = temp.sort(compare('createTime')) 
            }
            // 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==value[0].conversationId){
                 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/USER_LOGIN', response.data, { root: true })
                    resolve(response.data)
                }else{
                    reject(response)
                }
            }).catch(error => {
              reject(error)
            })
        })
    },
    initData({ commit, state }){
        let userInfo = getUserInfo()
        commit('user/SET_USERINFO', userInfo, { root: true })
    },
    init ({ commit, state }) {
      state.wsObject.emit('appevent', {
        eventType: 'conversations/index'
      })
    },
    connect({ dispatch, commit, state }) {
      dispatch('initData')
      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) => {
        callback(true)
        if(data.isSend==1){
        }else{
            commit('SEND_MESSAGE', [data])
        }
      })
      .on('conversations/index', (data, callback) => {
        callback(true)
        let { tempChatlist } = state
        let list = [...data].concat(tempChatlist)
        commit('SET_CHART_LIST', list)
      })
      .on('conversations/friend', (data, callback) => {
        console.log(data)
      })
      .on('messages/index', (data, callback) => {
        callback(true)
        if(isSend){
            isSend = false  
        }else{
            commit('CHANGE_ISSELECTMORE',false)
            data&&commit('ADD_MESSAGE', data)
            !data&&state.messagesPage--
        }
      })
      .on('conversations/show', (data, callback) => {
        callback(true)
        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(true)
        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())
            conversation.unReadTotal = 0 
            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){
                    obj.unReadTotal = 0 
                    obj.page = 1
                    obj.rows = 30
                    parm = {
                        conversationId:conversation.id,
                        page: obj.page,
                        rows: obj.rows
                    }
                    obj.messages = []
                    dispatch('selectMessage', parm)
                }
            }
        } 
        // dispatch('chenzhen/setCustomerInfo', null, { root: true })
        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())
        }
        
        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