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, Notification } from 'element-ui'
import { panelStatus } from '@/utils/common'
import Vue from 'vue'
let isSend = false;
const now = new Date();
let fd=true
const user = {
  namespaced: true,
  state: {
    name: 'ratel',
    userInfo:{},
    noshowMassageTotal:0,
    wsObject:null,
    img: 'https://cdn-images.baozheng.cc/uploads/content/file/data/000/000/090/df6886a6.jpg',
    whichPane:panelStatus.CHART,
    messagesPage:1,
    messagesPer:30,
    chatlist: [],
    chartings:[],
    searchChatlist:[],
    tempSearchChatlist:[],
    tempChatlist:[],
    emojis,
    isSelectMore:false,
    selectId: 0,
    selectFriendId: 0,
    onLineStatus:10,
    customerConversationNum:0,
  },

  mutations: {
    USER_LOGIN(state, value){
        setUserInfo(value)
        setToken(value.token)
        setUserId(value.customerId)
        state.userInfo = value
    },
    CHANGE_CUSTOMERCONVERSTATIONNUM(state, value){
        state.customerConversationNum = value
    },
    CHANGE_ONLINESTATUS(state, value){
        state.onLineStatus = value
    },
    SET_USERINFO(state, value){
        state.userInfo = value
    },
    CHANGE_JIBAtOTAL(state, value){
        state.noshowMassageTotal = 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
        // state.chartings = value
        state.noshowMassageTotal = 0
        for(let od of value){
           state.noshowMassageTotal+=od.unReadTotal
        }
        value.sort(compare('queryData'))
        value.reverse()
        state.chatlist = singel(value)
        state.chartings = singel(value)
    },
    CHANGE_ISSELECTMORE(state,value){
        state.isSelectMore = value
    },
    SET_WXOBJECT(state, value){
        state.wsObject = value
    },
    SELECT_SEESION (state, value) {
        state.noshowMassageTotal = 0
        for(let od of state.chartings){
           state.noshowMassageTotal+=od.unReadTotal
        }
        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,
                    username: value[i].userBo&&value[i].userBo.username,
                    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 
            })
        }
        tempList.sort(compare('id'))
        state.searchChatlist = singel(tempList)
        state.chartings = singel(tempList)
    },
    SET_CHART_LIST(state, value){
        state.noshowMassageTotal = 0
        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,
                    username: value[i].userBo&&value[i].userBo.username,
                    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.noshowMassageTotal+=value[i].unReadTotal
        }
        tempList.sort(compare('queryData'))
        tempList.reverse()
        state.chatlist =  singel(tempList) 
        state.chartings =  singel(tempList) 
    },
    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')) 
            }
        }
    },
    SEND_MESSAGE(state, value){
        let { chatlist, selectId } = state
        let array = [...chatlist]
        for(let c in array){
            if(array[c].id==value[0].conversationId){
                let temp = value == null?[]:value.sort(compare('createTime')) 
                array[c].messages = [...array[c].messages, ...temp]
                array[c].queryData = value[0].createTime
                array.sort(compare('queryData'))
                array.reverse()
            }
        }
    }
  },

  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)
            if(!data){
                let { selectId, chatlist } = state
                for(let i in chatlist){
                    if(chatlist[i].id==selectId){
                        chatlist[i].page--
                    }   
                }
            }
        }
      })
      .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
            console.log(state.chatlist)
            for(let i in state.chatlist){
                console.log(state.chatlist[i].id,data.id)
                if(state.chatlist[i].id == data.id){
                    temp =  Object.assign(state.chatlist[i])
                    temp.unReadTotal = data.unReadTotal
                    temp.queryData = data.lastUpdateTime
                    isNew = false
                    state.chatlist.splice(i, 1);
                }
            }

            if(isNew){
                console.log(456)
                let list = [data].concat(tempChatlist)
                commit('SET_CHART_LIST', list)
            }else{
                console.log(123)
                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())/1000
            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){
            let tmepNoshowMassage = 0
            for(let obj of state.chatlist){
                if(obj.id == conversation.id){
                    tmepNoshowMassage = obj.unReadTotal
                    obj.unReadTotal = 0 
                    obj.page = 1
                    obj.rows = 30
                    parm = {
                        conversationId:conversation.id,
                        page: obj.page,
                        rows: obj.rows
                    }
                    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())/1000
        }
        
        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('SELECT_SEESION', {id:0})
                    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)
            })
        })
    },
    changeCustomerStatus({ dispatch, commit, state }, prams){
        let customerId = getUserId()
        return new Promise((resolve, reject) => {
            service.chart.changeCustomerStatus({
                customerId,
                userState:prams
            }).then(response=>{
                if(response.code==200){
                    resolve(response.data)
                   dispatch('getStatuscrggr') 
                }else{
                    reject(response)
                }
            }).catch(error => {
              reject(error)
            })
        })
    },
    checkDevices({ dispatch, commit, state }, prams){
        let customerId = getUserId()
        window.quniamafe = function(){
            service.chart.checkDevices(customerId).then(response=>{
                if(response.code==200){
                    if(response.data.checkState==20){
                        window.clearInterval(aiOne)
                    }else{
                        Notification({
                          title: '警告',
                          position: 'bottom-left',
                          message: `您的客机 ${response.data.notOnlineDevices.join('-')} 客机不在线，请重启客机！`,
                          type: 'warning'
                        });
                    }
                }else{
                }
            }).catch(error => {
            })
        }
        var aiOne = window.setInterval('quniamafe()',10000)
    },
    getStatuscrggr({ dispatch, commit, state }, prams){
        let customerId = getUserId()
        service.chart.customersessionInfo({customerId}).then(response=>{
            if(response.code==200){
                commit('CHANGE_ONLINESTATUS', response.data.userState)
            }else{
            }
        }).catch(error => {
        })
    },
    customersessionInfo({ dispatch, commit, state }, prams){
        let customerId = getUserId()
        window.getCustomerStatus = function(){
            service.chart.customersessionInfo({customerId}).then(response=>{
                if(response.code==200){
                    commit('CHANGE_ONLINESTATUS', response.data.userState)
                }else{
                }
            }).catch(error => {
            })
        }
        var aiOne = window.setInterval('getCustomerStatus()',10000)
        window.getCustomerStatus()
    },
    customerConversation({ dispatch, commit, state }, prams){
        let customerId = getUserId()
        window.customerConversationNumInter = function(){
            service.chart.customerConversation({customerId}).then(response=>{
                if(response.code==200){
                    commit('CHANGE_CUSTOMERCONVERSTATIONNUM', response.data.canAccessNum)
                }else{
                }
            }).catch(error => {
            })
        }
        var aiOne = window.setInterval('customerConversationNumInter()',10000)
        window.customerConversationNumInter()
    },
    
  }
}
export default user