%% ---------------------------------------------------------------------------
%% @doc lib_guild_mod.erl

%% @author  hjh
%% @email  hejiahua@163.com
%% @since  2016-12-15
%% @deprecated 帮派进程
%% ---------------------------------------------------------------------------
-module(lib_guild_mod).
-export([]).

-compile(export_all).

-include("guild.hrl").
-include("sql_guild.hrl").
-include("figure.hrl").
-include("errcode.hrl").
-include("server.hrl").
-include("common.hrl").
-include("role.hrl").
-include("chat.hrl").
-include("def_module.hrl").
-include("def_daily.hrl").
-include("daily.hrl").
-include("def_fun.hrl").
-include("predefine.hrl").
-include("goods.hrl").
-include("designation.hrl").
-include("def_goods.hrl").
-include("server_kv.hrl").

make_record({sql_guild,Now}, [Id,Name,Announce,ChiefId,ChiefName,Agent,AgentTime,Lv,Exp,Division,Funds,
        Arrears,Flag,CreateTime,ModifyTimes,ApproveType,AutoApproveLv,AutoApprovePower,
        DisbandWarnningTime,WeekLabor,WeekLaborRe,WeekLaborLast,CReName,CReNameTime,Badges0,PartyN0,AssistN0,WarWin,LastReNew0]) ->
    RealAnnounce = case Announce == <<>> of
        true -> utext:get(4000005);
        false -> Announce
    end,
    Badges = make_badge(util:bitstring_to_term(Badges0),Now,[]),
    case Now>LastReNew0 of
        true->
            PartyN=0,AssistN=0,LastReNew=utime:next_logic_week_start();
        _->
            PartyN=PartyN0,AssistN=AssistN0,LastReNew=LastReNew0
    end,
    Guild = #guild{
        id = Id
        , name = Name
        , name_upper = string:to_upper(util:make_sure_list(Name))
        , announce = RealAnnounce
        , chief_id = ChiefId
        , chief_name = ChiefName
        , agent = Agent
        , agent_time = AgentTime
        , lv = Lv
        , exp = Exp
        , division = Division
        , funds = Funds
        , arrears = Arrears
        , flag = Flag
        , create_time = CreateTime
        , modify_times = ModifyTimes
        , approve_type = ApproveType
        , auto_approve_lv = AutoApproveLv
        , auto_approve_power = AutoApprovePower
        , disband_warnning_time = DisbandWarnningTime
        , week_labor = WeekLabor
        , week_labor_refresh = WeekLaborRe
        , week_labor_last = WeekLaborLast
        , c_rename = CReName
        , c_rename_time = CReNameTime
        , badges = Badges
        , fire_num = PartyN
        , assist   = AssistN
        , war_win  = WarWin
        , last_renew = LastReNew
    },
    mod_guild_cast:self_update_week_labor(guild,Guild);

make_record({sql_guild_member,Now}, [Id, GuildId, GuildName, Position,Precursor,WLabor0,WTime0,Labors,CreateTime]) ->
    case Now == WTime0 of
        true->
            WTime = WTime0,
            WLabor = WLabor0;
        _->
            WTime = Now,
            WLabor = 0
    end,
    #guild_member{
        id = Id
        , guild_id = GuildId
        , guild_name = GuildName
        , position = Position
        , precursor = Precursor
        , week_labor = WLabor
        , week_labor_refresh = WTime
        , labors = Labors
        , create_time = CreateTime
    };

make_record(guild_member, [Id, GuildId, GuildName, Position, CreateTime, Figure, OnlineFlag,
        LastLoginTime, LastLogoutTime, CombatPower, HCombatPower]) ->
    #guild_member{
        id = Id
        , figure = Figure
        , guild_id = GuildId
        , guild_name = GuildName
        , position = Position
        , online_flag = OnlineFlag
        , last_login_time = LastLoginTime
        , last_logout_time = LastLogoutTime
        , combat_power = CombatPower
        , h_combat_power = HCombatPower
        , create_time = CreateTime
    };

make_record(guild_apply, [RoleId, GuildId, CreateTime,Position]) ->
    #guild_apply{
        key = {RoleId, GuildId}
        , role_id = RoleId
        , guild_id = GuildId
        , create_time = CreateTime
        , position = Position
    };

make_record(guild_merge, [GuildID,TApply,FApplys0,Notes0])->
    Notes1 = util:bitstring_to_term(Notes0),
    FApplys1 = util:bitstring_to_term(FApplys0),
    Notes  = case is_list(Notes1) of
        true->
            Notes1;
        _->
            []
    end,
    FApplys  = case is_list(FApplys1) of
        true->
            FApplys1;
        _->
            []
    end,
    #guild_merge{
        guild_id = GuildID,
        tapply = TApply,
        fapplys = FApplys,
        notes = Notes
    }.


make_badge(undefined,_Now,Badges)->
    Badges;
make_badge([],_Now,Badges)->
    Badges;
make_badge([{Id,Stime,Etime}|T],Now,Badges)->
    case data_guild:get_badge(Id) of
        #base_badge{type=Type,cool=Cool}->
            case Cool>0 of
                true when Now>=Etime->
                    make_badge(T,Now,Badges);
                _->
                    Data = #guild_badge{id=Id,type=Type,stime=Stime,etime=Etime},
                    make_badge(T,Now,[Data|Badges])
            end;
        _->
            make_badge(T,Now,Badges)
    end.


%% ----------------------------------------------------
%% 进程启动初始化
%% ----------------------------------------------------

%% 初始化
init() ->
    Now = utime:logic_week_start(),
    init_guild_and_member(Now),
    init_guild_apply(),
    init_guild_merge(),
    self() ! 'init_guild_figure'.

%% 初始公会和成员
init_guild_and_member(Now) ->
    Sql = io_lib:format(?sql_guild_select_all, []),
    List = db:get_all(Sql),
    GuildMap = make_guild_map(List,Now,#{}),
    Guilds = maps:to_list(GuildMap),
    NewGuildMap = init_member_and_make_guild(Guilds,Now,GuildMap),
    lib_guild_data:save_guild_map(NewGuildMap).
    % lib_guild_support_mod:init_load_support(maps:keys(GuildMap)).

load_guild_badges(_GuildID)->
    [].


%% 初始化公会Map
make_guild_map([],_Now,GuildMap) -> GuildMap;
make_guild_map([T|L],Now,GuildMap) ->
    Guild = make_record({sql_guild,Now}, T),
    NewGuildMap = maps:put(Guild#guild.id, Guild, GuildMap),
    make_guild_map(L,Now,NewGuildMap).

%% 初始化成员和组装Guild
init_member_and_make_guild([],_Now,GuildMap) -> GuildMap;
init_member_and_make_guild([{GuildId, Guild}|L],Now,GuildMap) ->
    case init_guild_member(GuildId,Now,Guild) of
        [] -> NewGuildMap = maps:remove(GuildId, GuildMap);
        GuildMemberList ->
            NowTime = utime:unixtime(),
            {MemberNum, CombatPower} = calc_guild_data_by_member_list(GuildMemberList, NowTime, {0, 0}),
            NewGuild = Guild#guild{
                member_num = MemberNum
                , combat_power = CombatPower
                },
            NewGuildMap = maps:put(GuildId, NewGuild, GuildMap)
    end,
    init_member_and_make_guild(L,Now,NewGuildMap).

%% 初始化成员
init_guild_member(GuildId,Now,_Guild) ->
    Sql = io_lib:format(?sql_guild_member_select_by_guild_id, [GuildId]),
    List = db:get_all(Sql),
    F = fun([Id, GuildName, Position,Precursor,WLabor,WTime,Labors,CreateTime]) ->
        GuildMemberTmp = make_record({sql_guild_member,Now}, [Id, GuildId, GuildName, Position,Precursor,WLabor,WTime,Labors, CreateTime]),
        % case lib_role:get_figure_on_db(Id) of
        %     [] -> Figure = #figure{};
        %     Figure -> ok
        % end,
        Figure = #figure{},
        [_AccId, _AccName, _OnlineFlag, LastLoginTime, LastLogoutTime, LastLogoutCombatPower, HCombatPower] = lib_role:get_role_show_other_info(Id),
        %% 如果玩家最后登录时间>最后登出时间,表示玩家没有正常登出,重置最后登出时间为最后登录时间
        RealLastLogoutTime = ?IF(LastLoginTime > LastLogoutTime, LastLoginTime, LastLogoutTime),
        GuildMember = GuildMemberTmp#guild_member{
            figure = Figure#figure{power=LastLogoutCombatPower}
            , online_flag = ?ONLINE_OFF
            , last_login_time = LastLoginTime
            , last_logout_time = RealLastLogoutTime
            , combat_power = LastLogoutCombatPower
            , h_combat_power = HCombatPower
            },
        lib_guild_data:update_guild_member(GuildMember),
        GuildMember
    end,
    GuildMemberList = lists:map(F, List),
    GuildMemberList.

%% 根据成员信息计算公会数据
calc_guild_data_by_member_list([], _NowTime, Result) -> Result;
calc_guild_data_by_member_list([GuildMember|T], NowTime, {MemberNum, SumCombatPower}) ->
    #guild_member{
        last_logout_time = LastLogoutTime,
        combat_power = CombatPower
        } = GuildMember,
    NewMemberNum = MemberNum + 1,
    NewSumCombatPower = case NowTime - LastLogoutTime < ?CAL_GUILD_POWER_VAILD_TIME of
        true -> SumCombatPower + CombatPower;
        false -> SumCombatPower + CombatPower
    end,
    calc_guild_data_by_member_list(T, NowTime, {NewMemberNum, NewSumCombatPower}).


%% ----------------------------------------------------
%% 其他初始化
%% ----------------------------------------------------

%% 初始化公会请求
init_guild_apply() ->
    Sql = io_lib:format(?sql_guild_apply_select, []),
    List = db:get_all(Sql),
    % 公会请求
    F = fun([RoleId, GuildId, CreateTime,Position], Map) ->
        GuildApply = make_record(guild_apply, [RoleId, GuildId, CreateTime,Position]),
        maps:put({RoleId, GuildId}, GuildApply, Map)
    end,
    Map = lists:foldl(F, maps:new(), List),
    put(?P_GUILD_APPLY, Map),
    % 公会的玩家id请求列表
    F2 = fun({RoleId, GuildId}, _Apply, TmpMap) ->
        MemberIdList = maps:get(GuildId, TmpMap, []),
        case lists:member(RoleId, MemberIdList) of
            false -> NewMeberIdList = [RoleId|MemberIdList];
            true -> NewMeberIdList = MemberIdList
        end,
        maps:put(GuildId, NewMeberIdList, TmpMap)
    end,
    ApplyGuildMap = maps:fold(F2, maps:new(), Map),
    put(?P_GUILD_APPLY_GUILD, ApplyGuildMap),
    Map.

%初始化合并申请数据
init_guild_merge()->
    Sql = io_lib:format(?sql_guild_merge_select, []),
    List = db:get_all(Sql),
    F = fun([GuildID,TApply,FApplys,Notes], Map) ->
        GuildMerge = make_record(guild_merge, [GuildID,TApply,FApplys,Notes]),
        maps:put(GuildID, GuildMerge, Map)
    end,
    Map = lists:foldl(F, maps:new(), List),
    put(?P_GUILD_MERGE_GUILD, Map),
    Map.

%% 初始化职位权限
%% 职位权限 Value:#{Pos = #{PermissionType=IsAllow} }
init_position_permission_map(GuildId) ->
    % 读配置初始化
    F = fun(Position, TmpMap) ->
        case data_guild:get_guild_pos(Position) of
            [] -> PermissionList = [];
            #base_guild_pos{permission_list = PermissionList} -> ok
        end,
        PermissionTypeMap = maps:get(Position, TmpMap, #{}),
        F2 = fun(PermissionType, TmpPermissionTypeMap) -> maps:put(PermissionType, ?IS_ALLOW_YES, TmpPermissionTypeMap) end,
        NewPermissionTypeMap = lists:foldl(F2, PermissionTypeMap, PermissionList),
        maps:put(Position, NewPermissionTypeMap, TmpMap)
    end,
    Map = lists:foldl(F, maps:new(), ?POS_LIST),
    % 数据库初始化
    Sql = io_lib:format(?sql_position_permission_select, [GuildId]),
    List = db:get_all(Sql),
    F3 = fun([Position, PermissionType, IsAllow], TmpMap) ->
        PermissionTypeMap = maps:get(Position, TmpMap, #{}),
        NewPermissionTypeMap = maps:put(PermissionType, IsAllow, PermissionTypeMap),
        maps:put(Position, NewPermissionTypeMap, TmpMap)
    end,
    NewMap = lists:foldl(F3, Map, List),
    put(?P_POS_PERMISSION(GuildId), NewMap),
    NewMap.

%% 初始化职位名字
%% 职位名字 Value:#{Pos = PositionName}
init_position_name_map(GuildId) ->
    % 读配置初始化
    F = fun(Position, TmpMap) ->
        case data_guild:get_guild_pos(Position) of
            [] -> PositionName = "";
            #base_guild_pos{name = PositionName} -> ok
        end,
        maps:put(Position, util:make_sure_binary(PositionName), TmpMap)
    end,
    Map = lists:foldl(F, maps:new(), ?POS_LIST),
    % 数据库初始化
    Sql = io_lib:format(?sql_position_name_select, [GuildId]),
    List = db:get_all(Sql),
    F2 = fun([Position, PositionName], TmpMap) -> maps:put(Position, util:make_sure_binary(PositionName), TmpMap) end,
    NewMap = lists:foldl(F2, Map, List),
    put(?P_POS_NAME(GuildId), NewMap),
    NewMap.


%% ----------------------------------------------------
%% 操作
%% ----------------------------------------------------

%% 申请加入公会
apply_join_guild(RoleId, RoleInfoMap, GuildId) ->
    % ApplyType 0:无;1:审批中;2:自动加入
    case check_apply_join_guild(RoleId, RoleInfoMap, GuildId) of
        {false, ErrorCode} -> ApplyType = 0;
        {true, add_guild_apply} ->
            ErrorCode = ?SUCCESS, ApplyType = 1,
            lib_guild_data:add_guild_apply_on_db_and_p(RoleId, GuildId),
            send_guild_apply_red_point(GuildId);
        {true, auto_join, Guild, Position} ->
            case auto_join(RoleId, RoleInfoMap, Guild, Position) of
                {false, ErrorCode} -> ApplyType = 0;
                {ok, _GuildMember} -> ErrorCode = ?SUCCESS, ApplyType = 2
            end
    end,
    {ok, BinData} = pt_400:write(40002, [ErrorCode, GuildId, ApplyType]),
    lib_server_send:send_to_uid(RoleId, BinData),
    ok.

%% 检查申请加入公会
check_apply_join_guild(RoleId, RoleInfoMap, GuildId) when is_integer(GuildId) ->
    Guild = lib_guild_data:get_guild_by_id(GuildId),
    check_apply_join_guild(RoleId, RoleInfoMap, Guild);
check_apply_join_guild(RoleId, RoleInfoMap, Guild) when is_record(Guild, guild) ->
    #guild{id = GuildId, add_member_num = AddMemNum} = Guild,
    IsOnGuild = is_on_guild(RoleId),
    IsApply = is_apply(RoleId, GuildId),
    if
        IsOnGuild -> {false, ?ERRCODE(err400_on_guild_not_to_apply)};
        IsApply -> {false, ?ERRCODE(err400_is_apply_this_guild)};
        true ->
            #guild{
                lv = GuildLv, approve_type = ApproveType, auto_approve_lv = AutoApproveLv,
                auto_approve_power = AutoApprovePower, member_num = MemberNum
                } = Guild,
            #{figure:=Figure, combat_power:=CombatPower} = RoleInfoMap,
            #figure{lv = Lv} = Figure,
            MemberCapacity = data_guild_m:get_guild_member_capacity(GuildLv),
            ApplyMemberIdList = lib_guild_data:get_guild_apply_member_id_lsit_by_guild_id(GuildId),
            LenLimit = data_guild:get(guild_apply_len_limit),
            if
                % 是否已经满人
                MemberNum >= (MemberCapacity + AddMemNum)-> {false, ?ERRCODE(err400_member_enough)};
                % 判断申请列表是否足够人
                ApproveType == ?APPROVE_TYPE_MANUAL andalso length(ApplyMemberIdList) >= LenLimit -> {false, ?ERRCODE(err400_guild_apply_len_limit)};
                ApproveType == ?APPROVE_TYPE_AUTO andalso Lv < AutoApproveLv  -> {false, ?ERRCODE(err400_refuse_apply_lv)};
                ApproveType == ?APPROVE_TYPE_AUTO andalso CombatPower < AutoApprovePower -> {false, ?ERRCODE(err400_refuse_apply_power)};
                ApproveType == ?APPROVE_TYPE_MANUAL -> {true, add_guild_apply};
                % 是否符合自动加入
                ApproveType == ?APPROVE_TYPE_AUTO andalso Lv >= AutoApproveLv andalso CombatPower >= AutoApprovePower ->
                    {true, auto_join, Guild, ?POS_NORMAL};
                true -> {false, ?ERRCODE(err400_refuse_apply)}
            end
    end;
check_apply_join_guild(_, _, _) -> {false, ?ERRCODE(err400_this_guild_not_exist_to_apply)}.

%% 自动加入
auto_join(RoleId, RoleInfoMap, GuildId, Position) when is_integer(GuildId) ->
    Guild = lib_guild_data:get_guild_by_id(GuildId),
    auto_join(RoleId, RoleInfoMap, Guild, Position);
auto_join(RoleId, RoleInfoMap, Guild, Position) when is_record(Guild, guild) ->
    #guild{id = GuildId, name = GuildName, member_num = MemberNum, disband_warnning_time = DisbandWarnningTime} = Guild,
    #{figure:=Figure, combat_power:=CombatPower, hcombat_power:=HCombatPower, last_login_time:=LastLoginTime, online_flag:=OnlineFlag, last_logout_time:=LastLogoutTime} = RoleInfoMap,
    CreateTime = utime:unixtime(),
    GuildMember = make_record(guild_member, [RoleId, GuildId, GuildName, Position, CreateTime,
            Figure, OnlineFlag, LastLoginTime, LastLogoutTime, CombatPower, HCombatPower]),
    F = fun() ->
        lib_guild_data:db_guild_apply_delete_by_role_id(RoleId),
        lib_guild_data:db_guild_member_insert(GuildMember),
        %% 如果公会存在解散警告且公会人数达到解除警告要求要清除警告时间
        case DisbandWarnningTime > 0 andalso MemberNum + 1 >= ?AUTO_DISBAND_NEED_NUM of
            true ->
                db:execute(io_lib:format(?sql_guild_update_disband_warnning_time, [0, GuildId]));
            false -> skip
        end,
        ok
    end,
    case catch db:transaction(F) of
        ok ->
            lib_guild_data:add_guild_member(GuildMember),
            lib_guild_data:delete_guild_apply_by_role_id(RoleId),
            NewGuild = lib_guild_data:get_guild_by_id(GuildId),
            lib_guild_api:join_guild(NewGuild, GuildMember),
            %% 通知全社团在线成员新成员加入
            lib_guild_mod:notice_member_join(NewGuild),
            update_guild_daily_log(GuildId,1,Figure#figure.name,0,CreateTime),
            {ok, GuildMember};
        _Error ->
            ?ERR("_Error: ~p ~n",[_Error]),
            {false, ?FAIL}
    end;
auto_join(_, _, _, _) -> {false, ?FAIL}.

%% 是否在公会
is_on_guild(RoleId) ->
    case get(?P_MEMBER_GUILD_ID) of
        undefined -> MemberGuildIdMap = maps:new();
        MemberGuildIdMap -> ok
    end,
    maps:is_key(RoleId, MemberGuildIdMap).

%% 是否申请过本公会
is_apply(RoleId, GuildId) ->
    case lib_guild_data:get_guild_apply(RoleId, GuildId) of
        #guild_apply{} -> true;
        _ -> false
    end.

%% 海投简历
apply_join_guild_multi(RoleId, RoleInfoMap) ->
    GuildMap = lib_guild_data:get_guild_map(),
    % 战力排序
    % F = fun(GuildA, GuildB) ->
    %     #guild{combat_power = CombatPowerA} = GuildA,
    %     #guild{combat_power = CombatPowerB} = GuildB,
    %     CombatPowerA > CombatPowerB
    % end,
    % GuildListSort = lists:sort(F, maps:values(GuildMap)),
    GuildListSort = ulists:list_shuffle(maps:values(GuildMap)),
    case filter_apply_join_guild(GuildListSort, RoleId, RoleInfoMap, []) of
        {add_guild_apply, FilterList} ->
            GuildId = 0, ApplyType = 1,
            % Len = data_guild_m:get_config(guild_apply_multi_len),
            % SubFilterList = lists:sublist(FilterList, Len),
            [lib_guild_data:add_guild_apply_on_db_and_p(RoleId, TmpGuildId)||TmpGuildId<-FilterList],
            [send_guild_apply_red_point(TmpGuildId)||TmpGuildId<-FilterList];
        {auto_join, Guild, Position} ->
            GuildId = Guild#guild.id,
            ApplyType = 2,
            auto_join(RoleId, RoleInfoMap, Guild, Position)
    end,
    {ok, BinData} = pt_400:write(40003, [?SUCCESS, GuildId, ApplyType]),
    lib_server_send:send_to_uid(RoleId, BinData),
    ok.

get_merge_apply(RoleID,GuildId) when is_integer(GuildId)->
    GuildMerge = lib_guild_data:get_guild_merge_by_id(GuildId),
    get_merge_apply(RoleID,GuildMerge);
get_merge_apply(RoleID,GuildMerge) when is_record(GuildMerge,guild_merge)->
    #guild_merge{tapply=TApply,fapplys=FApplys}=GuildMerge,
    Datas = lists:foldl(fun(Target,Args)->
        TarGuild = lib_guild_data:get_guild_by_id(Target),
        case is_record(TarGuild,guild) of
            true->
                #guild{
                    name = GName,
                    chief_id=ChiefID,
                    flag = Flag,
                    lv=Lv,
                    week_labor_last=WLaborL,
                    member_num=MemN,
                    add_member_num = AddNum,
                    combat_power=Power
                }=TarGuild,
                GuildMember = lib_guild_data:get_guild_member(Target, ChiefID),
                Figure = case is_record(GuildMember,guild_member) of
                    true->
                        GuildMember#guild_member.figure;
                    _->
                        #figure{}
                end,
                [{Target,GName,Flag,Lv,WLaborL,Power,Figure,MemN,AddNum}|Args];
            _->
                Args
        end
    end,[],FApplys),

    AppGuild = lib_guild_data:get_guild_by_id(TApply),
    case is_record(AppGuild,guild) of
        true->
            #guild{
                name = TGName,
                chief_id=TChiefID,
                flag = TFlag,
                lv=TLv,
                week_labor_last=TWLaborL,
                member_num=TMemN,
                add_member_num = TAddNum,
                combat_power=TPower
            }=AppGuild,
            AppGuildMember = lib_guild_data:get_guild_member(TApply, TChiefID),
            TFigure = case is_record(AppGuildMember,guild_member) of
                true->
                    AppGuildMember#guild_member.figure;
                _->
                    #figure{}
            end,
            TGuildId = TApply;
        _->
            TGuildId=0, TGName="",TFlag=0,TLv=0,TWLaborL=0,TPower=0,TFigure=#figure{},TMemN=0,TAddNum=0
    end,

    {ok,Bin} = pt_400:write(40032,[TGuildId,TGName,TFlag,TLv,TWLaborL,TPower,TFigure,TMemN,TAddNum,Datas]),
    lib_server_send:send_to_uid(RoleID,Bin),
    ok;
get_merge_apply(_RoleID,_GuildMerge)->ok.



%%取消申请
cancle_guild_merge(RoleID,GuildID)->
    MyGuildMerge = lib_guild_data:get_guild_merge_by_id(GuildID),
    #guild_merge{tapply=Target}=MyGuildMerge,
    TarGuildMerge = lib_guild_data:get_guild_merge_by_id(Target),
    MyGuild = lib_guild_data:get_guild_by_id(GuildID),
    TarGuild = lib_guild_data:get_guild_by_id(Target),
    CKList = [
        {check_guild_record,MyGuild,TarGuild},
        {check_cancel_mutual,MyGuildMerge,TarGuildMerge}
    ],
    case util:check_lists(?MODULE,CKList) of
        {ok,{NMyGuildMerge,NTarGuildMerge}}->
            F = fun() ->
                lib_guild_data:db_guild_merge_save(NMyGuildMerge),
                lib_guild_data:db_guild_merge_save(NTarGuildMerge),
                ok
            end,
            case catch db:transaction(F) of
                ok ->
                    lib_guild_data:update_guild_merge(NMyGuildMerge),
                    lib_guild_data:update_guild_merge(NTarGuildMerge),
                    get_merge_apply(TarGuild#guild.chief_id,Target),
                    Res = ?SUCCESS;
                _R->
                    Res = ?FAIL
            end;
        {false,_Err} when is_record(TarGuild,guild) == false -> %%对面无了 允许撤销
            NMyGuildMerge = MyGuildMerge#guild_merge{tapply=0},
            lib_guild_data:db_guild_merge_save(NMyGuildMerge),
            lib_guild_data:update_guild_merge(NMyGuildMerge),
            Res = ?SUCCESS;
        {false,Err}->
            Res = Err
    end,
    {ok,Bin}=pt_400:write(40034,[Res]),
    lib_server_send:send_to_uid(RoleID,Bin),
    ok.

%%拒绝
reply_merge_apply(RoleID,GuildId,0,Target)->
    MyGuild = lib_guild_data:get_guild_by_id(GuildId),
    MyGuildMerge = lib_guild_data:get_guild_merge_by_id(GuildId),
    TarGuild = lib_guild_data:get_guild_by_id(Target),
    #guild_merge{fapplys=MFApplys}=MyGuildMerge,
    IsF = lists:member(Target,MFApplys),
    case is_record(TarGuild,guild) of
        true when IsF->
            TarGuildMerge = lib_guild_data:get_guild_merge_by_id(Target),
            NNotes = update_merge_notes(TarGuildMerge#guild_merge.notes,GuildId),
            F = fun() ->
                NMyGuildMerge0  = MyGuildMerge#guild_merge{fapplys=MFApplys--[Target]},
                NTarGuildMerge0 = TarGuildMerge#guild_merge{tapply=0,notes=NNotes},
                lib_guild_data:db_guild_merge_save(NMyGuildMerge0),
                lib_guild_data:db_guild_merge_save(NTarGuildMerge0),
                {ok,NMyGuildMerge0,NTarGuildMerge0}
            end,
            case catch db:transaction(F) of
                {ok,NMyGuildMerge,NTarGuildMerge} ->
                    lib_guild_data:update_guild_merge(NMyGuildMerge),
                    lib_guild_data:update_guild_merge(NTarGuildMerge),
                    {ok,Bin0} = pt_400:write(40033,[?SUCCESS,GuildId,1,0]),
                    lib_server_send:send_to_uid(TarGuild#guild.chief_id,Bin0),
                    get_merge_apply(TarGuild#guild.chief_id,Target),
                    #guild{
                        name = AName,
                        chief_id = AChiefId,
                        chief_name = AChiefName,
                        member_num = ANum
                    }=MyGuild,
                    #guild{
                        name = BName,
                        week_labor = BLives,
                        member_num = BNum
                    }=TarGuild,
                    lib_log_api:log_guild_merge(GuildId,AName,AChiefId,AChiefName,ANum,?MERGE_REFUSE,Target,BName,BLives,BNum,util:get_open_day());
                _R->
                    ?ERR("_Error: ~p ~n",[_R])
            end;
        _->
            NMyGuildMerge = MyGuildMerge#guild_merge{},
            lib_guild_data:update_guild_merge(NMyGuildMerge),
            lib_guild_data:db_guild_merge_save(NMyGuildMerge)
    end,
    {ok,Bin} = pt_400:write(40033,[?SUCCESS,Target,0,0]),
    lib_server_send:send_to_uid(RoleID,Bin),
    ok;
%%同意
reply_merge_apply(RoleID,GuildId,1,Target)->

    MyGuild = lib_guild_data:get_guild_by_id(GuildId),
    MyGuildMerge = lib_guild_data:get_guild_merge_by_id(GuildId),
    TarGuild = lib_guild_data:get_guild_by_id(Target),
    TarGuildMerge = lib_guild_data:get_guild_merge_by_id(Target),
    CKList = [
        {check_guild_record,MyGuild,TarGuild},
        {check_guild_merge_member_num,TarGuild,MyGuild},
        {check_mutual,MyGuildMerge,TarGuildMerge}
    ],
    MyGuildMemberMap = lib_guild_data:get_guild_member_map(GuildId),
    RoleIdList = maps:keys(MyGuildMemberMap),
    case util:check_lists(?MODULE,CKList) of
        true->
            #guild{name=GName}=TarGuild,
            F = fun() ->
                Sql = io_lib:format(?sql_guild_delete_by_guild_id, [GuildId]),
                db:execute(Sql),
                % 更新社团成员
                Sql2 = io_lib:format(?sql_guild_member_update_by_guild_id, [Target,GName,GuildId]),
                db:execute(Sql2),
                % 清理公会申请
                Sql3 = io_lib:format(?sql_guild_apply_delete, [GuildId]),
                db:execute(Sql3),
                % 清理职位名称
                Sql4 = io_lib:format(?sql_position_name_delete_by_guild_id, [GuildId]),
                db:execute(Sql4),
                % 清理权限
                Sql5 = io_lib:format(?sql_position_permission_by_guild_id, [GuildId]),
                db:execute(Sql5),

                %% 更新社团协助
                Sql7 = io_lib:format(?sql_guild_support_update_by_guild_id, [Target,GuildId]),
                db:execute(Sql7),

                NMyGuildMerge0 = MyGuildMerge#guild_merge{tapply=0,fapplys=[]},
                NTarGuildMerge0 = TarGuildMerge#guild_merge{tapply=0},
                lib_guild_data:db_guild_merge_save(NMyGuildMerge0),
                lib_guild_data:db_guild_merge_save(NTarGuildMerge0),

                {ok,NMyGuildMerge0,NTarGuildMerge0}
            end,
            case catch db:transaction(F) of
                {ok,NMyGuildMerge,NTarGuildMerge} ->
                    lib_guild_data:delete_guild(GuildId),
                    lib_guild_data:delete_guild_member_by_guild_id(GuildId, RoleIdList),
                    lib_guild_data:delete_guild_apply_by_guild_id(GuildId),
                    lib_guild_data:delete_position_name(GuildId),
                    lib_guild_data:delete_position_permission(GuildId),

                    %% 其他公会关联功能的清理 这里只做内存的清理
                    mod_chat_cache:delete_guild_cache([GuildId]),
                    GuildMemberList = maps:values(MyGuildMemberMap),
                    lib_guild_api:merge_guild(TarGuild,GuildMemberList),

                    lib_guild_data:add_guild_member_list(TarGuild,GuildMemberList),

                    lib_guild_data:update_guild_merge(NMyGuildMerge),
                    lib_guild_data:update_guild_merge(NTarGuildMerge),

                    lib_guild_support_mod:merge_guild(Target,GuildId),
                    lib_guild_api:after_merge_guild(MyGuild),

                    %%清理关联到的申请
                    clean_applys(MyGuildMerge#guild_merge.fapplys),

                    {ok,Bin0} = pt_400:write(40033,[?SUCCESS,GuildId,1,1]),
                    lib_server_send:send_to_uid(TarGuild#guild.chief_id,Bin0),

                    #guild{
                        name = AName,
                        chief_id = AChiefId,
                        chief_name = AChiefName,
                        member_num = ANum
                    }=MyGuild,
                    #guild{
                        name = BName,
                        week_labor = BLives,
                        member_num = BNum
                    }=TarGuild,
                    lib_log_api:log_guild_merge(GuildId,AName,AChiefId,AChiefName,ANum,?MERGE_AGREE,Target,BName,BLives,BNum,util:get_open_day()),
                    Res = ?SUCCESS;
             _Error ->
                    ?ERR("_Error: ~p ~n",[_Error]),
                    Res = ?FAIL
            end;
        {false,Err}->
            Res = Err
    end,
    {ok,Bin} = pt_400:write(40033,[Res,Target,0,1]),
    lib_server_send:send_to_uid(RoleID,Bin),
    ok.

%%清理关联到的申请
clean_applys([])->ok;
clean_applys([H|T])->
    GuildMerge = lib_guild_data:get_guild_merge_by_id(H),
    case GuildMerge#guild_merge.tapply>0 of
        true->
            NGuildMerge = GuildMerge#guild_merge{tapply=0},
            lib_guild_data:db_guild_merge_save(NGuildMerge),
            lib_guild_data:update_guild_merge(NGuildMerge),
            Guild = lib_guild_data:get_guild_by_id(H),
            get_merge_apply(Guild#guild.chief_id,H);
        _->
            skip
    end,
    clean_applys(T).

%%解散清理
clean_merge_data(GuildId)->
    GuildMerge = lib_guild_data:get_guild_merge_by_id(GuildId),
    #guild_merge{tapply=TApply,fapplys=FApplys}=GuildMerge,
    case TApply>0 of
        true->
            TGuildMerge = lib_guild_data:get_guild_merge_by_id(TApply),
            #guild_merge{fapplys=TFApplys}=TGuildMerge,
            NTGuildMerge  = TGuildMerge#guild_merge{fapplys=TFApplys--[TApply]},
            lib_guild_data:db_guild_merge_save(NTGuildMerge),
            lib_guild_data:update_guild_merge(NTGuildMerge),
            Guild = lib_guild_data:get_guild_by_id(TApply),
            get_merge_apply(Guild#guild.chief_id,TApply);
        _->
            skip
    end,
    clean_applys(FApplys).

update_merge_notes(Notes,GuildId)->
    Now = utime:unixtime(),
    Notes0 = lists:keystore(GuildId,1,Notes,{GuildId,Now}),
    Notes1  = lists:keysort(2,Notes0),
    Notes2  = lists:reverse(Notes1),
    {Notes3,_}  = ulists:split(10,Notes2),
    Notes3.

apply_guild_merge(RoleID,GuildID,Target)->
    MyGuild = lib_guild_data:get_guild_by_id(GuildID),
    TarGuild = lib_guild_data:get_guild_by_id(Target),
    MyGuildMerge = lib_guild_data:get_guild_merge_by_id(GuildID),
    TarGuildMerge = lib_guild_data:get_guild_merge_by_id(Target),
    Now = utime:unixtime(),
    CKList = [
        {check_guild_record,MyGuild,TarGuild},
        {check_guild_apply_ever,Now,Target,MyGuildMerge},
        {check_guild_member_num,MyGuild,TarGuild},
        {check_guild_level, MyGuild, TarGuild}
    ],
    case util:check_lists(?MODULE,CKList) of
        true->
            F = fun() ->
                NMyGuildMerge0  = MyGuildMerge#guild_merge{tapply=Target},
                TFApplys = TarGuildMerge#guild_merge.fapplys,
                NTFApplys =  case lists:member(GuildID,TFApplys) of
                    true->
                        TFApplys;
                    _->
                        [GuildID|TFApplys]
                end,
                NTarGuildMerge0 = TarGuildMerge#guild_merge{fapplys=NTFApplys},
                lib_guild_data:db_guild_merge_save(NMyGuildMerge0),
                lib_guild_data:db_guild_merge_save(NTarGuildMerge0),
                {ok,NMyGuildMerge0,NTarGuildMerge0}
            end,
            case catch db:transaction(F) of
                {ok,NMyGuildMerge,NTarGuildMerge} ->
                    lib_guild_data:update_guild_merge(NMyGuildMerge),
                    lib_guild_data:update_guild_merge(NTarGuildMerge),
                    get_merge_apply(TarGuild#guild.chief_id,Target),
                    #guild{
                        name = AName,
                        chief_id = AChiefId,
                        chief_name = AChiefName,
                        member_num = ANum
                    }=MyGuild,
                    #guild{
                        name = BName,
                        week_labor = BLives,
                        member_num = BNum
                    }=TarGuild,
                    lib_log_api:log_guild_merge(GuildID,AName,AChiefId,AChiefName,ANum,?MERGE_APPLY,Target,BName,BLives,BNum,util:get_open_day()),
                    Res = ?SUCCESS;
                _R->
                    ?ERR("_Error: ~p ~n",[_R]),
                    Res = ?FAIL
            end;
        {false,Err}->
            Res = Err
    end,
    {ok,Bin}=pt_400:write(40031,[Res]),
    lib_server_send:send_to_uid(RoleID,Bin),
    ok.


%% 筛选能请求加入的公会
filter_apply_join_guild([], _RoleId, _RoleInfoMap, Result) -> {add_guild_apply, Result};
filter_apply_join_guild([Guild|L], RoleId, RoleInfoMap, Result) ->
    case check_apply_join_guild(RoleId, RoleInfoMap, Guild) of
        {false, _ErrorCode} -> filter_apply_join_guild(L, RoleId, RoleInfoMap, Result);
        {true, add_guild_apply} -> filter_apply_join_guild(L, RoleId, RoleInfoMap, [Guild#guild.id|Result]);
        {true, auto_join, Guild, Position} -> {auto_join, Guild, Position}
    end.

%% 申请代理
%% 20200520 废掉代理 直接成为团长
apply_guild_position(RoleId, Position, GuildId) when Position=:=?POS_CHIEF->
    NewErrorCode = case check_apply_guild_agent_position(RoleId, Position, GuildId) of
        {false, ErrorCode} ->
            ErrorCode;
        {true,Guild,ChiefGuildMember,GuildMember} ->
            bulk_appoint_position_to_chief_done(Guild, GuildMember, ChiefGuildMember, ?AUTO_APPOINT);
        _R->
            ?FAIL
    end,
    {ok, BinData} = pt_400:write(40018, [Position, NewErrorCode]),
    lib_server_send:send_to_uid(RoleId, BinData),
    ok;
%% 申请帮派职位
apply_guild_position(RoleId, Position, GuildId) ->
    NewErrorCode = case check_apply_guild_position(RoleId, Position, GuildId) of
        {false, ErrorCode} ->
            ErrorCode;
        {true, add_guild_apply} ->
            lib_guild_data:add_guild_apply_on_db_and_p(RoleId, GuildId, Position),
            send_guild_apply_red_point(GuildId,Position),
            ?SUCCESS
    end,
    {ok, BinData} = pt_400:write(40018, [Position, NewErrorCode]),
    lib_server_send:send_to_uid(RoleId, BinData),
    ok.

%% 检查申请社团代理
check_apply_guild_agent_position(RoleId, Position, GuildId) ->
    IsOnGuild = is_on_guild(RoleId),
    IsApply = is_apply(RoleId, GuildId),
    Guild = lib_guild_data:get_guild_by_id(GuildId),
    ChiefGuildMember = lib_guild_data:get_chief(GuildId),
    GuildMember = lib_guild_data:get_guild_member(GuildId, RoleId),
    AgentTime = data_guild:get(agent_time),
    Unixtime  = utime:unixtime(),
    % UnixDate  = utime:unixdate()+4*3600,
    if
        is_record(Guild, guild) == false ->
            {false, ?ERRCODE(err400_this_guild_not_exist_to_apply)};
        % Guild#guild.agent =:= RoleId ->
        %     {false, ?ERRCODE(err400_apply_same_position)};
        % Guild#guild.agent > 0 ->
        %     {false, ?ERRCODE(err400_no_need_more_agent)};
        not IsOnGuild ->
            {false, ?ERRCODE(err400_no_guild)};
        IsApply andalso Position=<0 ->
            {false, ?ERRCODE(err400_is_apply_this_guild)};
        IsApply ->
            {false, ?ERRCODE(err400_is_apply_position)};
        is_record(ChiefGuildMember, guild_member) == false->
            {false,?ERRCODE(data_error)};
        is_record(GuildMember, guild_member) == false->
            {false,?ERRCODE(data_error)};
        ChiefGuildMember#guild_member.online_flag =:= ?ONLINE_ON ->
            {false,?ERRCODE(err400_cant_apply_now)};
        true ->
            case ChiefGuildMember#guild_member.last_logout_time+AgentTime=<Unixtime of
                true->
                    {true,Guild,ChiefGuildMember,GuildMember};
                _->
                    {false,?ERRCODE(err400_cant_apply_now)}
            end
    end.
%% 检查申请帮派职位
check_apply_guild_position(RoleId, Position, GuildId) ->
    IsOnGuild = is_on_guild(RoleId),
    IsApply = is_apply(RoleId, GuildId),
    Guild = lib_guild_data:get_guild_by_id(GuildId),
    if
        not IsOnGuild ->
            {false, ?ERRCODE(err400_no_guild)};
        IsApply andalso Position=<0 ->
            {false, ?ERRCODE(err400_is_apply_this_guild)};
        IsApply ->
            {false, ?ERRCODE(err400_is_apply_position)};
        is_record(Guild, guild) == false ->
            {false, ?ERRCODE(err400_this_guild_not_exist_to_apply)};
        true ->
            {true, add_guild_apply}
    end.

%% 审批公会请求
%% @param Type 0拒绝;1允许
approve_guild_apply(RoleId, ApplyRoleId, ApplyRoleInfoMap, Type) ->
    case check_approve_guild_apply(RoleId, ApplyRoleId) of
        {false, ErrorCode} -> skip;
        {true, #guild{id = GuildId} = Guild,GuildApply} ->
            case Type == 0 of
                true ->
                    ErrorCode = ?SUCCESS,
                    lib_guild_data:delete_guild_apply_by_key_on_db_and_p(ApplyRoleId, GuildId);
                false ->
                    GuildMember = lib_guild_data:get_guild_member_by_role_id(RoleId),
                    case agree_guild_apply(GuildMember,ApplyRoleId, ApplyRoleInfoMap, Guild,GuildApply) of
                        {ok, ErrorCode} ->
                    % 推送当前公会成员列表给操作者
                            mod_guild:send_guild_member_short_info(RoleId, GuildId, ?PAGE_SIZE,1, 0, 0, 0, 0);
                        {false, ErrorCode} -> skip
            end
            end
    end,
    {ok, BinData} = pt_400:write(40009, [ErrorCode, Type, ApplyRoleId]),
    lib_server_send:send_to_uid(RoleId, BinData),
    ok.

check_approve_guild_apply(RoleId, ApplyRoleId) ->
    Guild = lib_guild_data:get_guild_by_role_id(RoleId),
    GuildMember = lib_guild_data:get_guild_member_by_role_id(RoleId),
    if
        is_record(Guild, guild) == false -> {false, ?ERRCODE(err400_approver_not_on_guild)};
        is_record(GuildMember, guild_member) == false -> {false, ?ERRCODE(err400_approver_not_on_guild)};
        true ->
            #guild_member{guild_id = GuildId, position = Position} = GuildMember,
            PermissionList = get_position_permission_list(GuildId, Position),
            IsApprove = lists:member(?PERMISSION_APPROVE_APPLY, PermissionList),
            GuildApply = lib_guild_data:get_guild_apply(ApplyRoleId, GuildId),
            if
                is_record(GuildApply, guild_apply) == false -> {false, ?ERRCODE(err400_not_guild_apply)};
                IsApprove == false -> {false, ?ERRCODE(err400_not_permission_to_approve)};
                true -> {true, Guild,GuildApply}
            end
    end.

%% 同意加入公会/申请公会职位请求
agree_guild_apply(HandleGuildMember, RoleId, RoleInfoMap, Guild, GuildApply) ->
    ApplyPosition = GuildApply#guild_apply.position,
    IsApplyOperation = lists:member(ApplyPosition, ?BE_APPOINT_POS_LIST),
    CreateTime = utime:unixtime(),
    case check_agree_guild_apply(Guild, HandleGuildMember, RoleId, GuildApply) of
        {false, ErrorCode} -> {false, ErrorCode};
        {true, Position} when ApplyPosition =:= ?POS_LOG_JOIN ->
            #guild{
                id = GuildId, name = GuildName, member_num = MemberNum
                ,disband_warnning_time = DisbandWarnningTime
            } = Guild,
            #{
                figure:=Figure, combat_power:=CombatPower, hcombat_power:=HCombatPower
                ,last_login_time := LastLoginTime, online_flag:=OnlineFlag
                ,last_logout_time := LastLogoutTime
            } = RoleInfoMap,
            GuildMember = make_record(guild_member, [RoleId, GuildId, GuildName
                ,Position, CreateTime, Figure, OnlineFlag, LastLoginTime
                ,LastLogoutTime, CombatPower, HCombatPower]
            ),
            F = fun() ->
                lib_guild_data:db_guild_apply_delete_by_role_id(RoleId),
                lib_guild_data:db_guild_member_insert(GuildMember),
                %% 如果公会存在解散警告且公会人数达到解除警告要求要清除警告时间
                case DisbandWarnningTime > 0 andalso MemberNum + 1 >= ?AUTO_DISBAND_NEED_NUM of
                    true ->
                        db:execute(io_lib:format(?sql_guild_update_disband_warnning_time, [0, GuildId]));
                    false -> skip
                end,
                ok
            end,
            case catch db:transaction(F) of
                ok ->
                    lib_guild_data:add_guild_member(GuildMember),
                    lib_guild_data:delete_guild_apply_by_role_id(RoleId),
                    NewGuild = lib_guild_data:get_guild_by_id(GuildId),
                    lib_guild_api:join_guild(NewGuild, GuildMember),
                    %% 通知全社团在线成员新成员加入
                    lib_guild_mod:notice_member_join(NewGuild),
                    update_guild_daily_log(GuildId,1,Figure#figure.name,0,CreateTime),
                    {ok, ?SUCCESS};
                _Error ->
                    ?ERR("_Error: ~p ~n",[_Error]),
                    {false, ?FAIL}
            end;
        {true, _Position} when IsApplyOperation -> %% 申请职位处理
            HandleRoleId = HandleGuildMember#guild_member.id,
            case appoint_position_to_other(HandleRoleId, RoleId, ApplyPosition) of
                {1, _GuildId} ->
                    lib_guild_data:db_guild_apply_delete_by_role_id(RoleId),
                    lib_guild_data:delete_guild_apply_by_role_id(RoleId),
                    {ok, ?SUCCESS};
                {ErrorCode, _GuildId} ->
                    {false, ErrorCode}
            end
    end.

check_agree_guild_apply(Guild, HandleGuildMember, ApplyRoleId, GuildApply) ->
    #guild{lv = GuildLv, member_num = MemberNum} = Guild,
    #guild_apply{position = ApplyPosition} = GuildApply,
    case data_guild:get_guild_lv(GuildLv) of
        #base_guild_lv{member_capacity = MemberCapacity}->
            skip;
        _->
            MemberCapacity=1
    end,
    case ApplyPosition of
        ?POS_LOG_JOIN ->
            case MemberNum >= MemberCapacity of
                true ->
                    {false, ?ERRCODE(err400_member_enough)};
                false ->
                    case is_on_guild(ApplyRoleId) of
                        false ->
                            {true, ?POS_NORMAL};
                        _ ->
                            {false, ?ERRCODE(err400_other_have_guild_not_to_join)}
                    end
            end;
        _ ->
            #guild_member{position = Position} = HandleGuildMember,
            PositionNo = data_guild_m:get_position_no(Position),
            ApPositionNo = data_guild_m:get_position_no(ApplyPosition),
            case is_on_guild(ApplyRoleId) of
                true when PositionNo > ApPositionNo ->
                    {true, ?POS_NORMAL};
                true->
                    {false, ?ERRCODE(err400_not_permission_to_clean_apply)};
                _ ->
                    {false, ?ERRCODE(err400_no_join_guild)}
            end
    end.

%% 全部批准入会
approve_all_guild_apply_on_this_guild(RoleId) ->
    Guild = lib_guild_data:get_guild_by_role_id(RoleId),
    GuildMember = lib_guild_data:get_guild_member_by_role_id(RoleId),
    if
        is_record(Guild, guild) == false -> ErrorCode = ?ERRCODE(err400_approver_not_on_guild);
        is_record(GuildMember, guild_member) == false -> ErrorCode = ?ERRCODE(err400_approver_not_on_guild);
        true ->
            #guild_member{guild_id = GuildId, position = Position} = GuildMember,
            PermissionList = get_position_permission_list(GuildId, Position),
            IsApprove = lists:member(?PERMISSION_APPROVE_APPLY, PermissionList),
            if
                IsApprove == false -> ErrorCode = ?ERRCODE(err400_no_permission);
                true ->
                    ErrorCode = ?SUCCESS,
                    % Sql = io_lib:format(?sql_guild_apply_delete_by_guild_id, [GuildId]),
                    % db:execute(Sql),
                    % lib_guild_data:delete_guild_apply_by_guild_id(GuildId),
                    ApplyRoleIdList0 = lib_guild_data:get_guild_apply_member_id_lsit_by_guild_id(GuildId),
                    AllGuildApplyMap = lib_guild_data:get_guild_apply_map(),
                    ApplyRoleIdList = filter_applyer_join(GuildId,ApplyRoleIdList0,AllGuildApplyMap,[]),
                    case ApplyRoleIdList =/= [] of
                        true ->
                            approve_guild_apply_list(GuildMember,ApplyRoleIdList, RoleId),
                            %% 推送新的申请列表
                            mod_guild:send_guild_apply_list(RoleId, GuildId),
                            % 推送当前公会成员列表给操作者
                            mod_guild:send_guild_member_short_info(RoleId, GuildId, ?PAGE_SIZE, 1, 0, 0, 0, 0);
                            % send_guild_apply_red_point(GuildId);
                        false -> skip
                    end
            end
    end,
    {ok, BinData} = pt_400:write(40016, [ErrorCode, 1]),
    lib_server_send:send_to_uid(RoleId, BinData).

filter_applyer_join(_,[],_,ApplyRoleIdList)->
    ApplyRoleIdList;
filter_applyer_join(GuildID,[H|T],AllGuildApplyMap,ApplyRoleIdList)->
     case maps:get({H, GuildID}, AllGuildApplyMap,[]) of
        #guild_apply{position=?POS_LOG_JOIN}->
            filter_applyer_join(GuildID,T,AllGuildApplyMap,[H|ApplyRoleIdList]);
        _->
            filter_applyer_join(GuildID,T,AllGuildApplyMap,ApplyRoleIdList)
    end.

approve_guild_apply_list(_HandleGuildMember,[], _RoleId) -> skip;
approve_guild_apply_list(HandleGuildMember,[ApplyRoleId|L], RoleId) ->
    case check_approve_guild_apply(RoleId, ApplyRoleId) of
        {false, _ErrorCode} -> skip;
        {delete} -> skip;
        {true, Guild,GuildApply} ->
            case lib_role:get_role_show(ApplyRoleId) of
                [] -> skip;
                RoleShow ->
                    ApplyRoleInfoMap = lib_guild:make_role_map(RoleShow),
                    _ErrorCode = agree_guild_apply(HandleGuildMember, ApplyRoleId, ApplyRoleInfoMap, Guild, GuildApply)
                    % case ErrorCode == ?SUCCESS of
                    %     true ->
                    %         {ok, BinData} = pt_400:write(40011, [ErrorCode, ApplyRoleId]),
                    %         lib_server_send:send_to_uid(RoleId, BinData);
                    %     false -> skip
                    % end
            end
    end,
    approve_guild_apply_list(HandleGuildMember,L, RoleId).

%% 发送个人权限列表
send_role_permission_list(RoleId) ->
    Guild = lib_guild_data:get_guild_by_role_id(RoleId),
    GuildMember = lib_guild_data:get_guild_member_by_role_id(RoleId),
    if
        is_record(Guild, guild) == false -> PermissionList = [];
        is_record(GuildMember, guild_member) == false -> PermissionList = [];
        true ->
            #guild{id = GuildId} = Guild,
            #guild_member{position = Position} = GuildMember,
            PermissionList = lib_guild_mod:get_position_permission_list(GuildId, Position)
    end,
    {ok, BinData} = pt_400:write(40021, [PermissionList]),
    lib_server_send:send_to_uid(RoleId, BinData),
    ok.

%% 批量任命职位
bulk_appoint_position(RoleId, TargetPosition, AppointeeIdList) ->
    if
        % 任命领袖
        TargetPosition == ?POS_CHIEF ->
            bulk_appoint_position_to_chief(RoleId, AppointeeIdList);
        % 批量踢出公会
        TargetPosition == ?KICK_OUT_POSTION ->
            bulk_kick_out_guild(RoleId, AppointeeIdList);
        % 任命其他职位
        true ->
            bulk_appoint_position_to_other(RoleId, TargetPosition, AppointeeIdList)
    end.

%%批量任命会长
bulk_appoint_position_to_chief(RoleId, AppointeeIdList) ->
    if
        length(AppointeeIdList) =/= 1 ->
            ChangeList = [],
            ErrorCode = ?ERRCODE(err400_appoint_position_to_leader_only);
        true ->
            [AppointeeId] = AppointeeIdList,
            case check_bulk_appoint_position_to_chief(RoleId, AppointeeId) of
                {false, ErrorCode} -> ok;
                {ok, Guild, ApGuildMember, ChiefMember} ->
                    ErrorCode = bulk_appoint_position_to_chief_done(Guild, ApGuildMember, ChiefMember, ?MANUAL_APPOINT)
            end,
            case ErrorCode == ?SUCCESS of
                true-> ChangeList = [{AppointeeId,?POS_CHIEF},{RoleId,?POS_NORMAL}];
                false-> ChangeList = []
            end
    end,
    case lib_guild_data:get_guild_member_by_role_id(RoleId) of
        [] -> MyPosition = 0;
        #guild_member{position = MyPosition} ->
            ok
    end,
    {ok, BinData} = pt_400:write(40024, [ErrorCode, MyPosition, ChangeList]),
    lib_server_send:send_to_uid(RoleId, BinData),
    ok.

%% 任命职位
appoint_position(RoleId, AppointeeId, TargetPosition) ->
    {ErrorCode, GuildId} = if
        TargetPosition == ?POS_CHIEF ->
            appoint_position_to_chief(RoleId, AppointeeId);
        true ->
            appoint_position_to_other(RoleId, AppointeeId, TargetPosition)
    end,
     {ok, BinData} = pt_400:write(40013, [ErrorCode, AppointeeId, TargetPosition]),
    lib_server_send:send_to_uid(RoleId, BinData),
    % 推送当前公会成员列表给任命者
    case ErrorCode of
        1 ->
            mod_guild:send_guild_member_short_info(RoleId, GuildId, ?PAGE_SIZE, 1, 0, 0,0,0);
        _ ->
            ok
    end.

appoint_position_to_chief(RoleId, AppointeeId) ->
    case check_bulk_appoint_position_to_chief(RoleId, AppointeeId) of
        {false, ErrorCode} ->
            {ErrorCode, 0};
        {ok, Guild = #guild{id = GuildId}, ApGuildMember, ChiefMember} ->
            ErrorCode = bulk_appoint_position_to_chief_done(Guild, ApGuildMember, ChiefMember, ?MANUAL_APPOINT),
            {ErrorCode, GuildId}
    end.

check_bulk_appoint_position_to_chief(RoleId, AppointeeId) ->
    GuildMember = lib_guild_data:get_guild_member_by_role_id(RoleId),
    ApGuildMember = lib_guild_data:get_guild_member_by_role_id(AppointeeId),
    Guild = lib_guild_data:get_guild_by_role_id(RoleId),
    if
        is_record(GuildMember, guild_member) == false -> {false, ?ERRCODE(err400_not_on_guild_to_appoint)};
        is_record(ApGuildMember, guild_member) == false -> {false, ?ERRCODE(err400_not_on_guild_to_appointed)};
        is_record(Guild, guild) == false -> {false, ?ERRCODE(err400_guild_not_exist)};
        RoleId == AppointeeId -> {false, ?ERRCODE(err400_not_allow_appoint_again)};
        GuildMember#guild_member.guild_id =/= ApGuildMember#guild_member.guild_id ->
            {false, ?ERRCODE(err400_not_same_guild_to_appoint)};
        true ->
            #guild_member{position = Position} = GuildMember,
            #guild{chief_id = ChiefId} = Guild,
            if
                % 只有会长能任命
                Position =/= ?POS_CHIEF -> {false, ?ERRCODE(err400_not_allow_appoint)};
                % 不能重复任命会长
                ChiefId == AppointeeId -> {false, ?ERRCODE(err400_not_allow_appoint_again)};
                true -> {ok, Guild, ApGuildMember, GuildMember}
            end
    end.

%% 任命会长
bulk_appoint_position_to_chief_done(Guild, ApGuildMember, ChiefMember, AppointType) ->
    #guild{id = GuildId, chief_id = ChiefId} = Guild,
    % 新会长职位
    #guild_member{id = ApRoleId, figure = ApFigure} = ApGuildMember,
    #figure{name = ApName} = ApFigure,
    NewApPosition = ?POS_CHIEF,
    % 旧会长职位
    NewChiefPosition = ?POS_NORMAL,
    F = fun() ->
        Sql = io_lib:format(?sql_guild_update_chief, [ApRoleId, util:make_sure_binary(ApName),0,0,GuildId]),
        db:execute(Sql),
        lib_guild_data:db_guild_member_update_position(ApRoleId, NewApPosition),
        lib_guild_data:db_guild_member_update_position(ChiefId, NewChiefPosition),
        ok
    end,
    case catch db:transaction(F) of
        ok ->
            ErrorCode = ?SUCCESS,
            NewApGuildMember = ApGuildMember#guild_member{position = NewApPosition},
            lib_guild_data:update_guild_member(NewApGuildMember),
            NewChiefMember = ChiefMember#guild_member{position = NewChiefPosition},
            lib_guild_data:update_guild_member(NewChiefMember),
            NewGuild = Guild#guild{chief_id = ApRoleId, chief_name = ApName,agent=0,agent_time=0},
            lib_guild_data:update_guild(NewGuild),
            % 接口
            lib_guild_api:change_guild_member(?GEVENT_APPOINT_POSITION_TO_CHIEF, [NewGuild, ChiefMember, ApGuildMember, NewApGuildMember, AppointType]),
            lib_guild_api:change_guild_member(?GEVENT_BECOME_NORAML_AF_APPOINT_OTHER_TO_CHIEF, [NewGuild, ChiefMember, NewChiefMember]),
            % 推送当前公会成员列表给任命者
            mod_guild:send_guild_member_short_info(ChiefId, GuildId, ?PAGE_SIZE, 1, 0, 0, 0, 0);
        _Error ->
            ?ERR("_Error: ~p ~n",[_Error]),
            ErrorCode = ?FAIL
    end,
    ErrorCode.

appoint_position_to_other(RoleId, AppointeeId, TargetPosition) ->
    case check_appoint_position_to_other(RoleId, AppointeeId, TargetPosition) of
        {false, ErrorCode} ->
             {ErrorCode, 0};
        {ok, GuildMember = #guild_member{guild_id = GuildId}, ApGuildMember} ->
            do_appoint_position_to_other(GuildMember, ApGuildMember, TargetPosition),
            {?SUCCESS, GuildId}
    end.

check_appoint_position_to_other(RoleId, AppointeeId, TargetPosition) ->
    GuildMember = lib_guild_data:get_guild_member_by_role_id(RoleId),
    ApGuildMember = lib_guild_data:get_guild_member_by_role_id(AppointeeId),
    Guild = lib_guild_data:get_guild_by_role_id(RoleId),
    RightPositionList = ?BE_APPOINT_POS_LIST,
    IsRightPosition = lists:member(TargetPosition, RightPositionList),
    if
        is_record(GuildMember, guild_member) == false -> {false, ?ERRCODE(err400_not_on_guild_to_appoint)};
        is_record(ApGuildMember, guild_member) == false -> {false, ?ERRCODE(err400_not_on_guild_to_appointed)};
        is_record(Guild, guild) == false -> {false, ?ERRCODE(err400_guild_not_exist)};
        GuildMember#guild_member.guild_id =/= ApGuildMember#guild_member.guild_id ->
            {false, ?ERRCODE(err400_not_same_guild_to_appoint)};
        IsRightPosition == false -> {false, ?ERRCODE(err400_not_allow_appoint)};
        ApGuildMember#guild_member.position == TargetPosition -> {false, ?ERRCODE(err400_not_allow_appoint_again)};
        true ->
            #guild{id = GuildId, lv = GuildLv} = Guild,
            PositionNumList = get_position_num_list(GuildId),
            case lists:keyfind(TargetPosition, 1, PositionNumList) of
                false -> TargetPositionNum = 0;
                {TargetPosition, TargetPositionNum} -> ok
            end,
            MaxNum = data_guild_m:get_position_max_num(GuildLv, TargetPosition),
            #guild_member{position = Position} = GuildMember,
            PositionNo = data_guild_m:get_position_no(Position),
            PermissionList = lib_guild_mod:get_position_permission_list(GuildId, Position),
            IsEnableAppoint = lists:member(?PERMISSION_APPOINT_POS, PermissionList),
            % IsEnableAppoint = data_guild_m:is_enable_appoint_position(Position),
            #guild_member{position = ApPosition} = ApGuildMember,
            ApPositionNo = data_guild_m:get_position_no(ApPosition),
            if
                % 只有部分职位可以允许任命职位
                IsEnableAppoint == false -> {false, ?ERRCODE(err400_not_allow_appoint)};
                TargetPosition =/= ?POS_NORMAL andalso TargetPositionNum >= MaxNum ->
                    {false, ?ERRCODE(err400_this_position_full)};
                % 只能操作低于自己职位的
                PositionNo =< ApPositionNo andalso Position =/= ?POS_CHIEF ->
                    {false, ?ERRCODE(err400_not_allow_appoint)};
                true -> {ok, GuildMember, ApGuildMember}
            end
    end.

%% 普通职位转换
do_appoint_position_to_other(OperatorGuildMember, ApGuildMember, TargetPosition) ->
    #guild_member{id = ApRoleId,figure=Figure,guild_id = GuildId} = ApGuildMember,
    lib_guild_data:db_guild_member_update_position(ApRoleId, TargetPosition),
    NewApGuildMember = ApGuildMember#guild_member{position = TargetPosition},
    lib_guild_data:update_guild_member(NewApGuildMember),
    Guild = lib_guild_data:get_guild_by_id(GuildId),
    lib_guild_api:change_guild_member(?GEVENT_APPOINT_POSITION_TO_OTHER,
        [Guild, OperatorGuildMember, ApGuildMember, NewApGuildMember]),
    update_guild_daily_log(GuildId,3,Figure#figure.name,TargetPosition,utime:unixtime()),
    % 推送当前公会成员列表给任命者
    mod_guild:send_guild_member_short_info(OperatorGuildMember#guild_member.id, GuildId, ?PAGE_SIZE, 1, 0, 0, 0, 0),
    ok.

%%批量提出公会
bulk_kick_out_guild(RoleId, AppointeeIdList) ->
    case check_bulk_kick_out_guild(RoleId, AppointeeIdList) of
        {false, ErrorCode} -> ChangeList=[];
        {ok, Guild, ApGuildMemberList} ->
            ErrorCode = ?SUCCESS,
            ChangeList = bulk_kick_out_guild_done(Guild, ApGuildMemberList),
            mod_guild:send_guild_member_short_info(RoleId, Guild#guild.id, ?PAGE_SIZE, 1, 0, 0, 0, 0)
    end,
    case lib_guild_data:get_guild_member_by_role_id(RoleId) of
        [] -> MyPosition = 0;
        #guild_member{position = MyPosition} ->
            ok
    end,
    {ok, BinData} = pt_400:write(40024, [ErrorCode, MyPosition, ChangeList]),
    lib_server_send:send_to_uid(RoleId, BinData),
    ok.

check_bulk_kick_out_guild(RoleId, AppointeeIdList) ->
    GuildMember = lib_guild_data:get_guild_member_by_role_id(RoleId),
    Guild = lib_guild_data:get_guild_by_role_id(RoleId),
    if
        is_record(GuildMember, guild_member) == false -> {false, ?ERRCODE(err400_not_on_guild_to_appoint)};
        is_record(Guild, guild) == false -> {false, ?ERRCODE(err400_guild_not_exist)};
        true ->
            #guild{id = GuildId} = Guild,
            % 判断职位大小
            #guild_member{position = Position} = GuildMember,
            % 只有部分职位可以允许任命职位
            PermissionList = lib_guild_mod:get_position_permission_list(GuildId, Position),
            IsEnableAppoint = lists:member(?PERMISSION_FIRE_MEMBER, PermissionList),
            % 抽取能操作的玩家id
            GuildMemberMap = lib_guild_data:match_guild_member({position_low, GuildId, Position}),
            F = fun(Id, TmpList)->
                case maps:get(Id, GuildMemberMap, false) of
                    false-> TmpList;
                    TmpGuildMember -> [TmpGuildMember |TmpList]
                end
            end,
            ApGuildMemberList = lists:foldl(F, [], AppointeeIdList),
            if
                IsEnableAppoint == false -> {false, ?ERRCODE(err400_not_permission_to_kick)};
                AppointeeIdList == [] -> {false, ?ERRCODE(err400_please_select)};
                ApGuildMemberList == [] -> {false, ?ERRCODE(err400_this_position_can_not_kick_member)};
                true ->
                    {ok, Guild, ApGuildMemberList}
            end
    end.

bulk_kick_out_guild_done(Guild, ApGuildMemberList) ->
    F = fun(TmpGuildMember, TmpList) ->
        lib_guild_api:quit_guild(?GEVENT_KICK_OUT, Guild, TmpGuildMember),
        [{TmpGuildMember#guild_member.id, ?KICK_OUT_POSTION }|TmpList]
    end,
    ChangeList = lists:foldl(F, [], ApGuildMemberList),
    lib_guild_data:bulk_delete_guild_member_on_db_and_p(ApGuildMemberList),
    ChangeList.

%% 批量任命其他职位
bulk_appoint_position_to_other(RoleId, TargetPosition, AppointeeIdList) ->
    case check_bulk_appoint_position_to_other(RoleId, TargetPosition, AppointeeIdList) of
        {false, ErrorCode} -> ChangeList=[];
        {ok, _Guild, [], [], []} ->
            ErrorCode = ?ERRCODE(err400_please_select), ChangeList=[];
        {ok, Guild, MustGuildMemberList, ApGuildMemberList, OutGuildMemberList} ->
            {ErrorCode,ChangeList} = bulk_appoint_position_to_other_done(Guild, MustGuildMemberList, ApGuildMemberList, OutGuildMemberList, TargetPosition)
    end,
    case lib_guild_data:get_guild_member_by_role_id(RoleId) of
        [] -> MyPosition = 0;
        #guild_member{position = MyPosition} ->
            ok
    end,
    {ok, BinData} = pt_400:write(40024, [ErrorCode, MyPosition, ChangeList]),
    lib_server_send:send_to_uid(RoleId, BinData),
    ok.

check_bulk_appoint_position_to_other(RoleId, TargetPosition, AppointeeIdList) ->
    GuildMember = lib_guild_data:get_guild_member_by_role_id(RoleId),
    Guild = lib_guild_data:get_guild_by_role_id(RoleId),
    RightPositionList = [?POS_NORMAL, ?POS_DIRECTOR, ?POS_ELITE, ?POS_DUPTY_CHIEF],
    IsRightPosition = lists:member(TargetPosition, RightPositionList),
    if
        is_record(GuildMember, guild_member) == false -> {false, ?ERRCODE(err400_not_on_guild_to_appoint)};
        is_record(Guild, guild) == false -> {false, ?ERRCODE(err400_guild_not_exist)};
        IsRightPosition == false -> {false, ?ERRCODE(err400_not_allow_appoint)};
        true ->
            #guild{id = GuildId, lv = GuildLv} = Guild,
            % 人数
            MaxNum = data_guild_m:get_position_max_num(GuildLv, TargetPosition),
            % 判断职位大小
            #guild_member{position = Position} = GuildMember,
            MaxPositionNo = data_guild_m:get_position_no(Position),
            TargetPositionNo = data_guild_m:get_position_no(TargetPosition),
            % 只有部分职位可以允许任命职位
            PermissionList = lib_guild_mod:get_position_permission_list(GuildId, Position),
            IsEnableAppoint = lists:member(?PERMISSION_APPOINT_POS, PermissionList),
            % 抽取权限较高的玩家,必须在任命列表中
            GuildMemberMap = lib_guild_data:match_guild_member({position, GuildId, TargetPosition}),
            F = fun(_K, TmpGuildMember) ->
                #guild_member{position = TmpPosition} = TmpGuildMember,
                TmpPositionNo = data_guild_m:get_position_no(TmpPosition),
                % 只能操作低于自己职位的(除了会长和领袖)
                MaxPositionNo =< TmpPositionNo andalso Position =/= ?POS_CHIEF
            end,
            MustGuildMemberMap = maps:filter(F, GuildMemberMap),
            MemberIdList = maps:keys(MustGuildMemberMap),
            % 必须全部包含不能操作的玩家
            LeftList = MemberIdList -- AppointeeIdList,
            % 是否能操作剩余的玩家
            ApGuildMemberList = get_success_by_appoint_position_to_other(AppointeeIdList--MemberIdList, GuildMember, []),
            if
                length(AppointeeIdList) > MaxNum -> {false, ?ERRCODE(err400_this_position_full)};
                % 只能操作低于自己职位的(除了会长和领袖)
                MaxPositionNo =< TargetPositionNo andalso Position =/= ?POS_CHIEF  -> {false, ?ERRCODE(err400_not_allow_appoint)};
                IsEnableAppoint == false -> {false, ?ERRCODE(err400_not_allow_appoint)};
                LeftList =/= [] -> {false, ?ERRCODE(err400_not_allow_appoint)}; %%存在比自己职位高的或同等
                is_list(ApGuildMemberList) == false -> ApGuildMemberList;
                true ->
                    MustGuildMemberList = maps:values(MustGuildMemberMap),
                    OutGuildMemberList = maps:values(GuildMemberMap) -- (ApGuildMemberList++MustGuildMemberList),
                    {ok, Guild, MustGuildMemberList, ApGuildMemberList, OutGuildMemberList}
            end
    end.

get_success_by_appoint_position_to_other([], _GuildMember, Acc) -> Acc;
get_success_by_appoint_position_to_other([AppointeeId|AppointeeIdList], GuildMember, Acc) ->
    ApGuildMember = lib_guild_data:get_guild_member_by_role_id(AppointeeId),
    if
        is_record(ApGuildMember, guild_member) == false -> {false, ?ERRCODE(err400_not_on_guild_to_appointed)};
        GuildMember#guild_member.guild_id =/= ApGuildMember#guild_member.guild_id ->
            {false, ?ERRCODE(err400_not_same_guild_to_appoint)};
        true ->
            #guild_member{position = Position} = GuildMember,
            #guild_member{position = ApPosition} = ApGuildMember,
            MaxPositionNo = data_guild_m:get_position_no(Position),
            ApMaxPositionNo = data_guild_m:get_position_no(ApPosition),
            if
                % 无法任命学徒和会长到其他职位
                ApPosition == ?POS_CHIEF -> {false, ?ERRCODE(err400_not_allow_appoint)};
                % 只能操作低于自己职位的(除了会长和领袖)
                MaxPositionNo =< ApMaxPositionNo andalso (Position =/= ?POS_CHIEF) -> {false, ?ERRCODE(err400_not_allow_appoint)};
                true -> get_success_by_appoint_position_to_other(AppointeeIdList, GuildMember, [ApGuildMember|Acc])
            end
    end.

bulk_appoint_position_to_other_done(Guild, MustGuildMemberList, ApGuildMemberList, OutGuildMemberList, TargetPosition) ->
    #guild{id = GuildId} = Guild,
    TargetGuildMemberList = ApGuildMemberList++MustGuildMemberList,
    F = fun() ->
        Sql = io_lib:format(<<"UPDATE guild_member SET position = ~p WHERE guild_id = ~p AND position = ~p">>, [?POS_NORMAL, GuildId, TargetPosition]),
        db:execute(Sql),
        F2 = fun(#guild_member{id = RoleId}) -> lib_guild_data:db_guild_member_update_position(RoleId, TargetPosition) end,
        lists:foreach(F2, TargetGuildMemberList),
        ok
    end,
    case db:transaction(F) of
        ok ->
            ErrorCode = ?SUCCESS,
            F3 = fun(TmpGuildMember) ->
                NewTmpGuildMember = TmpGuildMember#guild_member{position = TargetPosition},
                lib_guild_data:update_guild_member(NewTmpGuildMember),
                {TmpGuildMember, NewTmpGuildMember}
            end,
            NewApTupleList = lists:map(F3, ApGuildMemberList),
            F4 = fun(TmpGuildMember) ->
                NewTmpGuildMember = TmpGuildMember#guild_member{position = ?POS_NORMAL},
                lib_guild_data:update_guild_member(NewTmpGuildMember),
                {TmpGuildMember, NewTmpGuildMember}
            end,
            NewOutTupleList = lists:map(F4, OutGuildMemberList),
            NewGuild = lib_guild_data:get_guild_by_id(GuildId),
            F5 = fun({TmpOldGuildMember, TmpGuildMember}) ->
                lib_guild_api:change_guild_member(?GEVENT_APPOINT_POSITION_TO_OTHER, [NewGuild, [], TmpOldGuildMember, TmpGuildMember])
            end,
            lists:foreach(F5, NewApTupleList++NewOutTupleList);
        _Error ->
            ?ERR("_Error: ~p ~n",[_Error]),
            ErrorCode = ?FAIL
    end,
    %%获取批量中职位受改变的人
    ApList = [
        {Id,TargetPosition}||#guild_member{id = Id}<-TargetGuildMemberList
    ],
    OutList = [
        {Id,?POS_NORMAL}||#guild_member{id = Id}<-OutGuildMemberList
    ],
    ChangeList = ApList ++ OutList,
    {ErrorCode,ChangeList}.

%% 自动任命为会长
auto_appoint_to_chief(DelaySec) ->
    GuildMap = lib_guild_data:get_guild_map(),
    spawn(fun() ->
        timer:sleep(DelaySec),
        F = fun(_K, Guild, _Acc) ->
            util:multiserver_delay(0.5, mod_guild, auto_appoint_to_chief_by_guild_id, [Guild#guild.id]),
            ok
        end,
        maps:fold(F, [], GuildMap)
    end),
    ok.

%%团长归来 代理人让权
chief_reback(GuildId)->
    Guild = lib_guild_data:get_guild_by_id(GuildId),
    case Guild of
        #guild{agent=Agent,agent_time=AgentTime} when AgentTime>0 ->
            %%存在代理人用权
            GuildMember = lib_guild_data:get_guild_member(GuildId, Agent),
            case is_record(GuildMember, guild_member) of
                true->
                    do_cancel_guild_agent(GuildMember,Guild);
                _->
                    %%找不到代理人
                    ignore
            end;
        _->
            ignore
    end,
    ok.

do_cancel_guild_agent(GuildMember,Guild)->
    #guild{id=GuildID}=Guild,
    #guild_member{id=RoleID,precursor=PrePos} = GuildMember,
    F = fun() ->
        lib_guild_data:db_guild_member_update_position(RoleID, PrePos),
        lib_guild_data:db_guild_update_agent(GuildID,0,0),
        ok
    end,
    case catch db:transaction(F) of
        ok ->
            NewGuildMember = GuildMember#guild_member{position =PrePos,precursor=5},
            lib_guild_data:update_guild_member(NewGuildMember),
            NewGuild = Guild#guild{agent=0,agent_time=0},
            lib_guild_data:update_guild(NewGuild),
            lib_guild_api:change_guild_member(?GEVENT_APPOINT_POSITION_TO_OTHER, [NewGuild, [], GuildMember,NewGuildMember]),
            ErrorCode = ?SUCCESS;
        _Error ->
            ?ERR("_Error: ~p ~n",[_Error]),
            ErrorCode = ?FAIL
    end,
    ErrorCode.


%%20191211 不再自选交接会长对象  交接给代理人
%%20191223 需要资金管理 七次欠费解散
auto_appoint_to_chief_by_guild_id(GuildId) ->
    Guild = lib_guild_data:get_guild_by_id(GuildId),
    ChiefGuildMember = lib_guild_data:get_chief(GuildId),
    %AutoChiefT = data_guild:get(official_agent_time),
    if
        is_record(Guild, guild) == false ->
            skip;
        is_record(ChiefGuildMember, guild_member) == false ->
            do_auto_appoint_to_chief_by_guild_id(Guild);
        true ->
            skip
            % #guild{
            %     agent=Agent,
            %     agent_time=AgentTime
            % }=Guild,
            % %#guild_member{last_logout_time = LastLogoutTime} = ChiefGuildMember,
            % Unixtime = utime:unixtime(),
            % if
            %     AgentTime == 0 orelse Unixtime - AgentTime < AutoChiefT ->
            %         skip;
            %     true ->
            %         % do_auto_appoint_to_chief_by_guild_id(Guild)
            %         case Agent>0 of
            %             true->
            %                 GuildMember = lib_guild_data:get_guild_member(GuildId, Agent),
            %                 case is_record(GuildMember, guild_member) of
            %                     true->
            %                         do_auto_appoint_to_chief_by_agent(Agent,GuildMember,ChiefGuildMember,Guild);
            %                     _->
            %                         skip
            %                 end;
            %             _->
            %                 skip
            %         end
            % end
    end.

%%零点活跃度更新
% do_liveness_handle(#guild{create_time = CreateTime, liveness_list = LivenessList} = Guild) ->
%     CostLiveNess = data_guild_m:get_config(cost_liveness),
%     DiffDays = utime:day_span(CreateTime) + 1,
%     case lists:keyfind(DiffDays, 1, CostLiveNess) of
%         {_, CostVal} ->
%             NewLiveNessList = cost_liveness(LivenessList, CostVal, []),
%             add_liveness(Guild#guild{liveness_list = NewLiveNessList}, 0);
%         _ -> add_liveness(Guild, 0)
%     end;
do_liveness_handle(Guild) -> Guild.

%%周更新劳务值
do_labor_handle(Now,Guild)->
    #guild{
        week_labor = WLabor,
        week_labor_last = OWLabor
    } = Guild,
    case utime:day_of_week() of
        1->
            Guild#guild{
                week_labor = 0,
                week_labor_refresh = Now,
                week_labor_last = max(WLabor-OWLabor,0)
            };
        5->
            %% 周五只刷新结算的活跃值，最新活跃值不清空
            %% 刷新逻辑：最新值一周刷一次，排行值(结算旧值)每周刷两次
            Guild#guild{
                week_labor_refresh = Now+86400*5,
                week_labor_last = WLabor
            };
        _->
           Guild
    end.


do_auto_appoint_to_chief_by_guild_id(Guild) ->
    #guild{id = GuildId, chief_id = ChiefId} = Guild,
    GuildMemberMap = lib_guild_data:get_guild_member_map(GuildId),
    Time = data_guild:get(appoint_leave_time),
    Unixtime = utime:unixtime(),
    F = fun(_K, GuildMember, List) ->
        #guild_member{position = Position, last_logout_time = LastLogoutTime} = GuildMember,
        case Position =/= ?POS_CHIEF andalso Unixtime - LastLogoutTime < Time of
            true -> [GuildMember|List];
            false -> List
        end
    end,
    GuildMemberList = maps:fold(F, [], GuildMemberMap),
    F2 = fun(GuildMemberA, GuildMemberB) ->
        #guild_member{position = PositionA, labors=HisLaborsA} = GuildMemberA,
        #guild_member{position = PositionB, labors=HisLaborsB} = GuildMemberB,
        NoA = data_guild_m:get_position_no(PositionA),
        NoB = data_guild_m:get_position_no(PositionB),
        case NoA == NoB of
            true -> HisLaborsA > HisLaborsB;
            false -> NoA > NoB
        end
    end,
    SortGuildMemberList = lists:sort(F2, GuildMemberList),
    ChiefGuildMember = lib_guild_data:get_guild_member_by_role_id(ChiefId),
    if
        is_record(ChiefGuildMember, guild_member) == false -> skip;
        SortGuildMemberList == [] -> %% 所有会员都超过离线解散时间 公会解散
            skip;
        true ->
            ApGuildMember = hd(SortGuildMemberList),
            bulk_appoint_position_to_chief_done(Guild, ApGuildMember, ChiefGuildMember, ?AUTO_APPOINT)
    end.

%%移交给代理人
do_auto_appoint_to_chief_by_agent(_Agent,GuildMember,ChiefGuildMember,Guild)->
    % #guild{id = GuildId, chief_id = ChiefId} = Guild,
    bulk_appoint_position_to_chief_done(Guild, GuildMember, ChiefGuildMember, ?AUTO_APPOINT).


%% 自动任命为精英
auto_appoint_to_elite(RoleId, AppointeeId, TargetPosition) ->
    case check_appoint_position_to_other(RoleId, AppointeeId, TargetPosition) of
        {false, _ErrorCode} -> ok;
        {ok, GuildMember, ApGuildMember} ->
            do_appoint_position_to_other(GuildMember, ApGuildMember, TargetPosition)
    end.

%% 研究技能
research_skill(RoleId, SkillId) ->
    case lib_guild_skill:check_research_skill(RoleId, SkillId) of
        {false, ErrorCode} ->
            {ok, BinData} = pt_400:write(40000, [ErrorCode]),
            lib_server_send:send_to_uid(RoleId, BinData);
        {ok, Guild, ResearchCfg} ->
            #guild_skill_research_cfg{research_cost = ResearchCost} = ResearchCfg,
            case catch lib_guild_skill:research_cost(ResearchCost, RoleId, Guild) of
                {ok, NewGuild} ->
                    lib_guild_data:update_guild(NewGuild),
                    {ok, _PreResearchLv, NewResearchLv} = lib_guild_skill_data:upgrade_skill_lv(Guild#guild.id, SkillId),
                    %% 日志
                    %lib_log_api:log_guild_skill(NewGuild#guild.id, NewGuild#guild.name, RoleId, 1, SkillId, ResearchCost, PreResearchLv, NewResearchLv),
                    {ok, BinData} = pt_400:write(40041, [1, SkillId, NewResearchLv, NewGuild#guild.funds]),
                    lib_server_send:send_to_uid(RoleId, BinData);
                Err ->
                    {ok, BinData} = pt_400:write(40000, [?FAIL]),
                    lib_server_send:send_to_uid(RoleId, BinData),
                    ?ERR("research_skill err:~p~n", [Err])
            end
    end.

%% 学习公会技能
learn_skill(RoleId, SkillId, ExtraData) ->
    case lib_guild_skill:check_learn_skill(RoleId, SkillId, ExtraData) of
        {false, ErrorCode} -> {false, ErrorCode};
        {ok, GuildMember, ResearchCfg} ->
            #guild_skill_research_cfg{learn_cost = LearnCost} = ResearchCfg,
            case catch lib_guild_skill:learn_cost(LearnCost, GuildMember) of
                {ok, NewGuildMember} ->
                    lib_guild_data:update_guild_member(NewGuildMember),
                    {ok, LearnCost, 0};
                Err ->
                    ?ERR("learn_skill err:~p~n", [Err]),
                    {false, ?FAIL}
            end
    end.

%% 增加公会资金
add_funds(RoleId, GuildId, AddFunds, Type) when is_integer(GuildId), AddFunds > 0 ->
    case lib_guild_data:get_guild_by_id(GuildId) of
        Guild when is_record(Guild, guild) ->
            NewGuild = add_funds(RoleId, Guild, AddFunds, Type),
            lib_guild_data:update_guild(NewGuild);
        _ -> skip
    end;
add_funds(RoleId, Guild, AddFunds, Type) when is_record(Guild, guild), AddFunds > 0 ->
    #guild{id = GuildId, funds = OldFunds} = Guild,
    NewFunds = OldFunds + AddFunds,
    lib_guild_data:db_guild_update_funds(GuildId, NewFunds),
    % lib_chat:send_TV({player, RoleId}, ?MOD_GUILD, 9, [AddGfunds]),
    %% 日志
    lib_log_api:log_produce_gfunds(RoleId, GuildId, Type, AddFunds, NewFunds, utime:unixtime()),
    NewGuild = Guild#guild{funds = NewFunds},
    {ok, BinData} = pt_400:write(40031, [NewFunds]),
    lib_server_send:send_to_guild(GuildId, BinData),
    NewGuild;
add_funds(_, _, _, _) -> skip.

%% 消耗公会资金(暂时无用)
cost_gfunds(RoleId, Guild, CostFunds, Type) when is_record(Guild, guild), CostFunds > 0 ->
    #guild{id = GuildId, funds = OldFunds} = Guild,
    NewFunds = max(0, OldFunds - CostFunds),
    lib_guild_data:db_guild_update_funds(GuildId, NewFunds),
    %% 日志
    lib_log_api:log_consume_gfunds(RoleId, GuildId, Type, CostFunds, NewFunds, utime:unixtime()),
    NewGuild = Guild#guild{funds = NewFunds},
    lib_guild_data:update_guild(NewGuild),
    {ok, BinData} = pt_400:write(40031, [NewFunds]),
    lib_server_send:send_to_guild(GuildId, BinData),
    NewGuild.

% %% 增加公会贡献
% add_donate_api(RoleId, AddDonate) when is_integer(RoleId), AddDonate > 0 ->
%     case lib_guild_data:get_guild_member_by_role_id(RoleId) of
%         GuildMember when is_record(GuildMember, guild_member) ->
%             NewGuildMember = add_donate_api(GuildMember, AddDonate),
%             lib_guild_data:update_guild_member(NewGuildMember),
%             #guild_member{guild_id = GuildId, position = Position, historical_donate = HisDonate} = NewGuildMember,
%             #guild{chief_id = ChiefId} = lib_guild_data:get_guild_by_id(GuildId),
%             auto_to_elite(ChiefId, RoleId, Position, HisDonate);
%         [] -> skip
%     end;
%% 增加公会贡献(这个接口不会保存内存数据需要在外部调用保存接口)
% add_donate_api(GuildMember, AddDonate) when is_record(GuildMember, guild_member), AddDonate > 0 ->
%     #guild_member{
%         id = RoleId, guild_id = _GuildId,
%         donate = Donate, historical_donate = HistoricalDonate
%     } = GuildMember,
%     NewDonate = Donate + AddDonate,
%     NewHistoricalDonate = HistoricalDonate + AddDonate,
%     db:execute(io_lib:format(?sql_guild_member_update_donate, [NewDonate, NewHistoricalDonate, RoleId])),
%     %% 日志
%     lib_log_api:log_produce_gdonate(RoleId, reward_add_donate, AddDonate, NewDonate, NewHistoricalDonate, "reward_add_donate"),
%     NewGuildMember = GuildMember#guild_member{donate = NewDonate, historical_donate = NewHistoricalDonate},
%     % lib_chat:send_TV({player, RoleId}, ?MOD_GUILD, 8, [AddDonate]),
%     NewGuildMember;
add_donate_api(_, _) -> skip.

% cost_donate_api(RoleId, ConsumeType, CostDonate, Other) when is_integer(RoleId), CostDonate > 0 ->
%     case lib_guild_data:get_guild_member_by_role_id(RoleId) of
%         GuildMember when is_record(GuildMember, guild_member) ->
%             HaveDonate = GuildMember#guild_member.donate,
%             if
%                 HaveDonate >= CostDonate ->
%                     NewGuildMember = cost_donate(GuildMember, CostDonate, ConsumeType, ""),
%                     lib_guild_data:update_guild_member(NewGuildMember),
%                     Result = ok;
%                 true ->
%                     Result = false
%             end,
%             case ConsumeType of
%                 %% 公会争霸鼓舞
%                 guild_war_inspire ->
%                     case Result of
%                         ok ->
%                             {Pid, BuildType} = Other,
%                             mod_guild_war_battle:do_inspire({ok, Pid, BuildType}, RoleId);
%                         _ -> mod_guild_war_battle:do_inspire(Result, RoleId)
%                     end;

%                 _ ->
%                     skip
%             end;
%         [] -> skip
%     end.
cost_donate_api(_RoleId, _ConsumeType, _CostDonate, _Other)->
    skip.

% cost_donate(GuildMember, CostDonate, ConsumeType, Extra) when is_record(GuildMember, guild_member), CostDonate > 0 ->
%     #guild_member{
%         id = RoleId, guild_id = _GuildId,
%         donate = Donate, historical_donate = HistoricalDonate} = GuildMember,
%     NewDonate = max(Donate - CostDonate, 0),
%     db:execute(io_lib:format(?sql_guild_member_update_donate, [NewDonate, HistoricalDonate, RoleId])),
%     %% 日志
%     lib_log_api:log_consume_gdonate(RoleId, ConsumeType, CostDonate, NewDonate, Extra),
%     {ok, BinData} = pt_400:write(40032, [NewDonate]),
%     lib_server_send:send_to_uid(RoleId, BinData),
%     GuildMember#guild_member{donate = NewDonate};
cost_donate(GuildMember, _, _, _) -> GuildMember.

%% 发送公会申请的小红点
%% 发送公会申请的小红点
send_guild_apply_red_point(GuildId) ->
    send_guild_apply_red_point(GuildId, ?POS_NORMAL, []).
send_guild_apply_red_point(GuildId, ApplyPosition) ->
    send_guild_apply_red_point(GuildId, ApplyPosition, []).

send_guild_apply_red_point(GuildId,ApplyPosition,FilterRoleIdList) ->
    Guild = lib_guild_data:get_guild_by_id(GuildId),
    if
        is_record(Guild, guild) ->
            #guild{id = GuildId} = Guild,
            GuildMemberMap = lib_guild_data:get_guild_member_map(GuildId),
            F = fun(_K, GuildMember, List) ->
                #guild_member{id = TmpRoleId, position = Position} = GuildMember,
                PermissionList = get_position_permission_list(GuildId, Position),
                IsAllowModify = lists:member(?PERMISSION_APPROVE_APPLY, PermissionList),
                PositionNo = data_guild_m:get_position_no(Position),
                ApplyPositionNo = data_guild_m:get_position_no(ApplyPosition),
                IsAllow2 = IsAllowModify andalso (PositionNo > ApplyPositionNo),
                case IsAllow2 of
                    true -> [TmpRoleId|List];
                    false -> List
                end
            end,
            List = maps:fold(F, [], GuildMemberMap),
            NewList = List -- FilterRoleIdList,
            [send_red_point(TmpRoleId, ?RED_POINT_GUILD_APPLY,ApplyPosition)||TmpRoleId<-NewList];
        true ->
            skip
    end.

send_guild_upgrade_red_point(_GuildId) ->
    skip.
    % Guild = lib_guild_data:get_guild_by_id(GuildId),
    % if
    %     is_record(Guild, guild) ->
    %         #guild{lv = GuildLv, exp=Exp} = Guild,
    %             LvCfg = data_guild:get_guild_lv(GuildLv),
    %             NextLvCfg = data_guild:get_guild_lv(GuildLv + 1),
    %             if
    %                 is_record(LvCfg, base_guild_lv) == false -> skip;
    %                 is_record(NextLvCfg, base_guild_lv) == false -> skip;
    %                 true ->
    %                     #guild_lv_cfg{growth_val_limit = ExpLimit} = LvCfg,
    %                     case Exp >= ExpLimit of
    %                         true ->
    %                             GuildMemberMap = lib_guild_data:get_guild_member_map(GuildId),
    %                             F = fun(GuildMember) ->
    %                                 #guild_member{id = TmpRoleId, position = Position} = GuildMember,
    %                                 PermissionList = get_position_permission_list(GuildId, Position),
    %                                 IsAllowModify = lists:member(?PERMISSION_UPGRADE_LV, PermissionList),
    %                                 case IsAllowModify of
    %                                     true ->
    %                                         send_red_point(TmpRoleId, ?RED_POINT_GUILD_UPGRADE);
    %                                     false -> skip
    %                                 end
    %                             end,
    %                             lists:foreach(F, maps:values(GuildMemberMap));
    %                         _ -> skip
    %                     end
    %             end;
    %     true -> skip
    % end.

%% 发送小红点
send_red_point(RoleId, ?RED_POINT_GUILD_APPLY = Type,Pos) ->
    {ok, BinData} = pt_110:write(11016, [?MOD_GUILD, Type, Pos]),
    lib_server_send:send_to_uid(RoleId, BinData);
send_red_point(_, _,_) -> ok.

%% 日常清理
day_clear(?TWELVE, _DelaySec) -> ok;
day_clear(?FOUR, _DelaySec) ->
    %% 注意顺序
    NowTime = utime:unixtime(),
    GuildMap = lib_guild_data:get_guild_map(),
    % NowWeek = utime:day_of_week(NowTime),
    % case NowWeek of
    %     1 -> %% 周一重置
    %         db:execute(?sql_guild_reset_announce_modify_times);
    %     _ -> skip
    % end,
    %% 清理过期的公会申请
    clear_expired_apply(NowTime),
    %% 重置公会相关
    clear_guild_info(GuildMap),
    %% 检测是否需要解散帮派
    check_auto_disband_guild(),
    %% 自动任命为会长，延时N秒等自动解散公会的逻辑处理完
    check_auto_appoint_chief(),
    ok;
day_clear(_Clock, _DelaySec) ->
    ok.

check_auto_appoint_chief() ->
    spawn(fun() ->
        util:multiserver_delay(60, mod_guild, auto_appoint_to_chief, [1500])
    end).

%% 清理过期的公会申请
clear_expired_apply(NowTime) ->
    ExpiredCreateTime = NowTime - ?APPLY_EXPIRED_TIME,
    db:execute(io_lib:format(?sql_guild_apply_delete_by_create_time, [ExpiredCreateTime])),
    lib_guild_data:clear_expired_apply(ExpiredCreateTime).


%% 重置公会相关
clear_guild_info(GuildMap) ->
    Sql = io_lib:format(?sql_guild_reset_announce_modify_times, []),
    db:execute(Sql),
    Now = utime:logic_week_start(),
    % NowTime = utime:unixtime(),
    F = fun(GuildId, _OldGuild, _Acc) ->
        Guild = lib_guild_data:get_guild_by_id(GuildId),
        NewGuild0 = Guild#guild{modify_times = 0},
        NewGuild1 = do_liveness_handle(NewGuild0),
        % NewGuild2 = lib_guild_badge:recheck_badge(NowTime,NewGuild1),
        LastGuild = do_labor_handle(Now,NewGuild1),
        lib_guild_data:update_guild(LastGuild)
    end,
    maps:fold(F, ok, GuildMap),
    %% 同步创建时间和刷新时间到排行榜进程
    common_rank_logic:sync_guild_create_time(),
    ok.

check_auto_disband_guild() ->
    GuildMap = lib_guild_data:get_guild_map(),
    %% 已经在公会争霸定级的公会不自动解散 TODO
    AllGuildIdsInGwar = [],
    %% ?ERR("All GuildIds In Division:~p", [AllGuildIdsInGwar]),
    spawn(fun() ->
        F2 = fun(GuildId, _Guild, _GuildAcc) ->
            case lists:member(GuildId, AllGuildIdsInGwar) of
                false ->
                    %% 睡眠发送
                    util:multiserver_delay(0.5, mod_guild, check_auto_disband_guild, [true,GuildId]);
                true ->
                    util:multiserver_delay(0.5, mod_guild, check_auto_disband_guild, [false,GuildId])
            end
        end,
        maps:fold(F2, ok, GuildMap)
    end),
    ok.

%% 检测是否需要自动解散公会(并存储数据库)
check_auto_disband_guild(IsInGWar,GuildId) ->
    case lib_guild_data:get_guild_by_id(GuildId) of
        [] -> skip;
        #guild{} = Guild ->
            NowTime = utime:unixtime(),
            case is_need_disband_guild(IsInGWar,Guild,NowTime) of
                {true, DisbandType} ->
                    disband_guild(DisbandType, Guild);
                auto_disband_warnning -> %% 公会人数少于1人 进入解散倒计时
                    lib_guild_data:update_guild(Guild#guild{disband_warnning_time = NowTime}),
                    Sql = io_lib:format(?sql_guild_update_disband_warnning_time, [NowTime, GuildId]),
                    db:execute(Sql),
                    mod_guild:send_guild_mail_by_guild_id(GuildId, utext:get(4000026), utext:get(4000027), [], []);
                false ->
                    skip
            end
    end,
    ok.

%% 是否需要解散公会
is_need_disband_guild(true,_,_)->
    false;%%社团战中 不予解散 下次
is_need_disband_guild(_,Guild, NowTime) ->
    #guild{
        id = GuildId,
        member_num = MemberNum,
        disband_warnning_time = DisbandWarnningTime
    } = Guild,
    if
        %% 时间有延迟，加多N分钟确保自动解散公会成功
        DisbandWarnningTime > 0 andalso (NowTime + 10 * 60) - DisbandWarnningTime >= ?AUTO_DISBAND_AF_WARNNING ->
            {true, ?DISBAND_REASON_MEMBER_NUM};
        MemberNum =< ?AUTO_DISBAND_NEED_NUM ->
            auto_disband_warnning;
        true ->
            GuildMemberMap = lib_guild_data:get_guild_member_map(GuildId),
            GuildMembers = maps:values(GuildMemberMap),
            is_members_offline_time_out(GuildMembers, NowTime, ?AUTO_DISBAND_OFFLINE_TIME)
    end.


%% 是否公会所有成员都离线都超过了解散时间
is_members_offline_time_out([], _, _) -> {true, ?DISBAND_REASON_ACTIVITY};
is_members_offline_time_out([Member|Members], NowTime, Timeout) ->
    #guild_member{last_logout_time = LastLogoutTime} = Member,
    case NowTime - LastLogoutTime >= Timeout of
        true ->
            is_members_offline_time_out(Members, NowTime, Timeout);
        false -> false
    end.

%% 解散公会
disband_guild(DisbandType, GuildId) when is_integer(GuildId) ->
    case lib_guild_data:get_guild_by_id(GuildId) of
        [] -> skip;
        Guild -> disband_guild(DisbandType, Guild)
    end;
disband_guild(DisbandType, Guild) ->
    #guild{id = GuildId, name = GuildName,flag=GuildFlag,lv=GuildLv} = Guild,
    GuildMemberMap = lib_guild_data:get_guild_member_map(GuildId),
    RoleIdList = maps:keys(GuildMemberMap),
    FirRankDesignationId = lib_common_rank_api:get_guild_title_id(),
    NowTime = utime:unixtime(),
    %% 数据库的清理都放到事务里面去
    F = fun() ->
        % 清理公会
        Sql = io_lib:format(?sql_guild_delete_by_guild_id, [GuildId]),
        db:execute(Sql),
        % 清理公会成员
        Sql2 = io_lib:format(?sql_guild_member_delete_by_guild_id, [GuildId]),
        db:execute(Sql2),
        % 清理公会申请
        Sql3 = io_lib:format(?sql_guild_apply_delete, [GuildId]),
        db:execute(Sql3),
        % 清理职位名称
        Sql4 = io_lib:format(?sql_position_name_delete_by_guild_id, [GuildId]),
        db:execute(Sql4),
        % 清理权限
        Sql5 = io_lib:format(?sql_position_permission_by_guild_id, [GuildId]),
        db:execute(Sql5),

        %% 清理公会红包
        lib_red_envelopes_data:db_clear_by_ownership_id(GuildId),
        %% 移除第一公会称号
        case FirRankDesignationId > 0 of
            true ->
                Sql9 = io_lib:format(?SQL_DSGT_UPDATE_ETIME, [NowTime, NowTime, FirRankDesignationId, util:link_list(RoleIdList)]),
                db:execute(Sql9);
            false -> skip
        end,
        ok
    end,
    case catch db:transaction(F) of
        ok ->
            ChiefGuildMember = lib_guild_data:get_chief(GuildId),
            lib_guild_support_mod:disband_guild(GuildId), %% 在删除公会成员前清理数据
            lib_guild_data:delete_guild(GuildId),
            lib_guild_data:delete_guild_member_by_guild_id(GuildId, RoleIdList),
            lib_guild_data:delete_guild_apply_by_guild_id(GuildId),
            lib_guild_data:delete_position_name(GuildId),
            lib_guild_data:delete_position_permission(GuildId),

            %% 其他公会关联功能的清理 这里只做内存的清理
            mod_chat_cache:delete_guild_cache([GuildId]),


            %% 移除第一公会称号
            spawn(fun() ->
                F1 = fun(TRoleId) ->
                    lib_designation_api:cancel_dsgt_online(TRoleId, FirRankDesignationId)
                end,
                lists:foreach(F1, RoleIdList)
            end),

            GuildMemberList = maps:values(GuildMemberMap),
            spawn(fun()->
                timer:sleep(urand:rand(100, 10000)),
                send_disband_guild_mail(GuildMemberList, Guild, DisbandType)
            end),

            %% 更新社团采集数据
            guild_collect_mgr:disband_guild(GuildId),
            %% 日志
            lib_log_api:log_guild(GuildId, GuildName, GuildFlag, GuildLv, 0,0,"",0,DisbandType, []),
            lib_guild_api:disband_guild(Guild, ChiefGuildMember, GuildMemberList),

            clean_merge_data(GuildId),

            ok;
        _Error ->
            ?ERR("_Error: ~p~n",[_Error]),
            fail
    end.

%% 发送解散公会的邮件
send_disband_guild_mail([], _Guild, _DisbandType) -> skip;
send_disband_guild_mail([#guild_member{id = RoleId}|T], Guild, DisbandType) ->
    case DisbandType of
        ?DISBAND_REASON_FUNDS ->
            lib_mail_api:send_guild_mail([RoleId],?MOD_GUILD, utext:get(4000001), utext:get(4000002), []);
        % ?DISBAND_REASON_MEMBER_NUM ->
        %     lib_mail_api:send_guild_mail([RoleId], utext:get(4000015), utext:get(4000017), []);
        % ?DISBAND_REASON_GM ->
        %     lib_mail_api:send_guild_mail([RoleId], utext:get(4000015), utext:get(4000022), []);
        % ?DISBAND_REASON_CHIEF ->
        %     lib_mail_api:send_guild_mail([RoleId], utext:get(4000023), utext:get(4000028), []);
        _ -> skip
    end,
    timer:sleep(100),
    send_disband_guild_mail(T, Guild, DisbandType).

%% 更新公会成员属性(职位等关联性强的赋值要额外写,不能简单赋值)
update_member_and_guild_attr(RoleId, AttrList) ->
    Guild = lib_guild_data:get_guild_by_role_id(RoleId),
    GuildMember = lib_guild_data:get_guild_member_by_role_id(RoleId),
    if
        is_record(Guild, guild) == false -> skip;
        is_record(GuildMember, guild_member) == false -> skip;
        true ->
            NewGuildMember = do_update_guild_member_attr(AttrList, GuildMember),
            lib_guild_data:update_guild_member(NewGuildMember),
            NewGuild = do_update_guild_by_member_attr(AttrList, NewGuildMember, Guild),
            lib_guild_data:update_guild(NewGuild)
    end,
    ok.

do_update_guild_member_attr([], GuildMember) -> GuildMember;
do_update_guild_member_attr([T|L], GuildMember) ->
    #guild_member{id=Rid,guild_id=GuildId,figure = Figure} = GuildMember,
    case T of
        {name, Name} -> NewGuildMember = GuildMember#guild_member{figure = Figure#figure{name = Name}};
        {lv, Lv} -> NewGuildMember = GuildMember#guild_member{figure = Figure#figure{lv = Lv}};
        {picture, Picture} -> NewGuildMember = GuildMember#guild_member{figure = Figure#figure{picture = Picture}};
        {picture_ver, PictureVer} -> NewGuildMember = GuildMember#guild_member{figure = Figure#figure{picture_ver = PictureVer}};
        {vip, Vip} -> NewGuildMember = GuildMember#guild_member{figure = Figure#figure{vip = Vip}};
        {title, Title} -> NewGuildMember = GuildMember#guild_member{figure = Figure#figure{title = Title}};
        {online_flag, OnlineFlag} ->
            {ok,Bin} = pt_400:write(40067,[Rid,OnlineFlag]),
            lib_server_send:send_to_all(guild,GuildId,Bin),
            NewGuildMember = GuildMember#guild_member{online_flag = OnlineFlag};
        {last_login_time, LastLoginTime} -> NewGuildMember = GuildMember#guild_member{last_login_time = LastLoginTime};
        {last_logout_time, LastLogoutTime} ->
            NewGuildMember = GuildMember#guild_member{last_logout_time = LastLogoutTime};
        {h_combat_power, HCombatPower} -> NewGuildMember = GuildMember#guild_member{h_combat_power = HCombatPower};
        {turn, Turn} -> NewGuildMember = GuildMember#guild_member{figure = Figure#figure{turn = Turn}};
        {figure, NewFigure} -> NewGuildMember = GuildMember#guild_member{figure = NewFigure};
        _ ->
            % ?ERR("ignore attr:~p~n", [T]),
            NewGuildMember = GuildMember
    end,
    do_update_guild_member_attr(L, NewGuildMember).

do_update_guild_by_member_attr([], _GuildMember, Guild) -> Guild;
do_update_guild_by_member_attr([T|L], GuildMember, Guild) ->
    #guild_member{id = RoleId} = GuildMember,
    #guild{id = GuildId, chief_id = ChiefId} = Guild,
    case T of
        {name, Name} ->
            case RoleId == ChiefId of
                true ->
                    db:execute(io_lib:format(?sql_guild_update_chief, [ChiefId,Name,0,0,GuildId])),
                    NewGuild = Guild#guild{chief_name = Name};
                false ->
                    NewGuild = Guild
            end;
        _ ->
            NewGuild = Guild
    end,
    do_update_guild_by_member_attr(L, GuildMember, NewGuild).

%% 更新公会成员属性
update_guild(RoleId, AttrList) ->
    case lib_guild_data:get_guild_member_by_role_id(RoleId) of
        [] -> skip;
        GuildMember ->
            NewGuildMember = do_update_guild_member_attr(AttrList, GuildMember),
            lib_guild_data:update_guild_member(NewGuildMember)
    end,
    ok.

%% ----------------------------------------------------
%% 公用
%% ----------------------------------------------------

%% 获得职位列表
get_position_num_list(GuildId) ->
    Map = lib_guild_data:get_guild_member_map(GuildId),
    F = fun(_K, GuildMember, List) ->
        #guild_member{position = Position} = GuildMember,
        case lists:keyfind(Position, 1, List) of
            false -> [{Position, 1}|List];
            {Position, Num} -> lists:keystore(Position, 1, List, {Position, Num+1})
        end
    end,
    maps:fold(F, [], Map).

%% 获得权限列表
get_position_permission_list(GuildId, Position) ->
    F = fun(PermissionType, IsAllow, List) ->
        case IsAllow == ?IS_ALLOW_NO of
            true -> List;
            false -> [PermissionType|List]
        end
    end,
    PosPermissionMap = lib_guild_data:get_position_permission_map(GuildId),
    PermissionTypeMap = maps:get(Position, PosPermissionMap, #{}),
    maps:fold(F, [], PermissionTypeMap).

%% 是否会长
is_chief(#guild_member{position = Position}) ->
    Position == ?POS_CHIEF.

%% 获取公会活跃人数
get_active_member_num(GuildId) ->
    NowTime = utime:unixtime(),
    GuildMemberMap = lib_guild_data:get_guild_member_map(GuildId),
    ActiveMembers = maps:filter(fun(_, Member) ->
        #guild_member{last_logout_time = LastLogoutTime} = Member,
        NowTime - LastLogoutTime < ?CAL_GUILD_POWER_VAILD_TIME
    end, GuildMemberMap),
    maps:size(ActiveMembers).

%%--------------------------------------------------
%% 对[#guild{}]类型列表排序
%% @param  List    [#guild{}]
%% @param  SortKey 用于排序的字段
%% @param  Len     排序的长度
%% @return         description
%%--------------------------------------------------
sort(List, SortKey, Len) ->
    SortList = lists:keysort(SortKey, List),
    lists:sublist(lists:reverse(SortList), Len).

%%获取公会列表
get_guild_list(GuildMap, 0) -> [Guild||{_Key, Guild}<-maps:to_list(GuildMap)];
get_guild_list(GuildMap, _) ->
    F = fun({_Key,Guild},TmpList)->
        #base_guild_lv{member_capacity=_Limit} = data_guild:get_guild_lv(Guild#guild.lv),
        [Guild|TmpList]
    end,
    lists:foldl(F, [], maps:to_list(GuildMap)).

%%增加公会贡献
% add_donate(GuildMember, _RoleId, CfgId, Num, LogNum) when is_record(GuildMember, guild_member)->
%     #guild_member{id=RoleId, position = Position, guild_id = GuildId, donate = Donate, figure = Figure, historical_donate = HisDonate} = GuildMember,
%     #guild{funds=OldFunds, chief_id=ChiefId} = Guild = lib_guild_data:get_guild_by_id(GuildId),
%     Utime = utime:unixtime(),
%     [{_,RewardList}] = data_guild:get_donate_cfg(CfgId),
%     AddDonate = case lists:keyfind(?TYPE_GDONATE, 1, RewardList) of
%         false -> 0;
%         {_,_,AddD} -> AddD * Num
%     end,
%     AddFunds = case lists:keyfind(?TYPE_GFUNDS, 1, RewardList) of
%         false -> 0;
%         {_,_,AddF} -> AddF * Num
%     end,
%     NewTotalDonate = max(Donate + AddDonate, 0),
%     NewHisDonateTotal = max(HisDonate + AddDonate, 0),
%     DonateLog = {CfgId, Figure#figure.name, LogNum, AddFunds, Utime},
%     NewFunds = OldFunds + AddFunds,
%     F1 = fun() ->
%         Sql = io_lib:format(?sql_guild_member_update_donate, [NewTotalDonate, NewHisDonateTotal, RoleId]),
%         db:execute(Sql),
%         Sql2 = io_lib:format(?sql_guild_update_funds, [NewFunds, GuildId]),
%         db:execute(Sql2),
%         % Sql1 = io_lib:format(?sql_guild_donate_log_replace, [GuildId, RoleId, CfgId, LogNum, AddFunds, Utime]),
%         % db:execute(Sql1),
%         ok
%     end,
%     case db:transaction(F1) of
%         ok->
%             OldLogList = lib_guild_data:get_donate_log_list(GuildId),
%             NewLogList = cut_limit_donate_log([DonateLog|OldLogList], GuildId),
%             lib_guild_data:update_donate_log_list(GuildId, NewLogList),
%             NewGuildMember = GuildMember#guild_member{donate = NewTotalDonate, historical_donate = NewHisDonateTotal},
%             lib_guild_data:update_guild_member(NewGuildMember),
%             auto_to_elite(ChiefId, RoleId, Position, NewHisDonateTotal),
%             NewGuild = Guild#guild{funds=NewFunds},
%             lib_guild_data:update_guild(NewGuild),
%             {ok, BinData1} = pt_400:write(40031, [NewFunds]),
%             lib_server_send:send_to_guild(GuildId, BinData1),
%             {ok, BinData2} = pt_400:write(40032, [NewTotalDonate]),
%             lib_server_send:send_to_uid(RoleId, BinData2),
%             %% 日志
%             lib_log_api:log_produce_gfunds(RoleId, GuildId, add_donate, AddFunds, NewFunds, Utime),
%             lib_log_api:log_produce_gdonate(RoleId, add_donate, AddDonate, NewTotalDonate, NewHisDonateTotal, "add_donate");
%         _Err->
%             ?ERR("add_donate:~p~n",[_Err])
%     end;
add_donate(_GuildMember, RoleId, _CfgId, _Num, _LogNum) -> ?ERR("add_donate error:~p~n",[RoleId]),ok.


% %%自否自动成为精英
% auto_to_elite(ChiefId, RoleId, Position, DonateTotal) when Position == ?POS_NORMAL->
%     case DonateTotal>= data_guild_m:get_config(auto_to_elite) of
%         true-> auto_appoint_to_elite(ChiefId, RoleId, ?POS_ELITE);
%         false-> ok
%     end;
% auto_to_elite(_, _, _, _) -> ok.

%%保留上限
cut_limit_donate_log(LogList, _GuildId) ->
    Limit = data_guild_m:get_config(donate_log_max_len),
    case length(LogList) > Limit+20 of
        true->
            SubList = lists:sublist(LogList, Limit),
            % {_, _, _, _, Time} = lists:last(SubList),
            % Sql = io_lib:format(?sql_guild_donate_log_delete, [Time,GuildId]),
            % db:execute(Sql),
            SubList;
        false-> LogList
    end.

% %%解散公会判断
% do_disband_guild(GuildId, RoleId) ->
%     GuildMember = lib_guild_data:get_guild_member_by_role_id(RoleId),
%     Guild = lib_guild_data:get_guild_by_id(GuildId),
%     case can_disband_guild(GuildMember, Guild) of
%         true ->
%             Err = ?SUCCESS,
%             disband_guild(?DISBAND_REASON_CHIEF, GuildId);
%         {false, Err} -> ok
%     end,
%     {ok, BinData} = pt_400:write(40026, [Err]),
%     lib_server_send:send_to_uid(RoleId, BinData),
%     ok.

% can_disband_guild(#guild_member{} = GuildMember, #guild{} = Guild)->
%     #guild{id = GuildId, create_time = CreateTime, member_num = MemberNum} = Guild,
%     #guild_member{guild_id = GuildId1, position = Position} = GuildMember,
%     PermissionList = lib_guild_mod:get_position_permission_list(GuildId, Position),
%     IsAllow = lists:member(?PERMISSION_DISBAND, PermissionList),
%     DisbandNeedTime = data_guild_m:get_config(disband_time),
%     IsTimeAllow = CreateTime + DisbandNeedTime =< utime:unixtime(),
%     DisBandNeedNum = data_guild_m:get_config(disband_num),
%     IsMemberNumAllow = MemberNum =< DisBandNeedNum,
%     if
%         GuildId1 =/= GuildId -> {false, ?FAIL};
%         IsAllow == false -> {false, ?ERRCODE(err400_no_permission)};
%         IsTimeAllow == false -> {false, ?ERRCODE(err400_time_not_enough)};
%         IsMemberNumAllow == false -> {false, ?ERRCODE(err400_member_num_enough)};
%         true -> true
%     end;
% can_disband_guild(_GuildMember, _Guild) -> {false, ?FAIL}.



%%更新社团日志
update_guild_daily_log(GuildId,Type,Name,Value,Time)->
    DailyLogMap = lib_guild_data:get_daily_log(),
    LogList = maps:get(GuildId,DailyLogMap,[]),
    NLogList1 = [{Type,Name,Value,Time}|LogList],
    {NLogList,_}  = ulists:split(20,NLogList1),
    NDailyLogMap = maps:put(GuildId,NLogList,DailyLogMap),
    lib_guild_data:save_daily_log(NDailyLogMap).

%%验证当前开服天数下 排行是否可合并
%%20210428修改合并条件
check({check_guild_labor_rank,GuildID,Target})->
    Day = util:get_open_day(),
    case catch mod_common_rank:get_labor_rank(GuildID,Target) of
        [GValue,TValue]->
            [Need,IsOpen] = data_guild:get_merge_con(Day),
            case (GValue>=Need andalso TValue=<Need) orelse (GValue=<Need andalso TValue=<Need) of
                true when IsOpen>0->
                    true;
                true when IsOpen=<0->
                    {false,?ERRCODE(err400_guild_merge_need_more_day)};
                _->
                    {false,?ERRCODE(err400_tar_guild_living)}
            end;
        _->
            {false,?ERRCODE(err400_inconformity_merge_condition)}
    end;

%% 验证当前开服天数下 社团等级是否满足要求
%% modify: 2021-06-29
check({check_guild_level, MyGuild, TargetGuild})->
	Day = util:get_open_day(),
	case data_guild:get_merge_con(Day) of
        [_|_] = CanMergeLvList ->
            GuildLaborLvList = data_guild:get_active_lv(Day),
            #guild{week_labor_refresh = MyLastRefreshTime, create_time = MyCreateTime} = MyGuild,
            MHasFirstRefresh = MyLastRefreshTime > MyCreateTime,
            MyDivision = case MHasFirstRefresh of
                           false -> 0;
                           _ -> lib_guild_mod:get_labor_lv(GuildLaborLvList, MyGuild#guild.week_labor_last)
                       end,
            #guild{week_labor_refresh = TarLastRefreshTime, create_time = TarCreateTime} = TargetGuild,
            THasFirstRefresh = TarLastRefreshTime > TarCreateTime,
            TarDivision = case THasFirstRefresh of
                             false -> 0;
                             _ -> lib_guild_mod:get_labor_lv(GuildLaborLvList, TargetGuild#guild.week_labor_last)
                         end,
            %% 被合并的社团等级需要是低等级 && 被合并的等级需要小于等于主动合并的等级
			case lists:member(TarDivision, CanMergeLvList) of
				true ->
                    case MyDivision >= TarDivision of
                        true -> true;
                        _ -> {false,?ERRCODE(err400_inconformity_merge_condition)}
                    end;
				_ ->
                    case TarDivision of
                        0 ->
                            {false,?ERRCODE(err400_tar_guild_wait)};
                        _ ->
                            {false,?ERRCODE(err400_tar_guild_living)}
                    end
			end;
		_ ->
			{false,?ERRCODE(err400_guild_merge_need_more_day)}
	end;

%%判断双方公会是否存在
check({check_guild_record,MyGuild,TarGuild})->
    case is_record(MyGuild,guild) of
        true->
            case is_record(TarGuild,guild) of
                true->
                    true;
                _->
                    {false,?ERRCODE(err400_guild_not_exist)}
            end;
        _->
            {false,?ERRCODE(err400_guild_not_exist)}
    end;
%%判断申请方是否申请过
check({check_guild_apply_ever,Now,Target,MyGuildMerge})->
    ValidT = data_guild:get(guild_merge_apply_valid),
    #guild_merge{tapply=TApply,notes=Notes}=MyGuildMerge,
    case lists:keyfind(Target,1,Notes) of
        {_,CTime}->
            case CTime+ValidT=<Now of
                true->
                    case TApply>0 of
                        false->
                            true;
                        _->
                            {false,?ERRCODE(err400_has_apply_unfinished)}
                    end;
                _->
                    {false,?ERRCODE(err400_cant_apply_again)} %%一定时间内不可重复申请
            end;
        _->
            case TApply>0 of
                false->
                    true;
                _->
                    {false,?ERRCODE(err400_has_apply_unfinished)}
            end
    end;

check({check_guild_member_num,MyGuild,TarGuild})->
    #guild{member_num=MNum,lv=MLv}=MyGuild,
    #guild{member_num=TNum}=TarGuild,
    MCap = case data_guild:get_guild_lv(MLv) of
        #base_guild_lv{member_capacity=V}->
            V;
        _->
            0
    end,
    case MCap-MNum>=TNum of
        true->
            true;
        _->
            {false,?ERRCODE(err400_no_enough_capacity)}
    end;
check({check_guild_merge_member_num,TarGuild,MyGuild})->
    #guild{member_num=MNum}=MyGuild,
    #guild{member_num=TNum,lv=TLv,add_member_num = AddNum}=TarGuild,
    TCap = case data_guild:get_guild_lv(TLv) of
        #base_guild_lv{member_capacity=V}->
            V+AddNum;
        _->
            0+AddNum
    end,
    case TCap-TNum>=MNum of
        true->
            true;
        _->
            {false,?ERRCODE(err400_opposite_no_enough_capacity)}
    end;
%%双方取消认证 要保证自己能取消
%%对不上取消自己
check({check_cancel_mutual,MyGuildMerge,TarGuildMerge})->
    TFApplys = TarGuildMerge#guild_merge.fapplys,
    case lists:member(MyGuildMerge#guild_merge.guild_id,TFApplys) of
        true->
            NTFApplys =  TFApplys--[MyGuildMerge#guild_merge.guild_id],
            NMyGuildMerge = MyGuildMerge#guild_merge{tapply=0},
            NTarGuildMerge = TarGuildMerge#guild_merge{fapplys=NTFApplys},
            {ok,{NMyGuildMerge,NTarGuildMerge}};
        _->
            NMyGuildMerge = MyGuildMerge#guild_merge{tapply=0},
            NTarGuildMerge = TarGuildMerge,
            {ok,{NMyGuildMerge,NTarGuildMerge}}
    end;
%%双方认证 申请方不对
check({check_mutual,MyGuildMerge,TarGuildMerge})->
    case MyGuildMerge#guild_merge.guild_id == TarGuildMerge#guild_merge.tapply of
        true->
            true;
        _->
            {false,?ERRCODE(err400_iden_applyer)}
    end.

%% 增加公会资金
add_gfunds(RoleId, GuildId, AddGfunds, Type) when is_integer(GuildId), AddGfunds > 0 ->
    case lib_guild_data:get_guild_by_id(GuildId) of
        Guild when is_record(Guild, guild) ->
            NewGuild = add_gfunds(RoleId, Guild, AddGfunds, Type),
            lib_guild_data:update_guild(NewGuild);
        _ -> skip
    end;
add_gfunds(RoleId, Guild, AddGfunds, Type) when is_record(Guild, guild), AddGfunds > 0 ->
    #guild{id = GuildId, funds = OldGfunds} = Guild,
    NewGfunds = OldGfunds + AddGfunds,
    lib_guild_data:db_guild_update_funds(GuildId, NewGfunds),
    % lib_chat:send_TV({player, RoleId}, ?MOD_GUILD, 9, [AddGfunds]),
    %% 日志
    lib_log_api:log_produce_gfunds(RoleId, GuildId, Type, AddGfunds, NewGfunds, utime:unixtime()),
    NewGuild = Guild#guild{funds = NewGfunds},
    {ok, BinData} = pt_400:write(40043, [NewGfunds]),
    lib_server_send:send_to_guild(GuildId, BinData),
    NewGuild;
add_gfunds(_, _, _, _) -> skip.

%% --------------------------------------------------------------------
%% 根据活跃度计算活跃等级
get_labor_lv(LaborList, Labor) ->
    F = fun(LaborCfg, TLv) ->
        case LaborCfg of
            {Lv, NeedLabor} when Labor >= NeedLabor ->
                Lv;
            _ -> TLv
        end end,
    lists:foldl(F, 1, LaborList).

%% --------------------------------------------------------------------
%% 获取历史社团数量
get_history_guild_num() ->
    GuildNum = lib_server_kv:get_value(?SERVER_KV_CREATE_GUILD_NUM, 0),
    GuildNum.

%% 更新历史社团数量
update_history_guild_num(Num) ->
    Now = utime:unixtime(),
    ServerKv = #server_kv{key = ?SERVER_KV_CREATE_GUILD_NUM, value = Num, time = Now},
    lib_server_kv:update_server_kv(ServerKv),
    ok.

%% 获取当前社团数量
get_guild_num() ->
    GuildMap = lib_guild_data:get_guild_map(),
    GuildNum = erlang:length(maps:keys(GuildMap)),
    GuildNum.

%% --------------------------------------------------------------------
%% 玩家加入社团，通知社团在线成员
notice_member_join(Guild) ->
    #guild{id = GuildId} = Guild,
    MemberMap = lib_guild_data:get_guild_member_map(GuildId),
    RoleList = maps:keys(MemberMap),
    F = fun(RoleId) ->
        Pid = misc:get_player_process(RoleId),
        case is_pid(Pid) andalso misc:is_process_alive(Pid) of
            true ->
                lib_server_send:send_to_uid(RoleId, pt_400, 40072, [1]);
            _ ->
                ignore
        end end,
    lists:map(F, RoleList),
    ok.

%% --------------------------------------------------------------------
%% @doc  TA数据记录  @end
%% --------------------------------------------------------------------
%% 社团成员状态变更后记录
after_guild_change(Player, [EventType, GuildId, GuildName, GuildLevel, GuildNum,
    GuildPower, GuildRank, OldPosition, NewPosition]) ->
    ta_agent_fire:guild_state(Player, [EventType, GuildId, GuildName, GuildLevel, GuildNum,
        GuildPower, GuildRank, OldPosition, NewPosition]),
    {ok, Player}.

%% 社团活跃变更后记录
after_update_labor(Player, [GuildId, GuildName, GuildLv, GuildNum, TaskType, Live, PersonLive, GuildLive]) ->
    ta_agent_fire:guild_activity(Player, [GuildId, GuildName, GuildLv, GuildNum,
        TaskType, Live, PersonLive, GuildLive]),
    {ok, Player}.