import { _decorator, Component, Node } from 'cc';
import { msgManager } from './msgManager';
import { userDataManager } from '../manager/userDataManager';
const { ccclass, property } = _decorator;

@ccclass('gameSocket')
export class gameSocket extends Component {
    private static _instance: gameSocket | null = null;
    public static get Instance() {
        if (gameSocket._instance === null)
        gameSocket._instance = new gameSocket();
        return gameSocket._instance;
    }
    sock:WebSocket = null;
    private current_url:string = ''  //当前url
    is_connected:Boolean = false;
    stopConnected:Boolean = false;
    check_heartbeat_succeed:boolean = false;
    is_online_status:boolean = false; //是否是在线状态

    private reconnectInterval = 1000;   // 重连间隔时间（毫秒）
    private reconnectMaxAttempts = 30;  // 最大重连尝试次数
    private reconnectAttempts = 0;      // 当前重连尝试次数

    private static RECV_HEART_BEAT ='1' //收到服务器心跳结果
    private static RECV_CHEAK_HEART_BEAT = '2' //服务器查询我的心跳

    _on_opened(event:Event):void {
        console.log('_on_opened=',event)
        this.reconnectAttempts = 0
        if(this.is_connected===true){

        }else{
            this.is_connected = true;
            this.check_heartbeat_succeed = true;
            gameSocket.Instance.is_online_status = true;
            if(userDataManager.user_data) {
                msgManager.relink()
            }
        }
    }

    _on_recv_data(event:any):void {
        console.log('_on_recv_data=',event)
        this.check_heartbeat_succeed = true;
        if(event.data===gameSocket.RECV_HEART_BEAT){
            // if(GameMng.reward_tong_bi){
            //     UIManager.removeWaitViewLayer()
            //     GameMng.reward_tong_bi = false;
            //     msgManager.ad_tongbi(1)
            // }
            // if(GameMng.firendOpenId!=""){
            //     UIManager.removeWaitViewLayer()
            //     msgManager.add_firend(parseInt(GameMng.firendOpenId))
            //     msgManager.user_join_room(parseInt(GameMng.firendOpenId))
            //     GameMng.firendOpenId = ""
            // }
            //console.log("接受服务端返回的心跳",GameUtil.curTime())
            return
        }
        if(event.data===gameSocket.RECV_CHEAK_HEART_BEAT){
            gameSocket.Instance.heartbeat();
            return
        }
        if(event.data===""||event.data===null){
            console.assert(true,"接受输出格式错误，data为空",event)
        }else{
            msgManager.recv(event.data)
        }
    }

    _on_socket_close(event:any):void {        
        console.log("_on_socket_close",event)
        this.reConnectOperation()
        this.is_connected = false;        
    }

    _on_socket_err(event:any):void {
        console.log("_on_socket_err",event)
        this.reConnectOperation()
        this.is_connected = false;
    }

    private reConnectOperation() {
        if (this.reconnectAttempts < this.reconnectMaxAttempts) {
            console.log('正在尝试重连...');
            setTimeout(()=>{
                this.reonnect()
            },this.reconnectInterval)
            this.reconnectAttempts++;
        } else {
            console.log('重连尝试次数已达上限');
        }
    }

    reonnect() {
        if(this.current_url.length<=0) {
            return
        } 
        this.connect(this.current_url)
    }

    connect(url:any):void {
        if(this.stopConnected){
            console.log("客户端退出链接，暂不提供重连")
            return
        }
        this.current_url = url
        if(!this.is_connected){
            try{
                this.sock = new WebSocket(url);
                this.sock.binaryType = "arraybuffer"; //"arraybuffer", "blob", "document", "json", and "text".
                this.sock.onopen = this._on_opened.bind(this);
                this.sock.onmessage = this._on_recv_data.bind(this);
                this.sock.onclose = this._on_socket_close.bind(this);
                this.sock.onerror = this._on_socket_err.bind(this);
            }catch(e:any){
                console.log("connect error",e)
            }
        }
    }

    heartbeat(){
        this.check_heartbeat_succeed = false;
        this.send_cmd(0);
    }

    /**
     * this.sock.readyState
     * CONNECTING：值为0，表示正在连接
     * OPEN：值为1，表示连接成功，可以通信了
     * CLOSING：值为2，表示连接正在关闭
     * CLOSED：值为3，表示连接已经关闭，或者打开连接失败
     */
    send_cmd(body):void {
        if (!this.sock || !this.is_connected) {
            return;
        }
        try{
            console.log('sock.readyState=',this.sock.readyState)
            if(this.sock.readyState===1){
                if(typeof body == 'number'){
                    body=body+""
                }
                console.log('发送消息',body)
                this.sock.send(body);
            }
        }catch(e:any){
            console.log("e",e)
        }
    }

    close():void {
        if (this.sock !== null) {
            this.sock.close();
            this.sock = null;
        }
        this.is_connected = false;
        this.check_heartbeat_succeed = false;
    }

}

