%% @doc    首充奖励
%% @author hek      由关联商品触发
%% @since  2016-11-14
%% @deprecated
%% ---------------------------------------------------------------------------

-module(lib_recharge_first).
-include("common.hrl").
-include("server.hrl").
-include("rec_recharge.hrl").
-include("def_recharge.hrl").
-include("def_event.hrl").
-include("rec_event.hrl").
-include("errcode.hrl").
-include("def_fun.hrl").
-include("figure.hrl").
-include("def_module.hrl").
-include("def_goods.hrl").
-include("goods.hrl").

-export ([
    login/1,
    send_first_state_to_client/1,
    get_recharge_gift_award/3,
    gm_clear_award/1,
    gm_update_days/2
]).

-export([
    %% 处理商品逻辑
    handle_product/3
]).

%% 玩家登陆
login(PS) ->
    PlayerId = PS#player_status.id,
    RechargeStatus = PS#player_status.recharge_status,
    FirstRecharge = get_recharge_first_db(PlayerId),
    NewRechargeStatus = RechargeStatus#recharge_status{first_data = FirstRecharge},
    PS#player_status{recharge_status = NewRechargeStatus}.

%% 充值触发首充，处理商品逻辑
handle_product(PS, ProductId, ChargeProductCfg) ->
    case lib_recharge_check:check_product(ProductId) of
        {true, ProductCfg} ->
            case is_already_trigger(PS, ProductId) of
                {ok, FirstTrigger} ->
                    do_handle_product(PS, FirstTrigger, ProductCfg, ChargeProductCfg);
                _ ->
                    {ok, PS}
            end;
        _ ->
            {ok, PS}
    end.
%% FirstTrigger:首充信息
%% ProductCfg 首充配置
%% ChargeProductCfg 触发首充的充值配置
do_handle_product(PS, FirstTrigger, ProductCfg, ChargeProductCfg) ->
    NowTime = utime:unixtime(),
    #player_status{
        id = PlayerId,
        sid = Sid,
        reg_time = RegTime,
        recharge_status = RechargeStatus,
        last_behavior = LastBehavior,
        figure = #figure{name = Name, lv = Lv}
    } = PS,
    #first_recharge{
        recharge = Recharge,
        product_id = ProductId
    } = FirstTrigger,
    CurRecharge = Recharge + ChargeProductCfg#base_recharge_product.money,
    OneCharge =
    case CurRecharge >= ProductCfg#base_recharge_product.money of
        true  -> FirstTrigger#first_recharge{recharge = CurRecharge, trigger_time = NowTime};
        false -> FirstTrigger#first_recharge{recharge = CurRecharge}
    end,
    replace_recharge_first_db(PlayerId, OneCharge),
    
    FirstRecharge = RechargeStatus#recharge_status.first_data,
    NewRechargeStatus = RechargeStatus#recharge_status{
        first_data = lists:keystore(ProductId, #first_recharge.product_id, FirstRecharge, OneCharge)
    },
    NewPS = PS#player_status{recharge_status = NewRechargeStatus},
    case OneCharge#first_recharge.trigger_time > 0 of
        true  ->
            %% 触发了一档
            AllCfg = sort_all_first_recharge(),
            NextId = get_next_first_recharge(AllCfg, ProductId),
            NextId > 0 andalso
                lib_server_send:send_to_sid(Sid, pt_159, 15907, [NextId]),
            Opday = util:get_open_day(),
            IsSameDay = case utime:day_span(NowTime, RegTime) of
                            1 -> 1;
                            _ -> 0
                        end,
            OnlineTime = welfare_api:get_now_online_time(NewPS),
            lib_log_api:log_recharge_first(PlayerId, Name, ProductId, 1, 0, [], IsSameDay, RegTime, Opday, LastBehavior, Lv, OnlineTime);
        false ->
            ok
    end,
    send_first_state_to_client(NewPS),
    {ok, NewPS}.

is_already_trigger(Player, ProductId) ->
    FirstRecharge = Player#player_status.recharge_status#recharge_status.first_data,
    case lists:keyfind(ProductId, #first_recharge.product_id, FirstRecharge) of
        #first_recharge{trigger_time = Time} when Time > 0 -> already_trigger;
        #first_recharge{} = One -> {ok, One};
        _ -> {ok, #first_recharge{product_id = ProductId}}
    end.

sort_all_first_recharge() ->
    ProductCfg =
        [
            data_recharge:get_product(Id) || Id <- data_recharge:get_recharge_first_ids()
        ],
    lists:keysort(#base_recharge_product.money, ProductCfg).

get_next_first_recharge([#base_recharge_product{product_id = Id}, #base_recharge_product{product_id = NextId}|_], Id) ->
    NextId;
get_next_first_recharge([_|T], Id) ->
    get_next_first_recharge(T, Id);
get_next_first_recharge(_, _) -> 0.
%% --------------------------- 协议处理部分 ---------------------------
%% 查看首充奖励状态
send_first_state_to_client(PS) ->
    RechargeStatus = PS#player_status.recharge_status,
    FirstRecharge = RechargeStatus#recharge_status.first_data,
    %% 首充配置按触发额度增序排列
    SendList = include_state(sort_all_first_recharge(), FirstRecharge, []),
    Now = utime:unixtime(),
    FormatList =
    [
        case TriggerTime > 0 of
            true  ->
                {ProductId, round(Recharge * 100), 1, utime:day_span(TriggerTime, Now), AwardList};
            false ->
                {ProductId, round(Recharge * 100), 0, 0, AwardList}
        end
        || #first_recharge{
                product_id   = ProductId,         %% 产品id
                recharge     = Recharge,
                trigger_time = TriggerTime,
                award_list   = AwardList
            } <- SendList
    ],
    lib_server_send:send_to_sid(PS#player_status.sid, pt_159, 15905, [FormatList]),
    ok.

%% 已经触发了，则发给前端；
%% 还没触发，发给前端，停止。预告展示下一阶段
include_state([#base_recharge_product{product_id = Id}|T], Info, List) ->
    case lists:keyfind(Id, #first_recharge.product_id, Info) of
        #first_recharge{trigger_time = Time} = One when Time > 0 ->
            include_state(T, Info, [One|List]);
        #first_recharge{} = One ->
            [One|List];
        _ ->
            [#first_recharge{product_id = Id}|List]
    end;
include_state([], _, List) -> List.

%% 领取首充奖励
get_recharge_gift_award(PS, ProductId, Index) ->
    case check_award(PS, ProductId, Index) of
        {true, Recharge, Award} -> do_get_recharge_gift_award(PS, Recharge, Index, Award);
        {false, ErrCode} -> {false, ErrCode}
    end.
do_get_recharge_gift_award(PS, Recharge, Index, CareerAward) ->
    #player_status{
        id = PlayerId,
        recharge_status = RechargeStatus,
        figure = #figure{name = Name, lv = Lv}
    } = PS,
    FirstRecharge = RechargeStatus#recharge_status.first_data,
    
    #first_recharge{
        product_id = ProductId,
        award_list = AwardList
    } = Recharge,
    NewRecharge = Recharge#first_recharge{award_list = [Index | AwardList]},
    %% 写库(先写库再发奖,避免写库失败重复领取)
    replace_recharge_first_db(PlayerId, NewRecharge),
    NewRechargeStatus = RechargeStatus#recharge_status{
        first_data = lists:keystore(Recharge#first_recharge.product_id, #first_recharge.product_id, FirstRecharge, NewRecharge)
    },
    Player = PS#player_status{recharge_status = NewRechargeStatus},
    Produce = #produce{type = recharge_gift_award, reward = CareerAward,subtype = Recharge#first_recharge.product_id, remark = lists:concat(["DayId:", Index])},

    Player1 = lib_goods_api:send_reward(Player, Produce),
    
    %% 首充才有传闻
    ProductId =:= 9999 andalso
        lib_chat:send_TV({all}, ?MOD_RECHARGE_ACT, Index, [Name, PlayerId]),
    OnlineTime = welfare_api:get_now_online_time(PS),
    lib_log_api:log_recharge_first(PlayerId, Name, ProductId, 2, Index, CareerAward, 0, 0, 0, 0, Lv, OnlineTime),
    {true, ?SUCCESS, Player1}.

check_award(PS, ProductId, Index) ->
    RechargeStatus = PS#player_status.recharge_status,
    FirstRecharge = RechargeStatus#recharge_status.first_data,
    case lists:keyfind(ProductId, #first_recharge.product_id, FirstRecharge) of
        #first_recharge{trigger_time = TriggerTime} = One when TriggerTime > 0 ->
            #first_recharge{
                award_list = AwardList
            } = One,
            AlreadyGot = lists:member(Index, AwardList),
            Reward = case data_recharge:get_recharge_first(ProductId, PS#player_status.figure#figure.career, Index) of
                      [] ->
                          data_recharge:get_recharge_first(ProductId, 0, Index);
                      _Cfg ->
                          _Cfg
                  end,
            DiffDays = utime:day_span(TriggerTime),
            if
                AlreadyGot -> {false, ?ERRCODE(err159_4_already_get)};
                Reward == [] -> {false, ?ERRCODE(missing_config)};
                Index > DiffDays -> {false, ?ERRCODE(err159_not_the_time)};
                true ->
                    {true, One, Reward}
            end;
        _ ->
            {false, ?ERRCODE(err159_3_not_buy)}
    end.

%% gm秘籍，清空首充
gm_clear_award(PS) ->
    PlayerId = PS#player_status.id,
    RechargeStatus = PS#player_status.recharge_status,
    db:execute(<<"delete from role_recharge_first where role_id=~p">>, [PlayerId]),
    NewRechargeStatus = RechargeStatus#recharge_status{first_data = []},
    NewPS = PS#player_status{recharge_status = NewRechargeStatus},
    send_first_state_to_client(NewPS),
    {ok, NewPS}.

%% 首充登陆天数
gm_update_days(Player, Days) ->
    RechargeStatus = Player#player_status.recharge_status,
    Time = utime:unixtime() - (Days - 1) * 86400,
    FirstDate =
    [
        case One#first_recharge.trigger_time > 0 of
            true  ->
                One#first_recharge{trigger_time = Time};
            false ->
                One
        end
        || #first_recharge{} = One <- RechargeStatus#recharge_status.first_data
    ],
    NewRechargeStatus = RechargeStatus#recharge_status{first_data = FirstDate},
    NewPlayer = Player#player_status{recharge_status = NewRechargeStatus},
    send_first_state_to_client(NewPlayer),
    NewPlayer.
%% -------------------------------- db function --------------------------------
get_recharge_first_db(PlayerId) ->
    Sql = io_lib:format(<<"select `product_id`, `recharge`, `trigger_time`, `award_list` from `role_recharge_first` where `role_id` = ~p">>, [PlayerId]),
    [
        #first_recharge{
            product_id      = ProductId,
            recharge  = Recharge,
            trigger_time         = TriggerTime,
            award_list      = util:bitstring_to_term(AwardList)
        }
        || [ProductId, Recharge, TriggerTime, AwardList] <- db:get_all(Sql)
    ].

replace_recharge_first_db(PlayerId, FirstRecharge) ->
    #first_recharge{
        award_list = AwardList,
        product_id      = ProductId,
        recharge        = Recharge,
        trigger_time    = TriggerTime
    } = FirstRecharge,
    NewAwardList = util:term_to_bitstring(AwardList),
    Sql = io_lib:format(<<"replace into `role_recharge_first`(`role_id`, `product_id`, `recharge`, `trigger_time`, `award_list`)
        values(~p, ~p, ~p, ~p, '~ts')">>, [PlayerId, ProductId, Recharge, TriggerTime, NewAwardList]),
    db:execute(Sql).


