%%%-------------------------------------------------------------------
%%% @author liushl
%%% @doc
%%%     基于商品类型处理
%%% @end
%%%-------------------------------------------------------------------
-module(recharge_router).
-author("liushl").

-include ("rec_recharge.hrl").
-include ("def_recharge.hrl").
-include ("server.hrl").
-include ("common.hrl").
%% API
-export([
    get_charge_module/1
    ,deal_with_by_type/3             %% 按类型处理商品
    ,deal_with_associate_product/3   %% 按类型处理触发关联商品
]).

%% 商品处理模块
get_charge_module(ProductType) ->
    case ProductType of
        ?PRODUCT_TYPE_NORMAL        -> lib_recharge;           %% 普通充值
        ?PRODUCT_TYPE_WELFARE       -> lib_recharge_welfare;   %% 福利卡购买
        ?PRODUCT_TYPE_FIRST_GIFT    -> lib_recharge_first;     %% 首充
        _ -> undefined
    end.

get_function_handler(ProductCfg, Func_Arg) ->
    Mod = get_charge_module(ProductCfg#base_recharge_product.product_type),
    case Mod =/= undefined of
        true  ->
            case lists:member(Func_Arg, Mod:module_info(exports)) of
                true  ->
                    Mod;
                false ->
                    false
            end;
        false ->
            lib_recharge
    end.

%% 按类型处理商品
deal_with_by_type(Player, ProductCfg, PayNo) ->
    case get_function_handler(ProductCfg, {deal_with_charge, 3}) of
        false ->
            Player;
        Mod ->
            case Mod:deal_with_charge(Player, ProductCfg, PayNo) of
                {ok, NewPlayer} ->
                    NewPlayer;
                Other ->
                    ?ERR("deal_with_by_type, bad return :~p~n", [Other]),
                    Player
            end
    end.

%% 按类型处理触发关联商品
deal_with_associate_product(Player, [], _) -> {ok, Player};
deal_with_associate_product(Player, [{ProductType, ProductId}|T], ProductCfg) ->
    case get_charge_module(ProductType) of
        undefined ->
            ?ERR("handle_associate_product:~p~n", [ProductType]),
            deal_with_associate_product(Player, T, ProductCfg);
        Module ->
            case catch Module:handle_product(Player, ProductId, ProductCfg) of
                {ok, NewPlayer} when is_record(NewPlayer, player_status) ->
                    deal_with_associate_product(NewPlayer, T, ProductCfg);
                Error ->
                    ?ERR("handle_associate_product:~p~n", [Error]),
                    deal_with_associate_product(Player, T, ProductCfg)
            end
    end.