import * as RongIMLib from '@/uni_modules/RongCloud-IMWrapper/js_sdk/index'
import * as CallLib from '@/uni_modules/RongCloud-CallWrapper/lib/index'
import store from '@/store/index.js'
import message from './message.js'
import listeners from './listeners.js'
import {
    getFriends,
    getUserInfo,
    getImToken,
    getMyGroups
} from '@/apis/interfaces/im.js'

const initIm = (KEY) => {
    RongIMLib.init(KEY)
    // CallLib.init()
    addListeners()
    // 初始化的时候 自动链接
    if (store.getters.getToken !== '') {
        getImToken().then(res => {
            connect(res.token, res.userInfo, () => {})
        })
    }
}

const setNotifyBadge = () => {
    // 获取未读消息数量
    RongIMLib.getTotalUnreadCount(({
        code,
        count
    }) => {
        if (code === 0) {
            // #ifdef APP-PLUS
            plus.runtime.setBadgeNumber(count)
            // #endif
            if (count > 0) {
                uni.setTabBarBadge({
                    index: 3,
                    text: String(count > 99 ? '99+' : count)
                })
            } else {
                uni.removeTabBarBadge({
                    index: 3
                })
            }
        }
    })
}

/**
 * 连接IM服务
 * @param {string} token    token 
 * @param {object} userInfo {targetId: string, name: string, portraitUrl: string}  
 */
const connect = (token, userInfo, callback) => {
    RongIMLib.connect(token, res => {
        callback(res)
        // 更新个人信息
        store.dispatch('setSenderInfo', userInfo)
        // 设置未读消息数量
        setNotifyBadge()
        // 首次运行获取好友列表
        const FK = 'ZHK_' + userInfo.targetId

        uni.getStorage({
            key: FK,
            success: () => {
                const model = uni.model.contactModel
                model.find((err, results) => {
                    results.map(item => {
                        store.dispatch('launchContact', item)
                    })
                })
            },
            fail: () => {
                // 程序是首次运行，初始化加载好友和群组信息
                Promise.all([getFriends(), getMyGroups()]).then(result => {
                    result.map(contacts => {
                        contacts.map(item => {
                            store.dispatch('initContact', item)
                        })
                    })
                    uni.setStorageSync(FK, userInfo.targetId)
                })
            }
        })
    })
}

/**
 * 断开链接
 */
const disconnect = () => {
    RongIMLib.disconnect()
    // 移除提醒数量
    // #ifdef APP-PLUS
    plus.runtime.setBadgeNumber(0)
    // #endif
    uni.removeTabBarBadge({
        index: 3
    })
}

// 允许通知的消息类型，触发更新消息列表操作
const notifyMsgTypes = [
    'RC:TxtMsg',
    'RC:VcMsg',
    'RC:HQVCMsg',
    'RC:ImgMsg',
    'RC:GIFMsg',
    'RC:ImgTextMsg',
    'RC:FileMsg',
    'RC:LBSMsg',
    'RC:SightMsg',
    'RC:ReferenceMsg',
    'RC:CombineMsg',
]

function inArray(search, array) {
    for (var i in array) {
        if (array[i] == search) {
            return true
        }
    }
    return false
}

const addListeners = () => {
    // 添加连接状态监听函数 
    RongIMLib.addConnectionStatusListener((res) => {
        console.log('连接状态监听', res.data.status)
        uni.$emit('onConnectionStatusChange', res.data.status)
    })
    // 添加消息监听函数
    RongIMLib.addReceiveMessageListener((res) => {
        const message = res.data.message
        console.log('收到消息', message)
        if (inArray(message.objectName, notifyMsgTypes)) {
            if (!store.getters.contactIsExist(message.targetId)) {
                getUserInfo(message.targetId).then(res => {
                    store.dispatch('initContact', res)
                }).catch(err => {
                    console.log('ERR', err)
                })
            }
            newMessage(message)
        } else if (message.objectName === RongIMLib.ObjectName.ProfileNotification) {
            store.dispatch('updateContact', JSON.parse(message.content.data))
            // 调用完更新之后，删除这条消息
            RongIMLib.deleteMessagesByIds([message.messageId], ({
                code
            }) => {
                console.log('消息删除结果', code)
            })
        } else if (message.objectName === RongIMLib.ObjectName.ContactNotification) {
            // 触发一个新好友的通知事件
            uni.$emit('onContactNotification', message.content)
        }
    })

    // 监听消息回执
    RongIMLib.addReadReceiptReceivedListener(({
        data
    }) => {
        uni.$emit('onReadReceiptReceived', data)
    })

    // 音视频通话相关的
    // 监听通话呼入
    // CallLib.onCallReceived(({
    //     data
    // }) => {
    //     uni.navigateTo({
    //         url: '/pages/im/private/call?targetId=' + data.targetId + '&mediaType=' +
    //             data.mediaType
    //     })
    // })
    // // 通话建立成功
    // CallLib.onCallConnected(() => {
    //     uni.$emit('onCallConnected')
    // })
    // // 外呼
    // CallLib.onCallOutgoing((res) => {
    //     uni.$emit('onCallOutgoing')
    // })
    // // 远端响铃
    // CallLib.onRemoteUserRinging((res) => {
    //     uni.$emit('onRemoteUserRinging')
    // })
    // // 远端加入
    // CallLib.onRemoteUserJoined((res) => {
    //     uni.$emit('onRemoteUserJoined')
    // })
    // // 断开链接
    // CallLib.onCallDisconnected((res) => {
    //     console.log('断开链接', res)
    //     uni.$emit('onCallDisconnected')
    // })
    // // 远端挂断
    // CallLib.onRemoteUserLeft((res) => {
    //     console.log('远端离开', res)
    //     uni.$emit('onRemoteUserLeft')
    // })
}

// 维护消息列表，检查是否需要通知声音，设置新消息提醒的数量
const newMessage = (msg) => {
    RongIMLib.getConversationNotificationStatus(msg.conversationType, msg.targetId, ({
        code,
        status
    }) => {
        if (code === 0) {
            if (status) {
                triTone()
            }
        }
    })
    setNotifyBadge()
    uni.$emit('onReceiveMessage', msg)
}

// 播放状态
let tipState = false

const triTone = () => {
    if (tipState == false) {
        const innerAudioContext = uni.createInnerAudioContext()
        innerAudioContext.autoplay = true
        innerAudioContext.src = '/utils/im/sounds/new-msg.mp3'
        innerAudioContext.onPlay(() => {
            tipState = true
        })
        innerAudioContext.onEnded(() => {
            tipState = false
            innerAudioContext.destroy()
        })
    }
}

export default {
    initIm,
    connect,
    setNotifyBadge,
    ...message
}
