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()
    listeners.imLibListeners()
    listeners.callLibListeners()
    // 初始化的时候 自动链接
    if (store.getters.getToken !== '') {
        getImToken().then(res => {
            connect(res.token, res.userInfo, (res) => {
                console.log('IM.CONNECT', res);
            })
        })
    }
}

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 = 'ZHKD_' + 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
    })
}

// 播放状态
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,
    disconnect,
    setNotifyBadge,
    ...message
}
