%% ---------------------------------------------------------------------------
%% @doc 定制活动-0元礼包。
%% @author zmh
%% @since  2020-07-20
%% ---------------------------------------------------------------------------
-module(zero_gift).


-export([
    send_personal_act_info/3
    ,personal_act_award/4
    ,init_personal_act_data/2
    ,notify_other_module/1
    ,check_clean/2
]).


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

send_personal_act_info(Role, Type, SubType) ->
    {
        Type, SubType, StartTime, AwardStatusList
    } = pack_p_act_info(Role, Type, SubType),
    {ok, BinData} = pt_331:write(33185, [Type, SubType, StartTime, AwardStatusList]),
    lib_server_send:send_to_sid(Role#player_status.sid, BinData),
    ok.

pack_p_act_info(Role, Type, SubType) ->
    case custom_act_personal:is_personal_act_open(Role, Type, SubType) of
        {true, _EndTime} ->
            ActInfo = #custom_act_personal{
                s_time   = StartTime,
                act_data = ActData
            } = custom_act_personal:get_custom_act_personal_open_info(Role, Type, SubType),
            %% 判断是否有提前展示时间
            ShowTime = lib_custom_act_util:keyfind_act_condition(
                Type, SubType, show_time
            ),
            ShowTime2 = case ShowTime of
                {show_time, Seconds} -> Seconds;
                _ -> 0
            end,
            StartTime2 = StartTime + ShowTime2,
            RewardL = lib_custom_act_util:get_act_reward_cfg_list(Type, SubType),
            Fun = fun(RewardCfg = #custom_act_reward_cfg{grade = Grade}) ->
                {Status, Time} = act_award_status(RewardCfg, ActData, ActInfo),
                {Grade, Time, Status}
            end,
            AwardStatusList = [Fun(Cfg) || Cfg <- RewardL],
            {Type, SubType, StartTime2, AwardStatusList};
        _ ->
            {Type, SubType, 0, []}
    end.

personal_act_award(Role, Type, SubType, Grade) ->
    #player_status{figure = #figure{lv = Lev}} = Role,
    IsOpen = custom_act_personal:is_personal_act_open(Role, Type, SubType),
    RewardCfg = lib_custom_act_util:get_act_reward_cfg_info(Type, SubType, Grade),
    %% 判断是否有提前展示时间
    ShowTime = lib_custom_act_util:keyfind_act_condition(Type, SubType, show_time),
    ShowTime2 = case ShowTime of
        {show_time, Seconds} -> Seconds;
        _ -> 0
    end,
    StartTime = case lib_custom_act_util:get_custom_act_open_info(Type, SubType) of
        #act_info{stime = STime} ->
            STime;
        _ ->
            0
    end,
    Now = utime:unixtime(),
    IsOpen2 = Now >= (StartTime + ShowTime2),
    {_,NeedLev} = lib_custom_act_util:keyfind_act_condition(Type, SubType, open_lv),
    if
        IsOpen =:= false ->
            {false, ?ERRCODE(err331_act_closed)};
        IsOpen2 =:= false ->
            {false, ?ERRCODE(err331_act_closed)};
        not is_record(RewardCfg, custom_act_reward_cfg) ->
            {false, ?ERRCODE(err331_no_act_reward_cfg)};
        Lev<NeedLev->
            {false, ?ERRCODE(err331_lv_unreach)};
        true ->
            Data = #custom_act_personal{
                act_data = Awards
            } = custom_act_personal:get_custom_act_personal_open_info(Role, Type, SubType),
            case check_act_award_status(Role, RewardCfg, Awards, Data) of
                {false, Reason} ->
                    {false, Reason};
                {Role2, {Award, ActInfo}} ->
                    KeyPos = #custom_free_gift_award.award_id,
                    {IsBuy,AwardData2} = case lists:keyfind(Grade, KeyPos, Awards) of
                        AwardData = #custom_free_gift_award{} -> %% 领取奖励
                            {false,AwardData#custom_free_gift_award{
                                is_get = ?ACT_REWARD_HAS_GET
                            }};
                        false -> %% 购买
                            {true,#custom_free_gift_award{
                                award_id = Grade, time = utime:unixtime()
                            }}
                    end,
                    Awards2 = lists:keystore(Grade, KeyPos, Awards, AwardData2),
                    NewData = Data#custom_act_personal{act_data = Awards2},
                    #player_status{id = RoleId, sid = Sid} = Role,
                    Role3 = custom_act_personal:save_personal_act(Role2, NewData),
                    custom_act_personal:save_personal_act_db(RoleId, NewData),
                    RewardCfg2 = RewardCfg#custom_act_reward_cfg{reward = Award},
                    Role4 = lib_custom_act:custom_act_send_reward(Role3, RewardCfg2),
                    {Status, Time} = act_award_status(RewardCfg2, Awards2, ActInfo),
                    IsBuy andalso custom_act_mobilize:update_mobilize_task(RoleId,freegift,1),
                    %% 关闭图标
                    case custom_act_personal:is_personal_act_open(Role4, Type, SubType) of
                        false ->
                            {ok, BinData} = pt_331:write(33103, [[{Type, SubType}]]),
                            lib_server_send:send_to_sid(Sid, BinData);
                        _ ->
                            ok
                    end,
                    lib_log_api:custom_act_reward_log(Role4, Role, Type, SubType, Grade, Awards2),
                    {ok, Role4, Status, Time}
            end
    end.


check_act_award_status(Role, RewardCfg, Awards,ActInfo) ->
    #custom_act_reward_cfg{
        type = Type, subtype = SubType, grade = Grade, condition = Condition, reward = Award
    } = RewardCfg,
    case lists:keyfind(cost, 1, Condition) of
        {cost, CostList0} ->
            CostList0;
        _ ->
            CostList0 = [{?TYPE_GOLD,?GOODS_ID_GOLD,99999999}]
    end,
    NeedLev = case lists:keyfind(buy_lv, 1, Condition) of
        {buy_lv, NLev} -> NLev;
        _ -> 99999999
    end,
    ReturnAward = case lists:keyfind(return, 1, Condition) of
        {return, ReAward} -> ReAward;
        _ -> []
    end,
    {Status, _Time} = act_award_status(RewardCfg, Awards, ActInfo),
    #player_status{figure = #figure{lv = Lev}} = Role,
    {CostList, NewAward} = case Status of
        0  -> {CostList0, Award};
        4 -> {[], ReturnAward};
        _ -> {CostList0, Award}
    end,
    IsBagFull = lib_goods_api:can_give_goods(Role, NewAward),
    IsCost = length([V||{_K,_T,V}<-CostList,V>0]),
    if
        Status =:= ?ACT_REWARD_HAS_GET ->
            {false, ?ERRCODE(err331_already_get_reward)};
        Status =:= 3 ->
            {false, ?ERRCODE(err331_act_overdue)};
        Status =:= 1 ->
            {false, ?ERRCODE(err331_award_not_due)};
        Lev < NeedLev ->
            {false, ?ERRCODE(err331_lv_unreach)};
        not IsBagFull ->
            {false, ?ERRCODE(err150_no_cell)};
        true ->
            case IsCost>0 of
                true->
                    % About = lib_custom_act_api:custom_act_consume_about(Type, SubType),
                    About = io_lib:format("type: ~w subtype: ~w grade: ~w", [Type, SubType, Grade]),
                    case lib_goods_api:cost_object_list_with_check(Role, CostList, custom_act_free_gift, About) of
                        {true, Role1,_} ->
                            {Role1, {NewAward, ActInfo}};
                        {false, ErrorCode, _Role1} ->
                            {false, ErrorCode}
                    end;
                _->
                    {Role,{NewAward,ActInfo}}
            end
    end.


act_award_status(AwardConfig, AwardList,#custom_act_personal{ e_time = ETime}) ->
    #custom_act_reward_cfg{grade = Grade, condition = Condition} = AwardConfig,
    CountDown = case lists:keyfind(count_down, 1, Condition) of
        {count_down, CountDown2} -> CountDown2;
        _ -> false
    end,
    Now = utime:unixtime(),
    case lists:keyfind(Grade, #custom_free_gift_award.award_id, AwardList) of
        #custom_free_gift_award{is_get = ?ACT_REWARD_HAS_GET} ->
            {2, 0};
        #custom_free_gift_award{time = Time} when (Now - Time) >= CountDown ->
            {4, 0};
        #custom_free_gift_award{time = Time} ->
            {1, Time + CountDown};
        false when Now >= ETime->
            {3, 0};
        _ ->
            {?ACT_REWARD_CAN_NOT_GET, ETime}
    end.

init_personal_act_data(_Role,_ActInfo)->
    [].


%% ---------------------------------------------------------------------------
%% @doc 活动派发接口：定制活动开启或者关闭 默认处理
notify_other_module(ActInfo) ->
    case ActInfo of
        #act_info{key={?CUSTOM_ACT_TYPE_FREE_GIFT,SubType},trigger_time = T} when T=:=1 ->
            db:execute(?delete_opening_custom_act_personal, [?CUSTOM_ACT_TYPE_FREE_GIFT, SubType]);
        _->
            ok
    end.

check_clean(Player,ActInfo)->
    case ActInfo of
        #act_info{key={?CUSTOM_ACT_TYPE_FREE_GIFT,SubType},trigger_time = T} when T=:=1 ->
           NPlayer = custom_act_personal:clear_personal_act_in_role(Player, ?CUSTOM_ACT_TYPE_FREE_GIFT, SubType),
           NPlayer;
        _->
           Player
    end.