import mobx from "mobx";
import { sendWebNet, sendWebNetWithToken, WebNetName } from "../Utils/WebNet/WebNet";
import { AESDecrypt, AESEncrypt } from "../Utils/Crypto";
import { changeScene, hideWaiting, showPanel, showToast, showWaiting } from "../../Module/UIFast";
import { startNecCaptcha } from "../Utils/ecaptcha/ecaptcha";
import { HomeScene } from "../Scenes/HomeScene";
import GameResultPanel from "../Panels/GameResultPanel";

const { makeAutoObservable } = mobx;

export enum ESpType {
    bag_silver = "sp_bag_silver",           // 银福袋
    revival_card = "sp_revival_card",       // 复活卡
    shield_card = "sp_shield_card",         // 护盾卡
    agility_card = "sp_agility_card",       // 移速卡
    experience_card = "sp_experience_card", // 双倍卡
    add_length = "sp_add_length",           // 加长卡
    decoration_1 = "sp_decoration_1",       // 蛇皮肤
}

export interface IStartInfo {
    barrierFlag: boolean,      // 本局游戏难度是否上升
    firstGameFlag: boolean,     // 本局是否第一局，为true则有一，二，无尽模式三个阶段的区别
    accumulateLuckNum: number,     // 当局累计获得福袋数量
    initScore: number,     // 当局初始分数值
    limitLuckNum: number,     // 当日上限可获得福袋数
    downArea: string[],     // 掉落分布，集合，比如每日上限6个，这里配置返回1、2、3
    currentAcquireNum: number,     // 当局剩余可获得福袋数，不包含accumulateLuckNum，当局累计获得福袋数量
    currentStage: 1 | 2 | 3,     // 当前应该进入的阶段(1-一阶段 2-二阶段 3-无尽模式)
    spCardList: [{ spId: ESpType, num: number }],     // 道具卡集合
    currentDressUp: "sp_decoration_default" | "sp_skin_snake_year", // sp_decoration_default装扮默认皮肤，sp_skin_snake_year装扮蛇皮肤
    startId: number,    // 游戏记录ID
    slideScore: number,    // 校验滑块的分数值
    eachUseLimitTimes: number //每局可使用道具限制数量	
}


class GameStore {

    gameInfo = {
        length: 0,
        energy: 0,
        killNum: 0,
        luckNum: 0,
        composeSpList: {},
        useSpCount: 0
    };

    startInfo: IStartInfo = null;

    async startGame(startId: string | number = null) {
        showWaiting();
        const { success, data } = await sendWebNetWithToken(WebNetName.startGame, {
            startId: startId,
        });
        hideWaiting();

        if (!success) {
            return false;
        }

        const decrypt: IStartInfo = JSON.parse(AESDecrypt(data, "6FDCE02EBB43C3A8", "cDOiBC1n2QrkAY2P"));

        console.log(decrypt);

        this.startInfo = decrypt;

        this.gameInfo = {
            length: decrypt.initScore || 0,
            energy: 0,
            killNum: 0,
            luckNum: 0,
            composeSpList: {},
            useSpCount: 0
        };

        return success;
    }

    async submitOne() {
        const { energy: score, killNum } = this.gameInfo;

        const params = {
            startId: this.startInfo.startId,
            score: score,
        };

        showWaiting();
        const { success, data } = await sendWebNet(WebNetName.submitOne, params);
        hideWaiting();

        if (!success) {
            changeScene(HomeScene);
            return false;
        }

        return success;
    }

    async submitTwo() {
        const { energy: score, killNum } = this.gameInfo;

        const params = {
            startId: this.startInfo.startId,
            score: score,
        };

        showWaiting();
        const { success, data } = await sendWebNet(WebNetName.submitTwo, params);
        hideWaiting();

        if (!success) {
            changeScene(HomeScene);
            return false;
        }

        return success;
    }

    async finalSubmit() {

        const { energy: score, killNum, luckNum, composeSpList } = this.gameInfo;


        const param: any = {
            startId: this.startInfo.startId,
            score,
            finalKill: killNum,
            composeSpList: [...Object.keys(composeSpList).map(key => ({ spId: key, num: composeSpList[key] } as any))],
        };

        const silverNum = luckNum + this.startInfo?.accumulateLuckNum || 0;
        if (silverNum) {
            param.composeSpList.push({
                spId: "sp_bag_silver",
                num: silverNum
            });
        }

        if (score >= this.startInfo.slideScore) {
            param.slideValue = await startNecCaptcha("1ee4615751874cbeaea4dd4681930f61", 3).catch(() => {
                showToast("校验失败");
                changeScene(HomeScene);
                return false;
            });
            if (!param.slideValue) {
                return false;
            }
        }

        console.log("提交参数", param);

        const encrypt = AESEncrypt(JSON.stringify(param), "6FDCE02EBB43C3A8", "cDOiBC1n2QrkAY2P");

        showWaiting();

        let res = null;
        for (let i = 0; i < 3; i++) {
            res = await sendWebNetWithToken(WebNetName.finalSubmit, { param: encrypt }, {
                isGet: false,
            });
            const { success } = res;
            if (success) {
                break;
            }
        }

        const { success, data } = res;

        hideWaiting();
        if (!success) {
            changeScene(HomeScene);
            return false;
        }

        showPanel(GameResultPanel, data);

        return success;

    }

    async useProps(spId) {
        const { success, data } = await sendWebNetWithToken(WebNetName.consumeSp, { spId, startId: this.startInfo.startId })
        return success
    }
}

const gameStore: GameStore = makeAutoObservable(new GameStore());

export default gameStore;