
import Vue from 'vue'
import store from '@/store';
import NIMSDK from 'nim-web-sdk-ng/dist/NIM_UNIAPP_SDK'
import { imToken } from '@/apis/interfaces/yxim.js'

export const INIT = async () => {
	
	let APPKEY = ''
	let TOKEN  = ''
	let UID	   = ''

	if( store.getters.getToken == '' || uni.getStorageSync('token') == '' ){
		return '用户未登录'
	}
	
	await imToken().then(res => {
		let { app_key, token, uid } = res;
		APPKEY = app_key
		TOKEN  = token
		UID	   = uid
	}).catch(err => {
		uni.showToast({
			title: 'IM INIT ERR' + err.code,
			icon : 'none'
		})
	})
	
	const yxim = new NIMSDK({
		appkey				: APPKEY,
		account				: UID,
		token				: TOKEN,
		debugLevel			: 'debug',
		needReconnect		: true,
		reconnectionAttempts: 5
	})
	
	// 注册监听事件
	const eventList = [
		'logined',
		'kicked',
		'willReconnect',
		'disconnect',
		'msg',
		'syncdone',
	]
	
	eventList.forEach(key => {
		yxim.on(key, res => {
			console.log(`{$key}:`, res ? JSON.parse(JSON.stringify(res)): res)
		})
	})
	
	await yxim.connect();
	
	// 挂载全局变量方法
	Vue.prototype.$nim = yxim;
}
