import { NetworkManager, PROTOCOLS } from "./NetworkManager";
import { HeroData, HatData } from "../Game/LevelData";
import { ConfigTest } from "../Game/ConfigTest";
import HttpRequest = Laya.HttpRequest;
import { RecommendWindow } from "../../Window/RecommendWindow";

export class ReData
{
    constructor(_obj:Object)
    {
        this.appid = _obj["appid"];
        this.banner = _obj["banner"];
        this.icon = _obj["icon"];
        this.image = _obj["image"];
        this.jump = _obj["jump"];
        this.next_appid = _obj["next_appid"];
        this.next_icon = _obj["next_icon"];
        this.next_path = _obj["next_path"];
        this.next_title = _obj["next_title"];
        this.path = _obj["path"];
        this.pos = _obj["pos"];
        this.sort = _obj["sort"];
        this.title = _obj["title"];
    }
    appid:string;
    banner:string;
    icon:string;
    image:string;
    jump:boolean;
    next_appid:string;
    next_icon:string;
    next_path:string;
    next_title:string;
    path:string;
    pos:string;
    sort:1;
    title:string;

    shownum:number;
}


export class ThingsEffect
{
    constructor(_data:any)
    {
        for(var key in _data)
        {
            var ccc = _data[key];
            if(ccc.type == "1")
            {
                ThingsEffect.rockettime = ccc.bufftime;
                ThingsEffect.rocketeffect = ccc.effect;
            }
            else if(ccc.type == "2")
            {
                ThingsEffect.Jstime = ccc.bufftime;
                ThingsEffect.JSEffect = ccc.effect;
            }
            else if(ccc.type == "7")
            {
                ThingsEffect.jumptime = ccc.bufftime == 0?1:ccc.bufftime;
                ThingsEffect.jumpeffect = ccc.effect;
            }
            else if(ccc.type == "3")
            {
                ThingsEffect.flytime = ccc.bufftime;
                ThingsEffect.flyeffect = ccc.effect;
            }
            else if(ccc.type == "4")
            {
                ThingsEffect.goldeffect = ccc.effect;
            }
        }
    }
    static Jstime = 0;
    static JSEffect = 0;
    static rockettime = 1;
    static rocketeffect = 1.5;
    static jumptime = 0.1;
    static jumpeffect = 0.3;
    static flytime = 4.5;
    static flyeffect = 2;
    static goldeffect = 1;
}

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

export enum AccountConfig
{
    hero,hat,wing,things,road,global,entity,sign,rewards,achievement,invite,mission,treasure_click
}

export enum AccountUser
{
    money,diamond,user_id,game_times,get_hats,get_heroes,get_dances,video_times,equip_hat,equip_dance,equip_hero,last_action_time,last_favorite_time,progress_dances,progress_hats,progress_heroes,revival,stage
}

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 class AccountData
{
    constructor(_token:string,_config:Object,_appSetting:Object,_user:Object,_userbase:Object,_useInvite:Object = null,_user_stage:Object = null,_user_sign,_user_achievement)
    {
        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.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 openid:string = "";
    private userId:string = "";

    public roadconfig:{[key:number]:any} = {};
    public m_RewardDic:Object = {};
    public m_EntityDic:{[key:number]:any} = {};
    public m_AchievementDic:Object = {};
    public m_heroDic:{[key:number]:HeroData} = {};
    public m_hatDic:{[key:number]:HatData} = {};
    public m_cbDic:{[key:number]:HatData} = {};

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

    public get sharecontent():string
    {
        return this.m_app_setting["sharecontent"];
    }

    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 cheat():boolean
    {
        return this.m_app_setting["cheat"] == "1";
    }
    public get checkscence():boolean
    {
        return this.m_app_setting["checkscence"] == 1;
    }
    public get trial():boolean
    {
        return this.m_app_setting["trial"] == "1";
    }

    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 HasHero(_id:number):boolean
    {
        var data = this.GetUser(AccountUser.get_heroes);
        for(var i = 0;i < data.length;i++)
        {
            var hd = data[i];
            if(_id == hd)
            {
                return true;
            }
        }
        return false;
    }
    public HasHat(_id:number):boolean
    {
        var data = this.GetUser(AccountUser.get_hats);
        for(var i = 0;i < data.length;i++)
        {
            var hd = data[i];
            if(_id.toString == hd)
            {
                return true;
            }
        }
        return false;
    }
    public HasDane(_id:number):boolean
    {
        var data = this.GetUser(AccountUser.get_dances);
        for(var i = 0;i < data.length;i++)
        {
            var hd = data[i];
            if(_id.toString == hd)
            {
                return true;
            }
        }
        return false;
    }

    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)
    {
        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 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;
    }

    public GetRoadConfig()
    {
        var configs = this.GetConfig(AccountConfig.road);
        for(var i = 0;i < configs.length;i++)
        {
            var config = configs[i];
            this.roadconfig[config.roadid] = config;
        }
    }

    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;
    }

    GetHeroDic():any
    {
        var config = this.GetConfig(AccountConfig.hero);
        //var config = ConfigTest.herodic;
        for(var i = 0;i < config.length;i++)
        {
            var data = config[i];
            var hero = new HeroData(Number(data.id));
            hero.curicon = data.icon;
            hero.name = data.name;
            hero.prefab = data.prefab;
            hero.quality = Number(data.quality);
            hero.require_num = Number(data.require_num);
            hero.require_type = Number(data.require_type);
            this.m_heroDic[data.id] = hero;
        }
        return this.m_heroDic;
    }

    GetHatDic():any
    {
        var config = this.GetConfig(AccountConfig.hat);
        //var config = ConfigTest.hat;
        for(var i = 0;i < config.length;i++)
        {
            var data = config[i];
            var hat = new HatData(Number(data.id));
            hat.icon = data.icon;
            hat.name = data.name;
            hat.prefab = data.prefab;
            hat.quality = Number(data.quality);
            hat.require_num = Number(data.require_num);
            hat.require_type = Number(data.require_type);
            this.m_hatDic[data.id] = hat;
        }
        return this.m_hatDic;
    }

    GetCbDic():any
    {
        var config = this.GetConfig(AccountConfig.wing);
        //var config = ConfigTest.cb;
        for(var i = 0;i < config.length;i++)
        {
            var data = config[i];
            var hat = new HatData(Number(data.id));
            hat.icon = data.icon;
            hat.name = data.name;
            hat.prefab = data.prefab;
            hat.quality = Number(data.quality);
            hat.require_num = Number(data.require_num) ;
            hat.require_type = Number(data.require_type) ;
            this.m_cbDic[data.id] = hat;
        }
        return this.m_cbDic;
    }
    

    public GetSeverConfig()
    {
        NetworkManager.Instance.HttpPostRequest(PROTOCOLS.Config,null,Laya.Handler.create(this,(data)=>
        {
            this.m_configs = data["configs"];
            new ThingsEffect(this.m_configs["things"]);
            this.GetHeroDic();
            this.GetHatDic();
            this.GetCbDic();
            this.GetRewardDic();
            this.GetEntityDic();
            this.GetAchievementData();
            this.InitData();
        }),null);
    }

    bannerdata:ReData[] = [];
    redata:ReData[] = [];

    InitData()
    {
        var url = "https://jiujiu.99huyu.cn/m/run/config.json";
        var args = null;

        let httpRequest = new HttpRequest();
        httpRequest.once(Laya.Event.COMPLETE, this, this.onHttpRequestComplete);
        httpRequest.once(Laya.Event.ERROR, this, this.onHttpRequestError);
        httpRequest.send(url, args, "get", "json");
    }

    onHttpRequestComplete(_data:any):void 
    {
        var data = _data.data.mores;
        for(var key in data.banner)
        {
            var kk = data.banner[key];
            var nd = new ReData(kk);
            this.bannerdata.push(nd);
            this.bannerdata.sort(RecommendWindow.ListSort);
        }
        for(var key in data.remen_game)
        {
            var kk = data.remen_game[key];
            var nd = new ReData(kk);
            this.redata.push(nd);
            this.redata.sort(RecommendWindow.ListSort);
        }
    }

    onHttpRequestError(errorcb:Laya.Handler,httpRequest:HttpRequest)
    {
        console.log("Error! Http request error..." + httpRequest.data);
    }
}

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("生成本地测试账号...");
            PlayerAccount.TestAccount;
        }
        return PlayerAccount.instance;
    }

    static get TestAccount()
    {
        var curaccount = new PlayerAccount("123456","我是谁，我在那？","123",1,"中国","上海","上海","iphone6s","123","123","123");
        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;

    public IsTest = false;

    public CurAccountData:AccountData;

    public SetAccountData(data)
    {
        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"];
        if(this.CurAccountData == null)
        {
            this.CurAccountData = new AccountData(token,configs,app_setting,user,user_base,null,null,user_sign,user_achievement);
            this.CurAccountData.GetSeverConfig();
        }
        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;
            }
        }

    }

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