import { initAir } from "./air";
import { middleLayerBase } from "./middleLayerBase";
import { buttonOnceClick, buttonOnClick, guid } from "./util";

const { ccclass, property } = cc._decorator;

@ccclass
export default class NewClass extends middleLayerBase {
  reWriteAir() {
    (<any>window).courseware.getData = async (callback) => {
      let data = null;
      if (this.courseItem && this.courseItem.data) {
        data = this.courseItem.data.replace(/http:/g, "https:");
        this.log("===成功调用getData===" + data);
        data = JSON.parse(data);
      }
      callback && callback(data);
    }

    (<any>window).courseware.stopTest = (callback) => {
      (<any>window).courseware.hasCalledStartTest = false;
      console.log(`===成功调用stopTest===`);
      if (!callback) {
        // 不传回调函数就表示取消评测
        console.log(`===成功取消录音评测===`);
        (<any>window).courseware.callOcMethod("stopTest", { isBreak: 1 });
        return;
      }
      // 结束录音
      (<any>window).air.testCallBack = (res) => {
        res = typeof (res) == 'string' ? res : JSON.stringify(res);
        console.log(`===成功调用testCallBack=== res == ${res}`);
        // 录音异常兼容处理
        const resObj = JSON.parse(res);
        if (resObj.errCode) {
          resObj.result = { overall: 0 };
          resObj.audioUrl = "";
          res = JSON.stringify(resObj);
          this.showTips(`评测服务信号弱，可能会造成评分不准确，请稍后再来录音评测吧~ [${resObj.errCode}]`);
        }
        this.saveRecordResult(res);
        callback && callback(res);
        (<any>window).air.testCallBack = null;
      };
      (<any>window).courseware.callOcMethod("stopTest", {});
    }

    if (!(<any>window).air) {
      (<any>window).air = {};
    }
    (<any>window).air.hideAirClassLoading = () => {
      if ((<any>window).air.onCourseInScreen) {
        (<any>window).air.onCourseInScreen(() => {
          console.log("***成功调用onCourseInScreen***");
          (<any>window).air.onCourseInScreen = null;
          this.setVideoToBottom();
          this.hideWaitingLetters();
          this.hideMask();
        });
      } else {
        this.setVideoToBottom();
        this.hideWaitingLetters();
        this.hideMask();
      }
    }
  }

  setVideoToBottom() {
    const videos = cc.find("Canvas").getComponentsInChildren(cc.VideoPlayer);
    if (videos.length > 0) {
      for (let i = 0; i < videos.length; i++) {
        const video = videos[i];
        cc.find("Canvas/Main Camera").getComponent(cc.Camera).backgroundColor = cc.color(0,0,0,0);
        video.stayOnBottom = true;
      }
    } else {
      // cc.macro.ENABLE_TRANSPARENT_CANVAS = false; 
    }
  }

  tipsTween = null;
  async showTips(str: string) {
    const tipsLayer = cc.find('middleLayer/tipsLayer');

    if (this.tipsTween) {
      this.tipsTween.stop();
      tipsLayer.active = false;
    }
    const label = cc.find('middleLayer/tipsLayer/tips/label');
    label.getComponent(cc.Label).string = `  ${str}  `;
    const tips = cc.find('middleLayer/tipsLayer/tips');
    tipsLayer.active = true;
    tips.width = Math.max(300, label.width + 50);

    this.tipsTween = cc.tween(tips)
      .set({ opacity: 255 })
      .to(5, { opacity: 0 })
      .call(() => {
        tipsLayer.active = false;
        this.tipsTween = null;
      })
      .start();
  }
  async showConfirm(str: string, yesFun: Function = null, noFun: Function = null) {
    if (this.IS_BUNDLE_LOADING) {
      return;
    }
    const tipsLayer = cc.find('middleLayer/confirmLayer');
    const label = cc.find('middleLayer/confirmLayer/confirm_bg/label');
    label.getComponent(cc.Label).string = `  ${str}  `;
    const tips = cc.find('middleLayer/confirmLayer/confirm_bg');
    tipsLayer.active = true;
    tips.width = Math.max(684, label.width + 50);

    const yesBtn = cc.find('middleLayer/confirmLayer/confirm_bg/btn_yes');
    buttonOnceClick(yesBtn, (evt) => {
      yesFun && yesFun(evt);
      yesBtn.off("click");
      noBtn.off("click");
      tipsLayer.active = false;
    });
    const noBtn = cc.find('middleLayer/confirmLayer/confirm_bg/btn_no');
    buttonOnceClick(noBtn, (evt) => {
      noFun && noFun(evt);
      yesBtn.off("click");
      noBtn.off("click");
      tipsLayer.active = false;
    });
  }

  hideBuyLoading() {
    cc.find(`middleLayer/iosActiveLayer/buyloading`).active = false;
    cc.find(`middleLayer/iosActiveLayer/buy_status_win`).active = false;
  }

  async wxBuy (product) {
    const statusWin = cc.find(`middleLayer/androidActiveLayer/buy_status_win`);
    cc.find(`buy_result_text`, statusWin).getComponent(cc.Label).string = `请使用微信扫码二维码付款`;
    // 生成二维码
    const qrcode = cc.find(`qrcode`, statusWin);
    qrcode.active = false;
    // 加载远程网络图片
    const kidInfo = await this.getUserBaseInfo();
    const userId = kidInfo.parent_id;
    const productid = product.id;
    const puid = userId;
    const payuuid = guid();

    const baseUrl = await this.getBaseUrl();
    cc.loader.load({url: `${baseUrl}/api/wxpay/v1/oxfordlite/qrcode?productid=${productid}&puid=${puid}&payuuid=${payuuid}`, type: "png"}, (err, text) => {
      qrcode.getComponent(cc.Sprite).spriteFrame = new cc.SpriteFrame(text);
      qrcode.active = true;
    });
    statusWin.active = true;

    const queryPayStatus = async () => {
      if (!statusWin.active) {
        return;
      }
      const flag = await this.asyncCallNetworkApiGet(`/api/wxpay/v1/oxfordlite/checkorder`, {payuuid});
      if (flag == 'true') {
        cc.find(`buy_result_text`, statusWin).getComponent(cc.Label).string = `新获得：${product.name}探索时间${product.days}天`;
        cc.find(`active_btn`, statusWin).active = true;
        return;
      }
      setTimeout(() => {
        queryPayStatus();
      }, 500);
    }
    await queryPayStatus();
  }

  showPayLoading(pNode) {
    const payloading = cc.find(`payloading`, pNode);
    payloading.active = true;
    payloading.getComponent(cc.Animation).play();
  }

  hidePayLoading(pNode) {
    const payloading = cc.find(`payloading`, pNode);
    payloading.getComponent(cc.Animation).stop();
    payloading.active = false;
  }

  // 购买
  async buy(product) {
    // 苹果支付
    cc.find(`middleLayer/iosActiveLayer/buyloading`).active = true;
    const statusWin = cc.find(`middleLayer/iosActiveLayer/buy_status_win`);

    const kidInfo = await this.getUserBaseInfo();
    const userId = kidInfo.parent_id;
    cc.find(`buy_status_text`, statusWin).getComponent(cc.Label).string = "支付中";
    cc.find(`buy_status_sub_text`, statusWin).getComponent(cc.Label).string = "请勿关闭App！";
    statusWin.active = true;
    this.showPayLoading(statusWin);
    (<any>window).courseware.startBuyToAppStore({
      productid: product.id,
      puid: userId,
      ios_product_str: product.ios_product_str
    }, async (res) => {
      this.hidePayLoading(statusWin);
      console.log(`===成功调用startBuyToAppStoreCallBack===${res}`);
      if (typeof (res) == 'string') {
        res = JSON.parse(res);
      }
      if (res.error) {
        cc.find(`buy_status_text`, statusWin).getComponent(cc.Label).string = `支付失败`;
        cc.find(`buy_status_sub_text`, statusWin).getComponent(cc.Label).string = res.error;

        setTimeout(() => {
          cc.find(`buy_status_text`, statusWin).getComponent(cc.Label).string = "";
          cc.find(`buy_status_sub_text`, statusWin).getComponent(cc.Label).string = "";
          statusWin.active = false;
          cc.find(`middleLayer/iosActiveLayer/buyloading`).active = false;
        }, 2000);
        return;
      }
      const orderData:any = await this.asyncCallNetworkApiPost(`/api/oxford/v1/paid/ios/order/save`, {
        productid: res.productid,
        puid: res.puid,
        iospaidcode: res.receiptData
      });

      if (orderData.code!=200) {
        cc.find(`buy_status_text`, statusWin).getComponent(cc.Label).string = `支付失败[${orderData.code}]`;
        cc.find(`buy_status_sub_text`, statusWin).getComponent(cc.Label).string = `请联系客服！`;
        return;
      }
      cc.find(`buy_status_text`, statusWin).getComponent(cc.Label).string = `购买成功！`;
      cc.find(`buy_status_sub_text`, statusWin).getComponent(cc.Label).string = `快去探索绘玩绘拼自然拼读世界吧！`;

      cc.find(`buy_result_text`, statusWin).getComponent(cc.Label).string = `新获得：${product.name}探索时间${product.days}天`;
      cc.find(`buy_result_text`, statusWin).active = true;
      cc.find(`active_btn`, statusWin).active = true;

      // 回调给苹果订单处理成功了
      (<any>window).courseware.callOcMethod("orderToSeverSuccess", {});
      (<any>window).courseware.behaviorToCollectWithParam("levelPayForSuccess", product.name);
    })
  }

  async showActiveWindow() {
    if (this.IS_BUNDLE_LOADING) {
      return;
    }
    const tipsLayer = cc.find('middleLayer/activeLayer');
    tipsLayer.active = true;
  }

  // 立即显示激活弹窗
  showActiveWindowDirect() {
    const tipsLayer = cc.find('middleLayer/activeLayer');
    tipsLayer.active = true;
  }

  version = null;
  isDev = null;
  type = null;
  engine_uuid = null;
  async checkVersion() {
    const { forceUpdateVersionName: onlineVersion, forceUpdateStoreList, forceUpdate } = await this.getOnlineVersion();
    const nativeVersion = await this.getNativeVersion();
    this.version = nativeVersion;
    if (onlineVersion != '' && onlineVersion != nativeVersion && forceUpdate != 0 && this.type != 'aixuebao') {
      console.log('onlineVersion = ' + onlineVersion);
      console.log('nativeVersion = ' + nativeVersion);

      (<any>window).courseware.needUpdate('检测到更新', forceUpdateStoreList[0]);
    }
  }
  async getNativeVersion() {
    const engineInfo = await this.getEngineInfo();
    const { version, isDev, type, uuid, mac } = JSON.parse(engineInfo);
    this.version = version;
    this.isDev = isDev;
    this.type = type;
    this.engine_uuid = mac || uuid;
    return this.version;
  }

  async getOnlineVersion() {
    let platform = '';
    if (cc.sys.isNative && cc.sys.os == cc.sys.OS_IOS) {
      platform = 'ios';
    } else if (cc.sys.isNative && cc.sys.os == cc.sys.OS_ANDROID) {
      platform = 'android';
    } else if (cc.sys.isNative && cc.sys.os == cc.sys.OS_WINDOWS) {
      platform = 'windows';
    } else {
      platform = 'web';
    }

    const res: any = await this.asyncCallNetworkApiGet('/api/application/v1/checkVersion', {
      pkg_name: 'com.iplayabc.oxford.lite',
      platform: platform
    });
    return JSON.parse(res).data;
  }

  showButtons() {
    cc.find('middleLayer/ExitBtn').active = true;
    const BtnRight = cc.find('middleLayer/BtnRight');
    const BtnLeft = cc.find('middleLayer/BtnLeft');
    if (this.courses && this.courses.length > 1 && this.courseIndex < this.courses.length - 1) {
      BtnRight.active = true;
    } else {
      BtnRight.active = false;
    }
    if (this.courseIndex > 0) {
      BtnLeft.active = false;
    }
  }

  hideButtons() {
    cc.find('middleLayer/BtnRight').active = false;
    cc.find('middleLayer/BtnLeft').active = false;
    cc.find('middleLayer/ExitBtn').active = false;
  }

  showMask() {

  }

  hideMask() {

  }

  preloadAll(onProgress, onComplete) {
    let platform = "web_desktop";
    if (cc.sys.isNative && cc.sys.os == cc.sys.OS_IOS) {
      platform = "ios";
    }
    if (cc.sys.isNative && cc.sys.os == cc.sys.OS_ANDROID) {
      platform = "android";
    }
    this.callNetworkApiGet(`/api/syllabus/v1/allbundles`, { orgid: this.ORG_ID, platform }, (datastr) => {
      const data = JSON.parse(datastr);
      this.batchPreloadScene(data.rows, [], onProgress, onComplete);
      // this.callNetworkApiGet(`/api/syllabus/v1/allresources`, { orgid: this.ORG_ID }, (datastr1) => {
      //   const data1 = JSON.parse(datastr1);
      //   this.batchPreloadScene(data.rows);
      //   this.preloadSource(data1.rows);
      // });
    });
  }

  batchPreloadScene(scenes = [], expects = [], onProgress = null, onComplete = null) {
    let i = 0;
    const load = function () {
      const scene = scenes[i];
      if (expects.includes(scene.sceneName)) {
        i++;
        if (i < scenes.length) {
          setTimeout(() => {
            onProgress && onProgress(i, scenes.length);
            load();
          }, 1);
        } else {
          onComplete && onComplete();
        }
        return;
      }
      cc.assetManager.loadBundle(scene.bondleUrl, { version: scene.version }, (err, bundle) => {
        console.log(`${scene.bondleUrl}---场景开始loadBundle----`);
        if (!bundle) {
          i++;
          if (i < scenes.length) {
            setTimeout(() => {
              onProgress && onProgress(i, scenes.length);
              load();
            }, 1);
          } else {
            onComplete && onComplete();
          }
          return;
        }
        // 用于测试多个模板是否冲突
        bundle.preloadScene(scene.sceneName, () => { }, () => {
          console.log(`${scene.sceneName}场景预加载结束`);
          i++;
          if (i < scenes.length) {
            setTimeout(() => {
              onProgress && onProgress(i, scenes.length);
              load();
            }, 1);
          } else {
            onComplete && onComplete();
          }
        });
      });
    }

    if (scenes && scenes.length > 0) {
      load();
    }
  }

  preloadSource(array) {
    const rows = array || [];
    let tempArr = rows.filter(item => item.indexOf(".mp4")<0).map(item => {
      return {url: item};
    });
    cc.assetManager.preloadAny(tempArr, null, (finished, total)=> {}, null);
  }

  saveRecordResult(recordResult) {
    if (this.isLogin == false) {
      // 游客
      return false;
    }
    this.getUserBaseInfo().then(kidInfo => {
      if (!kidInfo) {
        return;
      }
      const result = JSON.parse(recordResult);
      const token = cc.sys.localStorage.getItem('token');
      this.callNetworkApiPost(`/api/oxford/v1/kid/record/save`, {
        token,
        kidid: kidInfo.id,
        syllabusid: this.courseItem.course_id,
        courseware_id: this.courseItem.id,
        record_url: result.audioUrl,
        test_result: recordResult
      }, () => { });
    });
  }

  getHeadUrl(idx) {
    const heads = [
      '',
      'http://staging-teach.cdn.ireadabc.com/602db3fc276acfb8b78906a536ea1e5b.png',
      'http://staging-teach.cdn.ireadabc.com/ed358b7ccddaf305da7bd34fca4f718f.png',
      'http://staging-teach.cdn.ireadabc.com/a27604179a27f3bab05608645526ad6f.png',
      'http://staging-teach.cdn.ireadabc.com/eade6940df285da454ff922fb6844545.png',
      'http://staging-teach.cdn.ireadabc.com/6e3ec753fccfcf0c990a7f24517251f3.png',
      'http://staging-teach.cdn.ireadabc.com/11fd64bc4af9d2c0694ef3ccd3248995.png',
      'http://staging-teach.cdn.ireadabc.com/e327f3cb690ed3648324abfaac7af75b.png',
      'http://staging-teach.cdn.ireadabc.com/7368e6d99fe63e068836a9f34f7394a1.png',
      'http://staging-teach.cdn.ireadabc.com/13920368baaa36c532aa20f6eeeff97f.png',
      'http://staging-teach.cdn.ireadabc.com/c278f370c13a5bf30ce46d82caf95b26.png',
      'http://staging-teach.cdn.ireadabc.com/d0aa997b42b43d43331d6dfa2fab4524.png',
      'http://staging-teach.cdn.ireadabc.com/9d59d9c0caa602014e2c2442c91ceb3d.png',
    ];
    return heads[idx];
  }

  async getUserInfo() {
    const token = cc.sys.localStorage.getItem('token');
    const kidDataStr = await this.asyncCallNetworkApiGet('/api/oxford/v1/kid/info', {
      token: token
    });
    const kidData = JSON.parse(kidDataStr);
    if (kidData.code == 200) {
      const kidInfo = kidData.data;
      this.activeLevels = kidInfo ? kidInfo.active_levels : [];
      return kidData.data;
    } else {
      this.loadOnlineBundle('NJ_login');
    }
  }

  kidInfo = null;
  async getUserBaseInfo() {
    if (this.kidInfo) {
      return this.kidInfo;
    }

    const token = cc.sys.localStorage.getItem('token');
    const kidDataStr = await this.asyncCallNetworkApiGet('/api/oxford/v1/kid/baseinfo', {
      token: token
    });
    const kidData = JSON.parse(kidDataStr);
    if (kidData.code == 200) {
      this.kidInfo = kidData.data;
      return kidData.data;
    } else {
      this.loadOnlineBundle('NJ_login');
      return null;
    }
  }

  async unlockNextForder() {
    const kidDataStr = await this.asyncCallNetworkApiGet('/api/oxford/v1/kid/info', {
      token: cc.sys.localStorage.getItem('token')
    });
    const kidData = JSON.parse(kidDataStr);
    if (!kidData.data || !kidData.data.id) {
      this.showTips("用户登录失效，请重新登录");
      this.loadOnlineBundle("NJ_login");
      return;
    }

    let syllabusid = this.getData('NJ_game_select').nextFolderId;
    if (syllabusid == -1) {
      syllabusid = this.getData('nextLevelId');
    }
    if (!syllabusid || syllabusid == -1) {
      return;
    }
    const kidid = kidData.data.id;
    await this.asyncCallNetworkApiPost('/api/oxford/v1/kid/unlock', {
      kidid,
      syllabusid,
      presyllabusname: this.getData('NJ_game_select').folderName,
      token: cc.sys.localStorage.getItem('token')
    });
  }

  async saveAnswer(data, callback = null) {
    if (this.isLogin == false) {
      // 游客
      return;
    }
    const token = cc.sys.localStorage.getItem('token');
    const kidInfo: any = await this.getUserBaseInfo();
    if (!kidInfo) {
      return;
    }
    const res = await this.asyncCallNetworkApiPost(`/api/oxford/courseware/v1/${this.courseItem.id}/saveanswer`, {
      token,
      type_id: this.getData("syllabus_path").type_id,
      level_id: this.getData("syllabus_path").level_id,
      folder_id: this.getData("syllabus_path").folder_id,
      syllabus_id: this.courseItem.course_id,
      courseware_id: this.courseItem.id,
      template_name: this.courseItem.template_name,
      parent_id: kidInfo.parent_id,
      kid_id: kidInfo.id,
      score: data ? data.score : 0,
      result: JSON.stringify(data),
      study_duration: Date.now() - this.courseOpenTimeStamp,
      is_folder_end: (this.courseIndex == this.courses.length - 1) ? 1 : 0
    });
    callback && callback(res);
  }

  async onHomeworkFinish(callBack, data = null, isSaveAnswer = true) {
    console.log("===onHomeworkFinish===", callBack, data, isSaveAnswer);
    if (typeof (callBack) == 'object') {
      data = callBack;
    }
    if (isSaveAnswer) {
      await this.saveAnswer(data);
    }
    if (this.courseIndex == this.courses.length - 1) {
      await this.pdtdFinishHandler();
    } else {
      // 如果不是最后一页，跳转到下一页
      // 数字版又要不自动跳页了
      // this.goNextPage();
    }
  }

  async pdtdFinishHandler() {
    if (!this.getData("syllabus_path") || this.getData("syllabus_path").type !== "pdtd") {
      // 不是拼读天地的学习内容
      return;
    }
    if (this.getData("syllabus_path").pdtd_type === 'more_games') {
      // 不是指读学习内容
      return;
    }
    await this.playGetParterAnim();

    if (this.isLogin == true && this.gameModel != 'free') {
      this.unlockNextForder();
    }
  }

  isLevelActived() {
    if (this.isLogin == false) {
      // 游客
      return false;
    }
    // 最上层判断Level是否被购买激活过
    const currentLevelId = this.data["syllabus_path"].level_id;
    const activeLevelIds = this.activeLevels.map(item => item.syllabus_id);
    return activeLevelIds.includes(currentLevelId);
  }

  async playGetParterAnim() {
    const coolcat = cc.find('middleLayer/coolcat');
    coolcat.active = true;

    // 胜利音效
    this.playLocalAudio("win").then();

    const star = cc.find('middleLayer/coolcat/star');
    star.active = true;
    star.getComponent(dragonBones.ArmatureDisplay).playAnimation('normal', 1);

    const animData = this.getData('NJ_game_select');
    if (animData && animData.folderCover) {
      cc.assetManager.loadRemote(animData.folderCover, async (err, res) => {
        const apple = cc.find('middleLayer/coolcat/apple');
        apple.active = true;
        apple.getComponent(cc.Sprite).spriteFrame = new cc.SpriteFrame(res);
        const sx = 200 / apple.width;
        const sy = 200 / apple.height;
        const sl = Math.min(sx, sy);
        apple.scale = sl;
        cc.tween(apple)
          .set({ scale: 0 })
          .to(0.5, { scale: sl }, { easing: 'backOut' })
          .to(0.1, { angle: 20 })
          .to(0.2, { angle: -20 })
          .to(0.1, { angle: 0 })
          .delay(1)
          .to(0.1, { angle: 20 })
          .to(0.2, { angle: -20 })
          .to(0.1, { angle: 0 })
          .delay(1)
          .to(0.1, { angle: 0 })
          .call(() => {
            this.hideGetParterAnim();
          })
          .start()
      })
    } else {
      setTimeout(() => {
        this.hideGetParterAnim();
      }, 1000);
    }
  }

  hideGetParterAnim() {
    const coolcat = cc.find('middleLayer/coolcat');
    coolcat.active = false;
    const apple = cc.find('middleLayer/coolcat/apple');
    apple.active = false;
    apple.setPosition(0, 0);
    const light = cc.find('middleLayer/coolcat/light');
    light.active = false;
    const star = cc.find('middleLayer/coolcat/star');
    star.active = false;
  }

  saveLastGameData(callback) {
    // 游客不保存
    if (this.isLogin == false) {
      callback && callback(true);
      return;
    }
    // 自由模式不保存
    if (this.gameModel == 'free') {
      callback && callback(true);
      return;
    }
    const token = cc.sys.localStorage.getItem('token');
    this.callNetworkApiGet('/api/oxford/v1/kid/info', { token }, (res) => {
      const kidData = JSON.parse(res);
      if (kidData.code == 200) {
        this.callNetworkApiPost(`/api/oxford/v1/kid/lastgame`, {
          token,
          kidid: kidData.data.id,
          syllabusid: this.courseItem.course_id,
          coursewareid: this.courseItem.id,
          lastgameinfo: this.data ? JSON.stringify(this.data) : ""
        }, (res1) => {
          if (res1.code == 200) {
            callback && callback(true);
          } else {
            this.showTips(`保存学习记录失败！[${res1.code}]`);
            callback(false);
          }
        });
      } else {
        this.showTips("用户信息过期，请重新登录！");
        this.IS_BUNDLE_LOADING = false;
        this.loadOnlineBundle('NJ_login');
        callback && callback(false);
      }
    });
  }

  // 重写loadOnlineBundle方法；主要是对一些必要的页面跳转做一些拦截处理
  loadOnlineBundle(bundleName, callback = null) {
    if (this.IS_BUNDLE_LOADING) {
      return;
    }
    this.IS_BUNDLE_LOADING = true;
    cc.find('middleLayer/BtnRight').active = false;
    cc.find('middleLayer/BtnLeft').active = false;
    cc.find('middleLayer/ExitBtn').active = false;
    if (bundleName == 'NJ_login') {
      // 如果跳到登录页，则清理一些缓存的使用数据
      this.data = {};
      this.kidInfo = null;
      this.isLogin = false;
      cc.sys.localStorage.setItem("token", "");
    }

    if (this.isLogin == false && ["NJ_MoTianLun", "NJ_YueDuJiaYouZhan", "NJ_usercenter"].includes(bundleName)) {
      this.IS_BUNDLE_LOADING = false;
      // 游客
      // 提示先登录后购买
      this.showConfirm("需要登录后才能使用，去登录吗？", ()=>{
        this.loadOnlineBundle('NJ_login');
      });
      return;
    }

    this.callNetworkApiGet(`/api/template/v2/${bundleName}`, {}, (datastr) => {
      const data = JSON.parse(datastr).data;
      let sceneName, version, bondleUrl = "";

      const templateBaseUrl = `${this.DOMAIN}h5template/${data.name}/v${data.last_version}`;
      this.getConfigInfo(templateBaseUrl, (conf) => {

        if (cc.sys.os == cc.sys.OS_IOS) {
          sceneName = conf.ios.sceneName;
          version = conf.ios.version;
          bondleUrl = `${templateBaseUrl}/ios/${conf.ios.sceneName}`;
        } else if (cc.sys.os == cc.sys.OS_ANDROID) {
          sceneName = conf.android.sceneName;
          version = conf.android.version;
          bondleUrl = `${templateBaseUrl}/android/${conf.android.sceneName}`;
        } else {
          sceneName = conf.android.sceneName;
          version = "";
          bondleUrl = `${templateBaseUrl}/web_desktop`;
        }
        this.loadBundle(sceneName, version, bondleUrl, () => {
          cc.find('middleLayer/ram').active = bundleName == 'NJ_YouLeChang';
          cc.find('middleLayer/cross').active = (bundleName == 'NJ_YouLeChang'&&this.gameModel=='cross');
          cc.find('middleLayer/free').active = (bundleName == 'NJ_YouLeChang'&&this.gameModel=='free');
          callback&&callback();
        });
      });
    });

  }

  // 重写loadPageBundle方法；主要是添加上报记录“上次学习位置”
  loadPageBundle(callback = null) {
    this.saveLastGameData((flag) => {
      if (!flag) {
        return;
      }

      let sceneName, version, bondleUrl = "";
      const templateBaseUrl = `${this.DOMAIN}h5template/${this.courseItem.template_name}/v${this.courseItem.last_version}`;
      this.getConfigInfo(templateBaseUrl, (conf) => {

        if (cc.sys.os == cc.sys.OS_IOS) {
          sceneName = conf.ios.sceneName;
          version = conf.ios.version;
          bondleUrl = `${templateBaseUrl}/ios/${conf.ios.sceneName}`;
        } else if (cc.sys.os == cc.sys.OS_ANDROID) {
          sceneName = conf.android.sceneName;
          version = conf.android.version;
          bondleUrl = `${templateBaseUrl}/android/${conf.ios.sceneName}`;
        } else {
          sceneName = conf.android.sceneName;
          version = "";
          bondleUrl = `${templateBaseUrl}/web_desktop`;
        }
        this.loadBundle(sceneName, version, bondleUrl, callback);
      });
    });

  }

  isShowWaiting = false;
  showWaitingIntervalId = null;
  showWaitingLetters() {
    if (this.isShowWaiting) {
      return;
    }
    this.isShowWaiting = true;

    const laodingLayer = cc.find('middleLayer/loadingLayer');
    laodingLayer.active = true;
    const loading = cc.find('middleLayer/loadingLayer/loading');

    const anim = loading.getComponent(cc.Animation)
    anim.play('loading')

    const script = cc.find('middleLayer/loadingLayer/progress').getComponent('progressScript');
    script.setProgress(0);

    const changeObj = { value: 0 };
    this.showWaitingIntervalId = setInterval(() => {
      script.setProgress(changeObj.value);
    }, 1);

    cc.tween(changeObj)
      .to(5, { value: 0.9 })
      .call(() => {
        clearInterval(this.showWaitingIntervalId);
      })
      .start();
  }

  hideWaitingLetters() {
    cc.find('middleLayer/loadingLayer').active = false;
    this.isShowWaiting = false;
    if (this.showWaitingIntervalId) {
      clearInterval(this.showWaitingIntervalId);
    }
  }

  data: any = {};
  setData(key: string, data: any) {
    const obj = this.data[key];
    if (typeof data == "object") {
      this.data[key] = { ...obj, ...data };
    } else {
      this.data[key] = data;
    }

    if (!this.data["syllabus_path"]) {
      this.data["syllabus_path"] = {};
    }
    // 拼读天地下的节点ID提取
    if (key === "NJ_menu") {
      this.data["syllabus_path"].type = "pdtd";
      this.data["syllabus_path"].type_id = data;
    }
    if (key === "NJ_QianShuiTing" || key === "NJ_ShaMo" || key === "NJ_NongChang" || key === "NJ_XueShan" || key === "NJ_TianKong") {
      this.data["syllabus_path"].level_id = data;
    }
    if (key === "NJ_game_select") {
      this.data["syllabus_path"].pdtd_type = 'game_select';
      this.data["syllabus_path"].folder_id = data.folderId;
    }
    if (key === "NJ_MoreGames") {
      this.data["syllabus_path"].pdtd_type = 'more_games';
      this.data["syllabus_path"].folder_id = data.folderId;
    }

    // 阅读加油站下的节点ID提取
    if (key === "NJ_YueDuJiaYouZhan") {
      this.data["syllabus_path"].type = "ydjyz";
      this.data["syllabus_path"].type_id = data;
    }
    if (key === "NJ_BookTable") {
      this.data["syllabus_path"].level_id = data.levelId;
      this.data["syllabus_path"].folder_id = data.folderId;
    }

    // 趣问趣答下的节点ID提取
    if (key === "NJ_MoTianLun") {
      this.data["syllabus_path"].type = "qwqd";
      this.data["syllabus_path"].type_id = data;
    }
    if (key === "NJ_MonkyTree") {
      this.data["syllabus_path"].level_id = data;
    }
    if (key === "NJ_MonkyTree_Son") {
      this.data["syllabus_path"].folder_id = data.folderId;
    }


  }

  getData(key: string) {
    return this.data[key];
  }

  reSetData(_data) {
    this.data = _data;
  }

  activeLevels = null;
  isLogin = false;
  async start() {
    this.node.zIndex = 9999;
    cc.game.addPersistRootNode(this.node);
    // await this.checkVersion();

    if (this.isDev == 1) {
      cc.find(`middleLayer/debug`).active = true;
    }

    cc.find('middleLayer/BtnRight').active = false;
    cc.find('middleLayer/BtnLeft').active = false;
    cc.find('middleLayer/ExitBtn').active = false;
    cc.find('middleLayer/ram').active = false; 
    cc.find('middleLayer/cross').active = false; 
    cc.find('middleLayer/free').active = false; 
 

    this.showWaitingLetters();
    this.onMiddleLayerLoadingFinish();
    const token = cc.sys.localStorage.getItem('token');
    const kidDataStr = await this.asyncCallNetworkApiGet('/api/oxford/v1/kid/info', {
      token: token
    });

    const kidData = JSON.parse(kidDataStr);
    if (kidData.code == 200) {
      const kidInfo = kidData.data;
      this.activeLevels = kidInfo ? kidInfo.active_levels : [];
      this.isLogin = true;
      this.loadOnlineBundle('NJ_YouLeChang');
    } else {
      // 游客功能
      this.isLogin = false;
      this.loadOnlineBundle('NJ_YouLeChang');
    }
    this.initListener();
    global.middleLayer = cc.find('middleLayer').getComponent('middleLayer');

  }

  onClickExitBtn() {
    const exit = () => {
      cc.find('middleLayer/BtnRight').active = false;
      cc.find('middleLayer/BtnLeft').active = false;

      const exitBtn = cc.find('middleLayer/ExitBtn');
      exitBtn.active = false;
      cc.audioEngine.stopAll();
      (<any>window).courseware.freeAllOcMethod();

      const syllabusPath = this.getData("syllabus_path");
      if (!syllabusPath) {
        this.loadOnlineBundle('NJ_YouLeChang');
        return;
      }

      if (syllabusPath.type === "pdtd") {
        if (syllabusPath.pdtd_type == 'game_select') {
          this.setData("NJ_game_select", {
            step: 0,
            currentPartIdx: 0
          });
          const idx = this.getData('NJ_menu_select_idx');
          if (idx == '0') {
            this.loadOnlineBundle('NJ_QianShuiTing');
          } else if (idx == '1') {
            this.loadOnlineBundle('NJ_ShaMo');
          } else if (idx == '2') {
            this.loadOnlineBundle('NJ_NongChang');
          } else if (idx == '3') {
            this.loadOnlineBundle('NJ_XueShan');
          } else if (idx == '4') {
            this.loadOnlineBundle('NJ_TianKong');
          }
        } else {
          this.loadOnlineBundle('NJ_MoreGames_CourseList');
        }
      } else if (syllabusPath.type === "ydjyz") {

        console.log('xxxx 5')

        if (this.courseItem.template_name == "NJ_BookTable") {
          console.log('xxxx 6')

          this.loadOnlineBundle('NJ_YueDuJiaYouZhan');
        } else {
          const bookTable = this.getData("NJ_BookTable");
          this.loadOnlineCourseWare(bookTable.courseId);
        }
      } else if (syllabusPath.type === "qwqd") {
        console.log('xxxx 8')

        this.loadOnlineBundle('NJ_MonkyTree');
      }
    }
    this.showConfirm("确定离开吗？", () => {
      exit();
    });
  }

  initIosActiveWinListener() {
    // IOS 激活窗口事件绑定
    const iosActiveWin = cc.find('middleLayer/iosActiveLayer');
    buttonOnClick(cc.find('close', iosActiveWin), () => {
      iosActiveWin.active = false;
    });

    buttonOnClick(cc.find('active_bg/input_book_code/active', iosActiveWin), async () => {
      const input = cc.find('active_bg/input_book_code/active_input', iosActiveWin).getComponent(cc.EditBox);
      const activeCode = input.textLabel.string;
      const kidInfo = await this.getUserInfo();
      if (!kidInfo) {
        return;
      }
      const res = await this.asyncCallNetworkApiPost(`/api/oxford/v1/user/bind`, {
        kid_id: kidInfo.id, book_code: activeCode, token: cc.sys.localStorage.getItem('token')
      });
      if (res && res.code == 200) {
        this.showTips(res.msg);
        iosActiveWin.active = false;
        input.textLabel.string = "";
        await this.getUserInfo();
        this.reloadBundle();
      } else {
        this.showTips(res.msg);
      }

    });
  
    buttonOnClick(cc.find('active_bg/buy1_5', iosActiveWin), () => {
      cc.find('active_bg/1_5_product', iosActiveWin).active = true;
      cc.find('active_bg/one_level_product', iosActiveWin).active = false;
      cc.find('active_bg/input_book_code', iosActiveWin).active = false;

      cc.find('active_bg/buy1_5/xb_active', iosActiveWin).active = true;
      cc.find('active_bg/buy_one/xb_active', iosActiveWin).active = false;
      cc.find('active_bg/buy_book_code/xb_active', iosActiveWin).active = false;

      // 限时特惠
      cc.find('active_bg/lto', iosActiveWin).active = true;
      // 已有激活码，快捷激活
      cc.find('active_bg/goActiveLink', iosActiveWin).active = true;
    });
    buttonOnClick(cc.find('active_bg/buy_one', iosActiveWin), () => {
      cc.find('active_bg/1_5_product', iosActiveWin).active = false;
      cc.find('active_bg/one_level_product', iosActiveWin).active = true;
      cc.find('active_bg/input_book_code', iosActiveWin).active = false;

      cc.find('active_bg/buy1_5/xb_active', iosActiveWin).active = false;
      cc.find('active_bg/buy_one/xb_active', iosActiveWin).active = true;
      cc.find('active_bg/buy_book_code/xb_active', iosActiveWin).active = false;

      // 限时特惠
      cc.find('active_bg/lto', iosActiveWin).active = true;
      // 已有激活码，快捷激活
      cc.find('active_bg/goActiveLink', iosActiveWin).active = true;
    });
    buttonOnClick(cc.find('active_bg/buy_book_code', iosActiveWin), () => {
      cc.find('active_bg/1_5_product', iosActiveWin).active = false;
      cc.find('active_bg/one_level_product', iosActiveWin).active = false;
      cc.find('active_bg/input_book_code', iosActiveWin).active = true;

      cc.find('active_bg/buy1_5/xb_active', iosActiveWin).active = false;
      cc.find('active_bg/buy_one/xb_active', iosActiveWin).active = false;
      cc.find('active_bg/buy_book_code/xb_active', iosActiveWin).active = true;

      // 限时特惠
      cc.find('active_bg/lto', iosActiveWin).active = false;
      // 已有激活码，快捷激活
      cc.find('active_bg/goActiveLink', iosActiveWin).active = false;
    });
    buttonOnClick(cc.find('active_bg/goActiveLink/linkLabel', iosActiveWin), () => {
      cc.find('active_bg/1_5_product', iosActiveWin).active = false;
      cc.find('active_bg/one_level_product', iosActiveWin).active = false;
      cc.find('active_bg/input_book_code', iosActiveWin).active = true;

      cc.find('active_bg/buy1_5/xb_active', iosActiveWin).active = false;
      cc.find('active_bg/buy_one/xb_active', iosActiveWin).active = false;
      cc.find('active_bg/buy_book_code/xb_active', iosActiveWin).active = true;

      // 限时特惠
      cc.find('active_bg/lto', iosActiveWin).active = false;
      // 已有激活码，快捷激活
      cc.find('active_bg/goActiveLink', iosActiveWin).active = false;
    });
  
    buttonOnClick(cc.find('active_bg/1_5_product/card/buy', iosActiveWin), (btn) => {
      this.buy(btn.product);
    });

    buttonOnClick(cc.find('active_bg/one_level_product/level1/buy', iosActiveWin), (btn) => {
      this.buy(btn.product);
    });
    buttonOnClick(cc.find('active_bg/one_level_product/level2/buy', iosActiveWin), (btn) => {
      this.buy(btn.product);
    });
    buttonOnClick(cc.find('active_bg/one_level_product/level3/buy', iosActiveWin), (btn) => {
      this.buy(btn.product);
    });
    buttonOnClick(cc.find('active_bg/one_level_product/level4/buy', iosActiveWin), (btn) => {
      this.buy(btn.product);
    });
    buttonOnClick(cc.find('active_bg/one_level_product/level5/buy', iosActiveWin), (btn) => {
      this.buy(btn.product);
    });
    
    buttonOnClick(cc.find('buy_status_win/active_btn', iosActiveWin), (btn) => {
      cc.find(`buy_status_win/buy_status_text`, iosActiveWin).getComponent(cc.Label).string = "";

      cc.find(`buy_status_win/buy_status_sub_text`, iosActiveWin).getComponent(cc.Label).string = "";
      cc.find(`buy_status_win/buy_result_text`, iosActiveWin).active = false;
      btn.active = false;

      cc.find(`buy_status_win`, iosActiveWin).active = false;
      cc.find(`buyloading`, iosActiveWin).active = false;
      iosActiveWin.active = false;

      this.loadOnlineBundle('NJ_YouLeChang');
    });
  }

  initAndroidActiveWinListener() {
    // 安卓激活窗口事件绑定
    const androidActiveWin = cc.find('middleLayer/androidActiveLayer');
    buttonOnClick(cc.find('close', androidActiveWin), () => {
      cc.find('buy_status_win/active_btn', androidActiveWin).active = false;
      cc.find(`buy_status_win`, androidActiveWin).active = false;
      androidActiveWin.active = false;
      this.loadOnlineBundle('NJ_YouLeChang');
    });

    buttonOnClick(cc.find('active_bg/input_book_code/active', androidActiveWin), async () => {
      const input = cc.find('active_bg/input_book_code/active_input', androidActiveWin).getComponent(cc.EditBox);
      const activeCode = input.textLabel.string;
      const kidInfo = await this.getUserInfo();
      if (!kidInfo) {
        return;
      }
      const res = await this.asyncCallNetworkApiPost(`/api/oxford/v1/user/bind`, {
        kid_id: kidInfo.id, book_code: activeCode, token: cc.sys.localStorage.getItem('token')
      });
      if (res && res.code == 200) {
        this.showTips(res.msg);
        androidActiveWin.active = false;
        input.textLabel.string = "";
        await this.getUserInfo();
        this.reloadBundle();
      } else {
        this.showTips(res.msg);
      }

    });
  
    buttonOnClick(cc.find('active_bg/buy1_5', androidActiveWin), () => {
      cc.find('active_bg/1_5_product', androidActiveWin).active = true;
      cc.find('active_bg/one_level_product', androidActiveWin).active = false;
      cc.find('active_bg/input_book_code', androidActiveWin).active = false;

      cc.find('active_bg/buy1_5/xb_active', androidActiveWin).active = true;
      cc.find('active_bg/buy_one/xb_active', androidActiveWin).active = false;
      cc.find('active_bg/buy_book_code/xb_active', androidActiveWin).active = false;

      // 限时特惠
      cc.find('active_bg/lto', androidActiveWin).active = true;
      // 已有激活码，快捷激活
      cc.find('active_bg/goActiveLink', androidActiveWin).active = true;
    });
    buttonOnClick(cc.find('active_bg/buy_one', androidActiveWin), () => {
      cc.find('active_bg/1_5_product', androidActiveWin).active = false;
      cc.find('active_bg/one_level_product', androidActiveWin).active = true;
      cc.find('active_bg/input_book_code', androidActiveWin).active = false;

      cc.find('active_bg/buy1_5/xb_active', androidActiveWin).active = false;
      cc.find('active_bg/buy_one/xb_active', androidActiveWin).active = true;
      cc.find('active_bg/buy_book_code/xb_active', androidActiveWin).active = false;

      // 限时特惠
      cc.find('active_bg/lto', androidActiveWin).active = true;
      // 已有激活码，快捷激活
      cc.find('active_bg/goActiveLink', androidActiveWin).active = true;
    });
    buttonOnClick(cc.find('active_bg/buy_book_code', androidActiveWin), () => {
      cc.find('active_bg/1_5_product', androidActiveWin).active = false;
      cc.find('active_bg/one_level_product', androidActiveWin).active = false;
      cc.find('active_bg/input_book_code', androidActiveWin).active = true;

      cc.find('active_bg/buy1_5/xb_active', androidActiveWin).active = false;
      cc.find('active_bg/buy_one/xb_active', androidActiveWin).active = false;
      cc.find('active_bg/buy_book_code/xb_active', androidActiveWin).active = true;

      // 限时特惠
      cc.find('active_bg/lto', androidActiveWin).active = false;
      // 已有激活码，快捷激活
      cc.find('active_bg/goActiveLink', androidActiveWin).active = false;
    });
    buttonOnClick(cc.find('active_bg/goActiveLink/linkLabel', androidActiveWin), () => {
      cc.find('active_bg/1_5_product', androidActiveWin).active = false;
      cc.find('active_bg/one_level_product', androidActiveWin).active = false;
      cc.find('active_bg/input_book_code', androidActiveWin).active = true;

      cc.find('active_bg/buy1_5/xb_active', androidActiveWin).active = false;
      cc.find('active_bg/buy_one/xb_active', androidActiveWin).active = false;
      cc.find('active_bg/buy_book_code/xb_active', androidActiveWin).active = true;

      // 限时特惠
      cc.find('active_bg/lto', androidActiveWin).active = false;
      // 已有激活码，快捷激活
      cc.find('active_bg/goActiveLink', androidActiveWin).active = false;
    });
  
    buttonOnClick(cc.find('active_bg/1_5_product/card/buy', androidActiveWin), (btn) => {
      this.wxBuy(btn.product);
    });

    buttonOnClick(cc.find('active_bg/one_level_product/level1/buy', androidActiveWin), (btn) => {
      this.wxBuy(btn.product);
    });
    buttonOnClick(cc.find('active_bg/one_level_product/level2/buy', androidActiveWin), (btn) => {
      this.wxBuy(btn.product);
    });
    buttonOnClick(cc.find('active_bg/one_level_product/level3/buy', androidActiveWin), (btn) => {
      this.wxBuy(btn.product);
    });
    buttonOnClick(cc.find('active_bg/one_level_product/level4/buy', androidActiveWin), (btn) => {
      this.wxBuy(btn.product);
    });
    buttonOnClick(cc.find('active_bg/one_level_product/level5/buy', androidActiveWin), (btn) => {
      this.wxBuy(btn.product);
    });
    
    buttonOnClick(cc.find('buy_status_win/active_btn', androidActiveWin), (btn) => {
      btn.active = false;
      cc.find(`buy_status_win`, androidActiveWin).active = false;
      androidActiveWin.active = false;
      this.loadOnlineBundle('NJ_YouLeChang');
    });
  }

  initListener() {
    const exitBtn = cc.find('middleLayer/ExitBtn');
    buttonOnClick(exitBtn, () => {
      this.onClickExitBtn();
    });
    buttonOnClick(cc.find('middleLayer/BtnRight'), () => {
      if (this.courseIndex === this.courses.length - 1) {
        // 说明是最后一页
        this.showTips("已经是最后一页了~");
        return;
      }
      // this.showConfirm("确定跳过吗？", () => {
      if (!this.isShowWaiting) {
        this.goNextPage();
      }
      // });
    });
    buttonOnClick(cc.find('middleLayer/BtnLeft'), () => {
      this.goPrePage();
    });

    buttonOnClick(cc.find('middleLayer/downloadSourceLayer/close'), () => {
      cc.find('middleLayer/downloadSourceLayer').active = false;
      cc.find('middleLayer/downloadSourceLayer/loading').getComponent(cc.Animation).stop("loading");
      cc.find('middleLayer/downloadSourceLayer/progress/desc').getComponent(cc.Label).string = `0 / 0`;
      cc.find('middleLayer/downloadSourceLayer/progress/bar').width = 0;
      cc.find('middleLayer/downloadSourceLayer/per').getComponent(cc.Label).string = `0%`;
    });

    buttonOnClick(cc.find('middleLayer/ram'), () => {
      this.showConfirm(`
      确认下载全部课程内容吗？
下载时需要您等待一段时间，但可以增加查看流畅度
      `, ()=>{
        const laodingLayer = cc.find('middleLayer/downloadSourceLayer');
        laodingLayer.active = true;
        const loading = cc.find('middleLayer/downloadSourceLayer/loading');
        const anim = loading.getComponent(cc.Animation)
        anim.play('loading');
        cc.find('middleLayer/downloadSourceLayer/progress/bar').width = 0;

        this.preloadAll((finished, total) => {
          const percent = Math.floor(finished/total*100);
          cc.find('middleLayer/downloadSourceLayer/progress/desc').getComponent(cc.Label).string = `${finished} / ${total}`;
          cc.find('middleLayer/downloadSourceLayer/progress/bar').width = Math.floor(490 * percent / 100);
          cc.find('middleLayer/downloadSourceLayer/per').getComponent(cc.Label).string = `${percent}%`;
        }, () => {
          laodingLayer.active = false;
          anim.stop('loading');
          cc.find('middleLayer/downloadSourceLayer/progress/desc').getComponent(cc.Label).string = `0 / 0`;
          cc.find('middleLayer/downloadSourceLayer/progress/bar').width = 0;
          cc.find('middleLayer/downloadSourceLayer/per').getComponent(cc.Label).string = `0%`;
          this.showTips(`课程内容已全部下载完成`);
        });
      }, ()=>{});
    });

    buttonOnClick(cc.find('middleLayer/cross'), () => {
      this.showConfirm(`确定要切换为自由模式吗？`, ()=>{
        this.gameModel = "free";
        cc.sys.localStorage.setItem('gameModel', "free");
        cc.find('middleLayer/cross').active = false;
        cc.find('middleLayer/free').active = true;
        this.showTips(`已切换为自由模式`);
      }, ()=>{});
    });
    buttonOnClick(cc.find('middleLayer/free'), () => {
      this.showConfirm(`确定要切换为闯关模式吗？`, ()=>{
        this.gameModel = "cross";
        cc.sys.localStorage.setItem('gameModel', "cross");
        cc.find('middleLayer/cross').active = true;
        cc.find('middleLayer/free').active = false;
        this.showTips(`已切换为闯关模式`);
      }, ()=>{});
    });

    buttonOnClick(cc.find('middleLayer/activeLayer/close'), () => {
      cc.find('middleLayer/activeLayer').active = false;
    });

    buttonOnClick(cc.find('middleLayer/activeLayer/active_bg/active'), async () => {
      const input = cc.find('middleLayer/activeLayer/active_bg/active_input').getComponent(cc.EditBox);
      const activeCode = input.textLabel.string;
      const kidInfo = await this.getUserInfo();
      if (!kidInfo) {
        return;
      }
      const res = await this.asyncCallNetworkApiPost(`/api/oxford/v1/user/bind`, {
        kid_id: kidInfo.id, book_code: activeCode, token: cc.sys.localStorage.getItem('token')
      });
      if (res && res.code == 200) {
        this.showTips(res.msg);
        cc.find('middleLayer/activeLayer').active = false;
        input.textLabel.string = "";
        await this.getUserInfo();
        this.reloadBundle();
      } else {
        this.showTips(res.msg);
      }

    });

    this.initIosActiveWinListener();

    this.initAndroidActiveWinListener();
    

    buttonOnClick(cc.find(`middleLayer/exception_pay_win/active_btn`), (btn) => {
      cc.find(`middleLayer/exception_pay_win`).active = false;
      cc.find(`middleLayer/exception_pay_win/buy_status_text`).getComponent(cc.Label).string = "正在处理支付订单\n请勿关闭App";
      btn.active = false;
      this.loadOnlineBundle('NJ_YouLeChang');
    });


  };

  playLocalAudio(audioName) {
    const audio = cc.find(`middleLayer/audio/${audioName}`).getComponent(cc.AudioSource);
    return new Promise((resolve, reject) => {
      const id = cc.audioEngine.playEffect(audio.clip, false);
      cc.audioEngine.setFinishCallback(id, () => {
        resolve(id);
      });
    })
  };

  sendLogFlag = false;
  reportErrorLog() {
    if (!cc.sys.isNative) {
      return;
    }
    window["__errorHandler"] = (file: any, line: any, error: any) => {
      console.error("errorHandler:", file, line, error);
      if (this.sendLogFlag) {
        return;
      }
      this.sendLogFlag = true;
      this.callNetworkApiPost('/api/dashboard/v1/oxfordlite/client/runlog', {
        log_type: "error", file, line, error
      }, () => {
        setTimeout(() => {
          this.sendLogFlag = false;
        }, 500);
      })
    }
  }

  role = 'student';
  gameModel; // free: 自由模式；cross: 闯关模式；
  protected onLoad(): void {
    this.gameModel = cc.sys.localStorage.getItem('gameModel') || 'cross';
    initAir(this);
    this.reWriteAir();
    this.reportErrorLog();
  }
}
