%%% ----------------------------------------------------
%%% @Module:        pp_3v3
%%% @Author:        zhl
%%% @Description:   跨服3v3
%%% @Created:       2017/07/04
%%% ----------------------------------------------------

-module(pp_3v3).
-export([handle/3]).

-include("server.hrl").
-include("predefine.hrl").
%%-include("train.hrl").
-include("scene.hrl").
-include("3v3.hrl").
-include("figure.hrl").
-include("errcode.hrl").
-include("guild.hrl").
-include("goods.hrl").
-include("common.hrl").
-include("def_goods.hrl").
-include("def_module.hrl").

%% 获取跨服3v3个人战绩
handle(65000, #player_status{sid = RoleSid, role_3v3 = Role3v3} = Status, []) ->
    #role_3v3{tier = Tier, star = Star, continued_win = ContinuedWin, daily_win = DailyWin,
        daily_honor = DailyHonor, pack_time = PackTime, pack_reward = PackReward, daily_pk = DailyPk,
        season_pk = SeasonPk
    } = Role3v3,
    IsToday = utime:is_today(PackTime),
    if
        IsToday -> NPackTime = PackTime;
        true -> NPackTime = 0
    end,
    Data = [Tier, Star, ContinuedWin, DailyWin, DailyPk, SeasonPk, PackReward, DailyHonor, NPackTime],
    {ok, Bin} = pt_650:write(65000, Data),
    lib_server_send:send_to_sid(RoleSid, Bin),
    {ok, Status};

%% 领取今日段位奖励
handle(65003, #player_status{id = RoleID, sid = RoleSid, role_3v3 = Role3v3, figure = #figure{lv = Lv}} = Status, []) ->
    #role_3v3{daily_honor = DailyHonor, pack_time = PackTime} = Role3v3,
    IsToday = utime:is_today(PackTime),
    if
        IsToday ->
            ResID = ?ERRCODE(err650_kf_3v3_is_packed),
            NStatus = Status;
        DailyHonor =< 0 ->
            ResID = ?ERRCODE(err650_kf_3v3_lack_reward),
            NStatus = Status;
        Lv < ?KF_3V3_LV_LIMIT ->
            ResID = ?ERRCODE(lv_limit),
            NStatus = Status;
        true ->
            ResID = ?SUCCESS,
            NRole3v3 = Role3v3#role_3v3{daily_honor = 0, pack_time = utime:unixtime()},
            Status1 = Status#player_status{role_3v3 = NRole3v3},
            lib_3v3_local:replace_role_3v3(RoleID, NRole3v3),
            Produce = #produce{type = kf_3v3_daily, reward = [{?TYPE_CURRENCY, ?GOODS_ID_3V3_HONOR, DailyHonor}], show_tips = ?SHOW_TIPS_3},
            {ok, NStatus} = lib_goods_api:send_reward_with_mail(Status1, Produce, ?MOD_KF_3V3)
    end,
    {ok, Bin} = pt_650:write(65003, [ResID]),
    lib_server_send:send_to_sid(RoleSid, Bin),
    {ok, NStatus};

handle(65005, #player_status{sid = RoleSid} = Status, []) ->
    mod_3v3_local:get_left_time(RoleSid),
    {ok, Status};

%% 领取活跃奖励
handle(65004, #player_status{id = RoleID, sid = RoleSid, role_3v3 = Role3v3, figure = #figure{lv = Lv}} = Status, [RewardID]) ->
    #role_3v3{pack_reward = PackReward, daily_win = DailyWin, daily_pk = DailyPk} = Role3v3,
    case lists:keyfind(RewardID, 1, PackReward) of
        {_, Time} when Lv >= ?KF_3V3_LV_LIMIT ->
            IsToday = utime:is_today(Time),
            if
                IsToday -> %% 今日已领取
                    ResID = ?ERRCODE(err650_kf_3v3_is_packed),
                    NStatus = Status;
                RewardID > 0 andalso DailyPk < RewardID ->
                    ResID = ?ERRCODE(err650_kf_3v3_lack_count),
                    NStatus = Status;
                RewardID == 0 andalso DailyWin =< 0 ->
                    ResID = ?ERRCODE(err650_kf_3v3_lack_wincount),
                    NStatus = Status;
                true ->
                    case data_3v3:get_act_rewards(RewardID) of
                        [] ->
                            ResID = ?FAIL,
                            NStatus = Status;
                        Rewards ->
                            case lib_goods_api:can_give_goods(Status, Rewards) of
                                true ->
                                    ResID = ?SUCCESS,
                                    NPackReward = lists:keyreplace(
                                        RewardID, 1, PackReward, {RewardID, utime:unixtime()}),
                                    NRole3v3 = Role3v3#role_3v3{pack_reward = NPackReward},
                                    lib_3v3_local:replace_role_3v3(RoleID, NRole3v3),
                                    Status1 = Status#player_status{role_3v3 = NRole3v3},
                                    % NStatus = lib_goods_api:send_reward(Rewards, kf_3v3, Status1)
                                    Produce = #produce{type = kf_3v3_wincount, reward = Rewards, show_tips = ?SHOW_TIPS_3},
                                    NStatus = lib_goods_api:send_reward(Status1, Produce);
                                _ ->
                                    ResID = ?ERRCODE(err150_no_cell),
                                    NStatus = Status
                            end
                    end
            end;
        _ ->
            ResID = ?FAIL,
            NStatus = Status
    end,
    {ok, Bin} = pt_650:write(65004, [ResID, RewardID]),
    lib_server_send:send_to_sid(RoleSid, Bin),
    {ok, NStatus};

%% 连接不上跨服提示 | 等级不足 | 全局错误码
%% @desc : 连接不上跨服中心时活动不开启
handle(Cmd, #player_status{
        figure = #figure{lv = RoleLv}, sid = RoleSid, action_lock = ActionLock, scene = _SceneID
    } = Status, Recv) ->
    IsConn = clusters_api:is_connected_center(),
    ServOpenDay = util:get_open_day(),
    if
        IsConn == false -> %% 连接不上跨服中心
            {ok, Bin} = pt_650:write(65001, [?ERRCODE(err650_kf_3v3_not_conn)]),
            lib_server_send:send_to_sid(RoleSid, Bin),
            {ok, Status};
        ServOpenDay < ?SERVER_OPEN_DAY ->
            {ok, Bin} = pt_650:write(65001, [?ERRCODE(err157_9_open_day_limit)]),
            lib_server_send:send_to_sid(RoleSid, Bin),
            {ok, Status};
        RoleLv < ?KF_3V3_LV_LIMIT -> %% 等级不足
            {ok, Bin} = pt_650:write(65001, [?ERRCODE(lv_limit)]),
            lib_server_send:send_to_sid(RoleSid, Bin),
            {ok, Status};
        Cmd == 65002 orelse Cmd == 65010 orelse Cmd == 65011
            orelse Cmd == 65038 orelse Cmd == 65039 ->
            do_handle(Cmd, Status, Recv);
        true ->
            case ?ERRCODE(err650_in_kf_3v3_act) of
                ActionLock ->
                    do_handle(Cmd, Status, Recv);
                _ ->
                    case lib_player_check:check_all(Status) of
                        true ->
                            do_handle(Cmd, Status, Recv);
                        {false, ErrorStatus} ->
                            {ok, Bin} = pt_650:write(65001, [ErrorStatus]),
                            lib_server_send:send_to_sid(RoleSid, Bin),
                            {ok, Status}
                    end
            end
    end.

%% 取消关注界面
do_handle(65002, #player_status{id = RoleID} = Status, []) ->
    mod_3v3_local:cancel_attention([RoleID]),
    {ok, Status};

%% 获取自身队伍信息
do_handle(65010, Status, []) ->
    #player_status{id = RoleID, sid = RoleSid} = Status,
    mod_3v3_local:get_team_info([RoleID, RoleSid]),
    {ok, Status};

%% 获取3v3队伍列表
do_handle(65011, #player_status{sid = RoleSid, id = RoleID, server_id = ServerId} = Status, []) ->
    mod_3v3_local:get_team_list([RoleID, RoleSid, ServerId]),
    {ok, Status};

%% 查询3v3队伍信息
do_handle(65012, #player_status{sid = RoleSid} = Status, [TeamID]) ->
    mod_3v3_local:get_team_data([RoleSid, TeamID]),
    {ok, Status};

%% 创建队伍
do_handle(65013, Status, [PowerLimit, LvLimit, Password, IsAuto]) ->
    RoleData = lib_3v3_local:to_role_data(Status, [PowerLimit, LvLimit, Password, IsAuto]),
    Lock = ?ERRCODE(err650_in_kf_3v3_act),
    if
        Status#player_status.action_lock =:= Lock ->
            mod_3v3_local:create_team(RoleData);
        true ->
            case lib_player_check:check_all(Status) of
                true ->
                    mod_3v3_local:create_team(RoleData);
                {false, ErrorCode} ->
                    {ok, Bin} = pt_650:write(65001, [ErrorCode]),
                    lib_server_send:send_to_sid(Status#player_status.sid, Bin)
            end
    end,
    {ok, Status};

%% 快速加入队伍（个人匹配）
do_handle(65014, Status, [Type]) ->
    RoleData = lib_3v3_local:to_role_data(Status, [0, 0, 0, ?KF_3V3_IS_AUTO]),
    Lock = ?ERRCODE(err650_in_kf_3v3_act),
    if
        Status#player_status.action_lock =:= Lock ->
            mod_3v3_local:quick_join_team([RoleData, Type]);
        true ->
            case lib_player_check:check_all(Status) of
                true ->
                    mod_3v3_local:quick_join_team([RoleData, Type]);
                {false, ErrorCode} ->
                    {ok, Bin} = pt_650:write(65001, [ErrorCode]),
                    lib_server_send:send_to_sid(Status#player_status.sid, Bin)
            end
    end,
    {ok, Status};

%% 申请入队伍
do_handle(65015, Status, [TeamID, Password]) ->
    RoleData = lib_3v3_local:to_role_data(Status, [0, 0, 0, 0]),
    Lock = ?ERRCODE(err650_in_kf_3v3_act),
    if
        Status#player_status.action_lock == Lock ->
            mod_3v3_local:apply_join_team([RoleData, TeamID, Password]);
        true ->
            case lib_player_check:check_all(Status) of
                true ->
                    mod_3v3_local:apply_join_team([RoleData, TeamID, Password]);
                {false, ErrorCode} ->
                    {ok, Bin} = pt_650:write(65001, [ErrorCode]),
                    lib_server_send:send_to_sid(Status#player_status.sid, Bin)
            end
    end,
    {ok, Status};

%% 受邀入队伍
do_handle(65016, Status, [TeamID, Password]) ->
    RoleData = lib_3v3_local:to_role_data(Status, [0, 0, 0, 0]),
    Lock = ?ERRCODE(err650_in_kf_3v3_act),
    if
        Status#player_status.action_lock =:= Lock ->
            mod_3v3_local:invite_join_team([RoleData, TeamID, Password]);
        true ->
            case lib_player_check:check_all(Status) of
                true ->
                    mod_3v3_local:invite_join_team([RoleData, TeamID, Password]);
                {false, ErrorCode} ->
                    {ok, Bin} = pt_650:write(65001, [ErrorCode]),
                    lib_server_send:send_to_sid(Status#player_status.sid, Bin)
            end
    end,
    {ok, Status};

%% 离开队伍
do_handle(65017, Status, []) ->
    #player_status{
        platform = Platform, server_num = ServerNum, server_id = ServerId, id = RoleID, sid = RoleSid
    } = Status,
    mod_3v3_local:leave_team([Platform, ServerNum, ServerId, RoleID, RoleSid]),
    {ok, Status};

%% 踢出队伍
do_handle(65018, Status, [_TPlatform, _TServerNum, TRID]) ->
    #player_status{server_id = ServerId, id = RoleID, sid = RoleSid} = Status,
    mod_3v3_local:kick_out_team([ServerId, RoleID, RoleSid, TRID]),
    {ok, Status};

%% 邀请玩家 - 邀请的玩家只能是本服的玩家
do_handle(65019, Status, [TRID]) ->
    #player_status{server_id = ServerId, id = RoleID, sid = RoleSid} = Status,
    mod_3v3_local:invite_role([ServerId, RoleID, RoleSid, TRID]),
    {ok, Status};

%% 开始匹配
do_handle(65021, Status, []) ->
    #player_status{server_id = ServerId, id = RoleID, sid = RoleSid} = Status,
    Lock = ?ERRCODE(err650_in_kf_3v3_act),
    if
        Status#player_status.action_lock =/= Lock ->
            case lib_player_check:check_all(Status) of
                true ->
                    mod_3v3_local:start_matching_team([ServerId, RoleID, RoleSid]);
                {false, ErrorCode} ->
                    {ok, Bin} = pt_650:write(65001, [ErrorCode]),
                    lib_server_send:send_to_sid(RoleSid, Bin)
            end;
        true ->
            mod_3v3_local:start_matching_team([ServerId, RoleID, RoleSid])
    end,
    {ok, Status};

%% 取消匹配
do_handle(65022, Status, []) ->
    #player_status{
        platform = Platform, server_num = ServerNum, server_id = ServerId,
        id = RoleID, sid = RoleSid
    } = Status,
    mod_3v3_local:stop_matching_team([Platform, ServerNum, ServerId, RoleID, RoleSid]),
    {ok, Status};

%% 准备 | 取消准备
do_handle(65023, Status, [IsReady]) ->
    #player_status{server_id = ServerId, id = RoleID, sid = RoleSid} = Status,
    Lock = ?ERRCODE(err650_in_kf_3v3_act),
    if
        Status#player_status.action_lock =/= Lock ->
            case lib_player_check:check_all(Status) of
                true ->
                    mod_3v3_local:reset_ready([ServerId, RoleID, RoleSid, IsReady]);
                {false, ErrorCode} ->
                    {ok, Bin} = pt_650:write(65001, [ErrorCode]),
                    lib_server_send:send_to_sid(RoleSid, Bin)
            end;
        true ->
            mod_3v3_local:reset_ready([ServerId, RoleID, RoleSid, IsReady])
    end,
    {ok, Status};

%% 自动开始 | 取消自动开始
do_handle(65024, Status, [IsAuto]) ->
    #player_status{server_id = ServerId, id = RoleID, sid = RoleSid} = Status,
    Lock = ?ERRCODE(err650_in_kf_3v3_act),
    if
        Status#player_status.action_lock =/= Lock ->
            case lib_player_check:check_all(Status) of
                true ->
                    mod_3v3_local:reset_auto([ServerId, RoleID, RoleSid, IsAuto]);
                {false, ErrorCode} ->
                    {ok, Bin} = pt_650:write(65001, [ErrorCode]),
                    lib_server_send:send_to_sid(RoleSid, Bin)
            end;
        true ->
            mod_3v3_local:reset_auto([ServerId, RoleID, RoleSid, IsAuto])
    end,
    {ok, Status};

%% 3v3战场信息
do_handle(65030, Status, []) ->
    #player_status{server_id = ServerId, id = RoleID, sid = RoleSid} = Status,
    mod_3v3_local:get_battle_info([ServerId, RoleID, RoleSid]),
    {ok, Status};

%% 获取天梯排行榜 - 活动结束推送20强
do_handle(65038, Status, []) ->
    #player_status{server_id = ServerId, sid = RoleSid} = Status,
    mod_3v3_local:get_score_rank([ServerId, RoleSid]),
    {ok, Status};

%% 获取荣誉排行榜 - 每页最多5个排名
do_handle(65039, Status, [Page]) when Page >= 0 ->
    #player_status{server_id = ServerId, id = RoleID} = Status,
    clusters_node:apply_cast(mod_3v3_rank, get_page_rank, [[Page, ServerId, RoleID]]),
    {ok, Status};

%% 离开战场
do_handle(65040, Status, []) ->
    #player_status{platform = Platform, server_num = ServerNum, server_id = ServerId, id = RoleID, scene = SceneId} = Status,
    Is3v3Scene = lib_3v3_api:is_3v3_scene(SceneId),
    lib_3v3_local:leave_pk_room([Platform, ServerNum, RoleID, ?PK_3V3_ONLINE, ServerId, Is3v3Scene]),
    {ok, Status};

%% 公开招募
do_handle(65041, Status, [Type]) ->
    #player_status{id = RoleID, figure = Figure, combat_power = CombatPower} = Status,
    mod_3v3_local:open_call_member([RoleID, Type, Figure, CombatPower]);

%% 修改队伍条件
do_handle(65045, Status, [PowerLimit, LvLimit, Password]) ->
    #player_status{server_id = ServerId, id = RoleID, sid = RoleSid} = Status,
    mod_3v3_local:change_team_limit([ServerId, RoleID, RoleSid, PowerLimit, LvLimit, Password]);

do_handle(_Cmd, Status, _Recv) ->
    {ok, Status}.
