import { DataManager } from "../../tw/manager/DataManager";
import { NetManager } from "../../tw/manager/NetManager";

import Panel from "./Panel";
import centerAnchorOffset from "../views/centerAnchorOffset"

export default class SlotPanel extends Panel {
  optionList: any;
  itemList: any;
  conveyorList: any;
  itemWidth: number;
  speed: number;
  prizeIndex: number;
  start() {
    this.optionList = []
    this.itemList = []
    this.conveyorList = []
    this.itemWidth = 430
    this.speed = 1
    this.prizeIndex = -1
    if (!DataManager.ins.getOptionsData)
      NetManager.ins.getOptions(() => {
        this.initSlot()
      })
    else
      this.initSlot()
  }
  private async initSlot() {
    this.optionList = DataManager.ins.getOptionsData.optionList.filter(item => (item as any).scoreArea === '1,10')
    this.drawMask()
    this.renderSlotWrap()
  }

  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.prizeIndex > -1) && this.itemList[this.prizeIndex].x < 385){
      this.speed = 0
    }
    return false
  }
  onTap_slotStart() {
    // this.gameReset()
    this.calcSpeed(1, 20)
    .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()
          }, 100)
        }else {
          resolve()
        }
      }
      calc()
    })

  }

  stop() {
    setTimeout(() => {
      this.speed = 4
      this.prizeIndex = this.optionList.findIndex(item => item.name === '场景1奖品B')
      console.log(this.prizeIndex)
    },2000)
  }
  gameReset() {
    this.speed = 1
    this.prizeIndex = -1
    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
          centerAnchorOffset(gift)
          this.itemList.push(gift)
          container.addChild(gift)
        })
      })
    }, Promise.resolve())
  }

  get skinKey() { return 'Slot' }

  protected get closeBtns(): eui.Button[] {
    this['slotStartBtn'] && this['slotStartBtn'].addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_slotStart, this);
    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);