
const testMockData = {"eof":1,"file":"/storage/emulated/0/Android/data/com.example.oxford/cache/shengtong/gradeVoice.mp3","audioUrl":"https://staging-teach.cdn.ireadabc.com/db48d49e122ba65aa7c5ee56963418a6.mp3","result":{"duration":"2.470","fluency":100,"integrity":100,"kernel_version":"3.6.7","overall":99,"pronunciation":99,"resource_version":"2.3.6","rhythm":0,"speed":78},"tokenId":"621c32543327932cfc000002"};
const recordMockData = {"text":"what can i do for you","audioUrl":"https://staging-teach.cdn.ireadabc.com/368ad56174f85e2ff1f39f12bac5c693.mp3"};

export function initAir(_this) {
  // 安全兜底：确保 _this 存在且具备 log/showTips 方法，避免 e.log 为 null
  try {
    if (!_this) {
      _this = {};
    }
    if (typeof _this.log !== 'function') {
      _this.log = (...args) => {
        try {
          console.log.apply(console, args);
        } catch (e) {
          // 在某些 JSB 环境中 apply 可能异常，使用降级
          console.log(args && args.length === 1 ? args[0] : args.join(' '));
        }
      };
    }
    if (typeof _this.showTips !== 'function') {
      _this.showTips = (msg) => {
        try {
          console.warn(msg);
        } catch (e) {
          // 安全降级
        }
      };
    }
  } catch (e) {
    // 极端情况下保持不抛异常
    try { console.warn('initAir context fallback failed:', e); } catch (_) {}
  }

  const realAir = {
    uploadUrl: "",
    uploadData: null,
    engineInfo: null,
    hideAirClassLoading(templateName, loadData) {
      _this.log("***成功调用hideAirClassLoading***");
      window.air.onCourseInScreen && window.air.onCourseInScreen(() => {
        _this.log("***成功调用onCourseInScreen***");
      });
    },
    recordRealtimeCallBack: function (res) {
      _this.log(`***成功调用recordRealtimeCallBack***参数==${res}`);
    },
    recordWordSpellCallBack: function (res) {
      _this.log(`***成功调用recordWordSpellCallBack***参数==${res}`);
    },
    osmoCallback: function (res) {
      _this.log(`***成功调用osmoCallback***参数==${res}`);
    },
    osmoHandwritingCallback: function (res) {
      _this.log(`***成功调用osmoHandwritingCallback***参数==${res}`);
    },
    osmoHandwritingMlkitCallback: function (res) {
      _this.log(`***成功调用osmoHandwritingMlkitCallback***参数==${res}`);
    },
    osmoFingerReadCallback: function (res) {
      _this.log(`***成功调用osmoFingerReadCallback***参数==${res}`);
    },
    dialogStatus: function (res) {
      _this.log(`***成功调用dialogStatus***参数==${res}`);
    },
    startScanCodeCallback: null,
    needUpdateCallback: null,
    getEngineInfoCallback: null,
    logFileUploadCallback: null,
    takePictureCallBack: null,
    configurationPortraitCallback: null,
    configurationLandscapeCallback: null,
    startBuyToAppStoreCallBack: null,
    recognitionCameraCallBack: null,
    testCallBack: null,
    testConvertCallBack: null,
    recordCallBack: null,
    onCourseInScreen: null,
  };
  try {
    window.air = new Proxy(realAir, {
      set: function (target, key, value, receiver) {
        let newValue = value;
        if (key == "recordWordSpellCallBack" || key == "recordRealtimeCallBack" || key == "osmoCallback" || key == "osmoHandwritingCallback" || key == "osmoHandwritingMlkitCallback" || key == "osmoFingerReadCallback") {
          newValue = function (res) {
            _this.log(`||==成功调用${key}==||参数==${JSON.stringify(res)}`);
            if(typeof(res) == 'string') {
              value(res);
            } else {
              value(JSON.stringify(res));
            }
          }
        }
        return Reflect.set(target, key, newValue, receiver);
      },
      get: function (target, key, receiver) {
        return Reflect.get(target, key, receiver);
      },
      deleteProperty: function (target, key) {
        return Reflect.deleteProperty(target, key);
      }
    });
  } catch (e) {
    console.error("浏览器不支持ES6新特性Proxy/Reflect，请使用谷歌浏览器！");
  }
  window.courseware = {
    getData(callback) {
      _this.log("===成功调用getData===");
      const result = (_this && _this.COURSE_DATA) ? _this.COURSE_DATA : {};
      try {
        callback && callback(result);
      } catch (err) {
        try {
          _this.log(`getData callback error: ${err && err.message || err}`);
        } catch (_) {
          // 尝试输出
          try { console.warn(err); } catch (__){ }
        }
      }
    },
    uploadUrl() {
      _this.log("===成功调用uploadUrl===");
      return window.air.uploadUrl;
    },
    uploadData() {
      _this.log("===成功调用uploadData===");
      return window.air.uploadData;
    },
    nextPage() {
      _this.log("===成功调用nextPage===");
    },
    beforePage() {
      _this.log("===成功调用beforePage===");
    },
    jumpPage(page) {
      _this.log(`===成功调用jumpPage=== page == ${page}`);
    },
    sendAnswer(answerObj) {
      _this.log(`===成功调用sendAnswer=== answerObj == ${JSON.stringify(answerObj)}`);
      if (answerObj) {
        answerObj.callback && answerObj.callback();
      }
    },
    getAnswer(queryObj, callback) {
      _this.log(`===成功调用getAnswer=== queryObj == ${JSON.stringify(queryObj)}`);
      callback && callback(null);
    },
    addStar() {
      _this.log(`===成功调用addStar===`);
    },
    getTemplates(callback) {
      _this.log(`===成功调用getTemplates===`);
      callback && callback(null);
    },
    getTemplateUrl(templateName, callback) {
      _this.log(`===成功调用getTemplateUrl=== templateName == ${templateName}`);
      callback && callback(null);
    },
    gameEnd() {
      _this.log(`===成功调用gameEnd===`);
    },
    // 兼容模板调用：提供 courseware.log，代理到 _this.log，避免 e.log 为空
    log(...args) {
      try {
        // _this.log(...args);
      } catch (err) {
        try {
          console.log.apply(console, args);
        } catch (_) {
          console.log(args && args.length === 1 ? args[0] : args.join(' '));
        }
      }
    },
    // isSpeechToText 1: 录音转文本，0：纯录音
    startRecord(isSpeechToText) {
      _this.log(`===成功调用startRecord=== isSpeechToText == ${isSpeechToText}`);
      window.courseware.hasCalledStartRecord = true;
      window.courseware.callOcMethod("startRecord", { isSpeechToText });
    },
    stopRecord(callback1, callback2) {
      // 传两个参数是为了兼容以前
      window.courseware.hasCalledStartRecord = false;
      const callback = callback1 || callback2;
      _this.log(`===成功调用stopRecord===`);
      if (!callback) {
        // 不传回调函数就表示取消评测
        window.courseware.callOcMethod("stopRecord", { isBreak: 1 });
        return;
      }
      // 结束录音
      window.air.recordCallBack = (res) => {
        res = typeof(res) == 'string' ? res : JSON.stringify(res);
        _this.log(`===成功调用recordCallBack=== res == ${res}`);
        callback && callback(res);
        window.air.recordCallBack = null;
      };
      window.courseware.callOcMethod("stopRecord", { isBreak: 0 });
    },
    startTest(testText, option) {
      window.courseware.hasCalledStartTest = true;
      _this.log(`===成功调用startTest=== testText == ${testText}`);
      window.courseware.callOcMethod("startTest", { ...option, "params": testText });
    },
    stopTest(callback) {
      window.courseware.hasCalledStartTest = false;
      _this.log(`===成功调用stopTest===`);
      if (!callback) {
        // 不传回调函数就表示取消评测
        _this.log(`===成功取消录音评测===`);
        window.courseware.callOcMethod("stopTest", { isBreak: 1 });
        return;
      }
      // 结束录音
      window.air.testCallBack = (res) => {
        res = typeof(res) == 'string' ? res : JSON.stringify(res);
        _this.log(`===成功调用testCallBack=== res == ${res}`);
        // 录音异常兼容处理
        const resObj = JSON.parse(res);
        if (resObj.errCode) {
          resObj.result = {overall:0};
          resObj.audioUrl = "";
          res = JSON.stringify(resObj);
          _this.showTips(`评测服务信号弱，可能会造成评分不准确，请稍后再来录音评测吧~`);
        }
        callback && callback(res);
        window.air.testCallBack = null;
      };
      window.courseware.callOcMethod("stopTest", {});
    },

    startTestConvert(testText, option) {
      window.courseware.hasCalledStartTestConvert = true;
      _this.log(`===成功调用startTestConvert=== testText == ${testText}`);
      window.courseware.callOcMethod("startTestConvert", { ...option, "params": testText });
    },

    stopTestConvert(testCallback, convertCallback) {
      window.courseware.hasCalledStartTestConvert = false;
      _this.log(`===成功调用stopTestConvert===`);
      if (!testCallback) {
        // 不传回调函数就表示取消评测
        _this.log(`===成功取消录音评测===`);
        window.courseware.callOcMethod("stopTestConvert", { isBreak: 1 });
        return;
      }
      // 结束录音
      window.air.testCallBack = (res) => {
        res = typeof(res) == 'string' ? res : JSON.stringify(res);
        _this.log(`===成功调用testCallBack=== res == ${res}`);
        // 录音异常兼容处理
        const resObj = JSON.parse(res);
        if (resObj.errCode) {
          resObj.result = {overall:0};
          resObj.audioUrl = "";
          res = JSON.stringify(resObj);
          _this.showTips(`评测服务信号弱，可能会造成评分不准确，请稍后再来录音评测吧~`);
        }
        testCallback && testCallback(res);
        window.air.testCallBack = null;
      };
      // 结束变声
      window.air.testConvertCallBack = (res) => {
        res = typeof(res) == 'string' ? res : JSON.stringify(res);
        _this.log(`===成功调用testConvertCallBack=== res == ${res}`);
        // 录音异常兼容处理
        const resObj = JSON.parse(res);
        if (resObj.errCode) {
          resObj.convertUrl = "";
          res = JSON.stringify(resObj);
          _this.showTips(`变声失败，请稍后再来尝试吧~`);
        }
        convertCallback && convertCallback(res);
        window.air.testConvertCallBack = null;
      };
      window.courseware.callOcMethod("stopTestConvert", {});
    },

    startRealtimeRecord(params = {}) {
      window.courseware.hasCalledRealtimeRecord = true;
      _this.log(`===成功调用startRealtimeRecord===${JSON.stringify(params)}`);
      window.courseware.callOcMethod("startRealtimeRecord", params);
    },
    stopRealtimeRecord(params = {}) {
      window.courseware.hasCalledRealtimeRecord = false;
      _this.log(`===成功调用stopRealtimeRecord===`);
      window.courseware.callOcMethod("stopRealtimeRecord", params);
    },
    
    startWordSpell(params = {}) {
      window.courseware.hasWordSpelling = true;
      _this.log(`===成功调用startWordSpell===${JSON.stringify(params)}`);
      window.courseware.callOcMethod("startWordSpell", params);
    },
    stopWordSpell(params = {}) {
      window.courseware.hasWordSpelling = false;
      _this.log(`===成功调用stopWordSpell===`);
      window.courseware.callOcMethod("stopWordSpell", params);
    },

    // 拍照
    takePicture(callback) {
      _this.log(`===成功调用takePicture===`);
      window.air.takePictureCallBack = (res) => {
        if(typeof(res) == 'string') {
          callback && callback(res);
        } else {
          callback && callback(JSON.stringify(res));
        }
        window.air.takePictureCallBack = null;
      };
      window.courseware.callOcMethod("takePicture", {});
    },

    openRecognitionCamera(params = {}, callback) {
      window.courseware.hasCalledOpenRecognitionCamera = true;
      _this.log(`===成功调用openRecognitionCamera===${JSON.stringify(params)}`);
      window.air.recognitionCameraCallBack = (res) => {
        callback && callback(JSON.stringify(res));
        window.air.recognitionCameraCallBack = null;
      };
      window.courseware.callOcMethod("openRecognitionCamera", params);
    },
    closeRecognitionCamera() {
      window.courseware.hasCalledOpenRecognitionCamera = false;
      _this.log(`===成功调用closeRecognitionCamera===`);
      window.courseware.callOcMethod("closeRecognitionCamera", {});
    },
    getEngineInfo(callback) {
      _this.log(`===成功调用getEngineInfo===`);
      // 调用原生获取机器信息
      window.air.getEngineInfoCallback = (res) => {
        if(typeof(res) == 'string') {
          window.air.engineInfo = res;
          callback && callback(res);
        } else {
          window.air.engineInfo = JSON.stringify(res);
          callback && callback(JSON.stringify(res));
        }
        window.air.getEngineInfoCallback = null;
      };
      window.courseware.callOcMethod("getEngineInfo", {});
    },
    logUpload(callback) {
      _this.log(`===成功调用logUpload===`);
      // 调用原生获取机器信息
      window.air.logFileUploadCallback = (res) => {
        if(typeof(res) == 'string') {
          callback && callback(res);
        } else {
          callback && callback(JSON.stringify(res));
        }
        window.air.logFileUploadCallback = null;
      };
      window.courseware.callOcMethod("logUpload", {});
    },
    behaviorToCollectWithParam(event, type="") {
      // 埋点所需接口 levelPayForSuccess  userRegistrationEvent
      window.courseware.callOcMethod("behaviorToCollectWithParam", {event, type});
    },
    exitApp() {
      _this.log(`===成功调用exitApp===`);
      window.courseware.callOcMethod("exitApp", {});
    },
    changeHost() {
      _this.log(`===成功调用changeHost===`);
      // 调用原生获取机器信息
      if (window.air.engineInfo) {
        const engineInfo = JSON.parse(window.air.engineInfo);
        window.courseware.callOcMethod("changeHost", {isStagingEnv: engineInfo.isDev != 1});
      }
    },
    needUpdate(label, url, callback) {
      _this.log(`===成功调用needUpdate===`);
      // 调用原生获取机器信息
      window.air.needUpdateCallback = (res) => {
        callback && callback(res);
        window.air.needUpdateCallback = null;
      };
      window.courseware.callOcMethod("needUpdate", { label: label, url: url });
    },
    startScanCode(callback) {
      _this.log(`===成功调用startScanCode===`);
      // 调用原生开始扫码
      window.air.startScanCodeCallback = (res) => {
        callback && callback(res);
        window.air.startScanCodeCallback = null;
      };
      window.courseware.callOcMethod("startScanCode", {});
    },
    openOsmo(params = {}) {
      window.courseware.hasCalledOpenOsmo = true;
      _this.log(`===成功调用openOsmo===${JSON.stringify(params)}`);
      window.courseware.callOcMethod("openOsmo", params);
    },
    closeOsmo() {
      window.courseware.hasCalledOpenOsmo = false;
      _this.log(`===成功调用closeOsmo===`);
      window.courseware.callOcMethod("closeOsmo", {});
    },
    openOsmoHandwriting(params = {}) {
      window.courseware.hasCalledOpenOsmoHandwriting = true;
      _this.log(`===成功调用openOsmoHandwriting===${JSON.stringify(params)}`);
      window.courseware.callOcMethod("openOsmoHandwriting", params);
    },
    closeOsmoHandwriting() {
      window.courseware.hasCalledOpenOsmoHandwriting = false;
      _this.log(`===成功调用closeOsmoHandwriting===`);
      window.courseware.callOcMethod("closeOsmoHandwriting", {});
    },
    openOsmoHandwritingMlkit(params = {}) {
      window.courseware.hasCalledOpenOsmoHandwritingMlkit = true;
      _this.log(`===成功调用openOsmoHandwritingMlkit===${JSON.stringify(params)}`);
      window.courseware.callOcMethod("openOsmoHandwritingMlkit", params);
    },
    closeOsmoHandwritingMlkit() {
      window.courseware.hasCalledOpenOsmoHandwritingMlkit = false;
      _this.log(`===成功调用closeOsmoHandwritingMlkit===`);
      window.courseware.callOcMethod("closeOsmoHandwritingMlkit", {});
    },
    openOsmoFingerRead(params = {}) {
      window.courseware.hasCalledOpenOsmoFingerRead = true;
      _this.log(`===成功调用openOsmoFingerRead===${JSON.stringify(params)}`);
      window.courseware.callOcMethod("openOsmoFingerRead", params);
    },
    closeOsmoFingerRead() {
      window.courseware.hasCalledOpenOsmoFingerRead = false;
      _this.log(`===成功调用closeOsmoFingerRead===`);
      window.courseware.callOcMethod("closeOsmoFingerRead", {});
    },
    modifyVideoSpeed(params = {}, callback) {
      _this.log(`===成功调用modifyVideoSpeed===`);

      window.air.modifyVideoSpeedCallback = (res) => {
        _this.log(`===modifyVideoSpeedCallback=== res == ${res}`);
        callback && callback(res);
        window.air.modifyVideoSpeedCallback = null;
      };

      window.courseware.callOcMethod("modifyVideoSpeed", params);
    },
    onConfigurationPortrait(params = {}, callback) {
      _this.log(`===成功调用onConfigurationPortrait||竖屏===`);
      window.air.configurationPortraitCallback = (res) => {
        callback && callback(res);
        window.air.configurationPortraitCallback = null;
      };
      window.courseware.callOcMethod("onConfigurationPortrait", params);
    },
    onConfigurationLandscape(params = {}, callback) {
      _this.log(`===成功调用onConfigurationLandscape||横屏===`);
      window.air.configurationLandscapeCallback = (res) => {
        callback && callback(res);
        window.air.configurationLandscapeCallback = null;
      };
      window.courseware.callOcMethod("onConfigurationLandscape", params);
    },
    startBuyToAppStore(params = {}, callback) {
      // 苹果支付
      _this.log(`===成功调用startBuyToAppStore===`);
      window.air.startBuyToAppStoreCallBack = (res) => {
        callback && callback(res);
      };
      window.courseware.callOcMethod("startBuyToAppStore", params);
    },
    callOcMethod(method, param) {
      const paramStr = JSON.stringify(param);
      _this.log(`===成功调用原生方法${method}===参数==${paramStr}`);
      if (cc.sys.isNative && cc.sys.os == cc.sys.OS_IOS) {
        return jsb.reflection.callStaticMethod('RootViewController', `${method}:`, paramStr);
      } else if (cc.sys.isNative && cc.sys.os == cc.sys.OS_ANDROID) {
        return jsb.reflection.callStaticMethod('com/iplayabc/cocos/AppActivity', method, '(Ljava/lang/String;)Ljava/lang/String;', paramStr);
      } else if (cc.sys.isNative && cc.sys.os == cc.sys.OS_WINDOWS) {
        console.log('汪汪汪')
      } else {
        console.error(`非源生环境，网页版不支持${method}方法，将返回此方法的Mock数据以便于网页版调试使用`);
        if(method == 'getEngineInfo'){
          window.air.getEngineInfoCallback({isDev: 1, uuid: 'debug-xxxxxx-xxxxxx', version: '1.0.2'});
        } else if(method == 'logUpload'){
          window.air.logFileUploadCallback({"fileUrl":"abcedfgh","error":""});
        } else if (method == 'startTest') {
        } else if (method == 'stopTest') {
          window.air.testCallBack(testMockData);
        } else if (method == 'startRecord') {
        } else if (method == 'stopRecord') {
          window.air.recordCallBack(recordMockData);
        } else if (method == 'startBuyToAppStore') {
          window.air.startBuyToAppStoreCallBack({productid: 1, puid: 22, receiptData: "HelloWorld", error: ""});
        } else{
          console.error(`${method}方法还没有Mock数据，请联系技术支持人员添加`);
        }
      }
    },
    freeAllOcMethod() {
      if (window.courseware.hasCalledStartRecord) {
        window.courseware.stopRecord();
      }
      if (window.courseware.hasCalledStartTest) {
        window.courseware.stopTest();
      }
      if (window.courseware.hasCalledStartTestConvert) {
        window.courseware.stopTestConvert();
      }
      if (window.courseware.hasCalledRealtimeRecord) {
        window.courseware.stopRealtimeRecord();
      }
      if (window.courseware.hasWordSpelling) {
        window.courseware.stopWordSpell();
      }
      if (window.courseware.hasCalledOpenRecognitionCamera) {
        window.courseware.closeRecognitionCamera();
      }
      if (window.courseware.hasCalledOpenOsmo) {
        window.courseware.closeOsmo();
      }
      if (window.courseware.hasCalledOpenOsmoHandwriting) {
        window.courseware.closeOsmoHandwriting();
      }
      if (window.courseware.hasCalledOpenOsmoHandwritingMlkit) {
        window.courseware.closeOsmoHandwritingMlkit();
      }
      if (window.courseware.hasCalledOpenOsmoFingerRead) {
        window.courseware.closeOsmoFingerRead();
      }
    }
  };
}

// 兼容模板：提供全局 e 指向 courseware，避免 e 为 null
try {
  if (!window.e) {
    window.e = window.courseware;
  }
} catch (_) {}
