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 { Buried } from "../../../libs/tw/util/Buried";
import { NetManager } from "../../../libs/tw/manager/NetManager";
import PostPanel from "../Panel/PostPanel";
import { showSharePanel, isWeiXin, wxConfig, invokeWX } from "../Global/GUtils";
import InputNumPanel, { ForbidPanel } from "../Panel/InputNumPanel";
import OverPanel from "../Panel/OverPanel";

@Decorator.ClassName("StartScene")
export default class StartScene extends Scene {
    public btnStart: MButton;
    public btnRankList: MButton;
    public rankBtn: eui.Button;
    public ruleBtn: eui.Button;
    public signBtn: eui.Button;
    public prizeBtn: eui.Button;
    // public btnMustRead: MButton;
    // public btnRule: MButton;
    public labelFreeTime: eui.Label;
    // public btnBack: eui.Button;
    // private leftTimes: number = null;
    public musicBtn: eui.ToggleButton;
    public btnShare: MButton;


    private startExposure: any;
    private signExposure: any;



    async onSkinComplete() {
        super.onSkinComplete();



        if (!GameMgr.instance.inited) {
            if (isWeiXin()) {
                wxConfig();
            }

            GameMgr.instance.activityEnd = await new Promise<boolean>((resolve, reject) => {
                Net.sendGet(Net.uri.visit, undefined, (res) => {
                    resolve(res.data.activityEnd);
                });
            });

            this.loadMusic();

            this.verify();

        } else {
            this.init();
        }
    }

    private async loadMusic() {
        this.musicBtn.enabled = false;
        await RES.getResAsync("bgm_mp3");
        SoundMgr.instance.setMusic("bgm_mp3");
        SoundMgr.instance.enabled = true;
        this.musicBtn.selected = true;
        this.musicBtn.enabled = true;
    }

    private verify() {
        Loading.instace.show();
        Net.sendGet(Net.uri.getNumStatus, { //检验手机号
            activityId: window["activityId"]
        }, (res) => {
            Loading.instace.hide();
            switch (res.data) {
                case "0":
                    PanelCtrl.instance.show<InputNumPanel>(InputNumPanel).onPassed = () => {
                        this.init();
                    }
                    break;
                case "1":
                    this.init();
                    break;
                case "2":
                    PanelCtrl.instance.show(ForbidPanel);
                    break;
            }
        }, () => {
            Loading.instace.hide();
            PanelCtrl.instance.show(ForbidPanel);
            return false;
        });
    }

    private init() {
        GameMgr.instance.inited = true;
        /* if (isWeiXin()) {
            invokeWX(() => {
                let timestamp = NetUtils.getTimestamp();
                Net.sendPost(Net.uri.share, {
                    timestamp: timestamp,
                    token: NetUtils.md5(timestamp + "duiba4jxabc")
                }, () => {
                    SceneCtrl.instance.currentScene.dispatchEvent(new egret.Event("shareSuccess"));
                }, () => true);
            });
        } */

        this.initBuried()
        this.labelFreeTime.text = "";
        this.rankBtn.onTap(this, () => {
            Loading.instace.show();
            PanelCtrl.instance.show(RankListPanel);

        });

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

        this.signBtn.onTap(this, this.onTap_signBtn);

        this.musicBtn.selected = SoundMgr.instance.enabled;
        this.musicBtn.addEventListener(eui.UIEvent.CHANGE, (evt: eui.UIEvent) => {
            SoundMgr.instance.enabled = (evt.target as eui.ToggleButton).selected;
        }, this);

        // this.prizeBtn.visible = false;
        this.prizeBtn.onTap(this, () => {
            window.location.href = MConfigs.rewardRecordUrl;
        })

        this.btnShare.onTap(this, () => {
            if (GameMgr.instance.activityEnd) {
                ToastPanel.show("活动已结束");
                return;
            }

            setTimeout(() => {
                let timestamp = NetUtils.getTimestamp();
                Net.sendPost(Net.uri.share, {
                    timestamp: timestamp,
                    token: NetUtils.md5(timestamp + "duiba4jxabc")
                }, () => {
                    SceneCtrl.instance.currentScene.dispatchEvent(new egret.Event("shareSuccess"));
                }, () => true);
            }, 4000);
            window.location.href = MConfigs.shareUrl;

        });

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

            NetManager.ins.clickLog(this.startExposure);
            // this.btnStart.touchEnabled = false;
            // this.btnStart.touchChildren = false;
            Loading.instace.show();
            let leftTimes = GameMgr.instance.gameCount;
            if (typeof leftTimes == "number") {
                if (leftTimes > 0) { //有剩余次数
                    Net.sendPost(Net.uri.start, undefined, (res) => {
                        SceneCtrl.instance.change(MainScene, {
                            startId: res.data.startId,
                            maxScore: res.data.maxScore
                        });

                        NetUtils.refreshGameCount();
                    }, () => { Loading.instace.hide(); resume() });
                } else { //没有剩余次数
                    this.btnStart.touchEnabled = true;
                    this.btnStart.touchChildren = true;
                    showSharePanel();
                    resume();
                }
            }
        });
        this.refreshPage();

        this.addEventListener("shareSuccess", () => {
            this.refreshPage();
        }, this);
    }



    initBuried() {
        let startDpmIn = Buried.connectDpm(110, 1, 1); // 点击埋点   
        let startDcmIn = Buried.connectDcm(202, 0, 0); // 曝光埋点
        this.startExposure = Buried.createExposure(startDpmIn, startDcmIn);
        NetManager.ins.showLog(this.startExposure);

        let signDpmIn = Buried.connectDpm(110, 2, 1); // 点击埋点   
        let signDcmIn = Buried.connectDcm(202, 0, 0); // 曝光埋点
        this.signExposure = Buried.createExposure(signDpmIn, signDcmIn);
        NetManager.ins.showLog(this.signExposure);
    }

    public refreshPage() {
        NetUtils.refreshGameCount().then((res) => {
            let leftTimes = res.data.leftTimes;
            this.labelFreeTime.text = leftTimes <= 0 ? "今日暂无游戏次数" : `今日剩余次数：${leftTimes}次`;

            //判断是否需要弹签到弹窗
            Net.sendGet(Net.uri.signData, undefined, (res) => {
                if (!(res.data.todayPopSignFlag & 1 << 1)) { //没弹过弹窗
                    PanelCtrl.instance.show(SignInPanel, { response: res });
                }
            });
        }, () => {
            Loading.instace.show()
        });
    }

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

        NetManager.ins.clickLog(this.signExposure);
        Net.sendGet(Net.uri.signData, undefined, (res) => {
            PanelCtrl.instance.show(SignInPanel, { response: res });

        });
    }
}

export class SharePanel extends CommonPanel {
    private shareExposure: any;
    context: StartScene = null;

    onClose: () => void;

    constructor() {
        super();
        this.init({
            title: "次数已用完",
            content: "赶快号召小伙伴一起来参与吧~",
            btnText: "分享好友",
            onClose: () => {
                this.onClose && this.onClose();
            }
        });
    }

    onSkinComplete() {
        super.onSkinComplete();
        this.initBuried();
        this.btn.onOnceTap(this, (resume) => {
            NetManager.ins.clickLog(this.shareExposure);

            setTimeout(() => {
                let timestamp = NetUtils.getTimestamp();
                Net.sendPost(Net.uri.share, {
                    timestamp: timestamp,
                    token: NetUtils.md5(timestamp + "duiba4jxabc")
                }, () => {
                    SceneCtrl.instance.currentScene.dispatchEvent(new egret.Event("shareSuccess"));
                }, () => true);
            }, 4000);
            window.location.href = MConfigs.shareUrl;

            this.hidePanel();
            this.onClose && this.onClose();
        });
    }
    initBuried() {
        let shareDpmIn = Buried.connectDpm(110, 3, 1); // 点击埋点   
        let shareDcmIn = Buried.connectDcm(202, 0, 0); // 曝光埋点
        this.shareExposure = Buried.createExposure(shareDpmIn, shareDcmIn);
        NetManager.ins.showLog(this.shareExposure);

    }
}




