"use strict";
cc._RF.push(module, 'ade7a9A1W1Ah7vGKIj+9VNT', 'util');
// OP15/script/util.js

"use strict";

exports.__esModule = true;
exports.getPosByAngle = getPosByAngle;
exports.getAngleByPos = getAngleByPos;
exports.exchangeNodePos = exchangeNodePos;
exports.RandomInt = RandomInt;
exports.randomSortByArr = randomSortByArr;
exports.setSprNodeMaxLen = setSprNodeMaxLen;
exports.localPosTolocalPos = localPosTolocalPos;
exports.worldPosToLocalPos = worldPosToLocalPos;
exports.getScaleRateBy2Node = getScaleRateBy2Node;
exports.getDistance = getDistance;
exports.playAudioByUrl = playAudioByUrl;
exports.btnClickAnima = btnClickAnima;
exports.getSpriteFrimeByUrl = getSpriteFrimeByUrl;
exports.getSprNode = getSprNode;
exports.getSprNodeByUrl = getSprNodeByUrl;
exports.playAudio = playAudio;
exports.asyncDelay = asyncDelay;
exports.showFireworks = showFireworks;
exports.asyncTweenTo = asyncTweenTo;
exports.asyncTweenBy = asyncTweenBy;
exports.showTrebleFirework = showTrebleFirework;
exports.onHomeworkFinish = onHomeworkFinish;
exports.loadDragonBones = loadDragonBones;
exports.loadSpine = loadSpine;
exports.FireworkSettings = void 0;

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

function getPosByAngle(angle, len) {
  var radian = angle * Math.PI / 180;
  var x = Math.sin(radian) * len;
  var y = Math.cos(radian) * len;
  return {
    x: x,
    y: y
  };
}

function getAngleByPos(px, py, mx, my) {
  var x = Math.abs(px - mx);
  var y = Math.abs(py - my);
  var z = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
  var cos = y / z;
  var radina = Math.acos(cos); // 用反三角函数求弧度

  var angle = Math.floor(180 / (Math.PI / radina) * 100) / 100; // 将弧度转换成角度

  if (mx > px && my > py) {
    // 鼠标在第四象限
    angle = 180 - angle;
  }

  if (mx === px && my > py) {
    // 鼠标在y轴负方向上
    angle = 180;
  }

  if (mx > px && my === py) {
    // 鼠标在x轴正方向上
    angle = 90;
  }

  if (mx < px && my > py) {
    // 鼠标在第三象限
    angle = 180 + angle;
  }

  if (mx < px && my === py) {
    // 鼠标在x轴负方向
    angle = 270;
  }

  if (mx < px && my < py) {
    // 鼠标在第二象限
    angle = 360 - angle;
  } // console.log('angle: ', angle);


  return angle;
}

function exchangeNodePos(baseNode, targetNode) {
  return baseNode.convertToNodeSpaceAR(targetNode._parent.convertToWorldSpaceAR(cc.v2(targetNode.x, targetNode.y)));
}

function RandomInt(a, b) {
  if (b === void 0) {
    b = 0;
  }

  var max = Math.max(a, b);
  var min = Math.min(a, b);
  return Math.floor(Math.random() * (max - min) + min);
}

function randomSortByArr(arr) {
  var newArr = [];
  var tmpArr = arr.concat();

  while (tmpArr.length > 0) {
    var randomIndex = Math.floor(tmpArr.length * Math.random());
    newArr.push(tmpArr[randomIndex]);
    tmpArr.splice(randomIndex, 1);
  }

  return newArr;
}

function setSprNodeMaxLen(sprNode, maxW, maxH) {
  var sx = maxW / sprNode.width;
  var sy = maxH / sprNode.height;
  var s = Math.min(sx, sy);
  sprNode.scale = Math.round(s * 1000) / 1000;
}

function localPosTolocalPos(baseNode, targetNode) {
  var worldPos = targetNode.parent.convertToWorldSpaceAR(cc.v2(targetNode.x, targetNode.y));
  var localPos = baseNode.parent.convertToNodeSpaceAR(cc.v2(worldPos.x, worldPos.y));
  return localPos;
}

function worldPosToLocalPos(worldPos, baseNode) {
  var localPos = baseNode.parent.convertToNodeSpaceAR(cc.v2(worldPos.x, worldPos.y));
  return localPos;
}

function getScaleRateBy2Node(baseNode, targetNode, maxFlag) {
  if (maxFlag === void 0) {
    maxFlag = true;
  }

  var worldRect1 = targetNode.getBoundingBoxToWorld();
  var worldRect2 = baseNode.getBoundingBoxToWorld();
  var sx = worldRect1.width / worldRect2.width;
  var sy = worldRect1.height / worldRect2.height;

  if (maxFlag) {
    return Math.max(sx, sy);
  } else {
    return Math.min(sx, sy);
  }
}

function getDistance(start, end) {
  var pos = cc.v2(start.x - end.x, start.y - end.y);
  var dis = Math.sqrt(pos.x * pos.x + pos.y * pos.y);
  return dis;
}

function playAudioByUrl(audio_url, cb) {
  if (cb === void 0) {
    cb = null;
  }

  if (audio_url) {
    if (audio_url instanceof cc.AudioClip && audio_url.constructor.name == 'cc_AudioClip') {
      var audioId = cc.audioEngine.play(audio_url, false, 0.8);

      if (cb) {
        cc.audioEngine.setFinishCallback(audioId, function () {
          cb();
        });
      }
    } else {
      cc.assetManager.loadRemote(audio_url, function (err, audioClip) {
        var audioId = cc.audioEngine.play(audioClip, false, 0.8);

        if (cb) {
          cc.audioEngine.setFinishCallback(audioId, function () {
            cb();
          });
        }
      });
    }
  }
}

function btnClickAnima(btn, time, rate) {
  if (time === void 0) {
    time = 0.15;
  }

  if (rate === void 0) {
    rate = 1.05;
  }

  btn.tmpScale = btn.scale;
  btn.on(cc.Node.EventType.TOUCH_START, function () {
    cc.tween(btn).to(time / 2, {
      scale: btn.scale * rate
    }).start();
  });
  btn.on(cc.Node.EventType.TOUCH_CANCEL, function () {
    cc.tween(btn).to(time / 2, {
      scale: btn.tmpScale
    }).start();
  });
  btn.on(cc.Node.EventType.TOUCH_END, function () {
    cc.tween(btn).to(time / 2, {
      scale: btn.tmpScale
    }).start();
  });
}

function getSpriteFrimeByUrl(url, cb) {
  cc.loader.load({
    url: url
  }, function (err, img) {
    var spriteFrame = new cc.SpriteFrame(img);

    if (cb) {
      cb(spriteFrame);
    }
  });
}

function getSprNode(resName) {
  var sf = cc.find('Canvas/res/img/' + resName).getComponent(cc.Sprite).spriteFrame;
  var node = new cc.Node();
  node.addComponent(cc.Sprite).spriteFrame = sf;
  return node;
}

function getSprNodeByUrl(url, cb) {
  var node = new cc.Node();
  var spr = node.addComponent(cc.Sprite);
  getSpriteFrimeByUrl(url, function (sf) {
    spr.spriteFrame = sf;

    if (cb) {
      cb(spr);
    }
  });
}

function playAudio(audioClip, cb) {
  if (cb === void 0) {
    cb = null;
  }

  if (audioClip) {
    var audioId = cc.audioEngine.playEffect(audioClip, false, 0.8);

    if (cb) {
      cc.audioEngine.setFinishCallback(audioId, function () {
        cb();
      });
    }
  }
}

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

function _asyncDelay() {
  _asyncDelay = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(time) {
    return regeneratorRuntime.wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            return _context.abrupt("return", new Promise(function (resolve, reject) {
              try {
                setTimeout(function () {
                  resolve();
                }, time * 1000);
              } catch (e) {
                reject(e);
              }
            }));

          case 1:
          case "end":
            return _context.stop();
        }
      }
    }, _callee);
  }));
  return _asyncDelay.apply(this, arguments);
}

var FireworkSettings = /*#__PURE__*/function () {
  // 父节点
  // 火花节点的array
  // 发射点
  // 发射方向
  // 扩散范围
  // 发射数量
  // 缩放范围
  function FireworkSettings(baseNode, nodeList, pos, side, range, number, scalseRange) {
    if (pos === void 0) {
      pos = cc.v2(0, 0);
    }

    if (side === void 0) {
      side = cc.v2(0, 100);
    }

    if (range === void 0) {
      range = 50;
    }

    if (number === void 0) {
      number = 100;
    }

    if (scalseRange === void 0) {
      scalseRange = 0;
    }

    this.baseNode = void 0;
    this.nodeList = void 0;
    this.pos = void 0;
    this.side = void 0;
    this.range = void 0;
    this.number = void 0;
    this.scalseRange = void 0;
    this.baseNode = baseNode;
    this.nodeList = nodeList;
    this.pos = pos;
    this.side = side;
    this.range = range;
    this.number = number;
    this.scalseRange = scalseRange;
  }

  FireworkSettings.copy = function copy(firework) {
    return new FireworkSettings(firework.baseNode, firework.nodeList, firework.pos, firework.side, firework.range, firework.number);
  };

  return FireworkSettings;
}();

exports.FireworkSettings = FireworkSettings;

function showFireworks(_x2) {
  return _showFireworks.apply(this, arguments);
}

function _showFireworks() {
  _showFireworks = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3(fireworkSettings) {
    var baseNode, nodeList, pos, side, range, number, scalseRange;
    return regeneratorRuntime.wrap(function _callee3$(_context3) {
      while (1) {
        switch (_context3.prev = _context3.next) {
          case 0:
            baseNode = fireworkSettings.baseNode, nodeList = fireworkSettings.nodeList, pos = fireworkSettings.pos, side = fireworkSettings.side, range = fireworkSettings.range, number = fireworkSettings.number, scalseRange = fireworkSettings.scalseRange;
            new Array(number).fill(' ').forEach( /*#__PURE__*/function () {
              var _ref3 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(_, i) {
                var rabbonNode, node, rate, angle;
                return regeneratorRuntime.wrap(function _callee2$(_context2) {
                  while (1) {
                    switch (_context2.prev = _context2.next) {
                      case 0:
                        rabbonNode = new cc.Node();
                        rabbonNode.parent = baseNode;
                        rabbonNode.x = pos.x;
                        rabbonNode.y = pos.y;
                        rabbonNode.angle = 60 * Math.random() - 30;
                        node = cc.instantiate(nodeList[RandomInt(nodeList.length)]);
                        node.parent = rabbonNode;
                        node.active = true;
                        node.x = 0;
                        node.y = 0;
                        node.angle = 0;
                        node.scale = (Math.random() - 0.5) * scalseRange + 1;
                        rate = Math.random();
                        angle = Math.PI * (Math.random() * 2 - 1);
                        _context2.next = 16;
                        return asyncTweenBy(rabbonNode, 0.3, {
                          x: side.x * rate + Math.cos(angle) * range * rate,
                          y: side.y * rate + Math.sin(angle) * range * rate
                        }, {
                          easing: 'quadIn'
                        });

                      case 16:
                        cc.tween(rabbonNode).by(8, {
                          y: -2000
                        }).start();
                        cc.tween(rabbonNode).to(5, {
                          scale: (Math.random() - 0.5) * scalseRange + 1
                        }).start();
                        rabbonFall(rabbonNode);
                        _context2.next = 21;
                        return asyncDelay(Math.random());

                      case 21:
                        cc.tween(node).by(0.15, {
                          x: -10,
                          angle: -10
                        }).by(0.3, {
                          x: 20,
                          angle: 20
                        }).by(0.15, {
                          x: -10,
                          angle: -10
                        }).union().repeatForever().start();
                        cc.tween(rabbonNode).delay(5).to(0.3, {
                          opacity: 0
                        }).call(function () {
                          node.stopAllActions();
                          node.active = false;
                          node.parent = null;
                          node = null;
                        }).start();

                      case 23:
                      case "end":
                        return _context2.stop();
                    }
                  }
                }, _callee2);
              }));

              return function (_x12, _x13) {
                return _ref3.apply(this, arguments);
              };
            }());

          case 2:
          case "end":
            return _context3.stop();
        }
      }
    }, _callee3);
  }));
  return _showFireworks.apply(this, arguments);
}

function rabbonFall(_x3) {
  return _rabbonFall.apply(this, arguments);
}

function _rabbonFall() {
  _rabbonFall = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee4(node) {
    var time, offsetX;
    return regeneratorRuntime.wrap(function _callee4$(_context4) {
      while (1) {
        switch (_context4.prev = _context4.next) {
          case 0:
            time = 1 + Math.random();
            offsetX = RandomInt(-200, 200) * time;
            _context4.next = 4;
            return asyncTweenBy(node, time, {
              x: offsetX,
              angle: offsetX * 60 / 200
            });

          case 4:
            rabbonFall(node);

          case 5:
          case "end":
            return _context4.stop();
        }
      }
    }, _callee4);
  }));
  return _rabbonFall.apply(this, arguments);
}

function asyncTweenTo(_x4, _x5, _x6, _x7) {
  return _asyncTweenTo.apply(this, arguments);
}

function _asyncTweenTo() {
  _asyncTweenTo = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee5(node, duration, obj, ease) {
    return regeneratorRuntime.wrap(function _callee5$(_context5) {
      while (1) {
        switch (_context5.prev = _context5.next) {
          case 0:
            if (ease === void 0) {
              ease = undefined;
            }

            return _context5.abrupt("return", new Promise(function (resolve, reject) {
              try {
                cc.tween(node).to(duration, obj, ease).call(function () {
                  resolve();
                }).start();
              } catch (e) {
                reject(e);
              }
            }));

          case 2:
          case "end":
            return _context5.stop();
        }
      }
    }, _callee5);
  }));
  return _asyncTweenTo.apply(this, arguments);
}

function asyncTweenBy(_x8, _x9, _x10, _x11) {
  return _asyncTweenBy.apply(this, arguments);
}

function _asyncTweenBy() {
  _asyncTweenBy = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee6(node, duration, obj, ease) {
    return regeneratorRuntime.wrap(function _callee6$(_context6) {
      while (1) {
        switch (_context6.prev = _context6.next) {
          case 0:
            if (ease === void 0) {
              ease = undefined;
            }

            return _context6.abrupt("return", new Promise(function (resolve, reject) {
              try {
                cc.tween(node).by(duration, obj, ease).call(function () {
                  resolve();
                }).start();
              } catch (e) {
                reject(e);
              }
            }));

          case 2:
          case "end":
            return _context6.stop();
        }
      }
    }, _callee6);
  }));
  return _asyncTweenBy.apply(this, arguments);
}

function showTrebleFirework(baseNode, rabbonList) {
  var middle = new FireworkSettings(baseNode, rabbonList);
  middle.pos = cc.v2(0, -400);
  middle.side = cc.v2(0, 1000);
  middle.range = 200;
  middle.number = 100;
  middle.scalseRange = 0.4;
  var left = FireworkSettings.copy(middle);
  left.pos = cc.v2(-600, -400);
  left.side = cc.v2(200, 1000);
  var right = FireworkSettings.copy(middle);
  right.pos = cc.v2(600, -400);
  right.side = cc.v2(-200, 1000);
  showFireworks(middle);
  showFireworks(left);
  showFireworks(right);
}

function onHomeworkFinish() {
  var middleLayer = cc.find('middleLayer');

  if (middleLayer) {
    var middleLayerComponent = middleLayer.getComponent('middleLayer');

    if (middleLayerComponent.role == 'student') {
      middleLayerComponent.onHomeworkFinish(function () {});
    }
  } else {
    console.log('onHomeworkFinish');
  }
}

function loadDragonBones(dragonDisplay, _ref) {
  var tex = _ref.tex,
      atlas = _ref.atlas,
      ske = _ref.ske;
  return new Promise(function (resolve, reject) {
    cc.loader.load({
      url: tex,
      type: 'png'
    }, function (error, texture) {
      if (error) {
        reject();
        return;
      }

      cc.loader.load({
        url: atlas,
        type: 'txt'
      }, function (error, atlasJson) {
        if (error) {
          reject();
          return;
        }

        cc.loader.load({
          url: ske,
          type: 'txt'
        }, function (error, dragonBonesJson) {
          if (error) {
            reject();
            return;
          }

          var atlasObj = new dragonBones.DragonBonesAtlasAsset();
          atlasObj.uuid = atlas;
          atlasObj.atlasJson = atlasJson;
          atlasObj.texture = texture;
          var asset = new dragonBones.DragonBonesAsset();
          asset.uuid = ske;
          asset.dragonBonesJson = dragonBonesJson;
          var armatureName = asset._dragonBonesJsonData.armature[0].name || 'default';
          dragonDisplay.armatureName = armatureName;
          dragonDisplay.dragonAtlasAsset = atlasObj;
          dragonDisplay.dragonAsset = asset;
          resolve(asset._dragonBonesJsonData.armature[0].aabb);
        });
      });
    });
  });
}

function loadSpine(skeleton, picName, _ref2) {
  var tex = _ref2.tex,
      atlas = _ref2.atlas,
      ske = _ref2.ske;
  return new Promise(function (resolve, reject) {
    // cc.loader.load({ url: tex, type: 'png' }, (error, texture) => {
    cc.assetManager.loadRemote(tex, function (error, texture) {
      if (error) {
        reject();
        return;
      } // cc.loader.load({ url: atlas, type: 'txt' }, (error, atlasJson) => {


      cc.assetManager.loadAny({
        url: atlas
      }, function (error, atlasJson) {
        if (error) {
          reject();
          return;
        } // cc.loader.load({ url: ske, type: 'txt' }, (error, dragonBonesJson) => {


        cc.assetManager.loadAny({
          url: ske
        }, function (error, dragonBonesJson) {
          if (error) {
            reject();
            return;
          }

          var asset = new sp.SkeletonData();
          asset._uuid = ske;
          asset.skeletonJson = JSON.stringify(dragonBonesJson);
          asset.atlasText = atlasJson;
          asset.textures = [texture];
          asset.textureNames = [picName];
          console.log('picName: ', picName);
          skeleton.skeletonData = asset;
          var jsonObj = dragonBonesJson; //JSON.parse( assets[1]);

          var animationNameObj = jsonObj.animations;
          var animationNames = [];

          for (var name in animationNameObj) {
            console.log('name~~:  ', name);
            animationNames.push(name);
          }

          console.log("skeleton.animation: ", skeleton.animation);
          skeleton.animationNames = animationNames;
          skeleton.loop = false;
          console.log("jsonObj['skeleton'] : ", jsonObj['skeleton']);
          resolve(jsonObj['skeleton']); // const atlasObj = new dragonBones.DragonBonesAtlasAsset()
          // atlasObj.uuid = atlas
          // atlasObj.atlasJson = atlasJson
          // atlasObj.texture = texture
          // const asset = new dragonBones.DragonBonesAsset()
          // asset.uuid = ske
          // asset.dragonBonesJson = dragonBonesJson;
          // const armatureName = asset._dragonBonesJsonData.armature[0].name || 'default';
          // dragonDisplay.armatureName = armatureName;
          // dragonDisplay.dragonAtlasAsset = atlasObj
          // dragonDisplay.dragonAsset = asset;
          // resolve(asset._dragonBonesJsonData.armature[0].aabb);
        });
      });
    });
  });
}

cc._RF.pop();