%%%--------------------------------------
%%% @Module  : lib_capsule_toys
%%% @Author  : lhy
%%% @Created : 2019-04-11
%%% @Description:  超级扭蛋活动
%%%--------------------------------------
-module(lib_capsule_toys).
-include("server.hrl").
-include("figure.hrl").
-include("errcode.hrl").
-include("def_fun.hrl").
-include("def_module.hrl").
-include("predefine.hrl").
-include("common.hrl").
-include("custom_act.hrl").
-include("goods.hrl").
-include("def_goods.hrl").
-include("capsule_toys.hrl").

-export([
     reload/0                %% 配置改动，推送新配置给客户端
    ,get_capsule_toys_cfg/1  %% 获取后台配置
	,capsule_toys/4          %% 扭蛋寻宝
]).

reload() ->
    spawn(fun()-> reload_handle() end).

reload_handle() ->
    OnlineList = ets:tab2list(?ETS_ONLINE),
    [
        lib_player:apply_cast(PlayerId, ?APPLY_CAST_STATUS, ?MODULE, get_capsule_toys_cfg, [])
        ||#ets_online{id = PlayerId}<-OnlineList
    ].

get_capsule_toys_cfg(PS) ->
    #player_status{sid = Sid} = PS,
    KvIds = data_capsule_toys:get_kv_ids(),
    F1 = fun(Id, Acc) ->
        case data_capsule_toys:get_kv(Id) of
            [] ->
                Acc;
            {Key, Value} ->
                [{Id, util:term_to_string(Key), util:term_to_string(Value)} | Acc]
        end
    end,
    KvList = lists:foldl(F1, [], KvIds),
    AllRewardList = data_capsule_toys:get_ids_with_wlv(),
    F = fun({_LowerWlv, _UpperWlv, Id}, TmpList) ->
        case data_capsule_toys:get_capsule_toys_reward_cfg(Id)of
            #base_capsule_toys_reward{reward_type = Type, lower_wlv = LowerWlv, upper_wlv = UpperWlv,
                                      goods_num = GoodsNum, weight = Weight, rare = Rare} ->
                RewardList = data_capsule_toys:get_capsule_toys_rewards(Id),    %% ToDo
                [{Id, LowerWlv, UpperWlv, Type, util:term_to_string(RewardList), GoodsNum, Weight, Rare} | TmpList];
            _ ->
                TmpList
        end
    end,
    RewardCfgList = lists:foldl(F, [], AllRewardList),
    lib_server_send:send_to_sid(Sid, pt_331, 33150, [?CUSTOM_ACT_TYPE_ACT_CAPSULE_TOYS, KvList, RewardCfgList]).

capsule_toys(PS, SubType, DrawType, Wlv) ->
    CheckList = [{check_draw_type, DrawType}],
    case check_args(CheckList) of
    	true ->
            Times = ?IF(DrawType == 1, 1, 10),
            case DrawType of
                1 ->
                    #base_capsule_toys_constant{value = Cost} = data_capsule_toys:get_capsule_toys_constant_cfg(one),
                    Times = 1;
                2 ->
                    #base_capsule_toys_constant{value = Cost} = data_capsule_toys:get_capsule_toys_constant_cfg(ten),
                    Times = 10
            end,
    	    case lib_goods_api:cost_object_list_with_check(PS, Cost, capsule_toys, "") of
    	    	{true, NewPS,_} ->
    	    		do_capsule_toys(NewPS, Wlv, Times, DrawType, SubType, Cost);
    	    	{false, ErrCode, _NewPS} ->
    	    	    {false, ErrCode}
    	    end;
    	{false, ErrCode} ->
    	    {false, ErrCode}
    end.

do_capsule_toys(PS, Wlv, Times, DrawType, SubType, Cost) ->
    #player_status{figure = #figure{career = Career}} = PS,
    AllRewardList = data_capsule_toys:get_ids_with_wlv(),
    F = fun({LowerWlv, UpperWlv, Id}, WeightList) ->
    	if
    		Wlv >= LowerWlv andalso Wlv =< UpperWlv ->
    			case data_capsule_toys:get_capsule_toys_reward_cfg(Id)of
    				#base_capsule_toys_reward{weight = Weight} ->
    					[{Weight, Id} | WeightList];
    				_ ->
    				    WeightList
    			end;
    		true ->
    		    WeightList
    	end
    end,
    WeightList = lists:foldl(F, [], AllRewardList),
    {RewardList, BroadcastList} = do_capsule_toys_core(Career, Times, WeightList, [], []),
    %% 日志
    lib_log_api:log_capsule_toys(PS#player_status.id, ?CUSTOM_ACT_TYPE_ACT_CAPSULE_TOYS, SubType, Wlv, DrawType, RewardList, Cost),
    Produce = #produce{type = capsule_toys, reward = RewardList, show_tips = 1,
                               title = utext:get(3310041), content = utext:get(3310042)},
    {ok, NewPS} = lib_goods_api:send_reward_with_mail(PS, Produce, ?MOD_AC_CUSTOM),
    F2 = fun({_, GoodsTypeId, _Num}) ->
    		#ets_goods_type{goods_name = _GoodsName, color = _Color} = data_goods_type:get(GoodsTypeId)
            % lib_chat:send_TV({all}, ?MOD_AC_CUSTOM, 8, [NewPS#player_status.figure#figure.name, Color, GoodsName, Num])
    end,
    lists:foreach(F2, BroadcastList),
    {true, RewardList, NewPS}.

do_capsule_toys_core(_Career, 0, _WeightList, RewardList, BroadcastList) -> {RewardList, BroadcastList};
do_capsule_toys_core(Career, Times, WeightList, RewardList, BroadcastList) ->
    case urand:rand_with_weight(WeightList) of
    	false ->
            ?ERR("capsule toys weight rand null~n", []),
            do_capsule_toys_core(Career, Times - 1, WeightList, RewardList, BroadcastList);
    	Id ->
    		case data_capsule_toys:get_capsule_toys_reward_cfg(Id) of
    			#base_capsule_toys_reward{reward_type = RewardType, broadcast = 1} ->
                    Rewards = data_capsule_toys:get_capsule_toys_rewards(Id),   %% ToDo
                    Tmp = do_get_reward(Career, RewardType, Rewards),
    			    do_capsule_toys_core(Career, Times - 1, WeightList, Tmp ++ RewardList, Tmp ++ BroadcastList);
                #base_capsule_toys_reward{reward_type = RewardType, broadcast = 0} ->
                    Rewards = data_capsule_toys:get_capsule_toys_rewards(Id),   %% ToDo
                    Tmp = do_get_reward(Career, RewardType, Rewards),
                    do_capsule_toys_core(Career, Times - 1, WeightList, Tmp ++ RewardList, BroadcastList);
    			_ ->
    			    do_capsule_toys_core(Career,Times - 1, WeightList, RewardList, BroadcastList)
    		end
    end.

do_get_reward(Career, RewardType, Rewards) ->
    case RewardType of
        5 ->
            case lists:keyfind(Career, 1, Rewards) of
                false ->
                    [];
                {_, RewardList} ->
                    RewardList
            end;
        1 ->
            Rewards;
        _ ->
            []
    end.

%% ------------------------------------- check function --------------------------------
check_args([]) -> true;
check_args([H | T]) ->
    case do_check(H) of
    	true ->
    		check_args(T);
    	{false, ErrCode} ->
    	    {false, ErrCode}
    end.

%% 检查寻宝类型
do_check({check_draw_type, DrawType}) ->
    case DrawType of
    	1 ->
    		case data_capsule_toys:get_capsule_toys_constant_cfg(one) of
                #base_capsule_toys_constant{} ->
                    true;
                _ ->
                    {false, ?ERRCODE(missing_config)}
            end;
    	2 ->
    	    case data_capsule_toys:get_capsule_toys_constant_cfg(ten) of
                #base_capsule_toys_constant{} ->
                    true;
                _ ->
                    {false, ?ERRCODE(missing_config)}
            end;
    	_ ->
    	    {false, ?ERRCODE(err430_args_type_error)}
    end.
