%%-----------------------------------------------------------------------------
%% @Module  :       pp_top_pk.erl
%% @Author  :       J
%% @Email   :       j-som@foxmail.com
%% @Created :       2017-12-05
%% @Description:    巅峰竞技
%%-----------------------------------------------------------------------------

-module(pp_top_pk).
-include("common.hrl").
-include("server_kv.hrl").
-include("daily.hrl").
-include("server.hrl").
-include("def_module.hrl").
-include("figure.hrl").
-include("top_pk.hrl").
-include("errcode.hrl").
-include("goods.hrl").
-include("def_vip.hrl").
-include("def_fun.hrl").
-include("attr.hrl").
-export ([handle/3]).

handle(CMD, PS, Args) ->
    #player_status{figure = #figure{lv = Lv}, sid = Sid} = PS,
    OpenLv = ?TOP_PK_KV_OPEN_LV,
    if
        Lv >= OpenLv ->
            case do_handle(CMD, PS, Args) of
                {ok, NewPS} ->
                    {ok, NewPS};
                _ ->
                    {ok, PS}
            end;
        true ->
            send_error(Sid, ?ERRCODE(lv_limit))
    end.

%% 基本信息
do_handle(28101, PS, []) ->
    #player_status{top_pk = TopPkStatus, sid = Sid} = PS,
    #top_pk_status{score = Score, match_reward_list = MatchRewardList, enter_count = DailyCount} = TopPkStatus,
    SeasonId = lib_server_kv:get_value(?SERVER_KV_TOP_PK_SEASON_ID, 0),
    SeasonEndTime = lib_top_pk_util:get_season_end_time(),
    SeasonWorldLv = lib_top_pk_util:get_season_world_lv(),
    MaxCount = ?TOP_PK_KV_DAILY_COUNT,
    F = fun(MatchCount) ->
        IsGet = lists:member(MatchCount, MatchRewardList),
        if
            IsGet =:= true -> {MatchCount, 0};
            DailyCount >= MatchCount -> {MatchCount, 2};
            true -> {MatchCount, 1}
        end
    end,
    MatchPackList = lists:map(F, data_top_pk:get_match_num_list()),
    Data = [SeasonId, SeasonEndTime, Score, SeasonWorldLv, MaxCount, DailyCount, MatchPackList],
    {ok, BinData} = pt_281:write(28101, Data),
    lib_server_send:send_to_sid(Sid, BinData),
    ok;

%% 领取每日参与次数奖励
do_handle(28103, #player_status{sid = Sid} = PS, [MatchCount]) ->
    case lib_top_pk:send_match_reward(PS, MatchCount) of
        {false, ErrorCode} -> send_error(Sid, ErrorCode);
        {true, LastPS, RewardList} ->
            {ok, BinData} = pt_281:write(28103, [MatchCount, RewardList]),
            lib_server_send:send_to_sid(Sid, BinData),
            {ok, LastPS}
    end;

%% 段位奖励列表
do_handle(28105, #player_status{sid = Sid} = PS, []) ->
    #player_status{top_pk = TopPkStatus} = PS,
    #top_pk_status{score = Score, grade_reward_list = GradeRewardList} = TopPkStatus,
    InitGradeInfo = data_top_pk:get_grade_info(Score),
    GradeInfo = ?IF(InitGradeInfo =/= [], InitGradeInfo, #base_top_pk_grade_info{}),
    GradeNum = GradeInfo#base_top_pk_grade_info.grade_num,
    InitScore = ?TOP_PK_KV_INIT_SCORE,
    F = fun(NeedGradeNum) ->
        IsGet = lists:member(NeedGradeNum, GradeRewardList),
        if
            IsGet =:= true -> {NeedGradeNum, 0};
            GradeNum >= NeedGradeNum andalso Score>InitScore -> {NeedGradeNum, 2};
            true -> {NeedGradeNum, 1}
        end
    end,
    PackList = lists:map(F, data_top_pk:get_grade_reward_list()),
    {ok, BinData} = pt_281:write(28105, [PackList]),
    lib_server_send:send_to_sid(Sid, BinData),
    ok;

%% 领取段位奖励
do_handle(28106, #player_status{sid = Sid} = PS, [GradeNum]) ->
    case lib_top_pk:send_grade_reward(PS, GradeNum) of
        {false, ErrorCode} -> send_error(Sid, ErrorCode);
        {true, LastPS, RewardList} ->
            {ok, BinData} = pt_281:write(28106, [GradeNum, RewardList]),
            lib_server_send:send_to_sid(Sid, BinData),
            {ok, LastPS}
    end;

%% 匹配
do_handle(28110, PS, []) ->
    #player_status{
        id = RoleId, sid = Sid, platform = Platform, server_num = ServerNum,
        figure = #figure{name = RoleName, lv = Lv},  hightest_combat_power = Power,
        top_pk = #top_pk_status{score = Score, continued_fail = ContinuedFail, enter_count = EnterCount}
    } = PS,
    CheckAll = lib_player_check:check_all(PS),
    Lock = ?ERRCODE(err281_on_matching_state),
    case  CheckAll == true orelse CheckAll == {false, Lock} of
        true ->
            DailyKeyList = [{?MOD_TOPPK, ?DEFAULT_SUB_MODULE, ?DAILY_ID_BUY_COUNT}],
            [{_, BuyCount}] = lib_daily:get_count(RoleId, DailyKeyList),
            DefaultEnterCount = ?TOP_PK_KV_DAILY_COUNT,
            case EnterCount - BuyCount < DefaultEnterCount of
                true ->
                    Node = config:get_cls_node(),
                    Args = [RoleName, Lv, Platform, ServerNum, Power, Score, ContinuedFail],
                    mod_top_pk_local:apply_cast({'enter_match', Node, RoleId, Args});
                _ -> send_error(Sid, ?ERRCODE(err281_daily_enter_count_error))
            end;
        false ->
            {false, Code} = CheckAll,
            send_error(Sid, Code)
    end;

%% 取消匹配
do_handle(28114, PS, []) ->
    #player_status{top_pk = TopPkStatus, id = RoleId, sid = Sid} = PS,
    #top_pk_status{pk_state = PkState} = TopPkStatus,
    case PkState of
        {match, Node} ->
            MyNode = config:get_cls_node(),
            lib_top_pk_util:apply_cast(Node, mod_top_pk_match, cancel_match, [MyNode, RoleId]),
            {ok, LastPS} = lib_top_pk:cancel_match(PS),
            {ok, LastPS};
        _ ->
            send_error(Sid, ?ERRCODE(err281_not_on_match_state))
    end;

%% 排行榜数据
do_handle(28115, PS, [Page, PageSize]) ->
    mod_top_pk_local:apply_cast({'get_rank_info', PS#player_status.id, Page, PageSize}),
    ok;

%% 退出战场
do_handle(28116, #player_status{top_pk = #top_pk_status{pk_state = PkState}, id = RoleId}, [QuitType]) ->
    case PkState of
        {battle, BattleNode, BattlePid} when QuitType == 1->
            MyNode = config:get_cls_node(),
            unode:apply(BattleNode, mod_battle_field, player_quit, [BattlePid, {MyNode, RoleId}, []]);
        {battle, BattleNode, BattlePid} when QuitType == 2->
            MyNode = config:get_cls_node(),
            unode:apply(BattleNode, mod_battle_field, player_extra_quit, [BattlePid, {MyNode, RoleId}, []]);
        _ ->
            ok
    end;

%% 活动状态信息
% do_handle(28107, PS, []) ->
%     mod_top_pk_match_room:get_act_info(PS#player_status.sid);

%% 购买次数
% do_handle(28104, PS, [Count]) when Count > 0->
%     #player_status{id = RoleId, sid = Sid} = PS,
%     case lib_top_pk:get_activity_enabled() of
%         true ->
%             case data_top_pk:get_kv(default, buy_cost) of
%                 Price when Price > 0 ->
%                     CurBuyCount = lib_daily:get_count(RoleId, ?MOD_TOPPK, ?DAILY_ID_BUY_COUNT),
%                     {VipType, VipLv} = lib_vip_api:get_valid_vip_lv(PS),
%                     CountLimit = lib_vip:get_vip_privilege(VipType, VipLv, ?MOD_TOPPK, ?TOPPK_BUY_COUNT_RIGHT_ID),
%                     NewCount = Count + CurBuyCount,
%                     if
%                         NewCount =< CountLimit ->
%                             Cost = [{?TYPE_BGOLD, 0, Price * Count}],
%                             case lib_goods_api:cost_object_list_with_check(PS, Cost, top_pk_buy_cost, integer_to_list(Count)) of
%                                 {true, NewPS,_} ->
%                                     lib_daily:set_count(RoleId, ?MOD_TOPPK, ?DAILY_ID_BUY_COUNT, NewCount),
%                                     {ok, BinData} = pt_281:write(28104, [NewCount]),
%                                     lib_server_send:send_to_sid(Sid, BinData),
%                                     {ok, NewPS};
%                                 {false, Code, _} ->
%                                     send_error(Sid, Code)
%                             end;
%                         true ->
%                             send_error(Sid, ?ERRCODE(err281_buy_count_limit))
%                     end;
%                 _ ->
%                     send_error(Sid, ?FAIL)
%             end;
%         _ ->
%             send_error(Sid, ?ERRCODE(err157_act_not_open))
%     end;

do_handle(_CMD, _PS, _Args) ->
    skip.
    % ?ERR("pp_top_pk no match ~p, ~p~n", [_CMD, _Args]).

send_error(Sid, Code) ->
    {CodeInt, CodeArgs} = util:parse_error_code(Code),
    {ok, BinData} = pt_281:write(28100, [CodeInt, CodeArgs]),
    lib_server_send:send_to_sid(Sid, BinData).



