import BtnClosePanel from "../../component/BtnClosePanel";
import { AdFun } from "../../data/AdData";
import TurnableItem from "./TurnableItem";

const { ccclass, property } = cc._decorator;
/**
 * 转盘
 * @author 邹勇
 */
@ccclass
export default class Turnable extends cc.Component {
    @property(cc.Node)
    node_turn: cc.Node = null;
    @property(cc.Node)
    node_items: cc.Node[] = [];
    @property(cc.Node)
    btn_draw: cc.Node = null;
    @property(cc.Sprite)
    btn_close: cc.Sprite = null;
    @property(cc.RichText)
    lbl_left: cc.RichText = null;

    private audioId: number;

    onLoad() {
        this.initData();
    }

    /**
     * 初始化奖励和抽奖次数
     */
    private initData() {
        if (gData.turnable.config) {
            for (let i = 0; i < gData.turnable.config.length; i++) {
                let sc = this.node_items[i].getComponent(TurnableItem);
                sc.initData(gData.turnable.config[i].type);
            }
        }
        gData.turnable.requestData();
        this.updateLeftTimes();
    }

    /** 点击抽奖 */
    clickDraw() {
        if (gData.turnable.leftTimes > 0) {
            mk.ad.watchAd((success: boolean) => {
                mk.console.log("watchAD:" + success);
                if (success) {
                    gData.adData.watchVideo(AdFun.turntable);
                }
            });
        }
    }

    private async play() {
        this.audioId = await mk.audio.playEffect("turnableplay", true);
        this.btn_close.getComponent(BtnClosePanel).block_click = true;
        this.node_turn.angle = 1800;
        let index = 2;
        let tar = index * 60;
        cc.tween(this.node_turn)
            .to(5, { angle: tar }, { easing: 'expoInOut' })
            .call(this.playOver, this).start();
    }

    private playOver() {
        mk.audio.stopEffect(this.audioId);
        this.btn_close.getComponent(BtnClosePanel).block_click = false;
        this.updateLeftTimes();
        mk.ui.openPanel("module/reward/reward");
    }

    updateLeftTimes() {
        this.lbl_left.string = `剩余：<color=#FFED99>${gData.turnable.leftTimes}</color>次`;
    }

    update() {
        if (gData.turnable.requestFinish) {
            this.updateLeftTimes();
            gData.turnable.requestFinish = false;
        }
        if (gData.turnable.adData) {
            this.play();
            gData.reward.data = gData.turnable.adData;
            gData.turnable.adData = null;
        }
    }

    onDestroy() {

    }
}