import { WxApi } from "../WXSDK/Sdk";
import {Dictionary} from "../utils/Dictionary";
import { GameUtils } from "../utils/GameUtils";
import { NetworkManager, PROTOCOLS } from "./NetworkManager";
import { DispatcherManager } from "../utils/DispatcherManager";
import {UserInfoEvent} from "../Data/UserInfoEvent";


export enum requiretype {
    系统赠送 = 1, 金币购买 = 2, 观看视频 = 3, 分享 = 4, 签到 = 5, 活动 = 6, 通过关卡 = 7, 累计登陆 = 8, 邀请人数达到 = 9, 砖石购买 = 10
}

export enum AccountConfig {
    crop,things, land, global, entity, sign, rewards, achievement, invite, mission, treasure_click, theme, lottery
}

export enum AccountUser {
    money, diamond, user_id, game_times, get_themes, video_times, equip_themes, last_action_time, last_favorite_time, progress_themes, revival, stage,vmoney
}

export enum heroAttr {
    id, name, quality, icon, prefab, require_num, require_type
}

export enum signdata {
    sign_days, sign_time
}

export enum entity {
    id, name, entity_id, icon
}

export enum skinattr {
    effectValue_1,
    effectValue_2,
    effectValue_3,
    effectValue_4
}

export class AccountData {
    constructor(_token: string, _config: Object, _appSetting: Object, _user: Object, _userbase: Object, _useInvite: Object = null, _user_stage: Object = null, _user_sign, _user_achievement, _lottery,_use_land_task,_user_video) {
        this.m_token = _token;
        this.m_app_setting = _appSetting;
        this.m_user = _user;
        this.m_user_base = _userbase;
        this.m_sign = _user_sign;
        this.m_task = _user_achievement;
        this.lottery = _lottery;
        this.m_use_land_task = _use_land_task;
        this.m_user_video = _user_video;
        this.userId = this.m_user["user_id"];
        this.openid = this.m_user_base["openid"];
        console.log("user_id:" + this.userId);
        //console.log("open_id:"+this.openid);
    }

    public m_token: string;
    public m_configs: Object;
    public m_app_setting: Object;
    public m_user: Object;
    public m_user_base: Object;
    public m_sign: Object;
    public m_task: Object;
    public m_use_land_task:any;
    public m_user_video:Object;
    public openid: string = "";
    private userId: string = "";
    public lottery: any;
    public roadconfig: { [key: number]: any } = {};
    public m_RewardDic: Object = {};
    public m_EntityDic: { [key: number]: any } = {};
    public m_AchievementDic: Object = {};
    // public m_skinDic:Dictionary<number,SkinData> = new Dictionary();

    //获取玩家落入空中死亡距离
    public get DieDistance():number{
        return Number(this.m_app_setting["DieDistance"]);
    }
    //获取开局砸蛋几率
    public get HitEgg():number{
        return Number(this.m_app_setting["HitEgg"]);
    }
    //获取结算后砸蛋出现几率
    public get EndCheat():number{
        return Number(this.m_app_setting["EndCheat"]);
    }
    //获取误触奖励金币数
    public get CheatReward():number{
        return Number(this.m_app_setting["CheatReward"]);
    }
    //白名单用户
    public get WhiteUser():boolean{
        return this.m_app_setting["WhiteUser"] == "1";
    }

    //签到功能是否开启
    public get StrategySwitch():boolean{
        return this.m_app_setting["StrategySwitch"] == "1";
    }

    //签到功能是否开启
    public get ShowSign():boolean{
        return this.m_app_setting["ShowSign"] == "1";
    }
    //自动勾选
    public get Choose():boolean{
        return this.m_app_setting["choose"] == "1";
    }
    //发起挑战按钮开关
    public get ShowBattleBtn():boolean{
        return this.m_app_setting["ShowBattleBtn"] == "1";
    }

    public get lotterytime():number
    {
        return Number(this.lottery["day_video_times"]);
    }

    public get share(): boolean {
        return this.m_app_setting["share"] == "1";
    }

    public get sharecontent(): string {
        return this.m_app_setting["sharecontent"];
    }
    public get ShareImage(): string {
        return this.m_app_setting["ShareImage"];
    }
    public get cheattime() {
        return Number(this.m_app_setting["cheattime"]);
    }
    public get banner(): boolean {
        return this.m_app_setting["banner"] == "1";
    }
    public get video(): boolean {
        return this.m_app_setting["video"] == "1";
    }
    public get BtnCanMove(): boolean {
        return this.m_app_setting["BtnCanMove"] == "1";
    }
    public get checkscence(): boolean {
        return this.m_app_setting["checkscence"] == "1";
    }
    public get banner_dis(): number {
        return Number(this.m_app_setting["banner_dis"]);
    }
    public get bannerMoveTime(): number {
        return Number(this.m_app_setting["bannerMoveTime"]);
    }
    public get createBannerTimes(): number {
        return Number(this.m_app_setting["createBannerTimes"]);
    }
    public get bannerMoveProp(): number {
        return Number(this.m_app_setting["bannerMoveProp"]);
    }
    public get isShareThenVideo(): boolean {
        return this.m_app_setting["isShareThenVideo"] == "1";
    }
    public get isShowHuiTui(): boolean {
        return this.m_app_setting["isShowHuiTui"] == "1";
    }
    public get start_sprint(): number {
        return Number(this.m_app_setting["start_sprint"]);
    }

    public get IsVideoModel(): boolean {
        return this.m_app_setting["IsVideoModel"] == "1";
    }
    public get videoModelNum(): number {
        return Number(this.m_app_setting["videoModelNum"]);
    }
    public get VideoModelTitle(): string {
        return this.m_app_setting["VideoModelTitle"];
    }
    public get failcount():number
    {
        return Number(this.m_app_setting["failcount"]);
    }
    public get spminspeed():number
    {
        return Number(this.m_app_setting["spminspeed"]);
    }
    public get bgm():boolean
    {
        return this.m_app_setting["bgm"] == "1";
    }

    public get camerahight():number
    {
        return Number(this.m_app_setting["camerahight"]);
    }
    public get ctnfilename():string
    {
        return this.m_app_setting["ctnfilename"];
    }
    public get cheat():boolean
    {
        return this.m_app_setting["cheat"] == "1";
    }
    public get shakestage():boolean
    {
        return this.m_app_setting["shakestage"] && this.m_app_setting["shakestage"] == "1";
    }
    public get stageconfigcdn():boolean
    {
        return this.m_app_setting["stageconfigcdn"] == "1";
    }
    public get playerspeed():number
    {
        return Number(this.m_app_setting["playerspeed"]);
    }
    public get videlAdUnitId():string
    {
        return this.m_app_setting["videlAdUnitId"];
    }
    public get bannerAdUnitId():string
    {
        return this.m_app_setting["bannerAdUnitId"];
    }
    public get tri():boolean
    {
        return this.m_app_setting["tri"] == "1";
    }
    public get recommend():boolean
    {
        return this.m_app_setting["recommend"] == "1";
    }
    public get recommendflg():string
    {
        return this.m_app_setting["recommendflg"];
    }
    public get egg():boolean
    {
        return this.m_app_setting["egg"] == "1";
    }
    public get eggrate():number
    {
        return Number(this.m_app_setting["eggrate"]);
    }
    public get UseId(): string {
        return this.userId;
    }

    public GetConfig(_type: AccountConfig): any {
        var type = AccountConfig[_type];
        return this.m_configs[type];
    }

    public GetUser(_type: AccountUser) {
        var type = AccountUser[_type];
        return this.m_user[type];
    }
    public get GetVideoTotal()
    {
        return Number(this.m_user_video["total"]);
    }

    public GetSign(_datatype: signdata) {
        var type = signdata[_datatype];
        return this.m_sign[type];
    }

    public GetRewardConfig(_rewardid: number): any {
        var reward = this.m_RewardDic[_rewardid];
        return reward;
    }

    public GetEntity(_id: string, attr: entity) {
        if(!this.m_EntityDic[_id])return null;
        return this.m_EntityDic[_id][entity[attr]];
    }

    private GetRewardDic() {
        var config = this.GetConfig(AccountConfig.rewards);
        for (var key in config) {
            this.m_RewardDic[config[key].id] = config[key];
        }
    }

    public GetEntityDic() {
        var config = this.GetConfig(AccountConfig.entity);
        for (var key in config) {
            this.m_EntityDic[config[key].entity_id] = config[key];
        }
    }
    public GetThemeById(_id: number): any {
        var data = this.GetConfig(AccountConfig.theme);
        if (data) {
            for (let index = 0; index < data.length; index++) {
                const element = data[index];
                if (element.id == _id) {
                    return element;
                }
            }
        }
    }

    public GetSkinAttr(_id: number)  {
        var config = this.GetConfig(AccountConfig.theme);
        for (var i = 0; i < config.length; i++)  {
            if (config[i].id == _id)  {
                return config[i];
            }
        }
    }

    public GetAchievementData() {
        var data = this.GetConfig(AccountConfig.achievement);
        var dic = {};

        for (var key1 in data) {
            var type1 = data[key1].type;
            //var obj = {};

            if (dic[type1]) {
                continue;
            }

            var array = [];
            for (var key2 in data) {
                var type2 = data[key2].type;

                if (type1 == type2) {
                    array.push(data[key2]);
                }
            }

            dic[type1] = array;
        }
        this.m_AchievementDic = dic;
    }

    HasTheme(_id:number):boolean
    {
        var has = false;
        var getthemes = this.GetUser(AccountUser.get_themes);
        for(var i = 0; i < getthemes.length;i++)
        {
            if(getthemes[i] == _id)
            {
                has = true;
            }
        }
        return has;
    }

    GetSkinDic(_config:any)
    {
        
    }

    public GetHeroProgress(_id: number): number {
        var config = this.m_user["progress_heroes"];
        var progress = config[_id] ? config[_id] : 0;
        return progress;
    }

    public GetHatProgress(_id: number): number {
        var config = this.m_user["progress_hats"];
        var progress = config[_id] ? config[_id] : 0;
        return progress;
    }

    public GetCbProgress(_id: number): number {
        var config = this.m_user["progress_dances"];
        var progress = config[_id] ? config[_id] : 0;
        return progress;
    }

    public HasMotor(_id: number): boolean {
        var data = this.GetUser(AccountUser.get_themes);
        for (var i = 0; i < data.length; i++) {
            var hd = data[i];
            if (_id == hd) {
                return true;
            }
        }
        return false;
    }
    //获取皮肤的进度
    public GetMotorProgress(_id: number): number {
        var config = this.m_user["progress_themes"];
        var progress = config[_id] ? config[_id] : 0;
        return progress;
    }

    public GetSeverConfig(_config: any) {
        this.m_configs = _config;
        this.GetSkinDic(this.m_configs);
        this.GetRewardDic();
        this.GetEntityDic();
        // this.GetAchievementData();
        let _globe=_config["global"];
        for (let index = 0; index < _globe.length; index++) {
            const element = _globe[index];
            if (element.key == "tilirec") {
                PlayerAccount.CurrentAccount.tilirec= Number(element.value);
                return;
            }
        }
    }

    UpdateSkinDic()
    {
        this.GetSkinDic(this.m_configs);
    }

    public GetGlobe(_key:string)
    {
        var globe = this.GetConfig(AccountConfig.global);
        for(var key in globe)
        {
            var obj = globe[key];
            var kkk = obj["key"];
            if(kkk == _key)
            {
                var value = obj["value"];
                return value;
            }
        }
        return null;
    }
}

export class PlayerAccount {
    constructor(_code: string, _nickname: string, _avatar: string, _gender: number, _country: string, _province: string, _city: string, _device: string, _shareid: string, _scence: string, _ver: string) {
        this.localTime = Laya.timer.currTimer;

        this.Code = _code;
        this.NickName = _nickname;
        this.Avatar = _avatar;
        this.Gender = _gender;
        this.Country = _country;
        this.Province = _province;
        this.City = _city;
        this.Device = _device;
        this.ShareId = _shareid;
        this.Scene = _scence;
        this.ver = _ver;
        this.IsTest = false;

        PlayerAccount.instance = this;
    }

    private static instance: PlayerAccount;

    public static get CurrentAccount() {
        if (PlayerAccount.instance == null) {
            console.log("生成本地测试账号...");
            return PlayerAccount.TestAccount;
        }
        return PlayerAccount.instance;
    }

    static get TestAccount() {
        var code = Laya.LocalStorage.getItem("localcode");
        if(!code)
        {
            var time = new Date().getTime().toString();
            var random = GameUtils.randRangeint(10000,99999).toString();
            code = "xj_" + time + random;
            Laya.LocalStorage.setItem("localcode",code);
            console.log(time,random);
            console.log("新用户",code);
        }
        else
        {
            console.log("老用户",code);
        }
        var curaccount = new PlayerAccount(code, null, null, null, null, null, null, null, null, null, null);
        curaccount.IsTest = true;
        return curaccount;
    }

    public Code: string;
    public NickName: string;
    public Avatar: string;
    public Gender: number;
    public Country: string;
    public Province: string;
    public City: string;
    public Device: string;
    public ShareId: string;
    public Scene: string;
    public ver: string;
    public static ServerTime: number;
    private localTime;
    static localcofigkey = "mconfig";

    public IsTest = false;

    public CurAccountData: AccountData;

    public tilirec:number;

    public nowConfig:any;

    public SetAccountData(data,completecb:Laya.Handler) {
        var token = data["token"];
        var configs = data["configs"];
        var app_setting = data["app_setting"];
        var user = data["user"];
        var user_base = data["user_base"];
        var user_sign = data["user_sign"];
        var user_achievement = data["user_achievement"];
        var user_lottery = data["user_lottery"];
        var user_land_task = data["user_land_task"];
        var user_video = data["user_video"];
        if (this.CurAccountData == null) {
            WxApi.recordAldEvent("开始获取config数据");
            this.CurAccountData = new AccountData(token, configs, app_setting, user, user_base, null, null, user_sign, user_achievement, user_lottery,user_land_task,user_video);
            this.CheckLocalConfig(data.table_version, (_config) => {
                this.CurAccountData.GetSeverConfig(_config);
                this.nowConfig = _config;
                if(completecb != null)
                {
                    completecb.runWith(data);
                }
            });
        }
        else {
            if (configs) {
                this.CurAccountData.m_configs = configs;
            }
            if (app_setting) {
                this.CurAccountData.m_app_setting = app_setting;
            }
            if (user) {
                this.CurAccountData.m_user = user;
            }
            if (user_base) {
                this.CurAccountData.m_user_base = user_base;
            }
            if (user_sign) {
                this.CurAccountData.m_sign = user_sign;
            }
            if (user_achievement) {
                this.CurAccountData.m_task = user_achievement;
            }
            if (user_lottery) {
                this.CurAccountData.lottery = user_lottery;
            }
            if(user_land_task)
            {
                this.CurAccountData.m_use_land_task = user_land_task;
            }
            if(user_video)
            {
                this.CurAccountData.m_user_video = user_video;
            }
        }
        DispatcherManager.dispatchEvent( UserInfoEvent.updatePlayerInfo );
    }

    private CheckLocalConfig(_ver: string, cb: Function) {
        var curconfig = Laya.LocalStorage.getJSON(PlayerAccount.localcofigkey);
        if (curconfig) {
            //Laya.LocalStorage.removeItem(PlayerAccount.localcofigkey);
            if (curconfig.ver == _ver) {
                console.log("sever配置是最新的...", _ver);
                WxApi.recordAldEvent("config接口获取成功");
                cb(curconfig);
            }
            else {
                NetworkManager.Instance.HttpPostRequest(PROTOCOLS.Config, null, Laya.Handler.create(this, (data) => {
                    data.configs.ver = _ver;
                    Laya.LocalStorage.setJSON(PlayerAccount.localcofigkey, data.configs);
                    console.log("sever配置更新完成...", _ver);
                    WxApi.recordAldEvent("config接口获取成功");
                    cb(data.configs);
                }), Laya.Handler.create(this, (data) => {
                    console.log("配置获取失败" + data);
                    WxApi.recordAldEvent("config接口获取失败");
                }));
            }
        }
        else {
            NetworkManager.Instance.HttpPostRequest(PROTOCOLS.Config, null, Laya.Handler.create(this, (data) => {
                data.configs.ver = _ver;
                Laya.LocalStorage.setJSON(PlayerAccount.localcofigkey, data.configs);
                console.log("sever保存配置完成...", _ver);
                WxApi.recordAldEvent("config接口获取成功");
                
                cb(data.configs);

            }), Laya.Handler.create(this, (data) => {
                console.log("配置获取失败" + data);
                WxApi.recordAldEvent("config接口获取失败");
            }));
        }
    }

    public get ServerTime(): number {
        let time = Laya.timer.currTimer;
        let stime = PlayerAccount.ServerTime + Math.ceil((time - this.localTime) / 1000);
        return stime;
    }
}