
let wsurl='wss://' + process.env.VUE_APP_WEBSCOKET + '/ws/';
let ws = null
let weboscket_callback = null
import {getToken,generateUUID } from '@/api/auth';
import {Message} from 'element-ui'

//获取 websocket 推送的数据
let websocketonmessage = e => {
	let data=JSON.parse(e.data)
	if(data.type=="ping"){
		if(ws){
			ws.send('保持连接')
		}
	}
	return weboscket_callback(data);
}

// 连接成功
let websocketonopen = () => {
	console.log('websocket 成功')
}

// 连接失败时重新连接
let websocketonerror = () => {
	Message({
		message: '服务器繁忙，请稍后再试',
		type: 'error',
	})
	weboscket_callback({type:'error',msg:'服务器繁忙，请稍后再试'})
	// initWebSocket()
}

// 断开链接后报错
let websocketclose = e => {
	if(!e.wasClean){//当网络中断时处理
		Message({
			message: '网络连接失败，请稍后再试',
			type: 'error',
		})
		weboscket_callback({type:'break',msg:'网络连接失败，请稍后再试'})
		closewebsocket();
	}
}

// 手动关闭 websocket
let closewebsocket = () => {
	if(ws){
		console.log('websocket 关闭')
		ws.close()
		ws=null;
	}
}

let initWebSocket = () => {
	//初始化 websocket
	ws = new WebSocket(wsurl)
	ws.onmessage = websocketonmessage
	ws.onopen = websocketonopen
	ws.onerror = websocketonerror
	ws.onclose = websocketclose
}

// 发送数据
let sendData = (data, callback) => {
	weboscket_callback = callback
	//  判断 data 数据类型
	if (typeof data == 'string') {
		data = data
	} else {
		data = JSON.stringify(data)
	}
	if(ws){//  判断 websocket 的状态
		if (ws.readyState === ws.OPEN) {// 已经打开,可以直接发送
			// console.log("1")
			ws.send(data)
		} else if (ws.readyState === ws.CONNECTING) {// 正在开启状态中,则 1 秒后重新发送
			// console.log("2")
			setTimeout(() => {
				ws.send(data)
			}, 2000)
		}
	}else {
		// 未打开，则开启后重新调用
		initWebSocket()
		let wsData = {
			type: 'auth',
			token: getToken(),
			machine:generateUUID()
		};
		sendData(wsData, callback)
		sendData(data, callback)
	}
}

// 导出
export {
	initWebSocket,
	sendData,
	closewebsocket
}
