import store from '../vuexPre'
import Vue from 'vue'
import axios from 'axios'
const vue = new Vue()
const _ = require('lodash')
export default {
    install(Vue, options) {
        Vue.prototype.$IM = this
    },
    init(appKey, token) {


        console.log(appKey, token)
        RongIMLib.RongIMClient.init(appKey)
        RongIMLib.RongIMClient.setOnReceiveMessageListener({
            onReceived: (message) => {
                console.log(message)
                if (message.messageType === RongIMClient.MessageType.TextMessage) {
                    store.dispatch('receiveMessage', {
                        content: message.content.content,
                        contentType: 0,
                        state: 0,
                        time: message.sentTime,
                        // toUserId: store.state.userInfo.id,
                        userId: message.content.extra.userId,
                        storeId: message.content.extra ? message.content.extra.storeId : null,
                        typeFlag: message.content.extra.typeFlag
                    })
                }
            }
        })

        RongIMLib.RongIMClient.setConnectionStatusListener({
            onChanged: (status) => {
                console.log(RongIMLib.ConnectionStatus[status])
            }
        })

        console.log(token)
        RongIMClient.connect(String(token), {
            onSuccess: (userId) => {
                // console.log('连接成功,userId:', userId)
                store.commit('updateIMConnected', true)
            },
            onTokenIncorrect: () => {
                // console.log('连接失败', 'token无效')
            },
            onError: (errorCode) => {
                // console.log('连接失败', RongIMLib.ErrorCode[errorCode])
            }
        })
    },
    //发送信息
    sendMessage: (options) => {
        let target = options.target || ''
        let content = options.content || ''
        let userId = options.userId || ''
        let typeFlag = Number(options.typeFlag)
        let customer = options.customer || ''
        let msg = new RongIMLib.TextMessage(content)
        let success = options.success || function() {}

        console.log(options)

        RongIMClient.getInstance().sendMessage(RongIMLib.ConversationType.PRIVATE, typeFlag ? userId : customer, msg, {
            onSuccess: (message) => {
                // let formData = {
                //     'content': content,
                //     'contentType': 1,
                //     'state': 0,
                //     'time': message.sentTime,
                //     'storeId': target,
                //     'userId': userId,
                //     'typeFlag': typeFlag
                // }

                console.log(message)

                var formData = new FormData()
                formData.append('content', content.content)
                formData.append('contentType', 0)
                formData.append('state', 0)
                formData.append('time', message.sentTime)
                formData.append('storeId', target)
                formData.append('userId', userId)
                formData.append('typeFlag', typeFlag)
                formData.append('serviceName', customer)


                // vue.$http.post(api.saveChatInfo, formData).then(res => { success(res.body.data) })

                axios.post('/chatInfo/save', formData)
                    .then(res => {
                        if (res.data.success) {
                            success(res.data.data)
                        }
                    })

            },
            onError: (errorCode, message) => {
                console.log('发送失败:', RongIMLib.ErrorCode[errorCode], errorCode)
            }
        })
    },
    newConversation: (options) => {
        let userId = options.userId
        let storeId = options.storeId
        let type = options.type
        let success = options.success || function() {}

        function addConversation() {
            let index = _.findIndex(store.state.conversationList, i => {
                if (storeId) {
                    return Number(i.storeId) === Number(storeId) && Number(userId) === Number(i.userId) && Number(type) === Number(i.type)
                }

            })
            if (index === -1) {

                var newCon = new FormData()
                newCon.append('userId', userId)
                newCon.append('storeId', storeId)
                newCon.append('type', type)


                // return vue.$http.post(api.addConversation, newCon)

                return axios.post('/usersSession/save', newCon)
            } else {
                return new Promise((resolve, reject) => resolve())
            }
        }

        addConversation().then(() => {
            return axios.get('/usersSession/all', {
                params: {
                    userId: store.state.userInfo.id,
                    type: 1
                }
            })
        }).then(res => {
            if (res.data.success) {
                store.commit('updateConversationList', res.data.data)
                success()
            }
        })

    }
}