%%%--------------------------------------
%%% @Module  : lib_draw_record_mod_local.erl
%%% @Author  : lhy
%%% @Created : 2019-05-29
%%% @Description:  定制活动抽奖记录
%%%--------------------------------------

-module(lib_draw_record_mod_local).
-include("custom_act.hrl").
-include("figure.hrl").
-include("predefine.hrl").
-include("role.hrl").
-include("server.hrl").
-include("custom_act_draw_record.hrl").
-include("goods.hrl").
-include("common.hrl").

-export([
	     init/0   %%

	    ,refresh_draw_reward_record/2     %% 刷新记录
	    ,send_draw_reward_record/5        %% 发送记录
        ,act_end/3
]).

init() ->
    List2 = db_draw_reward_record_select(),
    %% 初始化玩家许愿记录
    DrawRecordList = [lib_draw_record:make_record(draw_role,
                      [Type, SubType, RoleId, GradeId, Time]) || [Type, SubType, RoleId, GradeId, Time] <- List2],
    F2 = fun(DrawRecord, Maps) ->
        do_init(DrawRecord, Maps)
    end,
    DrawMaps = lists:foldl(F2, #{}, DrawRecordList),
    #draw_record_state{draw_maps = DrawMaps}.

do_init(DrawRecord, Maps) ->
    #draw_role{type = Type, sub_type = SubType, grade_id = GradeId} = DrawRecord,
    case lib_draw_record_api:get_record_config_local(Type, SubType, GradeId) of
        true ->
            TmpL = maps:get({Type, SubType}, Maps, []),
            LengthLimit = lib_draw_record_api:get_upper_limit_length(Type, SubType),
            if
                length(TmpL) >= LengthLimit ->
                     Maps;
                true ->
                    NewList = [DrawRecord | lists:reverse(TmpL)],
                %    maps:put({Type, SubType}, NewList, Maps)
                    maps:put({Type, SubType}, lists:reverse(NewList), Maps)
            end;
        false ->
            Maps
    end.

%% 刷新记录
refresh_draw_reward_record(DrawRecord, State) ->
    #draw_record_state{draw_maps = DrawMaps} = State,
    #draw_role{type = Type, sub_type = SubType} = DrawRecord,
    case maps:get({Type, SubType}, DrawMaps, false) of
        false -> TmpList = [DrawRecord];
        TmpL ->  TmpList = [DrawRecord | TmpL]
    end,
    NewList = lists:sublist(TmpList, lib_draw_record_api:get_upper_limit_length(Type, SubType)),
    NewDrawMaps = maps:put({Type, SubType}, NewList, DrawMaps),
    NewState = State#draw_record_state{draw_maps = NewDrawMaps},
    NewState.

%% 发送记录
send_draw_reward_record(RoleId, Type, SubType, PersonalRecords, State) ->
    #draw_record_state{draw_maps = DrawMaps} = State,
    case maps:get({Type, SubType}, DrawMaps, false) of
    	false ->
    		AllDrawRecordList = [];
    	AllDrawRecordList ->
    	    skip
    end,
    List1 = pack_gift_record(false, PersonalRecords, []),
    List2 = pack_gift_record(true, AllDrawRecordList, []),
    {ok, BinData} = pt_332:write(33210, [Type, SubType, RoleId, List1, List2]),
    lib_server_send:send_to_uid(RoleId, BinData).

pack_gift_record(_NameFlag, [], List) -> List;
pack_gift_record(NameFlag, [DrawRecord| L], List) ->
    case DrawRecord of
        #draw_role{type = Type, sub_type = SubType, role_id = RoleId, grade_id = GradeId, time = Time} when NameFlag == true ->
            case lib_role:get_role_show(RoleId) of
                #ets_role_show{figure = #figure{name = Name}} ->
                    skip;
                _ ->
                    ?PRINT("no name~n", []),
                    Name = ""
            end,
            case get_grade_reward(Type, SubType, GradeId) of
                {true, Reward} ->
                    pack_gift_record(NameFlag, L, [{Name, Reward, Time} | List]);
                _ ->
                    pack_gift_record(NameFlag, L, List)
            end;
        #draw_role{type = Type, sub_type = SubType, grade_id = GradeId, time = Time} when NameFlag == false ->
            case get_grade_reward(Type, SubType, GradeId) of
                {true, Reward} ->
                    pack_gift_record(NameFlag, L, [{Reward, Time} | List]);
                _ ->
                    pack_gift_record(NameFlag, L, List)
            end;
        _ ->
            pack_gift_record(NameFlag, L, List)
    end.

get_grade_reward(Type, SubType, GradeId) ->
    case lib_custom_act_util:get_act_reward_cfg_info(Type, SubType, GradeId) of
        #custom_act_reward_cfg{reward = Reward} ->
            {true, Reward};
        _ ->
            false
    end.

act_end(Type, SubType, State) ->
    #draw_record_state{draw_maps = DrawMaps} = State,
    ActList = lib_draw_record_api:get_local_act_list(),
    case lists:member(Type, ActList) of
        false ->
            State;
        true ->
            spawn(fun()-> db_draw_record_delete(Type, SubType) end),
            OnlineList = ets:tab2list(?ETS_ONLINE),
            IdList = [[PlayerId, draw_record_local, Type, SubType] || #ets_online{id = PlayerId}<-OnlineList],
            lists:foreach(fun do_act_end/1, IdList),
            NewDrawMaps = maps:remove({Type, SubType}, DrawMaps),
            State#draw_record_state{draw_maps = NewDrawMaps}
    end.

%% 转到玩家进程清除玩家个人记录
do_act_end([PlayerId, Atom, Type, SubType]) ->
    lib_player:apply_cast(PlayerId, 2, lib_draw_record, reset, [Atom, Type, SubType]).

%% --------------------------------- db ------------------------------------------------
db_draw_reward_record_select() ->
    SQL = io_lib:format(?sql_custom_act_draw_record_select, []),
    db:get_all(SQL).
db_draw_record_delete(Type, SubType) ->
    SQL = io_lib:format(?sql_custom_act_draw_record_delete, [Type, SubType]),
    db:execute(SQL).
