%%%------------------------------------
%%% @Module  : pp_arena
%%% @Author  : fwx
%%% @Created :  2017-11-20
%%% @Description: arena
%%%------------------------------------
-module(pp_arena).
-export([]).

-compile(export_all).
-include("server.hrl").
-include("figure.hrl").
-include("errcode.hrl").
-include("common.hrl").
-include("arena.hrl").
-include("skill.hrl").
-include("def_module.hrl").
-include("def_vip.hrl").
-include("daily.hrl").
-include ("attr.hrl").


%% 获取玩家arena信息
handle(Cmd, Player, ProData) ->
    case lib_arena_util:is_arena_open() of
        false ->
            ok;
        true ->
            handle_do(Cmd, Player, ProData)
    end.

%% 获取玩家arena信息
handle_do(28001, Player, _Data) ->
    #player_status{
        id = RoleId,
        combat_power = Combat
    } = Player,
    DailyList = [
        {?MOD_ARENA, ?DEFAULT_SUB_MODULE, ?ARENA_USE_NUM}
        ,{?MOD_ARENA, ?DEFAULT_SUB_MODULE, ?ARENA_BUY_NUM}
        ,{?MOD_ARENA, ?DEFAULT_SUB_MODULE, ?ARENA_FIRST_WIN}
        ,{?MOD_ARENA, ?DEFAULT_SUB_MODULE, ?ARENA_DAILY}
        ,{?MOD_ARENA, ?DEFAULT_SUB_MODULE, ?ARENA_FIVE_BATTLE}
        ,{?MOD_ARENA, ?DEFAULT_SUB_MODULE, ?ARENA_SP_NUM}
        ,{?MOD_ARENA, ?DEFAULT_SUB_MODULE, ?ARENA_SP_AWARD}
    ],
    [
        {_, UseNum},
        {_, BuyNum},
        {_, FirstWin},
        {_, DailyAward},
        {_, FiveBattle},
        {_, SPNum},
        {_, SPAward}
    ] = lib_daily:get_count(RoleId, DailyList),
    {_, Trigger, NowCoolTime} = lib_arena:check_cooltime_and_onlinetime(Player, RoleId),
    mod_arena:cast_to_arena(get_arena_role, [RoleId, Combat, UseNum, BuyNum, DailyAward, FirstWin, FiveBattle, SPNum, SPAward, NowCoolTime, Trigger]),
    ok;

%% 随机对手
handle_do(28002, Player, _Data) ->
    mod_arena:cast_to_arena(random_rival_role, [Player#player_status.id]),
    ok;

%% 挑战对手
handle_do(28003, #player_status{id = RivalId}, [_SelfRank, RivalId | _]) ->
    lib_server_send:send_to_uid(RivalId, pt_280, 28000, [?ERRCODE(err280_challenge_self)]),
    ok;
handle_do(28003, Player, [SelfRank, RivalId, RivalRank, IsQuick, Sp]) ->
    #player_status{id = SelfId, arena_battle_pid = BattlePid, battle_attr = BattleAttr} = Player,
    case misc:is_process_alive(BattlePid) of
        true ->
            skip;
        false ->
            % 是否活着，是否处于未上锁状态，是否处于野外和主城只有这两个地区能挑战
            Ret = lib_player_check:check_list(Player, [alive, action_free, outside]),
            % 检查用户是否超过冷却时间，检查用户累计在线时长是否超过两小时
            {CdCheckRes, _, _} = lib_arena:check_cooltime_and_onlinetime(Player, SelfId),  
            if
                CdCheckRes == false ->
                    Code = ?ERRCODE(err280_arena_in_cooldown);   % 竞技场冷却超过30min，且在线时间不足2小时，等待冷却
                Ret =/= true ->
                    {false, Code} = Ret;
                is_record(BattleAttr, battle_attr) andalso BattleAttr#battle_attr.ghost =/= 0 ->
                    Code = ?ERRCODE(err120_ghost_state_limit);
                true ->
                    Code = ?SUCCESS
            end,
            NQuick = lib_arena:can_quick(Player, SelfRank, RivalRank, IsQuick),
            lib_arena:challenge_image_role(Player, SelfRank, RivalId, RivalRank, Code, NQuick, Sp)
    end,
    ok;

%% 挑战次数信息
handle_do(28004, Player, _Data) ->
    #player_status{id = RoleId, figure = #figure{vip = VipLv}} = Player,
    DailyList = [
        {?MOD_ARENA, ?DEFAULT_SUB_MODULE, ?ARENA_USE_NUM}
        ,{?MOD_ARENA, ?DEFAULT_SUB_MODULE, ?ARENA_BUY_NUM}
    ],
    [
        {_, UseNum},
        {_, BuyNum}
    ] = lib_daily:get_count(RoleId, DailyList),
    MaxFreeNum = case data_arena:get_arena_value(?ARENA_FREE_NUM_MAX) of
                     [] -> 0;
                     [TmpNum] -> TmpNum
                 end,
    %% 根据vip等级的可购买次数
    MaxBuyNum = get_vip_buy_num(VipLv, 1),
    ARENANum = max(MaxFreeNum + BuyNum - UseNum, 0),
    CanBuyNum = max(MaxBuyNum - BuyNum, 0),
    lib_server_send:send_to_uid(RoleId, pt_280, 28004, [ARENANum, CanBuyNum]),
    ok;

%% 购买挑战次数
handle_do(28005, Player, [BuyNum]) ->
    #player_status{
        id = RoleId, gold = PreGold, bgold = PreBGold, coin = PreCoin
        ,figure = #figure{vip = VipLev}
    } = Player,
    Num = lib_daily:get_count(RoleId, ?MOD_ARENA, ?ARENA_BUY_NUM),
    BuyCfg = data_arena:get_buy_cfg(Num + BuyNum),
    Result = if
        BuyNum =< 0 ->
            {false, ?ERRCODE(err280_error_args)};
        not (is_record(BuyCfg, arena_buy_cfg)) ->
            {false, ?ERRCODE(err280_over_max_buy_num)};
        VipLev < BuyCfg#arena_buy_cfg.need_vip ->
            {false, ?ERRCODE(err280_vip_less)};
        true ->
            Fun = fun(TmpNum, TmpCost) ->
                {Type, Price} = case data_arena:get_buy_cfg(TmpNum) of
                    #arena_buy_cfg{type = Type0, price = Price0} -> {Type0, Price0};
                    _ -> {0, 0}
                end,
                [{Type, 0, Price} | TmpCost]
            end,
            Cost = lists:foldl(Fun, [], lists:seq(Num + 1, BuyNum + Num)),
            case lib_goods_api:cost_object_list_with_check(Player, Cost, arena_buy_num, "") of
                {true, NewPlayerTmp,_} ->
                    #player_status{gold = AfterGold, bgold = AfterBGold, coin = AfterCoin} = NewPlayerTmp,
                    lib_daily:plus_count(RoleId, ?MOD_ARENA, ?ARENA_BUY_NUM, BuyNum),
                    %% 日志
                    lib_log_api:log_arena_buy_times(
                        RoleId, PreGold, PreBGold, PreCoin, BuyNum, AfterGold, AfterBGold, AfterCoin
                    ),
                    {ok, NewPlayerTmp};
                {false, ErrorCode, _NPlayerTmp} ->
                    {false, ErrorCode}
            end
    end,
    {ErrCode, NewPlayer} = case Result of
        {false, Reason} -> {Reason, Player};
        {ok, Player2} -> {?SUCCESS, Player2}
    end,
    lib_server_send:send_to_uid(RoleId, pt_280, 28005, [ErrCode]),
    {ok, NewPlayer};

%% 获取排行榜
handle_do(28006, Player, [PageNum, Num]) ->
    #player_status{id = RoleId} = Player,
    mod_arena:cast_to_arena(get_rank_list, [RoleId,PageNum,Num]),
    {ok, Player};

%% 领取奖励
handle_do(28008, Player, [?ARENA_AWARD_DAILY]) ->
    #player_status{id = RoleId, sid = Sid} = Player,
    Daily = lib_daily:get_count(RoleId, ?MOD_ARENA, ?ARENA_DAILY),
    case Daily > 0 of
        true  ->
            lib_server_send:send_to_sid(Sid, pt_280, 28000, [?ERRCODE(err280_already_receive_reward)]);
        false ->
            mod_arena:cast_to_arena(get_reward, [RoleId])
    end,
    ok;
handle_do(28008, Player, [?ARENA_AWARD_FIRST_WIN]) ->
    #player_status{id = RoleId, sid = Sid, figure = #figure{lv = Lv, name = Name}} = Player,
    Daily = lib_daily:get_count(RoleId, ?MOD_ARENA, ?ARENA_FIRST_WIN),
    if
        Daily =:= 0 ->
            lib_server_send:send_to_sid(Sid, pt_280, 28000, [?ERRCODE(err280_reward_condition)]);
        Daily =:= 1 ->
            case data_arena:get_arena_daily_reward(Lv) of
                [FirstWin, _FiveBattle] ->
                    lib_daily:increment(RoleId, ?MOD_ARENA, ?ARENA_FIRST_WIN),
                    NewPlayer = lib_goods_api:send_reward(Player, FirstWin, arena_first_win),
                    lib_server_send:send_to_sid(Sid, pt_280, 28008, [?SUCCESS, ?ARENA_AWARD_FIRST_WIN]),%日志
                    lib_log_api:log_arena_daily_reward(
                        [RoleId, Name, 1, 0, util:term_to_bitstring(FirstWin), utime:unixtime()]
                    ),
                    {ok, NewPlayer};
                _ ->
                    lib_server_send:send_to_sid(Sid, pt_280, 28000, [?ERRCODE(err280_none_reward)])
            end;
        true ->
            lib_server_send:send_to_sid(Sid, pt_280, 28000, [?ERRCODE(err280_already_receive_reward)])
    end;
handle_do(28008, Player, [?ARENA_AWARD_FIVE]) ->
    #player_status{id = RoleId, sid = Sid, figure = #figure{lv = Lv, name = Name}} = Player,
    Daily = lib_daily:get_count(RoleId, ?MOD_ARENA, ?ARENA_FIVE_BATTLE),
    case Daily > 0 of
        true  ->
            lib_server_send:send_to_sid(Sid, pt_280, 28000, [?ERRCODE(err280_already_receive_reward)]);
        false ->
            DailyList = [
                {?MOD_ARENA, ?DEFAULT_SUB_MODULE, ?ARENA_USE_NUM}
                ,{?MOD_ARENA, ?DEFAULT_SUB_MODULE, ?ARENA_SP_NUM}
            ],
            [
                {_, UseNum},
                {_, SPNum}
            ] = lib_daily:get_count(RoleId, DailyList),
            BattleNum = UseNum + SPNum,
            case BattleNum >= ?ARENA_BATTLE_REWARD_NUM of
                true  ->
                    case data_arena:get_arena_daily_reward(Lv) of
                        [_FirstWin, FiveBattle] ->
                            lib_daily:increment(RoleId, ?MOD_ARENA, ?ARENA_FIVE_BATTLE),
                            NewPlayer = lib_goods_api:send_reward(Player, FiveBattle, arena_five_battle),
                            lib_server_send:send_to_sid(Sid, pt_280, 28008, [?SUCCESS, ?ARENA_AWARD_FIVE]),
                            lib_log_api:log_arena_daily_reward(
                                [RoleId, Name, 2, 0, util:term_to_bitstring(FiveBattle), utime:unixtime()]
                            ),
                            {ok, NewPlayer};
                        _ ->
                            lib_server_send:send_to_sid(Sid, pt_280, 28000, [?ERRCODE(err280_none_reward)])
                    end;
                false ->
                    lib_server_send:send_to_sid(Sid, pt_280, 28000, [?ERRCODE(err280_reward_condition)])
            end
    end;
handle_do(28008, Player, [?ARENA_AWARD_SP]) ->
    #player_status{id = RoleId, sid = Sid} = Player,
    Daily = lib_daily:get_count(RoleId, ?MOD_ARENA, ?ARENA_SP_AWARD),
    case Daily > 0 of
        true  ->
            lib_server_send:send_to_sid(Sid, pt_280, 28000, [?ERRCODE(err280_already_receive_reward)]);
        false ->
            mod_arena:cast_to_arena(get_sp_reward, [RoleId])
    end,
    ok;

%% 大神列表
handle_do(28009, Player, _Data) ->
    mod_arena:cast_to_arena(get_sp_list, [Player#player_status.sid]),
    ok;

%% 退出战斗场景
handle_do(28012, Player, _Data) ->
    #player_status{sid = Sid, arena_battle_pid = BattlePid} = Player,
    case misc:is_process_alive(BattlePid) of
        true ->
            mod_battle_field:stop(BattlePid);
        false ->
            lib_server_send:send_to_sid(Sid, pt_280, 28012, [?FAIL])
    end,
    ok;

%% 战斗假人信息
handle_do(28013, Player, _Data) ->
    #player_status{sid = Sid, arena_battle_pid = BattlePid} = Player,
    case misc:is_process_alive(BattlePid) of
          true ->
              mod_battle_field:apply_cast(BattlePid, lib_arena_battle, send_fake_data, []);
          false ->
              lib_server_send:send_to_sid(Sid, pt_280, 28000, [?FAIL])
    end,
    ok;

%%  跳过比赛
handle_do(28015, Player, _Data) ->
    case data_arena:get_arena_value(?ARENA_REWARD_TIME) of
        [] -> RewardTime = 10;
        [RewardTime] -> skip
    end,
    #player_status{id = RoleId, sid = Sid, arena_battle_pid = BattlePid} = Player,
    UnixTime = utime:unixtime(),
    case misc:is_process_alive(BattlePid) of
        true ->
            mod_battle_field:apply_cast(BattlePid, lib_arena_battle, skip_battle, [RoleId]),
            lib_server_send:send_to_sid(Sid, pt_280, 28014, [2, UnixTime + RewardTime]),
            lib_server_send:send_to_sid(Sid, pt_280, 28015, [?SUCCESS]);
        false ->
            lib_server_send:send_to_sid(Sid, pt_280, 28015, [?FAIL])
    end,
    ok;

handle_do(_Cmd, _Player, _Data) ->
    {error, io_lib:format("~w  no handle_do, ~w, ~p", [?MODULE, _Cmd, _Data])}.

%% 根据vip等级的可购买次数
get_vip_buy_num(VipLev, Num) ->
    case data_arena:get_buy_cfg(Num) of
        #arena_buy_cfg{need_vip = NeedVip} when VipLev >= NeedVip ->
            get_vip_buy_num(VipLev, Num + 1);
        _ ->
            Num - 1
    end.