%%-----------------------------------------------------------------------------
%% module  :       lib_vie_rank
%% @author  :      zmh
%% Created :       20-10-26
%%-----------------------------------------------------------------------------
-module(lib_vie_rank).

-include("errcode.hrl").
-include("common.hrl").
-include("server.hrl").
-include("def_goods.hrl").
-include("def_event.hrl").
-include("rec_event.hrl").
-include("figure.hrl").
-include("vie_rank.hrl").
-include("def_module.hrl").
-include("custom_act.hrl").

-export ([
    get_vie_ranks/3,
    update_role_vie/2,
    update_role_vie/3,
    load_vie_ranks/0,
    handle_event/2,
    get_delay_show_act/2,
    delay_show_acts/1
]).

-compile(export_all).


%%个人榜单
get_vie_ranks(BaseType,SubType,Status)->
    #player_status{
        id=RoleID
    }=Status,
    ZoneID = czone_api:env_get_zone_id(),
    CustomActData = lib_custom_act_data:custom_act_data(?CUSTOM_ACT_TYPE_VIE_RANK, SubType),
    #custom_act_data{act_data = ActData} = CustomActData,
    case ActData of
        [#custom_vie{score=MScore}|_]->
            skip;
        _->
            MScore = 0
    end,
    clusters_node:apply_cast(mod_vie_rank_center,get_vie_role_ranks,[node(),ZoneID,RoleID,MScore,BaseType,SubType]).


%%道具获得
update_role_vie(ChangeList,Status)->
    update_role_vie(?VIE_ITEM,ChangeList,Status).
update_role_vie(Way,ChangeList,Status)->
    OpenSubList = lib_custom_act_util:get_open_subtype_list(?CUSTOM_ACT_TYPE_VIE_RANK),
    update_role_vie(Way,OpenSubList,ChangeList,Status).

update_role_vie(_Way,[],_,Status)->
    Status;
update_role_vie(_Way,_,[],Status)->
    Status;
update_role_vie(Way,[H|T],ChangeList,Status)->
    #act_info{key={Type,SubType},etime=ETime}=H,
    CustomActData = lib_custom_act_data:custom_act_data(Type, SubType),
    #custom_act_data{act_data = ActData} = CustomActData,
    case lib_custom_act_util:get_act_cfg_info(Type,SubType) of
        #custom_act_cfg{condition=Conditions}->
            case ActData of
                [#custom_vie{score=OScore}|_]->
                    skip;
                _->
                    OScore = 0
            end,
            %%查找检测类
            case lists:keyfind(type_id,1,Conditions) of
                {_,VieKey}->
                    skip;
                _->
                    VieKey = 0
            end,
            %%查找最低上榜积分
            MinS = data_vie_rank:get_min_score(VieKey),
            %%查找延迟展示时间
            case lists:keyfind(show_time,1,Conditions) of
                {_,DelayShow}->
                    skip;
                _->
                    DelayShow = 0
            end,
            VieValue =  data_vie_rank:get_vie_type_value(VieKey),
            case VieValue of
                ?VIE_RECHARGE when Way =:= ?VIE_RECHARGE->
                    Item = ?TYPE_GOLD;
                ?VIE_CONSUME when  Way =:= ?VIE_CONSUME ->
                    Item = ?TYPE_GOLD;
                ?VIE_ITEM when Way =:= ?VIE_ITEM -> %%道具获得类
                    case lists:keyfind(item,1,Conditions) of
                        {_,Item}->
                            skip;
                        _->
                            Item = 0
                    end;
                _->
                    Item = 0
            end,
            AddScore = case Item>0 of
                true->
                    calc_total(Item,ChangeList,0);
                _->
                    0
            end,
            #player_status{
                id = RoleID,
                figure = #figure{name=Name,vip=Vip,sup_vip=SVip}
            }=Status,
            SNum = config:get_server_num(),
            SerID = config:get_server_id(),
            Now = utime:unixtime(),
            NScore = AddScore+OScore,
            VieRole = #vie_rank{
                id = RoleID,
                name = Name,
                server_num = SNum,
                server_id = SerID,
                act = SubType,
                vip = Vip,
                svip = SVip,
                score = NScore,
                rtime = Now,
                dtime = ETime+DelayShow
            },
            NewActData = [#custom_vie{score=NScore}],
            AddScore>0 andalso lib_custom_act_data:save_custom_data(RoleID, CustomActData#custom_act_data{time=Now,act_data = NewActData}),
            AddScore>0 andalso lib_log_api:log_vie_score(SubType,RoleID,Name,AddScore,NScore),
            case NScore>=MinS of
                true when AddScore>0->
                    ZoneID = czone_api:env_get_zone_id(),
                    Args = [node(),ZoneID,SubType,VieRole],
                    clusters_node:apply_cast(mod_vie_rank_center,update_role_vie,Args);
                _->
                    ok
            end;
        _->
            ok
    end,
    update_role_vie(Way,T,ChangeList,Status).


get_rank_type(SubType)->
   Type = ?CUSTOM_ACT_TYPE_VIE_RANK,
   case lib_custom_act_util:get_act_cfg_info(Type,SubType) of
        #custom_act_cfg{condition=Conditions}->
            case lists:keyfind(type_id,1,Conditions) of
                {_,VieKey}->
                    skip;
                _->
                    VieKey = 0
            end;
        _->
            VieKey = 0
    end,
    VieKey.



%% 消费活动实时更新
handle_event(Status, #event_callback{type_id = ?EVENT_MONEY_CONSUME, data = Data})  ->
    #callback_money_cost{money_type = MoneyType, cost = Cost}=Data,
    MoneyType =:= ?TYPE_GOLD andalso update_role_vie(?VIE_CONSUME,[{?TYPE_GOLD,Cost}],Status),
    {ok, Status};
%% 处理玩家充值成功之后需要通知客户端更新的定制活动信息
handle_event(Status, #event_callback{type_id = ?EVENT_RECHARGE, data = Data})  ->
    #callback_recharge_data{gold = Gold}=Data,
    Gold>0 andalso update_role_vie(?VIE_RECHARGE,[{?TYPE_GOLD,Gold}],Status),
    {ok,Status};
handle_event(Status, _) ->
    {ok, Status}.



calc_total(_Item,[],Total)->
    Total;
calc_total(Item,[H|T],Total)->
    case H of
        {_,Item,Add}->
            calc_total(Item,T,Add+Total);
        {Item,_,Add}->
            calc_total(Item,T,Add+Total);
        {Item,Add}->
            calc_total(Item,T,Add+Total);
        _->
            calc_total(Item,T,Total)
    end.

%%加载数据
load_vie_ranks()->
    Now = utime:unixtime(),
    SQL = io_lib:format(?SQL_VIE_RANK_GET, [Now]),
    All = db:get_all(SQL),
    ViwRanks = init_vie_rank(All, []),
    ViwRanks.

init_vie_rank([],ViwRanks)->
    ViwRanks;
init_vie_rank([[Act,Rid,Name,ServerId,ServerNum,Vip,SVip,Score,RTime,DTime]|T],ViwRanks)->
    VieRole = #vie_rank{
        id = Rid,
        name = Name,
        server_num = ServerNum,
        server_id = ServerId,
        act = Act,
        vip = Vip,
        svip= SVip,
        score = Score,
        rtime = RTime,
        dtime = DTime
    },
    init_vie_rank(T,[VieRole|ViwRanks]).


%%有活动延迟展示要求
get_delay_show_act(_Status, ActList)->
    DelayActs = show_award_act_list(),
    ActList++DelayActs.

delay_show_acts(ActList)->
    delay_show_acts(ActList,utime:unixtime(),[]).
delay_show_acts([],_Now,ActList)->
    ActList;
delay_show_acts([H|T],Now,ActList)->
    #act_info{key={Type,SubType},etime=ETime}=H,
    case lists:member(Type,[?CUSTOM_ACT_TYPE_VIE_RANK]) of
        true->
            case lib_custom_act_util:get_act_cfg_info(Type,SubType) of
                #custom_act_cfg{condition=Condition}->
                    case lists:keyfind(show_time,1,Condition) of
                        {_,DShow}->
                            DTime = ETime+DShow,
                            case Now<DTime of
                                true->
                                    delay_show_acts(T,Now,ActList);
                                _->
                                    delay_show_acts(T,Now,[H|ActList])
                            end;
                        _->
                            delay_show_acts(T,Now,[H|ActList])
                    end;
                _->
                    delay_show_acts(T,Now,[H|ActList])
            end;
        _->
            delay_show_acts(T,Now,[H|ActList])
    end.



%% @doc 活动结束了，也需要展示出来的活动列表。
show_award_act_list() ->
    TypeList = [?CUSTOM_ACT_TYPE_VIE_RANK],
    Now = utime:unixtime(),
    show_award_act_list(Now,TypeList, []).

show_award_act_list(_Now,[], ActInfoList) ->
    ActInfoList;
show_award_act_list(Now,[Type | T], ActInfoList) ->
    Fun = fun(SubType, ActList) ->
        case lib_custom_act_util:get_act_cfg_info(Type,SubType) of
            #custom_act_cfg{start_time=STime,end_time=ETime,condition=Condition} when Now>ETime->
                case lists:keyfind(show_time,1,Condition) of
                    {_,DShow}->
                        DTime = ETime+DShow,
                        case Now<DTime of
                            true->
                                ActInfo = #act_info{key = {Type, SubType},stime=STime,etime=ETime},
                                [ActInfo | ActList];
                            _->
                                ActList
                        end;
                    _->
                        ActList
                end;
            _->
                ActList
        end
    end,
    SubTypeList = lib_custom_act_util:get_subtype_list(Type),
    NewActInfoList = lists:foldl(Fun, ActInfoList, SubTypeList),
    show_award_act_list(Now,T, NewActInfoList).


%%获取最大上榜人数
get_max_rank(SubType)->
    MaxRank = data_vie_rank:get_max_rank(SubType),
    MaxRank.