%% ---------------------------------------------------------------------------
%% @doc lib_team_api
%% @author ming_up@foxmail.com
%% @since  2016-11-17
%% @deprecated  队伍api接口
%% ---------------------------------------------------------------------------
-module(lib_team_api).

-export([
         create_team/5
        , thing_to_mb/1
        , send_to_team/2
        , quit_team/2
        , get_mb_ids/1
        , where_i_am/7
        , handle_event/2
        , change_scene_callback/4
        , get_his_teammate/1
        , share_mon_exp/6
        , kill_mon/3
        , change_location/1
        , inerrupt_follow/2
        , team_to_onhook/1
        , after_finish_task/2
        , need_check_password/1
        , get_svr_by_team/1
        , is_local_team/1
        ]).

-include("team.hrl").
-include("common.hrl").
-include("server.hrl").
-include("figure.hrl").
-include("rec_event.hrl").
-include("def_event.hrl").
-include("skill.hrl").
-include("dungeon.hrl").
-include("def_module.hrl").

%% 系统创建一个队伍 @returns TeamId
create_team(ActivityId, SubTypeId, SceneId, Mbs, Args) ->
    lib_team:create_cast(ActivityId, SubTypeId, SceneId, Mbs, Args).

%% 处理成队员record
thing_to_mb(PS = #player_status{}) ->
    Skill = case lists:keyfind(?SP_SKILL_KILLING, 1, PS#player_status.skill#status_skill.skill_passive) of
        false -> 0;
        _ -> ?SP_SKILL_KILLING
    end,
    Node = node(),
    ServerId = config:get_server_id(),
    OpenTime = util:get_open_time(),
    Welfare = lib_recharge_welfare:get_welfare_data(PS),
    #player_status{
        id=Id, platform=Platform, server_num=SerNum, scene=Scene, combat_power = Power
        ,scene_pool_id=ScenenPoolId, copy_id=CopyId, pid = Pid, sid = Sid
        ,figure=Figure, online = OL, action_lock = Lock
    } = PS,
    #mb{
        id=Id, platform=Platform, server_num=SerNum, server_id = ServerId,
        srv_open_time = OpenTime, pid = Pid, sid = Sid,
        figure=Figure, scene=Scene, skill = Skill, action_lock = Lock,
        scene_pool_id=ScenenPoolId, copy_id=CopyId, join_time=utime:unixtime(),
        power = Power, node = Node, online = OL, dungeon_count = 0, welfare = Welfare
    };
thing_to_mb(_) -> #mb{}.

%% 发送二进制给队员
send_to_team(TeamId, Bin) ->
    mod_team:cast_to_team(TeamId, {'send_to_team', Bin}).

%% 离开队伍
%% QuitType 0普通|1离线
quit_team(PS, QuitType) ->
    #player_status{id = RoleId, team = #status_team{team_id=TeamId}} = PS,
    case TeamId > 0 of
        true -> mod_team:cast_to_team(TeamId, {'quit_team', RoleId, QuitType});
        _ -> skip
    end.

%% 获取队伍内成员所有id @returns list() = [Id1, Id2,...]
get_mb_ids(TeamId) ->
    case mod_team:call_to_team(TeamId, 'get_mb_ids') of
        false -> [];
        Other -> Other
    end.

%% 获得队伍历史人员ID列表
get_his_teammate(TeamId) ->
    case mod_team:call_to_team(TeamId, 'get_his_teammate') of
        false -> [];
        Other -> Other
    end.

%% 告诉队伍进程场景信息
where_i_am(TeamId, Id, Scene, ScenenPoolId, CopyId, X, Y) when TeamId > 0 ->
    mod_team:cast_to_team(TeamId, {'change_my_position', Id, Scene, ScenenPoolId, CopyId, X, Y}),
    ok;
where_i_am(_, _, _, _, _, _, _) -> ok.

%% 处理升级回调事件
handle_event(PS = #player_status{}, #event_callback{type_id = ?EVENT_LV_UP}) ->
    #player_status{id = PlayerId, figure = #figure{lv = Lv}, team = #status_team{team_id=TeamId}} = PS,
    if
        TeamId>0 -> mod_team:cast_to_team(TeamId, {'update_team_mb', PlayerId, [{lv, Lv}]});
        true -> skip
    end,
    {ok, PS};
%% 客户端断开连接
handle_event(PS = #player_status{}, #event_callback{type_id = ?EVENT_DISCONNECT }) ->
    #player_status{id = PlayerId, team = #status_team{match_info = MatchInfo} = TeamStatus} = PS,
    if
        MatchInfo =/= [] ->
            mod_team_enlist:clear_role_match(PlayerId),
            {ok, PS#player_status{team = TeamStatus#status_team{match_info = []}}};
        true ->
            {ok, PS}
    end;

%% 处理角色改名回调事件
handle_event(PS = #player_status{}, #event_callback{type_id = ?EVENT_RENAME, data = Name}) ->
    #player_status{id = PlayerId, team = #status_team{team_id=TeamId}} = PS,
    if
        TeamId>0 -> mod_team:cast_to_team(TeamId, {'update_team_mb', PlayerId, [{name, Name}]});
        true -> skip
    end,
    {ok, PS};

%% 战力改变
handle_event(PS = #player_status{}, #event_callback{type_id = ?EVENT_COMBAT_POWER, data = #callback_combat_power_data{combat_power = CombatPower}}) ->
    #player_status{id = PlayerId, team = #status_team{team_id=TeamId}} = PS,
    if
        TeamId>0 -> mod_team:cast_to_team(TeamId, {'update_team_mb', PlayerId, [{power, CombatPower}]});
        true -> skip
    end,
    {ok, PS};
handle_event(PS = #player_status{}, #event_callback{type_id = ?EVENT_ONLINE_FLAG, data = OnlineFlag}) ->
    #player_status{id = RoleId, team = #status_team{team_id = TeamId}, sid = Sid} = PS,
    case TeamId > 0 of
        true ->
            mod_team:cast_to_team(TeamId, {'online_flag', RoleId, OnlineFlag, Sid});
        false ->
            skip
    end,
    {ok, PS};

handle_event(PS, _) ->
    {ok, PS}.

%% 有队伍 切入 幻魔场景
%%       切出 幻魔场景
change_scene_callback(Player, {OldSceneId, _OldScenePoolId, _OldCopyId, _OldX, _OldY}, _OldSceneData, NewSceneInfo) ->
    #player_status{team=#status_team{team_id = TeamId}, id = RoleId} = Player,
    if
        TeamId =/= 0 ->
            OldIsDesertedBossScene = local_boss_api:is_deserted_boss_scene(OldSceneId),
            NewIsDesertedBossScene = local_boss_api:is_deserted_boss_scene(NewSceneInfo),
            OldIsRewardBossScene   = local_boss_api:is_reward_boss_scene(OldSceneId),
            NewIsRewardBossScene   = local_boss_api:is_reward_boss_scene(NewSceneInfo),
            if 
                not OldIsDesertedBossScene andalso NewIsDesertedBossScene -> %% 切入
                    mod_team:cast_to_team(TeamId, {'force_set_join_type', enter_boss_scene, RoleId, 1}),
                    Player;
                OldIsDesertedBossScene andalso not NewIsDesertedBossScene -> %% 切出
                    mod_team:cast_to_team(TeamId, {'force_set_join_type', exit_boss_scene, RoleId, 2}),
                    Player;
                not OldIsRewardBossScene andalso NewIsRewardBossScene ->
                    mod_team:cast_to_team(TeamId, {'force_set_join_type', enter_boss_scene, RoleId, 1}),
                    Player;
                OldIsRewardBossScene andalso not NewIsRewardBossScene ->
                    mod_team:cast_to_team(TeamId, {'force_set_join_type', exit_boss_scene, RoleId, 2}),
                    Player;
                true ->
                    Player
            end;
        true ->
            Player 
    end.


%% 分享队员经验
share_mon_exp(AtterTeamId, AtterId, Exp, SceneId, ScenenPoolId, CopyId) ->
    case AtterTeamId > 0 of
        true  -> mod_team:cast_to_team(AtterTeamId, {'share_mon_exp', AtterId, Exp, SceneId, ScenenPoolId, CopyId});
        false -> skip
    end.

%% 队员击杀怪物
kill_mon(TeamId,AtterId, Mid) ->
    case TeamId > 0 of
        true  -> mod_team:cast_to_team(TeamId, {'kill_mon',AtterId,Mid});
        false -> skip
    end.

%% 切换场景或线路更新跟随者位置
change_location(Status) ->
    #player_status{team=STeam, follows=_FollowMbs, id=Id, scene=Scene, scene_pool_id=ScenePoolId, copy_id=CopyId, x=X, y=Y} = Status,
    case STeam#status_team.team_id > 0  of
        true ->
            mod_team:cast_to_team(STeam#status_team.team_id, {'change_location', Id, Scene, ScenePoolId, CopyId, X, Y});
        false ->
            skip
    end.

%% 中断跟随
inerrupt_follow(TeamId, Id) ->
    case TeamId > 0 of
        true  -> mod_team:cast_to_team(TeamId, {'inerrupt_follow', Id});
        false -> skip
    end.

%% 队长离线挂机处理
team_to_onhook(Ps)->
    #player_status{id = RoleId, sid = Sid, scene = SceneId, team = STeam} = Ps,
    #status_team{team_id = TeamId, positon = _Position} = STeam,
    if
%%        TeamId > 0 andalso Position == ?TEAM_LEADER ->
%%            mod_team:cast_to_team(TeamId, {'onhook_team_to_match', RoleId});
        TeamId > 0 -> %% 离线挂机直接退出队伍
            mod_team:cast_to_team(TeamId, {'quit_team', RoleId, 1});
        true ->
            {Target, _LvMin, _LvMax} = lib_team:get_onhook_target_type(SceneId),
            #team_enlist{activity_id = ActivityId, subtype_id = SubId} = Target,
            Mb = thing_to_mb(Ps),
            mod_team_enlist:match_teams(Mb, Sid, [{ActivityId, SubId}])
    end.

%%任务完成 需要解散任务标记队伍
after_finish_task(TaskID,Status)->
    case lists:member(TaskID,[10006000]) of
        true->
            #player_status{id=RoleID,team=Team}=Status,
            #status_team{team_id=TeamID} = Team,
            mod_team:cast_to_team(TeamID, {'quit_team', RoleID, 2});
        _->
            ignore
    end.

need_check_password(Password) ->
    Password =/= ?DEFAULT_PASS.


get_svr_by_team(TeamId) ->
    <<SvrId:16, _:32>> = <<TeamId:48>>,
    SvrId.

is_local_team(TeamId) ->
    ServerId = get_svr_by_team(TeamId),
    config:get_server_id() == ServerId.