%% ---------------------------------------------------------------------------
%% @doc 定制活动-招财猫活动。
%% @author zmh
%% @since  2020-06-28
%% ---------------------------------------------------------------------------
-module(lucky_cat).


-export([
    send_lucky_cat_cfg/1          %% 发送配置数据
    ,send_lucky_cat_act_info/3    %% 发送达摩许愿活动数据给前端

    ,lucky_cat_draw/3             %% 招财猫招财
    ,check/1
    ,handle_event/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").
-include("rec_event.hrl").
-include("def_event.hrl").

handle_event(Player, #event_callback{type_id = ?EVENT_RECHARGE, data = #callback_recharge_data{gold = Gold}}) ->
    Type = ?CUSTOM_ACT_TYPE_LUCKY_CAT,
    ActList = lib_custom_act_util:get_open_subtype_list(Type),
    act_recharge(Player,Gold,ActList),
    {ok, Player};
handle_event(Player, _) ->
    {ok, Player}.

act_recharge(_Player,_Add,[])->
    ok;
act_recharge(Player,Add,[H | T])->
    #player_status{id=RoleID}=Player,
    #act_info{key = {Type, SubType}} = H,
    RoleCat = lucky_cat_data(Player, Type, SubType),
    #role_luckycat{times=UsedT,recharge=OldV}=RoleCat,
    NRoleCat = RoleCat#role_luckycat{recharge=OldV+Add},
    ActData = #custom_act_data{
        type = Type, subtype = SubType, act_data = NRoleCat, time = utime:unixtime()
    },
    lib_custom_act_data:save_custom_data(RoleID,ActData),
    {ok, BinData} = pt_332:write(33220, [Type, SubType, UsedT,OldV+Add]),
    lib_server_send:send_to_uid(RoleID, BinData),
    act_recharge(Player,Add,T).


%% @doc 角色招财猫数据
lucky_cat_data(_Role, Type, SubType) ->
    #custom_act_data{
        act_data = ActData
    } = lib_custom_act_data:custom_act_data(Type, SubType),
    case ActData of
        #role_luckycat{}->
            ActData;
        _->
            #role_luckycat{}
    end.

%% 整理已开配置数据给前端
send_lucky_cat_cfg(Role) ->
    Type = ?CUSTOM_ACT_TYPE_LUCKY_CAT,
    InfoList = lib_custom_act_util:get_open_subtype_list(Type),
    ActInfoList = pack_act_all_info(Role, InfoList, []),
    {ok, BinData} = pt_332:write(33219, [ActInfoList]),
    lib_server_send:send_to_sid(Role#player_status.sid, BinData),
    {ok,Role}.

pack_act_all_info(_Role, [], ActInfoList) ->
    ActInfoList;
pack_act_all_info(Role, [Info | T], ActInfoList) ->
    #act_info{key = {Type, SubType}} = Info,
    case lib_custom_act_util:get_act_cfg_info(Type, SubType) of
        #custom_act_cfg{condition = Condition} ->
            skip;
        _ ->
            Condition = []
    end,
    case lists:keyfind(max_time,1,Condition) of
        {_,MaxTimes}->
            skip;
        _->
            MaxTimes = 8
    end,
    case lists:keyfind(mult,1,Condition) of
        {_,Mults}->
            skip;
        _->
            Mults = []
    end,
    Confs = joint_confs(Type,SubType,MaxTimes,[]),
    ActInfoList2 = [{Type,SubType,MaxTimes,Confs,Mults} | ActInfoList],
    pack_act_all_info(Role, T, ActInfoList2).


joint_confs(_Type,_SubType,0,Confs)->
    Confs;
joint_confs(Type,SubType,Times,Confs)->
    case lib_custom_act_util:get_act_reward_cfg_info(Type,SubType,Times) of
        #custom_act_reward_cfg{condition=Condition}->
            skip;
        _->
            Condition = []
    end,
    case lists:keyfind(luckycat_cost,1,Condition) of
        {_,Cost}->
            skip;
        _->
            Cost = 1
    end,
    case lists:keyfind(luckycat_recharge,1,Condition) of
        {_,Recharge}->
            skip;
        _->
            Recharge = 99999
    end,
    joint_confs(Type,SubType,Times-1,[{Times,Cost,Recharge}|Confs]).


%% @doc 招财猫活动信息
send_lucky_cat_act_info(Role, Type, SubType) ->
    case lib_custom_act_api:is_open_act(Type, SubType) of
        true ->
            RoleCat = lucky_cat_data(Role, Type, SubType),
            #role_luckycat{times=UsedT,recharge=Recharge}=RoleCat;
        false ->
            UsedT = 100,Recharge=0
    end,
    {ok, BinData} = pt_332:write(33220, [Type, SubType, UsedT,Recharge]),
    lib_server_send:send_to_sid(Role#player_status.sid, BinData),
    {ok,Role}.


%% ---------------------------------------------------------------------------
%% @doc 招财猫招财
-spec lucky_cat_draw(Role, Type, SubType) ->
    {false, Reason} | {ok, NewRole, Times, Sort,Mult} when
    Role        :: #player_status{},
    Type        :: integer(),
    SubType     :: integer(),
    Reason      :: integer(),
    NewRole     :: #player_status{},
    Times       :: integer(),   %% 已抽奖次数
    Sort        :: integer(),   %% 倍数序列
    Mult        :: integer().   %% 倍数
%% ---------------------------------------------------------------------------
lucky_cat_draw(Role, Type, SubType) ->
    #player_status{id = RoleId,figure=#figure{name=Name}} = Role,
    IsOpen  = lib_custom_act_api:is_open_act(Type, SubType),
    RoleCat = lucky_cat_data(Role, Type, SubType),
    #role_luckycat{times=NowTimes,recharge=TotalRecharge}=RoleCat,
    NewTimes = NowTimes + 1,
    Config = lib_custom_act_util:get_act_reward_cfg_info(Type, SubType, NewTimes),
    case lib_custom_act_util:get_act_cfg_info(Type, SubType) of
        #custom_act_cfg{condition = Condition} ->
            case lists:keyfind(mult,1,Condition) of
                {_,Mults}->
                    skip;
                _->
                    Mults = []
            end,
            case lists:keyfind(tv_show,1,Condition) of
                {_,TvC}->
                    skip;
                _->
                    TvC = 1000
            end;
        _ ->
            Mults = [],
            TvC = 1000
    end,
    if
        IsOpen =:= false ->
            {false, ?ERRCODE(err331_act_closed)};
        not is_record(Config, custom_act_reward_cfg) ->
            {false, ?ERRCODE(err331_has_no_more_times)};
        Mults =:= [] ->
            {false,?ERRCODE(missing_config)};
        true ->
            case check_cost(Role,TotalRecharge,Config) of
                {false, ErrorCode} ->
                    {false, ErrorCode};
                {true, Role2,WeightL,Cost,Rewards} ->

                    Sort = urand:rand_with_weight(WeightL),
                    case lists:keyfind(Sort,1,Mults) of
                        {_,Mult}->
                            skip;
                        _->
                            Mult = 1
                    end,
                    NRoleCat = RoleCat#role_luckycat{times=NewTimes},
                    ActData = #custom_act_data{
                        type = Type, subtype = SubType,time = utime:unixtime(), act_data = NRoleCat
                    },
                    lib_custom_act_data:save_custom_data(RoleId,ActData),
                    About = io_lib:format("~w,~w,~w", [Type,SubType,Sort]),
                    GainV = util:floor(Cost*Mult/100),
                    Gain  = [{T,K,GainV}||{T,K,_}<-Rewards],
                    Produce = #produce{
                        type = lucky_cat_draw, subtype = Type, reward = Gain
                        ,remark = About
                    },
                    {ok,Role3} = lib_goods_api:send_reward_with_mail(Role2, Produce,?MOD_AC_CUSTOM),
                    Log = {RoleId, Name, utime:unixtime(), NewTimes, Sort, Mult},
                    mod_custom_act_log:cast({lucky_cat_log, Type, SubType, Log}),
                    case Mult>=TvC of
                        true->
                            Pre = Mult div 100,
                            Aft0 = Mult rem 100,
                            Aft1 = Aft0 rem 10,
                            Aft = case Aft1=<0 of
                                true->
                                    Aft0 div 10;
                                _->
                                    Aft0
                            end,
                            spawn(fun() -> timer:sleep(9000), lib_chat:send_TV({all}, ?MOD_AC_CUSTOM, 1, [Name,RoleId,Cost,Pre,Aft,GainV]) end);
                        _->
                            skip
                    end,
                    lib_log_api:custom_act_reward_log(Role3, Role, Type, SubType, Sort,Gain),
                    {ok, Role3, NewTimes, Sort, Mult}
            end
    end.

%% @doc 扣除消耗
check_cost(Role,TotalRecharge,Config) ->
    #custom_act_reward_cfg{condition = Condition,reward=Rewards} = Config,
    case lists:keyfind(luckycat_cost,1,Condition) of
        {_,Cost}->
            skip;
        _->
            Cost = miss_cfg
    end,
    case lists:keyfind(luckycat_recharge,1,Condition) of
        {_,Recharge}->
            skip;
        _->
            Recharge = miss_cfg
    end,
    case lists:keyfind(luckycat_weight,1,Condition) of
        {_,Weight}->
            skip;
        _->
            Weight = miss_cfg
    end,
    CheckList = [
        {check_cfg_cost,Cost},
        {check_cfg_weight,Weight},
        {check_cfg_recharge,TotalRecharge,Recharge},
        {check_cost,Role,Cost}
    ],
    case util:check_lists(?MODULE,CheckList) of
        {ok,NewRole}->
            {true,NewRole,Weight,Cost,Rewards};
        {false,Err}->
            {false,Err}
    end.


check({check_cfg_weight,Weight})->
    case is_list(Weight) of
        true when Weight /= [] ->
            true;
        _->
            {false,?ERRCODE(missing_config)}
    end;
check({check_cfg_cost,Cost})->
    case is_integer(Cost) of
        true->
            true;
        _->
            {false,?ERRCODE(missing_config)}
    end;
check({check_cfg_recharge,TotalRecharge,Recharge})->
    case is_integer(Recharge) of
        true->
            case TotalRecharge>=Recharge of
                true->
                    true;
                _->
                    {false,?ERRCODE(err331_need_recharge_more)}
            end;
        _->
            {false,?ERRCODE(missing_config)}
    end;
check({check_cost,Role,Cost})->
    CostL = [{?TYPE_GOLD,?GOODS_ID_GOLD,Cost}],
    case lib_goods_api:cost_object_list_with_check(Role, CostL, lucky_cat_draw, "lucky_cat_draw") of
        {true, TmpNewPlayer,_} ->
            {ok, TmpNewPlayer};
        {false, Err,_} ->
            {false,Err}
    end.





