import { LogUtil } from "fastsdk";
import { JSON } from "@kit.ArkTS";
import { POST_MESSAGE_TO_HOST } from "classesLib";

export class UnityApiBridge {
  public PostMsgFunc(data: Record<string, string | number | object>) {
    try {
      LogUtil.info('===== 鸿蒙侧通信调试开始 =====');
      LogUtil.info(`1. 进入PostMsgFunc，原始数据： ${JSON.stringify(data)}`);
      const param: Array<ESObject> = [data];
      let msg: ESObject = {
        // modulePath: "./HLReceive.ets",
        moduleName:"tuanjieLib",
        funcName: "HLReceive.receiveMessage",
        args: param,
        callback: null,
        timeoutMs: -1,
      }
      LogUtil.info(`2. 构造的msg消息体：${JSON.stringify(msg)}`);
      // 核心调用
      POST_MESSAGE_TO_HOST(msg);
      LogUtil.info('3. POST_MESSAGE_TO_HOST调用完成，消息已发送');
      LogUtil.info('===== 鸿蒙侧通信调试结束 =====');
    } catch (e) {
      LogUtil.error(`❌ 鸿蒙侧调用失败，捕获异常： ${e}`);
    }
  }

  initSDK() {
    let SDKData: Record<string, string> = {
      'params': '{}',
      'func': "receive_init"
    };
    this.sendMessage(SDKData)
  }

  login() {
    LogUtil.info('HLPlatform login invoke');
    let SDKData: Record<string, string> = {
      'params': '{}',
      'func': "receive_login"
    };
    this.sendMessage(SDKData)
  }

  logout() {
    let SDKData: Record<string, string> = {
      'params': '{}',
      'func': "receive_logout"
    };
    this.sendMessage(SDKData);
  }

  switchAccount() {
    let SDKData: Record<string, string> = {
      'params': '{}',
      'func': "receive_switchAccount"
    };
    this.sendMessage(SDKData);
  }

  exit() {
    let SDKData: Record<string, string> = {
      'params': '{}',
      'func': "receive_exitGame"
    };
    this.sendMessage(SDKData)
  }

  startPay(parm: string) {
    let paramsData: Record<string, string> = {
      'payData': parm
    }
    let SDKData: Record<string, string | object> = {
      'params': paramsData,
      'func': "receive_pay"
    };
    this.sendMessage(SDKData);
  }

  sendEvent(eventType: number, jsonStr: string) {
    let data: Record<string, string> = {
      'type': `${eventType}`,
      'content': jsonStr
    };
    let SDKData: Record<string, string | object> = {
      'params': data,
      'func': "receive_report"
    };
    this.sendMessage(SDKData);
  }

  accessParticipate() {

  }

  openAccount() {
    let SDKData: Record<string, string | number> = {
      'params': '{}',
      'func': "receive_account"
    };
    this.sendMessage(SDKData)
  }

  shareData() {

  }

  sendMessage(data: Record<string, string | number | object>) {
    this.PostMsgFunc(data);
  }
}

export function RegisterHLPlatform() {
  let register: Record<string, Object> = {};
  register["UnityApiBridge"] = new UnityApiBridge();
  return register;
}