"use strict";
cc._RF.push(module, 'f4edeRi+NdAabqAkVYRwFjK', 'op_01');
// op_01/scene/op_01.js

"use strict";

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

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

function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }

cc.Class({
  "extends": cc.Component,
  properties: {},
  // 生命周期 onLoad
  onLoad: function onLoad() {
    this.initSceneData();
    this.initSize();
  },
  _imageResList: null,
  _audioResList: null,
  _animaResList: null,
  initSceneData: function initSceneData() {
    this._imageResList = [];
    this._audioResList = [];
    this._animaResList = [];
  },
  _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;
  },
  // 生命周期 start
  start: function start() {
    var _this = this;

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

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

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

      _this.preloadItem();
    });
  },
  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 _defaultData.defaultData;
  },
  preloadItem: function preloadItem() {
    this.addPreloadImage();
    this.addPreloadAudio();
    this.addPreloadAnima();
    this.preload();
  },
  addPreloadImage: function addPreloadImage() {
    var _this$_imageResList;

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

    (_this$_imageResList = this._imageResList).push.apply(_this$_imageResList, this.data.hotZoneItemArr.map(function (data) {
      return data.pic_url;
    }).map(function (url) {
      return {
        url: url
      };
    }));
  },
  addPreloadAudio: function addPreloadAudio() {
    var _this$_imageResList2;

    (_this$_imageResList2 = this._imageResList).push.apply(_this$_imageResList2, this.data.hotZoneItemArr.map(function (data) {
      return data.audio_url;
    }).map(function (url) {
      return {
        url: url
      };
    }));

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

    this._audioResList.push({
      url: this.data.endAudio
    });
  },
  addPreloadAnima: function addPreloadAnima() {},
  preload: function preload() {
    var _this2 = this;

    var preloadArr = [].concat(this._imageResList, this._audioResList, this._animaResList);
    cc.assetManager.loadAny(preloadArr, null, null, function (err, data) {
      if (window && window["air"]) {
        cc.find('Canvas').opacity = 0;

        window.air.onCourseInScreen = function (next) {
          cc.find('Canvas').opacity = 255;

          _this2.loadEnd();

          next();
        };

        window.air.hideAirClassLoading();
      } else {
        _this2.loadEnd();
      }

      cc.debug.setDisplayStats(false);
    });
  },
  loadEnd: function loadEnd() {
    this.initData();
    this.initView();
    this.initListener();
  },
  initData: function initData() {},
  initView: function initView() {
    var _this3 = this;

    return _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2() {
      var canvas, bg;
      return regeneratorRuntime.wrap(function _callee2$(_context2) {
        while (1) {
          switch (_context2.prev = _context2.next) {
            case 0:
              _this3.coolCatSpeakStart();

              canvas = cc.find('Canvas');
              bg = cc.find('Canvas/ImgBg');
              _context2.next = 5;
              return _this3.asyncLoadSpriteByUrl(bg, _this3.data.bgItem.url);

            case 5:
              bg.scale = Math.max(canvas.width / bg.width, canvas.height / bg.height);
              _this3.itemList = [];

              _this3.data.hotZoneItemArr.forEach( /*#__PURE__*/function () {
                var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(itemData) {
                  var item;
                  return regeneratorRuntime.wrap(function _callee$(_context) {
                    while (1) {
                      switch (_context.prev = _context.next) {
                        case 0:
                          _context.next = 2;
                          return _this3.createItem(itemData, bg);

                        case 2:
                          item = _context.sent;

                          _this3.itemList.push(item);

                        case 4:
                        case "end":
                          return _context.stop();
                      }
                    }
                  }, _callee);
                }));

                return function (_x) {
                  return _ref.apply(this, arguments);
                };
              }());

            case 8:
            case "end":
              return _context2.stop();
          }
        }
      }, _callee2);
    }))();
  },
  shakeItem: function shakeItem(item) {
    var time = 0.05;
    cc.tween(item).to(time, {
      angle: 10
    }).to(time * 2, {
      angle: -10
    }).to(time, {
      angle: 0
    }).start();
  },
  coolCatAlreadySpeakEnd: null,
  createItem: function createItem(itemData, bg) {
    var _this4 = this;

    return _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee4() {
      var bgScale, item;
      return regeneratorRuntime.wrap(function _callee4$(_context4) {
        while (1) {
          switch (_context4.prev = _context4.next) {
            case 0:
              bgScale = bg.width / _this4.data.bgItem.rect.width;
              item = cc.instantiate(cc.find('item'));
              item.parent = bg;
              item.on('click', /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3() {
                return regeneratorRuntime.wrap(function _callee3$(_context3) {
                  while (1) {
                    switch (_context3.prev = _context3.next) {
                      case 0:
                        item.clicked = true;

                        _this4.shakeItem(item);

                        _context3.next = 4;
                        return _this4.asyncPlayAudioByUrl(itemData.audio_url);

                      case 4:
                        if (_this4.coolCatAlreadySpeakEnd) {
                          _context3.next = 12;
                          break;
                        }

                        if (!_this4.itemList.every(function (tmpItem) {
                          return tmpItem.clicked;
                        })) {
                          _context3.next = 12;
                          break;
                        }

                        _this4.coolCatAlreadySpeakEnd = true;
                        _context3.next = 9;
                        return (0, _util.asyncDelay)(0.3);

                      case 9:
                        _context3.next = 11;
                        return _this4.coolCatSpeakEnd();

                      case 11:
                        (0, _util.onHomeworkFinish)();

                      case 12:
                      case "end":
                        return _context3.stop();
                    }
                  }
                }, _callee3);
              })));
              _context4.next = 6;
              return _this4.asyncLoadSpriteByUrl(item, itemData.pic_url);

            case 6:
              item.scale = itemData.imgScale * bgScale;
              item.x = itemData.rect.x * bgScale - bg.width / 2 + item.width * item.scaleX / 2;
              item.y = bg.height / 2 - itemData.rect.y * bgScale - item.height * item.scaleY / 2;
              return _context4.abrupt("return", item);

            case 10:
            case "end":
              return _context4.stop();
          }
        }
      }, _callee4);
    }))();
  },
  initListener: function initListener() {},
  coolCatSpeakStart: function coolCatSpeakStart(cb) {
    var _this5 = this;

    return _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee5() {
      var cat;
      return regeneratorRuntime.wrap(function _callee5$(_context5) {
        while (1) {
          switch (_context5.prev = _context5.next) {
            case 0:
              cat = cc.find('Canvas/catFrame/cat');
              (0, _util.playDragonBoneAnimation)(cat, 'begin', -1);
              _context5.next = 4;
              return _this5.asyncPlayAudioByUrl(_this5.data.startAudio);

            case 4:
              (0, _util.playDragonBoneAnimation)(cat, 'normal', -1);

            case 5:
            case "end":
              return _context5.stop();
          }
        }
      }, _callee5);
    }))();
  },
  coolCatSpeakEnd: function coolCatSpeakEnd() {
    var _this6 = this;

    return _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee6() {
      var cat;
      return regeneratorRuntime.wrap(function _callee6$(_context6) {
        while (1) {
          switch (_context6.prev = _context6.next) {
            case 0:
              cat = cc.find('Canvas/catFrame/cat');
              (0, _util.playDragonBoneAnimation)(cat, 'finish', -1);
              _context6.next = 4;
              return _this6.asyncPlayAudioByUrl(_this6.data.endAudio);

            case 4:
              (0, _util.playDragonBoneAnimation)(cat, 'normal', -1);

            case 5:
            case "end":
              return _context6.stop();
          }
        }
      }, _callee6);
    }))();
  },
  asyncLoadSpriteByUrl: function asyncLoadSpriteByUrl(node, url) {
    return new Promise(function (resolve, reject) {
      cc.loader.load({
        url: url
      }, function (err, img) {
        var spriteFrame = new cc.SpriteFrame(img);
        var spr = node.getComponent(cc.Sprite);
        spr.spriteFrame = spriteFrame;
        resolve();
      });
    });
  },
  currentAudioId: null,
  stopCurrentAudio: function stopCurrentAudio() {
    if (this.currentAudioId !== null) {
      cc.audioEngine.stop(this.currentAudioId);
      this.currentAudioId = null;
    }
  },
  asyncPlayAudioByUrl: function asyncPlayAudioByUrl(audio_url) {
    var _this7 = this;

    if (!audio_url) {
      return;
    }

    return new Promise(function (resolve, reject) {
      cc.assetManager.loadRemote(audio_url, function (err, audioClip) {
        _this7.stopCurrentAudio();

        var audioId = cc.audioEngine.play(audioClip, false, 0.8);
        cc.audioEngine.setFinishCallback(audioId, function () {
          resolve();
        });
      });
    });
  }
});

cc._RF.pop();