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



export default class RotatePannel extends Panel {
  countTxt: eui.Label;
  optionList: any;
  wheelPos: any;
  prizeIndex: number;
  start() {
    if (!DataManager.ins.getOptionsData)
      NetManager.ins.getOptions(() => {
        this.initRotate()
      })
    else
      this.initRotate()
  }
  private async initRotate() {
    this.optionList = DataManager.ins.getOptionsData.optionList.filter(item => (item as any).scoreArea === '21,30')
    this['rotateStart'] && this['rotateStart'].once(egret.TouchEvent.TOUCH_TAP, this.onTap_rotateStart, this);
    this.updateCountTxt()
    this.renderOptions(this['wheel'].width / 2, this['wheel'])
  }
  
  onTap_rotateStart() {
    if (!this.check()) return;
    this.closeBtns.forEach(btn => btn.touchEnabled = false);
    this['rotateStart'].touchEnabled = false;
    this.showAnimation(3000, 720*4, false, egret.Ease.sineIn, null)
    submitAfterDostart((status, data) => {
      let prizeName = data.lottery ? data.lottery.name : ''
      this.prizeIndex = this.optionList.findIndex(item => item.name === prizeName)
      let deg = this.prizeIndex > -1 ? 180 - this.prizeIndex * 45 : - 22.5
      this.showAnimation(3000, 720*4, false, egret.Ease.sineOut, () => {
        
      });

      wait(1000).then(() => {
        if (gameIsWinning()) {
          PanelCtrl.instance.show(ModuleTypes.PRIZE_PANEL);
        } else {
            PanelCtrl.instance.show(ModuleTypes.NO_PRIZE_PANEL);
        }
      });
      wait(300).then(() => {
        NetManager.ins.getInfo()
      });

    }, 30);
  }

  renderOptions(r, container) {
    let itemDeg = 360 / 8;
    this.optionList.reduce((sum, item, index) => {
      let gift = new eui.Group;
      return sum.then(() => {
        return loadImageByUrl(item.logo).then((image: any) => {
          image.y = 220
          centerAnchorOffset(image)
          gift.addChild(image)
          gift.addChild(this.renderText(item.name))
          container.addChild(gift);
          let giftDeg = index * itemDeg
          gift.rotation = 180 + giftDeg
          gift.x = r - Math.sin((Math.PI * giftDeg) / 180) * (r - 70);
          gift.y = r + Math.cos((Math.PI * giftDeg) / 180) * (r - 70);
          gift.scaleX = gift.scaleY = 0.35;
        });
      });
    }, Promise.resolve());
    this.showAnimation(50000, 360, true, null, null);
  }

  renderText(text) {
    const textField = new egret.TextField();
    textField.text = text;
    textField.strokeColor = 0xffffff;
    textField.size = 60;
    textField.lineSpacing = 20;
    textField.y = 0
    textField.textAlign = egret.HorizontalAlign.CENTER;
    centerAnchorOffset(textField)
    return textField;
  };

  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;
  }

  showAnimation(time, resultAngle, loop, type, cb) {
    console.log('showAnimation')
    let target = this['wheel'];
    egret.Tween.removeTweens(target);

    //这个是转盘转
    let tw = egret.Tween.get(target, {
      loop: loop
    });
    tw = tw.to({ rotation: resultAngle }, time, type);
    cb && tw.call(cb, self);
  }

  get skinKey() { return 'Rotate' }

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

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