// 刷新CDN路径
// https://staging-teach.cdn.ireadabc.com/h5template/h5-static-lib/js/air.js
// https://teach.cdn.ireadabc.com/h5template/h5-static-lib/js/air.js

const commonPostMessage = function (messageObj) {
  const obj = {...messageObj, urlParams: window.location.search}
  window.parent.postMessage(obj, '*');
};

const commonPostMessageWithCallback = function (messageObj, callback) {
  const onMessage = (e) => {
    let msgData = e.data;
    if(msgData && msgData.action === messageObj.action){
      window.removeEventListener("message", onMessage);
      callback && callback(msgData.data);
    }
  };
  window.addEventListener("message", onMessage);
  commonPostMessage(messageObj);
};

const realAir = {
  uploadUrl: null,
  uploadData: null,
  getDataCallback: null,
  setDataCallback: null,
  getUploadCallback: null,
  pageLoaded: false,
  isCourseInScreen: false,
  hideAirClassLoading: function(templateName,loadData){
    // 隐藏页面加载时候的loading
    if (deleteHistory && typeof (deleteHistory) == 'function') {
      deleteHistory();
    }
    window.parent.postMessage({ action: "course-ready", data: {template:templateName,loadData:loadData,urlParams: window.location.search}, urlParams: window.location.search}, '*');
    window.air.pageLoaded = true; 
    window.courseware.next(); 

    var cc = window.cc;

    if (cc && cc.director && cc.director._scene) {
      try {
        const canvas = cc.find("Canvas");
        canvas.on("mousemove", function () {});
        cc.director._scene.on("mousemove", function () {
          window.parent.postMessage({ action: "mousemove" }, "*");
        });
        cc.director._scene.on("touchmove", function () {
          window.parent.postMessage({ action: "mousemove" }, "*");
        });

        if (cc.systemEvent && cc.SystemEvent) {
          cc.systemEvent.on(cc.SystemEvent.EventType.KEY_DOWN, (event) => {
            switch (event.keyCode) {
              case cc.KEY.left:
                window.parent.postMessage({ action: "ArrowLeft" }, "*");
                break;
              case cc.KEY.right:
                window.parent.postMessage({ action: "ArrowRight" }, "*");
                break;
            }
          });
        }
      } catch (e) {
        console.log("====cc.director._scene绑定事件====");
      }
    }
  },
};

const uploadCallbackQueue = [];

try{
  window.air = new Proxy(realAir, {
    set: function (target, key, value, receiver) {
      if (key=="getUploadCallback") {
				uploadCallbackQueue.push(value);
			}
      return Reflect.set(target, key, value, receiver); 
    },
    get: function (target, key, receiver) {
			return Reflect.get(target, key, receiver);
    },
    deleteProperty: function(target, key){
			return Reflect.deleteProperty(target, key);
		}
  });
}catch(e){
  console.error("浏览器不支持ES6新特性Proxy/Reflect，请使用谷歌浏览器！");
}

function deleteHistory() {
  const disableBack = () => {
    window.history.pushState(null, "", document.URL);
    window.addEventListener("popstate", () => {
      window.history.pushState(null, "", document.URL);
    });
  }
  disableBack();
  window.addEventListener("load", disableBack);
}
deleteHistory();

if (window.self !== window.top) {
  window.addEventListener("message", function (e) {
    let msgData = e.data;
    // console.log("子页面接收到了消息", msgData);
    if(msgData.type === "webpackWarnings" || msgData.type === "webpackOk") {
      return;
    }
    if(msgData.action==="airEvents"){
      return;
    } 
    if (msgData.action === "getUpload" && msgData.uploadUrl) {
      window.air.uploadUrl = msgData.uploadUrl;
      window.air.uploadData = msgData.uploadData;
      for (let i = 0; i < uploadCallbackQueue.length; i++) {
        uploadCallbackQueue[i](msgData.uploadUrl, msgData.uploadData);
      }
      return;
    }
    if (msgData.action === "pauseCocos") {
      let cc = window.cc;
      if (cc && cc.game) {
        cc.game.pause();
        console.log('pause了');
      }
      return;
    }
    if (msgData.action === "resumeCocos") {
      let cc = window.cc;
      if (cc && cc.game) {
        cc.game.resume();
        console.log('resume了');
      }
      return;
    }
    if (msgData.action === "restartCocos") {
      let cc = window.cc;
      if (cc && cc.game) {
        cc.audioEngine.stopAll();
        // cc.game.restart();
        console.log('restart了');
      }
      return;
    }
    if (msgData.action === "setData") {
      window.air.setDataCallback && window.air.setDataCallback();
      return;
    }
    if (msgData.action === "getData") {
      try {
        const res = JSON.parse(msgData.data);
        if (res.msg !== "success") {
          console.log('数据加载失败！');
          return;
        }
        if (res.data && res.data != 'null') {
          window.air.callData = JSON.parse(res.data);
        }
        window.air.callDataFlag = true;
        return;
      } catch (e) {
        console.log('数据加载失败！');
      }
    }
  });
  window.parent.postMessage({ action: "getUpload" }, '*');

  document.onmousemove = function(){
    window.parent.postMessage({ action: "mousemove" }, '*');
  };
  document.ontouchmove = function(){
    window.parent.postMessage({ action: "mousemove" }, '*');
  };

  document.onkeydown = (event) => {
    switch(event.key) {
      case "ArrowLeft":
        window.parent.postMessage({ action: "ArrowLeft" }, '*');
        break;
      case "ArrowRight": 
        window.parent.postMessage({ action: "ArrowRight" }, '*');
        break;
    }
  }

  document.oncontextmenu = function(){
    return false;
  }
}


window.courseware = (function () {
  let obj = {
    airEvents: {},
    eventQueue: [],
    eventLock: false,
    next: () => {
      let exe = obj.eventQueue.splice(0,1); 
      if(exe.length>0){
        obj.eventLock = true;
        let evtName = exe[0].evtName;
        let data = exe[0].data; 
        if(obj.airEvents[evtName]){
          if(evtName === "course-in-screen"){
            if(window.air.isCourseInScreen){
              return;
            }
            window.air.isCourseInScreen = true;
          }
          console.log(`evtName==${evtName}的方法被执行`);
          obj.airEvents[evtName](data, obj.next);
        } else {
          console.warn(`airclass教室交互事件 ${evtName} 没有被捕获，请确认监听事件的先后顺序2`);
          obj.next();
        }
      }else{
        obj.eventLock = false;
      } 
    }
  };
  if (window.self !== window.top) {
    window.addEventListener("message", function (e) {
      let msgData = e.data;
      if(msgData.action!=="airEvents"){
        return;
      } 
      let evtName = msgData.evt; 
      let res = msgData.data;
      if (evtName === "course-out-screen"){
        console.log(`evtName==${evtName}的方法被执行`);
        window.location.reload();
        return;
      }
      if (res&&evtName!='userchange') {
        //userchange事件传过来的值不需要转换
        res = JSON.parse(res); 
      }
      if(!window.air.pageLoaded){
        //如果页面还没有加载完成
        obj.eventQueue.push({"evtName": evtName, data: res});
      }else{ 
        if (obj.eventQueue.length === 0 && !obj.eventLock) {
          //如果没有消息积压并且事件锁未锁定
          obj.eventLock = true; 
          if(obj.airEvents[evtName]){
            if(evtName === "course-in-screen"){
              if(window.air.isCourseInScreen){
                return;
              }
              window.air.isCourseInScreen = true;
            }
            console.log(`evtName==${evtName}的方法被执行`);
            obj.airEvents[evtName](res, obj.next); 
          } else {
            console.warn(`airclass教室交互事件 ${evtName} 没有被捕获，请确认监听事件的先后顺序1`);
            obj.next();
          }
        } else {
          obj.eventQueue.push({"evtName": evtName, data: res});
        }
      } 
    }); 
    obj.getData = function (callback, key = '') {
      window.parent.postMessage({ action: "getData", data: window.location.search, urlParams: window.location.search }, '*');
      window.air.callDataFlag = false;
      
      const liuintval = setInterval(()=>{
        if(window.air.callDataFlag){
          console.log("========我进来了=========");
          clearInterval(liuintval);
          setTimeout(() => {
            console.log("执行回调，回调数据为：");
            console.log(window.air.callData);
            callback(window.air.callData);
          }, 100);
        }
      }, 100);
    };
    obj.setData = function (data, callback, key = '') {
      let str = JSON.stringify(data);
      console.log("==setData==", str);
      window.parent.postMessage({ action: "setData", data: str, urlParams: window.location.search }, '*');
      window.air.setDataCallback = callback;
    };
    obj.uploadUrl = function () {
      // return net.getUploadFileURL();
      return window.air.uploadUrl;
    };
    obj.uploadData = function () {
      // return net.getAjaxData("uploadFile","");
      return window.air.uploadData;
    };
    obj.beganRecording = function(){
      commonPostMessage({ action: "beganRecording" }); 
    };
    obj.endRecording = function(callback){
      commonPostMessageWithCallback({ action: "endRecording" }, callback);
    };
    obj.speakPoints = function(audioUrl, evalText, callback){
      const obj = {audioUrl, evalText};
      commonPostMessageWithCallback({ action: "speakPoints", data: JSON.stringify(obj) }, callback);
    };
    obj.startRecord = function(testText){
      commonPostMessage({ action: "startRecord", data: testText  });
    };
    obj.stopRecord = function(callback){
      commonPostMessageWithCallback({ action: "stopRecord" }, callback);
    };
    obj.startTest = function(testText){
      commonPostMessage({ action: "startTest", data: testText });
    };
    obj.stopTest = function(callback){
      commonPostMessageWithCallback({ action: "stopTest" }, callback);
    };
    obj.getTemplates = function(callback){
      commonPostMessageWithCallback({ action: "getTemplates" }, callback);
    };
    obj.getTemplateUrl = function(templateName, callback){
      commonPostMessageWithCallback({ action: "getTemplateUrl", data: templateName}, callback);
    };
    obj.sendEvent = function(evtName,data,key = ''){
      if(evtName==="reconnect"){
        console.error("reconnect是内置的断线重连事件名称，请勿使用此名称作为事件名");
        return;
      }
      if(evtName==="userchange"){
        console.error("userchange是内置的用户变更事件名称，请勿使用此名称作为事件名");
        return;
      }
      let str = null;
      if(data){
        str = JSON.stringify(data);
      } 
      window.parent.postMessage({ action: "airEvents",evt: evtName, data: str, urlParams: window.location.search }, '*'); 
    };
    obj.onEvent = function(evtName,callback){  
      obj.airEvents[evtName] = callback; 
    };
    obj.removeEvent = function(evtName){
      if(obj.airEvents[evtName]){ 
        delete obj.airEvents[evtName];
      }  
    };
    obj.sendErrorLog = function (error) { 
      // todo 这块预留后面采集模板的报错信息
      // window.parent.postMessage({ action: "errorlog", data: error.stack }, '*'); 
    };
  } else {
    obj.getData = function (callback, key = '') {
      let data = localStorage.getItem("courseware_data_" + key);
      if (data) {
        data = JSON.parse(data);
      }
      callback && callback(data);
    };
    obj.setData = function (data, callback, key = '') {
      console.log("******local********");
      localStorage.setItem("courseware_data_" + key, JSON.stringify(data));
      callback && callback();
    };
    obj.uploadUrl = function () {
      var protocolStr = document.location.protocol;
      return `${protocolStr}//staging-teach.ireadabc.com/fileUpload`;
    };
    obj.uploadData = function () {
      return {};
    };
    obj.beganRecording = function(){
      console.log("******beganRecording********");
    };
    obj.endRecording = function(callback){
      console.log("******endRecording********");
      callback&&callback("");
    };
    obj.speakPoints = function(audioUrl, evalText, callback){
      console.log("******speakPoints********");
      callback&&callback("");
    };
    obj.startRecord = function(){
      console.log("******startRecord********");
    };
    obj.stopRecord = function(callback){
      console.log("******stopRecord********");
      callback&&callback("");
    };
    obj.startTest = function(testText){
      console.log("******startTest********");
    };
    obj.stopTest = function(callback){
      console.log("******stopTest********");
      callback&&callback("");
    };
    obj.getTemplates = function(callback){
      callback&&callback("");
    };
    obj.getTemplateUrl = function(templateName, callback){
      const obj = {
        play_url: "",
        form_url: "",
      };
      callback&&callback(JSON.stringify(obj));
    };
    obj.sendEvent = function(evtName, data, key = ''){ 
      if(evtName==="reconnect"){
        console.error("reconnect是内置的断线重连事件名称，请勿使用此名称作为事件名");
        return;
      }
      if(evtName==="userchange"){
        console.error("userchange是内置的用户变更事件名称，请勿使用此名称作为事件名");
        return;
      }
      return;
    };
    obj.onEvent = function(evtName,callback){
      console.warn("==本地测试用，onEvent的监听事件会直接触发==", "事件名："+ evtName);
      callback && callback("", function(){});
    };
    obj.removeEvent = function(evtName){
      
    };
    obj.sendErrorLog = function (error) { 

    };
  }

  return obj;
})();

