%% ---------------------------------------------------------------------------
%% @doc lib_guild_api.erl

%% @author  hjh
%% @email  hejiahua@163.com
%% @since  2016-12-28
%% @deprecated 公会接口
%% ---------------------------------------------------------------------------
-module(lib_guild_api).
-export([

    ]).

-compile(export_all).

-include("guild.hrl").
-include("scene.hrl").
-include("predefine.hrl").
-include("server.hrl").
-include("def_event.hrl").
-include("rec_event.hrl").
-include("figure.hrl").
-include("def_module.hrl").
-include("def_daily.hrl").
-include("common.hrl").
-include("activitycalen.hrl").
-include("rec_offline.hrl").
-include("def_fun.hrl").
-include("dungeon.hrl").
-include("sql_guild.hrl").
-include("language.hrl").
-include("chat.hrl").
-include("common_rank.hrl").

-export ([
        % sync_get_liveness_and_guild_num/1,    %%同步获取公会活跃度和公会人数
        % async_get_liveness_and_guild_num/4,   %%异步获取公会活跃度和公会人数，cast回调模块
        % get_liveness_and_guild_num/1          %%获取公会活跃度和公会人数(公会进程调用)
    ]).

%%社长登录 需要取消代理社长的权限
handle_event(Player, #event_callback{type_id = ?EVENT_LOGIN_CAST}) when is_record(Player, player_status) ->
    #player_status{
        figure = #figure{guild_id = GuildId},
        guild = #status_guild{position = Position}
    } = Player,
    case GuildId > 0 andalso Position == ?POS_CHIEF of
        true ->
            mod_guild:chief_reback(GuildId);
        false ->
            skip
    end,
    {ok, Player};

handle_event(Player, #event_callback{type_id = ?EVENT_LV_UP}) when is_record(Player, player_status) ->
    #player_status{id = RoleId, figure = #figure{lv = Lv, guild_id = GuildId} } = Player,
    case GuildId > 0 of
        true -> mod_guild:update_guild_member_attr(RoleId, [{lv, Lv}]);
        false -> skip
    end,
    {ok, Player};

handle_event(Player, #event_callback{type_id = ?EVENT_COMBAT_POWER}) when is_record(Player, player_status) ->
    #player_status{id = RoleId, figure = #figure{guild_id = GuildId}, combat_power = CombatPower} = Player,
    case GuildId > 0 of
        true ->
            mod_guild:update_guild_member_power(RoleId, CombatPower);
        false ->
            skip
    end,
    {ok, Player};

handle_event(Player, #event_callback{type_id = ?EVENT_PICTURE_CHANGE}) when is_record(Player, player_status) ->
    #player_status{id = RoleId, figure = #figure{picture = Picture, picture_ver = PictureVer, guild_id = GuildId} } = Player,
    case GuildId > 0 of
        true -> mod_guild:update_guild_member_attr(RoleId, [{picture, Picture}, {picture_ver, PictureVer}]);
        false -> skip
    end,
    {ok, Player};

handle_event(Player, #event_callback{type_id = ?EVENT_ONLINE_FLAG, data = OnlineFlag}) when is_record(Player, player_status) ->
    #player_status{id = RoleId, figure = #figure{guild_id = GuildId}, online = OldOnlineFlag} = Player,
    case GuildId > 0 of
        true ->
            NowTime = utime:unixtime(),
            if
                OnlineFlag == ?ONLINE_ON -> %% 这里顺序不要改 时间要在online_flag前面
                    mod_guild:update_guild_member_attr(RoleId, [{last_login_time, NowTime}, {online_flag, ?ONLINE_ON}]);
                % OnlineFlag == ?ONLINE_OFF_HOSTING -> %% 这里顺序不要改 时间要在online_flag前面
                %     mod_guild:update_guild_member_attr(RoleId, [{last_login_time, NowTime}, {online_flag, ?ONLINE_OFF_HOSTING}]);
                % OldOnlineFlag == ?ONLINE_OFF_HOSTING andalso OnlineFlag == ?ONLINE_OFF ->
                %     mod_guild:update_guild_member_attr(RoleId, [{last_logout_time, NowTime}, {online_flag, ?ONLINE_OFF}]);
                OldOnlineFlag == ?ONLINE_ON andalso OnlineFlag == ?ONLINE_OFF ->
                    mod_guild:update_guild_member_attr(RoleId, [{last_logout_time, NowTime}, {online_flag, ?ONLINE_OFF}]);
                true -> skip
            end;
        false -> skip
    end,
    {ok, Player};

handle_event(Player, #event_callback{type_id = ?EVENT_VIP}) when is_record(Player, player_status) ->
    #player_status{id = RoleId, figure = #figure{guild_id = GuildId, vip = Vip} } = Player,
    case GuildId > 0 of
        true -> mod_guild:update_guild_member_attr(RoleId, [{vip, Vip}]);
        false -> skip
    end,
    {ok, Player};

handle_event(Player, #event_callback{type_id = ?EVENT_JOIN_GUILD}) when is_record(Player, player_status) ->
    NewPlayer = handle_enter_guild(Player),
    {ok, NewPlayer};
handle_event(Player, #event_callback{type_id = ?EVENT_GUILD_QUIT, data = [LeaveGuildId, _LeaveDonate]}) when is_record(Player, player_status) ->
    AttrList = [
        {guild_id, 0}
        , {guild_name, <<>>}
        , {guild_lv, 0}
        , {position, 0}
        , {position_name, <<>>}
        , {create_time, 0}
        , {leave_time, utime:unixtime()}
        , {building_lv_map, #{}}
        , {depot_score, 0}
        , {badge,[]}
        , {flag, 0}
        ],
    #player_status{
        id = RoleId,
        scene = Scene,
        old_scene_info = OldSceneInfo
    } = Player,
    NewPlayer1 = handle_quit_gild(Player, ?EVENT_GUILD_QUIT),
    NewPlayer3 = lib_guild_support_mod:quit_guild(NewPlayer1),
    {ok, NewPlayer} = lib_guild:update_and_send_guild_info(NewPlayer3, AttrList),
    case lib_guild_api:check_in_guild_scene(Scene) of
        true->
            mod_guild_tribe_mgr:exit_scene(RoleId,LeaveGuildId,OldSceneInfo);
        _->
            skip
    end,
    lib_daily:set_count(RoleId,?MOD_GUILD_LABOR,0,2,0),
    {ok, NewPlayer};

handle_event(Player, #event_callback{type_id = ?EVENT_GUILD_DISBAND, data = LeaveGuildId}) when is_record(Player, player_status) ->
    AttrList = [
        {guild_id, 0}
        , {guild_name, <<>>}
        , {guild_lv, 0}
        , {position, 0}
        , {position_name, <<>>}
        , {create_time, 0}
        , {badge,[]}
        ],
    #player_status{
        id = RoleId,
        scene = Scene,
        old_scene_info = OldSceneInfo
    } = Player,
    NewPlayer1 = handle_quit_gild(Player, ?EVENT_GUILD_DISBAND),
    NewPlayer4 = lib_guild_support_mod:quit_guild(NewPlayer1),
    {ok, NewPlayer} = lib_guild:update_and_send_guild_info(NewPlayer4, AttrList),
    case lib_guild_api:check_in_guild_scene(Scene) of
        true->
            mod_guild_tribe_mgr:exit_scene(RoleId,LeaveGuildId,OldSceneInfo);
        _->
            skip
    end,
    {ok, NewPlayer};

handle_event(Player, #event_callback{type_id = ?EVENT_GUILD_MERGE, data = {GuildMember,Glv,Badges}}) when is_record(Player, player_status) ->
    #guild_member{id=RoleID,guild_id=GuildId,guild_name=GName}=GuildMember,
    #player_status{
        scene = Scene,
        old_scene_info = OldSceneInfo
    }=Player,
    #base_guild_pos{name = PName}=data_guild:get_guild_pos(5),
    AttrList = [
        {guild_id, GuildId}
        , {guild_name, GName}
        , {guild_lv, Glv}
        , {position, 5}
        , {position_name,PName}
        , {badge,Badges}
        ],
    {ok, NewPlayer} = lib_guild:update_and_send_guild_info(Player, AttrList),
    mod_guild:send_guild_info(RoleID, GuildId, 0),
    case lib_guild_api:check_in_guild_scene(Scene) of
        true->
            mod_guild_tribe_mgr:exit_scene(RoleID,0,OldSceneInfo);
        _->
            skip
    end,
    {ok, NewPlayer};

handle_event(Player, #event_callback{type_id = ?EVENT_RENAME, data = Name}) when is_record(Player, player_status) ->
    #player_status{id = RoleId, figure = #figure{guild_id = GuildId}} = Player,
    case GuildId > 0 of
        true ->
            mod_guild:update_guild_member_attr(RoleId, [{name, Name}]);
        false -> skip
    end,
    {ok, Player};

handle_event(Player, #event_callback{type_id = ?EVENT_TURN_UP}) when is_record(Player, player_status) ->
    #player_status{id = RoleId, figure = #figure{guild_id = GuildId, turn = Turn}} = Player,
    case GuildId > 0 of
        true -> mod_guild:update_guild_member_attr(RoleId, [{turn, Turn}]);
        false -> skip
    end,
    {ok, Player};

handle_event(Player, _Event) ->
    {ok, Player}.

handle_event(_Event) ->
    ok.

%% ------------- mod_guild进程内部调用,不要导致报错 ------------------

%% 创建公会
create_guild(Guild, GuildMember) ->
    lib_guild_util:log_guild_member(Guild, ?GLOG_CREATE, [GuildMember]),
    ok.

%% 加入公会
join_guild(Guild, GuildMember) ->
    common_join_guild(?GEVENT_JOIN_GUILD, Guild, GuildMember),
    #guild_member{id=MemID, guild_id = GuildId} = GuildMember,
    lib_player:apply_cast(MemID, ?APPLY_CAST_STATUS, ?MODULE, send_to_guild_channel, [GuildId]),
    ok.

send_to_guild_channel(Player, GuildId) ->
    #player_status{server_id = SerId, server_num = SerNum, server_name = ServerName, id = Id, figure = Figure} = Player,
    case data_language:get(?MOD_GUILD, 5) of
        #language{content = MsgSend} ->
            PackData = [?CHAT_CHANNEL_GUILD, SerId, SerNum, ServerName, Id, Figure, MsgSend, "[]", 0, utime:unixtime(), 0, 0],
            {ok, BinData} = pt_110:write(11001, PackData),
            lib_server_send:send_to_guild(GuildId, BinData);
        _ -> skip
    end.

join_guild(?GEVENT_CREATE_GUILD, Guild, GuildMember) ->
    common_join_guild(?GEVENT_CREATE_GUILD, Guild, GuildMember),
    ok.

common_join_guild(Event, Guild, GuildMember) ->
    #guild_member{id = RoleId, guild_id = GuildId, guild_name = GuildName,
        position = Position, create_time = CreateTime, figure = Figure, labors = Labors
    } = GuildMember,
    PositionNameMap = lib_guild_data:get_position_name_map(GuildId),
    PositionName = maps:get(Position, PositionNameMap, ""),
    % BuildDingMap = lib_guild_building_mod:get_build_lv_map(Guild),
    #guild{chief_id=Cid,badges=Badges,lv=GuildLv,member_num = MemberNum, combat_power = GuildPower} = Guild,
    List = [
        {guild_id, GuildId}
        , {guild_name, GuildName}
        , {guild_lv, Guild#guild.lv}
        , {position, Position}
        , {position_name, PositionName}
        , {create_time, CreateTime}
        , {badge,Badges}
        , {flag, Guild#guild.flag}
        % , {building_lv_map, BuildDingMap}
        ],
    lib_player:apply_cast(RoleId, ?APPLY_CAST_SAVE, lib_guild, update_and_send_guild_info, [List]),
    mod_chat_agent:update(RoleId, [{guild_id, GuildId}, {guild_name, GuildName}]),
    % lib_relationship:update_rela_role_info(RoleId,
    %                                        [{guild_id, GuildId}, {guild_name, GuildName}, {position, Position}, {position_name, PositionName}]),
    lib_player_event:async_dispatch(RoleId, ?EVENT_JOIN_GUILD),
    %lib_player:apply_cast(RoleId, ?APPLY_CAST_STATUS, lib_common_rank_api, reflash_role_info, []),
    lib_role:update_role_show(
        RoleId
        , [{guild_id, GuildId}, {guild_name, GuildName}, {position, Position}, {position_name, PositionName}]
    ),
    lib_guild_util:log_guild_member(Guild, ?GLOG_JOIN, [GuildMember]),
    RoleId /= Cid andalso lib_mail_api:send_sys_mail([RoleId], ?MOD_GUILD, utext:get(4000010), utext:get(4000011, [Guild#guild.lv,GuildName]), []),
    %% 刷新榜单
    lib_common_rank_api:refresh_rank_by_guild(Guild),
    %% 社团竞速团长任务
    SumCombatPower = lib_guild_util:count_guild_combat_power(GuildId, utime:unixtime()),
    lib_guild_race_rank_task:trigger_power_up_task(GuildId, SumCombatPower),
    %% 触发任务
    lib_task_api:join_guild(RoleId),
    %% 社团竞速
    RoleInfo = {RoleId, Figure#figure.name, Figure#figure.vip, Figure#figure.sup_vip, Position, Figure#figure.power, Labors},
    mod_guild_race_rank:member_change({GuildId, GuildName, GuildLv} , RoleInfo, 1),
    lib_guild_race_rank_task:trigger_invite_role_task(GuildId, MemberNum),
    %% 推送新的公会权限给客户端
    lib_guild:send_permission_list_to_role(RoleId, GuildId, Position),
    %% TA数据上报
    case Event of
        ?GEVENT_CREATE_GUILD -> EventType = 1;
        _ -> EventType = 2
    end,
    UpInfo = {RoleId, EventType, GuildId, GuildName, GuildLv, MemberNum,
        GuildPower, 0, Position},
    mod_common_rank:apply_cast(?MODULE, ta_data_update,
        [?RANK_TYPE_GUILD, UpInfo]),
    ok.

%% TA数据上报
ta_data_update(State, [RankType, UpInfo]) ->
    case UpInfo of
        {RoleId, EventType, GuildId, GuildName, GuildLv, MemberNum,
            GuildPower, OldPosition, NewPosition} ->
            #common_rank_state{guild_maps = RankMaps} = State,
            RankList = maps:get(RankType, RankMaps, []),
            case lists:keyfind(GuildId, #common_rank_guild.guild_id, RankList) of
                #common_rank_guild{rank = GuildRank} -> ok;
                _ -> GuildRank = 0
            end,
	        UnInfo1 = [EventType, GuildId, GuildName, GuildLv, MemberNum,
		        GuildPower, GuildRank, OldPosition, NewPosition],
            lib_player:apply_cast(RoleId, ?APPLY_CAST_STATUS, ?HAND_OFFLINE,
	            lib_guild_mod, after_guild_change, [UnInfo1]
            ),
            ok;
        _ ->
            ignore
    end,
    {ok, State}.

%% 退出公会
% 主动退出公会
quit_guild(?GEVENT_QUIT, Guild, GuildMember) ->
    lib_guild_util:log_guild_member(Guild, ?GLOG_QUIT, [GuildMember]),
    common_quit_guild(?GEVENT_QUIT, Guild, GuildMember),
    ok;
% 被踢出公会
quit_guild(?GEVENT_KICK_OUT, Guild, GuildMember) ->
    lib_guild_util:log_guild_member(Guild, ?GLOG_KICK_OUT, [GuildMember]),
    lib_mail_api:send_sys_mail([GuildMember#guild_member.id], ?MOD_GUILD, utext:get(4000013), utext:get(4000014), []),
    common_quit_guild(?GEVENT_KICK_OUT, Guild, GuildMember),
    ok.

common_quit_guild(EventType, Guild, GuildMember) ->
    #guild_member{id = RoleId, figure=#figure{name=Name} = _Figure, guild_id = GuildId, position = OldPosition} = GuildMember,
    % spawn(fun() -> lib_guild:db_player_guild_replace(RoleId, Donate, GuildId) end),
    lib_player_event:async_dispatch(RoleId, ?EVENT_GUILD_QUIT, [GuildId,0]),
    mod_chat_agent:update(RoleId, [{guild_id, 0}, {guild_name, <<>>}, {position, 0}, {position_name, <<>>}]),
    % lib_relationship:update_rela_role_info(RoleId, [{guild_id, 0}, {guild_name, <<>>}]),
    lib_auction_api:quit_guild(RoleId),
    mod_red_envelopes:quit_guild(RoleId, GuildId),
    lib_offline_api:update_offline_ps(RoleId, [{guild_id, 0}, {guild_name, <<>>}]),
    %lib_player:apply_cast(RoleId, ?APPLY_CAST_STATUS, ?HAND_OFFLINE, lib_common_rank_api, reflash_role_info, []),
    lib_role:update_role_show(
        RoleId, [{guild_id, 0}, {guild_name, <<>>}, {position, 0}, {position_name, <<>>}]
        ),
    %% 移除第一公会称号
    DesignationId = lib_common_rank_api:get_guild_title_id(),
    case DesignationId > 0 of
        true ->
            lib_designation_api:cancel_dsgt(RoleId, DesignationId);
        false -> skip
    end,
    %% 刷新榜单
    lib_common_rank_api:refresh_rank_by_guild(Guild),
    %% 更新社团竞榜数据
    mod_guild_race_rank:member_change(GuildId, RoleId, 0),
    %% 社团竞速团长任务
    SumCombatPower = lib_guild_util:count_guild_combat_power(GuildId, utime:unixtime()),
    lib_guild_race_rank_task:trigger_power_up_task(GuildId, SumCombatPower),
    %% 推送新的公会权限给客户端
    lib_guild:send_permission_list_to_role(RoleId, GuildId, 0),
    {ok,Bin} = pt_400:write(40030,[RoleId,Name]),
    lib_server_send:send_to_guild(GuildId, Bin),
    %% TA数据上报
    TaEventType =
    case EventType of
        ?GEVENT_KICK_OUT -> 3;
        _ -> 6
    end,
    #guild{name = GuildName, lv = GuildLv, member_num = MemberNum, combat_power = GuildPower} = Guild,
    UpInfo = {RoleId, TaEventType, GuildId, GuildName, GuildLv, MemberNum,
        GuildPower, OldPosition, 0},
    mod_common_rank:apply_cast(?MODULE, ta_data_update,
        [?RANK_TYPE_GUILD, UpInfo]),
    ok.

%%合并社团
merge_guild(Guild,GuildMemberList)->
    MemberLen = erlang:length(GuildMemberList),
    F = fun(GuildMember) -> guild_member_af_merge_guild(Guild,GuildMember,MemberLen) end,
    lists:foreach(F, GuildMemberList),
    ok.

guild_member_af_merge_guild(Guild,GuildMember,MergeMemberLen) ->
    #guild{id=GuildId,name=GName,lv=GLv,badges=Badges,member_num = MemberNum, combat_power = GuildPower}=Guild,
    #guild_member{id = RoleId, figure = Figure,position = OldPosition} = GuildMember,
    NGuildMember = GuildMember#guild_member{guild_id=GuildId,guild_name=GName,position=5,precursor=0,labors=0},
    lib_player_event:async_dispatch(RoleId, ?HAND_OFFLINE, ?EVENT_GUILD_MERGE, {NGuildMember,GLv,Badges}),
    mod_chat_agent:update(RoleId, [{guild_id, GuildId}, {guild_name, GName}]),
    lib_offline_api:update_offline_ps(RoleId, [{guild_id, GuildId}, {guild_name, GName}]),
    %% 社团竞速
    RoleInfo = {RoleId, Figure#figure.name, Figure#figure.vip, Figure#figure.sup_vip, 5, Figure#figure.power, 0},
    mod_guild_race_rank:member_change({GuildId, GName, GLv}, RoleInfo, 1),
    #base_guild_pos{name = PName}=data_guild:get_guild_pos(5),
    lib_role:update_role_show(
        RoleId
        , [{guild_id, GuildId}, {guild_name, GName}, {position, 5}, {position_name, PName}]
    ),
    lib_guild_util:log_guild_member(Guild, ?GLOG_MERGE, [GuildMember, NGuildMember]),
    %% TA数据上报
    UpInfo = {RoleId, 8, GuildId, GName, GLv, MemberNum+MergeMemberLen,
        GuildPower, OldPosition, 5},
    mod_common_rank:apply_cast(?MODULE, ta_data_update,
        [?RANK_TYPE_GUILD, UpInfo]),
    ok.


after_merge_guild(Guild)->
    #guild{id = GuildId} = Guild,
    lib_common_rank_api:disband_guild(GuildId),
    mod_red_envelopes:disband_guild(GuildId),
    %% 社团竞速
    mod_guild_race_rank:guild_disband(GuildId),
    ok.


%% 解散公会
%% @param ChiefGuildMember #guild_member{} | []
disband_guild(Guild, ChiefGuildMember, GuildMemberList) ->
    #guild{id = GuildId} = Guild,
    F = fun(GuildMember) -> guild_member_af_disband_guild(Guild, GuildMember) end,
    lists:foreach(F, GuildMemberList),
    lib_guild_util:log_guild_member(Guild, ?GLOG_DISBAND, [ChiefGuildMember]),
    lib_common_rank_api:disband_guild(GuildId),
    mod_red_envelopes:disband_guild(GuildId),
    %% 社团竞速
    mod_guild_race_rank:guild_disband(GuildId),
    ok.

guild_member_af_disband_guild(Guild, GuildMember) ->
    #guild_member{id = RoleId, guild_id = GuildId, position = Position} = GuildMember,
	#guild{name = GuildName, lv = GuildLv, member_num = MemberNum, combat_power = GuildPower} = Guild,
    % spawn(fun() -> lib_guild:db_player_guild_replace(RoleId, Donate, GuildId) end),
    lib_player_event:async_dispatch(RoleId, ?HAND_OFFLINE, ?EVENT_GUILD_DISBAND, GuildId),
    mod_chat_agent:update(RoleId, [{guild_id, 0}, {guild_name, <<>>}]),
    % lib_relationship:update_rela_role_info(RoleId, [{guild_id, 0}, {guild_name, <<>>}, {position, 0}, {position_name, <<>>}]),
    lib_auction_api:quit_guild(RoleId),
    lib_offline_api:update_offline_ps(RoleId, [{guild_id, 0}, {guild_name, <<>>}]),
    %lib_player:apply_cast(RoleId, ?APPLY_CAST_STATUS, ?HAND_OFFLINE, lib_common_rank_api, reflash_role_info, []),
    lib_role:update_role_show(
        RoleId
        , [{guild_id, 0}, {guild_name, <<>>}, {position, 0}, {position_name, <<>>}]
    ),
	%% TA数据上报
	UpInfo = {RoleId, 5, GuildId, GuildName, GuildLv, MemberNum,
		GuildPower, Position, 0},
	mod_common_rank:apply_cast(?MODULE, ta_data_update,
		[?RANK_TYPE_GUILD, UpInfo]),
    ok.

%% 更改公会玩家信息
%% @param Type: 1-10

%% 变成会长
change_guild_member(EventType, [Guild, OldChiefMember, OldGuildMember, GuildMember, AppointType]) when
        EventType == ?GEVENT_APPOINT_POSITION_TO_CHIEF ->
    #guild_member{id = RoleId, figure = Figure, guild_id = GuildId, position = Position} = GuildMember,
    #figure{name = RoleName} = Figure,
    PositionNameMap = lib_guild_data:get_position_name_map(GuildId),
    PositionName = maps:get(Position, PositionNameMap, ""),
    List = [{position, Position}, {position_name, PositionName}],
    lib_player:apply_cast(RoleId, ?APPLY_CAST_SAVE, lib_guild, update_and_send_guild_info, [List]),
    % 邮件
    OldChiefName = OldChiefMember#guild_member.figure#figure.name,
    #guild{name = GuildName, lv = GuildLv, member_num = MemberNum, combat_power = GuildPower} = Guild,
    case AppointType of
        ?MANUAL_APPOINT ->
            LogType = ?GLOG_POS_CHANGE,
            %% TA数据上报
            UpInfo = {RoleId, 4, GuildId, GuildName, GuildLv, MemberNum,
                GuildPower, Position, 1},
            lib_mail_api:send_sys_mail([RoleId], ?MOD_GUILD, utext:get(4000015), utext:get(4000016, [OldChiefName, GuildName]), []);
        _ ->
            LogType = ?GLOG_AUTO_CHIEF,
            UpInfo = {RoleId, 7, GuildId, GuildName, GuildLv, MemberNum,
                GuildPower, Position, 1},
            lib_mail_api:send_sys_mail([RoleId], ?MOD_GUILD, utext:get(4000015), utext:get(4000017, [GuildName]), [])
    end,
    % 传闻
    lib_chat:send_TV({guild, GuildId}, ?MOD_GUILD, 2, [RoleName,RoleId]),
    lib_role:update_role_show(RoleId, [{position, Position}, {position_name, PositionName}]),
    lib_guild_util:log_guild_member(Guild, LogType, [OldGuildMember, GuildMember]),
    %% 社团竞速活动
    mod_guild_race_rank:position_change(GuildId, RoleId, RoleName, Position),
    %% 推送新的公会权限给客户端
    lib_guild:send_permission_list_to_role(RoleId, GuildId, Position),
    mod_common_rank:apply_cast(?MODULE, ta_data_update,
        [?RANK_TYPE_GUILD, UpInfo]),
    lib_common_rank_api:rechange_guild_chief(GuildId, RoleId, RoleName),
    ok;

%% 其他职位(除了会长)
change_guild_member(EventType, [Guild, _OperatorGuildMember, OldGuildMember, GuildMember]) when
        EventType == ?GEVENT_APPOINT_POSITION_TO_OTHER ->
    #guild_member{id = RoleId, figure = Figure, guild_id = GuildId, position = Position} = GuildMember,
    #figure{name = RoleName} = Figure,
    PositionNameMap = lib_guild_data:get_position_name_map(GuildId),
    PositionName = maps:get(Position, PositionNameMap, ""),
    List = [{position, Position}, {position_name, PositionName}],
    lib_player:apply_cast(RoleId, ?APPLY_CAST_SAVE, lib_guild, update_and_send_guild_info, [List]),
    % 邮件
    % OperatorName = OperatorGuildMember#guild_member.figure#figure.name,
    % GuildName = Guild#guild.name,
    lib_mail_api:send_sys_mail([RoleId], ?MOD_GUILD, utext:get(4000018), utext:get(4000019, [PositionName]), []),
    lib_role:update_role_show(RoleId, [{position, Position}, {position_name, PositionName}]),
    lib_guild_util:log_guild_member(Guild, ?GLOG_POS_CHANGE, [OldGuildMember, GuildMember]),
    %% 社团竞速活动
    mod_guild_race_rank:position_change(GuildId, RoleId, RoleName, Position),
    %% 推送新的公会权限给客户端
    lib_guild:send_permission_list_to_role(RoleId, GuildId, Position),
    %% TA数据上报
    #guild{name = GuildName, lv = GuildLv, member_num = MemberNum, combat_power = GuildPower} = Guild,
    UpInfo = {RoleId, 4, GuildId, GuildName, GuildLv, MemberNum,
        GuildPower, OldGuildMember#guild_member.position, Position},
    mod_common_rank:apply_cast(?MODULE, ta_data_update,
        [?RANK_TYPE_GUILD, UpInfo]),
    ok;

%% 重新命名职位
change_guild_member(EventType, GuildMember) when
        EventType == ?GEVENT_RENAME_POSITION ->
    #guild_member{id = RoleId, guild_id = GuildId, position = Position} = GuildMember,
    PositionNameMap = lib_guild_data:get_position_name_map(GuildId),
    PositionName = maps:get(Position, PositionNameMap, ""),
    List = [
        {position, Position}
        , {position_name, PositionName}
        ],
    lib_player:apply_cast(RoleId, ?APPLY_CAST_SAVE, lib_guild, update_and_send_guild_info, [List]),
    lib_role:update_role_show(RoleId, [{position, Position}, {position_name, PositionName}]),
    ok;

%% 提升公会等级
change_guild_member(EventType, [GuildID, NewGuildLv]) when
        EventType == ?GEVENT_UPGRADE_GUILD ->
    GuildMemberMap = lib_guild_data:get_guild_member_map(GuildID),
    %% 更新社团竞速信息
    mod_guild_race_rank:guild_msg_change(GuildID, "", NewGuildLv, 2),
    List = [{guild_lv, NewGuildLv}],
    F = fun(RoleId, _, _Acc)->
        lib_player:apply_cast(RoleId, ?APPLY_CAST_SAVE, lib_guild, update_and_send_guild_info, [List])
    end,
    maps:fold(F, 0, GuildMemberMap),
    ok;

change_guild_member(EventType, [Guild, OldGuildMember, GuildMember]) when
        EventType == ?GEVENT_BECOME_NORAML_AF_APPOINT_OTHER_TO_CHIEF ->
    #guild_member{id = RoleId, guild_id = GuildId, position = Position, figure = Figure} = GuildMember,
    PositionNameMap = lib_guild_data:get_position_name_map(GuildId),
    PositionName = maps:get(Position, PositionNameMap, ""),
    List = [
        {position, Position}
        , {position_name, PositionName}
        ],
    lib_player:apply_cast(RoleId, ?APPLY_CAST_SAVE, lib_guild, update_and_send_guild_info, [List]),
    lib_role:update_role_show(RoleId, [{position, Position}, {position_name, PositionName}]),
    lib_guild_util:log_guild_member(Guild, ?GLOG_POS_CHANGE, [OldGuildMember, GuildMember]),
    %% 社团竞速活动
    mod_guild_race_rank:position_change(GuildId, RoleId, Figure#figure.name, Position),
    %% 推送新的公会权限给客户端
    lib_guild:send_permission_list_to_role(RoleId, GuildId, Position),
    %% TA数据上报
    #guild{name = GuildName, lv = GuildLv, member_num = MemberNum, combat_power = GuildPower} = Guild,
    UpInfo = {RoleId, 4, GuildId, GuildName, GuildLv, MemberNum,
        GuildPower, OldGuildMember#guild_member.position, Position},
    mod_common_rank:apply_cast(?MODULE, ta_data_update,
        [?RANK_TYPE_GUILD, UpInfo]),
    ok;

%%公会改名事件
change_guild_member(?GEVENT_RENAME, [GuildId, _OldGuildName, NowGuildName]) ->
    lib_common_rank_api:rename_guild(GuildId, NowGuildName),
    %% 更新社团竞速信息
    mod_guild_race_rank:guild_msg_change(GuildId, NowGuildName, 0, 1),
    guild_war_api:rename_guild(GuildId, NowGuildName),
    ok.


%% 更新公会成员之后的公会处理
guild_af_update_member_attr(Guild, GuildMember, AttrList) ->
    do_guild_af_update_guild_member_attr(AttrList, GuildMember, Guild),
    ok.

do_guild_af_update_guild_member_attr([], _GuildMember, _Guild) -> ok;
% do_guild_af_update_guild_member_attr([{name, _Name}|L], GuildMember, Guild) ->
%     #guild_member{id = RoleId} = GuildMember,
%     #guild{chief_id = ChiefId} = Guild,
%     case RoleId == ChiefId of
%         true -> lib_common_rank_api:reflash_rank_by_guild(Guild);
%         false -> skip
%     end,
%     do_guild_af_update_guild_member_attr(L, GuildMember, Guild);
do_guild_af_update_guild_member_attr([_T|L], GuildMember, Guild) ->
    do_guild_af_update_guild_member_attr(L, GuildMember, Guild).

%% 在跨服中心的接口
send_chief_figure_info_in_center(Node, RoleId, GuildId, ArgsMap) ->
    #{ser_id := SerId} = ArgsMap,
    clusters_center:apply_cast(SerId, mod_guild, send_chief_figure_info, [Node, RoleId, GuildId, ArgsMap]).

%% ------------------------------- 后台秘籍 ------------------------------------
%% 秘籍修改公会公告
modify_announce_by_gm(GuildId, Announce) ->
    case catch mod_guild:modify_announce_by_gm(GuildId, Announce) of
        {ok, Reply} ->
            ?ERR("modify_announce_by_gm code:~p", [Reply]),
            Reply;
        _Err ->
            ?ERR("modify_announce_by_gm err:~p", [_Err]),
            time_out
    end.

%% 秘籍修改公会名字
modify_guild_name_by_gm(GuildId, GuildName) ->
    case catch mod_guild:modify_name_by_gm(GuildId, GuildName) of
        {ok, Reply} ->
            ?ERR("modify_guild_name_by_gm code:~p", [Reply]),
            Reply;
        _Err ->
            ?ERR("modify_guild_name_by_gm err:~p", [_Err]),
            time_out
    end.

%% 秘籍解散公会
disband_guild_by_gm(GuildId) ->
    case lib_mutex_check:check_disband_guild(GuildId) of
        true ->
            case mod_guild:disband_guild_by_gm(GuildId) of
                {ok, Reply} ->
                    ?ERR("disband_guild_by_gm code:~p", [Reply]),
                    Reply;
                _Err ->
                    ?ERR("modify_announce_by_gm err:~p", [_Err]),
                    time_out
            end;
        {false, ErrorCode} -> ErrorCode
    end.

%%离开公会处理,
handle_quit_gild(Player, Type) ->
    CheckList = [],
    case do_handle_quit_gild(CheckList, Player, Type) of
        {no, NewPS} -> NewPS;
        {ok, NewPS} -> NewPS
    end.

do_handle_quit_gild([], PS, _Type) -> {no, PS};
do_handle_quit_gild([H|T], PS, Type) ->
    case do_act_handle_quit_gild(H, PS, Type) of
        {ok, NewPS} -> {ok, NewPS};
        {next, NewPS} -> do_handle_quit_gild(T, NewPS, Type)
    end.


do_act_handle_quit_gild(_, PS, _Type) ->
    {next, PS}.

%%加入公会处理
handle_enter_guild(Player) ->
    CheckList = [],
    case do_handle_enter_guild(CheckList, Player) of
        {no, NewPS} -> NewPS;
        {ok, NewPS} -> NewPS
    end.

do_handle_enter_guild([], PS) -> {no, PS};
do_handle_enter_guild([H|T], PS) ->
    case do_act_handle_enter_guild(H, PS) of
        {ok, NewPS} -> {ok, NewPS};
        {next, NewPS} -> do_handle_enter_guild(T, NewPS)
    end.

do_act_handle_enter_guild(_, PS) ->
    {next, PS}.

get_all_guild_ids(Pid) ->
    mod_guild:get_all_guild_ids(Pid).

% %%同步获取公会活跃度和公会人数
% sync_get_liveness_and_guild_num(GuildId) ->
%     case catch mod_guild:get_liveness_and_guild_num(GuildId) of
%         {LiveNess, Num} -> {LiveNess, Num};
%         _ -> {0, 0}
%     end.

% %%异步获取公会活跃度和公会人数，cast回调模块
% async_get_liveness_and_guild_num(GuildId, Mod, Function, Args) ->
%     mod_guild:apply_cast(?MODULE, do_async_get_liveness_and_guild_num, [GuildId, Mod, Function, Args]).

% do_async_get_liveness_and_guild_num([GuildId, Mod, Function, Args]) ->
%     {LiveNum, MemberNum} = get_liveness_and_guild_num(GuildId),
%     apply(Mod, Function, [LiveNum, MemberNum |Args]).

% %% 获取公会活跃度和公会人数(公会进程调用)
% get_liveness_and_guild_num(GuildId) ->
%     case lib_guild_data:get_guild_by_id(GuildId) of
%         #guild{liveness_list = LiveNessList, member_num = MemberNum} ->
%             LiveNum = lib_guild_mod:get_live_num(LiveNessList);
%         _ -> LiveNum = MemberNum = 0
%     end,
%     {LiveNum, MemberNum}.

check_day_night(_,undefined)->
    false;
check_day_night(NowSceneInfo,OldSceneInfo)->
    {NSceneId, _, _, _, _} = NowSceneInfo,
    {OSceneId, _, _, _, _} = OldSceneInfo,
    case data_scene:get(NSceneId) of
        #ets_scene{type =?SCENE_TYPE_GUILD} ->
            case data_scene:get(OSceneId) of
                #ets_scene{type =?SCENE_TYPE_GUILD} ->
                    true;
                _->
                    false
            end;
        _ ->
            false
    end.

%% 是否社团驻地
check_in_guild_scene(SceneId) when is_integer(SceneId) ->
    SceneData = data_scene:get(SceneId),
    check_in_guild_scene(SceneData);
check_in_guild_scene(#ets_scene{type = ?SCENE_TYPE_GUILD}) ->
    true;
check_in_guild_scene(_) ->
    false.

get_guild_scene()->
    [Start,End] = data_guild:get(guild_day_night),
    {_Date,{H,_M,_S}} = utime:localtime(),
    case Start=<H andalso H<End of
        true->
            data_guild:get(guild_scene);
        _->
            data_guild:get(guild_scene_night)
    end.

%% 获得公会会长
get_guild_chief(GuildId) ->
    mod_guild:apply_call(?MODULE, query_guild_chief, [GuildId], 5000).
query_guild_chief(GuildId) ->
    case lib_guild_data:get_guild_by_id(GuildId) of
        #guild{chief_id = ChiefId, chief_name = ChiefName} ->
            {ChiefId, ChiefName};
        _ ->
            {0, ""}
    end.


%% 给公会成员发邮件-传需要排除的玩家
send_mail_to_guild(GuildId, Mod, Title, Content, Reward, ExcludeRoles) ->
    mod_guild:apply_cast(?MODULE, guild_send_mail_to_members, [GuildId, Mod, Title, Content, Reward, ExcludeRoles]).
guild_send_mail_to_members(GuildId, Mod, Title, Content, Reward, ExcludeRoles) ->
    GuildMembers = lib_guild_data:get_guild_member_map(GuildId),
    AllRoles = [Id || #guild_member{id = Id} <- maps:values(GuildMembers)],
    lib_mail_api:send_sys_mail(AllRoles -- ExcludeRoles, Mod, Title, Content, Reward).

reconnect(Player) ->
    case check_in_guild_scene(Player#player_status.scene) of
        true  ->
            {MainX, MainY} = lib_scene:get_main_city_x_y(),
            {ok, Player#player_status{scene = ?MAIN_CITY_SCENE, x = MainX, y = MainY}};
        false ->
            {next, Player}
    end.

fix_guild_pool(SceneId, ScenePoolId, CopyId, GuildId) ->
    case lib_guild:is_guild_scene(SceneId) of
        true  ->
            {?GUILD_REM_POOL(GuildId), GuildId};
        false ->
            {ScenePoolId, CopyId}
    end.

