%% ---------------------------------------------------------------------------
%% @doc lib_guild_data.erl

%% @author  hjh
%% @email  hejiahua@163.com
%% @since  2016-12-15
%% @deprecated 帮派进程数据处理:更新,删除,获取;部分外部函数
%% ---------------------------------------------------------------------------
-module(lib_guild_data).
-export([]).

-compile(export_all).

-include("guild.hrl").
-include("sql_guild.hrl").
-include("figure.hrl").
-include("def_module.hrl").

-include("common.hrl").

%% -----------------------------------------------------------------
%% 公会操作
%% -----------------------------------------------------------------

%% 获得公会Maps
get_guild_map() ->
    case get(?P_GUILD) of
        undefined -> #{};
        Val -> Val
    end.

%% 保存公会Maps
save_guild_map(GuildMap) -> put(?P_GUILD, GuildMap).

%% 更新公会
update_guild(#guild{id = GuildId} = Guild) ->
    GuildMap = get_guild_map(),
    NewGuildMap = maps:put(GuildId, Guild, GuildMap),
    save_guild_map(NewGuildMap),
    ok.

%% 删除公会
delete_guild(GuildId) ->
    GuildMap = get_guild_map(),
    NewGuildMap = maps:remove(GuildId, GuildMap),
    save_guild_map(NewGuildMap),
    ok.

%% 根据增加玩家,更新公会
update_guild_by_add_member(GuildMember) ->
    #guild_member{guild_id = GuildId} = GuildMember,
    case get_guild_by_id(GuildId) of
        [] -> skip;
        #guild{member_num = MemberNum, disband_warnning_time = DisbandWarnningTime, chief_id = _ChiefId} = Guild ->
            %% 这里只处理内存的,db操作在前面的事务里面
            NewMemberNum = MemberNum + 1,
            case DisbandWarnningTime > 0 andalso NewMemberNum >= ?AUTO_DISBAND_NEED_NUM of
                true ->
                    %% 发送自动解散警告取消邮件
                    % mod_guild:send_guild_mail_by_guild_id(GuildId, utext:get(4000025), utext:get(4000026), [], []),
                    % lib_mail_api:send_sys_mail([ChiefId], ?MOD_GUILD, utext:get(4000025), utext:get(4000026), []),
                    NewDisbandWarnningTime = 0;
                false ->
                    NewDisbandWarnningTime = DisbandWarnningTime
            end,
            %% 重新计算公会战力
            NowTime = utime:unixtime(),
            SumCombatPower = lib_guild_util:count_guild_combat_power(GuildId, NowTime),
            NewGuild = Guild#guild{combat_power = SumCombatPower, member_num = NewMemberNum, disband_warnning_time = NewDisbandWarnningTime},
            update_guild(NewGuild)
    end.

%%增加N个成员
add_guild_member_list(Guild,GuildMemberList)->
    #guild{id=GuildId,name=GName,member_num = MemberNum} = Guild,
    update_guild_member_list(GuildId,GName,GuildMemberList),
    %% 这里只处理内存的,db操作在前面的事务里面
    NewMemberNum = MemberNum + length(GuildMemberList),
    %% 重新计算公会战力
    NowTime = utime:unixtime(),
    SumCombatPower = lib_guild_util:count_guild_combat_power(GuildId, NowTime),
    NewGuild = Guild#guild{combat_power = SumCombatPower, member_num = NewMemberNum},
    update_guild(NewGuild).

update_guild_member_list(_GuildId,_GName,[])->
    ok;
update_guild_member_list(GuildId,GName,[H|T])->
    NMember = H#guild_member{guild_id=GuildId,guild_name=GName,position=5,precursor=0,labors=0},
    lib_guild_data:update_guild_member(NMember),
    update_guild_member_list(GuildId,GName,T).

%% 根据删除玩家,更新公会
update_guild_by_delete_member(GuildMember) ->
    #guild_member{id=RoleID,guild_id = GuildId} = GuildMember,
    case get_guild_by_id(GuildId) of
        [] -> skip;
        #guild{member_num = MemberNum,agent=Agent} = Guild ->
            NewMemberNum = MemberNum - 1,
            %% 重新计算公会战力
            NowTime = utime:unixtime(),
            SumCombatPower = lib_guild_util:count_guild_combat_power(GuildId, NowTime),
            NewGuild = case Agent == RoleID of
                true->
                    Guild#guild{agent=0,agent_time=0,combat_power = SumCombatPower, member_num = NewMemberNum};
                _->
                    Guild#guild{combat_power = SumCombatPower, member_num = NewMemberNum}
            end,
            update_guild(NewGuild)
    end.

%% 批量删除玩家,更新公会
bulk_update_guild_by_delete_member(GuildMemberList) when GuildMemberList=/=[]->
    #guild_member{guild_id = GuildId} = hd(GuildMemberList),
    Length = length(GuildMemberList),
    case get_guild_by_id(GuildId) of
        [] -> skip;
        #guild{member_num = MemberNum} = Guild ->
            NewMemberNum = MemberNum - Length,
            %% 重新计算公会战力
            NowTime = utime:unixtime(),
            SumCombatPower = lib_guild_util:count_guild_combat_power(GuildId, NowTime),
            NewGuild = Guild#guild{combat_power = SumCombatPower, member_num = NewMemberNum},
            update_guild(NewGuild)
    end;
bulk_update_guild_by_delete_member(_) -> ok.

%% 根据公会id获得公会
get_guild_by_id(GuildId) ->
    GuildMap = get_guild_map(),
    maps:get(GuildId, GuildMap, []).

%% 根据玩家id获得公会
get_guild_by_role_id(RoleId) ->
    case get(?P_MEMBER_GUILD_ID) of
        undefined -> MemberGuildIdMap = maps:new();
        MemberGuildIdMap -> ok
    end,
    case maps:get(RoleId, MemberGuildIdMap, []) of
        [] -> [];
        GuildId -> get_guild_by_id(GuildId)
    end.

%% 所有已经加入公会的玩家id
get_all_role_in_guild() ->
    case get(?P_MEMBER_GUILD_ID) of
        undefined -> [];
        MemberGuildIdMap ->
            maps:keys(MemberGuildIdMap)
    end.

%% 所有已经加入公会的玩家id
get_all_role_in_guild(GuildId) ->
    case get(?P_MEMBER_GUILD_ID) of
        undefined -> [];
        MemberGuildIdMap ->
            MemberGuildIdL = maps:to_list(MemberGuildIdMap),
            F = fun(T, Acc) ->
                case T of
                    {RoleId, GuildId} ->
                        [RoleId|Acc];
                    _ -> Acc
                end
            end,
            lists:foldl(F, [], MemberGuildIdL)
    end.

%% 根据公会id获得公会会长信息
get_guild_chief_info_by_id(GuildId) ->
    case get_chief(GuildId) of
        [] -> {0, ""};
        #guild_member{id = Id, figure = #figure{name = Name}} -> {Id, Name}
    end.

%% 匹配
%% @param Type 类型
%% @return #{} | #{..}
match_guild(Type) ->
    case Type of
        % 公会名字模糊搜索
        {guild_name_fuzzy, Name} ->
            GuildMap = get_guild_map(),
            NameStr = util:make_sure_binary(Name),
            F = fun(_, Guild) ->
                case re:run(Guild#guild.name, NameStr, [{capture, none}]) of
                    match -> true;
                    _ -> false
                end
            end,
            maps:filter(F, GuildMap);
        % 公会id匹配
        {guild_id, MatchId} ->
            GuildMap = get_guild_map(),
            F = fun(GuildId, _Guild) ->
                GuildId == MatchId
            end,
            maps:filter(F, GuildMap);
        % 根据大写名字匹配
        {name_upper, NameUpper} ->
            GuildMap = get_guild_map(),
            maps:filter(fun(_Key, Guild) -> Guild#guild.name_upper =:= NameUpper end, GuildMap);
        {flag_use, Flag} ->
            GuildMap = get_guild_map(),
            maps:filter(fun(_Key, Guild) -> Guild#guild.flag =:= Flag end, GuildMap);
        _ ->
            #{}
    end.

%% -----------------------------------------------------------------
%% 公会成员信息
%% -----------------------------------------------------------------

%% 获得公会成员
get_guild_member(GuildId, RoleId) ->
    GuildMemberMap = get_guild_member_map(GuildId),
    maps:get(RoleId, GuildMemberMap, []).

%% 获得公会成员
get_guild_member_by_role_id(RoleId) ->
    case get(?P_MEMBER_GUILD_ID) of
        undefined -> MemberGuildIdMap = maps:new();
        MemberGuildIdMap -> ok
    end,
    case maps:get(RoleId, MemberGuildIdMap, []) of
        [] -> [];
        GuildId -> get_guild_member(GuildId, RoleId)
    end.

%% 获得公会成员map
get_guild_member_map(GuildId) ->
    case get(?P_GUILD_MEMBER(GuildId)) of
        undefined -> GuildMemberMap = maps:new();
        GuildMemberMap -> ok
    end,
    GuildMemberMap.

set_guild_member_map(GuildId, GuildMemberMap) ->
    put(?P_GUILD_MEMBER(GuildId), GuildMemberMap).

%% 删除公会的所有成员
delete_guild_member_by_guild_id(GuildId, RoleIdList) ->
    erase(?P_GUILD_MEMBER(GuildId)),
    PMemberGuildIdKey = ?P_MEMBER_GUILD_ID,
    case get(PMemberGuildIdKey) of
        undefined -> MemberGuildIdMap = maps:new();
        MemberGuildIdMap -> ok
    end,
    NewMemberGuildIdMap = maps:without(RoleIdList, MemberGuildIdMap),
    put(PMemberGuildIdKey, NewMemberGuildIdMap),
    ok.

%% 更新公会成员
update_guild_member(GuildMember) ->
    #guild_member{id = MemberId, guild_id = GuildId} = GuildMember,
    PMemberGuildIdKey = ?P_MEMBER_GUILD_ID,
    case get(PMemberGuildIdKey) of
        undefined -> MemberGuildIdMap = maps:new();
        MemberGuildIdMap -> ok
    end,
    NewMemberGuildIdMap = maps:put(MemberId, GuildId, MemberGuildIdMap),
    put(PMemberGuildIdKey, NewMemberGuildIdMap),
    GuildMemberMap = get_guild_member_map(GuildId),
    NewGuildMemberMap = maps:put(MemberId, GuildMember, GuildMemberMap),
    put(?P_GUILD_MEMBER(GuildId), NewGuildMemberMap),
    ok.

update_guild_member_labor(GuildMember)->
    #guild_member{
        id = RoleID,
        week_labor = WLabor,
        week_labor_refresh = WTime,
        labors = Labors
    }= GuildMember,
    Sql = io_lib:format("update guild_member set week_labor = ~p, week_labor_refresh = ~p,labors=~p where id = ~p", [WLabor,WTime,Labors,RoleID]),
    db:execute(Sql).

add_guild_member(GuildMember) ->
    update_guild_member(GuildMember),
    % 触发增加成员
    update_guild_by_add_member(GuildMember),
    ok.

delete_guild_member(GuildMember) ->
    #guild_member{id = MemberId, guild_id = GuildId} = GuildMember,
    % 成员和公会id的Maps
    PMemberGuildIdKey = ?P_MEMBER_GUILD_ID,
    case get(PMemberGuildIdKey) of
        undefined -> MemberGuildIdMap = maps:new();
        MemberGuildIdMap -> ok
    end,
    NewMemberGuildIdMap = maps:remove(MemberId, MemberGuildIdMap),
    put(PMemberGuildIdKey, NewMemberGuildIdMap),
    % 成员的处理
    GuildMemberMap = get_guild_member_map(GuildId),
    NewGuildMemberMap = maps:remove(MemberId, GuildMemberMap),
    put(?P_GUILD_MEMBER(GuildId), NewGuildMemberMap),
    ok.

%% 增加公会成员
add_guild_member_on_db_and_p(GuildMember) ->
    % 增加成员
    db_guild_member_insert(GuildMember),
    add_guild_member(GuildMember),
    GuildMember.

%% 删除公会成员
delete_guild_member_on_db_and_p(GuildMember) ->
    #guild_member{id = RoleId} = GuildMember,
    % 删除成员
    Sql = io_lib:format(?sql_guild_member_delete, [RoleId]),
    db:execute(Sql),
    delete_guild_member(GuildMember),
    update_guild_by_delete_member(GuildMember),
    ok.

%% 批量删除公会成员
bulk_delete_guild_member_on_db_and_p(GuildMemberList) ->
    F = fun(GuildMember, TmpList)->
        delete_guild_member(GuildMember),
        [GuildMember#guild_member.id| TmpList]
    end,
    Ids = lists:foldl(F, [], GuildMemberList),
    % 删除成员
    Sql = io_lib:format(<<"delete from guild_member where id in (~s)">>, [util:link_list(Ids)]),
    db:execute(Sql),
    bulk_update_guild_by_delete_member(GuildMemberList),
    ok.

%% 匹配
%% @param Type 类型
%% @return #{} | #{..}
match_guild_member(Type) ->
    case Type of
        {online_flag, GuildId, OnlineFlag} ->
            GuildMemberMap = get_guild_member_map(GuildId),
            maps:filter(fun(_, GuildMember) -> GuildMember#guild_member.online_flag =:= OnlineFlag end, GuildMemberMap);
        {position, GuildId, Position} ->
            GuildMemberMap = get_guild_member_map(GuildId),
            maps:filter(fun(_, GuildMember) -> GuildMember#guild_member.position =:= Position end, GuildMemberMap);
        {specify_positions, GuildId, PositionL} ->
            GuildMemberMap = get_guild_member_map(GuildId),
            maps:filter(fun(_, GuildMember) -> lists:member(GuildMember#guild_member.position, PositionL) end, GuildMemberMap);
        {position_low, GuildId, Position} ->
            GuildMemberMap = get_guild_member_map(GuildId),
            maps:filter(fun(_, GuildMember) -> GuildMember#guild_member.position > Position end, GuildMemberMap);
        _ -> #{}
    end.

%% 获得会长
get_chief(GuildId) ->
    Map = match_guild_member({position, GuildId, ?POS_CHIEF}),
    List = maps:values(Map),
    case List == [] of
        true -> [];
        false -> hd(List)
    end.

%%--------------------------------------------------
%% 搜索公会成员
%% @param  GuildId  公会Id
%% @param  RoleId   玩家id
%% @param  PageSize 分页大小
%% @param  PageNo   分页号
%% @param  SortType 排序类型 参考宏?sgm_
%% @param  SortFlag 0: 降序 1: 升序
%% @param  MemberType 0: 所有成员 1: 在线成员 2: 离线成员
%% @param  SpecailType 0: 正常 1：提取自己到最前面
%%--------------------------------------------------
search_guild_member(GuildId, RoleId, SortType, _SortFlag, MemberType, SpecailType) ->
    NowTime = utime:unixtime(),
    F = fun(GuildMemberA, GuildMemberB) ->
        case SortType of
            ?sgm_default ->
                %% 列表排列优先级：离线时间>职务>等级>贡献值>加入时间
                PosSortA = data_guild_m:get_position_sort(GuildMemberA#guild_member.position),
                PosSortB = data_guild_m:get_position_sort(GuildMemberB#guild_member.position),
                MemberAOfflineTime = case GuildMemberA#guild_member.online_flag == ?ONLINE_OFF of
                    true -> NowTime - GuildMemberA#guild_member.last_logout_time;
                    false -> 0
                end,
                MemberBOfflineTime = case GuildMemberB#guild_member.online_flag == ?ONLINE_OFF of
                    true -> NowTime - GuildMemberB#guild_member.last_logout_time;
                    false -> 0
                end,
                case MemberAOfflineTime == MemberBOfflineTime of
                    true ->
                        case PosSortA == PosSortB of
                            true ->
                                case GuildMemberA#guild_member.figure#figure.lv == GuildMemberB#guild_member.figure#figure.lv of
                                    true ->
                                        GuildMemberA#guild_member.create_time =< GuildMemberB#guild_member.create_time;
                                    false ->
                                        GuildMemberA#guild_member.figure#figure.lv > GuildMemberB#guild_member.figure#figure.lv
                                end;
                            false ->
                                PosSortA > PosSortB
                        end;
                    false -> MemberAOfflineTime < MemberBOfflineTime
                end;
            ?sgm_pos_lv_donate ->
                PosSortA = data_guild_m:get_position_sort(GuildMemberA#guild_member.position),
                PosSortB = data_guild_m:get_position_sort(GuildMemberB#guild_member.position),
                if
                    PosSortA > PosSortB ->
                        true;
                    PosSortA < PosSortB ->
                        false;
                    GuildMemberA#guild_member.figure#figure.lv > GuildMemberB#guild_member.figure#figure.lv ->
                        true;
                    GuildMemberA#guild_member.figure#figure.lv < GuildMemberB#guild_member.figure#figure.lv ->
                        false;
                    true ->
                        true
                end;
            _ ->
                true
        end
    end,
    if
        MemberType == ?member_type_online orelse MemberType == ?member_type_logout ->
            case MemberType == ?member_type_online of
                true -> OnlineFlag = 1;
                false -> OnlineFlag = 0
            end,
            GuildMemberMap = match_guild_member({online_flag, GuildId, OnlineFlag});
        true ->
            GuildMemberMap = get_guild_member_map(GuildId)
    end,
    GuildMemberList = maps:values(GuildMemberMap),
    GuildMemberListAfSort = lists:sort(F, GuildMemberList),
    if
        SpecailType == ?s_special_type_normal -> GuildMemberListAfSort;
        SpecailType == ?s_special_type_del_me -> lists:keydelete(RoleId, #guild_member.id, GuildMemberListAfSort);
        true ->
            case lists:keyfind(RoleId, #guild_member.id, GuildMemberListAfSort) of
                false -> GuildMemberListAfSort;
                GuildMember ->
                    GuildMemberListAfdel = lists:keydelete(RoleId, #guild_member.id, GuildMemberListAfSort),
                    [GuildMember|GuildMemberListAfdel]
            end
    end.

%% -----------------------------------------------------------------
%% 公会申请
%% -----------------------------------------------------------------

%% 获得公会申请
get_guild_apply_map() ->
    case get(?P_GUILD_APPLY) of
        undefined ->
            GuildApplyMap = lib_guild_mod:init_guild_apply(),
            GuildApplyMap;
        GuildApplyMap ->
            GuildApplyMap
    end.

get_guild_apply_map_by_role_id(RoleId) ->
    GuildApplyMap = get_guild_apply_map(),
    F = fun(_K, #guild_apply{role_id = TmpRoleId}) -> TmpRoleId == RoleId end,
    maps:filter(F, GuildApplyMap).

get_guild_apply_map_by_guild_id(GuildId) ->
    GuildApplyMap = get_guild_apply_map(),
    F = fun(_K, #guild_apply{guild_id = TmpGuildId}) -> TmpGuildId == GuildId end,
    maps:filter(F, GuildApplyMap).

get_guild_apply(RoleId, GuildId) ->
    GuildApplyMap = get_guild_apply_map(),
    maps:get({RoleId, GuildId}, GuildApplyMap, []).

%% 更新公会申请
update_guild_apply(GuildApply) ->
    #guild_apply{role_id = RoleId, guild_id = GuildId} = GuildApply,
    % 公会请求
    GuildApplyMap = get_guild_apply_map(),
    NewGuildApplyMap = maps:put({RoleId, GuildId}, GuildApply, GuildApplyMap),
    put(?P_GUILD_APPLY, NewGuildApplyMap),
    % 公会的玩家id请求列表
    ApplyGuildMap = get_guild_apply_guild_map(),
    MemberIdList = maps:get(GuildId, ApplyGuildMap, []),
    case lists:member(RoleId, MemberIdList) of
        false -> NewMeberIdList = [RoleId|MemberIdList];
        true -> NewMeberIdList = MemberIdList
    end,
    NewApplyGuildMap = maps:put(GuildId, NewMeberIdList, ApplyGuildMap),
    put(?P_GUILD_APPLY_GUILD, NewApplyGuildMap),
    NewGuildApplyMap.

%% 增加公会申请列表
add_guild_apply_on_db_and_p(RoleId, GuildId) ->
    add_guild_apply_on_db_and_p(RoleId, GuildId, 0).
add_guild_apply_on_db_and_p(RoleId, GuildId, Position) ->
    GuildApply = lib_guild_mod:make_record(guild_apply, [RoleId, GuildId, utime:unixtime(),Position]),
    db_guild_apply_save(GuildApply),
    update_guild_apply(GuildApply).

%% 删除公会申请
delete_guild_apply_by_key_on_db_and_p(RoleId, GuildId) ->
    % 数据库清理
    Sql = io_lib:format(?sql_guild_apply_delete_by_key, [RoleId, GuildId]),
    db:execute(Sql),
    % 公会请求清理
    AllGuildApplyMap = get_guild_apply_map(),
    NewAllGuildApplyMap = maps:remove({RoleId, GuildId}, AllGuildApplyMap),
    put(?P_GUILD_APPLY, NewAllGuildApplyMap),
    % 公会的玩家id请求列表清理
    ApplyGuildMap = get_guild_apply_guild_map(),
    MemberIdList = get_guild_apply_member_id_lsit_by_guild_id(GuildId),
    NewMeberIdList = lists:delete(RoleId, MemberIdList),
    case NewMeberIdList == [] of
        true -> NewApplyGuildMap = maps:remove(GuildId, ApplyGuildMap);
        false -> NewApplyGuildMap = maps:put(GuildId, NewMeberIdList, ApplyGuildMap)
    end,
    put(?P_GUILD_APPLY_GUILD, NewApplyGuildMap),
    ok.

delete_guild_apply_by_role_id(RoleId) ->
    % 公会请求清理
    AllGuildApplyMap = get_guild_apply_map(),
    GuildApplyMap = get_guild_apply_map_by_role_id(RoleId),
    Keys = maps:keys(GuildApplyMap),
    NewAllGuildApplyMap = maps:without(Keys, AllGuildApplyMap),
    put(?P_GUILD_APPLY, NewAllGuildApplyMap),
    % 公会的玩家id请求列表清理
    ApplyGuildMap = get_guild_apply_guild_map(),
    F2 = fun({TmpRoleId, TmpGuildId}, TmpApplyGuildMap) ->
        MemberIdList = maps:get(TmpGuildId, TmpApplyGuildMap, []),
        NewMeberIdList = lists:delete(TmpRoleId, MemberIdList),
        case NewMeberIdList == [] of
            true -> maps:remove(TmpGuildId, TmpApplyGuildMap);
            false -> maps:put(TmpGuildId, NewMeberIdList, TmpApplyGuildMap)
        end
    end,
    NewApplyGuildMap = lists:foldl(F2, ApplyGuildMap, Keys),
    put(?P_GUILD_APPLY_GUILD, NewApplyGuildMap),
    ok.

delete_guild_apply_by_guild_id(GuildId)->
    % 公会请求清理
    AllGuildApplyMap = get_guild_apply_map(),
    GuildApplyMap = get_guild_apply_map_by_guild_id(GuildId),
    Keys = maps:keys(GuildApplyMap),
    NewAllGuildApplyMap = maps:without(Keys, AllGuildApplyMap),
    put(?P_GUILD_APPLY, NewAllGuildApplyMap),
    % 公会的玩家id请求列表清理
    ApplyGuildMap = get_guild_apply_guild_map(),
    NewApplyGuildMap = maps:remove(GuildId, ApplyGuildMap),
    put(?P_GUILD_APPLY_GUILD, NewApplyGuildMap),
    ok.
delete_guild_apply_by_guild_id(GuildId,Position) ->
    % 公会请求清理
    AllGuildApplyMap = get_guild_apply_map(),
    GuildApplyMap = get_guild_apply_map_by_guild_id(GuildId),
    GuildApplys = maps:to_list(GuildApplyMap),
    [Keys,Roles] = filter_position(Position,GuildApplys,[],[]),
    NewAllGuildApplyMap = maps:without(Keys, AllGuildApplyMap),
    put(?P_GUILD_APPLY, NewAllGuildApplyMap),
    % 公会的玩家id请求列表清理
    ApplyGuildMap = get_guild_apply_guild_map(),
    Applys0 = maps:get(GuildId, ApplyGuildMap, []),
    Applys  = Applys0--Roles,
    NewApplyGuildMap = maps:put(GuildId, Applys, ApplyGuildMap),
    put(?P_GUILD_APPLY_GUILD, NewApplyGuildMap),
    ok.

filter_position(_Position,[],Keys,Roles)->
    [Keys,Roles];
filter_position(Position,[H|T],Keys,Roles)->
    {_,#guild_apply{
        key = Key,
        role_id = Rid,
        position = Apply
    }}=H,
    case Position =:= Apply of
        true->
            filter_position(Position,T,[Key|Keys],[Rid|Roles]);
        _->
            filter_position(Position,T,Keys,Roles)
    end.

clear_expired_apply(ExpiredCreateTime) ->
    AllGuildApplyMap = get_guild_apply_map(),
    F = fun(_K, #guild_apply{create_time = CrteaTimeTmp}) -> CrteaTimeTmp =< ExpiredCreateTime end,
    ExpiredApplyMap = maps:filter(F, AllGuildApplyMap),
    Keys = maps:keys(ExpiredApplyMap),
    NewAllGuildApplyMap = maps:without(Keys, AllGuildApplyMap),
    put(?P_GUILD_APPLY, NewAllGuildApplyMap),
    ApplyGuildMap = get_guild_apply_guild_map(),
    F1 = fun({TmpRoleId, TmpGuildId}, TmpApplyGuildMap) ->
        MemberIdList = maps:get(TmpGuildId, TmpApplyGuildMap, []),
        NewMeberIdList = lists:delete(TmpRoleId, MemberIdList),
        case NewMeberIdList == [] of
            true -> maps:remove(TmpGuildId, TmpApplyGuildMap);
            false -> maps:put(TmpGuildId, NewMeberIdList, TmpApplyGuildMap)
        end
    end,
    NewApplyGuildMap = lists:foldl(F1, ApplyGuildMap, Keys),
    put(?P_GUILD_APPLY_GUILD, NewApplyGuildMap),
    ok.

%% 获得公会的玩家id请求列表
get_guild_apply_guild_map() ->
    case get(?P_GUILD_APPLY_GUILD) of
        undefined -> maps:new();
        ApplyGuildMap -> ApplyGuildMap
    end.

%% 根据公会id,获得申请中的玩家id列表
get_guild_apply_member_id_lsit_by_guild_id(GuildId) ->
    ApplyGuildMap = get_guild_apply_guild_map(),
    maps:get(GuildId, ApplyGuildMap, []).

%% 获得公会的合并申请
get_guild_apply_merge_map() ->
    case get(?P_GUILD_MERGE_GUILD) of
        undefined -> maps:new();
        MergeGuildMap -> MergeGuildMap
    end.

%% 根据公会id,获得申请中的玩家id列表
get_guild_merge_by_id(GuildId) ->
    MergeGuildMap = get_guild_apply_merge_map(),
    GuildMerge = maps:get(GuildId, MergeGuildMap,#guild_merge{guild_id=GuildId}),
    GuildMerge.

%% 更新公会合并
update_guild_merge(GuilMerge) ->
    #guild_merge{guild_id = GuildId} = GuilMerge,
    MergeGuildMap = get_guild_apply_merge_map(),
    NewMergeGuildMap = maps:put(GuildId, GuilMerge, MergeGuildMap),
    put(?P_GUILD_MERGE_GUILD, NewMergeGuildMap),
    NewMergeGuildMap.

db_guild_merge_save(GuildMerge) ->
    #guild_merge{
        guild_id=GuildId,
        tapply=TApply,
        fapplys=FApplys0,
        notes=Notes0
    } = GuildMerge,
    Notes = util:term_to_string(Notes0),
    FApplys = util:term_to_string(FApplys0),
    Sql = io_lib:format(?sql_guild_merge_replace, [GuildId,TApply,FApplys,Notes]),
    db:execute(Sql).

%% -----------------------------------------------------------------
%% 公会职位名字
%% -----------------------------------------------------------------

get_position_name_map(GuildId) ->
    case get(?P_POS_NAME(GuildId)) of
        undefined -> lib_guild_mod:init_position_name_map(GuildId);
        PositionNameMap -> PositionNameMap
    end.

%% 清理
delete_position_name(GuildId) ->
    erase(?P_POS_NAME(GuildId)),
    ok.

update_position_name(GuildId, Position, PositionName) ->
    PositionNameMap = get_position_name_map(GuildId),
    NewPositionNameMap = maps:put(Position, PositionName, PositionNameMap),
    put(?P_POS_NAME(GuildId), NewPositionNameMap),
    NewPositionNameMap.

%% -----------------------------------------------------------------
%% 公会职位权限
%% -----------------------------------------------------------------

get_position_permission_map(GuildId) ->
    case get(?P_POS_PERMISSION(GuildId)) of
        undefined -> lib_guild_mod:init_position_permission_map(GuildId);
        PosPermissionMap -> PosPermissionMap
    end.

%% 清理
delete_position_permission(GuildId) ->
    erase(?P_POS_PERMISSION(GuildId)),
    ok.

update_position_permission(GuildId, Position, PermissionType, IsAllow) ->
    PosPermissionMap = get_position_permission_map(GuildId),
    PermissionTypeMap = maps:get(Position, PosPermissionMap, #{}),
    NewPermissionTypeMap = maps:put(PermissionType, IsAllow, PermissionTypeMap),
    NewPosPermissionMap = maps:put(Position, NewPermissionTypeMap, PosPermissionMap),
    put(?P_POS_PERMISSION(GuildId), NewPosPermissionMap),
    NewPosPermissionMap.

%% -----------------------------------------------------------------
%% 数据库操作
%% -----------------------------------------------------------------

db_guild_insert(Guild) ->
    #guild{
        id = Id
        , name = Name
        , announce = Announce
        , 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 = Badges0
        , fire_num = PartyN
        , assist   = AssistN
        , war_win  = WarWin
        , last_renew = LastReNew
    } = Guild,
    Badges = [{Bid,Stime,Etime}||#guild_badge{id=Bid,stime=Stime,etime=Etime}<-Badges0],
    Sql = io_lib:format(?sql_guild_insert, [Id, Name, util:make_sure_binary(Announce),
        ChiefId, util:make_sure_binary(ChiefName),Agent,AgentTime,Lv,Exp,Division,Funds,Arrears,Flag,CreateTime,ModifyTimes,ApproveType,
        AutoApproveLv, AutoApprovePower, DisbandWarnningTime,WeekLabor,WeekLaborRe,WeekLaborLast,CReName,CReNameTime,util:term_to_string(Badges),PartyN,AssistN,WarWin,LastReNew]),
    db:execute(Sql).

db_guild_member_insert(GuildMember) ->
    #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
    } = GuildMember,
    Sql = io_lib:format(?sql_guild_member_insert, [Id, GuildId, util:make_sure_binary(GuildName), Position,Precursor,WLabor,WTime,Labors, CreateTime]),
    db:execute(Sql).

db_guild_apply_save(GuildApply) ->
    #guild_apply{role_id = RoleId, guild_id = GuildId, create_time = CreateTime,position=Position} = GuildApply,
    Sql = io_lib:format(?sql_guild_apply_replace, [RoleId, GuildId, CreateTime,Position]),
    db:execute(Sql).

db_guild_apply_delete_by_role_id(RoleId) ->
    Sql = io_lib:format(?sql_guild_apply_delete_by_role_id, [RoleId]),
    db:execute(Sql).

db_guild_member_update_position(RoleId, Position) ->
    db_guild_member_update_position(RoleId, Position,5).
db_guild_member_update_position(RoleId, Position,Precursor)->
    Sql = io_lib:format(?sql_guild_member_update_position, [Position,Precursor,RoleId]),
    db:execute(Sql).


db_guild_update_agent(GuildId,Agentor,Time) ->
    Sql = io_lib:format(?sql_guild_update_agent, [Agentor,Time,GuildId]),
    db:execute(Sql).

db_guild_update_funds(GuildId, Funds) ->
    Sql = io_lib:format(?sql_guild_update_funds, [Funds, GuildId]),
    db:execute(Sql).

db_guild_update_badge(GuildID,Badges)->
    NBadges = [{Bid,Stime,Etime}||#guild_badge{id=Bid,stime=Stime,etime=Etime}<-Badges],
    Sql = io_lib:format(?sql_guild_update_badges, [util:term_to_string(NBadges), GuildID]),
    db:execute(Sql).

db_guild_update_party_num(GuildID,Num)->
    Sql = io_lib:format(?sql_guild_update_party_num, [Num, GuildID]),
    db:execute(Sql).

db_guild_update_badge_need(GuildID,PartyN,AssistN,WarWin,Time)->
    Sql = io_lib:format(?sql_guild_update_badge_need, [PartyN,AssistN,WarWin,Time,GuildID]),
    db:execute(Sql).


%% 修改这里要注意是否需要修改mod_guild_call:modify_name_by_gm
db_guild_update_name(GuildId, Flag, GuildName) ->
    SQL1 = io_lib:format("UPDATE `guild` SET `name` = '~ts', `c_rename` = 0, `c_rename_time` = ~p,`flag`= ~p WHERE `id` = ~p", [GuildName, utime:unixtime(),Flag, GuildId]),
    db:execute(SQL1),
    SQL2 = io_lib:format("UPDATE `guild_member` SET `guild_name` = '~ts' WHERE `guild_id` = ~p", [GuildName, GuildId]),
    db:execute(SQL2).

db_guild_update_labor(Guild)->
    #guild{
        id = GuildId,
        lv = Glv,
        exp = GExp,
        week_labor = WLabor,
        week_labor_refresh = WTime,
        week_labor_last = WLaborLast
    }=Guild,
    SQL = io_lib:format("UPDATE `guild` SET `lv`=~p,`exp`=~p,`week_labor` = ~p, `week_labor_refresh` = ~p,`week_labor_last`=~p  WHERE `id` = ~p", [Glv,GExp,WLabor,WTime,WLaborLast,GuildId]),
    db:execute(SQL).

get_daily_log()->
    case get(guild_daily_log) of
        undefined->
            DailyLogMap=#{};
        DailyLogMap->
            skip
    end,
    DailyLogMap.
save_daily_log(DailyLogMap)->
    put(guild_daily_log,DailyLogMap).