%%%--------------------------------------
%%% @Module  : lib_liveness
%%% @Author  : xiaoxiang
%%% @Created : 2017-07-10
%%% @Description:  玩家活跃度形象
%%%--------------------------------------
-module(lib_liveness).
-export([

]).
-compile(export_all).
-include("server.hrl").
-include("figure.hrl").
-include("errcode.hrl").
-include("def_fun.hrl").
-include("def_module.hrl").
-include("def_daily.hrl").
-include("activitycalen.hrl").
-include("predefine.hrl").
-include("goods.hrl").
-include("common.hrl").
-include("rec_event.hrl").
-include("def_event.hrl").

login(RoleId, _RoleLv) ->
    [Lv, Exp, Live, OLive, LTime] = db_player_liveness_select(RoleId),
    Attrs = case data_activitycalen:get_liveness(Lv) of
        #base_liveness_lv{attr = TmpAttr} ->
            TmpAttr;
        _ ->
            []
    end,
    case utime:is_logic_same_day(LTime) of
        true->
            #role_liveness{lv = Lv, exp = Exp,live=Live,olive=OLive,ltime=LTime,attr = Attrs};
        _->
            #role_liveness{lv = Lv, exp = Exp,live=0, olive=Live, ltime=utime:unixtime(),attr = Attrs}
    end.

calc_power(Status, AttrPower, BaseAttr) ->
    #player_status{role_liveness=RoleLives}=Status,
    #role_liveness{attr=Attrs}=RoleLives,
    PartialAttr = attr_conv:to_attr_record(Attrs),
    Power = lib_player_attr:calc_attr_power_partial(AttrPower, BaseAttr, PartialAttr),
    NRoleLives = RoleLives#role_liveness{combat=Power},
    {Status#player_status{role_liveness=NRoleLives},0}.

%% 增加活跃度
add_liveness(Player, Value) ->
    #player_status{id = RoleId, role_liveness = RoleLives, figure = #figure{lv = RoleLv}} = Player,
    case misc:is_process_alive(misc:get_player_process(RoleId)) of
        true ->
            #role_liveness{exp = Exp,live=Live} = RoleLives,
            NewRoleLives = RoleLives#role_liveness{exp = Exp + Value,live=Live+Value},
            NewPlayer = Player#player_status{role_liveness = NewRoleLives},
            db_player_liveness_replace(RoleId, NewRoleLives),
            get_player_liveness(NewPlayer),
            %% 更新奖励状态 通知客户端
            refresh_live_reward(RoleId, RoleLv),
            %% 增加活跃度通行证的活跃度
            permit_active:add_active(RoleId, Value),
            {ok, NewPlayer};
        false ->
            F = fun() ->
                [Lv, Exp, Live, OLive, LTime] = db_player_liveness_select(RoleId),
                db_player_liveness_replace(RoleId, #role_liveness{lv = Lv, exp = Exp + Value, live=Live+Value, olive=OLive,ltime=LTime})
                end,
            catch db:transaction(F),
            {ok, Player}
    end.

%% 刷新奖励状态
refresh_live_reward(RoleId, Lv) ->
    Live = lib_daily:get_count(RoleId, ?MOD_ACTIVITY, ?ACTIVITY_LIVE_DAILY),
    LiveMax = lib_daily:get_count_limit(?MOD_ACTIVITY, ?ACTIVITY_LIVE_DAILY),
    IdList = data_activitycalen:get_reward_id(),
    OldCountL = lib_daily:get_count(RoleId, [{?MOD_ACTIVITY, ?MOD_ACTIVITY_LIVE_REWARD, Id} || Id <- IdList]),
    OldList = [{Id, Value} || {{_, _, Id}, Value} <- OldCountL],
    F = fun({Id, OldVal}, TmL) ->
        case data_activitycalen:get_reward_config(Id, Lv) of
            #ac_reward{live = LiveLimit} ->
                case OldVal of
                    ?NOT_REWARD ->
                        case Live >= LiveLimit of
                            true ->
                                NewVal = ?HAVE_REWARD,
                                %% 置为已领状态
                                lib_daily:increment(RoleId, ?MOD_ACTIVITY, ?MOD_ACTIVITY_LIVE_REWARD, Id);
                            _ -> NewVal = ?NOT_REWARD
                        end;
                    _ -> NewVal = OldVal
                end,
                TmL ++ [{Id, NewVal}];
            _ -> TmL
        end
        end,
    NewList = lists:foldl(F, [], OldList),
    lib_server_send:send_to_uid(RoleId, pt_157, 15703, [Live, LiveMax, NewList]).


%% 查询玩家活跃度
get_player_liveness(Player) ->
    #player_status{id = RoleId, role_liveness = #role_liveness{lv = Lv, exp = Exp}} = Player,
    lib_server_send:send_to_uid(RoleId, pt_157, 15709, [Lv, Exp]).

%% 活跃度升级
liveness_lv_up(Player) ->
    #player_status{id = RoleId, role_liveness = RoleLives} = Player,
    #role_liveness{lv = Lv, exp=Exp} = RoleLives,
    case check_up(Lv,Exp) of
        {true, NewExp} ->
            NewLv = Lv + 1,
            #base_liveness_lv{attr=Attr,awards=Awards} = data_activitycalen:get_liveness(NewLv),
            NewRoleLives = RoleLives#role_liveness{lv = NewLv, attr = Attr,exp = NewExp},
            NewPlayer  = Player#player_status{role_liveness=NewRoleLives},
            LastPlayer = lib_player:count_player_attribute(NewPlayer),
            lib_player:send_attribute_change_notify(LastPlayer, ?NOTIFY_ATTR),
            db_player_liveness_replace(RoleId, NewRoleLives),
            lib_log_api:log_liveness_up(RoleId, Lv, Exp - NewExp, NewLv),
            lib_player_event:async_dispatch(RoleId, ?EVENT_LIVENESS_LV),
            Produce = #produce{type=role_liveness,reward=Awards},
            Awards /= [] andalso lib_goods_api:send_reward_with_mail(RoleId, Produce),
            lib_server_send:send_to_uid(RoleId, pt_157, 15710, [?SUCCESS, NewLv, NewExp]);
        {false, ErrCode} ->
            LastPlayer = Player,
            lib_server_send:send_to_uid(RoleId, pt_157, 15700, [ErrCode])
    end,
    {ok, LastPlayer}.

%% 检查是否能升级
check_up(Lv,Exp) ->
    case data_activitycalen:get_lv_max() of
        Max when is_integer(Max) andalso Lv < Max ->
            case data_activitycalen:get_liveness(Lv) of
                #base_liveness_lv{exp = Value} when Exp >= Value ->
                    {true, Exp - Value};
                #base_liveness_lv{} ->
                    {false, ?ERRCODE(err157_6_live_not_enough)};
                _ ->
                    {false, ?ERRCODE(err_config)}
            end;
        Max when is_integer(Max) andalso Lv >= Max ->
            {false, ?ERRCODE(err157_7_max_lv)};
        _ ->
            {false, ?ERRCODE(err157_5_cfg_err)}
    end.


%% ----------------------------------------------------------------
db_player_liveness_select(RoleId) ->
    Sql = io_lib:format(?sql_player_liveness_select, [RoleId]),
    case db:get_row(Sql) of
        [] ->
            [0, 0,0,0,0];
        [Lv, Exp,Live,OLive,LTime] ->
            [Lv, Exp,Live,OLive,LTime]
    end.

db_player_liveness_replace(RoleId, RoleLives) ->
    #role_liveness{lv = Lv, exp = Exp,live=Live,olive=OLive,ltime=LTime} = RoleLives,
    Sql = io_lib:format(?sql_player_liveness_replace, [RoleId, Lv, Exp,Live,OLive,LTime]),
    db:execute(Sql).


%% 4点事件
handle_event(Status, #event_callback{type_id = ?EVENT_FOUR_CLOCK}) when is_record(Status, player_status) ->
    #player_status{
        id = RoleId,
        role_liveness = RoleLives
    } = Status,
    #role_liveness{live=Live}=RoleLives,
    NRoleLives = RoleLives#role_liveness{live=0,olive=Live,ltime=utime:unixtime()},
    db_player_liveness_replace(RoleId, NRoleLives),
    NStatus = Status#player_status{role_liveness=NRoleLives},
    lib_task_api:finish_day_activity(NStatus, 0),
    {ok, NStatus};
handle_event(Status, _Event) ->
    {ok, Status}.

gm_olive(Status,Num)->
    #player_status{
        id = RoleId,
        role_liveness = RoleLives
    } = Status,
    NRoleLives = RoleLives#role_liveness{olive=Num,ltime=utime:unixtime()},
    NStatus = Status#player_status{role_liveness=NRoleLives},
    db_player_liveness_replace(RoleId, NRoleLives),
    NStatus.
