import store from '@/store/index.js';
import config from '@/config'


export const init = () => {
	if(!uni.getStorageSync('token')){
		console.log('sok-未登录');
		return
	}else{
		console.log('sok-登录');
	}
	
	
	var timeout = 10000;
	var timeoutObj = null;
	var timeAnt = 0

	setInterval(() => {
		timeAnt++
	}, 1000)

	openConnection()

	function checkOpenSocket() {
		uni.sendSocketMessage({
			data: 'ping',
			success: res => {
				timeAnt = 0
				return;
			},
			fail: err => {
				// 未连接打开websocket连接
				openConnection();
			}
		});
	}

	function openConnection() {
		// 打开连接
		// uni.closeSocket(); // 确保已经关闭后再重新打开
		uni.connectSocket({
			url: `wss://${config.sok}/ws/deviceUpMessage?token=${uni.getStorageSync('token')}`,
			success(res) {
				// console.log('连接成功 connectSocket=', res);
			},
			fail(err) {
				// console.log('连接失败 connectSocket=', err);
			}
		});
		uni.onSocketOpen(res => {
			checkOpenSocket()
			// console.log('连接成功');
		});
		uni.onSocketError(err => {
			// console.log('连接失败');
		});

		onSocketMessage(); // 打开成功监听服务器返回的消息
	}
	//	打开成功监听服务器返回的消息
	function onSocketMessage() {
		// 消息
		timeout = 10000;
		timeoutObj = null;
		uni.onSocketMessage(res => {
			timeAnt = 0
			getSocketMsg(res.data); // 监听到有新服务器消息
		});
	}
	// 监听到有新服器消息
	function getSocketMsg(data) {
		console.log(data);
		var obj;
		let pages = getCurrentPages() //获取加载的页面
		let currentPage = pages[pages.length - 1] //获取当前页面的对象
		let url = currentPage.route //当前页面url
		if (data !== 'pong') {
			store.commit('setSokStatus', 1);
			uni.hideLoading()
			obj = JSON.parse(data)
			store.commit('setCommand', obj.command);
			store.commit('setDataObj', obj);
			// 插枪状态
			console.log(obj);
			if (obj.insertStatus || obj.insertStatus === 0) {
				store.commit('setInsertStatus', obj.insertStatus);
			}
			if (obj.command == 'startResult' && obj.result == '-1') {
				uni.showModal({
					title: '提示',
					content: '启动失败，请重试',
					showCancel: false,
					confirmText: "确认",
					success: () => {}
				})
			}
			if (obj.command == 'startResult' && obj.result == '-2') {
				uni.showModal({
					title: '提示',
					content: '启动超时，请重试',
					showCancel: false,
					confirmText: "确认",
					success: () => {}
				})
			}
			if (obj.command == 'startResult' && obj.result == '01') {
				if (url != 'pageOrder/recharge/recharge') {
					uni.navigateTo({
						url: `/pageOrder/recharge/recharge?transactionNo=${obj.transactionNo}&type=order`
					});
				}
			}
			if (obj.command == 'transactionResult') {
				if (url == 'pageOrder/recharge/recharge') {
					uni.navigateBack()
				}
			}
		}else{
			// store.commit('setSokStatus', 0);
		}
		timeAnt = 0
		reset(); // 检测心跳reset,防止长时间连接导致连接关闭
	}
	// 检测心跳reset
	function reset() {
		clearInterval(timeoutObj);
		start(); // 启动心跳
	}
	// 启动心跳 start
	function start() {
		timeoutObj = setInterval(function() {
			if (timeAnt > 10) {
				// console.log('连接失败重新连接....');
				openConnection();
				return
			}
			uni.sendSocketMessage({
				data: 'ping',
				success: res => {
					// console.log(res);
				},
				fail: err => {
					// console.log('连接失败重新连接....');
					openConnection();
				}
			});
		}, timeout);
	}
}