//@eslint-disable

import tool from '@/utils/tool';
import systemConfig from '@/config';
import router from "@/router";
import {ElNotification} from 'element-plus';
import {eventBus} from "./eventBus"
import store from "../store";
// import api from '../api';

let websocket = null;
let global_callback = function () {};
let timeoutObj = null;
let timeout = 28 * 1000; //30秒一次心跳
let serverTimeoutObj = 60; //心跳倒计时
let timeOutNum = 60; // 断开 重连倒计时
let lockReconnect = false; //是否真正建立连接
const wsUri = systemConfig.WS_URL;
let showNot = null;

function networkDes() {
	ElNotification.error({
		title: '网络已断开',
		message: '网络已断开，正在重连……'
	})
}

function reConnect() {//重新连接
	if (lockReconnect) {
		return;
	}
	lockReconnect = true;
	//没连接上会一直重连，设置延迟避免请求过多
	timeOutNum && clearTimeout(timeOutNum);
	timeOutNum = setTimeout(function () {
		//新连接
		createWebSocket(global_callback);
		lockReconnect = false;
	}, 5000);
}

function startHeartbeat() {
	//清除时间
	clearTimeout(timeoutObj);
	clearTimeout(serverTimeoutObj);
	start();
}

//开启心跳
function start() {
	timeoutObj && clearTimeout(timeoutObj);
	serverTimeoutObj && clearTimeout(serverTimeoutObj);
	timeoutObj = setTimeout(function () {
		//这里发送一个心跳，后端收到后，返回一个心跳消息，
		if (websocket.readyState === 1) {//如果连接正常
			const heart = {type: "heart"}
			websocket.send(JSON.stringify(heart));
		} else {//否则重连
			reConnect();
		}
		serverTimeoutObj = setTimeout(function () {
			//超时关闭
			closeSock(false);
		}, timeout);
	}, timeout)
}

function createWebSocket(callback, token) {
	// websocket.readyState 0 (CONNECTING) 1 (OPEN) 2 (CLOSING) 3 (CLOSED)
	// 0 连接正在建立中，尚未连接
	// 1 已经建立，可以进行通信
	// 2 关闭握手过程，即将关闭
	// 3 闭或者根本没有建立‌

	if(websocket && websocket.readyState === 1){
		return
	}
	if (websocket === null || websocket.readyState === 3) {
		initWebSocket(callback, token);
	}
}

function initWebSocket(callback, token) {
	global_callback = callback;
	// 初始化websocket
	let reToken = token === undefined ? tool.cookie.get('TOKEN') : token;
	if(!reToken) return  // 没有token 不执行ws创建
	websocket = new WebSocket(wsUri + "?token=Bearer " + reToken);
	websocket.onmessage = function (e) {
		webSocketOnMessage(e);
	};
	websocket.onclose = function (e) {
		webSocketClose(e);
	};
	websocket.onopen = function () {
		websocketOpen();
	};

	// 连接发生错误的回调方法
	websocket.onerror = function () {
		networkDes()
		reConnect()
	};
}

// 实际调用的方法
function sendSock(agentData) {
	if (websocket.readyState === websocket.OPEN) {
		// 若是ws开启状态
		webSocketSend(agentData);
	} else if (websocket.readyState === websocket.CONNECTING) {
		// 若是 正在开启状态，则等待1s后重新调用
		setTimeout(function () {
			sendSock(agentData);
		}, 1000);
	} else {
		// 若未开启 ，则等待1s后重新调用
		setTimeout(function () {
			sendSock(agentData);
		}, 1000);
	}
}

function closeSock(active) {
	lockReconnect = active; 	// 主动断开时不重连
	websocket.close();
	return true
}

// 数据接收
function webSocketOnMessage(msg) {
	// 收到信息为Blob类型时
	let result = null;
	// 二进制文件
	if (msg.data instanceof Blob) {
		const reader = new FileReader();
		reader.readAsText(msg.data, "UTF-8");
		reader.onload = () => {
			result = JSON.parse(reader.result);
			global_callback(result);
		};
	} else {
		if(msg.type === "") return
		result = JSON.parse(msg.data);
		store.commit('set_home_msg', result);
		// if(result.type == 13){
		// 	store.commit("SET_WS_Msg_NUM", result.data.todo_msg_count);
		// }
		if(global_callback){
			global_callback(result);
		}
	}
	if (result.data && (result.data.type == -1 || result.data.type == 0 || result.data.type == 9 || result.data.type == 13)) {
		if(result.data.type == -1 || result.data.type == 0){
			if(result.data && result.data.data && result.data.data.token){
				let reToken = result.data.data.token.replace(/Bearer /g, "");
				tool.cookie.set("TOKEN", reToken);
			}
		}else{
			showNot = ElNotification.error({
				title: '系统退出',
				message: result.data.msg,
				duration:0
			});
			handleError('系统退出', result.msg);
		}
	}
	if(result && result.data){
		eventBus.$emit('sockBack',result);
	}
	if(result.data && result.data.type == 1){
		if(showNot && showNot.close){
			showNot.close();
		}
	}
	startHeartbeat()
}

function handleError() {
	// api.system.user.logout.post().then();
	router.replace({ path: "/login" }).then();
	closeSock(true);
}

function getSock(callback) {
	global_callback = callback;
}

// 数据发送
function webSocketSend(agentData) {
	websocket.send(agentData);
}

// 关闭
function webSocketClose() {
	reConnect()
}

function websocketOpen() {
	start()
}

export {
	sendSock,
	createWebSocket,
	closeSock,
	getSock,
	reConnect,
};
