import Scene from "../../MVC/views/Scene";
import PanelCtrl from "../../MVC/ctrls/panelCtrl";
import {ModuleTypes} from "../../Comm/types/sceneTypes";
import {GDispatcher} from "../../../libs/tc/util/GDispatcher";
import {NetManager} from "../../../libs/tw/manager/NetManager";
import {DataManager} from "../../../libs/tw/manager/DataManager";
import {NetName} from "../../../libs/tw/enum/NetName";
import TopLayerCtrl from "../../MVC/ctrls/topLayerCtrl";

import RotaryData, {PrizeTypes} from './RotaryData';
import SceneCtrl from "../../MVC/ctrls/sceneCtrl";

export default class StartScene extends Scene {
    public panel: eui.Image;
    public start_btn: eui.Button;
    public act_btn: eui.Button;
    public myPrize_btn: eui.Button;
    public tips_label: eui.Label;

    public get skinKey() {
        return 'StartScene'
    }

    public get groupName() {
        return 'start_scene'
    }

    constructor(data?) {
        super(data);
    }

    initEvents() {
        this.start_btn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.on_toush_tap_start, this);
        this.act_btn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.on_touch_tap_act, this);
        this.myPrize_btn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.on_touch_tap_myPrize, this);
        GDispatcher.addEvent('queryPrize', this.queryPrize, this);
    }

    on_toush_tap_start() {
        if (DataManager.ins.getData(NetName.GET_COUNT).data.remainTime > 0) {
            GDispatcher.dispatchEvent('queryPrize');
        } else {
            this.showToast("抽奖次数不足");
        }
    }

    on_touch_tap_act() {
        PanelCtrl.instance.btnDelay(this.act_btn);
        PanelCtrl.instance.show(ModuleTypes.RULE_PANEL);
    }

    on_touch_tap_myPrize() {
        PanelCtrl.instance.btnDelay(this.myPrize_btn);
        SceneCtrl.instance.change(ModuleTypes.MYPRIZE_SCENE);
    }

    // 设置全部按钮是否可以点击
    private setBtnTouch(touchEnabled: boolean) {
        this.start_btn.touchEnabled = touchEnabled;
        this.act_btn.touchEnabled = touchEnabled;
        this.myPrize_btn.touchEnabled = touchEnabled;
    }

    /**
     * 开始抽奖
     */
    private queryPrize() {
        this.setBtnTouch(false)	// 锁定按钮
        if (DataManager.ins.getData(NetName.GET_COUNT).data.remainTime) {
            this.getPrize('');
        } else {
            NetManager.ins.creditsCost((success) => {	// 预消耗积分
                if (!success) {
                    this.showToast("活动太火爆了，请稍后再试！");
                    this.setBtnTouch(true);	// 开启按钮
                    return;
                }
                let ticketNum = DataManager.ins.getData(NetName.CREDITS_COST).data;	// 消耗积分的票号
                this.queryStatus(ticketNum);
            });
        }
    }

    /**
     * 查询消耗积分的状态
     * @param ticketNum - 消耗积分的票号
     */
    private queryStatus(ticketNum: any) {
        NetManager.ins.queryStatus((success) => {
            if (!success) {
                this.setBtnTouch(true);	// 开启按钮
                return;
            }
            let data = DataManager.ins.getData(NetName.QUERY_STATUS).data; // 轮询结果
            if (data == 1) { // 消耗积分成功
                this.getPrize(ticketNum);
            } else if (data == 2) { // 积分消耗失败
                let msg = DataManager.ins.getData(NetName.QUERY_STATUS).message;
                // this.showToast(msg);
                this.showToast("积分不足");
                this.setBtnTouch(true)	// 开启按钮
            }
        }, ticketNum, () => {
            let data = DataManager.ins.getData(NetName.QUERY_STATUS).data;
            return data == 0;
        }, 10);
    }

    /**
     * 查询奖品的id
     * @param ticketNum - 消耗积分的票号
     */
    private getPrize(ticketNum: any) {
        NetManager.ins.getPrize((success) => {
            if (!success) {
                this.setBtnTouch(true); // 开启按钮
                return;
            }
            let data = DataManager.ins.getData(NetName.GET_PRIZE).data;
            if (data.prizeId == 'thanks') {	// 如果没有中奖
                this.rotateByPrize(PrizeTypes.THANKS, () => {
                    PanelCtrl.instance.show(ModuleTypes.NO_PRIZE_PANEL);
                    this.updateCount();	// 更新免费抽奖次数
                    this.setBtnTouch(true)	// 开启按钮
                });
            } else {
                this.queryPrizeInfo(data.prizeId); // 查询奖品详情
            }
        }, ticketNum);
    }

    /**
     * 查询奖品的信息
     * @param prizeId
     */
    private queryPrizeInfo(prizeId: any) {
        NetManager.ins.queryPrizeInfo((success) => {
            if (!success) {
                this.setBtnTouch(true);	// 开启按钮
                return;
            }
            let data = DataManager.ins.getData(NetName.QUERY_PRIZE_INFO).data;
            let optionId = DataManager.ins.getData(NetName.GET_PRIZE).data.optionId;
            let types = PrizeTypes.THANKS;
            if (optionId == window['prizeInfo'].first) {
                types = PrizeTypes.FIRST_PRIZE;
            } else if (optionId == window['prizeInfo'].second) {
                types = PrizeTypes.SECOND_PRIZE;
            } else if (optionId == window['prizeInfo'].third) {
                types = PrizeTypes.THIRD_PRIZE;
            }
            let url;
            if (data && data[0].refType == 'coupon') {	// 如果是优惠卷
                url = 'coupon'
            } else {
                let userRecordId = DataManager.ins.getData(NetName.GET_PRIZE).data.userRecordId;
                url = `/aaw/projectx/takePrize?projectOrderNo=${userRecordId}`;
            }
            this.rotateByPrize(types, () => {
                PanelCtrl.instance.show(ModuleTypes.PRIZE_PANEL, url);
                this.updateCount();	// 更新免费抽奖次数
                this.setBtnTouch(true)	// 开启按钮
            });
        }, prizeId);
    }

    /**
     * 根据奖项转转盘
     * @param prizeType - 奖品类型    使用prizeType枚举
     * @param callFun - 缓动回调
     */
    private rotateByPrize(prizeType: number, callFun: Function) {
        let key = RotaryData.key[prizeType];	// 转盘数据的key
        let index = Math.floor(Math.random() * RotaryData.data[key].length);
        let rs = RotaryData.data[key][index];	// 奖品在转盘上的范围
        let r = this.Random(rs.start, rs.end) + this.RandomInt(8, 18) * 360;
        let t = this.Random(4000, 7000);
        this.rotate(r, t, callFun);
    }

    /**
     * 开始一次旋转
     * @param rotation - 角度
     * @param time - 时间
     * @param callFun - 缓动回调
     */
    private rotate(rotation: number, time: number, callFun: Function) {
        var tw = egret.Tween.get(this.panel);
        tw.to({rotation: rotation}, time, egret.Ease.cubicInOut).wait(500).call(callFun);
    }

    private showToast(msg) {
        TopLayerCtrl.instance.show(ModuleTypes.TOAST_PANEL, {msg: msg});
    }

    removeEvents() {
        this.start_btn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.on_toush_tap_start, this);
        this.act_btn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.on_touch_tap_act, this);
        this.myPrize_btn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.on_touch_tap_myPrize, this);
        GDispatcher.removeEvent('queryPrize', this.queryPrize, this);
    }

    protected onSkinComplete(): void {
        super.onSkinComplete();
        this.onLoad();

    }

    protected onLoad(): void {
        NetManager.ins.getProjectUserInfo((success) => {
            if (!success) {
                return;
            }
            this.getCount();
        });
        this.initUI();
    }

    // 获取余剩下抽奖次数
    private getCount() {
        NetManager.ins.getCount((success) => {
            if (!success) {
                return;
            }
            let data = DataManager.ins.getData(NetName.GET_COUNT).data;
            let unitName = DataManager.ins.getData(NetName.GET_PROJECTUSERINFO).data.unitName;
            this.tips_label.text = (data.remainTime > 0) ? `今日免费抽奖：${data.remainTime}次` : `${data.credits}${unitName}/次`;
            if (data.remainTime > 0) {
                this.showToast(`恭喜你，获得${data.remainTime}次免费抽奖机会`);
            }
        });
    }

    private updateCount() {
        NetManager.ins.getCount((success) => {
            if (!success) {
                return;
            }
            let data = DataManager.ins.getData(NetName.GET_COUNT).data;
            this.tips_label.text = (data.remainTime > 0) ? `今日免费抽奖：${data.remainTime}次` : `${data.credits}积分/次`;
        });
    }

    private initUI(): void {

    }

    /**
     * 产生一个固定范围的随机数(左闭右开)
     * @param start
     * @param end
     */
    private Random(start: number, end: number) {
        return Math.random() * (end - start) + start;
    }

    /**
     * 产生一个固定范围的随机整数(左闭右开)
     * @param start
     * @param end
     */
    private RandomInt(start: number, end: number) {
        return Math.floor(Math.random() * (end - start) + start);
    }

    protected async preLoadRes() {

        return new Promise(function (resolve, reject) {
            resolve();
        });
    }
}