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.showBackBtn();
    });

    this.initListener();

  }

  initUI() {
    this.hideBackBtn();
  }

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

  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();
  }

  reportScore(data, callback) {
    if (!this.token) {
      return;
    }

    console.log('========== reportScore ==========');
    console.log(JSON.stringify({
      token: this.token,
      score: data.score,
      syllabus_id: this.courseItem.course_id,
      courseware_id: this.courseItem.id,
      type: ""
    }));
    this.callNetworkApiPost(`api/dige/v1/user/score/report`, {
      token: this.token,
      score: data.score,
      syllabus_id: this.courseItem.course_id,
      courseware_id: this.courseItem.id,
      type: ""
    }, res => {
      callback && callback(res);
    });
  }

  getRankList(data, callback) {
    if (!this.token) {
      return;
    }

    console.log('========== getRankList ==========');
    console.log(JSON.stringify({
      token: this.token,
      syllabus_id: this.courseItem.course_id,
      courseware_id: this.courseItem.id,
      direction: data.direction, // 方向 up 向上 down 向下
      ranking: data.ranking
    }));
    
    this.callNetworkApiGet(`api/dige/v1/user/score/rank`, {
      token: this.token,
      syllabus_id: this.courseItem.course_id,
      courseware_id: this.courseItem.id,
      direction: data.direction, // 方向 up 向上 down 向下
      ranking: data.ranking
    }, res => {
      callback && callback(res);
    });
  }
  

  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) {
    console.log('=========exitGame=========');
    let totalCount = 0;
    const tpl = cc.find('Canvas')?.getComponent(this.courseItem.template_name);

    console.log(JSON.stringify(tpl['data']));
    console.log('this.courseItem: ', JSON.stringify(this.courseItem));
    if(!data && tpl) {
      data = tpl['data'];
      totalCount = tpl['totalCount'];
      console.log('tpl-data: ', JSON.stringify(data));
      console.log('tpl-totalCount: ', totalCount);
    }

    cc.game.removePersistRootNode(this.node);

   
    if (this.token && data) {
      console.log(JSON.stringify({
        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),
        totalCount
      }));
      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),
        totalCount
      }, (res) => {
        console.log('-----------------');
        console.log(JSON.stringify(res));
        console.log('-----------------');
        cc.director.loadScene("emptyScene", () => {
          this.callNativeFunction({ name: "exit", value: "" });
        });
      });
    } else {
      cc.director.loadScene("emptyScene", () => {
          this.callNativeFunction({ name: "exit", value: "" });
        });
    }

    console.log('=========exitGame DONE=========');

  }

  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);
      }
    }
  }
}
