import { Scene } from "../../module/views/Scene";
import { showToast, showPanel, showWaiting, hideWaiting } from "../../module/ctrls";
import { Tools } from "../Tools";
import { GTool } from "../../module/tools/GTool";
import { countDown } from "../common/countDown";
import { getRecordUrl, doJoin, getNgameStartStatus, submit, getOrderStatus, ajaxElement } from "./Hdtool";

//补给站接口示例
export class IndexScene extends Scene {
    get groupNames() { return ["IndexScene"] };
    get skinName() { return "IndexScene" };

    startBtn: FYGE.Button;
    recordBtn: FYGE.Button;
    ruleBtn: FYGE.Button;

    //ajaxElement返回的数据
    data: {
        "rule": string,
        "element": {
            "isCreditsTypeOpen": boolean,
            "myCreditsLong": number,
            "freeLimit": number,
            "success": boolean,
            "myCredits": string,
            "needCredits": string,
            "freeEmpty": boolean,
            "needCreditsLong": number,
            "status": number
        }
    }
    //doJoin接口返回数据
    doJoinData: {
        "success": boolean,
        "code": string,
        "desc": string,
        "timestamp": number,
        "data": string
    }
    //start轮询接口返回数据
    startData: {
        "success": boolean,
        "code": string,
        "desc": string,
        "timestamp": number,
        "data": {
            "orderId": string,
            "submitToken": string,
        }
    }
    countTxt: FYGE.TextField
    myCredits: FYGE.TextField
    initUi() {
        this.countTxt = this.addChild(Tools.getText(
            "",
            30,
            "#ffffff",
            FYGE.TEXT_ALIGN.CENTER,
            400,
            (750 - 400) / 2,
            1340
        ))
    }
    start(data) {
        super.start();
        //status
        // 1  积分不足   状态暂时有问题
        // 3  没有抽奖次数
        // 4  今日没有抽奖次数
        // 5  页面显示 今日剩余
        // 6  <span>1</span>元宝/每次
        // 7  页面显示 剩余
        //次数文案
        const { freeLimit, status, needCredits, myCredits } = this.data.element;
        this.countTxt.text = (() => {
            switch (status) {
                case 1:
                    return "积分不足";
                case 3:
                    return "无剩余次数";
                case 4:
                    return "今日无剩余次数";
                case 5:
                    return "今日剩余免费次数：" + freeLimit;
                case 6:
                    return "每局消耗" + needCredits + (window["CFG"].unitName || "积分");
                case 7:
                    return "剩余免费次数：" + freeLimit;
                default:
                    return "";
            }
        })()
        //积分文案
        this.myCredits.text = "我的" + (window["CFG"].unitName || "积分") + "：" + myCredits;

    }
    async doJoin() {
        showWaiting();
        //@ts-ignore
        this.doJoinData = await doJoin()
        hideWaiting();
        if (this.doJoinData.success) { //轮询
            showWaiting();
            this.startData = await getNgameStartStatus(this.doJoinData.data)
            hideWaiting();
            if (this.startData.success) {//轮询成功
                //开始游戏
                if (!GTool.readCache(Tools.cacheKey)) {
                    //显示引导
                    // this.showGuide()
                } else {
                    // this.startGame();
                }
            }
        }
    }
    initEvents() {
        //开始游戏流程
        this.startBtn.addEventListener(FYGE.MouseEvent.CLICK, () => {
            //是否登录判断
            if (window["CFG"].isNotLoginUser) {
                Tools.btnDelay(this.startBtn)
                showToast("您未登录，正在尝试登录中")
                // console.log('调用登录方法');
                if (window['requirelogin']) {
                    window['requirelogin']();
                } else if (window['requireLogin']) {
                    window['requireLogin']();
                } else {

                }
            }
            //次数判断
            else {
                const { freeLimit, status } = this.data.element;
                if (freeLimit >= 1) {
                    //免费次数
                    this.doJoin();
                } else if (status == 4 || status == 3) {
                    showToast("参与次数已达上限")
                } else {
                    //消耗积分玩？没有弹窗，直接扣积分？
                    if (status == 1) {
                        showToast("积分不足，快去赚取更多积分~")
                        //或者跳转
                        if (window["CFG"].getCreditsLink) window.location.href = window["CFG"].getCreditsLink;
                    } else {
                        //积分参与
                        this.doJoin()
                    }
                }
            }
        }, this);
        //跳转我的奖品页面
        this.recordBtn.addEventListener(FYGE.MouseEvent.CLICK, () => {
            Tools.btnDelay(this.recordBtn)
            window.location.href = getRecordUrl('00');
        })
        //任务弹框
        this.ruleBtn.addEventListener(FYGE.MouseEvent.CLICK, () => {
            //打开任务弹框
            // showPanel(RulePanel, { rule: this.data.rule })
        })
    }
    //提交分数流程
    async submit() {
        showWaiting();
        //确认TODO,socre怎么传，
        var res = await submit(this.doJoinData.data, 1, this.startData.data.submitToken)
        if (res.success) {
            //轮询了
            var rr = await getOrderStatus(this.doJoinData.data)
            if (rr.success) {
                hideWaiting();
                //只用更新element
                this.data.element = rr.data.element;
                var lottery = rr.data.lottery
                //中奖弹框
                if (!lottery || lottery.type == "thanks") {
                    // showToast("很遗憾，奖品飘走了")
                    // this.resetGame();
                    // showPanel(NoPrizePanel)
                } else {
                    // showPanel(PrizePanel, lottery)
                }
            } else {
                //重新获取数据
                ajaxElement().then((r) => {
                    hideWaiting()//修改数据
                    if (r.success) this.data = r.data;
                    // this.resetGame()
                })
            }
        } else {//失败
            if (!res.data) {//网络问题
                setTimeout(() => { this.submit() }, 2000)
            } else {//后端返回的失败直接，重置游戏
                ajaxElement().then((r) => {
                    hideWaiting()//修改数据
                    if (r.success) this.data = r.data;
                    // this.resetGame()
                })
            }

        }
    }
}
