// noinspection JSUnresolvedVariable,JSUnresolvedFunction

import mockOpeBZPHX from "@/sdk/mockOpeBZPHX";

const TAG = '[OperateBZPHX]';
let _OperateBZPHX;

export async function createOperatePHX() {
  if (_OperateBZPHX) {
    console.debug(TAG, "use exist _OperateBZPHX")
    return _OperateBZPHX;
  } else {
    if (window.plus && window.plus.bridge) {
      _OperateBZPHX = await _registerOpePHX();
      return _OperateBZPHX
    } else {
      console.warn(TAG, "'window.plus.bridge' missing, check if it registered");
    }
  }
  return mockOpeBZPHX;
}

async function _registerOpePHX() {
  const _BARCODE = 'OperatePHX' // 插件名称
  const B = window.plus.bridge;
  window.plus.OperateBZPHX = {
    name: 'OperateBZPHX',
    callNative: function (funName, args, successCallback) {
      const callbackId = this.getCallbackId(successCallback, this.errorCallback);
      if (args != null) {
        args.unshift(callbackId)
      } else {
        args = [callbackId]
      }
      return B.exec(_BARCODE, funName, args)
    },
    getCallbackId: function (successCallback) {
      let success = typeof successCallback !== 'function' ? null : function (args) {
        successCallback(args)
      }
      return B.callbackId(success, this.errorCallback)
    },
    errorCallback: function (errorMsg) {
      console.log('Javascript callback error: ' + errorMsg)
    },

    /*
     * 初始化SDK，初始化过程会完成登录、实名、防沉迷认证等流程
     * 注意：初始化后其他接口调用才是可靠的
     *
     * gameKey: 字符串，4399 平台游戏 id，在 https://open.4399.cn/console/ 注册后可得到，开发者完成或运营协助完成
     * orientation: 整数，游戏方向，可取值：0，横屏；1，竖屏；6，可180度旋转的横屏
     * compatNotch: 是否支持全面屏幕，影响SDK对话框和页面显示
	   *     更多信息，参考官方说明：https://developer.android.google.cn/training/system-ui/immersive?hl=zh-cn
     * callback: 初始化回调
     */
    initSDK: function (gameKey, orientation, compatNotch, callback) {
      let fn = 'initSDK';
      this.callNative(fn, [gameKey, orientation, compatNotch], this.wrapJsCallback(fn, callback));
    },

    /**
     * 判断 SDK 内是否有已登录，已登录可以直接调用 getUser方法获取用户信息，而不需要调用登录
     *
     * @param callback 回调方法，回调格式：{
     *   event: "check_login",
     *   isLogin: "true"
     * }
     */
    isLogin: function (callback) {
      let fn = 'isLogin';
      this.callNative(fn, null, this.wrapJsCallback(fn, callback));
    },

    /**
     * 获取 SDK 登录用户，
     *
     * @param callback 回调方法，参数格式 {
     *         event: "get_user",
     *         "user": {
     *           uid: "0000000002",
     *           name: "ope_phx_test_user",
     *           nick: "Happy"
     *         }
     *       }
     */
    getUser: function (callback) {
      let fn = 'getUser';
      this.callNative(fn, null, this.wrapJsCallback(fn, callback));
    },

    /**
     * 登录
     *
     * @param callback 回调方法，参数格式 {
     *       event: "account_login",
     *       success: true,
     *       resultCode: 16,
     *       user: mockUser
     *     }
     */
    login: function (callback) {
      let fn = 'login';
      this.callNative(fn, null, this.wrapJsCallback(fn, callback));
    },

    /**
     * 登出
     *
     * 调用此接口时，游戏也应清楚自身的登录状态，并回到游戏登录页面
     */
    logout: function () {
      let fn = 'logout';
      this.callNative(fn, null, this.wrapJsCallback(fn));
    },

    /**
     * 读取存档
     *
     * @param callback 回调方法，参数格式 {
     *   data: Object
     *   resultCode: Number
     *   message: String
     * }
     *
     */
    readArchive: function (callback) {
      let fn = 'readArchive';
      this.callNative(fn, null, this.wrapJsCallback(fn, callback));
    },

    /**
     * 充值
     *
     * @param money 金额，整数
     * @param mark 游戏订单，唯一
     * @param commodity 商品名称，可选
     * @param supportExcess 是否支持超出金额
     * @param callback 回调对象，参数个数 {
     *         event: 'recharge_finished',
     *         success: true,
     *         message: '充值成功',
     *         resultCode: 0
     *       }
     */
    recharge: function (money, mark, commodity, supportExcess, callback) {
      let fn = 'recharge';
      this.callNative(fn, [money, mark, commodity, supportExcess], this.wrapJsCallback(fn, callback));
    },

    // 辅助接口，打js和android 日志
    _androidLog: function (obj) {
      console.log(obj);
      this.callNative('androidLog', [obj]);
    },

    wrapJsCallback: function (funName, callback) {
      return retValue => {
        this._androidLog({funName, callback});
        let json = {};
        if (retValue) {
          try {
            json = JSON.parse(retValue);
            this._androidLog({json});
          } catch (e) {
            this._androidLog(e.stack)
          }
        }
        if (callback)
          callback(json);
      }
    }
  };

  return window.plus.OperateBZPHX;
}


