/* eslint-disable no-redeclare */
/* eslint-disable no-var */
/* eslint-disable no-use-before-define */
/* eslint-disable no-self-assign */
/* eslint-disable no-unused-vars */
/* eslint-disable no-shadow */
/* eslint-disable no-undef */
   
  // 初始化图片   
  const imgjishi = require('./assets/img/daojishi.png')
  const bgPlan = require('./assets/img/bg-plan.png')
  const bgRainer = require('./assets/img/bg-rainer.png')
  const redpacket = require('./assets/img/redpacket.png')
  const close = require('./assets/img/close.png')
  const dialogExit = require('./assets/img/dialog-exit.png')
  const buttonCancel = require('./assets/img/button-cancel.png')
  const buttonExit = require('./assets/img/button-exit.png')
  const openRedpacket = require('./assets/img/open-redpacket.png')
  const open = require('./assets/img/open.png')
  const redpacketResult = require('./assets/img/redpacket-result.png')
  const buttonContinue = require('./assets/img/button-continue.png')
  const cursorAnimation = require('./assets/img/cursor-animation.png')

  const states = {}
  const clientWidth = document.documentElement.clientWidth * 2
  const clientHeight = document.documentElement.clientHeight * 2
  let QingLvGroup;
  let hitNum = 0;
  const config = {
      selfPool: 40,
      selfPic:'redpacket',
      rate:0.5,
      maxSpeed:1000,
      minSpeed:400,
      max:95
  }

  const ids = [0, 1, 2, 3, 4, 5]
  // test
  const redpackets = ['50元红包', '20元红包', '100元红包', '20元红包', '一套房', '20元红包']
  let time = 25
  const getIds = []
  const radio = clientWidth / 375 ;
  let e;
  function rfuc(n){
    return n * radio;
  }

  // 初始化红包
  function QingLv(config, game, closeFunc, getRed){
    this.init = function(){
        this.config = config;
        QingLvGroup = game.add.group();
        QingLvGroup.enableBody = true;
        QingLvGroup.createMultiple(config.selfPool, config.selfPic); // 初始化多个红包
        QingLvGroup.setAll('anchor.y',1)
        QingLvGroup.setAll('outOfBoundsKill', true);
        QingLvGroup.setAll('checkWorldBounds', true);
        this.maxWidth = game.width + 300;
        game.time.events.loop(Phaser.Timer.SECOND * config.rate, this.createQL, this);
    };
    this.createQL = function(){
        e = QingLvGroup.getFirstExists(false);
        
        if (e) {
            if (hitNum >= config.max) {
                return;
            }
            hitNum++;
            e.events.onInputDown.removeAll();
            let ram = Math.random();
            ram = ram < 0.5 ? ram += 0.5 : ram;
            e.loadTexture(this.config.selfPic)
            e.alpha = 1;
            e.angle = 30 // 角度
            // e.scale.setTo(rfuc(ram)); 
            e.reset(game.rnd.integerInRange(100, this.maxWidth), 100) // 红包生成的位置
            e.body.velocity.x = game.rnd.integerInRange(-300, -150); // 红包移动的速度
            e.body.velocity.y = game.rnd.integerInRange(config.minSpeed, config.maxSpeed);
            e.inputEnabled = true;
            e.events.onInputDown.add(this.hitted, this)
        }
    };
    this.hitted = async function(sprite){
        if (Math.random() < 1 / 4 && ids.length > 0 && game.state.states.main.leftTime < time * 2 / 3 && game.state.states.main.leftTime > 1) {
          const res = await getRed()
          console.log(res)
          let text = []
          if (isNaN(res) || '') {
            text = [res, '', '', '', '']
            return
          } else {
            text = [`${res}元红包`, '恭喜您抢到', '红包已经放入', '个人中心-钱包' , '，记得提现哦']
          }
          sprite.kill();
          
          // 点击获得红包,游戏暂停
          game.paused = true;

          // 背景
          const hexGraphics = new Phaser.Graphics().beginFill(0x000000, 0.5).drawRect(0,0,clientWidth,clientHeight + 2);
          const pausedMask = game.add.sprite(0, 0, hexGraphics.generateTexture())
          
          const openDialog = game.add.sprite(game.world.centerX, game.world.centerY, 'openRedpacket')
          openDialog.anchor.x = 0.5
          openDialog.anchor.y = 0.5
          
          const open = game.add.sprite(game.world.centerX - 239 / 2, game.world.centerY - 239 / 2 + 100, 'open')
          // open.anchor.x = 0.5
          // open.anchor.y = 0.5
          open.inputEnabled = true;
        
          const result = game.add.sprite(game.world.centerX, game.world.centerY, 'redpacketResult')
          result.anchor.x = 0.5
          result.anchor.y = 0.5
          result.scale.x = 1.2
          result.scale.y = 1.2
          result.visible = false

          const goOn = game.add.sprite(game.world.centerX - 194 / 2, game.world.centerY + result.height / 2 - 150, 'buttonContinue')
          // goOn.anchor.x = 0.5
          // goOn.anchor.y = 0.5
          goOn.visible = false

          let ticketText = {};
          const link = ''
          
          // 拆红包
          const clickOpen = function() {

            // 游戏暂停时,点击事件无效,只能通过这种画热点的形式来绑定事件
            const openRect = new Phaser.Rectangle(rfuc(130), rfuc(315), 239, 239).copyFrom(open);

            if (openRect.contains(game.input.x, game.input.y)) {
              const currentWidth = open.width

              // 拆红包动画
              const tempArr = [2, 4, 8, 4, 2, 1]
              let index = 0;
              const timer = setInterval(function() {
                if (index > tempArr.length - 1) { index = 0 }
                open.width = currentWidth / tempArr[index]
                open.height = open.height
                open.left = game.world.centerX - open.width / 2
                ++index
              }, 200)
              game.input.onDown.remove(clickOpen, this);
              const arrIndex = Math.floor(Math.random() * ids.length)
              const redpacketId = ids.splice(arrIndex, 1)
              getIds.push(redpacketId[0])

              setTimeout( ()=> {
                timer && clearInterval(timer)
                // document.getElementById('audioOpen').play()
                // 3
                const tipTextTop = game.world.centerY + result.height / 2 - goOn.height - 150
                tipText1 = game.add.text(0, tipTextTop, text[2], {fill: '#fff', fontSize: '25px', fontWeight: '400'})
                tipText2 = game.add.text(0, tipTextTop, text[3], {fill: '#ffe67d', fontSize: '25px', fontWeight: '400'})
                tipText3 = game.add.text(0, tipTextTop, text[4], {fill: '#fff', fontSize: '25px', fontWeight: '400'})
                tipText1.left = game.world.centerX - (tipText1.width + tipText2.width + tipText3.width) / 2
                tipText2.left = tipText1.left + tipText1.width
                tipText3.left = tipText1.left + tipText1.width + tipText2.width
                // 2
                const ticketTextTop = tipTextTop - tipText1.height - 50
                ticketText = game.add.text(0, ticketTextTop, text[0], {fill: '#ffe67d', fontSize: '50px', fontWeight: 'bolder'})
                ticketText.left = game.world.centerX - ticketText.width / 2 // 文字相对于屏幕左右居中
                // 1
                titleText = game.add.text(0, ticketTextTop - ticketText.height - 20, text[1], {fill: '#fff', fontSize: '40px', fontWeight: 'bolder'})
                titleText.left = game.world.centerX - titleText.width / 2

                openDialog.visible = false
                open.visible = false
                result.visible = true
                goOn.visible = true
                game.input.onDown.add(clickButton, this)
              }, 1000)
            }
          };

          const clickButton = function() {
            const continueRect = new Phaser.Rectangle(rfuc(198), rfuc(445), 194, 66).copyFrom(goOn);
            if (continueRect.contains(game.input.x, game.input.y)) {
              closeFunc()
              // result.visible = false
              // goOn.visible = false
              // pausedMask.visible = false
              // ticketText.visible = false
              // titleText.visible = false
              // tipText1.visible = false
              // tipText2.visible = false
              // tipText3.visible = false
              // game.paused = false
              // game.input.onDown.remove(clickButton, this);
            }
          }

          game.input.onDown.add(clickOpen, this)
        } else {
          sprite.inputEnabled = false;
          const anim = sprite.animations.add(config.selfPic);
          sprite.play(config.selfPic, 40, false);
          anim.onComplete.add(this.fade, this, sprite)
        }
    };
    this.fade = function(sprite){
        const tween = game.add.tween(sprite).to({alpha:0}, 300, 'Linear', true)
        tween.onComplete.add(this.killed, this, sprite);
    };
    this.killed = function(sprite){
        sprite.kill();
    }
  }
  states.boot = function(game) {
    this.preload = function() {
        if (typeof (GAME) !== "undefined") {
            this.load.baseURL = GAME + "/";
        }
        if (!game.device.desktop) {
            this.scale.scaleMode = Phaser.ScaleManager.EXACT_FIT;
            this.scale.forcePortrait = true;
            this.scale.refresh();
        }
    };
    this.create = function() {
        game.stage.backgroundColor = '#FFF';
        game.state.start('preload');
    };
  };
  states.preload = function(game) {
      this.preload = function(game) {
          // 加载图片
          game.load.spritesheet('daojishi', imgjishi, 250,120, 4)
          game.load.image('bgPlan', bgPlan)
          game.load.image('bgRainer', bgRainer)
          game.load.spritesheet('redpacket', redpacket, 144, 173, 2)
          game.load.image('close', close)
          game.load.image('dialogExit', dialogExit)
          game.load.image('buttonExit', buttonExit)
          game.load.image('buttonCancel', buttonCancel)
          game.load.image('openRedpacket', openRedpacket)
          game.load.image('open', open)
          game.load.image('redpacketResult', redpacketResult)
          game.load.image('buttonContinue', buttonContinue)
          game.load.spritesheet('cursorAnimation', cursorAnimation, 74, 108, 2)
      };
      this.create = function() {
          game.state.start('main');
      };
  };
  states.main = function(game, closeFunc, getRed) {
      this.create = function() {
          // 物理系统
          game.physics.startSystem(Phaser.Physics.ARCADE);

          // 背景图
          const bgPlan = game.add.sprite(0, 0, 'bgPlan');
          bgPlan.width = game.width;
          bgPlan.height = game.height;

          const cursorPointer = game.add.sprite(game.world.centerX - 36, game.world.centerY + 200, 'cursorAnimation');
          var anim = cursorPointer.animations.add('cursorAnimation');
          cursorPointer.play('cursorAnimation', 2, true);

          // document.getElementById('audioCountDown').play()

          // 开始游戏倒计时
          const daojishi = game.add.sprite(game.world.centerX - 140, game.world.centerY, 'daojishi');
          var anim = daojishi.animations.add('daojishi');
          daojishi.play('daojishi', 1, false);
          anim.onComplete.add(this.startGame, this, daojishi);
      };
      
      this.startGame = function(daojishi){
          this.leftTime = time
          const bgRainer = game.add.sprite(0, 0, 'bgRainer');
          bgRainer.width = game.width;
          bgRainer.height = game.height;
          daojishi.visible = false;
          this.createQingLv();

          // 添加按钮,并绑定事件
          const closeImg = game.add.button(rfuc(20), rfuc(20), 'close', function(){
            game.paused = true
            pausedMask.visible = true
            exitDialog.visible = true
            exitButton.visible = true
            cancelButton.visible = true

            game.input.onDown.add(buttonClick, this)
            game.input.onDown.add(exitClick, this)
          }.bind(this))

          // 剩余时间
          const leftTimeTips = game.add.text(game.camera.width - rfuc(90), rfuc(35), '倒计时', {fill: '#fff', fontSize: '25px', fontWeight: '800'})
          this.leftTimeText = game.add.text(0, 0, this.leftTime, {fill: '#FFF', fontSize: '30px', fontWeight: 'bolder'})
          this.leftTimeText.scale.setTo(rfuc(1))
          this.leftTimeText.fixedToCamera = true;
          this.leftTimeText.cameraOffset.setTo(game.camera.width - rfuc(50), rfuc(20));

          const hexGraphics = new Phaser.Graphics().beginFill(0x000000, 0.5).drawRect(0,0,clientWidth,clientHeight + 2);
          const pausedMask = game.add.sprite(0, 0, hexGraphics.generateTexture())
          pausedMask.visible = false;

          const exitDialog = game.add.sprite(rfuc(62), rfuc(150), 'dialogExit')
          exitDialog.visible = false;

          const exitButton = game.add.button(rfuc(80), rfuc(315), 'buttonExit')
          exitButton.visible = false;

          const isExit = false
          const cancelButton = game.add.button(rfuc(200), rfuc(315), 'buttonCancel')
          cancelButton.visible = false;
          

          game.time.events.repeat(Phaser.Timer.SECOND, this.leftTime, this.refreshTime, this)

          const buttonClick = function() {
            const cancelRect = new Phaser.Rectangle(rfuc(200), rfuc(315), 194, 66).copyFrom(cancelButton);
            if (cancelRect.contains(game.input.x, game.input.y)) {
              game.input.onDown.remove(buttonClick, this)
              game.paused = false
              pausedMask.visible = false
              exitDialog.visible = false
              exitButton.visible = false
              cancelButton.visible = false
            }
          }
          const exitClick = function() {
            const cancelRect = new Phaser.Rectangle(rfuc(200), rfuc(315), 194, 66).copyFrom(exitButton);
            if (cancelRect.contains(game.input.x, game.input.y)) {
              closeFunc()
            }
          }
      };

      this.createQingLv = function(){
          this.qinglv = new QingLv(config, game, closeFunc, getRed);
          this.qinglv.init();
      };
      
      this.refreshTime = function(){
          this.leftTime--;
          const tem = this.leftTime;
          this.leftTimeText.text = tem;
          if (this.leftTime === 0) {
            const hexGraphics = new Phaser.Graphics().beginFill(0x000000, 0.5).drawRect(0,0,clientWidth,clientHeight + 2);
            const pausedMask = game.add.sprite(0, 0, hexGraphics.generateTexture())
            const result = game.add.sprite(game.world.centerX, game.world.centerY, 'redpacketResult')
            result.anchor.x = 0.5
            result.anchor.y = 0.5
            result.scale.x = 1.2
            result.scale.y = 1.2
  
            // const exitButton = game.add.sprite(game.world.centerX, game.world.centerY + result.height / 2 - 100, 'buttonContinue')
            const exitButton = game.add.sprite(game.world.centerX - 194 / 2, game.world.centerY + result.height / 2 - 150, 'buttonContinue')
            // exitButton.anchor.x = 0.5
            // exitButton.anchor.y = 0.5
            const exitClick = function() {
              const cancelRect = new Phaser.Rectangle(rfuc(200), rfuc(315), 194, 66).copyFrom(exitButton);
              if (cancelRect.contains(game.input.x, game.input.y)) {
                closeFunc()
              }
            }
            game.input.onDown.add(exitClick, this)

            ticketText = game.add.text(0, game.world.centerY + result.height / 2 - 200 - exitButton.height , '红包雨已结束', {fill: '#fff', fontSize: '35px', fontWeight: 'bolder'})
            ticketText.left = game.world.centerX - ticketText.width / 2
            tipText = game.add.text(0, game.world.centerY + result.height / 2 - 200 - exitButton.height - ticketText.height - 20, '很遗憾，没有接到红包', {fill: '#fff', fontSize: '25px', fontWeight: '400'})
            tipText.left = game.world.centerX - tipText.width / 2

            game.paused = true;
          }
      }
  };

  // 生成游戏
module.exports = (element, rainTime, closeFunc, getRed) => {
    let game = null
    if (game == null) {
      time = rainTime
      game = new Phaser.Game(clientWidth, clientHeight + 2, Phaser.CANVAS, element);
      game.state.add('boot', states.boot.bind(game));
      game.state.add('preload', states.preload.bind(game));
      game.state.add('main', states.main.bind(game, game, closeFunc, getRed, getRed));
      game.state.start('boot');
    }
  }
  
