"use strict";
cc._RF.push(module, 'ddbf4iIJnhHIImfp+SKRF1C', 'OP15');
// OP15/scene/OP15.js

"use strict";

var _util = require("../script/util");

var _defaultData = require("../script/defaultData");

var _xstate = require("../script/xstate");

function _createForOfIteratorHelperLoose(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; return function () { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } it = o[Symbol.iterator](); return it.next.bind(it); }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }

var pure = _xstate.actions.pure,
    send = _xstate.actions.send,
    raise = _xstate.actions.raise,
    sendParent = _xstate.actions.sendParent;
cc.Class({
  "extends": cc.Component,
  properties: {
    /*ant: {
    	default: null,
    	type: cc.Node,
    },
    apple: {
    	default: null,
    	type: cc.Node,
    },
    bird: {
    	default: null,
    	type: cc.Node,
    },
    car: {
    	default: null,
    	type: cc.Node,
    },
    cat: {
    	default: null,
    	type: cc.Node,
    },
    cow: {
    	default: null,
    	type: cc.Node,
    },
    duck: {
    	default: null,
    	type: cc.Node,
    },
    egg: {
    	default: null,
    	type: cc.Node,
    },
    farmer: {
    	default: null,
    	type: cc.Node,
    },
    fish: {
    	default: null,
    	type: cc.Node,
    },
    girl: {
    	default: null,
    	type: cc.Node,
    },
    hen: {
    	default: null,
    	type: cc.Node,
    },
    house: {
    	default: null,
    	type: cc.Node,
    },*/
    rightAudio: {
      "default": null,
      type: cc.AudioClip
    },
    wrongAudio: {
      "default": null,
      type: cc.AudioClip
    },
    logoCat: {
      "default": null,
      type: cc.Node
    }
  },
  playAni: function playAni(idx, name, options) {
    var times = options && options.times || 1;
    var cb = options && options.callback || null; // const cat = cc.find(`Canvas/frame-border/ground/${node}`);

    var node = this._figurePointRectArray[idx].node;
    var dragonDisplay = node.getComponent(dragonBones.ArmatureDisplay);
    var state = dragonDisplay.playAnimation(name, times); // dragonDisplay.addEventListener(dragonBones.EventObject.COMPLETE, (event) => {
    // 	//TODO 这里写触发事件
    // 	//event.name为事件名称
    // 	console.log(event.name)
    // }, this);
    // animationDisplay.addEventListener(dragonBones.EventObject.COMPLETE, completeCallback);

    return state;
  },
  // 生命周期 onLoad
  onLoad: function onLoad() {
    this._timeoutIds = [];
    this._intervalIds = [];
    this.initSceneData();
    this.initSize();
    window.ccc = this;
  },
  _imageResList: null,
  _audioResList: null,
  _animaResList: null,
  _lastFingerPosition: null,
  _hintsNodeList: null,
  _figurePointRectArray: null,
  _allAnimationNodes: null,
  initSceneData: function initSceneData() {
    this._imageResList = [];
    this._audioResList = [];
    this._animaResList = [];
    this._allAnimationNodes = [];
    this._hintsNodeList = [];
    this._lastFingerPosition = {
      pos: null,
      dirty: false
    };
    this._figurePointRectArray = [];
  },
  _designSize: null,
  // 设计分辨率
  _frameSize: null,
  // 屏幕分辨率
  _mapScaleMin: null,
  // 场景中常用缩放（取大值）
  _mapScaleMax: null,
  // 场景中常用缩放（取小值）
  _cocosScale: null,
  // cocos 自缩放 （较少用到）
  initSize: function initSize() {
    // 注意cc.winSize只有在适配后(修改fitHeight/fitWidth后)才能获取到正确的值,因此使用cc.getFrameSize()来获取初始的屏幕大小
    var screen_size = cc.view.getFrameSize().width / cc.view.getFrameSize().height;
    var design_size = cc.Canvas.instance.designResolution.width / cc.Canvas.instance.designResolution.height;
    var f = screen_size >= design_size;
    cc.Canvas.instance.fitHeight = f;
    cc.Canvas.instance.fitWidth = !f;
    var frameSize = cc.view.getFrameSize();
    this._frameSize = frameSize;
    this._designSize = cc.view.getDesignResolutionSize();
    var sx = cc.winSize.width / frameSize.width;
    var 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;
  },
  createStateMachine: function createStateMachine() {
    var _this = this;

    var check = [{
      target: '#game.end',
      cond: function cond(ctx, evt) {
        console.log('[answer NEXT] check if end', ctx.questionIndex >= ctx.questionsCount - 1);
        return ctx.questionIndex >= ctx.questionsCount - 1;
      }
    }, {
      target: 'hint'
    } // reenter 'hint' state
    ];
    var QuestionState = {
      id: 'question',
      initial: 'hint',
      states: {
        hint: {
          invoke: {
            src: function src(ctx, event) {
              console.log("[hint] play question " + ctx.questionIndex + ": " + ctx.questionPlayTimes + " audio");
              ctx.questionPlayTimes += 1;
              return new Promise(function (resolve, reject) {
                (0, _util.playAudioByUrl)(ctx.questions[ctx.questionIndex].audio_url, function () {
                  console.log('hint finish');
                  resolve();
                });
              });
            },
            onDone: 'answer',
            onError: 'answer'
          }
        },
        answer: {
          after: {
            8000: [{
              target: 'wrong'
            } // reenter 'hint' state
            ]
          },
          invoke: {
            src: function src(context, event) {
              return function (callback, onReceive) {
                console.log('[answer] thinking and playing'); // check every second

                var id = setInterval(function () {
                  console.log("aaaaaa");

                  if (!_this._lastFingerPosition.dirty) {
                    return;
                  }

                  var region = context.questions[context.questionIndex];

                  var result = _this.checkInRegion(region.rect);

                  if (result === null) {
                    return;
                  }

                  console.log('[Genise JS] checkInRegion' + result);

                  if (result) {
                    callback('RIGHT');
                  } else {
                    callback('WRONG');
                  }
                }, 300);

                _this._intervalIds.push(id); // Perform cleanup


                return function () {
                  return clearInterval(id);
                };
              };
            }
          },
          on: {
            RIGHT: {
              target: 'right'
            },
            WRONG: {
              target: 'wrong'
            }
          }
        },
        right: {
          invoke: {
            src: function src(context, event) {
              _this._lastFingerPosition.pos = null;
              _this._lastFingerPosition.dirty = false;
              return new Promise(function (resolve, reject) {
                console.log('answer right'); // this.playAni(context.questionIndex, 'normal')

                var an = context.questions[context.questionIndex].node;
                console.log('in right ' + typeof an);
                an.active = true;
                var dragonDisplay = an.getComponent(dragonBones.ArmatureDisplay);
                dragonDisplay.playAnimation('normal', 0);

                var ddLogoCat = _this.logoCat.getComponent(dragonBones.ArmatureDisplay);

                ddLogoCat.playAnimation('right', 1);
                ddLogoCat.once(dragonBones.EventObject.COMPLETE, function () {
                  this.logoCat.getComponent(dragonBones.ArmatureDisplay).playAnimation('normal', 0);
                }, _this);
                (0, _util.playAudioByUrl)(_this.rightAudio, function () {
                  resolve();
                });
              });
            },
            onDone: {
              target: '#QuestionsArray.next',
              actions: raise('CHECK')
            },
            onError: {
              target: '#QuestionsArray.next',
              actions: raise('CHECK')
            }
          }
        },
        wrong: {
          invoke: {
            src: function src(context, event) {
              _this._lastFingerPosition.pos = null;
              _this._lastFingerPosition.dirty = false;
              return new Promise(function (resolve, reject) {
                console.log('answer wrong', context.questionIndex, context.questionPlayTimes, context.maxQuestionTryTimes);

                var ddLogoCat = _this.logoCat.getComponent(dragonBones.ArmatureDisplay);

                ddLogoCat.playAnimation('wrong', 1);
                ddLogoCat.once(dragonBones.EventObject.COMPLETE, function () {
                  this.logoCat.getComponent(dragonBones.ArmatureDisplay).playAnimation('normal', 0);
                }, _this);
                var wrongEffect = _this.wrongAudio; // 第一和第二题的提示音

                if ([0, 1].includes(context.questionIndex)) {
                  wrongEffect = _this.data["wrong_audio" + context.questionPlayTimes];
                } else {
                  // 非第一和第二题，并且做第二遍的提示音
                  if (context.questionPlayTimes == 2) {
                    wrongEffect = _this.data["wrong_audio" + context.questionPlayTimes];
                  }
                }

                if (context.questionPlayTimes >= context.maxQuestionTryTimes) {
                  var an = context.questions[context.questionIndex].node;
                  an.active = true;

                  if (an.isSpine) {
                    var skeleton = an.getComponent(sp.Skeleton);
                    skeleton.setToSetupPose();
                    setTimeout(function () {
                      skeleton.setAnimation(0, 'normal', true);
                    }, 1);
                  } else {
                    var dragonDisplay = an.getComponent(dragonBones.ArmatureDisplay);
                    dragonDisplay.playAnimation('normal', 0);
                    console.log('show animation', an.active);
                  }
                }

                (0, _util.playAudioByUrl)(wrongEffect, function () {
                  if (context.questionPlayTimes >= context.maxQuestionTryTimes) {
                    // const an = context.questions[context.questionIndex].node;
                    // an.active = true;
                    // const dragonDisplay = an.getComponent(dragonBones.ArmatureDisplay);
                    // dragonDisplay.playAnimation('normal', 0);
                    // console.log('show animation', an.active);
                    reject();
                  } else {
                    resolve();
                  }
                });
              });
            },
            onDone: {
              target: 'hint' // actions: raise('CHECK')

            },
            onError: {
              target: '#QuestionsArray.next',
              actions: raise('CHECK')
            }
          }
        }
      }
    };
    var QuestionsArrayStatus = {
      id: 'QuestionsArray',
      initial: 'play',
      states: {
        play: _extends({}, QuestionState),
        next: {
          on: {
            CHECK: [{
              target: '#game.end',
              cond: function cond(ctx, evt) {
                ctx.questionIndex += 1;
                ctx.questionPlayTimes = 0;
                console.log('#game.end', ctx.questionIndex >= ctx.questionsCount);
                return ctx.questionIndex >= ctx.questionsCount;
              }
            }, {
              target: 'play'
            }]
          }
        }
      }
    };
    var state = {
      id: 'game',
      initial: 'begin',
      context: {
        questionIndex: 0,
        questionPlayTimes: 0,
        maxQuestionTryTimes: 2,
        questionsCount: this._figurePointRectArray.length,
        questions: this._figurePointRectArray
      },
      states: {
        begin: {
          invoke: {
            src: function src(ctx) {
              console.log('game begin 1');

              if (window.courseware && window.courseware.openOsmoFingerRead) {
                _this.isOpenedOsmoFingerRead = true;
                window.courseware.openOsmoFingerRead({
                  "page_id": 27,
                  "book_id": "opw1"
                });
              }

              var dragonDisplay = _this.logoCat.getComponent(dragonBones.ArmatureDisplay);

              var state = dragonDisplay.playAnimation('begin', 0);
              return new Promise(function (resolve, reject) {
                (0, _util.playAudioByUrl)(_this.data.begin_audio, function () {
                  console.log('game begin audio finish');
                  resolve();
                });
              });
            },
            onDone: 'guide',
            onError: 'guide'
          }
        },
        guide: {
          invoke: {
            src: function src(ctx) {
              return new Promise(function (resolve, reject) {
                (0, _util.playAudioByUrl)(_this.data.guide_audio, function () {
                  console.log('game guide audio finish');
                  reject();
                });
              });
            },
            onDone: 'playing',
            onError: 'playing'
          }
        },
        playing: _extends({
          entry: function entry(ctx) {
            console.log('entry play stage');

            var dragonDisplay = _this.logoCat.getComponent(dragonBones.ArmatureDisplay);

            var state = dragonDisplay.playAnimation('normal', 0);
            cc.assetManager.loadRemote(_this.data.playing_audio, function (err, audioClip) {
              cc.audioEngine.playMusic(audioClip, true, 0.8);
            });
            ctx.questions.forEach(function (block) {
              block.node.active = false;
            });
          },
          exit: function exit() {
            console.log('exit play stage');
            cc.audioEngine.stopMusic();
          },
          on: {
            NEXT: 'end'
          }
        }, QuestionsArrayStatus),
        end: {
          entry: function entry(ctx, event) {
            console.log('game end');

            var dragonDisplay = _this.logoCat.getComponent(dragonBones.ArmatureDisplay);

            var state = dragonDisplay.playAnimation('finish', 0);

            if (window.courseware && window.courseware.closeOsmoFingerRead) {
              _this.isOpenedOsmoFingerRead = false;
              window.courseware.closeOsmoFingerRead();
            }

            (0, _util.playAudioByUrl)(_this.data.end_audio, function () {
              console.log('game finish');
              (0, _util.onHomeworkFinish)();
            }); // return new Promise((resolve,reject) => {
            // 	setTimeout(() => {
            // 		console.log('hint finish');
            // 		resolve()
            // 	}, 2000)
            // })
          }
        }
      }
    };
    var after = {};

    var _loop = function _loop(i) {
      var t = _this._hintsNodeList[i].node;
      var k = _this._hintsNodeList[i].after;
      after[k] = {
        actions: function actions() {
          if (t.isSpine) {
            var skeleton = t.getComponent(sp.Skeleton);
            skeleton.setToSetupPose();
            setTimeout(function () {
              skeleton.setAnimation(0, 'enlarge', false);
            }, 1); // skeleton.animation = skeleton.animationNames[0];
          } else {
            var dragonDisplay = t.getComponent(dragonBones.ArmatureDisplay);
            dragonDisplay.playAnimation('enlarge', 1);
            console.log(dragonDisplay._armatureKey, 'enlarge');
            dragonDisplay.addEventListener(dragonBones.EventObject.COMPLETE, function (event) {// TODO 这里写触发事件
              // event.name为事件名称
              // event.armature.animation.play('normal', 0);
              // console.log(event.animationState.name, dragonDisplay._armatureKey, 'end')
            }, _this);
          } // const dragonDisplay = t.getComponent(dragonBones.ArmatureDisplay);
          // dragonDisplay.playAnimation('enlarge', 1);
          // console.log(dragonDisplay._armatureKey, 'enlarge')
          // dragonDisplay.addEventListener(dragonBones.EventObject.COMPLETE, (event) => {
          // 	//TODO 这里写触发事件
          // 	//event.name为事件名称
          // 	event.armature.animation.play('normal', 0);
          // 	console.log(event.animationState.name, dragonDisplay._armatureKey, 'end')
          // }, this);

        }
      };
    };

    for (var i = 0; i < this._hintsNodeList.length; i++) {
      _loop(i);
    }

    if (this.data.begin_sep_time) {
      var t = +this.data.begin_sep_time * 1000;
      after[t] = {
        actions: function actions() {
          console.log('game begin 2');

          for (var _i = 0; _i < _this._allAnimationNodes.length; _i++) {
            var _t = _this._allAnimationNodes[_i];

            if (_t.isSpine) {
              (function () {
                var skeleton = _t.getComponent(sp.Skeleton);

                console.log('skeleton: ', skeleton);
                skeleton.setToSetupPose();
                setTimeout(function () {
                  skeleton.setAnimation(0, 'normal', true);
                }, 1);
                console.log('skeleton 22: ', skeleton); // skeleton.animation = skeleton.animationNames[0];
              })();
            } else {
              var dragonDisplay = _t.getComponent(dragonBones.ArmatureDisplay);

              dragonDisplay.playAnimation('normal', 0);
            }
          }
        }
      };
    }

    state.states.begin.after = after;
    var gameMachine = (0, _xstate.createMachine)(state);
    window.gameMachine = gameMachine;
    this.gameMachineService = (0, _xstate.interpret)(gameMachine).onTransition(function (state) {// console.log(1, state.value, state.context);
    });
    this.gameMachineService.start();

    if (window.gameMachineService) {
      window.gameMachineService = gameMachineService;
    }
  },
  // 生命周期 start
  start: function start() {
    var _this2 = this;

    var getData = this.getData.bind(this);

    if (window && window.courseware) {
      getData = window.courseware.getData;
    }

    getData(function (data) {
      // console.log('data:', data);
      _this2.data = data || _this2.getDefaultData();
      _this2.data = JSON.parse(JSON.stringify(_this2.data));

      _this2.preloadItem();
    });
    window.air = window.air || {};

    if (window.air) {
      window.air.osmoFingerReadCallback = function (result) {
        if (!_this2.gameMachineService) {
          return;
        } // const st = this.gameMachineService.state.value.constructor.name == 'Object' 
        // && this.gameMachineService.state.value['playing']
        // && this.gameMachineService.state.value['playing'].constructor.name == 'Object'
        // && this.gameMachineService.state.value['playing']['play']
        // && this.gameMachineService.state.value['playing']['play'] == 'answer'
        // if (st) {
        // }


        var resultObj = JSON.parse(result);
        console.log('[Genise JS] ' + JSON.stringify(resultObj.finger_pos_in_page));
        var p = resultObj.finger_pos_in_page;

        if (p.x == -1 || p.y == -1) {
          _this2._lastFingerPosition.pos = null;
          _this2._lastFingerPosition.dirty = false;
          return;
        }

        _this2._lastFingerPosition = {
          pos: {
            x: p.x,
            y: p.y
          },
          dirty: true
        };

        _this2.debugPointer(p.x, p.y);
      };
    }

    this.isDebug = false;
  },
  checkInRegion: function checkInRegion(r) {
    console.log('r~~~: ', r);

    if (!this._lastFingerPosition && !this._lastFingerPosition.pos) {
      return null;
    }

    var p = this._lastFingerPosition ? this._lastFingerPosition.pos || {
      x: 0,
      y: 0
    } : {
      x: 0,
      y: 0
    };
    var w = p.x > r.x && p.x < r.x + r.width;
    var h = p.y > r.y && p.y < r.y + r.height;
    return w && h;
  },
  getData: function getData(func) {
    if (window && window.courseware) {
      window.courseware.getData(func, 'scene');
      return;
    }

    var middleLayer = cc.find('middleLayer');

    if (middleLayer) {
      var middleLayerComponent = middleLayer.getComponent('middleLayer');
      middleLayerComponent.getData(func);
      return;
    }

    func(this.getDefaultData());
  },
  getDefaultData: function getDefaultData() {
    return {
      "begin_audio": "http://staging-teach.cdn.ireadabc.com/3d307a02663e1cd667b7c951340ec98b.mp3",
      "begin_sep_time": 1,
      "guide_audio": "http://staging-teach.cdn.ireadabc.com/3d307a02663e1cd667b7c951340ec98b.mp3",
      "playing_audio": "http://staging-teach.cdn.ireadabc.com/3d307a02663e1cd667b7c951340ec98b.mp3",
      "right_audio": "http://staging-teach.cdn.ireadabc.com/3d307a02663e1cd667b7c951340ec98b.mp3",
      "wrong_audio": "http://staging-teach.cdn.ireadabc.com/3d307a02663e1cd667b7c951340ec98b.mp3",
      "wrong_audio1": "http://staging-teach.cdn.ireadabc.com/3d307a02663e1cd667b7c951340ec98b.mp3",
      "wrong_audio2": "http://staging-teach.cdn.ireadabc.com/3d307a02663e1cd667b7c951340ec98b.mp3",
      "end_audio": "http://staging-teach.cdn.ireadabc.com/3d307a02663e1cd667b7c951340ec98b.mp3",
      "bgItem": {
        "url": "http://staging-teach.cdn.ireadabc.com/84ec6edc20bceaaa9dbe824092b6860d.png",
        "rect": {
          "x": 736.95,
          "y": 0,
          "width": 599.09,
          "height": 775
        }
      },
      "hotZoneItemArr": [{
        "id": "1659333645573",
        "index": 0,
        "audio_url": "http://staging-teach.cdn.ireadabc.com/5a1a2670845bfe76662e86d9a3a69f81.mp3",
        "itemType": "rect",
        "fontScale": 1.61953125,
        "imgScale": 1,
        "imgSizeW": 0,
        "imgSizeH": 0,
        "mapScale": 1.61953125,
        "dragDot": {
          "x": 1036.5,
          "y": 387.5
        },
        "gIdx": "1",
        "labelText": "1",
        "posX": 887.5,
        "posY": 165.5,
        "skeJsonData": {
          "url": "http://staging-teach.cdn.ireadabc.com/133a1f60719ed26247e35dc022d82862.json",
          "name": "spineboy-pro.json"
        },
        "texJsonData": {
          "url": "http://staging-teach.cdn.ireadabc.com/e0945b8265ea3b8053afb814c6b849d3.atlas",
          "name": "spineboy-pro.atlas"
        },
        "texPngData": {
          "url": "http://staging-teach.cdn.ireadabc.com/517553f50224915148f9efc5b7556798.png",
          "name": "spineboy-pro.png"
        },
        "animType": "spine",
        "rect": {
          "x": 48.05,
          "y": 65.5,
          "width": 205,
          "height": 200
        }
      }, {
        "id": "1659334098930",
        "index": 1,
        "audio_url": "http://staging-teach.cdn.ireadabc.com/16eb06a6beb9e4fa77c9b5d2d643ab29.mp3",
        "itemType": "rect",
        "fontScale": 1.61953125,
        "imgScale": 1,
        "imgSizeW": 0,
        "imgSizeH": 0,
        "mapScale": 1.61953125,
        "dragDot": {
          "x": 1036.5,
          "y": 387.5
        },
        "gIdx": "0",
        "labelText": "1",
        "posX": 1212.5,
        "posY": 643.5,
        "skeJsonData": {
          "url": "http://staging-teach.cdn.ireadabc.com/679fed26daa464819d553de6331b3552.json",
          "name": "alien-pro.json"
        },
        "texJsonData": {
          "url": "http://staging-teach.cdn.ireadabc.com/65d8214c6b5c5d0496e17adb0408276a.atlas",
          "name": "alien-pro.atlas"
        },
        "texPngData": {
          "url": "http://staging-teach.cdn.ireadabc.com/a319b372899239325b90bb4ec07b4970.png",
          "name": "alien-pro.png"
        },
        "animType": "spine",
        "rect": {
          "x": 375.56,
          "y": 543.5,
          "width": 200,
          "height": 200
        }
      }]
    }; // return defaultData;
  },
  preloadItem: function preloadItem() {
    this.addPreloadImage();
    this.addPreloadAudio();
    this.addPreloadAnima();
    this.preload();
  },
  addPreloadImage: function addPreloadImage() {
    this._imageResList.push({
      url: this.data.bgItem.url
    });

    for (var _iterator = _createForOfIteratorHelperLoose(this.data.hotZoneItemArr), _step; !(_step = _iterator()).done;) {
      var q = _step.value;

      if (q.gIdx == '0') {
        this._imageResList.push({
          url: q.texPngData.url
        });
      }

      if (q.gIdx == '1') {
        this._imageResList.push({
          url: q.texPngData.url
        });
      }

      if (q.gIdx == '2') {
        this._imageResList.push({
          url: q.pic_url
        });
      }
    }
  },
  prepareAudioClip: function prepareAudioClip(url, key) {
    var _this3 = this;

    if (url) {
      cc.assetManager.loadRemote(url, function (err, audioClip) {
        if (audioClip) {
          _this3[key] = audioClip;
        }
      });
    }
  },
  addPreloadAudio: function addPreloadAudio() {
    this._audioResList.push({
      url: this.data.begin_audio
    }); // this.prepareAudioClip(this.data.begin_audio1, 'begin_audio1')
    // this._audioResList.push({ url: this.data.begin_audio2 });
    // this.prepareAudioClip(this.data.begin_audio2, 'begin_audio2')


    this._audioResList.push({
      url: this.data.guide_audio
    });

    this._audioResList.push({
      url: this.data.playing_audio
    });

    if (this.data.wrong_audio) {
      this._audioResList.push({
        url: this.data.wrong_audio
      });

      this.wrongAudio = this.data.wrong_audio;
    }

    if (this.data.right_audio) {
      this._audioResList.push({
        url: this.data.right_audio
      });

      this.rightAudio = this.data.right_audio;
    }

    this._audioResList.push({
      url: this.data.wrong_audio1
    });

    this._audioResList.push({
      url: this.data.wrong_audio2
    });

    this._audioResList.push({
      url: this.data.end_audio
    });

    for (var _iterator2 = _createForOfIteratorHelperLoose(this.data.hotZoneItemArr), _step2; !(_step2 = _iterator2()).done;) {
      var q = _step2.value;

      if (q.gIdx == '0') {
        this._audioResList.push({
          url: q.audio_url
        });
      }
    }
  },
  debugPointer: function debugPointer() {
    var boxDebugger = cc.find('Canvas/box-debugger');

    if (!this.isDebug) {
      boxDebugger.active = false;
      return;
    }

    if (!this.POINTER_NODE) {
      this.POINTER_NODE = new cc.Node();
      this.POINTER_NODE.parent = boxDebugger;
      this.POINTER_NODE.name = 'POINTER_NODE';
      this.POINTER_NODE.addComponent(cc.Graphics);
    }

    var grap = this.POINTER_NODE.getComponent(cc.Graphics);
    grap.clear();
    var ground = cc.find('Canvas/frame-border/ground');
    var baseW = ground.width,
        baseH = ground.height;
    var _this$_lastFingerPosi = this._lastFingerPosition.pos,
        px = _this$_lastFingerPosi.x,
        py = _this$_lastFingerPosi.y;
    var x = baseW * px - baseW / 2;
    var y = baseH - baseH * py - baseH / 2 - 16;
    var pn = new cc.Node();
    grap.fillColor = cc.color(255, 0, 0);
    grap.circle(x, y, 32);
    grap.fill();
    grap.stroke();
  },
  debugGraphics: function debugGraphics() {
    var boxDebugger = cc.find('Canvas/box-debugger');

    if (!this.isDebug) {
      boxDebugger.active = false;
      return;
    }

    boxDebugger.active = true;
    console.log('show debug graphics');
    var ground = cc.find('Canvas/frame-border/ground');
    var canvas = cc.find('Canvas');
    var baseW = ground.width,
        baseH = ground.height;
    var _this$data$bgItem$rec = this.data.bgItem.rect,
        bgW = _this$data$bgItem$rec.width,
        bgH = _this$data$bgItem$rec.height;
    var scaleX = bgW / baseW;
    var scaleY = bgH / baseH;
    var added = false;
    this.data.hotZoneItemArr.forEach(function (area) {
      if (added) {// return
      }

      if (area.gIdx != '0') {
        return;
      }

      added = true;
      var dn = new cc.Node();
      var lblNode = new cc.Node();
      lblNode.parent = dn;
      var lbl = lblNode.addComponent(cc.Label);
      lblNode.color = cc.color(0, 0, 0);
      lbl.string = area.skeJsonData.name.substring(0, area.skeJsonData.name.length - 9);
      dn.name = lbl.string;
      dn.parent = boxDebugger;
      dn.width = baseW;
      dn.height = baseH;
      var grap = dn.addComponent(cc.Graphics);
      var r = (0, _util.RandomInt)(1, 255);
      var g = (0, _util.RandomInt)(1, 255);
      var b = (0, _util.RandomInt)(1, 255);
      grap.fillColor = cc.color(r, g, b, 127);
      var _area$rect = area.rect,
          rx = _area$rect.x,
          ry = _area$rect.y,
          rw = _area$rect.width,
          rh = _area$rect.height;
      var w = rw / bgW * baseW;
      var h = rh / bgH * baseH;
      var x = rx / bgW * baseW - baseW / 2;
      var y = baseH - ry / bgH * baseH - h - baseH / 2; // w *= scaleX
      // h *= scaleY
      // x *= scaleX
      // y *= scaleY
      // const p = boxDebugger.convertToNodeSpaceAR(cc.v2(x,y));
      // x = p.x;
      // y = p.y;

      lblNode.x = x;
      lblNode.y = y + h; // dn.scaleX = scaleX;
      // dn.scaleY = scaleY;
      // dn.scale = area.mapScale; // minScale; // this._mapScaleMax * area.mapScale; // ;

      console.log('[debug]', area.skeJsonData.name, x, y, w, h);
      grap.fillRect(x, y, w, h);
      grap.stroke();
    });
  },
  addPreloadAnima: function addPreloadAnima() {},
  preload: function preload() {
    var _this4 = this;

    var preloadArr = this._imageResList.concat(this._audioResList).concat(this._animaResList); // console.log(preloadArr);


    cc.assetManager.loadAny(preloadArr, null, function (f, t, item) {// console.log(f, t, item)
    }, function (err, data) {
      // console.log(err, data);
      var ground = cc.find("Canvas/frame-border/ground");
      var groundBg = cc.find("Canvas/frame-border/ground/bg");
      groundBg.active = false;
      var baseRect = _this4.data.bgItem.rect;
      (0, _util.getSpriteFrimeByUrl)(_this4.data.bgItem.url, function (sf) {
        var gs = groundBg.getComponent(cc.Sprite);
        gs.spriteFrame = sf;
        groundBg.active = true;
        var dbCount = 0;
        var finishDbCount = 0;

        for (var _iterator3 = _createForOfIteratorHelperLoose(_this4.data.hotZoneItemArr), _step3; !(_step3 = _iterator3()).done;) {
          var block = _step3.value;

          if (block.gIdx == '0' || block.gIdx == '1') {
            dbCount++;
          }
        }

        for (var _iterator4 = _createForOfIteratorHelperLoose(_this4.data.hotZoneItemArr), _step4; !(_step4 = _iterator4()).done;) {
          var _block = _step4.value;

          if (_block.gIdx == '2') {
            (function () {
              var s1 = (ground.width / _block.imgSizeW + ground.height / _block.imgSizeH) / 2;
              var node = new cc.Node();
              node.parent = ground;
              var spr = node.addComponent(cc.Sprite);
              (0, _util.getSpriteFrimeByUrl)(_block.pic_url, function (sf) {
                spr.spriteFrame = sf;
                node.scale = s1;
              });
            })();
          }

          if (_block.gIdx == '0' || _block.gIdx == '1') {
            (function () {
              var n = new cc.Node();
              n.scale = 0.25;
              n.parent = ground;
              n.active = false;

              if (_block.animType == 'spine') {
                var skeleton = n.addComponent(sp.Skeleton);
                n.isSpine = true;
                (0, _util.loadSpine)(skeleton, _block.texPngData.name, {
                  tex: _block.texPngData.url,
                  atlas: _block.texJsonData.url,
                  ske: _block.skeJsonData.url
                }).then(function (_ref) {
                  var width = _ref.width,
                      height = _ref.height;
                  n.width = width;
                  n.height = height;
                  n.active = true; // db.playAnimation('null', 0);
                  // skeleton.setToSetupPose();

                  skeleton.setAnimation(0, 'enlarge', true);

                  _this4._allAnimationNodes.push(n);

                  finishDbCount++;
                  console.log(finishDbCount, dbCount);

                  if (finishDbCount == dbCount) {
                    _this4.loadEnd();
                  }
                })["catch"](function () {
                  finishDbCount++;
                  console.log(finishDbCount, dbCount);

                  if (finishDbCount == dbCount) {
                    _this4.loadEnd();
                  }
                });
              } else {
                var db = n.addComponent(dragonBones.ArmatureDisplay);
                (0, _util.loadDragonBones)(db, {
                  tex: _block.texPngData.url,
                  atlas: _block.texJsonData.url,
                  ske: _block.skeJsonData.url
                }).then(function (_ref2) {
                  var width = _ref2.width,
                      height = _ref2.height;
                  n.width = width;
                  n.height = height;
                  n.active = true;
                  db.playAnimation('null', 0);

                  _this4._allAnimationNodes.push(n);

                  finishDbCount++;
                  console.log(finishDbCount, dbCount);

                  if (finishDbCount == dbCount) {
                    _this4.loadEnd();
                  }
                })["catch"](function () {
                  finishDbCount++;
                  console.log(finishDbCount, dbCount);

                  if (finishDbCount == dbCount) {
                    _this4.loadEnd();
                  }
                });
              }

              if (_block.gIdx == '0') {
                var rectInfo = {
                  node: n,
                  audio_url: _block.audio_url,
                  rect: {
                    x: _block.rect.x / baseRect.width,
                    y: _block.rect.y / baseRect.height,
                    width: _block.rect.width / baseRect.width,
                    height: _block.rect.height / baseRect.height
                  }
                };

                _this4._figurePointRectArray.push(rectInfo); // this.addRectNodeListener(block);


                if (_block.labelText) {
                  var k = +_block.labelText * 1000;

                  if (!isNaN(k)) {
                    _this4._hintsNodeList.push({
                      node: n,
                      after: k
                    });
                  }
                }
              }
            })();
          }
        }
      }); // console.log(this.data);

      console.log('resource perload finish'); // <<<<<<< HEAD
      // =======
      // 			if (window && window["air"]) {
      // 				// cc.find('Canvas').opacity = 0;
      // 				window.air.onCourseInScreen = (next) => {
      // 					// cc.find('Canvas').opacity = 255;
      // 					this.loadEnd();
      // 					next();
      // 				}
      // 				window.air.hideAirClassLoading();
      // 			} else {
      // 				this.loadEnd();
      // 			}
      // >>>>>>> 2d461e1910571bcfc6ad4dc93c2cedafc20923ea

      cc.debug.setDisplayStats(false);
    });
  },
  loadEnd: function loadEnd() {
    if (window && window["air"] && window["air"].hideAirClassLoading) {
      window["air"].hideAirClassLoading();
    }

    this.initData(); // this.initAudio();
    // this.initView();

    this.initBg(); // this.initListener();

    this.debugGraphics();
    this.createStateMachine();
  },
  _cantouch: null,
  initData: function initData() {
    // 所有全局变量 默认都是null 
    this._cantouch = true;
  },
  // audioBtn: null,
  // initAudio() {
  // 	const audioNode = cc.find('Canvas/res/audio');
  // 	const getAudioByResName = (resName) => {
  // 		return audioNode.getChildByName(resName).getComponent(cc.AudioSource);
  // 	}
  // 	this.audioBtn = getAudioByResName('btn');
  // },
  // initView() {
  // 	// this.initBg();
  // 	// this.initPic();
  // 	// this.initBtn();
  // 	this.initIcon();
  // },
  addRectNodeListener: function addRectNodeListener(data) {
    var bg = cc.find("Canvas/frame-border/ground/bg");
    var rate = bg.scale * bg.width / this.data.bgItem.rect.width;
    var rectNode = new cc.Node();
    rectNode.name = 'rect' + data.index;
    bg.addChild(rectNode);
    var ctx = rectNode.addComponent(cc.Graphics); // 红色矩形

    ctx.lineWidth = 4;
    ctx.strokeColor = cc.Color.BLACK;
    ctx.fillColor = cc.Color.WHITE.setA(100);
    var 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.anchorX = rectNode.anchorY = 0; // if (pageData.bgItem.isShowDebugLine) {

    ctx.rect(0, 0, rectNode.width, rectNode.height); // }

    ctx.stroke();
    ctx.fill();
  },
  initBg: function initBg() {
    var bgNode = cc.find('Canvas/bg');
    bgNode.scale = this._mapScaleMax;
    console.log('this._mapScaleMax', this._mapScaleMax);
  },

  /*initBtn() {
  		this.curPage = 0;
  	const bottomPart = cc.find('Canvas/bottomPart');
  	bottomPart.zIndex = 5; // 提高层级
  		bottomPart.x = bottomPart.parent.width / 2;
  	bottomPart.y = -bottomPart.parent.height / 2;
  		const leftBtnNode = bottomPart.getChildByName('btn_left');
  	//节点中添加了button组件 则可以添加click事件监听
  	leftBtnNode.on('click', () => {
  		if (!this._cantouch) {
  			return;
  		}
  		if (this.curPage == 0) {
  			return;
  		}
  		this.curPage = 0
  		this.leftMove();
  			// 游戏结束时需要调用这个方法通知系统作业完成
  		onHomeworkFinish();
  			cc.audioEngine.play(this.audioBtn.clip, false, 0.8)
  	})
  		const rightBtnNode = bottomPart.getChildByName('btn_right');
  	//节点中添加了button组件 则可以添加click事件监听
  	rightBtnNode.on('click', () => {
  		if (!this._cantouch) {
  			return;
  		}
  		if (this.curPage == 1) {
  			return;
  		}
  			this.curPage = 1
  		this.rightMove();
  			cc.audioEngine.play(this.audioBtn.clip, false, 0.5)
  	})
  },*/
  // update (dt) {},
  _timeoutIds: null,
  _intervalIds: null,
  // 生命周期
  onDestroy: function onDestroy() {
    console.log('op15 onDestroy');

    this._timeoutIds.forEach(function (id) {
      clearTimeout(id);
    });

    this._intervalIds.forEach(function (id) {
      clearInterval(id);
    });

    this.gameMachineService.stopChild();
    this.gameMachineService.stop();

    if (window.courseware && window.courseware.closeOsmoFingerRead) {
      if (this.isOpenedOsmoFingerRead) {
        window.courseware.closeOsmoFingerRead();
      }
    }
  }
});

cc._RF.pop();