%% ---------------------------------------------------------------------------
%% @doc 角色进程零点执行.
%% @author zhaoyu
%% @since  2016-12-29
%% ---------------------------------------------------------------------------
-module(lib_player_tomorrow).

-export([
        tomorrow/2,                    %% 角色进程零点执行
        week/2,                        %% 角色进程跨周执行
        log_info/0,
        log_money_info_do/0,
        log_daily_info_do/0,
        role_daily_active/0,
        role_daily_attr/0
    ]).

-include("server.hrl").
-include("daily.hrl").
-include("rec_recharge.hrl").
-include("common.hrl").
-include("task.hrl").
-include("def_module.hrl").
-include("def_fun.hrl").
-include("offline_hosting.hrl").
-include("def_daily.hrl").
-include("vip.hrl").
-include("activitycalen.hrl").
-include("local_boss.hrl").
-include("dungeon.hrl").
-include("predefine.hrl").
%% ---------------------------------------------------------------------------
%% @doc 角色进程零点执行
%% 注意：这里涉及清数据的话，所清理的数据必须只有角色进程自己处理的！！
%% 如果还有其他进程清理所涉及的数据的，不能放在这里执行！！
-spec tomorrow(Player, Time) -> NewPlayer when
    Player      :: #player_status{},
    Time        :: integer(),
    NewPlayer   :: #player_status{}.
%% ---------------------------------------------------------------------------
tomorrow(Player, ?TWELVE) ->
    #player_status{id=RoleID}=Player,
    CouponPlayer = relation_coupon:daily_reset(Player),
    LatticePlayer = lib_lattice:zero_time(CouponPlayer),
    TopPkPlayer = lib_top_pk:daily_reset(LatticePlayer),
    Kf3v3Player = lib_3v3_local:daily_check(TopPkPlayer),
    GodDunPlayer = lib_role_god_dun:daily_reset(Kf3v3Player),
    LastPlayer = GodDunPlayer,
    lib_task_api:refresh_task(LastPlayer),
    pp_mate:handle(14900, LastPlayer, []),
    {ok,Bin} = pt_102:write(10207,[0]),
    lib_server_send:send_to_uid(RoleID,Bin),
    lib_recharge_first:send_first_state_to_client(LastPlayer),
    LastPlayer;

tomorrow(Player,?FOUR) ->
    #player_status{id=RoleID}=Player,
    LastPlayer = Player,
    {ok,Bin} = pt_102:write(10207,[4]),
    lib_server_send:send_to_uid(RoleID,Bin),
    LastPlayer.

%% 跨周执行
week(Player, _CounterType) ->
    LastPlayer = Player,
    LastPlayer.

log_info() ->
    case utime:localtime() of
        {_, {23, 55, _}} ->
            spawn(?MODULE, log_money_info_do, []);
        {_, {23, 59, _}} ->
            spawn(?MODULE, role_daily_attr, []);
        {_, {3, 55, _}} ->
            spawn(?MODULE, log_daily_info_do, []);
        {_, {3, 59, _}} ->
            spawn(?MODULE, role_daily_active, []);
        _ ->
            ok
    end.

%% 每天23：55记录14天内有登录的玩家信息
log_money_info_do() ->
    Now = utime:unixtime(),
    SQL = io_lib:format(<<"SELECT pl.id,pl.nickname,pl.lv,plogin.last_logout_time,plogin.online_flag,ph.gold,ph.bgold,ph.coin,ph.honour,ph.hightest_combat_power,"
    "prr.total_money,prr.total_gold,prr.recency,prr.frequency,prr.monetary,prr.top"
    " FROM player_low pl"
    " LEFT JOIN player_high ph ON pl.id = ph.id"
    " LEFT JOIN player_recharge_rfmt prr ON pl.id = prr.role_id"
    " LEFT JOIN player_login AS plogin ON pl.id = plogin.id"
    " WHERE plogin.last_logout_time > ~p or plogin.last_logout_time = 0">>, [Now - 14 * 86400]
    ),
    RoleList = db:get_all(SQL),
    ZeroTime = utime:unixdate(Now),
    [
        begin
            case One of
                [RoleId, Name, Lv, LogoutTime, OnlineFlag, Gold, BGold, Coin, Honour, Power, undefined | _] ->
                    #role_recharge_statistic{
                        total_money = TotalMoney    %% 总充值钱：实数
                        , total_gold = TotalGold    %% 总充值元宝
                        , recency = Recency         %% 评级：充值间隔   last_pay_time与登录时间戳相差的天数区间
                        , frequency = Frequency     %% 评级：充值频率   最近30天内的充值次数
                        , monetary = Monetary       %% 评级：历史总充值
                        , top = Top                 %% 评级：最高额充值
                    } = #role_recharge_statistic{};
                [RoleId, Name, Lv, LogoutTime, OnlineFlag, Gold, BGold, Coin, Honour, Power, TotalMoney, TotalGold, Recency, Frequency, Monetary, Top] ->
                    ok
            end,
            %% 是否登陆过
            IsLogin =
                case OnlineFlag of
                    ?ONLINE_ON -> 1;
                    _ ->
                        %% 离线时间在0点后，表明今天登陆过
                        case LogoutTime > ZeroTime of
                            true  -> 1;
                            false -> 0
                        end
                end,
            lib_log_api:log_player_attr([RoleId, Name, Power, Lv, Gold, BGold, Coin, Honour, TotalMoney, TotalGold, Recency, Frequency, Monetary, Top, IsLogin, Now])
        end || One <- RoleList
    ].

%% 每天3：55记录14天内有登录的玩家
log_daily_info_do() ->
    Now = utime:unixtime(),
    SQL = io_lib:format(<<"SELECT pl.id,pl.nickname,pl.lv,plogin.last_logout_time,plogin.online_flag,v.type,v.end_time,ph.gold,ph.bgold,ph.coin"
    " FROM player_low pl"
    " LEFT JOIN player_login AS plogin ON pl.id = plogin.id"
    " LEFT JOIN role_sup_vip AS v ON pl.id = v.role_id"
    " LEFT JOIN player_high ph ON pl.id = ph.id"
    " WHERE plogin.last_logout_time > ~p or plogin.last_logout_time = 0">>, [Now - 14 * 86400]
    ),
    RoleList = db:get_all(SQL),
    ZeroTime = utime:unixdate(Now - 86400),
    [
        begin
            case
                {
                    data_task_lv_dynamic:get_task_type(?TASK_TYPE_GUILD),
                    data_task_lv_dynamic:get_task_type(?TASK_TYPE_DAILY)
                }
            of
                {
                    #task_type{module_id = ModGuild, counter_id = IdGuild},
                    #task_type{module_id = ModDaily, counter_id = IdDaily}
                } ->
                    [
                        {_, Activity},
                        {_, GuildTask},
                        {_, DailyTask},
                        {_, FastExpCount},
                        {_, DailyHostingValue},
                        {_, _DailyFame}
                    
                    ] = lib_daily:get_count_offline(RoleId,
                        [
                            {?MOD_ACTIVITY, 0, ?ACTIVITY_LIVE_DAILY}       %% 活跃度
                            , {ModGuild, 0, IdGuild}                       %% 公会周长
                            , {ModDaily, 0, IdDaily}                       %% 每日跑环
                            , {?MOD_DUNGEON, 0, ?MOD_EXP_DUN_FAST_DROP}    %% 放置冒险超级加速
                            , {?MOD_OFFLINE_HOSTING, 0, 1}                 %% 今日获得的托管值
                            , {?MOD_GOODS, 0, 2}                           %% 今日名望券
                        ]
                    ),
                    %% 贵族身份
                    SupVipType = ?IF(is_integer(SupVipTypeTemp), SupVipTypeTemp, 0),
                    %% 超级加速次数
                    LeftFastExpCount = fast_exp_drop:get_fast_drop_max_count(
                        #role_sup_vip{
                            type = SupVipType,
                            end_time = ?IF(is_integer(SupVipTime), SupVipTime, 0)
                        }
                    ) - FastExpCount,
                    %% 当前托管值
                    #ets_offline_hosting{value = HostingValueNow} = offline_hosting_data:host_setting_lookup(RoleId),
                    %% 是否登陆过
                    IsLogin =
                        case OnlineFlag of
                            ?ONLINE_ON -> 1;
                            _ ->
                                %% 离线时间在0点后，表明今天登陆过
                                case LogoutTime > ZeroTime of
                                    true  -> 1;
                                    false -> 0
                                end
                        end,
                    lib_log_api:log_player_daily([RoleId, Name, Lv, Activity, DailyTask, GuildTask, LeftFastExpCount, SupVipType,
                        HostingValueNow, DailyHostingValue, Gold, BGold, Coin, IsLogin, Now]);
                _ ->
                    ok
            end
        end || [RoleId, Name, Lv, LogoutTime, OnlineFlag, SupVipTypeTemp, SupVipTime, Gold, BGold, Coin] <- RoleList
    ].

%% 每天3:59记录，只对前天0点后有登录的玩家进行统计
role_daily_active() ->
    [
        lib_player:apply_cast(Pid, ?APPLY_CAST_STATUS, ta_agent_fire, role_daily_active, []) ||
        #ets_online{pid = Pid} <- ets:tab2list(?ETS_ONLINE)
    ].

%% 每天23:59记录，只对今日登录的玩家进行统计
role_daily_attr() ->
    [
        lib_player:apply_cast(Pid, ?APPLY_CAST_STATUS, ta_agent_fire, role_daily_attr, []) ||
        #ets_online{pid = Pid} <- ets:tab2list(?ETS_ONLINE)
    ].
