import WebSocket from "ws";
const logger = require("./log");

export default class Msg {
  public sendBufLen = 0;
  public sendBuf = new ArrayBuffer(512);
  public sendBufDV = new DataView(this.sendBuf, 0);
  public websocket;
  public isConnect: Boolean;
  public isConnecting: boolean;
  public websocketM;
  public isConnectM: Boolean;
  public isConnectingM: Boolean;
  public isInitiative: boolean = false;
  public handler;
  public account;

  onOpen(evt) {
    this.isConnecting = false;
    if (this.websocket.readyState == 1 && !this.isConnect) {
      this.isConnect = true;
      console.log("连接成功");
    } else {
      console.log("连接服务器失败(" + this.websocket.readyState + ")");
    }
  }

  onClose(evt) {
    this.isConnect = false;
    this.isConnecting = false;
    if (this.websocket) {
      this.websocket.close();
    }
    if (this.isInitiative) this.isInitiative = false;
    if (this.isConnectM) this.websocketM.close();
  }

  onMessage(evt) {
    this.isConnect = false;
    this.isConnecting = false;
    // console.log("receive message ",evt.data)
  }

  onError(evt) {
    this.isConnect = false;
    this.isConnecting = false;
    if (this.websocket) {
      this.websocket.close();
    }
    if (this.isConnectM) this.websocketM.close();
    // PlatformManager.onLoginError();
    // LoadingPanel.instance.tip = "连接服务器失败(" + Msg.websocket.readyState + ")";
  }

  connect(url, inputAccount): Promise<boolean> {
    return new Promise((resolve, reject) => {
      if (this.isConnect && this.websocket?.readyState === 1) {
        resolve(true);
        return;
      }
      if (this.isConnecting) {
        reject(new Error("already connecting"));
        return;
      }
      console.log("msg connect 开始连接 url:", url);
      const _that = this;
      this.isConnect = false;
      this.isConnecting = true;
      this.websocket = new WebSocket(url);
      this.websocket.binaryType = "arraybuffer";

      const timer = setTimeout(() => {
        reject(new Error("connection timeout"));
      }, 5000);

      this.websocket.onopen = function (evt) {
        clearTimeout(timer);
        _that.onOpen(evt);
        resolve(true);
      };
      this.websocket.onclose = function (evt) {
        _that.onClose(evt);
      };
      this.websocket.onmessage = function (evt) {
        _that.onMessage(evt);
      };
      this.websocket.onerror = function (evt) {
        clearTimeout(timer);
        _that.onError(evt);
        reject(new Error("WebSocket error"));
      };
      this.account = inputAccount;
    });
  }

  connectM(url) {
    if (this.isConnectM) {
      console.log("msg connectM 连接已存在");
    } else if (this.isConnectingM) {
      console.log("msg connectM 正在连接中");
    } else {
      const _that = this;
      this.isConnectM = false;
      this.isConnectingM = true;
      this.websocketM = new WebSocket(url);
      this.websocketM.binaryType = "arraybuffer";
      this.websocketM.onopen = function (evt) {
        _that.onOpenM(evt);
      };
      this.websocketM.onclose = function (evt) {
        _that.onCloseM(evt);
      };
      this.websocketM.onmessage = function (evt) {
        _that.handler.onMessageM(evt);
      };
      this.websocketM.onerror = function (evt) {
        _that.onErrorM(evt);
      };
    }
  }

  onOpenM(evt) {
    this.isConnectingM = false;
    if (this.websocketM.readyState == 1 && !this.isConnectM) {
      this.isConnectM = true;
      // Msg.CG_MIDDLE_LOGIN(account);
    } else {
      //trace("sopcket middle err:", websocketM.readyState);
    }
  }

  onCloseM(evt) {
    this.isConnectM = false;
    this.isConnectingM = false;
    console.log("onCloseM>>>>>>>>>>>>>>>>>>>>>>>>>>");
    if (this.websocketM) {
      this.websocketM.close();
    }
  }

  onErrorM(evt) {
    this.isConnectM = false;

    this.isConnectM = false;
    this.isConnectingM = false;
    console.log("onErrorM>>>>>>>>>>>>>>>>>>>>>>>>>>");
    if (this.websocketM) {
      this.websocketM.close();
    }
  }

  writeDouble(n) {
    this.sendBufDV.setFloat64(this.sendBufLen, n);
    this.sendBufLen = this.sendBufLen + 8;
  }

  writeInt(n) {
    this.sendBufDV.setInt32(this.sendBufLen, n);
    this.sendBufLen = this.sendBufLen + 4;
  }

  writeUint(n) {
    this.sendBufDV.setUint32(this.sendBufLen, n);
    this.sendBufLen = this.sendBufLen + 4;
  }

  writeShort(n) {
    this.sendBufDV.setInt16(this.sendBufLen, n);
    this.sendBufLen = this.sendBufLen + 2;
  }

  writeByte(n) {
    this.sendBufDV.setInt8(this.sendBufLen, n);
    this.sendBufLen = this.sendBufLen + 1;
  }

  writeString(str) {
    // 参数验证：确保 str 不为 undefined 或 null
    if (str === undefined || str === null) {
      console.error("writeString 接收到 undefined 或 null 参数:", str);
      str = ""; // 使用空字符串作为默认值
    }
    
    var oldPos = this.sendBufLen;
    this.writeShort(0);
    var totalByte = 0;
    var strLen = str.length;
    for (var i = 0; i < strLen; ++i) {
      var t = str.charCodeAt(i);
      if (t < 128) {
        totalByte = totalByte + 1;
        this.writeByte(t);
      } else if (t < 2048) {
        totalByte = totalByte + 2;
        this.writeByte((t >> 6) | 192);
        this.writeByte((t & 63) | 128);
      } else if (t < 65536) {
        totalByte = totalByte + 3;
        this.writeByte((t >> 12) | 224);
        this.writeByte(((t >> 6) & 63) | 128);
        this.writeByte((t & 63) | 128);
      } else {
        throw "error";
      }
    }
    this.sendBufDV.setInt16(oldPos, totalByte);
  }

  send(packetID) {
    var ab = new Uint8Array(this.sendBufLen);
    for (var i = 0; i < this.sendBufLen; ++i) {
      ab[i] = this.sendBufDV.getInt8(i);
    }

    this.websocket.send(ab.buffer);
  }

  close() {
    if (this.websocket) {
      this.websocket.close();
    }
    if (this.websocketM) {
      this.websocketM.close();
    }
    this.isConnect = false;
    this.isConnecting = false;
    this.isConnectM = false;
    this.isConnectingM = false;
  }

  CG_ASK_LOGIN(
    account: string,
    timestamp: number,
    authkey: string,
    lang: string,
    region: string,
    ip: string,
    params: string,
    server_id: number
  ) {
    logger.info("发送发货消息开始", {params:params, readyState: this.websocket.readyState, isConnect: this.isConnect });
    logger.info("发送登录消息", {readyState: this.websocket.readyState,isConnect: this.isConnect});
    if (this.isConnect != true || this.websocket.readyState != 1) return false;
    
    // 参数验证和默认值处理
    const safeAccount = account || "";
    const safeAuthkey = authkey || "";
    const safeLang = lang || "cn";
    const safeRegion = region || "CN";
    const safeIp = ip || "127.0.0.1";
    const safeParams = params || "{}";
    
    this.sendBufLen = 4;
    this.writeString(safeAccount);
    this.writeInt(timestamp);
    this.writeString(safeAuthkey);
    this.writeString(safeLang);
    this.writeString(safeRegion);
    this.writeString(safeIp);
    this.writeString(safeParams);
    this.writeInt(server_id);
    this.sendBufDV.setInt16(2, 62);
    this.sendBufDV.setInt16(0, this.sendBufLen - 4);
    this.send(62);
    logger.info("发送发货消息结束", {params:params, readyState: this.websocket.readyState, isConnect: this.isConnect });
    this.close(); // 主动断开连接
    return true;
  }

  CG_TEST_PROTO(account: string, param: string, server_id = 1) {
    logger.info("发送CDK道具消息", {readyState:this.websocket.readyState, isConnect:this.isConnect,param:param,server_id:server_id,account:account});
    if (this.isConnect != true || this.websocket.readyState != 1) return false;
    this.sendBufLen = 4;
    this.writeString(account);
    this.writeString(param);
    this.writeInt(server_id);
    this.sendBufDV.setInt16(2, 1259);
    this.sendBufDV.setInt16(0, this.sendBufLen - 4);
    this.send(1259);
    logger.info("发送完了断开连接",{account:account});
    this.close(); // 主动断开连接
    return true;
  }

  CG_SET_BAN(banInfo: string) {
    console.log("发送封禁消息", this.websocket.readyState, this.isConnect);
    if (this.isConnect != true || this.websocket.readyState != 1) return false;
    this.sendBufLen = 4;
    this.writeString(banInfo);
    this.sendBufDV.setInt16(2, 1490);
    this.sendBufDV.setInt16(0, this.sendBufLen - 4);
    this.send(1490);
    console.log("发送完了断开连接");
    this.close(); // 主动断开连接
    return true;
  }

  CG_CHAT_NEW_BAN(
      uuid: string,
      type: number,
      time: number,
      reason: string,
  ) {
    logger.info("发送禁言消息开始", {uuid:uuid,type:type,time:time,reason:reason, readyState: this.websocket.readyState, isConnect: this.isConnect });
    // console.log("发送登录消息", this.websocket.readyState, this.isConnect);
    if (this.isConnect != true || this.websocket.readyState != 1) return false;
    this.sendBufLen = 4;
    this.writeString(uuid);
    this.writeInt(type);
    this.writeInt(time);
    this.writeString(reason);
    this.sendBufDV.setInt16(2, 62);
    this.sendBufDV.setInt16(0, this.sendBufLen - 4);
    this.send(62);
    this.close(); // 主动断开连接
    return true;
  }



}
