import Scene from "../MViews/MScene";
import MButton from "../MUI/MButton";
import SceneCtrl from "../MCtrls/MSceneCtrl";
import MainScene from "./MainScene";
import PanelCtrl from "../MCtrls/MPanelCtrl";
import Net from "../Global/Net";
import { Decorator } from "../Decorator/Decorator";
import SoundMgr from "../Mgr/SoundMgr";
import GameMgr from "../Mgr/GameMgr";
import RankListPanel from "../Panel/RankListPanel";
import ToastPanel from "../MComponents/MToastPanel";
import Loading from "../../loading/Loading";
import RulePanel from "../Panel/RulePanel";
import SignInPanel from "../Panel/SignInPanel";
import CommonPanel from "../Panel/CommonPanel";
import MTimer from "../MComponents/MTimer";
import { NetUtils } from "../Global/NetUtils";
import { MConst } from "../Global/MConst";
import { MConfigs } from "../Global/MConfigs";
import WinningPanel from "../Panel/WinningPanel";
import Game from "./Game";
import MBuried from "../Global/MBuried";
import { isWeiXin, invokeWX } from "../Global/GUtils";

@Decorator.ClassName("StartScene")
export default class StartScene extends Scene {
    public btnStart: MButton;
    public btnRankList: MButton;
    public btnRule: MButton;
    public labelFreeTime: eui.Label;
    public btnReward: MButton;
    public toggleMusic: eui.ToggleButton;

    onSkinComplete() {
        super.onSkinComplete();

        this.btnRankList.onTap(this, () => {
            if (!GameMgr.instance.isWenzhouUser) {
                ToastPanel.show("只限温州地区用户可参与");
                return;
            }
            PanelCtrl.instance.show(RankListPanel, { defaultToggle: 1 });
        });

        this.btnRule.onTap(this, () => {
            PanelCtrl.instance.show(RulePanel);
        });

        this.btnReward.onTap(this, () => {
            if (!GameMgr.instance.isWenzhouUser) {
                ToastPanel.show("只限温州地区用户可参与");
                return;
            }
            window.location.href = MConfigs.rewardRecordUrl;
        });

        //去掉音乐按钮
        this.toggleMusic.visible = false;
        /* this.toggleMusic.selected = SoundMgr.instance.enabled;
        this.toggleMusic.addEventListener(eui.UIEvent.CHANGE, (evt: eui.UIEvent) => {
            if (this.enabledTest() == false) return;
            SoundMgr.instance.enabled = (evt.target as eui.ToggleButton).selected;
        }, this); */

        MBuried.doShowBuried(2);
        this.btnStart.onOnceTap(this, (resume) => {
            MBuried.doClickBuried(2);
            if (GameMgr.instance.allPeriodEnd) {
                ToastPanel.show("活动已结束");
                resume();
                return;
            }

            if (!GameMgr.instance.isWenzhouUser) {
                ToastPanel.show("只限温州地区用户可参与");
                resume();
                return;
            }

            let leftTimes = GameMgr.instance.leftTimes;
            if (typeof leftTimes == "number") {
                if (leftTimes > 0) { //有剩余次数
                    Net.sendPost(Net.Url.start, undefined, (res) => {
                        SceneCtrl.instance.change(MainScene, {
                            startId: res.data.startId,
                            maxScore: res.data.maxScore
                        });
                    }, () => { resume() });
                } else { //没有剩余次数
                    if (GameMgr.instance.leftShareTimes > 0) { //有分享次数
                        let panel = PanelCtrl.instance.show<SharePanel>(SharePanel);
                        panel.init({
                            title: "次数已用完",
                            content: "分享可额外获得1次参与机会哦",
                            btnText: "分享好友"
                        });
                        panel.context = this;
                    } else { //没有分享次数
                        PanelCtrl.instance.show(class extends CommonPanel {
                            onSkinComplete() {
                                super.onSkinComplete();
                                MBuried.doShowBuried(6);
                                this.btn.onTap(this, () => {
                                    this.hidePanel();
                                });
                            }
                        }, {
                            title: "今天次数已用完",
                            content: "明天再来吧~",
                            btnText: "知道了"
                        });
                    }
                    resume();
                }
            }
        });

        this.refreshPage();
    }

    public async refreshPage() {
        let res = await NetUtils.visit().catch(() => {
            Loading.instace.show();
        });

        if (GameMgr.instance.allPeriodEnd) {
            ToastPanel.show("活动已结束");
            // return;
        }

        if (!GameMgr.instance.isWenzhouUser) {
            ToastPanel.show("只限温州地区用户可参与");
            return;
        }

        let leftTimes = res.data.leftTimes;
        this.labelFreeTime.text = leftTimes <= 0 ? "今日暂无游戏次数" : `今日剩余次数：${leftTimes}次`;

        if (res.data.prevPopUpFlag) {
            if (res.data.prevPopUp.prizeId == null) {
                PanelCtrl.instance.show<CommonPanel>(class extends CommonPanel {
                    onSkinComplete() {
                        super.onSkinComplete();
                        this.btn.onTap(this, () => this.hidePanel());
                    }
                }).init({
                    title: "很遗憾",
                    content: "上期排行榜您未获奖  再接再厉吧~",
                    btnText: "好的"
                })
            } else {
                PanelCtrl.instance.show<WinningPanel>(WinningPanel).init({
                    rewardName: res.data.prevPopUp.prizeName,
                    imgUrl: res.data.prevPopUp.prizeIcon,
                    rank: res.data.prevPopUp.myIndex
                });
            }
        }

    }
}

class SharePanel extends CommonPanel {
    context: StartScene = null;
    onSkinComplete() {
        super.onSkinComplete();
        MBuried.doShowBuried(7)
        this.btn.onOnceTap(this, () => {
            this.hidePanel();
            MBuried.doClickBuried(7);
            if (isWeiXin()) { //微信分享
                let mask = new eui.Image("wx_share_mask_png");
                SceneCtrl.instance.currentScene.addChild(mask);
                invokeWX(() => {
                    this.shareRequest().then(() => {
                        this.context.refreshPage();
                    });
                    mask.destroy();
                }, () => {
                    mask.destroy();
                });
            } else { //端内分享
                this.shareRequest().then(() => {
                    window["showSharePanel"]();
                    setTimeout(() => {
                        this.context.refreshPage();
                    }, 4000);
                });
            }
        });
    }

    private shareRequest() {
        return new Promise((resove, reject) => {
            const timestamp = NetUtils.getTimestamp();
            Net.sendPost(Net.Url.share, {
                timestamp: timestamp,
                token: NetUtils.md5(timestamp + "wzmsBank123")
            }, () => {
                resove();
            }, () => { reject(); });
        });
    }
}