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

"use strict";

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

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

cc.Class({
  "extends": cc.Component,
  properties: {
    mouses: {
      "default": [],
      type: cc.Node
    },
    title: {
      "default": null,
      type: cc.Label
    },
    timer: {
      "default": null,
      type: cc.Label
    },
    timer1: {
      "default": null,
      type: cc.Label
    }
  },
  // 生命周期 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();
    });
    this.adjustMousePosition();
    this._flower = cc.find('Canvas/flower');
    this._flower.active = false;
    this._comeon = cc.find('Canvas/comeon');
    this._comeon.active = false;
  },
  adjustMousePosition: function adjustMousePosition() {
    var item,
        len = this.mouses.length;
    var rx = this._frameSize.width / this._frameSize.height / (this._designSize.width / this._designSize.height);
    rx = Math.max(rx, 1);

    for (var i = 0; i < len; i++) {
      item = this.mouses[i];
      item.x *= rx; //item.active = false;

      item._y0 = item.y;
      item._y1 = item.y - item.height * 2;
      item.y = item._y1;
    }
  },
  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() {},
  addPreloadAudio: function addPreloadAudio() {},
  addPreloadAnima: function addPreloadAnima() {},
  preload: function preload() {
    var _this2 = this;

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

    cc.assetManager.loadAny(preloadArr, null, null, function (err, data) {
      _this2.loadEnd();

      if (window && window["air"]) {
        window["air"].hideAirClassLoading();
      }

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

    window.WL = this;
    this._touched = false;
    this._hammer = cc.find('Canvas/hammer');
    this.updateFlagArea();
    this.title.string = this.data.title;

    if (this.data.random != null) {
      this.data.answer = this.data.random.split(',');
      console.log(this.data.random);
    }

    this._start = cc.find('Canvas/start');

    this._start.on('click', function () {
      _this3._start.active = false; // let audio_url = this.data.audio_url;
      // if (audio_url && audio_url!=""){
      // 	playAudioByUrl(audio_url, ()=>{
      // 		this.playGame();
      // 	});
      // }
      // else{

      _this3.playGame(); // }	

    });

    this.node.on(cc.Node.EventType.TOUCH_START, function (event) {
      if (!_this3._touched) return;
      var canvas = cc.find('Canvas');
      var pos = canvas.convertToNodeSpaceAR(cc.v2(event.touch._point.x, event.touch._point.y));
      var item,
          len = _this3.mouses.length;

      for (var i = 0; i < len; i++) {
        item = _this3.mouses[i];

        if (item.active && cc.rect(item.getBoundingBoxToWorld()).contains(event.touch._point)) {
          _this3._hammer.x = pos.x;
          _this3._hammer.y = pos.y;
          _this3._touched = false;

          _this3.playAudioByName(_this3.hit_result == false ? 'incorrect' : 'correct');

          _this3.sendAnswer(_this3._astr, !(_this3.hit_result == false));

          if (_this3.hit_result != false) {
            _this3.updateFlag();
          } else {
            _this3.currentOutline(_this3.mouse_id, false);
          }

          cc.tween(item).delay(0.5).call(function () {
            _this3.playAudioByName('dizzy');
          }).start();
          (0, _util.playDragonBoneAnimation)(_this3._hammer.children[0], 'normal', 1, function () {
            _this3._hammer.y = -1000;

            _this3.hitMouse(item);
          });
          return;
        }
      }

      var ground = cc.find('Canvas/ground');

      if (cc.rect(ground.getBoundingBoxToWorld()).contains(event.touch._point)) {
        _this3._hammer.x = pos.x;
        _this3._hammer.y = pos.y;

        _this3.playAudioByName('missed');

        (0, _util.playDragonBoneAnimation)(_this3._hammer.children[0], 'normal', 1, function () {
          _this3._hammer.y = -1000;
        });
      }
    }, this);
  },
  setLaughAni: function setLaughAni() {
    var _this4 = this;

    this._laugh = cc.tween(this.title.node).delay(3).call(function () {
      _this4.playAudioByName('laugh');

      _this4.setLaughAni();
    }).start();
  },
  playGame: function playGame() {
    var _this5 = this;

    this.updateFlagArea(function () {
      //this.playAudioByName('time321');
      //this.playTimer(()=>{
      _this5.nextMouse(); //})

    });
  },
  updateFlagArea: function updateFlagArea(cb) {
    var flag_area = cc.find('Canvas/flag_area');
    flag_area.removeAllChildren();
    var node = cc.find('res/img/icon_0');
    var lyt = flag_area.getComponent(cc.Layout);
    var width = flag_area.width - lyt.paddingRight;
    var padding_x = lyt.spacingX;
    var item,
        len = this.data.mouses.length;

    for (var i = 0; i < len; i++) {
      item = cc.instantiate(node);
      flag_area.addChild(item);
      item.y = 0;
      item.scale = this.Between(0.5, (width / len - padding_x) / item.width, 1);
      item.flag = item.getComponent(cc.Sprite);
      item.flag1 = item.getChildByName('icon_1');
      item.correct = item.getChildByName('icon_correct');
      item.incorrect = item.getChildByName('icon_incorrect');
    }

    this._mouse_index = 0;
    cb && cb();
  },
  nextMouse: function nextMouse() {
    var _this6 = this;

    this._startTime = this.getTime();
    console.log(this._startTime);
    var item,
        len = this.mouses.length;
    var mouse_id = (0, _util.RandomInt)(len);
    var info = this.data.mouses[this._mouse_index];

    if (this._time_ani) {
      this._time_ani.stop();

      this._time_ani = null;
    }

    var show_word = info.word;
    this.hit_result = true;

    if (this.data.answer != null) {
      if (this.data.answer.length > 0) {
        show_word = this.data.answer[(0, _util.RandomInt)(this.data.answer.length)];
      }

      if (show_word == '' || show_word == ' ' || show_word == ',') {
        show_word = info.word;
      }

      this.hit_result = info.word == show_word.toUpperCase() || info.word == show_word.toLowerCase();
    }

    console.log('show:' + show_word + ',target:' + info.word + " " + this.hit_result);
    this._aiexerciseid = info.aiexerciseid;
    this._astr = info.word;
    this.currentOutline(this._mouse_index);

    for (var i = 0; i < len; i++) {
      item = this.mouses[i];
      item.y = item._y1;
      item.active = false;

      if (mouse_id == i) {
        (function () {
          item.active = true;
          var mouse = item.getComponent(cc.js.getClassByName('Mouse'));
          mouse.init();
          mouse.setTitle(show_word);
          mouse.audio = info.audio_url;
          mouse.playAudio();

          _this6.moveUp(mouse.node, function () {
            _this6.setLaughAni();

            _this6._time_ani = cc.tween(_this6.node).delay(_this6.data.time).call(function () {
              if (_this6.hit_result == false) {
                _this6.sendAnswer(_this6._astr, true);

                _this6.updateFlag();
              } else {
                _this6.sendAnswer();

                _this6.currentOutline(_this6.mouse_id, false);
              }

              _this6.moveDown(mouse.node, function () {
                _this6.tryFinished();
              });
            }).start();
          });
        })();
      }
    }
  },
  moveUp: function moveUp(node, cb) {
    var _this7 = this;

    cc.tween(node).to(0.3, {
      y: node._y0
    }).call(function () {
      cb && cb();
      _this7._touched = true;
    }).start();
  },
  moveDown: function moveDown(node, cb) {
    this._touched = false;
    cc.tween(node).to(0.3, {
      y: node._y1
    }).call(function () {
      cb && cb();
    }).start();
  },
  hitMouse: function hitMouse(node) {
    if (this._time_ani) {
      this._time_ani.stop();

      this._time_ani = null;
    }

    if (this._laugh) {
      this._laugh.stop();

      this._laugh = null;
    }

    var mouse = node.getComponent(cc.js.getClassByName('Mouse'));
    mouse.hit();
  },
  afterHit: function afterHit(item) {
    var _this8 = this;

    this.moveDown(item, function () {
      _this8.tryFinished();
    });
  },
  updateFlag: function updateFlag() {
    var item = this.currentFlag();
    item.flag.enabled = false;
    item.flag1.active = true;
    item.correct.active = false;
    item.incorrect.active = false;
    cc.tween(item.flag1).to(0.1, {
      scale: 1.2
    }, {
      easing: 'quadIn'
    }).to(0.2, {
      scale: 0.8
    }, {
      easing: 'quadOut'
    }).to(0.1, {
      scale: 1
    }, {
      easing: 'quadIn'
    }).start();
  },
  currentFlag: function currentFlag() {
    var flag_number = this.data.mouses.length;
    var flag_index = this._mouse_index;
    var idx = flag_number - flag_index - 1;
    var area = cc.find('Canvas/flag_area');
    return area.children[idx];
  },
  currentOutline: function currentOutline(idx, correct) {
    if (correct === void 0) {
      correct = true;
    }

    var item = this.currentFlag(idx);
    item.flag.enabled = true;
    item.flag1.active = false;
    item.correct.active = correct;
    item.incorrect.active = !correct;
  },
  tryFinished: function tryFinished() {
    var _this9 = this;

    if (this._finished == true) return;

    if (this._laugh) {
      this._laugh.stop();

      this._laugh = null;
    }

    this._mouse_index++;

    if (this._mouse_index >= this.data.mouses.length) {
      this._finished = true;

      if (this.failure() == true) {
        this.playAudioByName('lose');
        this._comeon.active = true;
        (0, _util.playDragonBoneAnimation)(this._comeon, 'newAnimation', 1, function () {
          _this9._comeon.active = false;

          _this9.gameEnd();
        });
      } else {
        this.playAudioByName('victory');
        this._flower.active = true;
        (0, _util.playDragonBoneAnimation)(this._flower, 'normal', 1, this.gameEnd);
      }

      return;
    }

    this.nextMouse();
  },
  gameEnd: function gameEnd() {
    if (window && window.courseware) {
      window.courseware.gameEnd();
    }
  },
  sendAnswer: function sendAnswer(answer, isRight) {
    if (answer === void 0) {
      answer = "";
    }

    if (isRight === void 0) {
      isRight = false;
    }

    console.log(this._aiexerciseid, answer, isRight, this._startTime);

    if (window && window.courseware) {
      window.courseware.sendAnswer(this._aiexerciseid, answer, isRight, this._startTime);
    }
  },
  getTime: function getTime() {
    var date = new Date();
    return date.getTime();
  },
  playTimer: function playTimer(cb) {
    var _this10 = this;

    this.timer.node.active = true;
    this.setTimerString('3');
    cc.tween(this.timer.node).to(0.25, {
      scale: 1.2
    }, {
      easing: 'quadIn'
    }).to(0.5, {
      scale: 0.8
    }, {
      easing: 'quadOut'
    }).to(0.25, {
      scale: 1
    }, {
      easing: 'quadIn'
    }).call(function () {
      _this10.setTimerString('2');
    }).to(0.25, {
      scale: 1.2
    }, {
      easing: 'quadIn'
    }).to(0.5, {
      scale: 0.8
    }, {
      easing: 'quadOut'
    }).to(0.25, {
      scale: 1
    }, {
      easing: 'quadIn'
    }).call(function () {
      _this10.setTimerString('1');
    }).to(0.25, {
      scale: 1.2
    }, {
      easing: 'quadIn'
    }).to(0.5, {
      scale: 0.8
    }, {
      easing: 'quadOut'
    }).to(0.25, {
      scale: 1
    }, {
      easing: 'quadIn'
    }).call(function () {
      _this10.timer.node.active = false;
      cb && cb();
    }).start();
  },
  setTimerString: function setTimerString(str) {
    this.timer.string = str;
    this.timer1.string = str;
  },
  failure: function failure() {
    var area = cc.find('Canvas/flag_area');
    var len = area.childrenCount;
    var count = 0;

    for (var i = 0; i < len; i++) {
      if (area.children[i].incorrect.active == true) count++;
    }

    console.log(count / len);
    return count / len >= 0.4;
  },
  // update (dt) {},
  Between: function Between(a, b, c) {
    return [a, b, c].sort()[1];
  },
  // ------------------------------------------------
  getSprNode: 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;
  },
  getSpriteFrimeByUrl: function getSpriteFrimeByUrl(url, cb) {
    cc.loader.load({
      url: url
    }, function (err, img) {
      var spriteFrame = new cc.SpriteFrame(img);

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

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

    if (audio_url) {
      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();
          });
        }
      });
    }
  },
  playAudioByName: function playAudioByName(audioName) {
    return new Promise(function (resolve, reject) {
      try {
        var audioNode = cc.find('res/audio/' + audioName);
        var audioClip = audioNode.getComponent(cc.AudioSource).clip;
        (0, _util.playAudio)(audioClip, resolve);
      } catch (e) {
        reject(e);
      }
    });
  } // ------------------------------------------

});

cc._RF.pop();