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";

@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;


    private startExposure: any;
    private signExposure: any;



    async onSkinComplete() {
        super.onSkinComplete();
        if (!GameMgr.instance.inited) {
            if (isWeiXin()) {
                wxConfig();
            }
            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.btnStart.onOnceTap(this, (resume) => {
            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 (true) { //有剩余次数
                    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();
                    // let panel = PanelCtrl.instance.show<SharePanel>(SharePanel);
                    // panel;
                    // panel.context = this;

                    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() {
        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;

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

    onSkinComplete() {
        super.onSkinComplete();
        this.initBuried();
        this.btn.onOnceTap(this, (resume) => {
            NetManager.ins.clickLog(this.shareExposure);
            PanelCtrl.instance.show<PostPanel>(PostPanel).onClose = () => {
                SceneCtrl.instance.change(StartScene);
            }
            this.hidePanel()
        });
    }
    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);

    }
}

