import { middleLayerBase } from "./middleLayerBase";
import { initAir } from './air';
import { playAudioByUrl } from './util';


const { ccclass, property } = cc._decorator;

@ccclass
export default class NewClass extends middleLayerBase {
  callNetworkApiGetLocal(baseUrl, uri, data, callBack) {
    let queryStr = '?';
    const params = [];
    for (const key in data) {
      if (Object.hasOwnProperty.call(data, key)) {
        params.push(`${key}=${data[key]}`);
      }
    }
    queryStr += params.join("&");
    const xhr = new XMLHttpRequest();
    xhr.onreadystatechange = () => {
      if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status < 400)) {
        callBack(xhr.responseText);
      }
    };
    const url = `${baseUrl}${uri}${queryStr}`;
    console.log('url = ' + url);
    xhr.open('GET', url, true);
    xhr.setRequestHeader('Access-Control-Request-Private-Network', 'true');
    xhr.send();
  }

  // 需要预加载的数量
  preloadCount = null;
  // 统计已加载的数量
  loadedCount = null;

  role;



  

  // 统一释放异步资源的方法
  onLoad() {
    this.preloadCount = 0;
    this.loadedCount = 0;
    const uiNode = cc.find('middleLayer/ui');
    uiNode.parent.getComponent(cc.Widget).updateAlignment();
    const scale = Math.min(
      uiNode.parent.width / uiNode.width,
      uiNode.parent.height / uiNode.height,
    )
    uiNode.scale = scale;
    initAir(this);
    this.reWriteAir();
    // this.preloadAll();

    const engineInfo = cc.sys.localStorage.getItem('engine_info');
    if (engineInfo) {
      (<any>window).air.engineInfo = engineInfo;
      const engineObj = JSON.parse(engineInfo);
      if (engineObj.isDev == 1) {
        cc.find(`middleLayer/ui/BtnChangeEnv/Background/Label`).getComponent(cc.Label).string = `切换到正式`;
      } else {
        cc.find(`middleLayer/ui/BtnChangeEnv/Background/Label`).getComponent(cc.Label).string = `切换到测试`;
      }
    }

    this.role = 'student'; // 上古遗留问题

    try {
      // 有些壳上没有提供这个方法，所以处理一下异常
      this.onMiddleLayerLoadingFinish(); // 这个是用来隐藏原生端启动页的方法，酌情在适当的地方调用
    } catch (error) {}
  }

  start() {
    this.node.zIndex = 9999;
    cc.game.addPersistRootNode(this.node);
    this.initListener();

    const addressText = cc.find('middleLayer/ui/address');
    const str = cc.sys.localStorage.getItem('ip');
    console.log('str = ' + str);
    if (str) {
      addressText.getComponent(cc.EditBox).string = str;
    }

    const nameText = cc.find('middleLayer/ui/bundleName');
    const bundleName = cc.sys.localStorage.getItem('bundleName');
    if (bundleName) {
      nameText.getComponent(cc.EditBox).string = bundleName;
    }

    const courseIdNode = cc.find('middleLayer/ui/courseId');
    const courseId = cc.sys.localStorage.getItem('courseId');
    if (courseId) {
      courseIdNode.getComponent(cc.EditBox).string = courseId;
    }

    const courseIndexNode = cc.find('middleLayer/ui/courseIndex');
    const courseIndex = cc.sys.localStorage.getItem('courseIndex');
    if (courseIndex) {
      courseIndexNode.getComponent(cc.EditBox).string = courseIndex;
    }

    global.middleLayer = cc.find('middleLayer').getComponent('middleLayer');
    global.middleLayer.log("middleLayer.log('像这样在这里打log')");
  }

  preloadAll() {
    cc.find("middleLayer/ui/ProgressLabel").active = true;
    cc.find('middleLayer/ui/loadingProgress').active = true;
    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: 512, platform }, (datastr) => {
      const data = JSON.parse(datastr);
      if (data.rows && data.rows.length > 0) {
        this.preloadCount += data.rows.length;
      }
      this.callNetworkApiGet(`/api/syllabus/v1/allresources`, { orgid: 512 }, (datastr1) => {
        const data1 = JSON.parse(datastr1);
        if (data1.rows && data1.rows.length > 0) {
          this.preloadCount += data1.rows.length;
        }
        console.log('data.rows = ' + JSON.stringify(data.rows));
        this.batchPreloadScene(data.rows);
        this.preloadSource(data1.rows);
      });
    });
  }

  preloadSourceImman() {
    // 测试用
    cc.find("middleLayer/ui/ProgressLabel").active = true;
    cc.find('middleLayer/ui/loadingProgress').active = true;
    this.callNetworkApiGet(`/api/courseware/v1/getresources`, { courseid: 20894 }, (datastr1) => {
      const data1 = JSON.parse(datastr1);
      if (data1.rows && data1.rows.length > 0) {
        this.preloadCount += data1.rows.length;
      }
      this.log('data1.rows = ' + JSON.stringify(data1.rows));
      this.preloadSource(data1.rows);
    });
  }

  preloadOxfordScene() {
    // 测试用
    cc.find("middleLayer/ui/ProgressLabel").active = true;
    cc.find('middleLayer/ui/loadingProgress').active = true;
    this.callNetworkApiGet(`/api/syllabus/v1/allbundles`, { orgid: 512, platform: "web_desktop" }, (datastr) => {
      const data = JSON.parse(datastr);
      if (data.rows && data.rows.length > 0) {
        this.preloadCount += data.rows.length;
      }
      this.log('data.rows = ' + JSON.stringify(data.rows));
      // const arr = data.rows.filter(item => item.sceneName ==='l2_boardgame2_tree');
      // const arr1 = data.rows.filter(item => item.sceneName ==='BoardGame2');
      // const resArr = [...arr, ...arr1];
      this.batchPreloadScene(data.rows);
    });
  }

  batchPreloadScene(scenes = [], expects = []) {
    const _this = this;
    let i = 0;
    const load = function () {
      const scene = scenes[i];
      if (expects.includes(scene.sceneName)) {
        _this.loadedCount++;
        _this.updateProcessBar();
        i++;
        if (i < scenes.length) {
          setTimeout(() => {
            load();
          }, 1);
        }
        return;
      }
      cc.assetManager.loadBundle(scene.bondleUrl, { version: scene.version }, (err, bundle) => {
        console.log(`${scene.bondleUrl}---场景开始loadBundle----`);
        if (!bundle) {
          _this.loadedCount++;
          _this.updateProcessBar();
          i++;
          if (i < scenes.length) {
            setTimeout(() => {
              load();
            }, 1);
          }
          return;
        }

        // 用于测试多个模板是否冲突
        // bundle.preloadScene(scene.sceneName, () => { }, () => {
        //   console.log(`${scene.sceneName}场景预加载结束`);
        //   _this.loadedCount++;
        //   _this.updateProcessBar();
        //   i++;
        //   if (i < scenes.length) {
        //     setTimeout(() => {
        //       load();
        //     }, 1);
        //   }
        // });
      });
    }

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

  preloadSource(array) {
    const rows = array || [];
    let tempArr = rows.map(item => {
      return {url: item};
    });

    const label = cc.find("middleLayer/ui/ProgressLabel").getComponent(cc.Label);
    const loadingProgress = cc.find('middleLayer/ui/loadingProgress');
    cc.assetManager.preloadAny(tempArr, null, (finished, total)=>{
      label.string = `正在加载：${finished} / ${total}`;
      loadingProgress.getComponent(cc.ProgressBar).progress = finished / total;
    }, (err) => {
      if (err) {
        console.log(err)
      }
      cc.find("middleLayer/ui/ProgressLabel").active = false;
      loadingProgress.active = false;
      this.showLog("资源全部加载完成");
    });
  }

  async getUserInfo() {
    return {
      avatar_url: null,
      nick_name: null
    }
  }

  updateProcessBar() {
    const label = cc.find("middleLayer/ui/ProgressLabel").getComponent(cc.Label);
    const loadingProgress = cc.find('middleLayer/ui/loadingProgress');
    label.string = `正在加载：${this.loadedCount} / ${this.preloadCount}`;
    if (this.loadedCount > this.preloadCount * 0.99) {
      cc.find("middleLayer/ui/ProgressLabel").active = false;
      loadingProgress.active = false;
      this.showLog("资源全部加载完成");
    }
    loadingProgress.getComponent(cc.ProgressBar).progress = this.loadedCount / this.preloadCount;
  }

  onHomeworkFinish(callBack, data = null) {
    console.log('this.courseIndex = ' + JSON.stringify(this.currentBundleInfo));
    if (this.currentBundleInfo.sceneName == 'ls_fly') {
      const rightCount = data.reduce((preValue, right) => {
        if (right) {
          return preValue + 1;
        } else {
          return preValue;
        }
      }, 0);
      console.log('rightCount = ' + rightCount);
    }
    this.showRestartBtn();
    console.log('onHomeworkFinish: ' + JSON.stringify(data));
  }

  showRestartBtn() {
    const btnRestart = cc.find('middleLayer/BtnRestart');
    btnRestart.active = true;
    btnRestart.once('click', () => {
      btnRestart.active = false;
      this.loadPageBundle();
    });
  }

  callMiddleLayerFunction(apiName, data, callback) {
    switch (apiName) {
      case 'NS_login':
        if (data.userName == 'admin' && data.password == '123456') {
          this.showLog('登录成功！');
          callback('登录成功！');
        } else {
          this.showLog('密码错误！');
          callback('密码错误！');
        }
        break;
      case 'NS_logout':
        this.showLog('登出成功！');
        callback('登出成功！');
        break;
      case 'NS_select_book':
        if (data.bookId == 10001) {
          this.showLog('选择剧本: ' + data.bookId);
          callback('选择剧本: ' + data.bookId);
        } else {
          this.showLog('剧本未解锁！');
          callback('剧本未解锁！');
        }
        break;
      case 'NS_select_stage':
        if (data.stageId == 10011) {
          this.showLog('选择关卡: ' + data.stageId);
          callback('选择关卡: ' + data.stageId);
        } else {
          this.showLog('关卡未解锁！');
          callback('关卡未解锁！');
        }
        break;
      case 'NS_select_event':
        this.showLog('选择活动：' + data.eventId);
        callback('选择活动：' + data.eventId);
        break;
      case 'NS_select_game':
        this.showLog('选择游戏: ' + data.gameId);
        callback('选择游戏: ' + data.gameId);
        break;
      case 'PSQS_get_pass_code':
        this.showLog('获取验证码: ' + data.phone);
        callback({ success: true });
        break;
      case 'PSQS_login':
        this.showLog(`登录/注册: ${data.phone} ${data.code}`);
        callback({
          success: true,
          userInfo: { // userInfo为空时弹出填写用户信息的页面
            phone: 13812345678,
            nickName: "小豆梓",
            sex: "girl",
            provice: "辽宁省",
            city: "大连市",
            age: '5~8岁',
            grade: '一年级'
          },
          bookInfo: [{
            name: "kind_A",
            selected: true,
            bookList: [{
              id: 12334,
              coverImg: "http://staging-teach.cdn.ireadabc.com/0d332cb2b167feb4204b1d77a6f02ed6.jpg",
              duration: "21:33",
              rate: "55%",
              createDate: "2012-12-21"
            }, {
              id: 12231,
              coverImg: "http://staging-teach.cdn.ireadabc.com/0d332cb2b167feb4204b1d77a6f02ed6.jpg",
              duration: "21:33",
              readTime: 2,
              createDate: "2012-12-21"
            }],
          }, {
            name: "kind_B",
            bookList: [{
              id: 12235,
              coverImg: "http://staging-teach.cdn.ireadabc.com/0d332cb2b167feb4204b1d77a6f02ed6.jpg",
              duration: "21:33",
              readTime: 1,
              createDate: "2012-12-21"
            }],
          }]
        });
        break;
      case 'PSQS_set_user_info':
        this.showLog(`设置用户信息: ${JSON.stringify(data)}`);
        callback({ success: true });
        break;
      case 'PSQS_scan_code':
        this.showLog(`扫码`);
        callback({
          success: true,
          bookInfo: [{
            name: "kind_A",
            selected: true,
            bookList: [{
              id: 12334,
              coverImg: "http://staging-teach.cdn.ireadabc.com/0d332cb2b167feb4204b1d77a6f02ed6.jpg",
              duration: "21:33",
              rate: "0%",
              createDate: "2012-12-21"
            }],
          }, {
            name: "kind_B",
            bookList: [],
          }]
        });
        break;
      case 'PSQS_read_book':
        this.showLog('进入课件: ' + data.bookId);
        callback({ success: true });
        break;
      case 'PSQS_get_basic_info':
        this.showLog('获取基本信息');
        callback({
          version: 'bata 0.9.7',
          privacyPolicyUrl: 'http://www.baidu.com',
          userAgreement: 'http://www.baidu.com',
        });
        break;
      case 'PSQS_play_animate_over':
        break;
      case 'PSQS_jump_to_question':
        break;
      case 'PSQS_get_course_info':
        this.showLog('获取播放骨骼动画模板的信息');
        const returnData = {
          first: false, // 是不是第一个模板
          last: false, // 是不是最后一个模板
          playTime: 0, // 播放了几次 0：不需要跳题 1：需要跳题
          saveData: {}
        }
        callback(returnData);
        break;
      case 'PSQS_show_rabbit':
        break;
      case 'PSQS_hide_rabbit':
        break;
      case 'PSQS_logout':
        callback({ success: true });
        break;
      case 'PSQS_get_province':
        callback(['北京', '上海']);
        break;
      case 'PSQS_get_city':
        callback(['北京市']);
        break;
      case 'PSQS_check_login':
        callback({
          success: true,
          userInfo: { // userInfo为空时弹出填写用户信息的页面
            phone: 13812345678,
            nickName: "小豆梓",
            sex: "girl",
            provice: "辽宁省",
            city: "大连市",
            age: '5~8岁',
            grade: '一年级'
          },
          bookInfo: [{
            name: "kind_A",
            bookList: [{
              id: 12334,
              coverImg: "http://staging-teach.cdn.ireadabc.com/0d332cb2b167feb4204b1d77a6f02ed6.jpg",
              duration: "21:33",
              rate: "55%",
              createDate: "2012-12-21"
            }, {
              id: 12231,
              coverImg: "http://staging-teach.cdn.ireadabc.com/0d332cb2b167feb4204b1d77a6f02ed6.jpg",
              duration: "21:33",
              readTime: 2,
              createDate: "2012-12-21"
            }],
          }, {
            name: "kind_B",
            selected: true,
            bookList: [{
              id: 12235,
              coverImg: "http://staging-teach.cdn.ireadabc.com/0d332cb2b167feb4204b1d77a6f02ed6.jpg",
              duration: "21:33",
              readTime: 1,
              createDate: "2012-12-21"
            }],
          }]
        });
        break;
      default:
        this.showLog('未定义接口: ' + apiName);
        break;
    }
  }

  localMode = false;

  asyncDelayLog(str) {
    console.log(str);
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve(null);
      }, 1);
    });
  }


  covertUrl = null;
  initListener() {

    const exitBtn = cc.find('middleLayer/ExitBtn');
    exitBtn.on('click', () => {
      cc.find('middleLayer/BtnRight').active = false;
      cc.find('middleLayer/BtnLeft').active = false;

      cc.tween(exitBtn)
        .to(0.1, { scaleX: 0.4, scaleY: 0.6 })
        .to(0.1, { scaleX: 0.6, scaleY: 0.4 })
        .to(0.1, { scaleX: 0.5, scaleY: 0.5 })
        .call(() => {
          exitBtn.active = false;
          cc.game.removePersistRootNode(this.node);
          // cc.director.getScene().destroy();
          cc.audioEngine.stopAll();
          (<any>window).courseware.freeAllOcMethod();
          const flag = cc.director.loadScene("debug_shell", (err, scene) => {
          });
          if (!flag) {
            // 没有壳的情况下，直接加载中间层场景
            cc.director.loadScene("middleLayer_for_debug", (err, scene) => {
            });
          }
        })
        .start();
    });

    cc.find('middleLayer/BtnRight').on('click', () => {
      this.goNextPage();
      if (this.courseIndex == 0) {
        cc.find('middleLayer/BtnLeft').active = false;
      } else {
        cc.find('middleLayer/BtnLeft').active = false;
      }
      if (this.courseIndex == this.courses.length - 1) {
        cc.find('middleLayer/BtnRight').active = false;
      } else {
        cc.find('middleLayer/BtnRight').active = true;
      }
    });

    cc.find('middleLayer/BtnLeft').on('click', () => {
      this.goPrePage();
      if (this.courseIndex == 0) {
        cc.find('middleLayer/BtnLeft').active = false;
      } else {
        cc.find('middleLayer/BtnLeft').active = false;
      }
      if (this.courseIndex == this.courses.length - 1) {
        cc.find('middleLayer/BtnRight').active = false;
      } else {
        cc.find('middleLayer/BtnRight').active = true;
      }
    });

    cc.find('middleLayer/ui/BtnOpenOsmo').on('click', () => {
      (<any>window).courseware.onConfigurationLandscape();
    });

    cc.find('middleLayer/ui/BtnCloseOsmo').on('click', () => {
      (<any>window).courseware.onConfigurationPortrait();
    });

    cc.find('middleLayer/ui/BtnOpenFinger').on('click', () => {
      // (<any>window).courseware.openOsmoFingerRead({
      //   "page_id": 27,
      //   "book_id": "opw1"
      // });

      const courseIdNode = cc.find('middleLayer/ui/courseId');
      const str = courseIdNode.getComponent(cc.EditBox).string;
      const arr = str.split(",");
      const pms = {};
      if (arr[0]!=undefined&&arr[0]!=null) {
        pms["x"] = parseFloat(arr[0]);
      }
      if (arr[1]!=undefined&&arr[1]!=null) {
        pms["y"] = parseFloat(arr[1]);
      }
      if (arr[2]!=undefined&&arr[2]!=null) {
        pms["width"] = parseFloat(arr[2]);
      }
      if (arr[3]!=undefined&&arr[3]!=null) {
        pms["height"] = parseFloat(arr[3]);
      }
      this.hideUI();
      (<any>window).courseware.openRecognitionCamera(pms, ()=>{
      });
    });

    cc.find('middleLayer/ui/BtnCloseFinger').on('click', () => {
      // (<any>window).courseware.closeOsmoFingerRead();
    });

    cc.find('middleLayer/ui/BtnOpenRecord').on('click', () => {
      (<any>window).courseware.startRecordScreen(null);
    });

    cc.find('middleLayer/ui/BtnCloseRecord').on('click', () => {
      (<any>window).courseware.stopRecordScreen(res => {
        this.log('--------录屏返回结果 stopRecordScreen ------------');
        this.log(res)
        this.log('------------------------------');
        this.log(`录屏URL: ${JSON.parse(res).url}`);
      });
    });

    cc.find('middleLayer/ui/BtnScanCode').on('click', () => {
      (<any>window).courseware.startScanCode((res) => {
        this.showLog(res);
      });
    });

    cc.find('middleLayer/ui/BtnNeedUpdate').on('click', () => {
      (<any>window).courseware.needUpdate('检测到更新：', 'http://www.baidu.com', (res) => {
        this.showLog(res);
      });
    });

    cc.find('middleLayer/ui/BtnChangeEnv').on('click', async () => {
      await this.getEngineInfo();
      const engineObj = JSON.parse((<any>window).air.engineInfo);
      if (engineObj.isDev == 1) {
        engineObj.isDev = 0;
        (<any>window).air.engineInfo = JSON.stringify(engineObj);
        cc.sys.localStorage.setItem('engine_info', (<any>window).air.engineInfo);
        cc.find(`middleLayer/ui/BtnChangeEnv/Background/Label`).getComponent(cc.Label).string = `切换到测试`;
      } else {
        engineObj.isDev = 1;
        (<any>window).air.engineInfo = JSON.stringify(engineObj);
        cc.sys.localStorage.setItem('engine_info', (<any>window).air.engineInfo);
        cc.find(`middleLayer/ui/BtnChangeEnv/Background/Label`).getComponent(cc.Label).string = `切换到正式`;
      }
    });

    cc.find('middleLayer/ui/BtnOpenTest').on('click', () => {
      // (<any>window).courseware.startTest('apple');
      (<any>window).courseware.startTestConvert('My name is Lucy');
    });

    cc.find('middleLayer/ui/BtnCloseTest').on('click', () => {
      (<any>window).courseware.stopTestConvert(res => {
        this.log('--------录音评测返回结果 stopTest ---------');
        this.log(res)
        this.log('------------------------------');
        this.log(`录音的评分是${JSON.parse(res).result.overall}`);
        this.log(`录音的音频URL是${JSON.parse(res).audioUrl}`);
      }, covert => {
        this.log('--------变声返回结果 ---------');
        this.log(covert)
        this.covertUrl = JSON.parse(covert).convertUrl;
        this.log(`变声的URL：${JSON.parse(covert).convertUrl}`);
        this.log('------------------------------');
      });
    });

    cc.find('middleLayer/ui/BtnCovert').on('click', () => {
      // playAudioByUrl(this.covertUrl);
      playAudioByUrl(`http://teach.cdn.ireadabc.com/oxford_voice/33E1F02E-082F-4A58-9689-598F9A89CA7F/014141419191914141419991476719511478314714767352.mp3`);
    });

    
    const BtnStartLocal = cc.find('middleLayer/ui/BtnStartLocal');
    BtnStartLocal.on('click', () => {
      const addressText = cc.find('middleLayer/ui/address');
      const str = addressText.getComponent(cc.EditBox).string;
      cc.sys.localStorage.setItem('ip', str);
      const address = str.split(':')[0];
      const port = str.split(':')[1] || 8081;
      this.localMode = true;
      this.loadLocalBundle(address, port);
      this.showWaitingLetters();
      this.hideUI();
      this.showDebugUI();
    });

    const BtnStartOnline = cc.find('middleLayer/ui/BtnStartOnline');
    BtnStartOnline.on('click', () => {
      const nameText = cc.find('middleLayer/ui/bundleName');
      const bundleName = nameText.getComponent(cc.EditBox).string;
      cc.sys.localStorage.setItem('bundleName', bundleName);
      this.hideUI();
      this.showWaitingLetters();
      this.loadOnlineBundle(bundleName);
      this.showDebugUI();
    });

    const BtnStartCourseWare = cc.find('middleLayer/ui/BtnStartCourseWare');
    BtnStartCourseWare.on('click', () => {
      const courseIdNode = cc.find('middleLayer/ui/courseId');
      const courseIndexNode = cc.find('middleLayer/ui/courseIndex');
      const courseId = courseIdNode.getComponent(cc.EditBox).string;
      const courseIndex = courseIndexNode.getComponent(cc.EditBox).string;
      cc.sys.localStorage.setItem('courseId', courseId);
      cc.sys.localStorage.setItem('courseIndex', courseIndex);
      this.hideUI();
      this.loadOnlineCourseWare(courseId, false, null, courseIndex);
      this.showDebugUI();
    });

    const BtnLoad = cc.find('middleLayer/ui/BtnLoad');
    BtnLoad.on('click', () => {
      // 测试获取设备信息
      (<any>window).courseware.openPhotoAlbum(res => {
        console.log('--------getEngineInfo返回结果---------');
        console.log(res)
        console.log('------------------------------');
        this.showLog(res);
      });
    });

    const BtnError = cc.find('middleLayer/ui/BtnError');
    BtnError.on('click', () => {
      this.loadOnlineBundle("test_error");
    });

    const btnClose = cc.find('middleLayer/ConsoleNode/BtnClose');
    const btnOpen = cc.find('middleLayer/ConsoleNode/BtnOpen');
    const consoleNode = cc.find('middleLayer/ConsoleNode/Console');
    const consoleBg = cc.find('middleLayer/ConsoleNode/bg');
    btnOpen.on('click', () => {
      btnClose.active = true;
      btnOpen.active = false;
      consoleNode.active = true;
      consoleBg.active = true;
    });

    btnClose.on('click', () => {
      btnClose.active = false;
      btnOpen.active = true;
      consoleNode.active = false;
      consoleBg.active = false;
    });
  }

  log(str) {
    const logStr = `${new Date().toLocaleString()}: ${str}`;
    console.log(logStr);
    const content = cc.instantiate(cc.find('middleLayer/ConsoleNode/content'));
    content.active = true;
    const label = content.getChildByName('label');
    label.getComponent(cc.Label).string = logStr;
    const consoleContent = cc.find('middleLayer/ConsoleNode/Console/content');
    consoleContent.addChild(content);
    consoleContent.getComponent(cc.Layout).updateLayout();
  }
  hideUI() {
    cc.find('middleLayer/ui').active = false;
  }
  loadLocalBundle(address, port) {
    this.callNetworkApiGetLocal(`http://${address}:${port}`, '/dist/config.json', {}, (datastr) => {
      const data = JSON.parse(datastr);
      let sceneName = '';
      let version = '';
      let bondleUrl = '';
      if (cc.sys.os == cc.sys.OS_IOS) {
        sceneName = data.ios.sceneName;
        version = data.ios.version;
        bondleUrl = `http://${address}:${port}/dist/ios/${sceneName}/`;
      } else if (cc.sys.os == cc.sys.OS_ANDROID) {
        sceneName = data.android.sceneName;
        version = data.android.version;
        bondleUrl = `http://${address}:${port}/dist/android/${sceneName}/`;
      } else {
        sceneName = data.android.sceneName;
        version = "";
        bondleUrl = `http://${address}:${port}/dist/web_desktop/`;
      }
      this.loadBundle(sceneName, version, bondleUrl);
    });
  }

  reWriteAir() {
    (<any>window).courseware.getData = (callback) => {
      let data = null;
      if (this.courseItem && this.courseItem.data) {
        data = JSON.parse(this.courseItem.data);
      }
      this.log("===成功调用getData===" + JSON.stringify(data));
      callback && callback(data);
    }
    (<any>window).courseware.nextPage = () => {
      this.goNextPage();
      if (this.courseIndex == 0) {
        cc.find('middleLayer/BtnLeft').active = false;
      } else {
        cc.find('middleLayer/BtnLeft').active = false;
      }
      if (this.courseIndex == this.courses.length - 1) {
        cc.find('middleLayer/BtnRight').active = false;
      } else {
        cc.find('middleLayer/BtnRight').active = true;
      }
    }
    (<any>window).courseware.beforePage = () => {
      this.goPrePage();
      if (this.courseIndex == 0) {
        cc.find('middleLayer/BtnLeft').active = false;
      } else {
        cc.find('middleLayer/BtnLeft').active = false;
      }
      if (this.courseIndex == this.courses.length - 1) {
        cc.find('middleLayer/BtnRight').active = false;
      } else {
        cc.find('middleLayer/BtnRight').active = true;
      }
    }
    (<any>window).courseware.sendAnswer = (answerObj) => {
      this.log("===成功调用sendAnswer===" + JSON.stringify(answerObj));
      this.callNetworkApiPost(`/api/oxford/courseware/v1/${this.courseItem.id}/saveanswer`, answerObj, (data) => {
        answerObj.callback && answerObj.callback(JSON.stringify(data.row));
      });
    }
    (<any>window).courseware.getAnswer = (queryObj, callback) => {
      this.log("===成功调用getAnswer===" + JSON.stringify(queryObj));
      this.callNetworkApiGet(`/api/oxford/courseware/v1/${this.courseItem.id}/getanswer`, queryObj, (datastr) => {
        const data = JSON.parse(datastr);
        callback && callback(JSON.stringify(data.rows));
      });
    }

    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();
        });
      } else {
        this.hideWaitingLetters();
      }
    }
  }

  callNativeFunction(param) {
    const paramStr = JSON.stringify(param);
    if (cc.sys.isNative && cc.sys.os == cc.sys.OS_IOS) {
      return jsb.reflection.callStaticMethod('CocosMng', 'cocosWithNativeProtocol:', paramStr);
    } else if (cc.sys.isNative && cc.sys.os == cc.sys.OS_ANDROID) {
      return jsb.reflection.callStaticMethod('com/iplayabc/cocos/AppActivity', 'cocosWithNativeProtocol', '(Ljava/lang/String;)Ljava/lang/String;', paramStr);
    } else if (cc.sys.isNative && cc.sys.os == cc.sys.OS_WINDOWS) {
      console.log('汪汪汪')
    } else {
      console.error('非源生环境11');
    }
  }

  logList = [];
  showLog(str) {
    this.logList.push(str);
    console.log(str);

    if (this.logList.length == 1) {
      this.showOneLog();
    }
  }

  showDebugUI() {
    cc.find('middleLayer/ConsoleNode/BtnOpen').active = true;
  }

  showOneLog() {
    const str = this.logList[0];
    if (str === undefined) {
      return;
    }
    const node = new cc.Node();
    node.anchorX = 0.5;
    const label = node.addComponent(cc.RichText);
    label.string = `<outline color=black width=3>${str}</outline>`;
    label.maxWidth = this.node.width / 2;
    node.x = this.node.width / 4;
    node.y = -this.node.height / 2;
    node.parent = this.node;
    cc.tween(node)
      .to(5, { y: this.node.height })
      .removeSelf()
      .start();
    setTimeout(() => {
      this.logList.shift();
      this.showOneLog();
    }, 1000);
  }

  exit() {
    cc.game.removePersistRootNode(this.node);
    cc.director.loadScene("emptyScene", () => {
      this.callNativeFunction({ name: 'exit', value: '' });
    });
  }

  exitGame() {
    this.showTips(`已经调用了 exitGame `);
  }

  saveGolds(num) {
    this.showTips(`已经调用了 saveGolds；金币: ${num} `);
  }

  getPageInfo() {
    this.showTips(`已经调用了 getPageInfo `);
		return {length: 2, index: 0};
  }
  
  goNextCross() {
    this.showTips(`已经调用了 goNextCross `);
  }


  getRainbowColorList() {
    return [
      cc.color(255, 255, 0),
      cc.color(128, 255, 0),
      cc.color(0, 255, 0),
      cc.color(0, 0, 0),

      cc.color(0, 255, 128),
      cc.color(0, 255, 255),

      cc.color(0, 128, 255),
      cc.color(0, 0, 255),
      cc.color(128, 0, 255),
      cc.color(255, 0, 255),
      cc.color(255, 0, 128),

      cc.color(255, 0, 0),
      cc.color(255, 128, 0),
      cc.color(255, 255, 0),
    ];
  }
}
