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

const { ccclass, property } = cc._decorator;

@ccclass
export default class NewClass extends middleLayerBase {

  role;
  token;
  course_id;
  courseware_id;
  // 统一释放异步资源的方法
  async onLoad() {
    initAir(this);
    this.reWriteAir();
    this.role = 'student';
  }

  async start() {
    this.node.zIndex = 9999;
    cc.game.addPersistRootNode(this.node);
    global.middleLayer = cc.find('middleLayer').getComponent('middleLayer');

    const jsonStr = this.callNativeFunction({
      name: "loadSceneList",
      value: "",
    });

    this.initUI();

    if (!jsonStr) {
      console.error("没有jsonStr!!");
      return;
    }
    console.log("===jsonStr===", jsonStr);
    const { bundleInfo } = JSON.parse(jsonStr);

    this.API_BASE = bundleInfo.base_url || this.API_BASE;
    if (this.API_BASE.indexOf("staging-")<0) {
      this.DOMAIN = this.DOMAIN.replace("staging-", "");
    }
    this.token = bundleInfo.token;
    this.course_id = bundleInfo.course_id;
    this.courseware_id = bundleInfo.courseware_id;
    if (!bundleInfo.course_id || !bundleInfo.courseware_id) {
      console.error("缺少必要的参数！请检查是否传入了以下参数：course_id，courseware_id，toke");
      return;
    }
    this.loadOnlineCourseWare(this.course_id, false, this.courseware_id);

    this.initListener();

  }

  initUI() {
    this.showBackBtn();
  }

  showBackBtn() {
		const backBtn = cc.find("middleLayer/UI/back_btn");
    backBtn.active = true;
	}

  onBackBtnClick() {
    const backBtn = cc.find("middleLayer/UI/back_btn");
    backBtn.active = false;
    
    this.exitGame();
  }


  onHomeworkFinish(callBack, data = null) {
    if (!this.token) {
      return;
    }
    if (typeof (callBack) == 'object') {
      data = callBack;
    }
    this.callNetworkApiPost(`api/dige/v1/user/report`, {
      token: this.token,
      syllabus_id: this.courseItem.course_id,
      courseware_id: this.courseItem.id,
      template_name: this.courseItem.template_name,
      study_duration: Date.now() - this.courseOpenTimeStamp,
      result: JSON.stringify(data),
    }, res => {
      callBack && callBack(res);
    });
  }

  exitGame(data = null) {

    cc.game.removePersistRootNode(this.node);
    if (this.token && data) {
      this.callNetworkApiPost(`api/dige/v1/user/report`, {
        token: this.token,
        syllabus_id: this.courseItem.course_id,
        courseware_id: this.courseItem.id,
        template_name: this.courseItem.template_name,
        study_duration: Date.now() - this.courseOpenTimeStamp,
        result: JSON.stringify(data),
      }, (res) => {
        console.log('-----------------');
        console.log(res);
        console.log('-----------------');
        cc.director.loadScene("emptyScene", () => {
          this.callNativeFunction({ name: "exit", value: "" });
        });
      });
    } else {
      cc.director.loadScene("emptyScene", () => {
          this.callNativeFunction({ name: "exit", value: "" });
        });
    }
  }

  initListener() {
    
  }

  async getUserInfo() {

  
    console.log("in getUserInfo");

    let res = await this.asyncCallNetworkApiGet(`api/dige/v1/user/info`, {});
    console.log("res: ", res);

    if (res.code != 200) {
      global.middleLayer.showTips(res.msg);
      return;
    } 

    return {
      avatar_url: null,
      nick_name: null
    }

  }

  async getHeadUrl() {
    return '';
  }

  reWriteAir() {
    (<any>window).courseware.getData = (callback) => {
      let data = null;
      if (this.courseItem && this.courseItem.data) {

        this.courseItem.data = this.courseItem.data.replace(/https/g, 'http');
        data = JSON.parse(this.courseItem.data);
      }
      this.log("===成功调用getData===" + JSON.stringify(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}`);
        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 = () => {
      (<any>window).air.onCourseInScreen && (<any>window).air.onCourseInScreen(() => {
        console.log("***成功调用onCourseInScreen***");
        (<any>window).air.onCourseInScreen = null;
      });
      this.hideWaitingLetters();
    }
  }

  saveRecordResult(recordResult) {
    if (!this.token) {
      return;
    }
    const result = JSON.parse(recordResult);
    this.callNetworkApiPost(`api/dige/v1/record/save`, {
      token: this.token,
      syllabus_id: this.courseItem.course_id,
      courseware_id: this.courseItem.id,
      record_url: result.audioUrl,
      test_result: recordResult
    }, () => { });
  }

  getQueryString (name) {
    const reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
    const r = window.location.search.substr(1).match(reg);
    if (r != null) {
      return unescape(r[2]);
    }
    return null;
  };
  
  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 (param.name == "loadSceneList") {
        // Mock数据
        console.error("非源生环境，需要从URL中获取必要的参数");
        const token = this.getQueryString("token");
        const course_id = this.getQueryString("course_id");
        const courseware_id = this.getQueryString("courseware_id");
        const resobj = { bundleInfo: {token,course_id,courseware_id}};
        return JSON.stringify(resobj);
      }
      if (param.name == "exit") {
        console.log("==调用退出方法成功==参数：", paramStr);
      }
    }
  }
}
