%%-----------------------------------------------------------------------------
%% module  :       mod_glamour_focus
%% @author  :      zmh
%% Created :       20200213
%% description:    跑马投注
%%-----------------------------------------------------------------------------
-module(mod_glamour_focus).

-include("errcode.hrl").
-include("common.hrl").
-include("server.hrl").
-include("goods.hrl").
-include("figure.hrl").
-include("def_module.hrl").
-include("def_goods.hrl").
-include("predefine.hrl").
-include("glamour.hrl").

-export ([init/1, handle_call/3, handle_cast/2, handle_info/2, code_change/3, terminate/2]).
-export ([
    start_link/0,
    enter_account/2,
    enter_run/0,
    init_focus_runer/1,
    init_focus_runer/2,
    get_focus_data/1,
    use_item/3,
    get_top_focuser_show/1,
    get_logs/1,
    back_use_item/6,
    guess_runer/4,
    get_focus_state/1,
    get_focus_view/1,
    sync_round_data/1,
    get_show_focusers/1,
    enter_account/0,
    enter_glamour_show/1,
    get_role_focuster/1,
    buy_items/3
    ,update_ta_data/1
    ,update_role_ta_data/2
    ,ta_update_data_on_player/2
    ,clean_focusers/0
]).


%%通知结算
enter_account(Round,NewRuners)->
    gen_server:cast(?MODULE,{enter_account,Round,NewRuners}).

init_focus_runer(Runers)->
    gen_server:cast(?MODULE,{init_focus_runer,Runers}).

init_focus_runer(Round,Runers)->
    gen_server:cast(?MODULE,{init_focus_runer,Round,Runers}).

%%吃瓜群众拿自己数据
get_focus_data(Focuser)->
    gen_server:cast(?MODULE,{get_focus_data,Focuser}).

%%使用气氛道具
use_item(RunID,Item,Focuser)->
    gen_server:cast(?MODULE,{use_item,RunID,Item,Focuser}).

%%使用回调
back_use_item(RunID,RName,Item,FocuserID,Res,IsFree)->
    gen_server:cast(?MODULE,{back_use_item,RunID,RName,Item,FocuserID,Res,IsFree}).

get_top_focuser_show(RoleID)->
    gen_server:cast(?MODULE,{get_top_focuser_show,RoleID}).

get_logs(RoleID)->
    gen_server:cast(?MODULE,{get_logs,RoleID}).

guess_runer(RunID,Add,IsLikeT,Focuser)->
    gen_server:cast(?MODULE,{guess_runer,RunID,Add,IsLikeT,Focuser}).

get_focus_state(RoleID)->
    gen_server:cast(?MODULE,{get_focus_state,RoleID}).

get_focus_view(Focuser)->
    gen_server:cast(?MODULE,{get_focus_view,Focuser}).

enter_glamour_show(Focuser)->
    gen_server:cast(?MODULE,{enter_glamour_show,Focuser}).

sync_round_data(Round)->
    gen_server:cast(?MODULE,{sync_round_data,Round}).

get_show_focusers(RoleID)->
    gen_server:cast(?MODULE,{get_show_focusers,RoleID}).

enter_account()->
    gen_server:cast(?MODULE,{enter_account}).

clean_focusers() ->
    gen_server:cast(?MODULE, {clean_focusers}).

enter_run()->
    gen_server:cast(?MODULE,{enter_run}).

buy_items(RoleID,Item,Focuser)->
    gen_server:cast(?MODULE,{buy_items,RoleID,Item,Focuser}).

get_role_focuster(RoleID)->
    gen_server:call(?MODULE,{get_role_focuster,RoleID}).

%% 分批上报TA数据
update_ta_data(UpDataMap) ->
    F = fun(_GuildId, MemList) ->
        gen_server:cast(?MODULE, {update_ta_data, MemList}),
        timer:sleep(2*100)
        end,
    spawn(fun() ->
        maps:map(F, UpDataMap),
        %% 延迟10s清理数据
        lib_activitycalen_api:activity_end_clean_record(?MOD_GUILD, 10),
        %% 最后再清理跑马数据 TODO:有没有更好的方案？
        gen_server:cast(?MODULE, {clean_focusers})
    end),
    ok.

update_role_ta_data(RoleID, LastTime) ->
    gen_server:cast(?MODULE, {update_role_ta_data, RoleID, LastTime}).

%% API
start_link() ->
    gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).

init([]) ->
   process_flag(trap_exit, true),
   save_all_focuser(maps:new()),
   save_all_logs([]),
   save_show_ranks([]),
   {ok,#glamour_focus_mgr{runers=maps:new()}}.

handle_call(Msg, From, State) ->
    case catch do_handle_call(Msg, From, State) of
        {'EXIT', Error} ->
            ?ERR("handle_call error: ~p~nMsg=~p~n", [Error, Msg]),
            {reply, error, State};
        Return  ->
            Return
    end.

handle_cast(Msg, State) ->
    case catch do_handle_cast(Msg, State) of
        {'EXIT', Error} ->
            ?ERR("handle_cast error: ~p~nMsg=~p~n", [Error, Msg]),
            {noreply, State};
        Return  ->
            Return
    end.

handle_info(Info, State) ->
    case catch do_handle_info(Info, State) of
        {'EXIT', Error} ->
            ?ERR("handle_info error: ~p~nInfo=~p~n", [Error, Info]),
            {noreply, State};
        Return  ->
            Return
    end.

code_change(_OldVsn, State, _Extra) ->
    {ok, State}.

terminate(_Reason, _State) ->
    ok.

do_handle_call({get_role_focuster,RoleID},_,State)->
    case get_focuser(RoleID) of
        #glamour_focuser{items=Items}->
            skip;
        _->
            Items = none
    end,
    {reply,{ok,Items},State};

do_handle_call(_Msg, _From, State) ->
    {reply, ok, State}.

%% 上报数据
do_handle_cast({update_ta_data, MemList}, State)->
    FocuserMap = get_all_focuser(),
    F = fun(MemInfo) ->
        case MemInfo of
            {RoleId, LastTime, IsHosting} ->
                case maps:get(RoleId, FocuserMap, []) of
                    #glamour_focuser{
                        use_free_items = FreeTimes, use_buy_items = PayTimes,
                        focus_times = LikeTimes
                    } ->
                        lib_player:apply_cast(RoleId, ?APPLY_CAST_STATUS,
                            ?MODULE, ta_update_data_on_player,
                            [[IsHosting, LikeTimes, FreeTimes, PayTimes, LastTime]]
                        );
                    _ ->
                        lib_player:apply_cast(RoleId, ?APPLY_CAST_STATUS,
                            ?MODULE, ta_update_data_on_player,
                            [[IsHosting, 0, 0, 0, LastTime]]
                        )
                end;
            _ ->
                ignore
        end end,
    lists:map(F, MemList),
    {noreply, State};

do_handle_cast({update_role_ta_data, RoleId, LastTime}, State) ->
    FocuserMap = get_all_focuser(),
    IsHosting  = offline_hosting_api:is_offline_hosting(RoleId, ?MOD_GUILD),
    case maps:get(RoleId, FocuserMap, []) of
        #glamour_focuser{
            use_free_items = FreeTimes, use_buy_items = PayTimes,
            focus_times = LikeTimes
        } ->
            lib_player:apply_cast(RoleId, ?APPLY_CAST_STATUS,
                ?MODULE, ta_update_data_on_player,
                [[IsHosting, LikeTimes, FreeTimes, PayTimes, LastTime]]
            );
        _ ->
            lib_player:apply_cast(RoleId, ?APPLY_CAST_STATUS,
                ?MODULE, ta_update_data_on_player,
                [[IsHosting, 0, 0, 0, LastTime]]
            )
    end,
    {noreply, State};

%%首次初始化前两轮参赛
do_handle_cast({init_focus_runer,Runers},State)->
    RunerMap = maps:from_list(Runers),
    NState = State#glamour_focus_mgr{runers=RunerMap},
    save_all_focuser(maps:new()),
    save_all_logs([]),
    save_show_ranks([]),
    NRuners = merge_runers(Runers,[]),
    init_runer_focuser(NRuners),
    {noreply,NState};

do_handle_cast({init_focus_runer,Round,Runers},State)->
    #glamour_focus_mgr{runers=RunerMap}=State,
    NRunerMap = maps:put(Round,Runers,RunerMap),
    NState = State#glamour_focus_mgr{runers=NRunerMap},
    {noreply,NState};

do_handle_cast({sync_round_data,Round},State)->
    {noreply,State#glamour_focus_mgr{round=Round}};

do_handle_cast({enter_account,Round,NewRuners},State)->
    #glamour_focus_mgr{
        runers = RunerMap
    }=State,
    FocuserMap = get_all_focuser(),
    Focusers = maps:to_list(FocuserMap),
    [NewFocusers,TemRanks] =  account_all_focuser(Round,Focusers,NewRuners,[],[]),
    sort_all_focus(TemRanks),
    NewFocuserMap = maps:from_list(NewFocusers),
    Ranks = get_all_ranks(),
    Bin = pack_runer_data(Ranks,3),
    lib_server_send:send_to_all(Bin),
    save_all_focuser(NewFocuserMap),
    NRunerMap = maps:put(Round,NewRuners,RunerMap),
    case lists:keyfind(1,#glamour_runer.rank,NewRuners) of
        #glamour_runer{id=Rid,figure=#figure{name=Name}}->
            lib_chat:send_TV({all}, ?MOD_GLAMOUR, 3, [Round,Name,Rid]);
        _->
            ok
    end,
    {noreply,State#glamour_focus_mgr{runers=NRunerMap}};

do_handle_cast({enter_run},State)->
    NState = auto_focus(State),
    {noreply,NState};

do_handle_cast({get_focus_data,Focuser},State)->
    NFocuser = get_focuser(Focuser),
    #glamour_focuser{
        rid = RoleID,
        money = Money,
        items = Items0,
        buys  = Buys
    }=NFocuser,
    Items = util:combine_list(Items0++Buys),
    {ok,Bin} = pt_142:write(14205,[Money,Items]),
    lib_server_send:send_to_uid(RoleID,Bin),
    {noreply,State};

do_handle_cast({get_top_focuser_show,RoleID},State)->
    Ranks = get_all_ranks(),
    Bin   = pack_runer_data(Ranks,3),
    lib_server_send:send_to_uid(RoleID,Bin),
    {noreply,State};

%%气氛道具使用
do_handle_cast({use_item,RunID,Item,InitFocuser},State)->
    NFocuser = get_focuser(InitFocuser),
    #glamour_focuser{rid=RoleID,items=Items,buys=Buys}=NFocuser,
    case lists:keyfind(Item,1,Items) of
        {_,V} when V>0->
            mod_glamour_mgr:use_item(RunID,Item,RoleID,true);
        _->
            case lists:keyfind(Item,1,Buys) of
                {_,V} when V>0->
                    mod_glamour_mgr:use_item(RunID,Item,RoleID,false);
                _->
                    {ok,Bin} = pt_142:write(14209,[0,0,?ERRCODE(err142_no_enough_item),0]),
                    lib_server_send:send_to_uid(RoleID,Bin)
            end
    end,
    {noreply,State};

%%使用回调
do_handle_cast({back_use_item,RunID,RName,Item,FocuserID,Res,IsFree},State)->
    FocuserMap = get_all_focuser(),
    Focuser = maps:get(FocuserID,FocuserMap,[]),
    case Focuser of
        #glamour_focuser{items=Items,buys=Buys,
            use_free_items = UseFreeItems, use_buy_items = UseBuyItems,
            figure=#figure{name=Name}}->
            {NItems,NBuys,NFreeItems,NBuyItems} = case IsFree of
                true->
                    NItems0 = case lists:keyfind(Item,1,Items) of
                        {_,V}->
                            lists:keyreplace(Item,1,Items,{Item,max(V-1,0)});
                        _->
                            Items
                    end,
                    {NItems0,Buys, UseFreeItems+1, UseBuyItems};
                _->
                    NBuys0 = case lists:keyfind(Item,1,Buys) of
                        {_,V}->
                            lists:keyreplace(Item,1,Buys,{Item,max(V-1,0)});
                        _->
                            Buys
                    end,
                    {Items,NBuys0,UseFreeItems,UseBuyItems+1}
            end,
            NFocuser = Focuser#glamour_focuser{items=NItems,buys=NBuys,
                use_free_items = NFreeItems, use_buy_items = NBuyItems},
            NFocuserMap = maps:put(FocuserID,NFocuser,FocuserMap),
            {ok,Bin} = pt_142:write(14209,[RunID,Item,?SUCCESS,Res]),
            lib_server_send:send_to_uid(FocuserID,Bin),
            IsHit = case Res == 2 of
                true->
                    1;
                _->
                    0
            end,
            Free = case IsFree of
                true->
                    1;
                _->
                    0
            end,
            lib_log_api:log_glamour_item(FocuserID,Name,RunID,RName,Item,IsHit,Free),
            save_all_focuser(NFocuserMap);
        _->
            skip
    end,
    {noreply,State};


do_handle_cast({get_logs,RoleID},State)->
    Logs = get_all_logs(),
    LogList = [{OpTy,Rid,Vip,SubVip,Name,Aim,Value,Time}||#glamour_log{opty=OpTy,rid=Rid,name=Name,aim=Aim,value=Value,time=Time,vip=Vip,sub_vip=SubVip}<-Logs],

    {ok,Bin} = pt_142:write(14213,[LogList]),
    lib_server_send:send_to_uid(RoleID,Bin),
    {noreply,State};

do_handle_cast({get_focus_view,Focuser},State)->
    #glamour_focus_mgr{
        round = Round,
        runers = RunerMap
    } = State,
    NFocuser = get_focuser(Focuser),
    #glamour_focuser{
        rid = RoleID,
        focus = Focus
    }=NFocuser,
    Runers = maps:get(Round,RunerMap,[]),
    Bin = pack_bet_view(Runers,Focus,[]),
    lib_server_send:send_to_uid(RoleID,Bin),

    {noreply,State};


do_handle_cast({enter_glamour_show,Focuser},State)->

    #glamour_focuser{
        rid = RoleID,
        figure=#figure{vip=Vip,name=Name,sup_vip=SubVip}
    }=Focuser,

    GlamourLog = #glamour_log{
        opty = 0,
        rid  = RoleID,
        vip  = Vip,
        sub_vip=SubVip,
        name = Name,
        aim = Name,
        value = 0,
        time = utime:unixtime()
    },
    update_log(GlamourLog),

    {noreply,State};

do_handle_cast({guess_runer,RunID,Add,IsLikeT,Focuser},State)->
    #glamour_focus_mgr{
        round = Round,
        runers = RunerMap
    }=State,
    NFocuser0 = get_focuser(Focuser),
    #glamour_focuser{
        rid=RoleID,
        money=Money,
        focus=Focus,
        figure=#figure{name=Name,vip=Vip,sup_vip=SubVip},
        focus_times = FocusTimes
    }=NFocuser0,
    Runers   = maps:get(Round,RunerMap,[]),
    Runer    = lists:keyfind(RunID,#glamour_runer.id,Runers),
    CheckList = [
        {check_bet_time,IsLikeT},
        {check_runer_exit,Runer},
        {check_money_enough,Money,Add}
    ],
    case util:check_lists(lib_role_glamour,CheckList) of
        true->
            NFocus = case lists:keyfind(RunID,1,Focus) of
                {_,V}->
                    lists:keyreplace(RunID,1,Focus,{RunID,V+Add});
                _->
                    lists:keystore(RunID,1,Focus,{RunID,Add})
            end,
            NMoney = case length(Focus)=<0 of
                true-> %%首次不扣
                    Money;
                _->
                    max(0,Money-Add)
            end,
            NFocuser = NFocuser0#glamour_focuser{money=NMoney,focus=NFocus,focus_times = FocusTimes+1},
            #glamour_runer{figure=#figure{name=RName},trust=Trust}=Runer,
            NRuner = Runer#glamour_runer{trust=Trust+Add},
            NRuners = lists:keyreplace(RunID,#glamour_runer.id,Runers,NRuner),
            NRunerMap = maps:put(Round,NRuners,RunerMap),
            GlamourLog = #glamour_log{
                opty = 1,
                rid  = RoleID,
                vip  = Vip,
                sub_vip=SubVip,
                name = Name,
                aim = RName,
                value = Add,
                time = utime:unixtime()
            },
            update_log(GlamourLog),
            mod_glamour_mgr:sync_runer_trust(RunID,Trust+Add),
            update_role_focuser(NFocuser),
            Bin = pack_focus_data(NRuners),
            Scene = lib_guild_api:get_guild_scene(),
            lib_server_send:send_to_all(scene,Scene,Bin),
            {ok,BinM} = pt_142:write(14210,[?SUCCESS]),
            lib_server_send:send_to_uid(RoleID,BinM),
            %% 投注成功，完成战团任务
            lib_role_legion:trigger_task(RoleID, ?MOD_GLAMOUR, 0),
            contract_task_api:glamour_guess_trigger(RoleID, 1),
            NState = State#glamour_focus_mgr{runers=NRunerMap};
        {false,Err}->
            {ok,Bin} = pt_142:write(14210,[Err]),
            lib_server_send:send_to_uid(RoleID,Bin),
            NState = State
    end,
    {noreply,NState};

do_handle_cast({get_focus_state,RoleID},State)->
    #glamour_focus_mgr{
        round = Round,
        runers = RunerMap
    } = State,
    Runers = maps:get(Round,RunerMap,[]),
    Bin = pack_focus_data(Runers),
    lib_server_send:send_to_uid(RoleID,Bin),
    {noreply,State};

do_handle_cast({get_show_focusers,RoleID},State)->
    FocuserMap = get_all_focuser(),
    AllN = maps:size(FocuserMap),
    ShowFocusers0 = get_all_ranks(),
    ShowFocusers = [{Rank,Figure,Money}||#glamour_focuser{rank=Rank,figure=Figure,total=Money}<-ShowFocusers0],
    {ok,Bin} = pt_142:write(14208,[AllN,ShowFocusers]),
    lib_server_send:send_to_uid(RoleID,Bin),
    {noreply,State};

do_handle_cast({enter_account},_State)->
    FocuserMap = get_all_focuser(),
	%% 先不清理数据，TA数据上报需要记录
    % save_all_focuser(maps:new()),
    save_all_logs([]),
    save_show_ranks([]),

    Focusers  = maps:values(FocuserMap),
    Focusers0 = compare_focuser_money(Focusers),
    NFocusers = compare_data(Focusers0,1,max,[]),

    spawn(fun()-> account_mail_award(NFocusers) end),

    {noreply,#glamour_focus_mgr{runers=maps:new()}};

do_handle_cast({clean_focusers}, State)->
    save_all_focuser(maps:new()),
    {noreply, State};

do_handle_cast({buy_items,RoleID,Item,Focuser},State)->
    Focuser0 = get_focuser(Focuser),
    #glamour_focuser{
        money = Money,
        buys = Buys,
        items = Items
    }=Focuser0,
    NBuys = case lists:keyfind(Item,1,Buys) of
        {_,V}->
            lists:keystore(Item,1,Buys,{Item,V+1});
        _->
            lists:keystore(Item,1,Buys,{Item,1})
    end,
    NFocuser = Focuser0#glamour_focuser{buys=NBuys},
    update_role_focuser(NFocuser),
    Has   = util:combine_list(Items++NBuys),
    {ok,Bin} = pt_142:write(14205,[Money,Has]),
    lib_server_send:send_to_uid(RoleID,Bin),
    {noreply, State};

do_handle_cast(_Msg, State) ->
    {noreply, State}.


do_handle_info(_Msg, State) ->
    {noreply, State}.


get_focuser(RoleID) when is_integer(RoleID)->
    FocuserMap = get_all_focuser(),
    maps:get(RoleID,FocuserMap,[]);
get_focuser(InitFocuser)->
    #glamour_focuser{
        rid=RoleID
    }=InitFocuser,
    Focuser = get_focuser(RoleID),
    case is_record(Focuser,glamour_focuser) of
        true->
            Focuser;
        _->
            FocuserMap = get_all_focuser(),
            NFocuserMap = maps:put(RoleID,InitFocuser,FocuserMap),
            save_all_focuser(NFocuserMap),
            update_all_ranks(InitFocuser),
            InitFocuser
    end.

update_role_focuser(Focuser)->
    #glamour_focuser{rid=RoleID}=Focuser,
    FocuserMap = get_all_focuser(),
    NFocuserMap = maps:put(RoleID,Focuser,FocuserMap),
    save_all_focuser(NFocuserMap).

get_all_focuser()->
    case get(?GLAMOUR_FOCUSERS) of
        undefined->
            FocuserMap = maps:new();
        FocuserMap->
            skip
    end,
    FocuserMap.

save_all_focuser(FocuserMap)->
    put(?GLAMOUR_FOCUSERS,FocuserMap).

get_all_logs()->
    case get(?GLAMOUR_LOGS) of
        undefined->
            [];
        Logs ->
            Logs
    end.

save_all_logs(Logs)->
    put(?GLAMOUR_LOGS,Logs).


get_all_ranks()->
    case get(?GLAMOUR_RANKS) of
        undefined->
            [];
        Ranks->
            Ranks
    end.

save_show_ranks(Ranks)->
    put(?GLAMOUR_RANKS,Ranks).

%%日志更新
update_log(GlamourLog)->
    #glamour_log{
        opty=OpTy,
        rid = Rid,
        vip=Vip,
        sub_vip=SubVip,
        name=Name,
        aim=Aim,
        value=Value,
        time=Time
    }=GlamourLog,
    {ok,Bin} = pt_142:write(14206,[OpTy,Rid,Vip,SubVip,Name,Aim,Value,Time]),
    lib_server_send:send_to_all(Bin),
    Logs = get_all_logs(),
    NLogs0 = [GlamourLog|Logs],
    NLogs1 = lists:keysort(#glamour_log.time,NLogs0),
    NLogs2 = lists:reverse(NLogs1),
    Max = data_glamour:get(log_num),
    {NLogs,_} = ulists:split(Max,NLogs2),
    save_all_logs(NLogs).

pack_runer_data(Runers,Limit)->
    pack_runer_data(Runers,Limit,[]).
pack_runer_data([],_,Datas)->
    {ok,Bin} = pt_142:write(14203,[Datas]),
    Bin;
pack_runer_data([H|T],Limit,Datas)->
    #glamour_focuser{
        rank = Rank,
        figure=Figure,
        total = AllM
    }=H,
    case Rank=<Limit of
        true->
            pack_runer_data(T,Limit,[{Figure,AllM}|Datas]);
        _->
            pack_runer_data(T,Limit,Datas)
    end.

pack_focus_data(Runers)->
    pack_focus_data(Runers,[]).
pack_focus_data([],Datas)->
    {ok,Bin} = pt_142:write(14202,[Datas]),
    Bin;
pack_focus_data([H|T],Datas)->
    #glamour_runer{
        id = Rid,
        trust = Trust
    }=H,
    pack_focus_data(T,[{Rid,Trust}|Datas]).

account_all_focuser(_Round,[],_Runers,Focusers,TemRanks)->
    [Focusers,TemRanks];
account_all_focuser(Round,[{K,H}|T],Runers,Focusers,TemRanks)->
    NewH = account_focuser(Round,H,Runers),
    account_all_focuser(Round,T,Runers,[{K,NewH}|Focusers],[NewH|TemRanks]).


account_focuser(Round,Focuser,Runers)->
    #glamour_focuser{
        rid=RoleID,
        focus=Focus,
        money=Money,
        figure=#figure{name=Name},
        buys = Buys,
        total=_OTotal
    }=Focuser,
    {NewMoney,TempDatas,_ExtraAdd} = account_focuser(Focus,Runers,Money,[],0),
    Adds = max(NewMoney-Money,0),
    Items0 = data_glamour:get(init_item),
    Datas  = [{K,T,V}||{K,T,V,_}<-TempDatas],
    {ok,Bin0} = pt_142:write(14207,[Adds,NewMoney,Datas]),
    Items     = util:combine_list(Items0++Buys),
    {ok,Bin1} = pt_142:write(14205,[NewMoney,Items]),
    lib_server_send:send_to_uid(RoleID,<<Bin0/binary,Bin1/binary>>),
    log_glamour_like(RoleID,Name,Money,NewMoney,Round,TempDatas),
    Focuser#glamour_focuser{focus=[],money=NewMoney,total=NewMoney,items=Items}.

account_focuser([],[],Money,Datas,ExtraAdd)->
    IntelAdd = data_glamour:get(intel_add),
    {Money+IntelAdd,Datas,ExtraAdd+IntelAdd};
account_focuser([],Runers,Money,Datas,ExtraAdd)->
    Datas0 = [{Rank,Figure,0,0}||#glamour_runer{rank=Rank,figure=Figure}<-Runers],
    NDatas = Datas++Datas0,
    IntelAdd = data_glamour:get(intel_add),
    {Money+IntelAdd,NDatas,ExtraAdd+IntelAdd};
account_focuser([{RunID,Add}|T],Runers,Money,Datas,ExtraAdd)->
    Backs = data_glamour:get(reback),
    case lists:keytake(RunID,#glamour_runer.id,Runers) of
        {value,#glamour_runer{rank=Rank,figure=Figure},NRuners}->
            case lists:keyfind(Rank,1,Backs) of
                {_,V}->
                    MultAdd = util:ceil(Add*V),
                    NewMoney = Money+Add+MultAdd,
                    account_focuser(T,NRuners,NewMoney,[{Rank,Figure,Add,MultAdd}|Datas],ExtraAdd+util:ceil(Add*(V-1)));
                _->
                    account_focuser(T,NRuners,Money,[{Rank,Figure,Add,Add}|Datas],ExtraAdd)
            end;
        _->
            account_focuser(T,Runers,Money,Datas,ExtraAdd)
    end.

pack_bet_view([],_,Datas)->
    {ok,Bin} = pt_142:write(14214,[Datas]),
    Bin;
pack_bet_view([H|T],Focus,Datas)->
    case H of
        #glamour_runer{
            id = Rid,
            figure = Figure
        }->
            case lists:keyfind(Rid,1,Focus) of
                {_,Bet}->
                    skip;
                _->
                    Bet=0
            end,
            pack_bet_view(T,Focus,[{Figure,Bet}|Datas]);
        _->
            pack_bet_view(T,Focus,Datas)
    end.

sort_all_focus(Focusers)->
    Focusers0 = compare_focuser_money(Focusers),
    Max = data_glamour:get(show_num),
    NFocusers = compare_data(Focusers0,1,Max,[]),
    save_show_ranks(NFocusers).

update_all_ranks(Focuser)->
    Focusers = get_all_ranks(),
    case lists:keymember(Focuser#glamour_focuser.rid,#glamour_focuser.rid,Focusers) of
        true->
            ignore;
        _->
            sort_all_focus([Focuser|Focusers])
    end.

%%资金降序
compare_focuser_money(Focusers)->
    lists:sort(fun
        (A1, A2) ->
            compare_focuser_money(A1, A2)
    end, Focusers).
compare_focuser_money(A,B)->
    #glamour_focuser{total=TotalA,figure=#figure{power=PowerA}}=A,
    #glamour_focuser{total=TotalB,figure=#figure{power=PowerB}}=B,
    case TotalA==TotalB of
        true->
            PowerA>=PowerB;
        _->
            TotalA>TotalB
    end.

compare_data([],_,_Max,Focusers)->
    lists:reverse(Focusers);
compare_data(_,Max,Max,Focusers)->
    lists:reverse(Focusers);
compare_data([H|T],Rank,Max,Focusers)->
    compare_data(T,Rank+1,Max,[H#glamour_focuser{rank=Rank}|Focusers]).

merge_runers([],Runers)->
    Runers;
merge_runers([{_,H}|T],Runers)->
    merge_runers(T,H++Runers).

init_runer_focuser(Runers)->
    init_runer_focuser(Runers,[]).
init_runer_focuser([],Datas)->
    FocuserMap = maps:from_list(Datas),
    NDatas = [V||{_,V}<-Datas],
    save_show_ranks(NDatas),
    save_all_focuser(FocuserMap);
init_runer_focuser([H|T],Datas)->
    #glamour_runer{
        id = Rid,
        figure = Figure
    }=H,
    NewH = #glamour_focuser{
        rid = Rid,
        figure = Figure,
        money = data_glamour:get(init_money)+data_glamour:get(runer_add),
        total = data_glamour:get(init_money)+data_glamour:get(runer_add),
        items = data_glamour:get(init_item)
    },
    init_runer_focuser(T,[{Rid,NewH}|Datas]).


account_mail_award([])->
    ok;
account_mail_award([H|T])->
    #glamour_focuser{
        rid = Rid,
        figure = Figure,
        total = Total,
        rank = Rank
    }=H,
    Rewards = data_glamour:get_award(Total),
    Title = utext:get(1420001),
    Content = utext:get(1420002,[Rank]),
    Rewards /= [] andalso begin
        lib_mail_api:send_sys_mail([Rid], Title, Content, Rewards),
        lib_achievement_api:async_event(Rid, lib_achievement_api, glamour_coin_event, Total),
        lib_log_api:log_glamour_rank(Rid,Figure#figure.name,Rank,Total,Rewards)
    end,
    timer:sleep(300),
    account_mail_award(T).


auto_focus(State)->
    #glamour_focus_mgr{
        round = Round,
        runers = RunerMap
    }=State,
    Add      = data_glamour:get(intel_add),
    Runers   = maps:get(Round,RunerMap,[]),
    Runer    = urand:list_rand(Runers),
    case Runer of
        #glamour_runer{id=RunID}->
            skip;
        _->
            RunID = 0
    end,
    case RunID>0 of
        true->
            Now = utime:unixtime(),
            FocuserMap = get_all_focuser(),
            F = fun(RoleID,Focuser,{ArgsMap,ArgsRuners})->
                #glamour_focuser{
                    focus=Focus,
                    figure=#figure{name=Name,vip=Vip,sup_vip=SubVip}
                }=Focuser,
                case length(Focus)=<0 of
                    true-> %%还没投注的 帮助投注
                        #glamour_runer{figure=#figure{name=RName},trust=Trust}=Runer,
                        NFocus = [{RunID,Add}],
                        NFocuser = Focuser#glamour_focuser{focus=NFocus},
                        NRuner = Runer#glamour_runer{trust=Trust+Add},
                        NArgsRuners = lists:keyreplace(RunID,#glamour_runer.id,ArgsRuners,NRuner),
                        GlamourLog = #glamour_log{
                            opty = 1,
                            rid  = RoleID,
                            vip  = Vip,
                            sub_vip=SubVip,
                            name = Name,
                            aim = RName,
                            value = Add,
                            time = Now
                        },
                        update_log(GlamourLog),
                        mod_glamour_mgr:sync_runer_trust(RunID,Trust+Add),
                        NMap = maps:put(RoleID,NFocuser,ArgsMap),
                        {NMap,NArgsRuners};
                    _->
                        NMap = maps:put(RoleID,Focuser,ArgsMap),
                        {NMap,ArgsRuners}
                end
            end,
            {NFocuserMap,NRuners} = maps:fold(F, {FocuserMap,Runers}, FocuserMap),
            Bin = pack_focus_data(NRuners),
            lib_server_send:send_to_all(Bin),
            NRunerMap = maps:put(Round,NRuners,RunerMap),
            save_all_focuser(NFocuserMap),
            State#glamour_focus_mgr{runers = NRunerMap};
        _->
            State
    end.

log_glamour_like(RoleID,Name,Money,NewMoney,Round,Datas)->
    NDatas = [{Rank,Figure#figure.id,Add,MultAdd}||{Rank,Figure,Add,MultAdd}<-Datas,Add>0],
    lib_log_api:log_glamour_like(RoleID,Name,Money,NewMoney,Round,NDatas).


%% @doc TA数据上报 @end
ta_update_data_on_player(Player, [IsHosting, LikeTimes, FreeTimes, PayTimes, UseTime]) ->
    IsCountDown = lib_activitycalen_api:get_enter_activity_record(Player#player_status.id, ?MOD_GUILD),
    ta_agent_fire:guild_ballroom(Player, [IsHosting, IsCountDown, LikeTimes, FreeTimes, PayTimes, UseTime]),
    {ok, Player}.