import { initAir } from "./air";
import { middleLayerBase } from "./middleLayerBase";
import { asyncDelay, asyncLoadDragonBoneAnime, buttonOnceClick, buttonOnClick } 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 = JSON.parse(this.courseItem.data);
        this.log("===成功调用getData===" + this.courseItem.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.hideWaitingLetters();
          this.hideMask();
        });
      } else {
        this.hideWaitingLetters();
        this.hideMask();
      }
    }
  }

  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;
    });
  }
  async showActiveWindow() {
    if (this.IS_BUNDLE_LOADING) {
			return;
		}
    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',
      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() {

  }

  saveRecordResult(recordResult) {
    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) {
      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) {
    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!=='game_select') {
      // 不是指读学习内容
      return;
    }
    const isLastPart = await this.isLastPart();
    if (isLastPart) {
      await this.playGetParterAnim();
      this.unlockNextForder();
      return;
    }
    const gameSelectData = this.getData('NJ_game_select');
    const pageFirstIdx = gameSelectData.pageIdxMap.findIndex(num => num == gameSelectData.currentPageIdx);
    if (gameSelectData.pageIdxMap[pageFirstIdx + gameSelectData.currentPartIdx + 1] == gameSelectData.currentPageIdx) {
      console.log('if');
      this.setData('NJ_game_select', {
        folderId: gameSelectData.folderId,
        currentPartIdx: gameSelectData.currentPartIdx + 1
      });
    } else {
      console.log('else');
      this.setData('NJ_game_select', {
        folderId: gameSelectData.folderId,
        step: 0,
        currentPageIdx: gameSelectData.currentPageIdx + 1,
        currentPartIdx: 0
      });
    }
    this.loadOnlineCourseWare(gameSelectData.courseId);
  }

  async isLastPart() {
    const gameSelectData = this.getData('NJ_game_select');
    const pageFirstIdx = gameSelectData.pageIdxMap.findIndex(num => num == gameSelectData.currentPageIdx);
    if (pageFirstIdx + gameSelectData.currentPartIdx == gameSelectData.partLength - 1) {
      return true;
    }
    return false;
  }

  async playGetParterAnim() {
    const animData = this.getData('NJ_game_select: partnerData');
    // const animData = {
    //   havePic: "http://staging-teach.cdn.ireadabc.com/7a23e43f8ec4964e3feb9709ec553fd4.png",
    //   skeJsonData: {
    //     url: "http://staging-teach.cdn.ireadabc.com/5069b9316d9b69705281752f03b47901.json",
    //     name: "mao_ske.json"
    //   },
    //   texJsonData: {
    //     url: "http://staging-teach.cdn.ireadabc.com/3bbb72fd8ad3c02aa1df8d3785f4b34f.json",
    //     name: "mao_tex.json"
    //   },
    //   texPngData: {
    //     url: "http://staging-teach.cdn.ireadabc.com/c130de476dac5e9bbd71f92b2711d3ba.png",
    //     name: "mao_tex.png"
    //   },
    // }
    cc.assetManager.preloadAny({ url: animData.havePic });
    const coolcat = cc.find('middleLayer/coolcat');
    await asyncLoadDragonBoneAnime(coolcat, animData);
    const animaNode = coolcat['animaNode'];
    animaNode.scale = 0.6;
    animaNode.getComponent(dragonBones.ArmatureDisplay).playAnimation('normal', -1);
    const widget: cc.Widget = animaNode.addComponent(cc.Widget);
    widget.isAlignBottom = true;
    widget.isAlignRight = true;
    widget.right = 750;
    widget.bottom = 510;
    coolcat.active = true;

    const light = cc.find('middleLayer/coolcat/light');
    light.active = true;
    light.stopAllActions();
    const lightTween = cc.tween(light)
      .set({ opacity: 0 })
      .by(1, { opacity: 255, angle: 60 })
      .repeatForever()
      .start();

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

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

    cc.assetManager.loadRemote(animData.havePic, async (err, res) => {
      const apple = cc.find('middleLayer/coolcat/apple');
      apple.active = true;
      apple.getComponent(cc.Sprite).spriteFrame = new cc.SpriteFrame(res);
      cc.tween(apple)
        .set({ scale: 0 })
        .to(0.5, { scale: 1 }, { easing: 'backOut' })
        .to(0.1, { angle: 20 })
        .to(0.2, { angle: -20 })
        .to(0.1, { angle: 0 })
        .call(() => {
          lightTween.stop();
          cc.tween(light)
            .to(0.2, { opacity: 0 })
            .start();
        })
        .delay(0.2)
        .to(1, { x: 280, y: -270, scale: 0.3 }, { easing: 'quadInOut' })
        .to(0.1, { angle: 20 })
        .to(0.2, { angle: -20 })
        .to(0.1, { angle: 0 })
        .call(() => {
          const gameSelectData = this.getData('NJ_game_select');
          this.showConfirm('还想再来一次吗？', () => {
            // 识别页
            this.hideGetParterAnim();

            this.setData('NJ_game_select', {
              folderId: gameSelectData.folderId,
              step: 0,
              currentPageIdx: 0,
              currentPartIdx: 0
            });

            this.loadOnlineCourseWare(gameSelectData.courseId);

          }, () => {
            // 潜水艇页
            this.hideGetParterAnim();
            cc.find('middleLayer/BtnRight').active = false;
            cc.find('middleLayer/BtnLeft').active = false;
            cc.find('middleLayer/ExitBtn').active = false;

            this.setData("NJ_game_select", {
              folderId: gameSelectData.folderId,
              step: 0,
              currentPageIdx: 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');
            }
          });
        })
        .start();
    });
  }

  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) {
    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;
    console.log(" in loadOnlineBundle")
    cc.find('middleLayer/BtnRight').active = false;
    cc.find('middleLayer/BtnLeft').active = false;
    cc.find('middleLayer/ExitBtn').active = false;
    cc.find('middleLayer/showtime').active = (bundleName == 'NJ_YouLeChang');

    if (bundleName == 'NJ_login') {
      // 如果跳到登录页，则清理一些缓存的使用数据
      this.data = {};
      cc.sys.localStorage.setItem("token", "");
    }

    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, 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") {
      if (key === "NJ_game_select" && this.data[key] && this.data[key].folderId != data.folderId) {
        this.data[key] = data;
      } else {
        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;
  }

  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;

		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) {
      this.loadOnlineBundle('NJ_YouLeChang');
    } else {
      this.loadOnlineBundle('NJ_login');
    }
    this.initListener();
  }

  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') {
          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") {
        if (this.courseItem.template_name == "NJ_BookTable") {
          this.loadOnlineBundle('NJ_YueDuJiaYouZhan');
        } else {
          const bookTable = this.getData("NJ_BookTable");
          this.loadOnlineCourseWare(bookTable.courseId);
        }
      } else if (syllabusPath.type === "qwqd") {
        this.loadOnlineBundle('NJ_MonkyTree');
      }
    }
    if (this.courseItem &&
      (this.courseItem.template_name == "NJ_game_select" || this.courseItem.template_name == "NJ_BookTable")
    ) {
      // 如果是纸书索引页面则直接返回
      exit();
    } else {
      this.showConfirm("确定离开吗？", () => {
        exit();
      });
    }
  }

  initListener() {
    buttonOnClick(cc.find('middleLayer/showtime'), () => {
      this.loadOnlineCourseWare(54603);
    });
    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/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 = "";
        this.reloadBundle();
      } else {
        this.showTips(res.msg);
      }

    });
  };

  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/oxford/client/runlog', {
        log_type: "error", file, line, error
      }, () => {
        setTimeout(() => {
          this.sendLogFlag = false;
        }, 500);
      })
    }
  }

  role = 'student';
  protected onLoad(): void {
    initAir(this);
    this.reWriteAir();
    this.reportErrorLog();
  }
}
