import Game from "../game/Game";

/**
 * @description 游戏核心玩法数据
 * @author 邹勇
 */
export class GameData {


    public dataFinish: boolean = false;

    public savePropFinish: boolean = false;

    public savePropsFinish: boolean = false;

    public getPropsFnish: boolean = false;


    public configs: any = {};
    public adShowConfig: ADShowCfg;
    /** 功能开启 */
    public funOpenData: string[] = [];

    public gameData: PlayerProp = null;
    /** 标志位：刷新主界面货币 */
    public init_coin: boolean = false;

    /** 标志位：刷新主界面头像 */
    public init_head: boolean = false;

    public props: Map<number, number> = new Map<number, number>();

    public pools = [
        { url: "game/prefab/tips", num: 20 },
        { url: "game/prefab/coin", num: 20 }
    ];

    /** 主页样式脚本 */
    public gameStyle: Game = null;

    /**
     * 初始化游戏数据：网络配置信息，用户信息
     * @returns 
     */
    public async init() {

        let data: any = { "versionCode": gData.appData.version };
        let response = await mk.http.sendData('getAllConfigInfo', data);
        if (response.errcode != 0) {
            if (response.errcode == -10003 || response.errcode == -20003) {
                //清除缓存
                gData.loginData.reload();
            }
            return;
        }
        mk.console.logSingle("getAllConfigInfo", response.data);
        this.initConfigs(response.data);

        data = {};
        response = await mk.http.sendData('getInfoCrypt', data);
        if (response.errcode != 0) {
            return;
        }
        mk.console.logSingle("getInfoCrypt", response.data);
        this.initPlayerProp(response.data)
        this.initProps(response.data.gameUserData);
        gData.moduleData.forEach(element => {
            element.init();
        });

        data = {};
        response = await mk.http.sendData('user/adShowConfig', data);
        if (response.errcode != 0) {
            return;
        }
        this.adShowConfig = response.data;
        mk.console.logSingle("user/adShowConfig", response.data);

        this.dataFinish = true;
    }

    private initConfigs(data) {
        this.configs = data;
        this.funOpenData = this.configs.ServerConfig.Functionswitch.split(",");
    }

    /**
     * 初始化玩家数据
     */
    private initPlayerProp(res_data) {
        this.gameData = new PlayerProp();
        this.gameData.cashIndex = res_data.cashIndex;
        this.gameData.gameUserData = res_data.gameUserData;
        this.gameData.isSignInToday = res_data.isSignInToday;
        this.gameData.isWithdrawable = res_data.isWithdrawable;
        this.gameData.lastTime = res_data.lastTime;
        this.gameData.loginDays = res_data.loginDays;
        this.gameData.newPlayer = res_data.newPlayer;
        this.gameData.piggyBank = res_data.piggyBank;
        this.gameData.piggyBankCashTimes = res_data.piggyBankCashTimes;
        this.gameData.redMoney = res_data.redMoney;
        this.gameData.signInDay = res_data.signInDay;
        this.gameData.totalPiggyBankCashTimes = res_data.totalPiggyBankCashTimes;
        this.gameData.turntableTimes = res_data.turntableTimes;
        this.gameData.userTuCaoInfo = res_data.userTuCaoInfo;
        this.gameData.versioncfg = res_data.versioncfg;
    }

    /**
     * 保存单个数据
     */
    public async setProp(key: GameProp, value: number) {
        let data = {
            key: key + '',
            value: value + ''
        };
        this.props.set(key, value);
        await mk.http.sendData('savePlayerProp', data);
        this.savePropFinish = true;
    }

    /**
     * 保存多个数据
     */
    public async setProps(arr: { key: GameProp, value: number }[]) {
        let needProp = {};
        for (let i = 0; i < arr.length; i++) {
            needProp[arr[i].key + ''] = arr[i].value + "";
        }
        let data = {
            needProp: needProp
        };

        for (let i = 0; i < arr.length; i++) {
            this.props.set(arr[i].key, arr[i].value);
        }
        await mk.http.sendData('saveAllPlayerProp', data);
        this.savePropsFinish = true;
    }

    /** 获取属性 */
    public getProp(key: GameProp): number {
        if (this.props == null) {
            return 0;
        }
        let value = this.props.get(key);
        return value == null ? 0 : value;
    }

    /**
     * 向服务器请求所有属性后更新
     */
    public async getAllProps() {
        let response = await mk.http.sendData('getAllPlayerProp', {});
        if (response.errcode != 0) {
            return;
        }

        this.initProps(response.data);

        this.getPropsFnish = true;
    }

    private initProps(data) {
        if (data == null) {
            return;
        }
        for (let key in data) {
            this.props.set(parseInt(key), JSON.parse(data[key]));
        }
    }

    /**
     * 第二天需要重置的数据
     */
    public resetProps() {
        let arr = [];
        arr.push({ key: GameProp.sign_can, value: 1 });

        this.setProps(arr);
    }

    /** 是否是新用户 */
    public isNewPlayer(): boolean {
        let v = this.getProp(GameProp.newPlayer);
        return v == 0;
    }
}

/**
 * 所有模块的非校验数据
 */
export enum GameProp {
    /** -------------------- 通用玩家数据 ------------------------- */
    /** 是否新手 */
    newPlayer = 1,
    /** 当前新手引导步骤 */
    guideID = 2,

    /** ------------------ 游戏核心数据 --------------------------- */
    /** 关卡数 */
    levelNum = 10,
    /** 锤子道具数目 */
    hammerPropNum = 1001,
    /** 重设道具数目 */
    resetPropNum = 1002,
    /** 变色道具数目 */
    changePropNum = 1003,

    /** ------------------ 转盘数据 ------------------------------ */
    turnable_leftTimes = 20,

    /** ------------------ 存钱罐数据 ----------------------------- */

    /** ------------------ 签到数据 ----------------------------- */
    /** 上次签到进度 */
    sign_last_bar = 120,
    /** 当前能否签到 */
    sign_can = 121,
    /** ------------------ 红包提现 ----------------------------- */
    /** 提现进度 */
    redBag_cash_bar = 220,
}

/**
 * 玩家数据
 */
class PlayerProp {
    /** 自定义不需要校验的数据 */
    gameUserData = 0;

    _isSignInToday = 0;
    /**
     * 今日是否有签到
     * - 0 未签到，表示可以签到
     * - 1 有签到，表示不可签到
     */
    set isSignInToday(value: number) {
        this._isSignInToday = value;
        gData.sign.init_data = true;
    }
    get isSignInToday(): number {
        return this._isSignInToday;
    }

    private _piggyBank: number = 0;
    /** 存钱罐存款 */
    set piggyBank(value: number) {
        this._piggyBank = value;
        gData.gameData.init_coin = true;
        gData.pigbank.init_data = true;
    }
    get piggyBank(): number {
        return this._piggyBank;
    }

    _isWithdrawable = 0;
    /**
     * 存钱罐能否提现
     * - 0 不能提现
     * - 1 能提现
     */
    set isWithdrawable(value: number) {
        if (this._isWithdrawable != value) {
            this._isWithdrawable = value;
            gData.pigbank.init_data = true;
        }
    }
    get isWithdrawable(): number {
        return this._isWithdrawable;
    }

    /** 存钱罐每日提现次数 */
    piggyBankCashTimes = 0;
    /** 累计存钱罐每日提现次数 */
    totalPiggyBankCashTimes = 0;
    /** 提现进度 */
    cashIndex = 0;
    /** 上次登录时间 */
    lastTime = 0;
    /** 登录天数 */
    loginDays = 0;
    newPlayer = 0;

    private _redMoney: number = 0;
    /** 红包币数量 */
    set redMoney(value: number) {
        this._redMoney = value;
        gData.gameData.init_coin = true;
    }
    get redMoney(): number {
        return this._redMoney;
    }

    _signInDay = 0;
    /** 累计签到次数 客户端理解 上次签到天数 */
    set signInDay(value: number) {
        this._signInDay = value;
        gData.sign.init_data = true;
    }
    get signInDay(): number {
        return this._signInDay;
    }
    /** 转盘次数 */
    turntableTimes = 0;
    /** 版本号 */
    versioncfg = 0;
    /** 福袋数据 */
    userTuCaoInfo = 0;
    /** 关卡数 */
    levelNum = 0;
    /** 锤子道具数目 */
    hammerPropNum = 0;
    /** 重设道具数目 */
    resetPropNum = 0;
    /** 变色道具数目 */
    changePropNum = 0;
}

/**
 * 奖励状态
 */
export enum RewardState {
    /** 已领取 */
    none = 1,
    /** 未解锁 */
    lock = 2,
    /** 可领取 */
    unlock = 3
}

/**
 * 奖励类型
 */
export enum RewardType {
    /** 红包币 */
    redBag = 1,
    /** 毛币 */
    rmb = 2,
    /** 金猪币 */
    pigRmb = 3,
}

/**
 * 音频路径
 */
export enum AUDIO_TYPE {
    /**主界面背景音乐*/
    bgm = 'bgm',
    /**打开存钱罐界面播放一次*/
    pigBank = 'pigBank',
    /**关卡玩法背景音乐*/
    missionBg = 'missionBg',
    /**红包币领取界面关闭音效*/
    rewardClose = 'rewardClose',
    /**红包币领取界面开启音效*/
    rewardOpen = 'rewardOpen',
    /**红包界面打开音效*/
    reward = 'reward',
    /**提现到账界面打开播放一次*/
    receiptNotice = 'receiptNotice',
    /**通用按钮点击音效 */
    button = 'button',
    /**转盘转动音效*/
    turnableplay = 'turnableplay',
    /**转盘转动音效*/
    turnplateDrawEnd = 'turnplateDrawEnd',
    /**主页背景音乐 */
    music_startBg = "music_startBg",
    /**游戏背景音乐 */
    music_gameBg = "music_gameBg",
    /**按钮点击 */
    ef_button_click = "ef_button_click",
    /**红包打开 */
    ef_redPacket_open = "ef_redPacket_open",
    /**红包来了音效 */
    ef_redPacket_come = "ef_redPacket_come",
    /**消除4个 */
    ef_bonus4 = "ef_bonus4",
    /**消除5个 */
    ef_bonus5 = "ef_bonus5",
    /**消除6个 */
    ef_bonus6 = "ef_bonus6",
    /**消除7个 */
    ef_bonus7 = "ef_bonus7",
    /**消除8个 */
    ef_bonus8 = "ef_bonus8",
    /**普通消除音效 */
    ef_eliminate = "ef_eliminate",
    /**bouns消除音效 */
    ef_eliminate_bonus = "ef_eliminate_bonus",
    /**胜利音效 */
    ef_win = "ef_win",
    /**锤子 */
    ef_change = "ef_change",
    /**刷新 */
    ef_refresh = "ef_refresh",
    /**飞翔 */
    ef_fly = "ef_fly",
}

/** ECPM */
type ADShowCfg = {
    average_ecpm: number,
    insert_probability: number,
    is_show_banner: number,
    is_show_inter: number,
}

type PlayerInfoType = {
    /** 自定义不需要校验的数据 */
    gameUserData: object,
    /** 今日是否有签到 */
    isSignInToday: number,
    /** 存钱罐存款 */
    piggyBank: number,
    /** 存钱罐能否提现 */
    isWithdrawable: boolean,
    /** 存钱罐每日提现次数 */
    piggyBankCashTimes: number,
    /** 累计存钱罐每日提现次数 */
    totalPiggyBankCashTimes: number,
    /** 提现进度 */
    cashIndex: number,
    /** 上次登录时间 */
    lastTime: number,
    /** 登录天数 */
    loginDays: number,
    newPlayer: Boolean,
    /** 红包币数量 */
    redMoney: number,
    /** 累计签到次数 客户端理解 上次签到天数 */
    signInDay: number,
    /** 转盘次数 */
    turntableTimes: number,
    /** 版本号 */
    versioncfg: string,
    /** 福袋数据 */
    userTuCaoInfo: object,
}

/**事件类型 */
export enum EVENT_TYPE {
    BACK_WxAuth = "BACK_WxAuth",
    UPDATE_CashNum = "UPDATE_CashNum",
}

export enum StorageKey {


}