import store from '@/store/index.js'
import method from '@/common/methodTool'
let isSocketClose = false; // 是否关闭socket
let heartbeatInterval = null; // 心跳定时器
let socketTask = null; // websocket对象
let againTimer = null; //断线重连定时器


let url = null;

/**
 * sockeUrl：websocet的地址
 * */
const sokcet = (sockeUrl) => {
	url = sockeUrl;
	isSocketClose = false;
	//判断是否有websocet对象，有的话清空
	if (socketTask) {
		socketTask.close();
		socketTask = null;
		clearInterval(heartbeatInterval);
	}

	// 连接
	console.log(url)
	socketTask = uni.connectSocket({
		url: url,
		success(data) {
			console.log("websocket连接成功");
			clearInterval(againTimer) //断线重连定时器
		},
		fail: (err) => {
			console.log("报错", err);
		}
	});
	// 连接打开
	socketTask.onOpen((res) => {
		console.log('WebSocket打开');
		clearInterval(againTimer) //断线重连定时器
		clearInterval(heartbeatInterval);
		// // 30秒发送一次心跳
		// heartbeatInterval = setInterval(() => {
		// 	sendMsg('心跳ing')
		// }, 30000)
	})
	// 监听连接失败
	socketTask.onError((err) => {
		console.log('WebSocket连接打开失败，请检查', err);
		//停止发送心跳
		clearInterval(heartbeatInterval)
		//如果不是人为关闭的话，进行重连
		if (!isSocketClose) {
			reconnect(url)
		}
	})

	// // 监听连接关闭 -
	socketTask.onClose((e) => {
		console.log('WebSocket连接关闭！',e);
		clearInterval(heartbeatInterval)
		if (!isSocketClose) {
			reconnect(url)
		}
	})

	// 监听收到信息
	socketTask.onMessage((res) => {
		console.log(res, 'res监听收到信息')
		
		if(res.data == 'offLine') {
			stop();
			uni.setStorageSync('needToLogin','1')
			uni.showToast({
				icon:'none',
				title:'用户在其他终端登录，强制下线',
				duration:3000,
			})
			setTimeout(() => {
				method.exit();
			},3000)
		}
	});


}

const reconnect = (url) => {
	console.log('进入断线重连', isSocketClose);
	clearInterval(againTimer) //断线重连定时器
	clearInterval(heartbeatInterval);
	console.log(socketTask)
	socketTask && socketTask.close(); // 确保已经关闭后再重新打开
	socketTask = null;
	// 连接  重新调用创建websocet方法
	againTimer = setInterval(() => {
		sokcet(url)
		console.log('在重新连接中...');
	}, 20000)


}

const sendMsg = (msg) => { //向后端发送心跳包
	console.log(msg)
	try {
		//通过 WebSocket 连接发送数据
		socketTask.send({
			data:msg
		});
	} catch (e) {
		console.log(e,'msg')
		if (isSocketClose) {
			return
		} else {
			reconnect(url)
		}

	}
}

const stop = () => {
	isSocketClose = true
	clearInterval(heartbeatInterval);
	clearInterval(againTimer) //断线重连定时器
	socketTask && socketTask.close(); // 确保已经关闭后再重新打开
	socketTask = null;
}





export const websocket = {
	sokcet,
	stop,
	sendMsg
};
