
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) {
  const realAir = {
    uploadUrl: "",
    uploadData: null,
    engineInfo: null,
    hideAirClassLoading(templateName, loadData) {
      _this.log("***成功调用hideAirClassLoading***");
      window.air.onCourseInScreen && window.air.onCourseInScreen(() => {
        _this.log("***成功调用onCourseInScreen***");
      });
    },
    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,
    takePictureCallBack: null,
    configurationPortraitCallback: null,
    configurationLandscapeCallback: null,
    recognitionCameraCallBack: null,
    testCallBack: null,
    recordCallBack: null,
    onCourseInScreen: null,
  };
  try {
    window.air = new Proxy(realAir, {
      set: function (target, key, value, receiver) {
        let newValue = value;
        if (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===");
      callback && callback(null);
    },
    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)}`);
      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===`);
    },
    // 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}`);
        callback && callback(res);
        window.air.testCallBack = null;
      };
      window.courseware.callOcMethod("stopTest", {});
    },
    // 拍照
    takePicture(callback) {
      _this.log(`===成功调用takePicture===`);
      window.air.takePictureCallBack = (res) => {
        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", {});
    },
    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", {});
    },
    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);
    },
    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('CocosMng', `${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'});
        } 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{
          console.error(`${method}方法还没有Mock数据，请联系技术支持人员添加`);
        }
      }
    },
    freeAllOcMethod() {
      if (window.courseware.hasCalledStartRecord) {
        window.courseware.stopRecord();
      }
      if (window.courseware.hasCalledStartTest) {
        window.courseware.stopTest();
      }
      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();
      }
    }
  };
}
