/**
 * Created by rockyl on 2018/8/16.
 */

import { props } from "../props";
import { playSound, createSvga } from "./utils";
import ObjectPool = engine.ObjectPool;
import { getTextureByName } from "./utils";
import { Goods } from "./Goods";
import { PoolName } from "./object-pool-init";
import { FrontBoxs } from "./frontBox";
import { BackBoxs } from "./backBox";
import { Zhuazi } from './Zhuazi';

export default class GameView extends engine.Container {
  private _hasSetup;

  //触摸层
  private rectBg: engine.Rect;
  //npc层
  private NpcBg: engine.Container;
  //盒子1
  private box1: engine.Container;
  //盒子2
  private box2: engine.Container;
  //盒子3
  private box3: engine.Container;
  //盒子4
  private box4: engine.Container;
  //盒子5
  private box5: engine.Container;
  //前传输区域
  private frontTransfer: engine.Container;
  //后传输区域
  private backTransfer: engine.Container;
  //前台板
  private frontDesk: engine.Sprite;
  //后台板
  private backDesk: engine.Sprite;
  private _frontBoxs: FrontBoxs;
	private _backBoxs: BackBoxs;
	private _Zhuazi: Zhuazi;
	private prizeBox: engine.Container;
	private rect;
  //当前分数
	private score;
	
	//中奖盒子移动距离
	private moveTime;

  //游戏状态
  private gameIng;
  //是否已获取位移值
  public startstatus=false;
  //是否中奖
  public ifPrize=false;
  //npc出身计时器
  private timer;
  //倒计时计时器
  private countdownTimer: any;
  //倒计时
  private countdown: number;

  //当前速度
  private speed: number;

  // 当前场景上面的物品
  private goodsItems = [];

  private _goods: Goods;

  constructor() {
    super();
    this.once(engine.Event.ADDED_TO_STAGE, this.setup, this);
  }

  // private waterSvga;
  // private boomSvga;
  // private playerSvga;

  setup() {
    if (this._hasSetup) {
      return;
    }

    this._hasSetup = true;
		const frontBoxs = (this._frontBoxs = new FrontBoxs());
		this._frontBoxs.GameView = this;
		const backBoxs = (this._backBoxs = new BackBoxs());
		this._Zhuazi = new Zhuazi();
		this._Zhuazi.GameView = this;
    this.frontTransfer = new engine.Container();
    this.backTransfer = new engine.Container();
    this.frontTransfer.width = 0;
    this.frontTransfer.height = 0;
    this.frontTransfer.alpha = 1;
    // this.frontTransfer.x = 0;
    // this.frontTransfer.y = 434;

    this.backTransfer.width = 0;
    this.backTransfer.height = 0;
    this.backTransfer.alpha = 1;
    // this.backTransfer.x = 0;
    // this.backTransfer.y = 390;
		this.rect = new engine.Rect();
		// this.rect.width = 608;
		this.rect.width = 611;
		this.rect.height = 704;
		this.rect.x = 65;
		this.rect.y = 263;
    this.NpcBg = new engine.Container();
		this.addChild(this.NpcBg);
		this.addChild(this.rect);
		
		
		
		let gameBg = new engine.Sprite(getTextureByName("游戏背景"));
		gameBg.x = 65;
		gameBg.y = 263;
		this.NpcBg.addChild(gameBg);
		
    this.frontDesk = new engine.Sprite(getTextureByName("前传输带"));
    this.frontDesk.x = 60;
    this.frontDesk.y = 781;

    this.backDesk = new engine.Sprite(getTextureByName("后传输带"));
    this.backDesk.x = 60;
    this.backDesk.y = 712;

    this.NpcBg.addChild(this.backDesk);
    this.NpcBg.addChild(this.frontDesk);
    this.NpcBg.addChild(this.backTransfer);
		this.NpcBg.addChild(this.frontTransfer);
		this.NpcBg.addChild(this._Zhuazi);

		this.NpcBg.mask = this.rect;
		this._Zhuazi.setup();
		
		// this._Zhuazi.move();
		this.backTransfer.addChild(this._backBoxs);
		this._backBoxs.setup();
		this.frontTransfer.addChild(this._frontBoxs);
		this._frontBoxs.setup();

    //	this.player.fillColor="rgba(0, 0, 0,1)"
    //console.log(this.player.fillColor)

    // this.rectBg = new engine.Rect();
    // this.rectBg.alpha = 0;
    // this.rectBg.width = 750;
    // this.rectBg.height = 1624;
    // this.addChild(this.rectBg);
	}
	/**
	 * 
	 * @param 暂停move
	 */
	stopMove() {
		this._frontBoxs.stop();
	}
	/**
	 * 赋值x距离值
	 */
	setMoveX(x, item) {
		this.moveTime = x;
    this.prizeBox = item;
		this._Zhuazi.move();
  }
	/**
	 * 显示隐藏盒子
	 */
	setVisible(isshow) {
		this._frontBoxs.showHidePrizeBox(isshow);
	}
	/**
	 * 获取中奖盒子移动的距离
	 */
	getMoveX() {
		return this.moveTime;
  }
  /**
   * 重置moveTime
   */
  resetMoveX() {
    this.moveTime = null;
  }
	/**
	 * 获取中奖盒子
	 */
	getBox() {
		return this.prizeBox;
	}
  /**
   * 重置场景
   */
  reset() {
    this.startstatus = false;
    this.ifPrize = false;
		this._Zhuazi.getReset();
  }

  /**
   * 开始
   */
  start(type=null) {
    this.speed = 1;
    this.gameIng = true;
    console.log('执行', type);
    this.startstatus = true;
    this.ifPrize = type && type.prize || false;
    // this.creatNpc()
    // this.beginNpc();
    // this.countdown = props.countDown;

    // this.countdownTimer = setInterval(() => {
    //   if (this.gameIng) {
    //     if (this.countdown > 0) {
    //       engine.globalEvent.dispatchEvent("food-fell-time-update", {
    //         time: this.countdown
    //       });
    //       this.countdown -= 1;
    //     } else {
    //       engine.globalEvent.dispatchEvent("food-fell-game-over", {
    //         score: this.score,
    //         reason: 1
    //       });
    //       this.died();
    //     }
    //   }
    // }, 1000);
  }

  /**
   * npc开始掉落
   */
  beginNpc() {
    this.timer = setTimeout(() => {
      if (this.gameIng) {
        // this.speed += props.acceleratedSpeed;
        // this.creatNpc()
      }
      //递归执行
      // this.beginNpc();
    }, 2000 / this.speed);
  }

  /**
   * 暂停
   */
  pause() {
    this.gameIng = false;
  }

  /**
   * 恢复
   */
  revive() {
    this.gameIng = true;
  }

  /**
   * 重新开始
   */
  resume() {
    this.reset();
    this.start();
  }

  /**
   * 初始化盒子位置
   */
  initNpc() {
    this.box1 = new engine.Sprite(getTextureByName("草泥马盒"));
    this.box2 = new engine.Sprite(getTextureByName("狗盒"));
    this.box3 = new engine.Sprite(getTextureByName("猫盒"));
    this.box4 = new engine.Sprite(getTextureByName("草泥马盒"));
    this.box5 = new engine.Sprite(getTextureByName("猫盒"));
    this.box1.x = 120;
    this.box1.y = 434;
    this.box2.x = 306;
    this.box2.y = 434;
    this.box3.x = 487;
    this.box3.y = 434;
    this.box4.x = 240;
    this.box4.scaleX = 0.5;
    this.box4.scaleY = 0.5;
    this.box4.y = 390;
    this.box5.x = 434;
    this.box5.y = 390;
    this.box5.scaleX = 0.5;
    this.box5.scaleY = 0.5;
    this.backTransfer.addChild(this.box4);
    this.backTransfer.addChild(this.box5);
    this.frontTransfer.addChild(this.box1);
    this.frontTransfer.addChild(this.box2);
    this.frontTransfer.addChild(this.box3);
  }

  /**
   * 创建NPC
   */
  // private creatNpc() {
  //   // this.initNpc();
  //   let goods = (this._goods = <Goods>ObjectPool.getObject(PoolName));
  //   console.log(goods);
  //   this.goodsItems.push(goods);
  //   this.NpcBg.addChild(goods);
  //   goods.addEventListener(
  //     engine.Event.ENTER_FRAME,
  //     (goods["onGoodsEnter"] = () => {
  //       if (goods.y > 1624) {
  //         this.removeNpc(goods);
  //       } else {
  //         if (this.gameIng) {
  //           //速度叠加
  //           // goods.y += (4 * this.speed)
  //           goods.x += 2 * this.speed;
  //           //如果玩家和物品发生碰撞
  //           if (this.hasHit(this.player, goods)) {
  //             if (goods["npcType"] == "rain") {
  //               console.log("碰到雨滴");
  //               this.score += props.rainScore;
  //               this.waterSvga.visible = true;
  //               this.waterSvga.play(false, false);
  //               this.waterSvga.once(
  //                 engine.Event.END_FRAME,
  //                 () => {
  //                   this.waterSvga.visible = false;
  //                 },
  //                 this
  //               );
  //             } else if (goods["npcType"] == "stone") {
  //               console.log("碰到石头");
  //               this.score += props.stoneScore;
  //             } else if (goods["npcType"] == "boom") {
  //               console.log("碰到炸弹");
  //               this.boomSvga.visible = true;
  //               this.boomSvga.play(false, false);
  //               this.boomSvga.once(
  //                 engine.Event.END_FRAME,
  //                 () => {
  //                   this.boomSvga.visible = false;
  //                 },
  //                 this
  //               );
  //               engine.globalEvent.dispatchEvent("food-fell-game-over", {
  //                 score: this.score,
  //                 reason: 2
  //               });
  //               this.died();
  //             }
  //             engine.globalEvent.dispatchEvent("food-fell-score-update", {
  //               score: this.score
  //             });
  //             this.removeNpc(goods);
  //           }
  //         }
  //       }
  //     }),
  //     this
  //   );
  // }

  /**
   * 玩家死亡
   */
  private died() {
    this.score = 0;
    this.pause();
  }

  /**
   * 回收指定物品
   * @param goods 物品
   */
  private removeNpc(goods) {
    this.NpcBg.removeChild(goods);
    ObjectPool.recycleObject(PoolName, goods);
    goods.removeEventListener(
      engine.Event.ENTER_FRAME,
      goods["onGoodsEnter"],
      this
    );
    let index = this.goodsItems.indexOf(goods);
    if (index > -1) {
      this.goodsItems.splice(index, 1);
    }
  }

  /**
   * 回收对象
   */
  private recycleGoods() {
    clearTimeout(this.timer);
    clearInterval(this.countdownTimer);
    for (let goods of this.goodsItems) {
      if (goods) {
        this.removeChild(goods);
        ObjectPool.recycleObject(PoolName, goods);
        goods.removeEventListener(
          engine.Event.ENTER_FRAME,
          goods["onGoodsEnter"],
          this
        );
      }
    }
    this.goodsItems = [];
  }


  /**
   * 碰撞检测
   * @param a a盒子
   * @param b b盒子
   */
  private hasHit(a, b) {
    if (
      Math.abs(a.x + a.width / 2 - (b.x + b.width / 2)) <
        a.width / 2 + b.width / 2 &&
      Math.abs(a.y + a.height / 2 - (b.y + b.height / 2)) <
        a.height / 2 + b.height / 2
    ) {
      return true;
    } else {
      return false;
    }
  }
}
