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 PhoneNumPanel from "../Panel/PhoneNumPanel";
import RankPrizePanel from "../Panel/RankPrizePanel";
import TaskPanel from "../Panel/TaskPanel";
import TdCodePanel from "../Panel/TdCodePanel";
import ShareGuide from "../../shareGuide/ShareGuide";
import DailyLotPanel from "../Panel/DailyLotPanel";
import RankNoPrizePanel from "../Panel/RankNoPrizePanel";
import ActOverLotPanel from "../Panel/ActOverLotPanel";
import NoTimesPanel from "../Panel/NoTimesPanel";

@Decorator.ClassName("StartScene")
export default class StartScene extends Scene {


    public btnStart: MButton;
    public btnRule: MButton;
    public btnRecord: MButton;
    public dailyLotBtn: MButton;
    public btnRankList: MButton;
    public taskBtn: MButton;
    public labelFreeTime: eui.Label;

    //首页数据
    private homePageData: {
        //剩余游戏次数
        "residueTimes": number,
        //是否登录，true为已经登陆
        "isLogin": boolean,
        //上期分数暂时不用
        "socre": number,
        //上期排名
        "sort": number,
        //是否可以做任务得次数
        "doTask": boolean,
        //增加得次数
        "addTimes": number,
        //抽奖状态 0：不可抽奖     1：可以抽奖        2：已抽奖
        "lotteryStatus": 0 | 1 | 2,
        //奖品id
        "prizeId1": number,
        "prizeId2": number,
        "minEnableCaptchaScore": number,
        //活动是否已经结束，true为已结束
        "allPeriodEnd": boolean,
        //活动结束抽奖状态 0：不可抽奖      1：可以抽奖          2：已抽奖
        "lotteryEndStatus": 0 | 1 | 2
    }

    // private actOver: boolean = Date.now() > new Date(MConfigs.actEndTime).getTime()

    onSkinComplete() {
        super.onSkinComplete();

        //曝光埋点
        NetUtils.showLog(1);
        NetUtils.showLog(2);
        //规则按钮
        this.btnRule.onTap(this, () => {
            PanelCtrl.instance.show(RulePanel, { msg: MConfigs.rule });
        });
        //奖品页面
        this.btnRecord.onTap(this, () => {
            //未登录
            if (!this.homePageData.isLogin) {
                PanelCtrl.instance.show(PhoneNumPanel);
                return
            }
            location.href = MConfigs.rewardRecordUrl;
        });
        //排行榜列表
        this.btnRankList.onTap(this, () => {
            if (this.homePageData.allPeriodEnd) {
                ToastPanel.show("活动已结束")
                return
            }
            //未登录
            if (!this.homePageData.isLogin) {
                PanelCtrl.instance.show(PhoneNumPanel);
                return
            }
            PanelCtrl.instance.show(RankListPanel, { defaultToggle: 1 });
        });
        //任务列表
        this.taskBtn.onTap(this, () => {
            if (this.homePageData.allPeriodEnd) {
                ToastPanel.show("活动已结束")
                return
            }
            //未登录
            if (!this.homePageData.isLogin) {
                PanelCtrl.instance.show(PhoneNumPanel);
                return
            }
            Loading.instace.show();
            Net.sendGet(
                Net.Url.taskList,
                //参数
                undefined,
                //成功回调
                (res) => {
                    Loading.instace.hide();
                    PanelCtrl.instance.show(TaskPanel, res.data);
                },
                //失败回调
                () => { Loading.instace.hide(); });
        });
        //每日抽奖，根据首页接口
        this.dailyLotBtn.onTap(this, () => {
            //已结束
            if (this.homePageData.allPeriodEnd) {
                ToastPanel.show("活动已结束")
                return
            }
            //未登录
            if (!this.homePageData.isLogin) {
                PanelCtrl.instance.show(PhoneNumPanel);
                return
            }
            //1或2带入 0也带入
            // if (this.homePageData && this.homePageData.lotteryStatus) {
            PanelCtrl.instance.show(DailyLotPanel, { lotteryStatus: this.homePageData.lotteryStatus });
            // } else {
            //     ToastPanel.show("今日还未参与游戏")
            // }
        });


        // this.btnShare.onOnceTap(this, (resume) => {
        //     window['share']();
        //     MTimer.set(120, () => {
        //         const timestamp = NetUtils.getTimestamp();
        //         Net.sendPost(Net.Url.share, {
        //             timestamp: timestamp,
        //             token: NetUtils.md5(timestamp + "duiba4szrcb")
        //         }, () => {
        //             ToastPanel.show("分享成功");
        //             this.refreshPage();
        //             resume();
        //         }, () => { resume(); });
        //     });
        // });

        this.btnStart.onTap(this, () => {
            if (this.homePageData.allPeriodEnd) {
                ToastPanel.show("活动已结束")
                return
            }
            if (!this.homePageData.isLogin) {
                PanelCtrl.instance.show(PhoneNumPanel);
                //点击埋点
                NetUtils.clickLog(2);
                return
            }
            //点击埋点
            NetUtils.clickLog(2);

            let leftTimes = this.homePageData.residueTimes || 0;
            if (leftTimes > 0) { //有剩余次数
                Loading.instace.show();
                Net.sendPost(Net.Url.start, undefined, (res) => {
                    Loading.instace.hide();
                    SceneCtrl.instance.change(MainScene, {
                        startId: res.data.startId,
                        maxScore: res.data.maxScore
                    });
                }, () => { Loading.instace.hide(); });
            }
            //没有剩余次数，判断是否还能做任务
            else if (this.homePageData.doTask) {
                // ToastPanel.show("可通过完成任务获得更多次数")
                //显示去做任务弹框
                PanelCtrl.instance.show(NoTimesPanel)
            }
            //完全没次数了
            else {
                ToastPanel.show("今日次数已用完")
            }
        });


        this.refreshPage();

        /*this.btnStart.onOnceTap(this, (resume) => {
            let leftTimes = this.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 (this.leftShareTimes > 0) { //有分享次数
                        let panel = PanelCtrl.instance.show<SharePanel>(SharePanel);
                        panel.init({
                            title: "次数已用完",
                            content: "分享好友可增加游戏机会哦~",
                            btnText: "分享好友"
                        });
                        panel.context = this;
                    } else { //没有分享次数
                        PanelCtrl.instance.show(class extends CommonPanel {
                            onSkinComplete() {
                                super.onSkinComplete();
                                this.btn.onTap(this, () => {
                                    this.hidePanel();
                                });
                            }
                        }, {
                                title: "今天次数已用完",
                                content: "明天再来吧~",
                                btnText: "知道了"
                            });
                    }
                    resume();
                }
            }
        });*/
    }

    public refreshPage() {
        Loading.instace.show();
        Net.sendGet(
            Net.Url.homePage,
            undefined,
            (res) => {
                Loading.instace.hide();
                GameMgr.instance.minEnableCaptchaScore = res.data.minEnableCaptchaScore;
                this.homePageData = res.data;
                this.labelFreeTime.text = this.homePageData.residueTimes <= 0 ? "今日暂无游戏次数" : `今日剩余次数：${this.homePageData.residueTimes}次`;
                //判断活动是否已结束
                if (this.homePageData.allPeriodEnd) {
                    //活动结束，次数文案修改
                    this.labelFreeTime.text = "活动已结束";
                    //先弹结束后是否抽奖
                    if (this.homePageData.lotteryEndStatus) {
                        PanelCtrl.instance.show(ActOverLotPanel, { lotteryEndStatus: this.homePageData.lotteryEndStatus });
                    } else {
                        //如果没资格抽奖，那上期将也肯定没有
                        ToastPanel.show("活动已结束")
                    }
                    //再弹上期中奖情况
                    this.lastRankPrize();
                    return
                }
                //判断是否登录，如果未登录，弹手机号码
                // if (!this.homePageData.isLogin) {
                //     PanelCtrl.instance.show(PhoneNumPanel);
                // } else {
                //判断是否提示上期中奖，
                this.lastRankPrize();
                // }
                //判断是否有增加的次数
                if (this.homePageData.addTimes) {
                    ToastPanel.show("任务完成，次数+" + this.homePageData.addTimes);
                    //发接口消除
                    // Net.sendGet(Net.Url.remove, { type: "task" }, (res) => { }, () => { return true })
                }

                //判断是否关注
                this.judgeFocused();

            },
            //失败时，是否需要再次请求
            () => { Loading.instace.show() }
        );
    }
    //查询上期中奖情况
    private lastRankPrize() {
        if (this.homePageData.sort != null || this.homePageData.sort == 0) {
            //有奖
            if (this.homePageData.prizeId1 || this.homePageData.prizeId2) {
                PanelCtrl.instance.show(RankPrizePanel, {
                    rank: this.homePageData.sort,
                    prizes: [this.homePageData.prizeId1, this.homePageData.prizeId2]
                });
            } else {
                PanelCtrl.instance.show(RankNoPrizePanel, { rank: this.homePageData.sort });
            }
        }
    }
    //判断是否关注了，没关注就弹二维码弹框
    private judgeFocused() {
        Net.sendGet(
            Net.Url.getWechatUserNew,
            undefined,
            (res) => {
                //0未关注，1已关注
                if (res && res.data && res.data.subscribe == "0") {
                    PanelCtrl.instance.show(TdCodePanel)
                }
            },
            //失败了，无感知
            () => { return true }
        )
    }

    //只发接口更新次数文案
    updateTimes() {
        Net.sendGet(
            Net.Url.homePage,
            undefined,
            (res) => {
                this.homePageData = res.data;
                this.labelFreeTime.text = this.homePageData.residueTimes <= 0 ? "今日暂无游戏次数" : `今日剩余次数：${this.homePageData.residueTimes}次`;
            },
            //失败时，为了不弹toast
            () => { return true }
        )
    }
}

class SharePanel extends CommonPanel {
    context: StartScene = null;
    onSkinComplete() {
        super.onSkinComplete();
        this.btn.onOnceTap(this, (resume) => {
            window['share']();
            MTimer.set(120, () => {
                const timestamp = NetUtils.getTimestamp();
                Net.sendPost(Net.Url.share, {
                    timestamp: timestamp,
                    token: NetUtils.md5(timestamp + "duiba4szrcb")
                }, () => {
                    ToastPanel.show("分享成功");
                    this.context.refreshPage();
                    resume();
                }, () => { resume(); });
            });
        });
    }
}