import Panel from "../../views/Panel";
import ToastCtrl from "../../ctrls/toastCtrl";
import { NetManager } from "../../../libs/tw/manager/NetManager";
import { DataManager } from "../../../libs/tw/manager/DataManager";
import NetConst from "../../NetConst";
import { onNotSuccess } from "./onNotSuccess";
import { HtmlTextParser } from "../../rulePanel/HtmlTextParser";
import RotaryData from "./RotaryData";
import PanelCtrl from "../../ctrls/panelCtrl";
import { ModuleTypes } from "../../types/sceneTypes";
import { getlogItem } from "../../getLogItem";
import Guide from "../guide";

export default class TurnTablePanel extends Panel {
    public countLabel: eui.Label;
    public closeBtn: eui.Button;
    public prizeGroup: eui.Group;
    public selectRect1: eui.Rect;
    public startBtn: eui.Button;


    private totalTimes: number = 0;      // 转盘需要旋转总次数
    private selectTimes: number = 0;    // 当前已经旋转次数
    private selectIndex: number = 0;     // 当前选中奖品index

    constructor(data?) {
        super();
        this.data = data || {};
    }

    initEvents() {
        this.startBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTouchTap_start, this);
        this.closeBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTouchTap, this);
    }

    removeEvents() {
        this.startBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onTouchTap_start, this);
        this.closeBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onTouchTap, this);
    }

    onTouchTap_start() {
        NetManager.ins.clickLog(getlogItem(27));
        const data = DataManager.ins.getData('gameAjaxElement').data || {};
        const element = data.element || {};
        const freeLimit = element.freeLimit || 0;
        if(freeLimit > 0) {
            this.setBtnTouch(false);
            this.rota(2400);    // 开始旋转，设置一个很大的值 期间等待接口返回成功后改变这个值
            this.getPrize();// 抽奖
        } else {
            PanelCtrl.instance.show(ModuleTypes.TURNTABLE_TIPS_PANEL);
            // this.showToast('今日抽奖次数已达上限，分享活动可增加抽奖次数哦~');
        }
    }

    destroy() {
        super.destroy();
        window['turntableAddTime'] = function(res) {

        };
        window['initShare'](1);
    }

    /**
     * 开始旋转
     * @param times - 总共要旋转的次数
     */
    private rota(times) {
        this.totalTimes = times;    // 设置总共要旋转的次数
        this.selectPrize();         // 转盘选择奖品
    }

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

    // 转盘选择奖品
    private selectPrize() {
        function setWait(wait, dt, that) {  // 设置等待时间
            if(dt < 8) wait += that.Random(150, 250);
            if(dt < 4) wait += that.Random(150, 250);
            if(dt < 2) wait += that.Random(150, 250);
            // if(dt < 1) wait += that.Random(150, 250);
            return wait;
        }

        let dt = this.totalTimes - ++this.selectTimes;  // 差值
        if(dt < 0) {   // 次数到了就结束
            this.selectTimes = this.selectIndex;    // 当前旋转次数等于当前选择的奖品index（防止直接进行下次旋转时出错）
            setTimeout(() => {
                this.setBtnTouch(true);
                const data = DataManager.ins.getData('getOrderStatus').data;
                if(!data || !data.lottery || data.lottery.type == 'thanks') {
                    PanelCtrl.instance.show(ModuleTypes.TURNTABLE_NOPRIZE_PANEL);
                } else {
                    // console.log(data.lottery.title);
                    // console.log(data.lottery.title.indexOf('爱豆'));
                    // if(data.lottery.title.indexOf('爱豆') > -1) {
                    //     PanelCtrl.instance.show(ModuleTypes.TURNTABLE_IDOU_PANEL, data.lottery);
                    // } else {
                    PanelCtrl.instance.show(ModuleTypes.TURNTABLE_PRIZE_PANEL, data);
                    // }
                }
            }, 100);
            return;
        }

        // 计算等待时间，次数越多越慢的效果，传入一个标准时间，一个剩下需要旋转的次数和当前的Context
        let wait = setWait(100, dt, this);

        // 设置阴影位置
        let index = this.selectIndex = (++this.selectIndex > 7) ? 0 : this.selectIndex; // index
        this.selectRect.x = this[`prizeGroup${index}`].x;
        this.selectRect.y = this[`prizeGroup${index}`].y;
        if(this.guide.parent) {
            this.prizeGroup.removeChild(this.guide);
        }
        this.guide = new Guide();
        this.guide.init(this.selectRect, this.prizeGroup.width, this.prizeGroup.height);
        this.prizeGroup.addChild(this.guide);

        // 等待并递归
        setTimeout(() => {
            this.selectPrize(); // 递归
        }, wait);
    }

    /**
     * 抽奖
     */
    private getPrize() {
        JoinGame().then(    // doJoin and getStartStatus
            (res) => {
                Submit().then(  // getOrderStatus
                    (res) => {
                        // console.log(res);
                        // 改变一下要旋转总次数 当前旋转次数整除转盘个数 + 1 * 转盘个数 + 数倍的转盘个数 + 奖品所在的转盘index
                        let id;
                        if(res && res['data'] && res['data'].lottery && res['data'].lottery.type != 'thanks') {
                            if(res['data'].lottery.type == 'lucky') {
                                id = 'thanks';
                            } else {
                                id = res['data'].lottery.id;
                            }
                            this.totalTimes = (~~(this.selectTimes / 8) + 1) * 8 + 16 + RotaryData.data[id];
                        } else {
                            setTimeout(() => {
                                PanelCtrl.instance.show(ModuleTypes.TURNTABLE_NOPRIZE_PANEL);
                            }, 2000);
                        }
                    },
                    (err) => {
                        onNotSuccess(err);
                    }
                )
            },
            (err) => {
                onNotSuccess(err);
            }
        );
    }

    private showToast(msg) {
        ToastCtrl.instance.show(msg);
    }

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

    }

    private selectRect: egret.Shape;
    private guide = new Guide();

    protected onLoad(): void {
        this.initUI();
        NetManager.ins.showLog(getlogItem(10));
        NetManager.ins.showLog(getlogItem(27));

        this.selectRect = new egret.Shape();
        this.selectRect.graphics.beginFill(0x000000, 1);
        this.selectRect.graphics.drawRect(0, 0, 158, 152);
        this.selectRect.graphics.endFill();
        this.selectRect.x = 0;
        this.selectRect.y = 0;

        this.guide = new Guide();
        this.guide.init(this.selectRect, this.prizeGroup.width, this.prizeGroup.height);
        // this.prizeGroup.addChild(this.guide);
        window['turntableAddTime'] = (res) => {
            if(res.kShareChannel == 'copyURL') {    // 如果是复制链接，则不算分享成功
                return;
            }
            NetManager.ins.addTimesForActivity((success) => {
                if(!success) {
                    PanelCtrl.instance.show(ModuleTypes.TURNTABLE_NOSHARE_PANEL);
                    return;
                }
                // 1.显示Toast  2.更新label
                // this.showToast('分享成功~');
                NetConst.ajaxElement((success, res) => {
                    if(!success) {
                        return;
                    }
                    // console.log(res);
                    const data = res.data || null;
                    const element = data.element || null;
                    if(element) {
                        let text = `今日还剩</spen><font color="#fff600">${element.freeLimit}</font>次免费抽奖机会`
                        this.countLabel.textFlow = (new HtmlTextParser).parser(text);
                    }
                })
            }, 2, 1, 1);
        }
    }

    private initUI(): void {
        this.ajaxElement();
        // this.queryPrizeInfo();
        window['initShare'](6);
    }

    private ajaxElement() {
        NetConst.ajaxElement((success, res) => {
            if(!success) {
                return;
            }
            // console.log(res);
            const data = res.data || null;
            const element = data.element || null;
            if(element) {
                let text = `今日还剩</spen><font color="#fff600">${element.freeLimit}</font>次免费抽奖机会`
                this.countLabel.textFlow = (new HtmlTextParser).parser(text);
            }

            const options = data.options || [];

            // for(let i = 0; i < options.length; i++) {
            //     const option = options[i];
            //     if(option.prizeType == "thanks") {
            //         options.splice(i, 1);
            //     }
            // }
            for(let i = 0; i < options.length; i++) {
                const option = options[i];
                if(option.prizeType == 'thanks') {
                    RotaryData.key.push('thanks');
                    RotaryData.data['thanks'] = i;
                } else {
                    RotaryData.key.push(option.id);
                    RotaryData.data[option.id] = i;
                }
                this[`prize${i}`].source = option.logo;
                this[`prizeLabel${i}`].text = option.name;
            }
        })
    }

    /**
     * 产生一个固定范围的随机数(左闭右开)
     * @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() {

    }

    public get skinKey() {
        return 'TurnTablePanel'
    }

    // public get groupName() {
    //     return 'turnTable_panel'
    // }
}


/**
 * 加入游戏
 */
const JoinGame = function() {
    // Waiting.instance.show();
    return new Promise((resolve, reject) => {
        NetConst.doJoin((success, res) => {
            if(!success) {
                reject(res);
                // Waiting.instance.hide();
                return;
            }
            resolve(res);
            // const doJoinData = res.data;
            // NetConst.getNgameStartStatus((success, res) => {
            //     // Waiting.instance.hide();
            //     if(!success) {
            //         reject(res);
            //         return;
            //     }
            //     resolve(res);
            // }, doJoinData, (res) => {
            //     return res.code != "0000000000";
            // }, 10);
        });
    });
};

/**
 * 游戏结束提交
 */
export const Submit = function() {
    // Waiting.instance.show();
    return new Promise((resolve, reject) => {
        NetConst.getOrderStatus((success, res) => {	// 轮询查询订单状态
            // Waiting.instance.hide();
            if(!res || !success) {  // 返回true
                reject(res);
                return;
            }
            resolve(res);   // 返回false
        }, DataManager.ins.getData('doJoin').data, (res) => {
            return res.code != "0000000000";
        }, 10);
    })
};
