import { DataManager } from "../../tw/manager/DataManager";
import { NetManager } from "../../tw/manager/NetManager";
import { ModuleTypes } from "../../../libs/new_wx/types/sceneTypes";
import wait from "../../../libs/new_tc/wait";
import submitAfterDostart from "../../../libs/new_tw/ctrls/submitAfterDostart";
import PanelCtrl from "../../../libs/new_wx/ctrls/panelCtrl";
import Panel from "./Panel";
import centerAnchorOffset from "../views/centerAnchorOffset"
import showAlertPanel from "../../../libs/new_wx/ctrls/showAlertPanel";
import getCountTxt from "../../../libs/new_tw/datas/getCountTxt";
import gameIsWinning from "../../new_tw/datas/gameIsWinning";


export default class SlotPanel extends Panel {
  optionList: any;
  itemList: any;
  conveyorList: any;
  itemWidth: number;
  speed: number;
  cutSpeed: number;
  prizeItem: any;
  countTxt: eui.Label;
  Do: number;
  dis: number;
  N: number;
  INITALSPEED: number;
  start() {
    this.optionList = []
    this.itemList = []
    this.conveyorList = []
    this.itemWidth = 430
    this.speed = 1
    this.dis = 0
    this.N = 2
    this.INITALSPEED = 30
    if (!DataManager.ins.getOptionsData)
      NetManager.ins.getOptions(() => {
        this.initSlot()
      })
    else
      this.initSlot()
  }
  private async initSlot() {
    this['slotStartBtn'] && this['slotStartBtn'].once(egret.TouchEvent.TOUCH_TAP, this.onTap_slotStart, this);
    this.optionList = DataManager.ins.getOptionsData.optionList.filter(item => (item as any).scoreArea === '11,20')
    this.drawMask()
    this.renderSlotWrap()
    this.updateCountTxt()
  }

  play() {
    egret.startTick(this.onTick, this)
  }

  onTick() {
    this.itemList.forEach(item => {
      item.x -= this.speed
      if (item.x < -300) {
        item.x = this.itemList[this.itemList.length - 1].x + this.itemWidth
        this.itemList.push(item)
        this.itemList.shift()
      }
    })
    this.conveyorList.forEach(item => {
      item.x -= this.speed
      if (item.x < -300) {
        item.x = this.conveyorList[this.conveyorList.length - 1].x + item.width
        this.conveyorList.push(item)
        this.conveyorList.shift()
      }
    })
    if(this.Do) {
      this.dis += this.speed
      if ( this.dis >= this.Do) {
        this.dis = this.Do
        this.speed = 0
        egret.stopTick(this.onTick, this);
        wait(500).then(() => {
          if (gameIsWinning()) {
            PanelCtrl.instance.show(ModuleTypes.PRIZE_PANEL);
          } else {
            PanelCtrl.instance.show(ModuleTypes.NO_PRIZE_PANEL);
          }
        });
        wait(300).then(() => {
          NetManager.ins.getInfo()
          // this.gameReset()
        });
        return
      }
      this.speed = (1 - this.dis / this.Do) * this.INITALSPEED
      if(this.speed < 5){
        this.speed = 5
      }
    }
    return false
  }
  onTap_slotStart() {
    if (!this.check()) return;
    this.closeBtns.forEach(btn => btn.touchEnabled = false);
    this['slotStartBtn'].touchEnabled = false;
    this.calcSpeed(1, this.INITALSPEED)
      .then(() => {
        this.stop()
      })
    
  }

  calcSpeed(count, val) {
    return new Promise((resolve, reject) => {
      let calc = () => {
        let flag = count > 0 ? this.speed < val : this.speed > val
        this.speed += count
        if (flag) {
          setTimeout(() => {
            calc()
          }, 50)
        } else {
          resolve()
        }
      }
      calc()
    })

  }

  stop() {
    submitAfterDostart((status, data) => {
      let prizeName = data.lottery ? data.lottery.name : ''
      wait(2000).then(() => {
        let hashIndex = this.optionList.findIndex(item => item.name === prizeName)
        this.prizeItem = this.itemList[hashIndex]
        this.Do = (this.prizeItem ? this.prizeItem.x : -100) - 384 + this.N * this.itemList.length * this.itemWidth
      })
    }, 20);
  }

  gameReset() {
    this.speed = 1
    this.prizeItem = null
    let slotWrap: any = this.getChildByName('slotWrap')
    slotWrap.removeChildren()
    this.renderOptions(slotWrap)
    this.renderConveyor(slotWrap)
  }

  private renderConveyor = async (container: any) => {
    let conveyor
    await loadImageByUrl('conveyor_png').then((img: any) => {
      conveyor = img
    })
    this.conveyorList = []
    for (let i = 0; i < this.optionList.length; i++) {
      let conveyorHash
      conveyorHash = cloneImage(conveyor)
      conveyorHash.y = 244
      conveyorHash.x = 150 + conveyor.width * (i - 1)
      this.conveyorList.push(conveyorHash)
    }
    this.conveyorList.forEach(element => { container.addChild(element) })
  }

  private drawMask = () => {
    var circle: egret.Shape = new egret.Shape();
    circle.graphics.beginFill(0x0000ff);
    circle.graphics.drawCircle(0, 0, 432 / 2);
    circle.graphics.endFill();
    circle.x = 159 + 432 / 2
    circle.y = 367 + 432 / 2
    this.addChild(circle)
    this.mask = circle
  }

  private renderSlotWrap = () => {
    const slotWrap = new egret.DisplayObjectContainer()
    this.renderOptions(slotWrap)
    this.renderConveyor(slotWrap)
    slotWrap.y = 450
    slotWrap.name = 'slotWrap'
    this.addChild(slotWrap)
    this.play()
    slotWrap.mask = this.mask
    this.addChild(this['slotWrapTop'])
  }

  private renderOptions = (container: any) => {
    this.itemList = []
    let x = window.innerWidth - 430
    this.optionList.reduce((sum, item) => {
      let gift
      return sum.then(() => {
        return loadImageByUrl(item.logo).then(image => {
          gift = image
          gift.x = x += this.itemWidth
          gift.y = gift.height / 2
          gift.name = item.name
          centerAnchorOffset(gift)
          this.itemList.push(gift)
          container.addChild(gift)
        })
      })
    }, Promise.resolve())
  }

  updateCountTxt() {
    if (this.countTxt) {
      this.countTxt.text = getCountTxt();
    }
  }

  check() {
    if (DataManager.ins.getInfoData.status.code == 2) {
      showAlertPanel('对不起，您的积分不足。', null, 'lackOfMoney')
      return false;
    }
    if (DataManager.ins.getInfoData.status.code == 3) {
      showAlertPanel('对不起，参与次数已用完。', null, 'lackOfChance')
      return false;
    }
    return true;
  }

  get skinKey() { return 'Slot' }

  protected get closeBtns(): eui.Button[] {
    return [this['slotClose']]
  }
}

const loadImageByUrl = (url: string) => {
  return new Promise((resolve, reject) => {
    RES.getResByUrl(
      url,
      texture => {
        let image = new egret.Bitmap(texture)
        resolve(image)
      },
      this,
      'image'
    )
  })
}

const cloneImage = (bitmap: egret.Bitmap) => new egret.Bitmap(bitmap.texture);