import { middleLayerBase } from "./middleLayerBase";
import { initAir } from './air';
// @ts-ignore
const StudyRecord = require('./studyRecord.js');

const { ccclass, property } = cc._decorator;

@ccclass
export default class NewClass extends middleLayerBase {

  role;
  token;
  course_id;
  courseware_id;
  backPageScene;
  isRunCamp = false;
  isTodayWork = false;

  JRZY_ID = -1; //今日作业
  JRSX_ID = -2; //今日所学

  // 统一释放异步资源的方法
  async onLoad() {

    console.log(" jj_f onLoad .... 1");

    initAir(this);
    this.reWriteAir();
    this.role = 'student';
    console.log(" jj_f onLoad .... 2");

    // (<any>window).courseware.getEngineInfo();
  }

  async start() {

    console.log(" jj_f start .... 1");

    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;
    this.isRunCamp = bundleInfo.is_run_camp;
    if (this.isRunCamp) {
      this.setCurHomeworkData( bundleInfo.homework_id, bundleInfo.syllabus_id, bundleInfo.user_id);
      this.initExitPanel();
      this.initNetworkLoading();
    }
    this.isTodayWork = bundleInfo.is_today_work;
    if (this.isTodayWork) {
      this.setCurHomeworkData( bundleInfo.homework_id, bundleInfo.syllabus_id, bundleInfo.user_id);
      this.initExitPanel();
      this.initNetworkLoading();
    }

    if (bundleInfo.study_record) {
       console.log('bundleInfo.study_record: ', bundleInfo.study_record);

       const study_record = JSON.parse(bundleInfo.study_record);

       this.initStudyRecord(study_record);
    }
    

    cc.sys.localStorage.setItem('student_token', bundleInfo.token);
    console.log("student_token 1: ", bundleInfo.token);

    if (!this.isRunCamp && !this.isTodayWork && !bundleInfo.study_record) {
      await this.getUserInfo();
    }

    // 打开特殊课件
    if (this.course_id < 1) {
      this.openCustomTemplate();
      return;
    }
    console.log("this.course_id~ :", this.course_id);


    if (!bundleInfo.course_id) {
      console.error("缺少必要的参数！请检查是否传入了以下参数：course_id");
      this.showBackBtn();
      return;
    }
    // this.loadOnlineCourseWare(this.course_id, false, this.courseware_id);
    this.loadOnlineCourseWare(this.course_id, this.courseware_id);

    this.initListener();

    console.log(" jj_f start .... 2");

  }

  

  openCustomTemplate() {

      console.log("in openCustomTemplate");

      //打开今日作业
      if (this.course_id == this.JRZY_ID) {
        this.loadOnlineBundleNew("JJ_page_homework");
        return;
      }
  
      // 打开今日所学c
      if (this.course_id == this.JRSX_ID) {
        this.loadOnlineBundleNew("JJ_page_learn");
        return;
      }

      this.showBackBtn();
  }


  initUI() {
    this.showBackBtn();
  }

  initExitPanel() {

    const exitPanel = cc.find('middleLayer/UI/exit_panel');
    exitPanel.active = false;

    const exitBtn = cc.find('middleLayer/UI/exit_panel/bg/btn_exit');
    exitBtn.on(cc.Node.EventType.TOUCH_END, () => {
      exitPanel.active = false;

      this.isRunCamp = false;
      this.isTodayWork = false;
      this.curHomeworkId = null;
      this.curSyllabusId = null;
      this.curUserId = null;
      this.exitGame();
    });

    const cancelBtn = cc.find('middleLayer/UI/exit_panel/bg/btn_cancel');
    cancelBtn.on(cc.Node.EventType.TOUCH_END, () => {
      exitPanel.active = false;
    });
  }

  initNetworkLoading() {
    const networkLoading = cc.find('middleLayer/UI/network_loading');
    networkLoading.active = false;

    const icon = cc.find('middleLayer/UI/network_loading/icon');
    icon.active = true;

   // 创建一个永久旋转的动画
    cc.tween(icon)
      .by(2, { angle: -360 }) // 逆时针旋转360度
      .repeatForever() // 无限重复
      .start();
  }

  showNetworkLoading() {
    const networkLoading = cc.find('middleLayer/UI/network_loading');
    networkLoading.active = true;
  }
  hideNetworkLoading() {
    const networkLoading = cc.find('middleLayer/UI/network_loading');
    networkLoading.active = false;
  }

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

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

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


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


  showExitPanel() {
    const exitPanel = cc.find('middleLayer/UI/exit_panel');
    exitPanel.active = true;
  }

  exitGame(data = null) {

    console.log(' in  exitGame data: ', data);
    console.log(' this.token: ', this.token);

    if (this.isRunCamp && this.curHomeworkId) {
      this.showExitPanel();
      return;
    }

    if (this.isTodayWork && this.curHomeworkId) {
      this.showExitPanel();
      return;
    }
    
    // if (this.node) {
    //   cc.game.removePersistRootNode(this.node);
    // }
    // if (this.token && data) {

    //   console.log('data str: ', JSON.stringify(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('-----------------');


    //     this.backScene();
    //   });
    // } else {
      this.backScene();
    // }
  }

  initListener() {
    
  }

  backScene() {

    let sceneName = 'emptyScene';

    if (this.backPageScene) {
      sceneName = this.backPageScene;
      this.backPageScene = null;

      this.loadOnlineBundleNew(sceneName);
      return;
    }

    cc.director.loadScene(sceneName, () => {
      this.callNativeFunction({ name: "exit", value: "" });
    });
  }
  

  async getUserInfo(data = {}) {
    let res = await this.asyncCallNetworkApiGetNew(`api/jj/v1/user/info`, data);

    if (typeof res == 'object') {
      console.log('res~1: ', JSON.stringify(res));
    } else {
      console.log('res~2: ', res);
    }

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

    if (res.code == '200') {

      cc.sys.localStorage.setItem('student_token', res.data.student_token);
      this.token = res.data.student_token
      // console.log("student_token 2: ", res.data.student_token);

      global.userInfo = res.data;

      console.log('res: ', res);
    }

    return res;
  }

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


  curHomeworkId;
  curSyllabusId;
  curUserId;
  setCurHomeworkData(homework_id, syllabus_id, user_id = null) {
    this.curHomeworkId = homework_id;
    this.curSyllabusId = syllabus_id;
    this.curUserId = user_id;
	}


  onHomeworkFinish(d1 = null, d2 = null) {

    if (this.studyRecord) {
      this.defaultReportData();
    }

  
    if (this.isRunCamp) {
      this.onHomeworkFinishRunCamp(d1, d2);
      return;
    }

    if (this.isTodayWork) {
      this.onHomeworkFinishTodayWork(d1, d2);
      return;
    }


    

    console.log('in onHomeworkFinish');
    let data = d1;
    let callback = null;
    if (typeof(d1) == 'function') {
      data = d2;
      callback = d1;
    }
  
    if (this.curHomeworkId == null || this.curSyllabusId == null) {
      callback && callback();
      return;
    }

    this.callNetworkApiPostNew(`api/app_source/v1/student/homework/finished`, {
      syllabus_id: this.curSyllabusId,
      homework_id: this.curHomeworkId,
      result: JSON.stringify(data || {}),
    }, res => {

      this.curSyllabusId = null;
      this.curHomeworkId = null;
      callback && callback(res);
    });

  }



  onHomeworkFinishTodayWork(d1 = null, d2 = null) {

    console.log('in onHomeworkFinishTodayWork');
    let data = d1;
    let callback = null;
    if (typeof(d1) == 'function') {
      data = d2;
      callback = d1;
    }

  
    if (this.curHomeworkId == null || this.curSyllabusId == null || this.curUserId == null) {
      callback && callback();
      this.isTodayWork = false;
      return;
    }

    console.log('in onHomeworkFinish 1');
    console.log(' curUserId : ' + this.curUserId);
    console.log(' curHomeworkId : ' + this.curHomeworkId);
    console.log(' curSyllabusId : ' + this.curSyllabusId);

    this.showNetworkLoading();


    this.callNetworkApiPostNew(`v1/class-work/finish/${this.curUserId}/${this.curHomeworkId}`, {
      "id": this.curHomeworkId,
      "useTime": 10,
      "score": 100,
      "accuracy": 1
    }, res => {

      this.hideNetworkLoading();

      this.curSyllabusId = null;
      this.curHomeworkId = null;
      this.isTodayWork = false;
      callback && callback(res);
    });

  }


  onHomeworkFinishRunCamp(d1 = null, d2 = null) {

    console.log('in onHomeworkFinishRunCamp');
    let data = d1;
    let callback = null;
    if (typeof(d1) == 'function') {
      data = d2;
      callback = d1;
    }

  
    if (this.curHomeworkId == null || this.curSyllabusId == null || this.curUserId == null) {
      callback && callback();
      this.isRunCamp = false;
      return;
    }

    console.log('in onHomeworkFinish 1');
    console.log(' curUserId : ' + this.curUserId);
    console.log(' curHomeworkId : ' + this.curHomeworkId);
    console.log(' curSyllabusId : ' + this.curSyllabusId);

    this.showNetworkLoading();

    this.callNetworkApiPostNew(`v1/learning-camp/finish/${this.curUserId}/${this.curHomeworkId}`, {
      "id": this.curHomeworkId,
      "useTime": 10,
      "score": 100,
      "accuracy": 1
    }, res => {

      this.hideNetworkLoading();

      this.curSyllabusId = null;
      this.curHomeworkId = null;
      this.isRunCamp = false;
      callback && callback(res);
    });

  }





  studyRecord: any;
  studyRecordModel;
  initStudyRecord(study_record) {
    try {
      console.log('initStudyRecord study_record: ', study_record);
      console.log('StudyRecord constructor:', StudyRecord);
      console.log('StudyRecord type:', typeof StudyRecord);
      
      this.studyRecordModel = study_record;
      this.studyRecord = new StudyRecord();
      
      console.log('StudyRecord instance created:', this.studyRecord);
    } catch (error) {
      console.error('Error creating StudyRecord instance:', error);
      console.error('StudyRecord constructor:', StudyRecord);
    }
  }

  setSRRecord(key, value) {
    if (this.studyRecord) {
      this.studyRecord.recordAudioScore(key, value);
    }
  }

  addSRAudioDuration(duration) {
    if (this.studyRecord) {
      this.studyRecord.addAudioDuration(duration);
    }
  }

  showSRResultByRecord(isShowScore = false) {
    if (this.studyRecord) {
      console.log('=-=-=-=-= isShowScore: ', isShowScore);

      this.studyRecordModel.recordData = this.studyRecord.getAllAudioKeyData();
      const score = this.studyRecord.getTotalAverageAudioScore();

      this.reportData(score);
      
      if (isShowScore) {
        this.showSRResult(score)
      }
    }
  }

  showSRResultByQuestion(isShowScore = false) {
    if (this.studyRecord) {
      console.log('=-=-=-=-= isShowScore: ', isShowScore);

      this.studyRecordModel.recordData = this.studyRecord.getAllQuestionResults();
      const score = this.studyRecord.getAverageScore();
      this.reportData(score);

      if (isShowScore) {
        this.showSRResult(score)
      }
    }


    
  }

  showSRResult(score) {
    if (this.studyRecord) {
      console.log('showSRResult score: ', score);
      this.showScoreLayer(score);
      // this.studyRecord.showResult();
    }
  }

  setTotalQuestions(total) {
    if (this.studyRecord) {
      this.studyRecord.setTotalQuestions(total);
    }
  }

  setQuestionResult(index, score) {
    if (this.studyRecord) {
      this.studyRecord.setQuestionResult(index, score);
    }
  }

  defaultReportData() {

    setTimeout(() => {
      if (this.isDestroy) {
        return;
      }
      if (!this.isStudyRecordReported) {
        this.reportData(0);
      }
    }, 500);

  }


  isStudyRecordReported = false;
  reportData(score = 0)  {
    console.log('reportData 1');

    if (this.isStudyRecordReported) {
      return;
    }

    if (this.studyRecord) {
      this.isStudyRecordReported = true;
      console.log('reportData 2');

      console.log('=-=-=-=-= reportData');

      const reportData = this.studyRecord.reportData(this.studyRecordModel, score);
      // 在这里处理网络请求
      this.callNetworkApiPostNew(`insights/v1/study-analysis`, {
        ...this.studyRecordModel,
        recordData: reportData
      }, res => {
        if (res == null) {
          console.log('reportData => res is null');
          return;
        }
        console.log('reportData => res:', res);
      });
    }
  }

  showScoreLayer(score) {
    const scoreLayer = cc.find('middleLayer/UI/score_layer');
    if (scoreLayer) {
      scoreLayer.active = true;
      const animNodeWin = cc.find('middleLayer/UI/score_layer/animNodeWin');
      const animNodeTry = cc.find('middleLayer/UI/score_layer/animNodeTryAgain');
      if (score >= 60) {
        animNodeWin.active = true;
        animNodeTry.active = false;

        const label = cc.find('label', animNodeWin).getComponent(cc.Label);
        label.string = score;

      } else {
        animNodeWin.active = false;
        animNodeTry.active = true;
      }
     
    }
  }

  closeScoreLayer() {
    const scoreLayer = cc.find('middleLayer/UI/score_layer');
    if (scoreLayer) {
      scoreLayer.active = false;
    }
  }


}
