import config from "@/common/config.js"
let timer = null
let retimer = null


import * as sdk from "@/common/imSdk/lim-sdk.js";

import lim from "@/common/imSdk/sdk-bridge.js";

export default {
	socketTask: null,
	// 连接WebSocket
	connectSocket() {

		const ListenerMap = {
			onSocketConnectEvent: (option, status, data) => {
				console.log("已建立连接:" + JSON.stringify(status));
			},
			onSocketErrorEvent: (error) => {
				console.log("连接出现错误:" + userId);
			},
			onSocketReConnectEvent: () => {
				console.log("正在重连:");
			},
			onSocketCloseEvent: () => {
				console.log("连接关闭:");
			},
			onSocketReConnectSuccessEvent: () => {
				console.log("重连成功");
			},
			onTestMessage: (e) => {
				console.log("onTestMessage ：" + e);
			},
			onP2PMessage: (e) => {
				console.log("onP2PMessage ：" + e);
				e = JSON.parse(e)
				e.pushType="TEXT"
				uni.$emit('onP2PMessage', e.data);
			},
			onLogin: (uid) => {
				console.log("用户" + uid + "登陆sdk成功");
			}

		};


		const userId = uni.getStorageSync("userId")
		const imUserSign = uni.getStorageSync("imUserSign")

		var listeners = {};
		for (const v in ListenerMap) {
			listeners[v] = ListenerMap[v];
		}

		console.log(lim)

		if (this.socketTask != null) {
			return false
		}

		lim.lim.im.init(config.getImApiUrl(), config.getImAppId(), userId, imUserSign, listeners, (
			sdk) => {
			if (sdk) {
				console.warn("====================")
				this.socketTask = sdk;
				console.log(this.socketTask)

				console.log('sdk 成功连接的回调, 可以使用 sdk 请求数据了.');
				sdk.getAllFriend().then(res => {
					console.warn(res)
				})
				sdk.getUserSequence().then(res => {
					console.warn(res)
				})

				sdk.getUserConversationList(0).then(res => {
					console.warn(res)
				})

				return uni.switchTab({
					url: "/pages/tabbar/index/index"
				})
			} else {
				console.log('sdk 初始化失败.');
			}
		})


		/* 

		this.socketTask = uni.connectSocket({
			url: 'wss://im-api.q3z3.com/ws?Authorization=' + uni.getStorageSync('Authorization'),
			complete: () => {}
		});
		this.socketTask.onOpen(res => {
			console.log('WebSocket连接已打开！');
			// 设置心跳
			timer = setInterval(() => {
				uni.sendSocketMessage({
					data: 'isConnact',
					success: res => {
						if (res.errMsg == 'sendSocketMessage:ok') {
							console.log('WebSocket已连接')
						} else {
							this.connectSocket()
						}
					}
				})
			}, 5000)
		})
		// 监听接收
		this.socketTask.onMessage(res => {
			if (res.data == 'ok') {
				return
			}
			var data = JSON.parse(res.data);
			fc.getPush(data);
			console.log('WebSocket接收消息！');
		})
		// 监听关闭
		this.socketTask.onClose(res => {
			console.log('WebSocket连接已关闭！');
			let token = uni.getStorageSync('Authorization');
			if (this.socketTask && token) {
				this.socketTaskClose()
				retimer = setTimeout(() => {
					this.connectSocket()
				}, 5000)
			}
		})
		// 监听异常
		this.socketTask.onError(res => {
			console.log('WebSocket连接打开失败，正在尝试重新打开！');
			if (this.socketTask) {
				this.socketTaskClose()
				retimer = setTimeout(() => {
					this.connectSocket()
				}, 5000)
			}

		}); 
		*/

	},
	// 关闭WebSocket
	socketTaskClose() {
		if (this.socketTask) {
			this.socketTask.close()
			clearInterval(timer)
			clearTimeout(retimer)
			console.log('关闭WebSocket！');
		}
	},
}