%%%-------------------------------------------------------------------
%%% @author liushl
%%% @doc
%%%     式神抽奖
%%% @end
%%%-------------------------------------------------------------------
-module(god_lottery).
-author("liushl").

-behaviour(gen_server).

-include("common.hrl").
-include("god.hrl").
-include("def_goods.hrl").
-include("errcode.hrl").
-include("def_module.hrl").
-include("goods.hrl").
%% API
-export([
    start_link/0,
    ask_limit_lottery_info/1,
    ask_lottery/1,
    lottery/3,
    counts_award/2,
    blessing_award/2
]).

%% gen_server callbacks
-export([init/1,
    handle_call/3,
    handle_cast/2,
    handle_info/2,
    terminate/2,
    code_change/3]).

-define(SERVER, ?MODULE).

%% 唤神抽奖
-record(state, {
    limit_lottery = []       % 限时抽奖
}).

-record(limit_lottery_info, {
    phase = 1,              % 期数
    begin_time = 0,         % 开始时间
    end_time = 0,           % 结束时间
    ref = [],               % 活动切换倒计时
    role_lottery = []       % 玩家参与情况
}).

-record(limit_lottery_role, {
    role_id = 0,            % 玩家id
    counts = 0,             % 已抽奖次数
    blessing = 0,           % 祝福值
    counts_award = [],      % 保底奖励领奖情况
    bless_award = [],       % 祝福领取
    time = 0                % 操作时间
}).

%%%===================================================================
%%% 外部API
%%%===================================================================
%% 活动信息
ask_limit_lottery_info(RoleId) ->
    gen_server:cast(?MODULE, {ask_limit_lottery_info, RoleId}).
%% 当前期数
ask_lottery(RoleId) ->
    gen_server:call(?MODULE, {ask_lottery, RoleId}).
%% 抽奖
lottery(RoleId, AddCounts, AddBlessing) ->
    gen_server:cast(?MODULE, {lottery, RoleId, AddCounts, AddBlessing}).
%% 领取次数奖励
counts_award(RoleId, AwardId) ->
    gen_server:cast(?MODULE, {get_counts_award, RoleId, AwardId}).
%% 领取祝福值奖励
blessing_award(RoleId, Stage) ->
    gen_server:cast(?MODULE, {get_blessing_award, RoleId, Stage}).

%%--------------------------------------------------------------------
%% @doc
%% Starts the server
%%
%% @end
%%--------------------------------------------------------------------
-spec(start_link() ->
    {ok, Pid :: pid()} | ignore | {error, Reason :: term()}).
start_link() ->
    gen_server:start_link({local, ?SERVER}, ?MODULE, [], []).

%%%===================================================================
%%% gen_server callbacks
%%%===================================================================

%%--------------------------------------------------------------------
%% @private
%% @doc
%% Initializes the server
%%
%% @spec init(Args) -> {ok, State} |
%%                     {ok, State, Timeout} |
%%                     ignore |
%%                     {stop, Reason}
%% @end
%%--------------------------------------------------------------------
-spec(init(Args :: term()) ->
    {ok, State :: #state{}} | {ok, State :: #state{}, timeout() | hibernate} |
    {stop, Reason :: term()} | ignore).
init([]) ->
    #limit_lottery_info{phase = LimitPhase} = LotteryInfo = calc_phase(),
    %% 加载玩家限时召唤数据
    RoleInfo =
    [begin
        NBlessAward0 = util:to_term(BlessAward),
        NBlessAward = case NBlessAward0 == [] of
                          true ->
                              calc_bless_award(LimitPhase, NBlessAward0, Blessing);
                          _ ->
                              NBlessAward0
                      end,
        #limit_lottery_role{
            role_id = RoleId,            % 玩家id
            counts = Counts,             % 已抽奖次数
            blessing = Blessing,           % 祝福值
            counts_award = util:to_term(CountsAward),      % 进度奖励领奖情况
            bless_award = NBlessAward
        }
    end || [RoleId, Counts, Blessing, CountsAward, BlessAward] <- db_get_lottery_role()],
    LimitLotteryInfo = LotteryInfo#limit_lottery_info{role_lottery = RoleInfo},
    {ok, #state{limit_lottery = LimitLotteryInfo}}.

%% 初始化，计算当前是第几期
calc_phase() ->
    ConfigTime = data_god:get_kv(lottery_call_startime),
    Config = data_god:get_all_limit_lottery_phase(),
    Original = utime:unixtime({ConfigTime, {0, 0, 0}}),
    Now = utime:unixtime(),
    %% 保证配置的正确
    case Config of
        [{_, _} | _] when Now + 10 >= Original ->
            %% 计算一个循环的时间
            RoundTime = lists:sum([Day || {_, Day} <- Config]) * 86400,
            %% 以距离现在最近的一个循环时间开始作为起始进行计算
            CheckTime = umath:floor((Now - Original) / RoundTime) * RoundTime + Original,
            case calc_phase(CheckTime, Now, Config, Config) of
                {Phase, BeginTime, EndTime, LeftTime} ->
                    Ref = erlang:send_after(LeftTime * 1000, self(), next_limit_phase),
                    #limit_lottery_info{phase = Phase, begin_time = BeginTime, end_time = EndTime - 1, ref = Ref};
                _ ->
                    #limit_lottery_info{}
            end;
        _ ->
            #limit_lottery_info{}
    end.
calc_phase(_BeginTime, _Now, [], _Config) ->   %% 配置读完了都没找到
    false;
calc_phase(BeginTime, Now, [{Phase, Days} | T], Config) ->
    EndTime = BeginTime + Days * 86400,
    if
        Now < BeginTime -> false; % 有问题，不开
        Now > EndTime -> % 继续判断下一期, 这一期的结束时间作为下一期的开始时间
            calc_phase(EndTime, Now, T, Config);
        true -> % 正好在活动期内
            {Phase, BeginTime, EndTime, EndTime - Now}
    end.
%%--------------------------------------------------------------------
%% @private
%% @doc
%% Handling call messages
%%
%% @end
%%--------------------------------------------------------------------
-spec(handle_call(Request :: term(), From :: {pid(), Tag :: term()},
        State :: #state{}) ->
    {reply, Reply :: term(), NewState :: #state{}} |
    {reply, Reply :: term(), NewState :: #state{}, timeout() | hibernate} |
    {noreply, NewState :: #state{}} |
    {noreply, NewState :: #state{}, timeout() | hibernate} |
    {stop, Reason :: term(), Reply :: term(), NewState :: #state{}} |
    {stop, Reason :: term(), NewState :: #state{}}).
handle_call(Request, From, State) ->
    try
        do_handle_call(Request, From, State)
    catch ?EXCEPTION(_ErrClass, _ErrReason, _Stacktrace) ->
        ?ERR("handle_call Request:~w, Error:~w", [Request, {_ErrClass, _ErrReason, ?GET_STACK(_Stacktrace)}]),
        {reply, error, State}
    end.
do_handle_call({ask_lottery, RoleId}, _From, State) ->
    LimitLottery = State#state.limit_lottery,
    #limit_lottery_info{phase = Phase, role_lottery = RoleInfo} = LimitLottery,
    case lists:keyfind(RoleId, #limit_lottery_role.role_id, RoleInfo) of
        #limit_lottery_role{counts = Counts, blessing = Blessing} ->
            ok;
        _ -> Counts = 0, Blessing = 0
    end,
    {reply, [Phase, Counts, Blessing], State};

do_handle_call(Request, _From, State) ->
    io:format("module:~p: handle_call unexpect message:~p~n", [?MODULE, Request]),
    {reply, ok, State}.

%% 保底奖励领取条件检查
check_counts_award(RoleId, AwardId, Phase, RoleLottery) ->
    case lists:keyfind(RoleId, #limit_lottery_role.role_id, RoleLottery) of
        false -> {false, ?ERRCODE(err173_not_enough_times)};
        Role ->
            Role = lists:keyfind(RoleId, #limit_lottery_role.role_id, RoleLottery),
            #limit_lottery_role{counts = Counts, counts_award = CountsAward} = Role,
            if
                CountsAward =:= [] -> MaxId = 0;
                true -> MaxId = lists:max(CountsAward)
            end,
            Config = data_god:get_god_lottery_phase(Phase),
            case lists:member(AwardId, CountsAward) of
                false when Phase > 0 andalso is_record(Role, limit_lottery_role) andalso is_record(Config, base_god_limit_phase) andalso (MaxId + 1) =:= AwardId ->
                    #base_god_limit_phase{count_award = CountConfig} = Config,
                    AwardConfig = lists:keyfind(AwardId, 1, CountConfig),
                    if
                        AwardConfig =:= false ->
                            {false, ?ERRCODE(err173_error_config)};
                        true ->
                            {_, NeedCounts, Award} = AwardConfig,
                            if
                                Counts >= NeedCounts ->
                                    %%如果都领完,重置
                                    case calc_finish([AwardId | CountsAward], CountConfig) of
                                        true ->
                                            NewCounts = Counts - calc_max_counts(0, CountConfig),
                                            NewCountsAward = [];
                                        _ ->
                                            NewCounts = Counts,
                                            NewCountsAward = [AwardId | CountsAward]
                                    end,
                                    {ok, Config#base_god_limit_phase.god_id, Award, Role#limit_lottery_role{counts = NewCounts, counts_award = NewCountsAward}};
                                true ->
                                    {false, ?ERRCODE(err173_not_enough_times)}
                            end
                    end;
                true -> {false, ?ERRCODE(err173_have_receive)};
                _ -> {false, ?ERRCODE(err173_error_config)}
            end
    end.

%% 祝福值奖励领取条件检查
check_blessing_award(RoleId, Stage, Phase, RoleLottery) ->
    Config = data_god:get_god_lottery_phase(Phase),
    case lists:keyfind(RoleId, #limit_lottery_role.role_id, RoleLottery) of
        false ->
            {false, ?ERRCODE(err173_not_enough_times)};
        Role when is_record(Config, base_god_limit_phase)->
            Role = lists:keyfind(RoleId, #limit_lottery_role.role_id, RoleLottery),
            #limit_lottery_role{blessing = Blessing, bless_award = BlessAward} = Role,
            #base_god_limit_phase{blessing_award = BlessAwards, god_id = GodId} = Config,
            State = case lists:keyfind(Stage, 1, BlessAward) of
                        {_, S} ->
                            S;
                        _ ->
                            0
                    end,
            case lists:keyfind(Stage, 1, BlessAwards) of
                {_, BlessCount, Award} ->
                    ok;
                _ ->
                    {BlessCount = 0, Award = []}
            end,
            case State of
                1 when Blessing >= BlessCount andalso Phase > 0 andalso is_record(Role, limit_lottery_role) ->
                    NewBlessAward = lists:keystore(Stage, 1, BlessAward, {Stage, 2}),
                    {ok, GodId, Award, Role#limit_lottery_role{bless_award = NewBlessAward}, BlessCount};
                0 ->
                    {false, ?ERRCODE(err173_not_enough_times)};
                2 ->
                    {false, ?ERRCODE(err173_have_receive)};
                _ ->
                    {false, ?ERRCODE(err173_error_config)}
            end;
        _ ->
            {false, ?ERRCODE(missing_config)}
    end.


%%--------------------------------------------------------------------
%% @private
%% @doc
%% Handling cast messages
%%
%% @end
%%--------------------------------------------------------------------
-spec(handle_cast(Request :: term(), State :: #state{}) ->
    {noreply, NewState :: #state{}} |
    {noreply, NewState :: #state{}, timeout() | hibernate} |
    {stop, Reason :: term(), NewState :: #state{}}).
handle_cast(Msg, State) ->
    try
        do_handle_cast(Msg, State)
    catch ?EXCEPTION(_ErrClass, _ErrReason, _Stacktrace) ->
        ?ERR("handle_cast Msg:~w, Error:~w", [Msg, {_ErrClass, _ErrReason, ?GET_STACK(_Stacktrace)}]),
        {noreply, State}
    end.

do_handle_cast({ask_limit_lottery_info, RoleId}, State) ->
    #state{limit_lottery = LimitLottery} = State,
    #limit_lottery_info{phase = Phase, role_lottery = RoleLottery, begin_time = BeginTime, end_time = EndTime} = LimitLottery,
    RoleInfo =
        case lists:keyfind(RoleId, #limit_lottery_role.role_id, RoleLottery) of
            #limit_lottery_role{} = One -> One;
            _ -> #limit_lottery_role{bless_award = calc_bless_award(Phase, [], 0)}
        end,
    #limit_lottery_role{counts = Counts, blessing = Blessing, counts_award = CountsAward, bless_award = BlessAward} = RoleInfo,
    Info = [Phase, BeginTime, EndTime, Counts, Blessing, BlessAward, CountsAward],
    lib_server_send:send_to_uid(RoleId, pt_173, 17315, Info),
    {noreply, State};

%% 玩家抽奖
do_handle_cast({lottery, RoleId, AddCounts, AddBlessing}, State) ->
    LimitLottery = State#state.limit_lottery,
    RoleInfo = LimitLottery#limit_lottery_info.role_lottery,
    NowPhase = LimitLottery#limit_lottery_info.phase,
    case lists:keyfind(RoleId, #limit_lottery_role.role_id, RoleInfo) of
        #limit_lottery_role{counts = Counts, blessing = Blessing, bless_award = BlessAward} = One ->
            NBlessAward = calc_bless_award(NowPhase, BlessAward, Blessing + AddBlessing),
            NewOne = One#limit_lottery_role{counts = Counts + AddCounts, bless_award = NBlessAward, blessing = Blessing + AddBlessing},
            NewRoleInfo = lists:keyreplace(RoleId, #limit_lottery_role.role_id, RoleInfo, NewOne);
        _ ->
            NBlessAward = calc_bless_award(NowPhase, [], AddBlessing),
            NewOne = #limit_lottery_role{role_id = RoleId, counts = AddCounts, bless_award = NBlessAward, blessing = AddBlessing},
            NewRoleInfo = [NewOne | RoleInfo]
    end,
    db_save_lottery_role(NewOne),
    NewLimitLottery = LimitLottery#limit_lottery_info{role_lottery = NewRoleInfo},
    {noreply, State#state{limit_lottery = NewLimitLottery}};

%% 领取保底奖励
do_handle_cast({get_counts_award, RoleId, AwardId}, State) ->
    #state{limit_lottery = LimitLottery} = State,
    #limit_lottery_info{phase = Phase, role_lottery = RoleLottery} = LimitLottery,
    case check_counts_award(RoleId, AwardId, Phase, RoleLottery) of
        {false, Err} ->
            lib_server_send:send_to_uid(RoleId, pt_173, 17317, [Err, AwardId]),
            {noreply, State};
        {ok, GodId, Award, NewRole} ->
            #limit_lottery_role{blessing = Blessing, counts = Counts} = NewRole,
            NewRoleLottery = lists:keyreplace(RoleId, #limit_lottery_role.role_id, RoleLottery, NewRole),
            db_save_lottery_role(NewRole),
            god_logic:log_god_lottery([RoleId, Phase, GodId, 4, 0, Blessing, Counts, [{award_id, AwardId}], Award]),
            Produce = #produce{reward = Award, type = god_lottery_counts_award},
            ?INFO("Award ~p", [Award]),
            lib_goods_api:send_reward_with_mail(RoleId, Produce, ?MOD_GOD),
            NewLimitLottery = LimitLottery#limit_lottery_info{role_lottery = NewRoleLottery},
            lib_server_send:send_to_uid(RoleId, pt_173, 17317, [?SUCCESS, AwardId]),
            {noreply, State#state{limit_lottery = NewLimitLottery}}
    end;
%% 领取累计奖励
do_handle_cast({get_blessing_award, RoleId, Stage}, State) ->
    LimitLottery = State#state.limit_lottery,
    RoleLottery = LimitLottery#limit_lottery_info.role_lottery,
    Phase = LimitLottery#limit_lottery_info.phase,
    case check_blessing_award(RoleId, Stage, Phase, RoleLottery) of
        {false, Err} ->
            lib_server_send:send_to_uid(RoleId, pt_173, 17318, [Err, Stage]),
            {noreply, State};
        {ok, GodId, Award, NewRole, NeedBlessing} ->
            #limit_lottery_role{blessing = Blessing, counts = Counts} = NewRole,
            NewRoleLottery = lists:keyreplace(RoleId, #limit_lottery_role.role_id, RoleLottery, NewRole),
            db_save_lottery_role(NewRole),
            god_logic:log_god_lottery([RoleId, Phase, GodId, 3, 0, Blessing, Counts, [{blessing, NeedBlessing}], Award]),
            Produce = #produce{reward = Award, type = god_lottery_blessing_award},
            lib_goods_api:send_reward_with_mail(RoleId, Produce, ?MOD_GOD),
            NewLimitLottery = LimitLottery#limit_lottery_info{role_lottery = NewRoleLottery},
            lib_server_send:send_to_uid(RoleId, pt_173, 17318, [?SUCCESS, Stage]),
            {noreply, State#state{limit_lottery = NewLimitLottery}}
    end;

do_handle_cast(_Request, State) ->
    io:format("module:~p: handle_cast unexpect message:~p~n", [?MODULE, _Request]),
    {noreply, State}.

%%--------------------------------------------------------------------
%% @private
%% @doc
%% Handling all non call/cast messages
%%
%% @spec handle_info(Info, State) -> {noreply, State} |
%%                                   {noreply, State, Timeout} |
%%                                   {stop, Reason, State}
%% @end
%%--------------------------------------------------------------------
-spec(handle_info(Info :: timeout() | term(), State :: #state{}) ->
    {noreply, NewState :: #state{}} |
    {noreply, NewState :: #state{}, timeout() | hibernate} |
    {stop, Reason :: term(), NewState :: #state{}}).
handle_info(Info, State) ->
    try
        do_handle_info(Info, State)
    catch ?EXCEPTION(_ErrClass, _ErrReason, _Stacktrace) ->
        ?ERR("handle_info Info:~w, Error:~w", [Info, {_ErrClass, _ErrReason, ?GET_STACK(_Stacktrace)}]),
        {noreply, State}
    end.

do_handle_info(next_limit_phase, State) ->
    #state{limit_lottery = LimitLottery} = State,
    #limit_lottery_info{phase = Phase, role_lottery = RoleLottery} = LimitLottery,
    case data_god:get_god_lottery_phase(Phase) of
        #base_god_limit_phase{count_award = CountAwards, blessing_award = BlessAwards} ->
            skip;
        _ ->
            CountAwards = BlessAwards = []
    end,
    %%发送玩家未领取奖励
    seng_all_award(RoleLottery, CountAwards, BlessAwards),
    %% 先停止本期活动
    notice_phase(),
    db_del_limit_lottery_role(),
    NextLottery =
        case data_god:get_god_lottery_phase(Phase + 1) of
            #base_god_limit_phase{} = One -> One;
            _ ->
                case data_god:get_god_lottery_phase(1) of
                    #base_god_limit_phase{} = One -> One;
                    _ -> false
                end
        end,
    case NextLottery of
        #base_god_limit_phase{phase = NextPhase, days = Days} ->
            BeginTime = LimitLottery#limit_lottery_info.end_time + 1,
            EndTime = BeginTime + Days * 86400,
            Ref = erlang:send_after((EndTime - BeginTime) * 1000, self(), next_limit_phase),
            NewLimitLottery = #limit_lottery_info{phase = NextPhase, begin_time = BeginTime, end_time = EndTime - 1, role_lottery = [], ref = Ref},
            NewState = State#state{limit_lottery = NewLimitLottery},
            {noreply, NewState};
        _ ->
            ?ERR("lottery no config"),
            NewLimitLottery = #limit_lottery_info{},
            NewState = State#state{limit_lottery = NewLimitLottery},
            {noreply, NewState}
    end;
do_handle_info(_Info, State) ->
    ?ERR("module:~p: handle_info unexpect message:~p~n", [?MODULE, _Info]),
    {noreply, State}.

%%--------------------------------------------------------------------
%% @private
%% @doc
%% This function is called by a gen_server when it is about to
%% terminate. It should be the opposite of Module:init/1 and do any
%% necessary cleaning up. When it returns, the gen_server terminates
%% with Reason. The return value is ignored.
%%
%% @spec terminate(Reason, State) -> void()
%% @end
%%--------------------------------------------------------------------
-spec(terminate(Reason :: (normal | shutdown | {shutdown, term()} | term()),
        State :: #state{}) ->
    term()).
terminate(_Reason, _State) ->
    ok.

%%--------------------------------------------------------------------
%% @private
%% @doc
%% Convert process state when code is changed
%%
%% @spec code_change(OldVsn, State, Extra) -> {ok, NewState}
%% @end
%%--------------------------------------------------------------------
-spec(code_change(OldVsn :: term() | {down, term()}, State :: #state{},
        Extra :: term()) ->
    {ok, NewState :: #state{}} | {error, Reason :: term()}).
code_change(_OldVsn, State, _Extra) ->
    {ok, State}.

%%%===================================================================
%%% Internal functions
%%%===================================================================
%%活动变更
notice_phase() ->
    {ok, Bin} = pt_173:write(17320, [2]),
    lib_server_send:send_to_all(Bin).
db_get_lottery_role() ->
    Sql = io_lib:format(<<"select role_id,counts,blessing,counts_award,bless_award from god_lottery_role">>, []),
    db:get_all(Sql).
db_save_lottery_role(LotteryRole) ->
    #limit_lottery_role{
        role_id = RoleId,            % 玩家id
        counts = Counts,             % 已抽奖次数
        blessing = Blessing,           % 祝福值
        counts_award = CountsAward,      % 进度奖励领奖情况
        bless_award = BlessAward
    } = LotteryRole,
    Sql = io_lib:format(<<"replace into god_lottery_role(role_id,counts,blessing,counts_award,bless_award,time) values(~p,~p,~p,'~ts','~ts',~p)">>, [
        RoleId, Counts, Blessing, util:term_to_bitstring(CountsAward), util:term_to_bitstring(BlessAward), utime:unixtime()]),
    db:execute(Sql).
db_del_limit_lottery_role() ->
    db:execute(<<"truncate god_lottery_role">>).


calc_finish(_CountsAward, []) ->
    true;
calc_finish(CountsAward, [{Stage, _, _} | T]) ->
    case lists:member(Stage, CountsAward) of
        false ->
            false;
        _ ->
            calc_finish(CountsAward, T)
    end.

calc_max_counts(MaxCounts, []) ->
    MaxCounts;
calc_max_counts(MaxCounts, [{_, Counts, _} | T]) ->
    case MaxCounts > Counts of
        true ->
            calc_max_counts(MaxCounts, T);
        _ ->
            calc_max_counts(Counts, T)
    end.

%%计算奖励
calc_bless_award(Phase, BlessAward, Bless) ->
    BlessingAward =
    case data_god:get_god_lottery_phase(Phase) of
        #base_god_limit_phase{blessing_award = Awares} ->
            Awares;
        _ ->
            []
    end,
    calc_bless_award2(BlessAward, Bless, BlessingAward).

calc_bless_award2(BlessAward, _, []) ->
    BlessAward;
calc_bless_award2(BlessAward, Bless, [{Stage, Max, _} | T]) ->
    case lists:keyfind(Stage, 1, BlessAward) of
        {_, S} when S >= 2 ->
            calc_bless_award2(BlessAward, Bless, T);
        {_, S} when S >= 1 ->
            calc_bless_award2(BlessAward, Bless, T);
        _ ->
            case Bless >= Max of
                true ->
                    NBlessAward = lists:keystore(Stage, 1, BlessAward, {Stage, 1}),
                    calc_bless_award2(NBlessAward, Bless, T);
                _ ->
                    NBlessAward = lists:keystore(Stage, 1, BlessAward, {Stage, 0}),
                    calc_bless_award2(NBlessAward, Bless, T)
            end
    end.

%%发送未领取奖励
seng_all_award([], _CountsAwards, _BlessAwards) ->
    ok;
seng_all_award([#limit_lottery_role{role_id = RoleId, counts = Counts, counts_award = CountAward, bless_award = BlessAward} = _Info | T], CountsAwards, BlessAwards) ->
    NewBlessAwards = calc_unclaimed_blessing_award(BlessAwards, BlessAward, []),
    NewCountAwards = calc_unclaimed_count_award(Counts, CountAward, CountsAwards, []),
    %%已完成但未领取的直接发背包
    NewBlessAwards =/= [] andalso lib_goods_api:send_reward_by_id(NewBlessAwards, god_lottery_blessing_award, RoleId),
    NewCountAwards =/= [] andalso lib_goods_api:send_reward_by_id(NewCountAwards, god_lottery_counts_award, RoleId),
    seng_all_award(T, CountsAwards, BlessAwards).

calc_unclaimed_blessing_award(_BlessAward, [], Awards) ->
    Awards;
calc_unclaimed_blessing_award(BlessAward, [{Stage, State} | T], Awards) ->
    if
        State =:= 1 ->
            case lists:keyfind(Stage, 1, BlessAward) of
                {_, _, Award} ->
                    ok;
                _ ->
                    Award = []
            end,
            calc_unclaimed_blessing_award(BlessAward, T, Award ++ Awards);
        true -> calc_unclaimed_blessing_award(BlessAward, T, Awards)
    end.

calc_unclaimed_count_award(_Counts, _CountAward, [], Awards) ->
    Awards;
calc_unclaimed_count_award(Counts, CountAward, [{Stage, Num, Award} | T], Awards) ->
    case lists:member(Stage, CountAward) of
        true ->
            calc_unclaimed_count_award(Counts, CountAward, T, Awards);
        _ ->
            if
                Counts >= Num -> calc_unclaimed_count_award(Counts, CountAward, T, Award ++ Awards);
                true -> calc_unclaimed_count_award(Counts, CountAward, T, Awards)
            end
    end.
