// Learn cc.Class:
//  - https://docs.cocos.com/creator/manual/en/scripting/class.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

// import { getSprNode } from "./util";
import {
  onHomeworkFinish,
  getSprNode,
  playAudioByUrl,
  getScaleRateBy2Node,
  localPosTolocalPos,
  randomSortByArr,
  loadDragonBones,
  playAudio,
  showTrebleFirework,
  delayCall,
  removeFromArr,
  showBtnAnima,
  asyncDelay,
  jellyShake,
  showLog,
  formatTime,
  getSpriteFrimeByUrl,
  RandomInt,
  exchangeNodePos,
  getSprNodeByUrl,
  callMiddleLayerFunction
} from "../script/util";

cc.Class({
  extends: cc.Component,

  properties: {
    baseWidth: {
      default: 1280,
      type: cc.Integer,
    },
    baseHeight: {
      default: 940,
      type: cc.Integer,
    },
	videoControlBar: {
		default: null,
		type: cc.Node
	}
  },

  onLoad() {
    cc.debug.setDisplayStats(false);
    this.initSceneData();
    this.initSize();
    if (window && window["air"]) {
      window["air"].hideAirClassLoading();
    }
  },

  initSceneData() {
    this._imageResList = [];
    this._audioResList = [];
    this._animaResList = [];
  },

  _designSize: null,
  _frameSize: null,
  _mapScaleMin: null,
  _mapScaleMax: null,
  _cocosScale: null,
  canvas: null,
  initSize() {
    // 注意cc.winSize只有在适配后(修改fitHeight/fitWidth后)才能获取到正确的值,因此使用cc.getFrameSize()来获取初始的屏幕大小
    let screen_size =
      cc.view.getFrameSize().width / cc.view.getFrameSize().height;
    let design_size =
      cc.Canvas.instance.designResolution.width /
      cc.Canvas.instance.designResolution.height;
    let f = screen_size >= design_size;

    cc.Canvas.instance.fitHeight = f;
    cc.Canvas.instance.fitWidth = !f;

    const frameSize = cc.view.getFrameSize();
    this._frameSize = frameSize;

    this._designSize = cc.view.getDesignResolutionSize();

    let sx = cc.winSize.width / frameSize.width;
    let sy = cc.winSize.height / frameSize.height;
    this._cocosScale = Math.min(sx, sy);

    sx = frameSize.width / this._designSize.width;
    sy = frameSize.height / this._designSize.height;
    this._mapScaleMin = Math.min(sx, sy) * this._cocosScale;
    this._mapScaleMax = Math.max(sx, sy) * this._cocosScale;

    this.canvas = cc.find("Canvas");

    // cc.log('cc.Canvas: ', cc.Canvas);
  },

  isTeacher: null,
  serverAllUser: null,
  start() {
    const nextBtn = cc.find("middleLayer/BtnRight");
    if (nextBtn) {
      nextBtn.active = false;
    }

    let getData = this.getData.bind(this);
    if (window && window.courseware) {
      getData = window.courseware.getData;
    }
    getData((data, aspect) => {
      if (window["air"]?.airClassInfo?.user?.classRole == "tea") {
        this.isTeacher = true;
      }
      if (aspect) {
        console.log("aspect : ", aspect);
        this.serverAllUser = aspect.all_user;
        this.initPageData(aspect);
      }

      // this.initPageData({});

      this.data = data || this.getDefaultData();
      console.log("data:", this.data);
      console.log("dataStr:", JSON.stringify(this.data));

      this.preloadItem();
    });
  },

  // 用于存储公共数据 当翻页时清空
  pageData: null,
  initPageData(aspect) {
    const pageDataStr = aspect?.page_aspect?.pagedata;
    if (!pageDataStr) {
      this.pageData = {};
    } else {
      this.pageData = JSON.parse(pageDataStr);
    }
    console.log("this.pageData: ", this.pageData);
  },

  setPageData(key, value, isSend = true) {
    if (this.pageData) {
      console.log("this.pageData: ", this.pageData);

      this.pageData[key] = value;
      if (isSend) {
        this.sendPageData();
      }
    }
  },

  getPageData(key) {
    if (this.pageData && this.pageData[key] != null) {
      return this.pageData[key];
    }
  },

  sendPageData() {
    const data = this.pageData;
    if (window && window.courseware) {
      let storePageAspect = window.courseware.storePageAspect;
      if (storePageAspect) {
        storePageAspect(data);
        console.log("storePageAspect : ", data);
      }
    }
  },

  _imageResList: null,
  _audioResList: null,
  _animaResList: null,
  preloadItem() {
    this.addPreloadImage();
    this.addPreloadAudio(() => {
      this.preload();
    });
  },

  getData(func) {
    if (window && window.courseware) {
      window.courseware.getData(func, "ak_08");
      return;
    }

    const middleLayer = cc.find("middleLayer");
    if (middleLayer) {
      const middleLayerComponent = middleLayer.getComponent("middleLayer");
      middleLayerComponent.getData(func);
      return;
    }

    func(this.getDefaultData());
  },

  getDefaultData() {
    return {
      "quesArr": [
          {
              "itemType": "jump",
              "ques_end": "12",
              "ques_start": "0",
              "bgItem": {
                  "url": "http://staging-teach.cdn.ireadabc.com/50b1b7f2d7b1718b6daf00884d356119.png",
                  "rect": {
                      "x": 258.22,
                      "y": 0,
                      "width": 706.57,
                      "height": 451
                  }
              },
              "hotZoneItemArr": [
                  {
                      "id": "1668133708637",
                      "index": 0,
                      "itemType": "rect",
                      "fontScale": 0.95546875,
                      "imgScale": 1,
                      "imgSizeW": 0,
                      "imgSizeH": 0,
                      "mapScale": 0.95546875,
                      "dragDot": {
                          "x": 611.5,
                          "y": 225.5
                      },
                      "gIdx": "0",
                      "posX": 555.5,
                      "posY": 277.5,
                      "rect": {
                          "x": 262.78,
                          "y": 243,
                          "width": 69,
                          "height": 69
                      }
                  }
              ]
          },
          {
              "itemType": "jump",
              "ques_end": "29",
              "ques_start": "12",
              "bgItem": {
                  "url": "http://staging-teach.cdn.ireadabc.com/98b98a011abefb0f6d60fcf5fc5f6ac1.png",
                  "rect": {
                      "x": 258.22,
                      "y": 0,
                      "width": 706.57,
                      "height": 451
                  }
              },
              "hotZoneItemArr": [
                  {
                      "id": "1668134323523",
                      "index": 0,
                      "itemType": "rect",
                      "fontScale": 0.95546875,
                      "imgScale": 1,
                      "imgSizeW": 0,
                      "imgSizeH": 0,
                      "mapScale": 0.95546875,
                      "dragDot": {
                          "x": 611.5,
                          "y": 225.5
                      },
                      "gIdx": "0",
                      "posX": 484.5,
                      "posY": 189.5,
                      "rect": {
                          "x": 177.78,
                          "y": 141,
                          "width": 97,
                          "height": 97
                      }
                  }
              ]
          },
          {
              "itemType": "jump",
              "ques_start": "29",
              "ques_end": "55",
              "bgItem": {
                  "url": "http://staging-teach.cdn.ireadabc.com/feed50b453939eb1591b73e5d282bb98.png",
                  "rect": {
                      "x": 258.22,
                      "y": 0,
                      "width": 706.57,
                      "height": 451
                  }
              },
              "hotZoneItemArr": [
                  {
                      "id": "1668134374725",
                      "index": 0,
                      "itemType": "rect",
                      "fontScale": 0.95546875,
                      "imgScale": 1,
                      "imgSizeW": 0,
                      "imgSizeH": 0,
                      "mapScale": 0.95546875,
                      "dragDot": {
                          "x": 611.5,
                          "y": 225.5
                      },
                      "gIdx": "0",
                      "posX": 557.5,
                      "posY": 269.5,
                      "rect": {
                          "x": 253.78,
                          "y": 224,
                          "width": 91,
                          "height": 91
                      }
                  }
              ]
          },
          {
              "itemType": "jump",
              "ques_start": "55",
              "ques_end": "65",
              "bgItem": {
                  "url": "http://staging-teach.cdn.ireadabc.com/30ef6004735117f09f7f689e5118b45a.png",
                  "rect": {
                      "x": 258.22,
                      "y": 0,
                      "width": 706.57,
                      "height": 451
                  }
              },
              "hotZoneItemArr": [
                  {
                      "id": "1668134384739",
                      "index": 0,
                      "itemType": "rect",
                      "fontScale": 0.95546875,
                      "imgScale": 1,
                      "imgSizeW": 0,
                      "imgSizeH": 0,
                      "mapScale": 0.95546875,
                      "dragDot": {
                          "x": 611.5,
                          "y": 225.5
                      },
                      "gIdx": "0",
                      "posX": 837.5,
                      "posY": 183.5,
                      "rect": {
                          "x": 534.78,
                          "y": 139,
                          "width": 89,
                          "height": 89
                      }
                  }
              ]
          },
          {
              "itemType": "jump",
              "ques_end": "82",
              "ques_start": "65",
              "bgItem": {
                  "url": "http://staging-teach.cdn.ireadabc.com/c45dc1e2f2c7cc43e50b0f682c575a75.png",
                  "rect": {
                      "x": 258.22,
                      "y": 0,
                      "width": 706.57,
                      "height": 451
                  }
              },
              "hotZoneItemArr": [
                  {
                      "id": "1668134393657",
                      "index": 0,
                      "itemType": "rect",
                      "fontScale": 0.95546875,
                      "imgScale": 1,
                      "imgSizeW": 0,
                      "imgSizeH": 0,
                      "mapScale": 0.95546875,
                      "dragDot": {
                          "x": 611.5,
                          "y": 225.5
                      },
                      "gIdx": "0",
                      "posX": 705.5,
                      "posY": 211.5,
                      "rect": {
                          "x": 399.78,
                          "y": 164,
                          "width": 95,
                          "height": 95
                      }
                  }
              ]
          },
          {
              "itemType": "jump",
              "ques_end": "110",
              "ques_start": "82",
              "bgItem": {
                  "url": "http://staging-teach.cdn.ireadabc.com/99bdeb87ff53a23e04a4d193af0e114d.png",
                  "rect": {
                      "x": 258.22,
                      "y": 0,
                      "width": 706.57,
                      "height": 451
                  }
              },
              "hotZoneItemArr": [
                  {
                      "id": "1668134406640",
                      "index": 0,
                      "itemType": "rect",
                      "fontScale": 0.95546875,
                      "imgScale": 1,
                      "imgSizeW": 0,
                      "imgSizeH": 0,
                      "mapScale": 0.95546875,
                      "dragDot": {
                          "x": 611.5,
                          "y": 225.5
                      },
                      "gIdx": "0",
                      "posX": 420.5,
                      "posY": 260.5,
                      "rect": {
                          "x": 122.78,
                          "y": 221,
                          "width": 79,
                          "height": 79
                      }
                  }
              ]
          }
      ],
      "videoType": "940_600",
      "video_url": "http://staging-teach.cdn.ireadabc.com/527fe2dc673ff50393f55b5e8dbc0e25.mp4"
  };
  },

  preload() {
    const preloadArr = this._imageResList
      .concat(this._audioResList)
      .concat(this._animaResList);
    console.log("preloadArr:  ", JSON.stringify(preloadArr));
    cc.assetManager.loadAny(preloadArr, null, null, (err, data) => {
      // console.log(' preload data, ', data);
      // this.loadEnd();
      this.addServerListener();
      if (window && window["air"]) {
        window["air"].hideAirClassLoading();
      }
    });
  },

  addPreloadImage() {
    const quesArr = this.data.quesArr;
    if (!quesArr || quesArr.length == 0) {
      return;
    }

    for (let i = 0; i < quesArr.length; i++) {
      const item = quesArr[i];

      if (item.bgItem) {
        this._imageResList.push({ url: item.bgItem.url });
      }

      if (!item.hotZoneItemArr) {
        continue;
      }
      item.hotZoneItemArr.forEach((value) => {
        this._imageResList.push({ url: value.pic_url | "" });
        this._imageResList.push({ url: value.pic2_url | "" });
      });
    }
  },

  addPreloadAudio(callback) {
    const url1 = this.data.video_url;
    if (!url1) {
      callback();
      return;
    }

    this.getVideoUrl((url) => {
      console.log("url: ", url);
      this.data.video_url = url;
      this._audioResList.push({ url: url || "" });

      callback();
    });
  },

  addPreloadAnima() {
    // if (!this.data.hotZoneItemArr) {
    // 	return;
    // }
    // this.data.hotZoneItemArr.forEach((item) => {
    // 	if (item.skeJsonData) {
    // 		this._animaResList.push({ url: item.skeJsonData.url || '' });
    // 		this._animaResList.push({ url: item.texJsonData.url || '' });
    // 		this._animaResList.push({ url: item.texPngData.url || '' });
    // 	}
    // })
  },

  loadEnd(cb) {
    console.log(" in loadEnd ");
    if (this.isDestroy) {
      return;
    }

    // this.initData();

    // this.initView();

    // this.initListener();

    // cb();

    // return;

    this.initData();
    this.initMask();
    this.showHideProgressBar();
    this.getState(() => {
      this.initView();
      this.initListener();
      callMiddleLayerFunction("PSQS_hide_rabbit", {}, () => {});
      cb();
    });
  },

  isFirst: null,
  isLast: null,
  playTimes: null,
  jumpData: null,
  getState(cb) {
    // this.isFirst = this.checkIsFirst(); // data.first; //this.checkIsFirst();
    // this.isLast = this.checkIsLast(); // data.last // this.checkIsLast();
    // this.playTimes = this.checkPlayTimes(); // data.playTime// this.checkPlayTimes();
    // this.jumpData = this.getJumpData(); //data.saveData // this.getJumpData();
    // let saveData = this.getJumpData()
    // if(saveData == null) {
    //   this.jumpData = {step: 0}
    // } else {
    //   saveData.step++;
    //   this.jumpData = saveData;
    // }
    // console.log("PSQS_get_course_info",this.isFirst, this.isLast, this.playTimes, this.jumpData.step);
    // cb();
    // return;

    console.log(" in getState 1");
    callMiddleLayerFunction("PSQS_get_course_info", {}, (data) => {
      this.isFirst = data.first; //this.checkIsFirst();
      this.isLast = data.last // this.checkIsLast();
      this.playTimes = data.playTime// this.checkPlayTimes();
      if(data.saveData == null) {
        this.jumpData = {step: 0}
      } else {
        data.saveData.step++;
        this.jumpData = data.saveData;
      }

      if (this.data.isDebug) {
        this.playTimes += 1;
      }

      console.log("PSQS_get_course_info",this.isFirst, this.isLast, this.playTimes, this.jumpData.step);

      cb && cb();
    });
  },

  checkIsFirst() {
    return true;
  },

  checkIsLast() {
    return true;
  },

  checkPlayTimes() {
    return 0;
  },

  getJumpData() {
    return;// {"step":5};
  },

  maskSpr: null,
  initMask() {
    const mask = getSprNode("black");
    const sx = this.canvas.width / mask.width;
    const sy = this.canvas.height / mask.height;
    mask.scaleX = sx;
    mask.scaleY = sy;
    mask.opacity = 255;
    this.canvas.addChild(mask, 21);
    this.maskSpr = mask;
  },

  initMusic() {
    cc.assetManager.loadRemote(this.data.bg_audio_url, (err, clip) => {
      cc.audioEngine.setMusicVolume(0.3);
      const audioID = cc.audioEngine.playMusic(clip, true);
    });
  },

  isDebug: null,

  treeType: null,
  treeTypeArr: null,
  typeIndex: null,

  btnArr: null,
  fruitArr: null,
  modelLevel: null,

  STATE_STOP: null,
  STATE_PLAYING: null,
  STATE_PAUSE: null,
  isSupportRecord: null,
  readyStartTime: null,
  readyEndTime: null,

  audioObj: null,

  isFirstVideoPlayEnd: null,

  isLocal: null,
  initData() {
    this.isLocal = false;
    this.quesIndex = 0;
    this.curEndTime = -1;

    this.dragEndRectArr = [];

    if (this.data.jumpTime) {
      this.jumpTime = Number(this.data.jumpTime);
    }

    this.initAudioEffect();
  },

  setProgressBarMarkPoints() {
	let points = [];
	for(let i=0;i<this.data.quesArr.length;i++) {
		const endTime = Number(this.data.quesArr[i].ques_end)
		points.push(endTime / this.videoDuration)
	}
	this.videoControlBar.emit("set_mark_points", points)
  },

  resetQuesIndex(jumpTime) {
    this.quesIndex = -1;
    for (let i = 0; i < this.data.quesArr.length; i++) {
      const startTime = this.data.quesArr[i].ques_start;
      const endTime = this.data.quesArr[i].ques_end;
      if (Number(jumpTime) >= Number(startTime) && Number(jumpTime) < Number(endTime)) {
        this.quesIndex = i;
		    console.log("重定位题号：",this.quesIndex)
      }
    }
  },

  audioGoodjob: null,
  audioTryagain: null,
  readyClip: null,
  goClip: null,
  goodjobClip: null,
  initAudioEffect() {
    const audioNode = cc.find("Canvas/res/audio");

    const getAudioByResName = (resName) => {
      return audioNode.getChildByName(resName).getComponent(cc.AudioSource)
        .clip;
    };

    // this.audioGoodjob = getAudioByResName('goodjob');
    // this.audioTryagain = getAudioByResName('tryagain');

    this.readyClip = getAudioByResName("ready");
    this.goClip = getAudioByResName("go");
    this.goodjobClip = getAudioByResName("goodjob");
  },

  sendServerEvent(key, data) {
    const c = window.courseware;
    if (c) {
      c.sendEvent(key, data);
    }
  },

  addServerListener() {
    console.log(" in addServerListener");

    // this.loadEnd(()=>{});
    const c = window.courseware;
    if (!c) {
      return;
    }

    if (!window.air) {
      console.log(" window air err !!!!!!!!");
      return;
    }

    window.air.onCourseInScreen = (next) => {
      //各种逻辑
      // this.showTemplateStartAnima();
      this.loadEnd(() => {
        next();
      });
    };
  },

  initView() {
    console.log(" in initView");
    this.hideMask();

    this.initVideo();
    this.initHand();

    this.initHotZone();
  },

  initHand() {
    this.hand = cc.find("Canvas/hand");
    this.hand.active = false;
  },

  initStartView() {
    this.showStartLight();
    if (this.playTimes > 0) {
      this.showStartTitleGo();
    } else {
      this.showStartTitleReady();
    }
  },

  lightBg: null,
  lightLeft: null,
  lightRight: null,
  showStartLight() {
    const lightBg = getSprNode("black");
    lightBg.scaleX = this.canvas.width / lightBg.width;
    lightBg.scaleY = this.canvas.height / lightBg.height;
    lightBg.opacity = 180;
    this.canvas.addChild(lightBg, 10);

    const lightLeft = getSprNode("light");
    lightLeft.anchorY = 0.9;
    lightLeft.x = -this.canvas.width / 2;
    lightLeft.y = this.canvas.height / 2;
    lightLeft.scale = this._mapScaleMin;
    lightLeft.zIndex = 10;
    lightLeft.parent = this.canvas;
    lightLeft.rotation = 45;
    lightLeft.opacity = 0;
    cc.tween(lightLeft)
      .to(1, { rotation: -45 }, { easing: "cubicOut" })
      .start();
    cc.tween(lightLeft).to(0.5, { opacity: 255 }).start();

    const lightRight = getSprNode("light");
    lightRight.anchorY = 0.9;
    lightRight.x = this.canvas.width / 2;
    lightRight.y = this.canvas.height / 2;
    lightRight.scale = this._mapScaleMin;
    lightRight.zIndex = 10;
    lightRight.parent = this.canvas;
    lightRight.rotation = -45;
    lightRight.opacity = 0;
    cc.tween(lightRight)
      .to(1, { rotation: 45 }, { easing: "cubicOut" })
      .start();
    cc.tween(lightRight).to(0.5, { opacity: 255 }).start();

    this.lightBg = lightBg;
    this.lightLeft = lightLeft;
    this.lightRight = lightRight;
  },

  title: null,
  showStartTitleReady() {
    const title = getSprNode("start_title");
    title.scale = this._mapScaleMin;
    title.y = this.canvas.height / 2 + title.height * title.scaleY;
    title.parent = this.canvas;
    title.zIndex = 11;

    cc.tween(title)
      .delay(0.3)
      .call(() => {
        playAudio(this.readyClip, () => {
          this.startAudioEnd();
        });
      })
      .to(1.5, { y: 0 }, { easing: "elasticOut" })
      .start();

    this.title = title;
  },

  async showStartTitleGo() {
    const title = new cc.Node();
    title.parent = this.canvas;
    title.zIndex = 11;
    title.scale = this._mapScaleMin;
    this.title = title;

    playAudio(this.goClip, () => {
      this.startAudioEnd();
    });

    const popNum = (name, time = 1) => {
      const sprNode = getSprNode(name);
      title.addChild(sprNode);
      sprNode.scale = 0.2;
      sprNode.opacity = 0;

      cc.tween(sprNode)
        .to(time / 10, { opacity: 255 })
        .start();

      cc.tween(sprNode)
        .to(0.8 * time, { scale: this._mapScaleMin }, { easing: "elasticOut" })
        .delay(0 * time)
        .to(0.2 * time, { opacity: 0 })
        .start();
    };

    await asyncDelay(2.2);

    popNum("go_1", 0.7);
    await asyncDelay(0.7);
    popNum("go_2", 0.7);
    await asyncDelay(0.7);
    popNum("go_3", 0.7);
    await asyncDelay(0.7);
    popNum("go_0");
    await asyncDelay(1);
  },

  isDestroy: null,
  startAudioEnd() {
    if (this.isDestroy) {
      return;
    }
    this.hideStartView();
  },

  async hideStartView() {
    const hideSpr = (sprNode, cb = null) => {
      cc.tween(sprNode)
        .to(0.3, { opacity: 0 })
        .call(() => {
          sprNode.active = false;
          cb && cb();
        })
        .start();
    };

    hideSpr(this.lightLeft);
    hideSpr(this.lightRight);
    hideSpr(this.title);

    await asyncDelay(0.2);
    hideSpr(this.lightBg, () => {
      if (this.isDestroy) {
        return;
      }

      this.startQuesVideo();
    });
  },

  serverStartTest(text) {
    console.log(" in serverStartTest: ", text);
    const cw = window?.courseware;
    if (cw) {
      if (this.curQues.isKK && this.curQues.KKText) {
        cw.startTest(text, { pronounce: this.curQues.KKText });
      } else {
        cw.startTest(text);
      }
    }
    this.addMask();
  },

  hideMask(cb = null) {
    const mask = this.maskSpr;
    mask.opacity = 255;

    cc.tween(mask)
      .to(0.2, { opacity: 0 }, { easing: "sineOut" })
      .call(() => {
        // mask.active = false;
        cb && cb();
      })
      .start();
  },

  serverStopTest(item) {
    const cw = window?.courseware;
    if (cw) {
      cw.stopTest((data) => {
        console.log("stopTest data: ", data);

        if (data && typeof data == "string") {
          console.log(JSON.parse(data));
          data = JSON.parse(data);
        }

        this.setRecordItemAudio(data, item);
      });
    }
  },

  setRecordItemAudio(data, item) {
    if (!data) {
      return;
    }

    const audioUrl = data.audioUrl;
    item.audioUrl = audioUrl;

    const overall = data.result?.overall;
    const integrity = data.result?.integrity;
    const score = integrity * 0.1 + overall * 0.9; //data.result?.overall;
    // item.score = score;
    console.log("overall is : ", overall);
    console.log("integrity is : ", integrity);
    console.log("score is : ", score);

    item.score = score;

    console.log(" score: ", score);
    this.hideMask();

    this.video.pause();
	  this.videoControlBar.emit("update_video_status", 0);

    this.wrongTimes++;

    if (this.wrongTimes >= 3) {
      this.startEndVideo();
    } else {
      if (score >= 60) {
        this.startRightVideo();
      } else {
        this.startWrongVideo();
      }
    }
  },

  initVideo() {
    // this.initQuesList();
    this.initCurQues();

    // this.getVideoUrl((url) => {
    this.initVideoRemote();
    // })
    // this.checkStart();
  },

  // 设置视频背景
  initVideoBg(width, height, scale) {
    console.log("视频尺寸", width, height,scale);
    const bgNode = cc.find('Canvas/video_bg')
    bgNode.width = width*scale;
    bgNode.height = height*scale;
  },

  getVideoUrl(callback) {
    const url1 = this.data.video_url;
    const url2 = url1.replace(/.mp4$/g, "_m.mp4");

    this.httpHeadCall(url2, (success) => {
      if (success) {
        console.log("return url2: ", url2);
        callback(url2);
      } else {
        console.log("return url1: ", url1);
        callback(url1);
      }
    });
  },

  checkStart() {
    console.log(" in checkStart ..", this.curQues);
    const data = this.curQues;
    const videoNode = data?.videoObj?.ques_video;

    if (videoNode.isLoadEnd) {
      this.startQuesVideo();
    } else {
      delayCall(0.2, () => {
        this.checkStart();
      });
    }
  },

  gameEnd() {
    console.log(" in gameEnd");
    this.showRestart();

    const data = this.getHomeworkFinishData();
    console.log("homeworkData: ", JSON.stringify(data));
    onHomeworkFinish(data);
  },

  getHomeworkFinishData() {
    const arr = this.data.quesArr;
    const result = [];
    for (let i = 0; i < arr.length; i++) {
      const oneData = {};
      oneData.type = arr[i].itemType;

      if (oneData.type == "sound") {
        oneData.word = arr[i].text;
        oneData.audio_url = arr[i].audioUrl;
        oneData.score = arr[i].score;
      } else {
        oneData.is_right = arr[i].isRight;
      }

      result.push(oneData);
    }

    return { result };
  },

  getCurrentQuesIndexByTime(curretnTime) {
    let qIndex = -1;
    for(let i=0; i<this.data.quesArr.length; i++) {
      if(curretnTime>=Number(this.data.quesArr[i].ques_end)) {
        qIndex = i;
      }
    }
    return qIndex;
  },

  checkNextQues() {
    this.quesIndex++;
    this.initCurQues();
    if (!this.curQues) {
      this.gameEnd();
    } else {
      this.startQuesVideo();
    }
  },

  startQuesVideo(currentTime = null) {
    // currentTime = "110";
    console.log("in startQuesVideo", currentTime);
    this.wrongTimes = 0;

    const video = this.video;
    video.node.name = "ques_video";

    console.log("this.curQues: ", this.curQues);

    if (currentTime) {
      video.currentTime = Number(currentTime);
    } else {
      video.currentTime = Number(this.curQues.ques_start);
    }

    if (this.playTimes > 0) {
      if (this.curQues) {
        this.curEndTime = Number(this.curQues.ques_end);
      }
    }

    // 如果是最后一题
    if(this.isTheEndVideo) {
      this.curEndTime = -1;
    }

    delayCall(0.01, () => {
      video.play();
	    this.videoControlBar.emit("update_video_status", 1);
    });
  },

  isWaitingUserAction: false,
  startWaitVideo() {
    console.log("in startWaitVideo");
	  this.isWaitingUserAction = true;
    this.curQues.hotZoneBg.active = true;
    this.hand.active = true;

    this.hand.x = this.curQues.hotZoneBg.handX;
    this.hand.y = this.curQues.hotZoneBg.handY;

    return;
    // const videoNode = this.curQues?.videoObj?.wait_video;
    // const video = videoNode.getComponent(cc.VideoPlayer);
    // video.node.name = 'wait_video';
    // video.play();

    // this.curVideo = video;
    // this.resetVideoPos(videoNode);

    const video = this.video;
    video.node.name = "wait_video";
    video.currentTime = Number(this.curQues.wait_start);
    this.curEndTime = Number(this.curQues.wait_end);
    delayCall(0.01, () => {
      video.play();
	  this.videoControlBar.emit("update_video_status", 1);
    });

    if (this.curQues.itemType == "sound") {
      this.serverStartTest(this.curQues.text);
      delayCall(3, () => {
        this.serverStopTest(this.curQues);
      });
    } else {
      this.curQues.hotZoneBg.active = true;
    }
  },

  hideWaitingVideo() {
    console.log(" in hiddeWaitVideo ");
    this.isWaitingUserAction = false;
    this.curQues.hotZoneBg.active = false;
    this.hand.active = false;
  },

  continueWaitVideo() {
    console.log(" in continueWaitVideo ");

    this.video.currentTime = Number(this.curQues.wait_start);
    this.curEndTime = Number(this.curQues.wait_end);

    delayCall(0.01, () => {
      this.video.play();
	  this.videoControlBar.emit("update_video_status", 1);
    });
  },

  startRightVideo() {
    console.log("in startRightVideo");

    // const videoNode = this.curQues?.videoObj?.right_video;
    // const video = videoNode.getComponent(cc.VideoPlayer);
    // video.node.name = 'right_video';
    // video.play();

    // this.curVideo = video;
    // this.resetVideoPos(videoNode);

    const video = this.video;
    video.node.name = "right_video";
    video.currentTime = Number(this.curQues.right_start);
    this.curEndTime = Number(this.curQues.right_end);

    delayCall(0.01, () => {
      video.play();
	  this.videoControlBar.emit("update_video_status", 1);
    });
  },

  startWrongVideo() {
    console.log("in startWrongVideo");

    // const videoNode = this.curQues?.videoObj?.wrong_video;
    // const video = videoNode.getComponent(cc.VideoPlayer);
    // video.node.name = 'wrong_video';
    // video.play();

    // this.curVideo = video;
    // this.resetVideoPos(videoNode);

    const video = this.video;
    video.node.name = "wrong_video";

    if (this.wrongStartTime && this.wrongEndTime) {
      video.currentTime = this.wrongStartTime;
      this.curEndTime = this.wrongEndTime;
    } else {
      video.currentTime = Number(this.curQues.wrong_start);
      this.curEndTime = Number(this.curQues.wrong_end);
    }

    delayCall(0.01, () => {
      video.play();
	  this.videoControlBar.emit("update_video_status", 1);
    });
  },

  startEndVideo() {
    console.log("in startEndVideo");

    // const videoNode = this.curQues?.videoObj?.end_video;
    // const video = videoNode.getComponent(cc.VideoPlayer);
    // video.node.name = 'end_video';
    // video.play();

    // this.curVideo = video;
    // this.resetVideoPos(videoNode);

    if (!this.curQues.end_start) {
      this.checkNextQues();
      return;
    }

    const video = this.video;
    video.node.name = "end_video";
    video.currentTime = Number(this.curQues.end_start);
    this.curEndTime = Number(this.curQues.end_end);
    delayCall(0.01, () => {
      video.play();
	  this.videoControlBar.emit("update_video_status", 1);
    });
  },

  resetVideoPos(videoNode) {
    if (this.lastVideo) {
      // this.lastVideo.y = -this.canvas.height * 1.5;
      this.lastVideo.x = this.lastVideo.baseX;
      this.lastVideo.y = this.lastVideo.baseY;
    }

    videoNode.x = 0;
    videoNode.y = 0;
    this.lastVideo = videoNode;
  },

  initCurQues() {
    if(this.quesIndex >= 0) {
      this.curQues = this.data.quesArr[this.quesIndex];
      console.log("curQues: ", this.curQues);
    } else {
      this.curQues = this.data.quesArr[this.data.quesArr.length-1];
      console.log('题目序号为负 - 跳转到最后一段音频');
    }
  },

  videoDuration: null,
  initVideoRemote() {
    const url = this.data.video_url;

    console.log(" in initVideoRemote url: ", url);

    const videoConfigSize = this.data.videoType.split('_');
    let videoSizeW = 1920;
    let videoSizeH = 1080;
    if(videoConfigSize.length ==2 && !isNaN(Number(videoConfigSize[0])) && !isNaN(Number(videoConfigSize[1]))) {
      videoSizeW = Number(videoConfigSize[0]);
      videoSizeH = Number(videoConfigSize[1]);
    }

    const scale = this.canvas.height / videoSizeH;
    this.initVideoBg(videoSizeW, videoSizeH, scale);
  
    const videoRemoteNode = new cc.Node();
    videoRemoteNode.width = videoSizeW;
    videoRemoteNode.height = videoSizeH;
    videoRemoteNode.parent = this.canvas;
    // videoRemoteNode.y = -this.canvas.height * 1.5;

    videoRemoteNode.scale = scale;

    const video = videoRemoteNode.addComponent(cc.VideoPlayer);
    video.resourceType = cc.VideoPlayer.ResourceType.REMOTE;
    video.remoteURL = url;

    // video.isFullscreen = true;
    video.stayOnBottom = true;

    this.video = video;
	
    video.node.on("meta-loaded", (e) => {
      console.log("meta-loaded e:", e);
    });
    video.node.on("ready-to-play", async (e) => {
      console.log("e: ", e);
      if (this.isDestroy) {
        return;
      }

      video.play();
      checkIsPlaying();
    });

    const checkIsPlaying = () => {
      delayCall(0.05, () => {
        if (video.currentTime > 0) {
          video.node.isLoadEnd = true;
          video.pause();

          this.videoLoadEnd();

          // this.startQuesVideo();
        } else {
          checkIsPlaying();
        }
      });
    };

    video.node.on("completed", () => {
      console.log(" in completed!!!!");

      if (this.isLast && this.playTimes > 0) {
        this.showGoodjob();
      } else {
        this.showMask(() => {
          if (!this.isLocal) {
            callMiddleLayerFunction("PSQS_play_animate_over", null, () => {});
          }
        });
      }

      // this.curVideoPlayEnd();
    });

    return video.node;
  },

  showGoodjob() {
    const goodjob = cc.find("Canvas/goodjob");
    goodjob.zIndex = 15;
    goodjob.active = true;
    goodjob.scale = this._mapScaleMin;

    const dragonDisplay = goodjob.getComponent(dragonBones.ArmatureDisplay);
    dragonDisplay.playAnimation("newAnimation", 1);

    playAudio(this.goodjobClip, async () => {
      await asyncDelay(3);
      console.log(" end .....");
      this.showMask(() => {
        if (!this.isLocal) {
          callMiddleLayerFunction("PSQS_play_animate_over", null, () => {});
        }
      });
    });
  },

  getColorRect(w, h) {
    const node = new cc.Node();
    const ctx = node.addComponent(cc.Graphics);
    ctx.fillRect(0, 0, w, h);
    ctx.fillColor = cc.Color.GREEN;
    ctx.fill();
    return node;
  },

  videoLoadEnd() {
    this.videoDuration = this.video.getDuration();
    
    if (this.jumpData) {
      console.log(this.jumpData)
      this.setJumpTime();
    }

    // 时长获取到以后 可以计算题目点
    this.setProgressBarMarkPoints();

    // 设置进度条的起始和结束标签
    this.videoControlBar.emit("set_start_end_label", "00:00", this.getEndTimeLabel(this.videoDuration))

    if (this.jumpTime) {
      this.resetQuesIndex(this.jumpTime);
      this.initCurQues();
    } else if (this.isFirst) {
      this.initStartView();
      return;
    }

    this.startQuesVideo(this.jumpTime);
  },

  isTheEndVideo: false,
  setJumpTime() {
    let isFind = false;
    for (let i = 0; i < this.data.quesArr.length; i++) {
      const id = i;
      if (id == this.jumpData.step) {
        const quesData = this.data.quesArr[i];
        this.jumpTime = Number(quesData.ques_start);
        isFind = true;
        break;
      }
    }

    if (!isFind) {
      // 没有找到就是最后一题
      const lastQuesData = this.data.quesArr[this.data.quesArr.length - 1];
      this.jumpTime = lastQuesData.ques_end;
      this.isTheEndVideo = true;
      console.log("没有找到开始时间:", this.jumpTime)
    } else {
      console.log("找到开始时间:", this.jumpTime); 
    }
  },

  //秒数转化为时分秒
  getEndTimeLabel(value) {
    var secondTime = parseInt(value);// 秒
    var minuteTime = 0;// 分
    var hourTime = 0;// 小时
    if(secondTime > 60) {//如果秒数大于60，将秒数转换成整数
        //获取分钟，除以60取整数，得到整数分钟
        minuteTime = parseInt(secondTime / 60);
        //获取秒数，秒数取余，得到整数秒数
        secondTime = parseInt(secondTime % 60);
        //如果分钟大于60，将分钟转换成小时
        if(minuteTime > 60) {
            //获取小时，获取分钟除以60，得到整数小时
            hourTime = parseInt(minuteTime / 60);
            //获取小时后取余的分，获取分钟除以60取余的分
            minuteTime = parseInt(minuteTime % 60);
        }
    }
    var result = "" + parseInt(secondTime);

    if(minuteTime > 0) {
      result = "" + parseInt(minuteTime) + ":" + result;
    }
    if(hourTime > 0) {
      result = "" + parseInt(hourTime) + ":" + result;
    }
    
    return result;
  },

  curVideoPlayEnd() {
    if (this.playTimes == 0) {
      return;
    }
    switch (this.video.node.name) {
      case "ques_video":
        this.startWaitVideo();
        break;
      case "wait_video":
        this.continueWaitVideo();
        break;
      case "right_video":
        this.startEndVideo();
        // this.checkNextQues();
        break;
      case "wrong_video":
        if (this.curQues.itemType == "sound") {
          this.startWaitVideo();
        } else {
          this.checkNextQues();
        }
        break;
      case "end_video":
        this.checkNextQues();
        break;
    }
  },

  showMask(cb) {
    const mask = this.maskSpr;
    mask.opacity = 0;

    cc.tween(mask)
      .to(0.2, { opacity: 255 }, { easing: "sineIn" })
      .call(() => {
        cb && cb();
      })
      .start();
  },

  showRestart() {
    // this.setCurTipAudioUrl(this.data.finish_audio_url);

    const circle = getSprNode("bg_circle");
    // circle.x = this.canvas.width / 4;
    this.canvas.addChild(circle, 5);

    cc.tween(circle)
      .set({ scale: 0.8, opacity: 255 })
      .to(2, { scale: 1.2, opacity: 0 })
      .union()
      .repeatForever()
      .start();

    const btn = getSprNode("btn_restart");
    this.canvas.addChild(btn, 6);
    btn.x = circle.x;

    circle.on("touchstart", () => {
      this.replay();
    });
  },

  replay() {
    const middleLayer = cc.find("middleLayer");
    if (middleLayer) {
      middleLayer.getComponent("middleLayer").reloadBundle();
    }
  },

  refreshVideoTimeLabel() {
    const currentTime = this.muteVideoPlayer.currentTime;
    this.curTimeLabel.string = formatTime(
      "mm:ss",
      new Date(currentTime * 1000)
    );
  },

  refreshItemTimeLabel(item) {
    const currentTime = this.videoPlayer.currentTime;
    this.curTimeLabel.string = formatTime(
      "mm:ss",
      new Date(currentTime * 1000)
    );
  },

  updateCheckStop() {
	  // console.log("检查停止时间", this.curEndTime);
    if (!this.video || this.curEndTime == -1) {
      return;
    }

    if (this.video.currentTime >= this.curEndTime) {
      this.video.pause();
	    this.videoControlBar.emit("update_video_status", 0);
      this.video.currentTime = this.curEndTime;
      this.curEndTime = -1;
      this.curVideoPlayEnd();
	    // this.videoControlBar.active = false;
    }
  },

  update() {
    if (this.isDestroy) {
      return;
    }
	
    // 更新当前进度条
    if(this.videoDuration== null) {
      this.videoControlBar.emit("update_video_progress", 0)
    } else {
      this.videoControlBar.emit("update_video_progress", this.video.currentTime / this.videoDuration)
    }

    // 如果没有正在拖动中 检查是否为题目停止
    if(!this.isDragProgressBar) {
      this.updateCheckStop();
    }
  },
  
  // 重置题目相关数据 - 在用户拖动进度条完成以后
  restQuesData(curretnTime) {
    let userDragTime = curretnTime;
    this.resetQuesIndex(userDragTime);
    this.initCurQues();
    if(this.quesIndex >= 0) {
      this.curEndTime = Number(this.curQues.ques_end);
    } else {
      // 如果没有找到题目索引 则把当前截止时间设置为无穷大
      this.curEndTime = -1;
    }
    this.video.currentTime = userDragTime;
  },

  // 是否正在拖动进度条 
  isDragProgressBar: false,
  initListener() {
    const canvas = cc.find("Canvas");

    let downFlag = false;

    const touchStart = (e) => {
      this.canvasTouchStart(e);
      // console.log("touch start");
      if(e.target.name != "VideoControlBar" && e.target.name != "dragButton") {
        this.showHideProgressBar(true);
      }

      if (canvas.hasEventListener(cc.Node.EventType.MOUSE_DOWN)) {
        canvas.off(cc.Node.EventType.MOUSE_DOWN, mouseDown);
      }
    };

    const mouseDown = (e) => {
      if (!downFlag) {
        return;
      }
      this.canvasTouchStart(e);
      // console.log("mouse down");
      if(e.target.name != "VideoControlBar" && e.target.name != "dragButton") {
        this.showHideProgressBar(true);
      }

      if (canvas.hasEventListener(cc.Node.EventType.TOUCH_MOVE)) {
        canvas.off(cc.Node.EventType.TOUCH_MOVE, touchMove);
        this.removeHtmlCanvasListener("touchmove");
      }
    };

    const touchMove = (e) => {
      this.canvasTouchMove(e);
      // console.log('touch move');

      if (canvas.hasEventListener(cc.Node.EventType.MOUSE_MOVE)) {
        canvas.off(cc.Node.EventType.MOUSE_MOVE, mouseMove);
      }
    };

    const mouseMove = (e) => {
      if (!downFlag) {
        return;
      }
      this.canvasTouchMove(e);
      console.log("mouse move");

      if (canvas.hasEventListener(cc.Node.EventType.TOUCH_MOVE)) {
        canvas.off(cc.Node.EventType.TOUCH_MOVE, touchMove);
        this.removeHtmlCanvasListener("touchmove");
      }
    };

    const touchEnd = (e) => {
      downFlag = false;
      this.canvasTouchEnd(e);

      if (canvas.hasEventListener(cc.Node.EventType.MOUSE_UP)) {
        canvas.off(cc.Node.EventType.MOUSE_UP, mouseUp);
      }
      if (canvas.hasEventListener(cc.Node.EventType.MOUSE_LEAVE)) {
        canvas.off(cc.Node.EventType.MOUSE_LEAVE, mouseUp);
      }
      this.removeHtmlTouchEnd();
    };

    const mouseUp = (e) => {
      downFlag = false;

      this.canvasTouchEnd(e);

      if (canvas.hasEventListener(cc.Node.EventType.TOUCH_END)) {
        canvas.off(cc.Node.EventType.TOUCH_END, touchEnd);
      }
      if (canvas.hasEventListener(cc.Node.EventType.TOUCH_CANCEL)) {
        canvas.off(cc.Node.EventType.TOUCH_CANCEL, touchEnd);
      }
    };

    canvas.on(cc.Node.EventType.TOUCH_START, touchStart);
    canvas.on(cc.Node.EventType.MOUSE_DOWN, mouseDown);

    canvas.on(cc.Node.EventType.TOUCH_MOVE, touchMove);
    canvas.on(cc.Node.EventType.MOUSE_MOVE, mouseMove);

    canvas.on(cc.Node.EventType.TOUCH_END, touchEnd);
    canvas.on(cc.Node.EventType.TOUCH_CANCEL, touchEnd);
    canvas.on(cc.Node.EventType.MOUSE_UP, mouseUp);

    // 监听组件发来的拖动开始和结束消息
    this.videoControlBar.on("on_drag_button", (isDragStart)=>{
      if(isDragStart) {
        this.hideWaitingVideo();
        this.isDragProgressBar = true;
        this.video.pause();
        this.videoControlBar.emit("update_video_status", 0);
        this.cleanProgressBarTimer();
      } else {
        this.restQuesData(this.video.currentTime);
        this.isDragProgressBar = false;
        this.video.play();
        this.videoControlBar.emit("update_video_status", 1);
        this.setProgressBarTimer();
      }
    })

    // 监听组件发来的拖动百分比
    this.videoControlBar.on("on_drag_percent", (percent)=>{
      this.video.currentTime = percent * this.videoDuration;
      this.showProgressBar();
    })

    // 监听组件发来视频播放、暂停事件
    this.videoControlBar.on("video_btn_click", (isPlay)=>{
      this.cleanProgressBarTimer();
      this.setProgressBarTimer();
      if(isPlay) {
        if(this.isWaitingUserAction) {
          this.hideWaitingVideo();
          this.restQuesData(this.video.currentTime);
        }
        this.video.play();
      } else {
        this.video.pause();
      }
    })

    this.videoControlBar.on("on_touch_progressbar", (e)=>{
      console.log("Click bar")
      this.showProgressBar();
    })
  },

  // 显示进度条 2秒没有操作后消失
  // 进度条是否正在显示
  isShowProgressBar: null,
  // 隐藏进度条定时器
  timeoutHideBarId : null,
  showHideProgressBar(withAnimation = false) {
    this.cleanProgressBarTimer()

    if(this.isShowProgressBar) {
      // 如果当前显示进度条
      this.videoControlBar.emit("hide_bar", true);
      this.isShowProgressBar = false;
    } else {
      // 如果当前显示进度条
      this.videoControlBar.emit("show_bar", withAnimation);
      this.isShowProgressBar = true;
      this.setProgressBarTimer();
    }
  },

  // 显示进度条 重置计时器
  showProgressBar() {
    cc.log("显示进度条")
    this.cleanProgressBarTimer();
    this.videoControlBar.emit("show_bar", false);
    this.isShowProgressBar = true;
    this.setProgressBarTimer();
  },

  cleanProgressBarTimer() {
    if(this.timeoutHideBarId) {
      clearTimeout(this.timeoutHideBarId);
    }
  },

  setProgressBarTimer() {
    this.timeoutHideBarId = setTimeout(()=>{
      this.videoControlBar.emit("hide_bar", true);
      this.isShowProgressBar = false;
    }, 2000)
  },

  canvasTouchStart(e) {
    const pos = e.getLocation();
    // this.knife.x = pos.x - e.currentTarget.width / 2;
    // this.knife.y = pos.y - e.currentTarget.height / 2;
  },

  canvasTouchMove(e) {
    if (!this._curShowItem) {
      return;
    }
    const pos = e.getLocation();
    this._curShowItem.x =
      (pos.x - e.currentTarget.width / 2) / this._curShowItem.parent.scale;
    this._curShowItem.y =
      (pos.y - e.currentTarget.height / 2) / this._curShowItem.parent.scale;

    // console.log('pos: ', pos.x);
  },

  canvasTouchEnd(e) {
    if (!this._curShowItem) {
      return;
    }
    this.checkOnDragEndRect();
    this._curShowItem = null;
  },

  checkOnDragEndRect() {
    console.log("emptyGroupArr: ", this.emptyGroupArr);
    for (let i = 0; i < this.dragEndRectArr.length; i++) {
      const rect = this.dragEndRectArr[i];

      const worldPos = this._curShowItem.parent.convertToWorldSpaceAR(
        cc.v2(this._curShowItem.x, this._curShowItem.y)
      );
      const worldRect = rect.getBoundingBoxToWorld();
      if (worldRect.contains(worldPos)) {
        console.log("rect in ");
        this._curShowItem.selectRect = rect;
        // this.checkIsDragEndSuccess(rect);

        return;
      }
    }

    this.itemBack();
  },

  checkIsDragEndSuccess(dragItem) {
    const rect = dragItem.selectRect;

    const worldPos = dragItem.parent.convertToWorldSpaceAR(
      cc.v2(dragItem.targetPx, dragItem.targetPy)
    );
    const worldRect = rect.getBoundingBoxToWorld();

    console.log(" worldPos: ", worldPos);
    console.log(" worldRect: ", worldRect);

    if (worldRect.contains(worldPos)) {
      dragItem.x = dragItem.targetPx;
      dragItem.y = dragItem.targetPy;
      // dragItem.isDragEnd = true;

      // cc.audioEngine.playEffect(this.rightClip, false, 0.8);

      return true;
    } else {
      return false;
      // this.itemBack();
    }
  },

  itemBack() {
    cc.audioEngine.playEffect(this.wrongClip, false, 0.8);

    cc.tween(this._curShowItem)
      .to(
        0.5,
        { x: this._curShowItem.baseX, y: this._curShowItem.baseY },
        { easing: "elasticOut" }
      )
      .start();
  },

  removeHtmlCanvasListener(type) {
    // const canvasHtml = document.querySelector('canvas');
    // canvasHtml.addEventListener(type, (e) => {})
  },

  removeHtmlTouchEnd() {
    // const canvasHtml = document.querySelector('canvas');
    // canvasHtml.removeEventListener('touchend', this.htmlCanvasTouchendFunc, this);
  },

  initHotZone() {
    this.initHotZoneBg();
  },

  hotZoneBg: null,
  initHotZoneBg() {
    for (let i = 0; i < this.data.quesArr.length; i++) {
      this.data.quesArr[i].index = i;
      const data = this.data.quesArr[i];

      const hotZoneBg = new cc.Node();
      hotZoneBg.name = "hotZoneBg";
      hotZoneBg.parent = cc.find("Canvas");
      hotZoneBg.data = data;

      data.hotZoneBg = hotZoneBg;
      hotZoneBg.active = false;

      if (!data.bgItem) {
        continue;
      }

      cc.loader.load({ url: data.bgItem.url }, (err, img) => {
        hotZoneBg.width = img.width;
        hotZoneBg.height = img.height;

        const sprNode = new cc.Node();
        sprNode.name = "bgItemSpr";
        var sf = new cc.SpriteFrame(img);
        // const spr = hotZoneBg.addComponent(cc.Sprite);
        const spr = sprNode.addComponent(cc.Sprite);
        spr.spriteFrame = sf;
        sprNode.width = hotZoneBg.width;
        sprNode.height = hotZoneBg.height;
        sprNode.parent = hotZoneBg;

        sprNode.opacity = 0;

        // const sx = this.canvas.width / hotZoneBg.width;
        const sy = this.canvas.height / hotZoneBg.height;
        // const s = Math.min(sx, sy);
        hotZoneBg.scale = sy;

        if (data.itemType != "sound") {
          this.initHotZoneItem(hotZoneBg);
        }
      });
    }

    // this.hotZoneBg = new cc.Node();
    // this.hotZoneBg.name = 'hotZoneBg';
    // this.hotZoneBg.parent = cc.find('Canvas');
    // // this.hotZoneBg.zIndex = 4;

    // const titleH = 107 * this._mapScaleMin + 11 * 2

    // if (!this.data.bgItem) {
    // 	return;
    // }

    // cc.loader.load({ url: this.data.bgItem.url }, (err, img) => {

    // 	// this.addMask(this.hotZoneBg);

    // 	this.hotZoneBg.width = img.width;
    // 	this.hotZoneBg.height = img.height;

    // 	const sprNode = new cc.Node();
    // 	sprNode.name = 'bgItemSpr'
    // 	var sf = new cc.SpriteFrame(img);
    // 	// const spr = this.hotZoneBg.addComponent(cc.Sprite);
    // 	const spr = sprNode.addComponent(cc.Sprite);
    // 	spr.spriteFrame = sf
    // 	sprNode.width = this.hotZoneBg.width;
    // 	sprNode.height = this.hotZoneBg.height;
    // 	sprNode.parent = this.hotZoneBg;
    // 	window['bg'] = sprNode

    // 	const sx = this.canvas.width / this.hotZoneBg.width;
    // 	const sy = (this.canvas.height - titleH) / this.hotZoneBg.height;
    // 	const s = Math.min(sx, sy);
    // 	this.hotZoneBg.scale = s;

    // 	// this.hotZoneBg.y = -frameSize.height / 2 * this._cocosScale + this.hotZoneBg.height / 2 * this.hotZoneBg.scaleY + (subNum * mapS * this._cocosScale);
    // 	this.hotZoneBg.y = 0 - titleH / 2;
    // 	// console.log('this.hotZoneBg.y', this.hotZoneBg.y);

    // 	// this.data.bgItem.isShowDebugLine = true;
    // 	this.initHotZoneItem();

    // });
  },

  initHotZoneItem(bg) {
    const quesData = bg.data;
    quesData.hotZoneItemArr.forEach((item) => {
      // console.log('item.gIdx: ', item.gIdx);
      switch (item.gIdx) {
        case "0":
          this.setOneHand(item, bg);
          break;

        case "1":
          this.setOneAnimaSmall(item, bg);
          break;

        case "2":
          this.setOnePic(item, bg);
          break;

        default:
          break;
      }
    });
  },

  setOneDragEndRect(data, bg) {
    console.log(" in setOneDragEndRect");

    const quesData = bg.data;
    const rate = (bg.scale * bg.width) / quesData.bgItem.rect.width;

    const rectNode = new cc.Node();
    rectNode.name = "rect" + data.index;
    bg.addChild(rectNode);

    const ctx = rectNode.addComponent(cc.Graphics);
    // 红色矩形
    ctx.lineWidth = 4;
    ctx.strokeColor = cc.Color.BLACK;
    ctx.fillColor = cc.Color.WHITE.setA(100);

    const scale = rate / bg.scaleY;
    // console.log('scale: ', scale);
    // console.log('scale2: ', scale / data.mapScale);

    rectNode.width = data.rect.width * scale;
    rectNode.height = data.rect.height * scale;
    rectNode.x = -bg.width / 2 + data.rect.x * scale;
    rectNode.y = bg.height / 2 - data.rect.height * scale - data.rect.y * scale;
    // rectNode.scale = 1 / data.mapScale;

    rectNode.anchorX = rectNode.anchorY = 0;

    if (quesData.bgItem.isShowDebugLine) {
      ctx.rect(0, 0, rectNode.width, rectNode.height);
    }
    ctx.stroke();
    ctx.fill();

    // console.log('```data: ', data)

    this.dragEndRectArr.push(rectNode);

    if (data.audio_url) {
      cc.assetManager.loadRemote(data.audio_url, (err, audioClip) => {
        rectNode.audioClip = audioClip;
      });
    }
  },

  setOneDragPic(data, bg) {
    const quesData = bg.data;
    const rate = (bg.scale * bg.width) / quesData.bgItem.rect.width;

    const picNode = new cc.Node();
    picNode.name = "pic" + data.index;
    picNode.data = data;
    bg.addChild(picNode);

    cc.loader.load({ url: data.pic_url }, (err, img) => {
      const spr = picNode.addComponent(cc.Sprite);
      spr.spriteFrame = new cc.SpriteFrame(img);

      const scale = rate / bg.scaleY;

      console.log("picNode.width: ", picNode.width);
      console.log("data.rect.width: ", data.rect.width);
      console.log("scale: ", scale);

      // picNode.width = data.rect.width * scale;
      // picNode.height = data.rect.height * scale;

      const picScale = (data.rect.width * scale) / picNode.width;
      picNode.scale = picScale;

      picNode.x = -bg.width / 2 + data.rect.x * scale;
      picNode.y =
        bg.height / 2 - data.rect.height * scale - data.rect.y * scale;

      picNode.x += (picNode.width / 2) * picNode.scaleX;
      picNode.y += (picNode.height / 2) * picNode.scaleX;
      // picNode.anchorX = picNode.anchorY = 0;

      // if (data.audio_url) {
      // 	this.addPicAudio(picNode);
      // }

      this.addDragPoint(picNode, data, bg);

      if (!quesData.dragPicArr) {
        quesData.dragPicArr = [];
      }
      quesData.dragPicArr.push(picNode);
    });
  },

  addDragPoint(picNode, data, bg) {
    const quesData = bg.data;
    picNode.baseX = picNode.x;
    picNode.baseY = picNode.y;

    const realRate = bg.width / quesData.bgItem.rect.width;
    picNode.targetPx =
      -bg.width / 2 + (data.dragDot.x - quesData.bgItem.rect.x) * realRate;
    picNode.targetPy =
      bg.height / 2 - (data.dragDot.y - quesData.bgItem.rect.y) * realRate;

    // if (data.audio_url) {
    // 	cc.assetManager.loadRemote(data.audio_url, (err, audioClip) => {
    // 		picNode.audioClip = audioClip;
    // 	});
    // }

    picNode.on(cc.Node.EventType.TOUCH_START, () => {
      // if (picNode.isDragEnd) {
      // 	if (picNode.audioClip) {
      // 		cc.audioEngine.stopAllEffects();
      // 		cc.audioEngine.playEffect(picNode.audioClip, false, 0.8);
      // 	}
      // 	return;
      // }
      this._curShowItem = picNode;
    });
  },

  setOneAction(data) {
    const rate =
      (this.hotZoneBg.scale * this.hotZoneBg.width) /
      this.data.bgItem.rect.width;
    const rectNode = new cc.Node();
    rectNode.name = "rect" + data.index;
    this.hotZoneBg.addChild(rectNode);

    const ctx = rectNode.addComponent(cc.Graphics);
    // 红色矩形
    ctx.lineWidth = 4;
    ctx.strokeColor = cc.Color.BLACK;
    ctx.fillColor = cc.Color.WHITE.setA(100);

    const scale = rate / this.hotZoneBg.scaleY;

    rectNode.width = data.rect.width * scale;
    rectNode.height = data.rect.height * scale;
    rectNode.x = -this.hotZoneBg.width / 2 + data.rect.x * scale;
    rectNode.y =
      this.hotZoneBg.height / 2 -
      data.rect.height * scale -
      data.rect.y * scale;
    const { x, y, width, height } = rectNode;
    rectNode.anchorX = rectNode.anchorY = 0;

    if (this.data.bgItem.isShowDebugLine) {
      ctx.rect(0, 0, rectNode.width, rectNode.height);
    }
    ctx.stroke();
    ctx.fill();

    console.log("setOneAction ~~ data: ", data);
    const actionData = data["actionData_" + data.gIdx];
    if (!actionData) {
      return;
    }
    if (actionData.type == "text") {
      const label = this.setOneActionText(rectNode, actionData);
      label.node.scale = scale * data.fontScale;

      // label.overflow = cc.Label.Overflow.NONE;
      // label.node.setContentSize(new cc.Size(0, lineHeight));
      label["_forceUpdateRenderData"](true);
    } else if (actionData.type == "pic") {
      const pic = this.setOneActionPic(rectNode, actionData);
    } else if (actionData.type == "anima") {
      const anima = this.setOneActionAnima(rectNode, actionData);
    }
  },

  setOneActionText(rectNode, actionData) {
    // const labelNode = new cc.Node();
    // labelNode.parent = rectNode;
    const label = this.getLabel(); // labelNode.addComponent(cc.Label);
    const labelNode = label.node;
    labelNode.parent = rectNode;

    label.font = cc.find("Canvas/res/font/aharoni").getComponent(cc.Label).font;
    label.string = actionData.text;
    // label.string = `<size=${size}><color=#751e00>${this.curGroup.title }</color></size>`
    // label.lineHeight = size;
    // label.horizontalAlign = cc.macro.TextAlignment.LEFT
    // labelNode.anchorX = 0;
    // labelNode.anchorY = 1
    labelNode.color = cc.Color.BLACK;

    const opArr = actionData.changeOption;
    // console.log('opArr', opArr);

    const tweenArr = [];

    for (let i = 0; i < opArr.length; i++) {
      const opData = opArr[i];
      console.log("opArr[0]", opArr[i]);
      if (opData[0] == "fontColor") {
        const color = new cc.Color();
        cc.Color.fromHEX(color, opData[1]);
        labelNode.color = color;
      } else if (opData[0] == "opacity") {
        // console.log('opData: ', opData)
        labelNode.opacity = Number((opData[1] / 100) * 255) + 0.1;
        // console.log(labelNode.opacity);
        tweenArr.push({
          item: labelNode,
          option: `{"${opData[0]}" : ${(opData[2] / 100) * 255}}`,
          optionName: opData[0],
        });
      } else {
        label[opData[0]] = opData[1];
        tweenArr.push({
          item: label,
          option: `{"${opData[0]}" : ${opData[2]}}`,
          optionName: opData[0],
        });
      }
    }

    if (actionData.audio_url) {
      cc.assetManager.loadRemote(actionData.audio_url, (err, audioClip) => {
        labelNode.audioClip = audioClip;
      });
    }

    label.lineHeight = label.fontSize;

    labelNode.y += rectNode.height / 2;
    labelNode.x += rectNode.width / 2;

    rectNode.addComponent(cc.Button);
    rectNode.on("click", () => {
      if (labelNode.audioClip) {
        cc.audioEngine.stopAllEffects();
        cc.audioEngine.playEffect(labelNode.audioClip, false, 0.8);
      }

      if (labelNode.isClicked) {
        // return;
      }
      labelNode.isClicked = true;

      // const j = JSON.stringify({'fontSize': 500});
      // console.log('j: ', JSON.parse('{"fontSize":500}'));

      for (let i = 0; i < tweenArr.length; i++) {
        const tweenData = tweenArr[i];

        // JSON.parse(tweenData.option)

        // console.log( JSON.parse(tweenData.option) );

        if (tweenData.optionName == "opacity") {
          console.log("~~~ ", tweenData.item[tweenData.optionName]);
          // tweenData.item[tweenData.optionName] = tweenData.item[tweenData.optionName] + 1

          cc.tween(tweenData.item)
            .to(actionData.changeTime, JSON.parse(tweenData.option))
            .start();
        }
      }

      // cc.tween({})
      // 	.to(5, { scale: (Math.random() - 0.5) + 1})
      // 	.start();
    });

    // labelNode.opacity = 255;

    return label;
  },

  setOneActionPic(rectNode, actionData) {
    console.log("setOneActionPic actionData: ", actionData);
    const picNode = new cc.Node();
    rectNode.addChild(picNode);

    cc.loader.load({ url: actionData.pic_url }, (err, img) => {
      const spr = picNode.addComponent(cc.Sprite);
      spr.spriteFrame = new cc.SpriteFrame(img);

      picNode.y += rectNode.height / 2;
      picNode.x += rectNode.width / 2;

      picNode.scaleX = rectNode.width / picNode.width;
      picNode.scaleY = rectNode.height / picNode.height;

      const opArr = actionData.changeOption;
      const tweenArr = [];

      for (let i = 0; i < opArr.length; i++) {
        const opData = opArr[i];
        console.log("opData: ~~~ ", opData);

        if (opData[0] == "opacity") {
          picNode.opacity = Number((opData[1] / 100) * 255) + 0.1;
          console.log(picNode.opacity);
          tweenArr.push({
            item: picNode,
            option: `{"${opData[0]}" : ${(opData[2] / 100) * 255}}`,
            optionName: opData[0],
          });
        } else {
          // picNode[opData[0]] = Number(opData[1]);
          // tweenArr.push({item: picNode, option: `{"${opData[0]}" : ${opData[2]}}`, optionName: opData[0]})
        }

        if (actionData.audio_url) {
          cc.assetManager.loadRemote(actionData.audio_url, (err, audioClip) => {
            rectNode.audioClip = audioClip;
          });
        }

        rectNode.addComponent(cc.Button);
        rectNode.on("click", () => {
          if (rectNode.audioClip) {
            cc.audioEngine.stopAllEffects();
            cc.audioEngine.playEffect(rectNode.audioClip, false, 0.8);
          }

          if (rectNode.isClicked) {
            // return;
          }
          rectNode.isClicked = true;

          for (let i = 0; i < tweenArr.length; i++) {
            const tweenData = tweenArr[i];

            if (tweenData.optionName == "opacity") {
              cc.tween(tweenData.item)
                .to(actionData.changeTime, JSON.parse(tweenData.option))
                .start();
            }
          }
        });
      }
    });
  },

  setOneActionAnima(rectNode, actionData) {
    const animaNode = new cc.Node();
    rectNode.addChild(animaNode);

    if (actionData.audio_url) {
      cc.assetManager.loadRemote(actionData.audio_url, (err, audioClip) => {
        rectNode.audioClip = audioClip;
      });
    }

    const data = actionData;

    const dragonDisplay = animaNode.addComponent(dragonBones.ArmatureDisplay);
    if (!data.texPngData) {
      return;
    }

    const image = data.texPngData.url; //"http://staging-teach.cdn.ireadabc.com/5a0c5af3e952acd0ac83a6e5c6f03ff1.png";
    const ske = data.skeJsonData.url; //"http://staging-teach.cdn.ireadabc.com/bd825dcceea298d1146be8067ae3d17f.json";
    const atlas = data.texJsonData.url; //"http://staging-teach.cdn.ireadabc.com/246f8991b729fa3e5a7f4802de828efa.json";
    cc.loader.load(image, (error, texture) => {
      cc.loader.load({ url: atlas, type: "txt" }, (error, atlasJson) => {
        cc.loader.load({ url: ske, type: "txt" }, (error, dragonBonesJson) => {
          const atlas = new dragonBones.DragonBonesAtlasAsset();
          atlas.atlasJson = atlasJson;
          atlas.texture = texture;

          const asset = new dragonBones.DragonBonesAsset();
          asset.dragonBonesJson = dragonBonesJson;

          dragonDisplay.dragonAtlasAsset = atlas;
          dragonDisplay.dragonAsset = asset;

          let json = JSON.parse(asset.dragonBonesJson);
          let armatures = json["armature"];
          let armatureNames = [];
          for (let i = 0; i < armatures.length; i++) {
            armatureNames.push(armatures[i].name);
          }
          // console.log('armatureNames: ', armatureNames);

          let animationNames = [];

          if (armatureNames.length > 0) {
            let defaultArmatureName = armatureNames[0];
            dragonDisplay.armatureName = defaultArmatureName;
            // let animationNames = dragonDisplay.getAnimationNames(defaultArmatureName);
            let defaultArmature = armatures[0];
            let animations = defaultArmature.animation;
            for (let i = 0; i < animations.length; i++) {
              animationNames.push(animations[i].name);
            }

            // rectNode.addComponent(cc.Button);
            // rectNode.on('click', () => {
            // 	if (rectNode.isClicked) {
            // 		// return;
            // 	}
            // 	rectNode.isClicked = true;
            // 	console.log('clicked');

            // 	if (rectNode.audioClip) {
            // 		cc.audioEngine.stopAllEffects();
            // 		cc.director.emit('STOP_ALL_AUDIO')
            // 		cc.audioEngine.playEffect(rectNode.audioClip, false, 0.8);
            // 	}

            // 	if (animationNames.length > 0) {
            // 		dragonDisplay.playAnimation(animationNames[0], 1);
            // 	}
            // });
          }

          // animaNode.x = rectNode.x + rectNode.width / 2;
          // animaNode.y = rectNode.y + rectNode.height / 2;

          // const sx = rectNode.width / animaNode.width;
          // const sy = rectNode.height / animaNode.height;
          // const scale = Math.min(sx, sy);
          // animaNode.scale = scale;

          animaNode.y += rectNode.height / 2;
          animaNode.x += rectNode.width / 2;

          animaNode.scaleX = rectNode.width / animaNode.width;
          animaNode.scaleY = rectNode.height / animaNode.height;

          const opArr = actionData.changeOption;
          const tweenArr = [];

          for (let i = 0; i < opArr.length; i++) {
            const opData = opArr[i];
            console.log("opData: ~~~ ", opData);

            if (opData[0] == "opacity") {
              animaNode.opacity = Number((opData[1] / 100) * 255) + 0.1;
              console.log(animaNode.opacity);
              tweenArr.push({
                item: animaNode,
                option: `{"${opData[0]}" : ${(opData[2] / 100) * 255}}`,
                optionName: opData[2] == null ? "" : opData[0],
              });
            } else {
              // animaNode[opData[0]] = Number(opData[1]);
              // tweenArr.push({item: animaNode, option: `{"${opData[0]}" : ${opData[2]}}`, optionName: opData[2] == null ? '' : opData[0]})
            }

            if (actionData.audio_url) {
              cc.assetManager.loadRemote(
                actionData.audio_url,
                (err, audioClip) => {
                  rectNode.audioClip = audioClip;
                }
              );
            }

            rectNode.addComponent(cc.Button);
            rectNode.on("click", () => {
              if (rectNode.audioClip) {
                cc.audioEngine.stopAllEffects();
                cc.audioEngine.playEffect(rectNode.audioClip, false, 0.8);
              }

              if (rectNode.isClicked) {
                // return;
              }
              rectNode.isClicked = true;

              for (let j = 0; j < tweenArr.length; j++) {
                const tweenData = tweenArr[j];

                console.log("tweenData: ", tweenData);

                if (tweenData.optionName) {
                  cc.tween(tweenData.item)
                    .to(actionData.changeTime, JSON.parse(tweenData.option))
                    .start();
                }
              }

              if (animationNames.length > 0) {
                dragonDisplay.playAnimation(animationNames[0], 1);
              }
            });
          }
        });
      });
    });
  },

  setOneAnimaSmall(data) {
    const rate =
      (this.hotZoneBg.scale * this.hotZoneBg.width) /
      this.data.bgItem.rect.width;

    const rectNode = new cc.Node();
    rectNode.name = "rect" + data.index;
    this.hotZoneBg.addChild(rectNode);

    const ctx = rectNode.addComponent(cc.Graphics);
    // 红色矩形
    ctx.lineWidth = 4;
    ctx.strokeColor = cc.Color.BLACK;
    ctx.fillColor = cc.Color.WHITE.setA(100);

    const scale = rate / this.hotZoneBg.scaleY;

    rectNode.width = data.rect.width * scale;
    rectNode.height = data.rect.height * scale;
    rectNode.x = -this.hotZoneBg.width / 2 + data.rect.x * scale;
    rectNode.y =
      this.hotZoneBg.height / 2 -
      data.rect.height * scale -
      data.rect.y * scale;

    rectNode.anchorX = rectNode.anchorY = 0;

    if (this.data.bgItem.isShowDebugLine) {
      ctx.rect(0, 0, rectNode.width, rectNode.height);
    }
    ctx.stroke();
    ctx.fill();

    const animaNode = new cc.Node();
    animaNode.name = "anima_" + data.index;
    this.hotZoneBg.addChild(animaNode);

    if (data.audio_url) {
      cc.assetManager.loadRemote(data.audio_url, (err, audioClip) => {
        animaNode.audioClip = audioClip;
      });
    }

    const dragonDisplay = animaNode.addComponent(dragonBones.ArmatureDisplay);
    if (!data.texPngData) {
      return;
    }

    const image = data.texPngData.url; //"http://staging-teach.cdn.ireadabc.com/5a0c5af3e952acd0ac83a6e5c6f03ff1.png";
    const ske = data.skeJsonData.url; //"http://staging-teach.cdn.ireadabc.com/bd825dcceea298d1146be8067ae3d17f.json";
    const atlas = data.texJsonData.url; //"http://staging-teach.cdn.ireadabc.com/246f8991b729fa3e5a7f4802de828efa.json";
    cc.loader.load(image, (error, texture) => {
      cc.loader.load({ url: atlas, type: "txt" }, (error, atlasJson) => {
        cc.loader.load({ url: ske, type: "txt" }, (error, dragonBonesJson) => {
          const atlas = new dragonBones.DragonBonesAtlasAsset();
          atlas.atlasJson = atlasJson;
          atlas.texture = texture;

          const asset = new dragonBones.DragonBonesAsset();
          asset.dragonBonesJson = dragonBonesJson;

          dragonDisplay.dragonAtlasAsset = atlas;
          dragonDisplay.dragonAsset = asset;

          let json = JSON.parse(asset.dragonBonesJson);
          let armatures = json["armature"];
          // console.log('armatures: ', armatures);
          let armatureNames = [];
          for (let i = 0; i < armatures.length; i++) {
            armatureNames.push(armatures[i].name);
          }
          // console.log('armatureNames: ', armatureNames);
          if (armatureNames.length > 0) {
            let defaultArmatureName = armatureNames[0];
            dragonDisplay.armatureName = defaultArmatureName;
            // let animationNames = dragonDisplay.getAnimationNames(defaultArmatureName);
            let defaultArmature = armatures[0];
            let animations = defaultArmature.animation;
            let animationNames = [];
            for (let i = 0; i < animations.length; i++) {
              animationNames.push(animations[i].name);
            }

            rectNode.addComponent(cc.Button);
            rectNode.on("click", () => {
              if (rectNode.isClicked) {
                // return;
              }
              rectNode.isClicked = true;
              console.log("clicked");

              if (animaNode.audioClip) {
                cc.audioEngine.stopAllEffects();
                cc.director.emit("STOP_ALL_AUDIO");
                cc.audioEngine.playEffect(animaNode.audioClip, false, 0.8);
              }

              if (animationNames.length > 0) {
                dragonDisplay.playAnimation(animationNames[0], 1);
              }
            });
          }

          animaNode.x = rectNode.x + rectNode.width / 2;
          animaNode.y = rectNode.y + rectNode.height / 2;

          const sx = rectNode.width / animaNode.width;
          const sy = rectNode.height / animaNode.height;
          const scale = Math.min(sx, sy);
          animaNode.scale = scale;
        });
      });
    });
  },

  setSubmitRect(data, bg) {
    const quesData = bg.data;
    const rate = (bg.scale * bg.width) / quesData.bgItem.rect.width;

    const rectNode = new cc.Node();
    rectNode.name = "rect" + data.index;
    bg.addChild(rectNode);

    const ctx = rectNode.addComponent(cc.Graphics);
    // 红色矩形
    ctx.lineWidth = 4;
    ctx.strokeColor = cc.Color.BLACK;
    ctx.fillColor = cc.Color.WHITE.setA(100);

    const scale = rate / bg.scaleY;

    rectNode.width = data.rect.width * scale;
    rectNode.height = data.rect.height * scale;
    rectNode.x = -bg.width / 2 + data.rect.x * scale;
    rectNode.y = bg.height / 2 - data.rect.height * scale - data.rect.y * scale;
    // rectNode.scale = 1 / data.mapScale;

    rectNode.anchorX = rectNode.anchorY = 0;

    if (quesData.bgItem.isShowDebugLine) {
      ctx.rect(0, 0, rectNode.width, rectNode.height);
    }
    ctx.stroke();
    ctx.fill();

    console.log("```data: ", data);

    // if (data.audio_url) {
    // 	cc.assetManager.loadRemote(data.audio_url, (err, audioClip) => {
    // 		rectNode.audioClip = audioClip;
    // 	});
    // }

    rectNode.addComponent(cc.Button);
    rectNode.on("click", () => {
      if (rectNode.isClicked) {
        // return;
      }
      rectNode.isClicked = true;
      if (this.curQues.itemType == "submit") {
        this.checkSubmitSelectQues();
      } else if (this.curQues.itemType == "drag") {
        this.checkSubmitDragQues();
      }
      // console.log('clicked');
      // this.video.pause();
      // if (data.selectType == 'right') {
      // 	this.startRightVideo();
      // } else {
      // 	this.startWrongVideo();
      // }

      bg.active = false;
      // if (rectNode.audioClip) {
      // 	cc.audioEngine.stopAllEffects();
      // 	cc.audioEngine.playEffect(rectNode.audioClip, false, 0.8);
      // }
    });
  },

  setOptPic(data, bg) {
    const quesData = bg.data;

    const rate = (bg.scale * bg.width) / quesData.bgItem.rect.width;

    const picNode = new cc.Node();
    picNode.name = "pic" + data.index;
    picNode.data = data;
    bg.addChild(picNode);
    picNode.data = data;

    if (!quesData.optPicArr) {
      quesData.optPicArr = [];
    }
    quesData.optPicArr.push(picNode);

    const scale = rate / bg.scaleY;
    picNode.width = data.rect.width * scale;
    picNode.height = data.rect.height * scale;
    picNode.x = -bg.width / 2 + data.rect.x * scale;
    picNode.y = bg.height / 2 - data.rect.height * scale - data.rect.y * scale;

    picNode.anchorX = picNode.anchorY = 0;

    getSprNodeByUrl(data.pic_url, (spr) => {
      const sprNode = spr.node;

      sprNode.scaleX = picNode.width / sprNode.width;
      sprNode.scaleY = picNode.height / sprNode.height;
      sprNode.anchorX = sprNode.anchorY = 0;
      sprNode.parent = picNode;

      picNode.spr1 = sprNode;
    });

    getSprNodeByUrl(data.pic2_url, (spr) => {
      const sprNode = spr.node;

      sprNode.scaleX = picNode.width / sprNode.width;
      sprNode.scaleY = picNode.height / sprNode.height;
      sprNode.anchorX = sprNode.anchorY = 0;
      sprNode.parent = picNode;
      sprNode.opacity = 0;

      picNode.spr2 = sprNode;
    });

    picNode.isSelect = false;
    picNode.on("touchstart", () => {
      this.hideAllOptSelect();
      picNode.isSelect = true;

      // picNode.isSelect = !picNode.isSelect;
      if (picNode.isSelect) {
        picNode.spr1.opacity = 0;
        picNode.spr2.opacity = 255;
      } else {
        picNode.spr1.opacity = 255;
        picNode.spr2.opacity = 0;
      }
    });

    if (data.audio_url) {
      this.addPicAudio(picNode);
    }

    // cc.loader.load({ url: data.pic_url }, (err, img) => {

    // 	const spr = picNode.addComponent(cc.Sprite);
    // 	spr.spriteFrame = new cc.SpriteFrame(img)

    // 	const scale = rate / bg.scaleY;

    // 	picNode.width = data.rect.width * scale;
    // 	picNode.height = data.rect.height * scale;
    // 	picNode.x = -bg.width / 2 + data.rect.x * scale;
    // 	picNode.y = bg.height / 2 - data.rect.height * scale - data.rect.y * scale;

    // 	picNode.anchorX = picNode.anchorY = 0;

    // 	// if (data.audio_url) {
    // 	// 	this.addPicAudio(picNode);
    // 	// }

    // });
  },

  hideAllOptSelect() {
    const optPicArr = this.curQues.optPicArr;
    optPicArr.forEach((it) => {
      it.isSelect = false;
      it.spr1.opacity = 255;
      it.spr2.opacity = 0;
    });
  },

  setOnePic(data) {
    const rate =
      (this.hotZoneBg.scale * this.hotZoneBg.width) /
      this.data.bgItem.rect.width;

    const picNode = new cc.Node();
    picNode.name = "pic" + data.index;
    picNode.data = data;
    this.hotZoneBg.addChild(picNode);

    cc.loader.load({ url: data.pic_url }, (err, img) => {
      const spr = picNode.addComponent(cc.Sprite);
      spr.spriteFrame = new cc.SpriteFrame(img);

      const scale = rate / this.hotZoneBg.scaleY;

      picNode.width = data.rect.width * scale;
      picNode.height = data.rect.height * scale;
      picNode.x = -this.hotZoneBg.width / 2 + data.rect.x * scale;
      picNode.y =
        this.hotZoneBg.height / 2 -
        data.rect.height * scale -
        data.rect.y * scale;

      picNode.anchorX = picNode.anchorY = 0;

      if (data.audio_url) {
        this.addPicAudio(picNode);
      }
    });
  },

  setOneAudioRect(data, bg) {
    const quesData = bg.data;
    const rate = (bg.scale * bg.width) / quesData.bgItem.rect.width;

    const rectNode = new cc.Node();
    rectNode.name = "rect" + data.index;
    bg.addChild(rectNode);

    const ctx = rectNode.addComponent(cc.Graphics);
    // 红色矩形
    ctx.lineWidth = 4;
    ctx.strokeColor = cc.Color.BLACK;
    ctx.fillColor = cc.Color.WHITE.setA(100);

    const scale = rate / bg.scaleY;

    rectNode.width = data.rect.width * scale;
    rectNode.height = data.rect.height * scale;
    rectNode.x = -bg.width / 2 + data.rect.x * scale;
    rectNode.y = bg.height / 2 - data.rect.height * scale - data.rect.y * scale;
    // rectNode.scale = 1 / data.mapScale;

    rectNode.anchorX = rectNode.anchorY = 0;

    if (quesData.bgItem.isShowDebugLine) {
      ctx.rect(0, 0, rectNode.width, rectNode.height);
    }
    ctx.stroke();
    ctx.fill();

    console.log("```data: ", data);

    if (data.audio_url) {
      cc.assetManager.loadRemote(data.audio_url, (err, audioClip) => {
        rectNode.audioClip = audioClip;
      });
    }

    rectNode.addComponent(cc.Button);
    rectNode.on("click", () => {
      if (rectNode.isClicked) {
        // return;
      }
      rectNode.isClicked = true;
      console.log("clicked");
      if (rectNode.audioClip) {
        // cc.audioEngine.stopAllEffects();
        cc.audioEngine.playEffect(rectNode.audioClip, false, 0.8);
      }
    });
  },

  setOneHand(data, bg) {
    const rectNode = this.setOneRect(data, bg);

    const worldPos = rectNode.parent.convertToWorldSpaceAR(
      cc.v2(rectNode.x + rectNode.width / 2, rectNode.y + rectNode.height / 2)
    );
    const pos = this.hand.parent.convertToNodeSpaceAR(worldPos);

    bg.handX = pos.x;
    bg.handY = pos.y;
  },

  setOneRect(data, bg) {
    const quesData = bg.data;
    const rate = (bg.scale * bg.width) / quesData.bgItem.rect.width;

    const rectNode = new cc.Node();
    rectNode.name = "rect" + data.index;
    bg.addChild(rectNode);

    const ctx = rectNode.addComponent(cc.Graphics);
    // 红色矩形
    ctx.lineWidth = 4;
    ctx.strokeColor = cc.Color.BLACK;
    ctx.fillColor = cc.Color.WHITE.setA(100);

    const scale = rate / bg.scaleY;
    // console.log('scale: ', scale);
    // console.log('scale2: ', scale / data.mapScale);

    rectNode.width = data.rect.width * scale;
    rectNode.height = data.rect.height * scale;
    rectNode.x = -bg.width / 2 + data.rect.x * scale;
    rectNode.y = bg.height / 2 - data.rect.height * scale - data.rect.y * scale;
    // rectNode.scale = 1 / data.mapScale;

    rectNode.anchorX = rectNode.anchorY = 0;

    if (quesData.bgItem.isShowDebugLine || this.data.isDebug) {
      ctx.rect(0, 0, rectNode.width, rectNode.height);
    }
    ctx.stroke();
    ctx.fill();

    console.log("```data: ", data);

    // if (data.audio_url) {
    // 	cc.assetManager.loadRemote(data.audio_url, (err, audioClip) => {
    // 		rectNode.audioClip = audioClip;
    // 	});
    // }

    rectNode.addComponent(cc.Button);
    rectNode.on("click", () => {
      // if (rectNode.isClicked) {
      // 	return;
      // }
      // rectNode.isClicked = true;
      // console.log('clicked');
      // this.video.pause();

      // if (data.selectType == 'right') {
      // 	this.curQues.isRight = true;
      // 	this.startRightVideo();
      // } else {
      // 	this.curQues.isRight = false;

      // 	if (data?.labelArr) {
      // 		this.wrongStartTime = Number(data.labelArr[0].value);
      // 		this.wrongEndTime = Number(data.labelArr[1].value);
      // 	} else {
      // 		this.wrongStartTime = null;
      // 		this.wrongEndTime = null;
      // 	}
      // 	this.startWrongVideo();
      // }

      const id = this.quesIndex;
      bg.active = false;
      this.hand.active = false;
	    console.log("跳转", id)
      this.showMask(() => {
        if (!this.isLocal) {
          console.log("[MRBR_VIDEO] 调用系统方法:PSQS_jump_to_question")
          callMiddleLayerFunction("PSQS_jump_to_question", { step: id }, null);
        }
      });
    });

    return rectNode;
  },

  addPicAudio(picNode) {
    const data = picNode.data;

    cc.assetManager.loadRemote(data.audio_url, (err, audioClip) => {
      picNode.audioClip = audioClip;
    });

    picNode.addComponent(cc.Button);
    picNode.on("click", () => {
      if (picNode.audioClip) {
        cc.audioEngine.stopAllEffects();
        cc.audioEngine.playEffect(picNode.audioClip, false, 0.8);
      }
    });
  },

  getLabel() {
    const resLabel = cc.find("Canvas/res/label");
    const labelNode = cc.instantiate(resLabel);
    const label = labelNode.getComponent(cc.Label);

    return label;
  },

  getRichText() {
    const resLabel = cc.find("Canvas/res/label");
    const label = resLabel.getComponent(cc.Label);
    const fontFamily = label.fontFamily;

    const node = new cc.Node();
    const richText = node.addComponent(cc.RichText);
    richText.fontFamily = fontFamily;
    return richText;
  },

  getAnim(resName) {
    const anim = cc.find("Canvas/res/anim/" + resName);
    const newAnim = cc.instantiate(anim);
    return newAnim;
  },

  checkSubmitDragQues() {
    console.log("in checkSubmitDragQues");

    let isRight = true;
    const dragPicArr = this.curQues.dragPicArr;
    for (let i = 0; i < dragPicArr.length; i++) {
      const isDragRight = this.checkIsDragEndSuccess(dragPicArr[i]);
      if (!isDragRight) {
        console.log("dragItem: ", dragPicArr[i]);
        console.log("drag fail ");

        isRight = false;
        break;
      }
    }

    this.video.pause();
	this.videoControlBar.emit("update_video_status", 0);

    this.curQues.isRight = isRight;
    if (isRight) {
      this.startRightVideo();
    } else {
      this.startWrongVideo();
    }
  },

  checkSubmitSelectQues() {
    let isRight = true;
    const optPicArr = this.curQues.optPicArr;
    for (let i = 0; i < optPicArr.length; i++) {
      const data = optPicArr[i].data;

      // console.log('optPicArr[i].isSelect: ', optPicArr[i].isSelect);
      // console.log('data.selectType: ', data.selectType);

      if (optPicArr[i].isSelect) {
        if (data.selectType != "right") {
          isRight = false;
          break;
        }
      } else {
        if (data.selectType == "right") {
          isRight = false;
          break;
        }
      }
    }

    console.log("clicked");
    this.video.pause();
	  this.videoControlBar.emit("update_video_status", 0);
    this.curQues.isRight = isRight;
    if (isRight) {
      this.startRightVideo();
    } else {
      this.startWrongVideo();
    }
  },

  httpHeadCall(requsetUrl, callback) {
    let xhr = new XMLHttpRequest();
    console.log("Status: Send Post Request to " + requsetUrl);
    try {
      xhr.onreadystatechange = () => {
        try {
          console.log("xhr.readyState: ", xhr.readyState);

          if (xhr.readyState == 4) {
            if (xhr.status >= 200 && xhr.status < 400) {
              callback(true);
            } else {
              callback(false);
            }
          }
        } catch (e) {
          console.log(e);
        }
      };

      xhr.open("HEAD", requsetUrl, true);
      // xhr.setRequestHeader('content-type', 'application/json');
      // xhr.setRequestHeader('token', this.token);

      // xhr.send(JSON.stringify(requestData));
      xhr.send();

      xhr.timeout = 15000;
      xhr.onerror = (e) => {
        console.log("汪汪汪 posterror", e);
        callback(false);
      };

      xhr.ontimeout = (e) => {
        console.log("汪汪汪 ontimeout", e);
        callback(false);
      };
    } catch (e) {
      console.log("Send Get Request error: ", e);
    }
  },

  isDestroy: null,
  onDestroy() {
    this.isDestroy = true;

    cc.Tween.stopAll();
    cc.game.canvas.style.backgroundColor = "#000000";

    // 清除进度条隐藏定时器
    if(this.timeoutHideBarId) {
      clearTimeout(this.timeoutHideBarId);
    }
    // this.pauseVideo();
  },
});
