import Panel from "../views/Panel";
import MItem from "../components/MItem";
import MButton from "../MUI/MButton";
import { MConfigs } from "../Global/MConfigs";
import Net from "../Global/Net";
import { Decorator } from "../Decorator/Decorator";
import { MConst } from "../Global/MConst";
import ToastPanel from "../Components/ToastPanel";
import SceneCtrl from "../Ctrls/SceneCtrl";
import PanelCtrl from "../Ctrls/PanelCtrl";
import WinningPanel from "./WinningPanel";
import StartScene from "../Scene/StartScene";
import GameMgr from "../Mgr/GameMgr";
import { MUtils } from "../Global/MUtils";
import { NetUtils } from "../Global/NetUtils";
import MainScene from "../Scene/MainScene";
import PropsItem from "./PropsItem";
import Loading from "../Loading/Loading";
import { Buried } from "../../libs/tw/util/Buried";
import MLabel from "../MUI/MLabel";

@Decorator.OnUpdate
export default class SelectPropsPanel extends Panel implements Decorator.IDefaultCallback {
    get skinKey() { return "SelectPropsPanel" }
    public labelScore: MLabel;
    public labelCountDown: eui.Label;
    public dataGroup: eui.DataGroup;
    private timer = MConfigs.selectPropsCountDown * 1000;
    private timing: boolean = false;
    public bg: eui.Image;
    public bgMask: eui.Image;
    public groupBottom: eui.Group;
    public btnSubmit: MButton;
    data: {
        context: MainScene
    }

    async preLoadRes() {
        await super.preLoadRes();
        return RES.loadGroup("props");
    }

    constructor(data: any) {
        super(data);
        this.visible = false;
    }

    onUpdate(dt: number) {
        if (this.timing) {
            if (this.timer > 0) {
                this.timer -= dt;
            } else {
                this.timer = 0;
                this.timing = false;
                //时间到的逻辑
                Loading.instace.show();
                this.hidePanel();
                this.data.context.finalSubmit();
            }
            this.labelCountDown.text = Math.ceil(this.timer / 1000).toString() + "S";
        }
    }

    onSkinComplete() {
        super.onSkinComplete();
        this.visible = false;
        this.timing = true;
        this.labelScore.text = this.data.context.score.toString();
        Buried.doShowBuried(11);
        this.btnSubmit.onOnceTap(this, () => {
            Buried.doClickBuried(11);
            Loading.instace.show();
            this.hidePanel();
            this.data.context.finalSubmit();
        });

        Net.sendGet(Net.Url.queryProps, {
            startId: this.data.context.startId
        }, (res) => {
            let map = res.data.spMap;
            let arr = [];

            for (let id of Object.keys(map)) {
                if (map[id] && map[id] > 0) {
                    let limit: number = Infinity;
                    if (id == MConst.ReviveCardId) { //是复活卡
                        if (res.data.leftReviveTimes <= 0 || this.data.context.timer <= 0) { //没有复活次数了或没有游戏时间了
                            continue;
                        }
                    } else { //是加分卡
                        limit = res.data.maxUseSpCnt;
                    }

                    arr.push({
                        id: id,
                        num: map[id],
                        context: this,
                        limit: limit,
                        mainScene: this.data.context
                    });
                }
            }

            if (arr.length <= 0) { //没有可用道具直接提交
                this.hidePanel();
                this.data.context.finalSubmit();
                return;
            } else {
                this.visible = true;
            }

            this.dataGroup.dataProvider = new eui.ArrayCollection(arr);
            this.dataGroup.itemRenderer = SelectPropsItem;
            this.bgMask.height -= (102 + 45) * (3 - arr.length);
            this.bg.mask = this.bgMask;
            this.groupBottom.y -= (102 + 45) * (3 - arr.length);
        }, true);

    }
}

class SelectPropsItem extends MItem {
    public btnUse: MButton;
    public selector: eui.Group;
    public labelSelectorNum: eui.Label;
    public btnReduce: eui.Button;
    public btnAdd: eui.Button;

    private _selectNum: number = 0;
    private get selectNum() {
        return this._selectNum;
    }
    private set selectNum(v: number) {
        v = Math.clamp(v, 1, Math.min(this.data.limit, this.data.num) || 0);
        this._selectNum = v;
        this.labelSelectorNum.text = this._selectNum.toString();

        if (this._selectNum <= 0) {
            this.btnUse.enabled = false;
        } else {
            this.btnUse.enabled = true;
        }
    }

    data: {
        id: string,
        num: number,
        limit: number,
        context: SelectPropsPanel,
        mainScene: MainScene
    }

    createChildren() {
        super.createChildren();
        this.btnUse.visible = false;
    }

    dataChanged() {
        let propsItem = new PropsItem();
        propsItem.data = this.data;
        propsItem.x = -8;
        propsItem.y = 10;
        this.addChild(propsItem);

        if (this.data.id == MConst.ReviveCardId) { //是复活卡
            //复活卡使用按钮便移动
            this.btnUse.x = 209;
            //隐藏复活卡的选择器
            this.selector.visible = false;
            //复活按钮点击事件
            this.btnUse.onOnceTap(this, () => {
                Buried.doClickBuried(12);
                Loading.instace.show();
                this.data.context.hidePanel();
                //获取复活接口所需参数
                const startId = this.data.mainScene.startId;
                const seq = NetUtils.encryptSeq(this.data.mainScene.reviveSeq);
                //请求复活接口
                Net.sendPost(Net.Url.revive, {
                    startId: startId,
                    seq: seq,
                    token: NetUtils.md5(startId.toString() + seq.toString() + MConst.Md5ConstStr)
                }, () => { //成功
                    //游戏继续
                    this.data.mainScene.revive();
                    Loading.instace.hide();
                }, true);
            });
        } else { //是加分卡
            //加分卡点击事件
            this.btnUse.onOnceTap(this, () => {
                Buried.doClickBuried(12);
                Loading.instace.show();
                this.data.context.hidePanel();
                this.data.mainScene.finalSubmit(this.data.id, this.selectNum);
            });
        }

        this.btnUse.visible = true;
    }

    onSkinComplete() {
        //设置默认的使用数量为1
        this.selectNum = 1;
        this.btnAdd.onTap(this, () => this.selectNum++);
        this.btnReduce.onTap(this, () => this.selectNum--);
        Buried.doShowBuried(12);
    }
}