import { Widget, _decorator, Node, tween, math, Toggle } from 'cc';
import { UIBase } from '../scriptBase/UIBase';
import { CoinItem } from '../uiItem/CoinItem';
import { CoinMgr } from '../manager/CoinMgr';
import { Global } from '../Global';
import { UI } from '../enum/UI';
import { CfgLuckySpin } from '../config/CfgLuckySpin';
import { InputBlock } from '../misc/InputBlock';
import { DtoReward } from '../dto/DtoReward';
import { AudioMgr } from '../manager/AudioMgr';
const { ccclass, property, requireComponent } = _decorator;

@ccclass('UI/UILuckySpin')
@requireComponent(Widget)
export class UILuckySpin extends UIBase {

    private coinItem: CoinItem = null
    private zhuanPan: Node = null
    private lights: Toggle = null

    private orgAngle: number = 0

    protected onLoad(): void {
        this.coinItem = this.findComp('CoinItem', CoinItem)
        this.zhuanPan = this.findNode('ZhuanPan')
        this.lights = this.findComp('Lights', Toggle)
    }

    public onOpen(data?: any): void {
        this.coinItem.init(CoinMgr.CurCoin)
        this.orgAngle = this.zhuanPan.angle
    }

    public onClose(data?: any): void {

    }

    private spin(): void {
        AudioMgr.playSfx('抽奖转盘')

        this.orgAngle = this.zhuanPan.angle

        const targetAngle: number = this.orgAngle - (720 + 60 * math.randomRangeInt(0, 6))

        const idx: number = (6 + (targetAngle % 360) / 60) % 6
        const data = CfgLuckySpin[idx]
        if (!data) {
            return
        }

        this.scheduleOnce(() => {
            const reward: DtoReward = {
                itemId: data.itemId,
                cnt: data.cnt
            }
            this.open(UI.GetReward, [reward])
        }, 3)

        InputBlock.setActive(3)

        tween(this.zhuanPan).to(3, { angle: targetAngle }, { easing: 'sineInOut' }).start()
        this.schedule(() => {
            this.lights.isChecked = !this.lights.isChecked
        }, 0.25, 10)
    }

    protected onBtnSpinClick(): void {
        if (CoinMgr.CurCoin < Global.Lucky_Spin_Coin_Cost) {
            this.open(UI.Toast, '星星币不足')
            return
        }
        CoinMgr.CurCoin -= Global.Lucky_Spin_Coin_Cost
        this.coinItem.updateCoin(CoinMgr.CurCoin, false)
        this.spin()
    }

}


