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 from './RotaryData';
import Utils from "../../MVC/utils/Utils";
import { getlogItem } from "../../getlogItem";

export default class StartScene extends Scene {
    public infoImg: eui.Image;
    public infoGroup: eui.Group;
    public infoMask: eui.Rect;
    public label1: eui.Label;
    public label2: eui.Label;
    public panel: eui.Group;
    public start_btn: eui.Button;
    public hand: eui.Image;
    public act_btn: eui.Button;
    public myPrize_btn: eui.Button;
    public tips_label: eui.Label;

    private timer: egret.Timer;

    private count: number;


    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);
        GDispatcher.addEvent('getCount', this.getCount, this);
        GDispatcher.addEvent('panelEffect', this.panelEffect, this);
    }

    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);
        GDispatcher.removeEvent('getCount', this.getCount, this);
        GDispatcher.removeEvent('panelEffect', this.panelEffect, this);
    }

    on_toush_tap_start() {
        NetManager.ins.clickLog(getlogItem(1));
        let count = DataManager.ins.ajaxElementData.element.freeLimit;
        if(count > 0) {
            GDispatcher.dispatchEvent('queryPrize');
        } else {
            PanelCtrl.instance.btnDelay(this.start_btn);
            PanelCtrl.instance.show(ModuleTypes.NO_TIMES_PANEL);
        }
    }

    on_touch_tap_act() {
        NetManager.ins.clickLog(getlogItem(2));
        PanelCtrl.instance.btnDelay(this.act_btn);
        PanelCtrl.instance.show(ModuleTypes.RULE_PANEL);
    }

    on_touch_tap_myPrize() {
        NetManager.ins.clickLog(getlogItem(3));
        PanelCtrl.instance.btnDelay(this.myPrize_btn);
        window.location.href = this.gotoRecord();
    }

    //获取我的奖品
    private gotoRecord(): string {
        let recordUrl: string;
        let oaId: number;
        if(DataManager.ins.customCfgData) {
            oaId = DataManager.ins.customCfgData.oaId;
            recordUrl = DataManager.ins.customCfgData.recordUrl;
        } else {
            oaId = DataManager.ins.gameCfgData.gameInfo.oaId;
            recordUrl = window['recordUrl'];
        }

        if(recordUrl.indexOf('?') != -1) {
            recordUrl += '&origins=' + oaId + '00';
        } else {
            recordUrl += '?origins=' + oaId + '00';
        }
        return recordUrl;
    }

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

    /**
     * 开始抽奖
     */
    private queryPrize() {
        this.setBtnTouch(false);	// 锁定按钮
        this.doJoin();
    }

    /**
     * 开始游戏
     */
    private doJoin() {
        ////////////////////////////////////////////////////////////////////////////////////////////////
        // 参加游戏
        NetManager.ins.doJoin((success) => {
            if(!success) {
                this.setBtnTouch(true);	// 开启按钮
                return;
            }
            ////////////////////////////////////////////////////////////////////////////////////////////////
            // 获取游戏开始状态
            NetManager.ins.getStartStatus((success, res) => {
                if(res.code != "0000000000") {
                    this.showToast("手速太快啦，稍后再试吧~");
                    this.setBtnTouch(true);	// 开启按钮
                    return;
                }
                if(!success) {
                    this.setBtnTouch(true);	// 开启按钮
                    return;
                }
                ////////////////////////////////////////////////////////////////////////////////////////////////
                // 查询奖品信息
                NetManager.ins.getOrderStatus((success, res) => {	// 轮询查询订单状态
                    if(res.code != "0000000000") {
                        this.showToast("手速太快啦，稍后再试吧~");
                        this.setBtnTouch(true);	// 开启按钮
                        return;
                    }
                    if(!success) {
                        this.setBtnTouch(true);	// 开启按钮
                        return;
                    }
                    let data = res.data;
                    this.rotateByPrize(data.lottery.id, () => {
                        if(!data.lottery || data.lottery.type === 'thanks') {	// 如果未中奖
                            PanelCtrl.instance.show(ModuleTypes.NO_PRIZE_PANEL);
                            this.setBtnTouch(true)	// 开启按钮
                        } else {
                            // 如果手机号不存在
                            if(!DataManager.ins.getData(NetName.GET_PHONE)) {
                                PanelCtrl.instance.show(ModuleTypes.PHONE_PANEL, data.lottery);
                            } else {    // 如果存在
                                PanelCtrl.instance.show(ModuleTypes.PRIZE_PANEL, data.lottery);
                            }
                            GDispatcher.dispatchEvent('getCount');	// 更新免费抽奖次数
                            this.setBtnTouch(true)  // 开启按钮
                        }
                    });
                }, DataManager.ins.getData(NetName.DO_JOIN_DATA).data, (res) => {
                    return res.code != "0000000000";
                }, 10);
                /////////////////////////////////////////// 查询奖品信息 ///////////////////////////////////////////
            }, DataManager.ins.getData(NetName.DO_JOIN_DATA).data, (res) => {
                return res.code != "0000000000";
            }, 10);
            ////////////////////////////////////////// 查询开始状态 ///////////////////////////////////////////
        });
        //////////////////////////////////////////////// 开始游戏 ////////////////////////////////////////////////
    }

    /**
     * 获取手机号
     */
    getPhone() {
        NetManager.ins.getPhone((success, res) => {
            if(!success) {
                return;
            }
        });
    }

    /**
     * 根据奖项转转盘
     * @param prizeId
     * @param callFun - 缓动回调
     */
    private rotateByPrize(prizeId, callFun: Function) {
        egret.Tween.removeTweens(this.panel);
        // let key = RotaryData.key[prizeId];	// 转盘数据的key
        let index = ~~(Math.random() * RotaryData.data[prizeId].length);
        let rs = RotaryData.data[prizeId][index];	// 奖品在转盘上的范围
        let r = Utils.Random(rs.start, rs.end) + Utils.RandomInt(8, 18) * 360;
        let t = Utils.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});
    }

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

    protected onLoad(): void {
        GDispatcher.dispatchEvent('getCount');
        this.initUI();
    }

    // 获取余剩下抽奖次数
    private getCount() {
        NetManager.ins.ajaxElement((success, res) => {
            if(!success) {
                return;
            }
            if(res.element.freeLimit <= 0) {
                this.hand.visible = false;
            }
            this.tips_label.text = `今日免费抽奖：${res.element.freeLimit}次`
        });
    }

    private initUI(): void {
        NetManager.ins.getCarousel((success, res) => {
            if(!success) {
                return;
            }
            this.count = res.data.length - 1;
            this.easyScroller(this.label1, this.label2, 1000);
        });
        this.getPhone();
        this.timer = new egret.Timer(5000, 0);
        this.timer.addEventListener(egret.TimerEvent.TIMER, this.getCarousel, this);
        this.timer.start();

        this.infoGroup.mask = this.infoMask;
        this.getPrizeInfo();

        NetManager.ins.showLog(getlogItem(1));
        NetManager.ins.showLog(getlogItem(2));
        NetManager.ins.showLog(getlogItem(3));

        this.initEffect();
    }

    private initEffect() {
        this.handEffect();
        this.panelEffect();
    }

    private panelEffect() {
        egret.Tween.get(this.panel).to({rotation: 360}, 8000).call(() => {
            this.panelEffect();
        });
    }

    private handEffect() {
        egret.Tween.get(this.hand).to({x: 405, y: 395}, 500, egret.Ease.quadInOut).call(() => {
            egret.Tween.get(this.hand).to({x: 391, y: 367}, 500, egret.Ease.quadInOut).call(() => {
                this.handEffect();
            })
        })
    }

    protected async preLoadRes() {

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

    private getCarousel() {
        NetManager.ins.getCarousel((success, res) => {
            if(!success) {
                return;
            }
            if(!res.data || res.data.length <= 0) {
                this.infoImg.visible = false;
                this.infoGroup.visible = false;
                return;
            }
            this.count = res.data.length - 1;
            this.infoImg.visible = true;
            this.infoGroup.visible = true;
        })
    }

    private easyScroller(obj1: any, obj2: any, duration: number) {
        let data = DataManager.ins.getData(NetName.GET_CAROUSEL).data;
        this.infoImg.visible = true;
        this.infoGroup.visible = true;
        obj1.y = 48;
        obj2.y = 48;
        if(this.count < 0) {
            this.count = data.length - 1;
        }
        obj1.text = `恭喜手机尾号${data[this.count]}的客户中奖`;
        this.count--;
        if(this.count < 0) {
            this.count = data.length - 1;
        }
        obj2.text = `恭喜手机尾号${data[this.count]}的客户中奖`;
        this.count--;
        if(this.count < 0) {
            this.count = data.length - 1;
        }
        egret.Tween.get(obj1).to({y: 0}, duration).wait(1500).call(() => {
            egret.Tween.get(obj1).to({y: -48}, duration).call(() => {
                egret.Tween.get(obj2).to({y: 0}, duration).wait(1500).call(() => {
                    egret.Tween.get(obj2).to({y: -48}, duration).call(() => {
                        this.easyScroller(obj1, obj2, duration);
                    });
                });
            });
        });
    }

    /**
     * 获得所有奖品信息
     */
    private getPrizeInfo() {
        let options = DataManager.ins.ajaxElementData.options;
        for(let i = 0; i < options.length; i++) {
            let v = options[i];
            RotaryData.key.push(v.id);
            RotaryData.data[v.id] = [{start: i * 45 + 5, end: i * 45 + 40}];
            this[`img${i}`].source = v.logo;
            this[`lab${i}`].text = v.name;
        }
    }

}