import Scene from "../views/Scene";
import MButton from "../MUI/MButton";
import SceneCtrl from "../Ctrls/SceneCtrl";
import MainScene from "./MainScene";
import PanelCtrl from "../Ctrls/PanelCtrl";
import SignInPanel from "../Panel/SignInPanel";
import SelectPropsPanel from "../Panel/SelectPropsPanel";
import Net from "../Global/Net";
import { Decorator } from "../Decorator/Decorator";
import SoundMgr from "../Mgr/SoundMgr";
import GameMgr from "../Mgr/GameMgr";
import MovieClipMgr from "../Mgr/MovieClipMgr";
import RankListPanel from "../Panel/RankListPanel";
import ToastPanel from "../Components/ToastPanel";
import Loading from "../Loading/Loading";
import RulePanel from "../Panel/RulePanel";
import MyPropsPanel from "../Panel/MyPropsPanel";
import { MConfigs } from "../Global/MConfigs";
import SpUserPanel from "../Panel/SpUserPanel";
import { Buried } from "../../libs/tw/util/Buried";
import MItem from "../components/MItem";
import { NetUtils } from "../Global/NetUtils";
import { MConst } from "../Global/MConst";
import RewardPanel from "../Panel/RewardPanel";
import CommonPanel from "../Panel/CommonPanel";

interface StartButton extends MButton {
    labelStartShadow: eui.Label;
    labelStart: eui.Label;
}

@Decorator.ClassName("StartScene")
export default class StartScene extends Scene {
    public btnReward: eui.Button;
    public btnMusic: eui.ToggleButton;
    public btnStart: StartButton;
    public btnRule: MButton;
    public btnRankList: MButton;
    public dataGroup: eui.DataGroup;

    async preLoadRes() {
        await super.preLoadRes();
        return new Promise(async resolve => {
            await RES.getResAsync("bgm_mp3");
            resolve();
        });
    }

    onSkinComplete() {
        super.onSkinComplete();

        SoundMgr.instance.setMusic("bgm_mp3");

        //任务
        this.dataGroup.itemRenderer = TaskItem;
        this.refreshTask();

        if (!GameMgr.instance.hasSetMusic) {
            SoundMgr.instance.enabled = true;
        }

        this.btnReward.onTap(this, () => {
            location.href = MConfigs.rewardRecordUrl;
        });

        this.btnStart.onOnceTap(this, (resume) => {
            if (!GameMgr.instance.hasSetMusic) {
                SoundMgr.instance.enabled = true;
                GameMgr.instance.hasSetMusic = true;
            }

            let leftTimes = GameMgr.instance.leftTimes;
            if (leftTimes == null) {
                ToastPanel.show("invalid leftTimes value");
                resume();
            } else if (leftTimes <= 0) {
                // ToastPanel.show("今日游戏次数已用完");
                if (GameMgr.instance.leftInviteCnt <= 0) {
                    PanelCtrl.instance.show<CommonPanel>(CommonPanel).data = {
                        title: "机会用完",
                        content: "今日游戏次数已达上限\n明天再来哦",
                        btnLabel: "我知道了",
                    };
                } else {
                    PanelCtrl.instance.show<CommonPanel>(CommonPanel).data = {
                        title: "机会不足",
                        content: "每邀请1个好友登录\n民生银行APP\n即可获得1次游戏次数",
                        tip: "每日助力上限为10次",
                        btnLabel: "去邀请",
                        btnEvent: (context) => {
                            window.open(MConfigs.share.url);
                            context.hidePanel();
                        }
                    };
                }
                resume();
            } else if (GameMgr.instance.allPeriodEnd) {
                ToastPanel.show("该活动已结束！");
                resume();
            } else {
                Net.sendPost(Net.Url.start, undefined, (res) => {
                    SceneCtrl.instance.change(MainScene, { startId: res.data.startId });
                }, () => { resume() });
            }
        });

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

        this.btnRankList.onTap(this, () => {
            PanelCtrl.instance.show(RankListPanel, { defaultToggle: 1 });
        });

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

        this.refresh();
    }

    private refresh() {
        Net.sendGet(Net.Url.visit, undefined, (res) => {
            GameMgr.instance.minEnableCaptchaScore = res.data.minEnableCaptchaScore;
            GameMgr.instance.leftTimes = res.data.leftTimes;

            GameMgr.instance.allPeriodEnd = res.data.allPeriodEnd;

            const text = "开始游戏×" + res.data.leftTimes;
            this.btnStart.labelStart.text = text;
            this.btnStart.labelStartShadow.text = text;

            if (res.data.prevPopUpFlag) {
                PanelCtrl.instance.show(RankListPanel, { defaultToggle: 2 });
            }
        }, true);

        Net.sendGet(Net.Url.shareData, undefined, (res) => {
            GameMgr.instance.leftInviteCnt = res.data.leftInviteCnt;
            GameMgr.instance.assistItemId = res.data.assistItemId;

            let newInviteCnt = res.data.newInviteCnt;
            if (newInviteCnt > 0) {
                PanelCtrl.instance.show<CommonPanel>(CommonPanel).data = {
                    title: "恭喜您",
                    content: `${newInviteCnt}个好友为你助力成功\n次数+${newInviteCnt}`,
                    btnLabel: "我知道了",
                }
            }
        });
    }


    public refreshTask() {
        Net.sendGet(Net.Url.taskData, undefined, (res) => {
            const taskList = res.data as { id: string, status: 0 | 1 | 2 }[]

            let arr: ItemData[] = [];
            let shareConfig: ItemData = MConfigs.task["share"];
            shareConfig.status = 0;
            shareConfig.context = this;
            arr.push(shareConfig);
            for (let i = 0; i < taskList.length; i++) {
                let config: ItemData = MConfigs.task[taskList[i].id];
                config.status = taskList[i].status;
                config.context = this;
                arr.push(config);
            }
            this.dataGroup.dataProvider = new eui.ArrayCollection(arr);
        }, () => { Loading.instace.show() });
    }
}


interface ItemData {
    title: string,
    tip: string,
    content: string,
    url: string,
    status?: 0 | 1 | 2,
    taskCode: string,
    context?: StartScene
}

class TaskItem extends MItem { //Item
    public title: eui.Label;
    public content: eui.Label;
    public btn: MButton;
    public tip: eui.Label;

    data: ItemData;

    onSkinComplete() {
        this.btn.onOnceTap(this, (resume) => {
            switch (this.data.status) {
                case 0:
                    window.location.href = this.data.url;
                    break;
                case 1:
                    let timestamp = NetUtils.getTimestamp();
                    Net.sendPost(Net.Url.taskComplete, {
                        taskId: this.data.taskCode,
                        timestamp: timestamp,
                        token: NetUtils.md5(this.data.taskCode + timestamp.toString() + MConst.Md5ConstStr)
                    }, (res) => {
                        PanelCtrl.instance.show<RewardPanel>(RewardPanel).data = {
                            imgUrl: res.data.icon,
                            rewardUrl: res.data.url
                        };
                        this.data.context.refreshTask();
                        resume();
                    }, () => { resume() });
                    break;
                case 2:
                    break;
                default:
                    ToastPanel.show("invalid task status code");
                    resume();
                    break;
            }
        });
    }

    dataChanged() {
        this.title.text = this.data.title;
        this.tip.text = this.data.tip;
        this.content.text = this.data.content;
        //处理分享任务
        if (this.data.taskCode == "share") {
            this.btn.label = "去邀请";
            this.btn.touchEnabled = true;
        } else {
            //按钮文字
            let btnStr = "";
            switch (this.data.status) {
                case 0:
                    btnStr = "去完成";
                    break;
                case 1:
                    btnStr = "去领取"
                    break;
                case 2:
                    btnStr = "已完成"
                    break;
                default:
                    ToastPanel.show("invalid task status code");
                    break;
            }
            this.btn.label = btnStr;
            //处理已完成
            if (this.data.status == 2) {
                this.btn.touchEnabled = false;
            } else {
                this.btn.touchEnabled = true;
            }
        }
    }
}