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,
    messagesObject:{},
    chatlist: [],
    searchChatlist:[],
    tempSearchChatlist:[],
    tempChatlist:[],
    friendlist: [
        // {
        //     id: 0,
        //     wxid: "", //微信号
        //     initial: '新的朋友', //姓名首字母
        //     img: 'static/images/newfriend.jpg', //头像
        //     signature: "", //个性签名
        //     nickname: "新的朋友",  //昵称
        //     sex: 0,   //性别 1为男，0为女
        //     remark: "新的朋友",  //备注
        //     area: "",  //地区
        // }
    ],
    emojis,
    selectId: 1,
    selectFriendId: 0
  },

  mutations: {
    USER_LOGIN(state, value){
        setToken(value.token)
        state.userInfo = value
    },
    CHANGE_CONVERSATIONPANEL(state, value){
        if(panelStatus.CHART==value){
            state.whichPane = panelStatus.CHART
            state.searchChatlist = []
            state.tempSearchChatlist = []
        }else{
            state.whichPane =  panelStatus.SEARCH
            state.whichPane = value
        }
    },
    SET_WXOBJECT(state, value){
        state.wsObject = value
    },
    SELECT_SEESION (state, value) {
        state.messagesObject = 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].lastMessage&&value[i].lastMessage.content,
              date:  value[i].lastMessage&&value[i].lastMessage.createTime
            }]
            tempList.push({
                id: value[i].id, 
                user: {
                    name: value[i].userBo.nickname,
                    img: value[i].userBo.avatar
                },
                messages: temp,
                queryData:value[i].lastUpdateTime,
                index: i 
            })
        }
        state.searchChatlist = tempList.sort(compare('queryData'))
    },
    SET_CHART_LIST(state, value){
        state.tempChatlist = value
        let tempList = []
        for(let i in value){
            let temp = [{
              content: value[i].lastMessage&&value[i].lastMessage.content,
              date:  value[i].lastMessage&&value[i].lastMessage.createTime
            }]
            tempList.push({
                id: value[i].id, 
                user: {
                    name: value[i].userBo.nickname,
                    img: value[i].userBo.avatar
                },
                messages: temp,
                queryData:value[i].lastUpdateTime,
                index: i 
            })
        }
        state.chatlist = tempList.sort(compare('queryData'))
        
    },
    SELECT_MESSAGE(state, value){
        let { chatlist, selectId } = state
        for(let c in chatlist){
            if(chatlist[c].id==selectId){
                chatlist[c].messages = value==null?[]:value.sort(compare('createTime')) 
            }
        }
    },
    initData (state) {
        let data = localStorage.getItem('vue-chat');
        if (data) {
            state.chatlist = JSON.parse(data);
        }
    },
    search (state, value) {
       state.searchText = value
    },
    selectFriend (state, value) {
       state.selectFriendId = value
    },

    // send (state) {
    //     let result = state.friendlist.find(friend => friend.id === state.selectFriendId)
    //     let msg = state.chatlist.find(msg => msg.user.name === result.remark)
    //     if( !msg ){
    //        state.selectId = 1
    //         for(let i = 0; i < state.chatlist.length; i++ ){
    //             state.chatlist[i].id++;
    //             state.chatlist[i].index++;
    //         }
    //         state.chatlist.unshift({
    //             id: 1,
    //             user: {
    //                 name: result.remark,
    //                 img:  result.img
    //             },
    //             messages: [
    //                 {
    //                     content: '已经置顶聊天，可以给我发信息啦！',
    //                     date: new Date()
    //                 }
    //             ],
    //             index: 1
    //         })
    //     }else {
    //         state.selectId = msg.index
    //         router.push({ path: '/chat'})
    //     }
    // }
  },

  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) => {
        console.log(data)
        callback()
        if (data.eventType == "conversations/create" && data.message) {
          // dispatch('conversation/newConversation', data, { root: true })
        } else {
          data.self = data.isSend == 1 || data.customerId == state.customerServiceId
          // dispatch('conversation/newMessage', data, { root: true })
        }
      })
      .on('conversations/index', (data, callback) => {
        console.log(data)
        commit('SET_CHART_LIST', data)
        // console.log('conversations/index')
        // _.each(data, (conversation) => {
        //   dispatch('conversation/addConversation', {...conversation, from: 'index'}, { root: true })
        // })
      })
      .on('conversations/friend', (data, callback) => {
        console.log(data)
        // console.log('conversations/friend')
        // console.log(data)
        // _.each(data, (conversation) => {
        //   dispatch('conversation/addFriendConversation', {...conversation, from: 'index'}, { root: true })
        // })
      })
      .on('messages/index', (data, callback) => {
        callback(true)
        commit('SELECT_MESSAGE', data)
        // console.log('messages/index')
        // if (_.isEmpty(data)) return
        // _.each(data, (message) => {
        //   message.self = message.isSend == 1 || message.customerId == state.customerServiceId
        //   dispatch('conversation/addMessage', message, { root: true })
        // })
        // dispatch('conversation/isMessagesDone', data, { root: true })
      })
      .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)
        // console.log('conversations/show')
        // dispatch('conversation/addConversation', data, { root: true })
      })
      .on('conversions/search', (data, callback) => {
        console.log(data)
        callback()
        commit('SET_SEARCHCHART_LIST', data)
        // _.each(data, (conversation) => {
        //   dispatch('conversation/addConversation', conversation, { root: true })
        // })
      })

      // dispatch('conversation/init', {}, { root: true })
      // dispatch('conversation/showConversation', { id: 3 }, { root: true })

      // Common.wsClient.emit('appevent', {
      //   eventType: 'messages/create',
      //   message: {
      //     conversationId: 3,
      //     type: 3,
      //     content: "文本",
      //     imageUrl: "https://cdn-images.baozheng.cc/uploads/bag/order/front/000/248/943/medium_0789ee03.jpeg"
      //   },
      // })
    },
    selectSession({ commit, state }, conversation) {
        console.log(5555555555555555555555)
        commit('SELECT_SEESION', conversation)
        state.wsObject.emit('appevent', {
            eventType: 'messages/index',
            message: {
                conversationId:conversation.id,
                page: state.messagesPage,
                rows: state.messagesPer
            }
        })
    },
    changeChartPanel({ commit, state }){
        commit('CHANGE_CONVERSATIONPANEL', panelStatus.CHART)
    },
    searchSession({ commit, state }, keyword) {
        console.log(44444)
        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 = state.messagesObject.messages
        temp.push({
            conversationId:conversation.id,
            type: conversation.type,
            isSend:1,
            content: conversation.content,
            createTime: Date.parse(new Date())
        })
        commit('SELECT_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