%% ---------------------------------------------------------------------------
%% @doc mod_guild_cast.erl

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

-compile(export_all).

-include("guild.hrl").
-include("sql_guild.hrl").
-include("figure.hrl").
-include("role.hrl").
-include("errcode.hrl").
-include("predefine.hrl").
-include("common.hrl").
%% -include("guild_act.hrl").
-include("def_module.hrl").
-include("def_daily.hrl").
-include("def_fun.hrl").
-include("rename.hrl").
-include("designation.hrl").
-include("relationship.hrl").

%% cast
handle_cast({'apply_cast', Moudle, Method, Args}, State) ->
    apply(Moudle, Method, Args),
    {noreply, State};

%%旗帜使用情况
handle_cast({'search_guild_flag_list', RoleID},State)->
    GuildMap = lib_guild_data:get_guild_map(),
    GuildList = lib_guild_mod:get_guild_list(GuildMap, 0),
    Flags = [Flag||#guild{flag=Flag}<-GuildList],
    {ok,Bin} = pt_400:write(40020,[0,Flags]),
    lib_server_send:send_to_uid(RoleID,Bin),
    {noreply, State};

%% 搜索公会列表
handle_cast({'search_guild_list', RoleId, GuildName, Filter, PageSize, PageNo}, State) ->
    % 搜索出条件
    if
        GuildName == "" -> GuildMap = lib_guild_data:get_guild_map();
        true ->
            GuildMap = case catch list_to_integer(GuildName) of
                Integer when is_integer(Integer) ->
                    case lib_guild_data:match_guild({guild_id, Integer}) of
                        Map when Map =/= #{} -> Map;
                        _ -> lib_guild_data:match_guild({guild_name_fuzzy, GuildName})
                    end;
                _ -> lib_guild_data:match_guild({guild_name_fuzzy, GuildName})
            end
    end,
    case GuildMap =/= #{} of
        true ->
            GuildList = lib_guild_mod:get_guild_list(GuildMap, Filter),
            % 战力排序
            F = fun(GuildA, GuildB) ->
                #guild{combat_power = CombatPowerA} = GuildA,
                #guild{combat_power = CombatPowerB} = GuildB,
                CombatPowerA > CombatPowerB
            end,
            GuildListSort = lists:sort(F, GuildList),
            GuildListLen = length(GuildListSort),
            % 获得分页
            {PageTotal, StartPos, ThisPageSize} = lib_guild_util:calc_page_cache(GuildListLen, PageSize, PageNo),
            GuildListSortSub = lists:sublist(GuildListSort, StartPos, ThisPageSize),
            % 数据组装
            GuildApplyMap = lib_guild_data:get_guild_apply_map(),
            F2 = fun(TmpGuild) ->
                #guild{
                    id = GuildId, name = TmpGuildName,
                    lv = GuildLv, chief_id = ChiefId,chief_name=ChiefName,
                    flag = Flag,division = _Division,
                    auto_approve_lv = ReqLv,auto_approve_power=ReqPow,
                    member_num = MemberNum,combat_power= GuildCombatPower,approve_type=AppT,
                    announce = Announce, badges = Badges0, week_labor_last = WeekLaborLast,
                    add_member_num = AddMemberNum, create_time = CreateTime, week_labor_refresh = LastRefreshTime
                } = TmpGuild,
                IsApply = case maps:is_key({RoleId, GuildId}, GuildApplyMap) of
                    true -> 1;
                    false -> 0
                end,
                Badges = [{BadgeID,BSTime,BETime}||#guild_badge{id=BadgeID,stime=BSTime,etime=BETime}<-Badges0],
                ChiefMember = lib_guild_data:get_guild_member_by_role_id(ChiefId),
                ChiefFigure   = case ChiefMember of
                    #guild_member{figure=Figure}->
                        Figure;
                    _->
                        #figure{id=ChiefId,name=ChiefName}
                end,
                OpenDay = util:get_open_day(),
                GuildLaborLvList = data_guild:get_active_lv(OpenDay),
                HasFirstRefresh = LastRefreshTime > CreateTime,
                Division = case HasFirstRefresh of
                               false -> 0;
                               _ -> lib_guild_mod:get_labor_lv(GuildLaborLvList, WeekLaborLast)
                           end,
                {GuildId,TmpGuildName,Flag,GuildLv,Division,WeekLaborLast,GuildCombatPower,ChiefFigure,MemberNum,IsApply,AppT,Announce,ReqLv,ReqPow,Badges,AddMemberNum}
            end,
            SendList = lists:map(F2, GuildListSortSub),
            GuildNum = lib_guild_mod:get_history_guild_num(),
            {ok, BinData} = pt_400:write(40001, [Filter, PageTotal, PageNo, SendList, GuildNum]),
            lib_server_send:send_to_uid(RoleId, BinData);
        false ->
	        GuildNum = lib_guild_mod:get_history_guild_num(),
            case GuildName =/= "" of
                true ->
                    {ok, BinData} = pt_400:write(40000, [?ERRCODE(err400_not_find_guild)]),
                    lib_server_send:send_to_uid(RoleId, BinData),
                    {ok, BinData1} = pt_400:write(40001, [Filter, 0, PageNo, [], GuildNum]),
                    lib_server_send:send_to_uid(RoleId, BinData1);
                false ->
                    {ok, BinData} = pt_400:write(40001, [Filter, 0, PageNo, [], GuildNum]),
                    lib_server_send:send_to_uid(RoleId, BinData)
            end
    end,
    {noreply, State};

%% 申请加入公会
handle_cast({'apply_join_guild', RoleId, RoleInfoMap, GuildId}, State) ->
    lib_guild_mod:apply_join_guild(RoleId, RoleInfoMap, GuildId),
    {noreply, State};

%% 海投简历
handle_cast({'apply_join_guild_multi', RoleId, RoleInfoMap}, State) ->
    lib_guild_mod:apply_join_guild_multi(RoleId, RoleInfoMap),
    {noreply, State};

%% 申请帮派职位
handle_cast({apply_guild_position, RoleId, Position, GuildId}, State) ->
    lib_guild_mod:apply_guild_position(RoleId, Position, GuildId),
    {noreply, State};

%%  获取公会信息界面-基础信息
handle_cast({'send_guild_info', RoleId, GuildId, _Status}, State) ->
    case lib_guild_data:get_guild_by_id(GuildId) of
        [] -> skip;
        Guild ->
            % TmpMember = lib_guild_data:get_guild_member_by_role_id(RoleId),
            % GuildMember = ?IF(is_record(TmpMember, guild_member), TmpMember, #guild_member{}),
            #guild{name = GuildName, chief_id = _ChiefId, chief_name = ChiefName,
            announce = Announce, funds = Funds, lv = GuildLv,exp=Exp,flag = Flag,
            member_num = MemberNum, combat_power = CombatPower,badges = Badges0,division=_Division,week_labor_last=WeekLabor,
            disband_warnning_time = DisbandWarnningTime, create_time = CreateTime, add_member_num = AddMemberNum,
            week_labor_refresh = LastRefreshTime
            } = Guild,
            %#guild_member{position = Position} = GuildMember,
            OnlineFlag = 1,
            GuildMemberMap = lib_guild_data:match_guild_member({online_flag, GuildId, OnlineFlag}),
            OnlineNum = maps:size(GuildMemberMap),
            PositionMemberMap = lib_guild_data:match_guild_member({specify_positions, GuildId, [?POS_CHIEF, ?POS_DUPTY_CHIEF, ?POS_DIRECTOR, ?POS_ELITE]}),
            PositionMemberList = [{TmpPosition, TmpRoleId, TmpFigure#figure{position = TmpPosition} } || #guild_member{position = TmpPosition, id = TmpRoleId, figure = TmpFigure} <- maps:values(PositionMemberMap)],
            DisbandType = 0,
            % SalaryStatus = case Status == 0 andalso data_guild:get_salary(Position, LiveNum) of
            %     Reward when is_list(Reward) andalso Reward =/= [] -> 0;
            %     _ -> ?IF(Status == 0, 2, Status)
            % end,
            OpenDay = util:get_open_day(),
            GuildLaborLvList = data_guild:get_active_lv(OpenDay),
            HasFirstRefresh = LastRefreshTime > CreateTime,
            Division = case HasFirstRefresh of
                           false -> 0;
                           _ -> lib_guild_mod:get_labor_lv(GuildLaborLvList, WeekLabor)
                       end,
            Badges = [{BadgeID,BSTime,BETime}||#guild_badge{id=BadgeID,stime=BSTime,etime=BETime}<-Badges0],
            {ok, BinData} = pt_400:write(40005, [GuildId, GuildName,Flag,ChiefName, Announce, PositionMemberList, GuildLv,Exp,Division,
                 Funds,MemberNum, WeekLabor, CombatPower, OnlineNum, DisbandWarnningTime, DisbandType, CreateTime,Badges,AddMemberNum]),
            lib_server_send:send_to_uid(RoleId, BinData)
    end,
    {noreply, State};

%% 获取公会信息界面-成员列表
handle_cast({'send_guild_member_short_info', RoleId, GuildId, PageSize, PageNo, SortType, SortFlag, MemberType, SpecialType}, State) ->
    GuildMemberList = lib_guild_data:search_guild_member(GuildId, RoleId, SortType, SortFlag, MemberType, SpecialType),
    Len = length(GuildMemberList),
    % 获得分页
    {PageTotal, StartPos, ThisPageSize} = lib_guild_util:calc_page_cache(Len, PageSize, PageNo),
    GuildMemberListSub = lists:sublist(GuildMemberList, StartPos, ThisPageSize),
    F = fun(#guild_member{
            id = TmpRoleId, figure = Figure, position = Position,week_labor=WeekLabor,labors=Labors,
            combat_power = CombatPower, online_flag = OnlineFlag, last_logout_time = LastLogoutTime, create_time = CreateTime}) ->
        case CombatPower == 0 of
            true -> %% 战力为0去缓存拿一遍
                LastCombatPower = lib_role:get_role_combat_power(TmpRoleId);
            false ->
                LastCombatPower = CombatPower
        end,
        OfflineTime = ?IF(OnlineFlag == ?ONLINE_ON, 0, LastLogoutTime),
        {TmpRoleId,Figure,Position,LastCombatPower,WeekLabor,Labors,OnlineFlag,OfflineTime,CreateTime}
    end,
    List = lists:map(F, GuildMemberListSub),
    {ok, BinData} = pt_400:write(40006, [PageTotal, PageNo, List]),
    lib_server_send:send_to_uid(RoleId, BinData),
    {noreply, State};

%% 退出公会
handle_cast({'quit_guild', RoleId}, State) ->
    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 -> ErrorCode = ?ERRCODE(err400_not_on_guild_to_quit);
        is_record(Guild, guild) == false -> ErrorCode = ?ERRCODE(err400_not_on_guild_to_quit);
        true ->
            #guild_member{position = Position} = GuildMember,
            #guild{id = GuildId, member_num = MemberNum} = Guild,
            if
                Position == ?POS_CHIEF andalso MemberNum > 1 ->
                    ErrorCode = ?ERRCODE(err400_chief_not_to_quit);
                Position == ?POS_CHIEF andalso MemberNum == 1 ->
                    case lib_mutex_check:check_disband_guild(GuildId) of
                        true ->
                            %% 如果公会只剩会长一人可以退出公会并且公会即时解散
                            case lib_guild_mod:disband_guild(?DISBAND_REASON_CHIEF_QUIT, GuildId) of
                                ok -> ErrorCode = ?SUCCESS;
                                _ -> ErrorCode = ?FAIL
                            end;
                        {false, ErrorCode} -> skip
                    end;
                true ->
                    ErrorCode = ?SUCCESS,
                    lib_guild_data:delete_guild_member_on_db_and_p(GuildMember),
                    NewGuild = lib_guild_data:get_guild_by_id(GuildId),
                    lib_guild_api:quit_guild(?GEVENT_QUIT, NewGuild, GuildMember)
            end
    end,
    {ok, BinData} = pt_400:write(40007, [ErrorCode]),
    lib_server_send:send_to_uid(RoleId, BinData),
    {noreply, State};

%% 申请列表
handle_cast({'send_guild_apply_list', RoleId, GuildId}, State) ->
    GuildApplyMap = lib_guild_data:get_guild_apply_map_by_guild_id(GuildId),
    GuildApplyList = maps:values(GuildApplyMap),
    GuildApplyListSort = lists:keysort(#guild_apply.create_time, GuildApplyList),
    % Len = length(GuildApplyList),
    % {PageTotal, StartPos, ThisPageSize} = lib_guild_util:calc_page_cache(Len, PageSize, PageNo),
    % GuildApplyListSub = lists:sublist(GuildApplyListSort, StartPos, ThisPageSize),
    F = fun(#guild_apply{role_id = TmpRoleId,position = Position,create_time=Time}) ->
        case lib_role:get_role_show(TmpRoleId) of
            [] -> Figure = #figure{}, CombatPower = 0;
            #ets_role_show{figure = Figure, combat_power = CombatPower} -> ok
        end,
        {TmpRoleId, Figure, CombatPower,Position,Time}
    end,
    List = lists:map(F, GuildApplyListSort),
    {ok, BinData} = pt_400:write(40008, [List]),
    lib_server_send:send_to_uid(RoleId, BinData),
    {noreply, State};

%% 审批公会请求
handle_cast({'approve_guild_apply', RoleId, ApplyRoleId, ApplyRoleInfoMap, Type}, State) ->
    lib_guild_mod:approve_guild_apply(RoleId, ApplyRoleId, ApplyRoleInfoMap, Type),
    {noreply, State};

%% 审批设置界面
handle_cast({'send_approve_setting_view', RoleId, GuildId}, State) ->
    case lib_guild_data:get_guild_by_id(GuildId) of
        [] -> skip;
        Guild ->
            #guild{approve_type = ApproveType, auto_approve_lv = AutoApproveLv, auto_approve_power = AutoApprovePower} = Guild,
            {ok, BinData} = pt_400:write(40010, [ApproveType, AutoApproveLv, AutoApprovePower]),
            lib_server_send:send_to_uid(RoleId, BinData)
    end,
    {noreply, State};

%% 设置审批
handle_cast({'setting_approve', RoleId, ApproveType, AutoApproveLv, AutoApprovePower}, State) ->
    GuildMember = lib_guild_data:get_guild_member_by_role_id(RoleId),
    if
        is_record(GuildMember, guild_member) == false -> ErrorCode = ?ERRCODE(err400_not_on_guild_to_modify_approve_setting);
        true ->
            #guild_member{guild_id = GuildId, position = Position} = GuildMember,
            PermissionList = lib_guild_mod:get_position_permission_list(GuildId, Position),
            IsAllowModify = lists:member(?PERMISSION_APPROVE_SETTING, PermissionList),
            Guild = lib_guild_data:get_guild_by_id(GuildId),
            if
                is_record(Guild, guild) == false -> ErrorCode = ?ERRCODE(err400_not_on_guild_to_modify_approve_setting);
                IsAllowModify == false -> ErrorCode = ?ERRCODE(err400_no_permission);
                true ->
                    ErrorCode = ?SUCCESS,
                    Sql = io_lib:format(?sql_guild_update_approve, [ApproveType, AutoApproveLv, AutoApprovePower, GuildId]),
                    db:execute(Sql),
                    NewGuild = Guild#guild{approve_type = ApproveType, auto_approve_lv = AutoApproveLv, auto_approve_power = AutoApprovePower},
                    lib_guild_data:update_guild(NewGuild)
            end
    end,
    {ok, BinData} = pt_400:write(40011, [ErrorCode]),
    lib_server_send:send_to_uid(RoleId, BinData),
    {noreply, State};

%% 公告编辑界面
handle_cast({'send_announce_view_info', Sid, GuildId}, State) ->
    Guild = lib_guild_data:get_guild_by_id(GuildId),
    if
        is_record(Guild, guild) == false ->
            lib_guild:send_error_code(Sid, ?ERRCODE(err400_not_on_guild_to_modify_announce));
        true ->
            #guild{modify_times = ModifyTimes} = Guild,
            FreeModifyTimes = data_guild:get(notice_limit),
            {ok, BinData} = pt_400:write(40019, [max(0, FreeModifyTimes - ModifyTimes), FreeModifyTimes]),
            lib_server_send:send_to_sid(Sid, BinData)
    end,
    {noreply, State};

handle_cast({'modify_announce_by_gm', GuildId, Announce}, State) ->
    Len = data_guild:get(announce_len),
    CheckLength = util:check_length(Announce, Len),
    CheckKeyWord = lib_word:check_keyword(Announce),
    if
        GuildId =< 0 -> skip;
        CheckLength == false -> skip;
        CheckKeyWord -> skip;
        true ->
            Guild = lib_guild_data:get_guild_by_id(GuildId),
            if
                is_record(Guild, guild) == false ->
                    ?ERR("guild not exist:~p", [GuildId]);
                true ->
                    #guild{chief_id = _ChiefId} = Guild,
                    AnnounceBin = util:make_sure_binary(Announce),
                    Sql = io_lib:format(?sql_guild_update_announce, [AnnounceBin, GuildId]),
                    db:execute(Sql),
                    NewGuild = Guild#guild{announce = AnnounceBin},
                    lib_guild_data:update_guild(NewGuild)
            end
    end,
    {noreply, State};

%% 编辑公告
handle_cast({'modify_announce', RoleId, Announce, SaveType}, State) ->
    GuildMember = lib_guild_data:get_guild_member_by_role_id(RoleId),
    if
        is_record(GuildMember, guild_member) == false -> ErrorCode = ?ERRCODE(err400_not_on_guild_to_modify_announce), Left = 0;
        true ->
            #guild_member{guild_id = GuildId, position = Position} = GuildMember,
            PermissionList = lib_guild_mod:get_position_permission_list(GuildId, Position),
            IsAllowModify = lists:member(?PERMISSION_MODIFY_TENET_AND_ANNOUNCE, PermissionList),
            Guild = lib_guild_data:get_guild_by_id(GuildId),
            #guild{modify_times = ModitifyTimes} = ?IF(is_record(Guild, guild), Guild, #guild{}),
            TimesLimit = data_guild:get(notice_limit),
            if
                is_record(Guild, guild) == false -> ErrorCode = ?ERRCODE(err400_not_on_guild_to_modify_announce), Left = 0;
                IsAllowModify == false -> ErrorCode = ?ERRCODE(err400_not_permission_to_modify_announce), Left = 0;
                ModitifyTimes >= TimesLimit -> ErrorCode = ?ERRCODE(err400_modify_times_limit), Left = 0;
                true ->
                    ErrorCode = ?SUCCESS,
                    Left = max(0, TimesLimit - (ModitifyTimes + 1)),
                    AnnounceBin = util:make_sure_binary(Announce),
                    Sql = io_lib:format(?sql_guild_update_announce, [AnnounceBin, GuildId]),
                    db:execute(Sql),
                    Sql1 = io_lib:format(?sql_guild_update_announce_modify_times, [ModitifyTimes + 1, GuildId]),
                    db:execute(Sql1),
                    NewGuild = Guild#guild{announce = AnnounceBin, modify_times = ModitifyTimes + 1},
                    lib_guild_data:update_guild(NewGuild),
                    case SaveType == 2 of
                        true ->
                            %% 给公会成员发邮件
                            GuildMemberMap = lib_guild_data:get_guild_member_map(GuildId),
                            RoleIdList = maps:keys(GuildMemberMap),
                            lib_mail_api:send_guild_member_mail(RoleIdList,?MOD_GUILD, utext:get(4000005), Announce, []);
                        false -> skip
                    end
            end
    end,
    {ok, BinData} = pt_400:write(40012, [ErrorCode, Left]),
    lib_server_send:send_to_uid(RoleId, BinData),
    {noreply, State};

%% 任命职位
handle_cast({'appoint_position', RoleId, AppointeeId, Position}, State) ->
    lib_guild_mod:appoint_position(RoleId, AppointeeId, Position),
    {noreply, State};

%% 踢出公会
handle_cast({'kick_out_guild', RoleId, LeaveId}, State) ->
    GuildMember = lib_guild_data:get_guild_member_by_role_id(RoleId),
    LeaveGuildMember = lib_guild_data:get_guild_member_by_role_id(LeaveId),
    if
        is_record(GuildMember, guild_member) == false -> ErrorCode = ?ERRCODE(err400_not_on_guild_to_kick);
        is_record(LeaveGuildMember, guild_member) == false -> ErrorCode = ?ERRCODE(err400_not_on_guild_to_kicked);
        GuildMember#guild_member.guild_id =/= LeaveGuildMember#guild_member.guild_id ->
            ErrorCode = ?ERRCODE(err400_not_same_guild_to_kick);
        true ->
            #guild_member{guild_id = GuildId, position = Position} = GuildMember,
            #guild_member{position = LeavePosition} = LeaveGuildMember,
            PermissionList = lib_guild_mod:get_position_permission_list(GuildId, Position),
            IsAllowKick = lists:member(?PERMISSION_FIRE_MEMBER, PermissionList),
            PositionNo = data_guild_m:get_position_no(Position),
            LeavePositionNo = data_guild_m:get_position_no(LeavePosition),
            if
                IsAllowKick == false -> ErrorCode = ?ERRCODE(err400_not_permission_to_kick);
                % LeavePosition == ?POS_CHIEF -> ErrorCode = ?ERRCODE(err400_this_position_can_not_kick_member);
                PositionNo =< LeavePositionNo -> ErrorCode = ?ERRCODE(err400_this_position_can_not_kick_member);
                true ->
                    ErrorCode = ?SUCCESS,
                    lib_guild_data:delete_guild_member_on_db_and_p(LeaveGuildMember),
                    Guild = lib_guild_data:get_guild_by_id(GuildId),
                    lib_guild_api:quit_guild(?GEVENT_KICK_OUT, Guild, LeaveGuildMember)
                    % 推送当前公会成员列表给任命者
                    % mod_guild:send_guild_member_short_info(RoleId, GuildId, ?PAGE_SIZE, 1, 0, 0, 0, 0)
            end
    end,
    {ok, BinData} = pt_400:write(40014, [ErrorCode, LeaveId]),
    lib_server_send:send_to_uid(RoleId, BinData),
    {noreply, State};

%% 清空申请列表
handle_cast({'clean_all_guild_apply_on_this_guild', RoleId}, State) ->
    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_not_on_guild_to_clean_apply);
        is_record(GuildMember, guild_member) == false -> ErrorCode = ?ERRCODE(err400_not_on_guild_to_clean_apply);
        true ->
            #guild{id = GuildId} = Guild,
            % 权限
            #guild_member{position = Position} = GuildMember,
            PermissionList = lib_guild_mod:get_position_permission_list(GuildId, Position),
            IsAllow = lists:member(?PERMISSION_APPROVE_APPLY, PermissionList),
            if
                IsAllow == false -> ErrorCode = ?ERRCODE(err400_no_permission);
                true ->
                    ErrorCode = ?SUCCESS,
                    Sql = io_lib:format(?sql_guild_apply_delete_by_guild_id, [GuildId,?POS_LOG_JOIN]),
                    db:execute(Sql),
                    lib_guild_data:delete_guild_apply_by_guild_id(GuildId,?POS_LOG_JOIN)
                    % lib_guild_mod:send_guild_apply_red_point(GuildId)
            end
    end,
    {ok, BinData} = pt_400:write(40016, [ErrorCode, 2]),
    lib_server_send:send_to_uid(RoleId, BinData),
    {noreply, State};

%% 全部批准入会
handle_cast({'approve_all_guild_apply_on_this_guild', RoleId}, State) ->
    lib_guild_mod:approve_all_guild_apply_on_this_guild(RoleId),
    {noreply, State};

%% 增加公会资金
handle_cast({'add_gfunds', RoleId, GuildId, AddGfunds, Type}, State) ->
    lib_guild_mod:add_gfunds(RoleId, GuildId, AddGfunds, Type),
    {noreply, State};

% %% 增加贡献成长值
% handle_cast({'add_growth', RoleId, GuildId, AddGrowth, ProduceType, Extra}, State) ->
%     lib_guild_mod:add_growth(RoleId, GuildId, AddGrowth, ProduceType, Extra),
%     {noreply, State};

%% 自动任命为会长
handle_cast({'auto_appoint_to_chief', DelaySec}, State) ->
    lib_guild_mod:auto_appoint_to_chief(DelaySec),
    {noreply, State};

handle_cast({'auto_appoint_to_chief_by_guild_id', GuildId}, State) ->
    lib_guild_mod:auto_appoint_to_chief_by_guild_id(GuildId),
    {noreply, State};

%% 更新公会成员属性
handle_cast({'update_guild_member_attr', RoleId, AttrList}, State) ->
    lib_guild_mod: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 ->
            lib_guild_api:guild_af_update_member_attr(Guild, GuildMember, AttrList)
    end,
    {noreply, State};

%% 发送公会邮件
handle_cast({'send_guild_mail_by_role_id', RoleId, Title, Content, CmAttachment, ExcludeIdList}, State) ->
    Guild = lib_guild_data:get_guild_by_role_id(RoleId),
    if
        is_record(Guild, guild) == false -> skip;
        true ->
            GuildMemberMap = lib_guild_data:get_guild_member_map(Guild#guild.id),
            RoleIdList = maps:keys(GuildMemberMap) -- ExcludeIdList,
            lib_mail_api:send_guild_mail(RoleIdList,?MOD_GUILD, Title, Content, CmAttachment)
    end,
    {noreply, State};

%% 发送公会邮件
handle_cast({'send_guild_mail_by_guild_id', GuildId, Title, Content, CmAttachment, ExcludeIdList}, State) ->
    Guild = lib_guild_data:get_guild_by_id(GuildId),
    if
        is_record(Guild, guild) == false -> skip;
        true ->
            GuildMemberMap = lib_guild_data:get_guild_member_map(Guild#guild.id),
            RoleIdList = maps:keys(GuildMemberMap) -- ExcludeIdList,
            lib_mail_api:send_guild_mail(RoleIdList,?MOD_GUILD, Title, Content, CmAttachment)
    end,
    {noreply, State};

%% 玩家拥有的权限列表
handle_cast({'send_role_permission_list', RoleId}, State) ->
    lib_guild_mod:send_role_permission_list(RoleId),
    {noreply, State};

%% 红点信息
handle_cast({'send_red_point', RoleId, Type}, State) ->
    lib_guild_mod:send_red_point(RoleId, Type, 5),
    {noreply, State};

% %% 检测是否能解散公会
% handle_cast({'do_disband_guild', GuildId, RoleId}, State) ->
%     lib_guild_mod:do_disband_guild(GuildId, RoleId),
%     {noreply, State};

%% 解散公会
handle_cast({'disband_guild', DisbandType, GuildId}, State) ->
    lib_guild_mod:disband_guild(DisbandType, GuildId),
    {noreply, State};

handle_cast({'apply_cast_guild_member', GuildId, MemberType, Module, Method, Args}, State) ->
    GuildMemberList = lib_guild_data:search_guild_member(GuildId, 0, 0, 0, MemberType, 0),
    F = fun(#guild_member{id = PlayerId}) -> lib_player:apply_cast(PlayerId, ?APPLY_CAST_STATUS, Module, Method, Args) end,
    lists:foreach(F, GuildMemberList),
    {noreply, State};

%% 清理
handle_cast({'day_clear', Clock, DelaySec}, State) ->
    lib_guild_mod:day_clear(Clock, DelaySec),
    {noreply, State};

%% 更新公会的创建时间
handle_cast({'update_guild_create_time', GuildId, CreateTime}, State) ->
    Guild = lib_guild_data:get_guild_by_id(GuildId),
    if
        is_record(Guild, guild) == false -> skip;
        true ->
            Sql = io_lib:format(?sql_guild_update_create_time, [CreateTime, GuildId]),
            db:execute(Sql),
            lib_guild_data:update_guild(Guild#guild{create_time = CreateTime})
    end,
    {noreply, State};

% %% 定制活动定时奖励发放
% handle_cast({'ac_custom_timer_reward', ModuleSub, AcSub, GuildRankList}, State) ->
%     F = fun({GuildId, Rank}, TmpMap) ->
%         GuildMemberMap = lib_guild_data:get_guild_member_map(GuildId),
%         F = fun(RoleId, #guild_member{position = Position, create_time = CreateTime}, TmpList) ->
%             [{RoleId, Position, CreateTime}|TmpList]
%         end,
%         RoleInfoList = maps:fold(F, [], GuildMemberMap),
%         TmpMap#{Rank=>RoleInfoList}
%     end,
%     Map = lists:foldl(F, #{}, GuildRankList),
%     spawn(lib_ac_custom_reward, ac_custom_timer_reward, [ModuleSub, AcSub, Map]),
%     {noreply, State};

%% 更新玩家的战力
handle_cast({'update_guild_member_power', RoleId, CombatPower}, State) ->
    % Guild = lib_guild_data:get_guild_by_role_id(RoleId),
    GuildMember = lib_guild_data:get_guild_member_by_role_id(RoleId),
    if
        is_record(GuildMember, guild_member) == false -> skip;
        true ->
            #guild_member{h_combat_power = OldHCombatPower,figure=Figure} = GuildMember,
            HCombatPower = max(CombatPower, OldHCombatPower),
            NewGuildMember = GuildMember#guild_member{figure=Figure#figure{power=CombatPower},combat_power = CombatPower, h_combat_power = HCombatPower},
            lib_guild_data:update_guild_member(NewGuildMember)
            % #guild{combat_power = GuildCombatPower} = Guild,
            % NewGuild = Guild#guild{combat_power = max(GuildCombatPower+CombatPower-OldCombatPower, 0)},
            % lib_guild_data:update_guild(NewGuild)
    end,
    {noreply, State};

%% 检测是否需要解散帮派
handle_cast({'check_auto_disband_guild',IsInGWar, GuildId}, State) ->
    lib_guild_mod:check_auto_disband_guild(IsInGWar,GuildId),
    {noreply, State};

%% 更新玩家的战力
handle_cast({'count_guild_combat_power'}, State) ->
    %% 更新公会的战力值
    NowTime = utime:unixtime(),
    GuildMap = lib_guild_data:get_guild_map(),
    F = fun(GuildId, _OldGuild, _Acc) ->
        Guild = lib_guild_data:get_guild_by_id(GuildId),
        SumCombatPower = lib_guild_util:count_guild_combat_power(GuildId, NowTime),

        LastGuild = Guild#guild{combat_power = SumCombatPower},

        %% 刷新榜单
        lib_common_rank_api:refresh_rank_by_guild(LastGuild),

        %% 社团竞速团长任务
        lib_guild_race_rank_task:trigger_power_up_task(GuildId, SumCombatPower),

        lib_guild_data:update_guild(LastGuild)
    end,
    maps:fold(F, ok, GuildMap),
    {noreply, State};

handle_cast({'get_guild_week_labor', GuildId,RoleID,Stage},State)->
    Guild = lib_guild_data:get_guild_by_id(GuildId),
    case Guild of
        #guild{week_labor_refresh=WTime,week_labor=WeekLabors}->
            skip;
        _->
            WeekLabors=0,WTime=utime:logic_week_start()
    end,
    {ok,Bin} = pt_404:write(40402,[WeekLabors,WTime,Stage]),
    lib_server_send:send_to_uid(RoleID,Bin),
    {noreply, State};

handle_cast({update_guild_labor, GuildId,RoleID,Name,_Total,Add,_Type,Tid},State)->
    case lib_guild_data:get_guild_by_id(GuildId) of
        Guild when is_record(Guild, guild) ->
            NGuild = self_update_week_labor(guild,Guild),
            #guild{
                lv=Glv,
                name=GName,
                chief_id = ChiefId,                  % 会长id
                chief_name = ChiefName,             % 会长名字
                exp=CurExp,
                week_labor=WLabor,
                member_num = MemberNum
            }=NGuild,
            {NGlv,NExp} = update_guild_lv(Glv,CurExp,Add),

            NWlabor = WLabor+Add,
            NewGuild0 = NGuild#guild{lv=NGlv,exp=NExp,week_labor=NWlabor},
            NewGuild = case NGlv == Glv of
                true->
                    NewGuild0;
                _->
                    lib_guild_badge:trigger_badge(NewGuild0,guild_level)
            end,
            lib_guild_data:db_guild_update_labor(NewGuild),

            {ok,Bin0} = pt_404:write(40406,[NWlabor]),

            {ok,Bin1} = pt_400:write(40029,[NGlv,NExp]),

            lib_guild_data:update_guild(NewGuild),
            %% 刷新榜单
            lib_common_rank_api:refresh_guild_labor_rank(NewGuild),
            GuildMember = lib_guild_data:get_guild_member_by_role_id(RoleID),
            if
                is_record(GuildMember, guild_member) == false -> skip;
                true ->
                    NGuildMember = self_update_week_labor(member,GuildMember),
                    #guild_member{week_labor=MWLabor,labors=MLabors} = NGuildMember,
                    NewGuildMember = NGuildMember#guild_member{week_labor=MWLabor+Add,labors=MLabors+Add},
                    mod_guild_race_rank:live_change(GuildId, RoleID, MLabors+Add),
                    lib_guild_data:update_guild_member(NewGuildMember),
                    lib_guild_data:update_guild_member_labor(NewGuildMember),

                    %% TA数据上报
                    UnInfo =  [GuildId, GName, Glv, MemberNum, Tid, Add, MWLabor+Add, NWlabor],
                    lib_player:apply_cast(RoleID, ?APPLY_CAST_STATUS, lib_guild_mod, after_update_labor, [UnInfo])
            end,

            Now = utime:unixtime(),
            case Tid>0 of
                true->
                    lib_guild_mod:update_guild_daily_log(GuildId,2,Name,Add,Now),
                    {ok,Bin2} =  pt_404:write(40404,[2,Name,Add,Now]),
                    Bin3 = <<Bin1/binary,Bin2/binary>>;
                _->
                    Bin3 = Bin1
            end,
            case NGlv /= Glv of
                true->
                    lib_guild_mod:update_guild_daily_log(GuildId,4,GName,NGlv,Now),
                    {ok,Bin4} =  pt_404:write(40404,[4,GName,NGlv,Now]),
                    lib_guild_api:change_guild_member(?GEVENT_UPGRADE_GUILD, [GuildId,NGlv]),
                    lib_log_api:log_guild_lv(GuildId,GName,ChiefId,ChiefName,Glv,NGlv),
                    Bin = <<Bin3/binary,Bin4/binary,Bin0/binary>>;
                _->
                    Bin = <<Bin3/binary,Bin0/binary>>
            end,
            lib_server_send:send_to_guild(GuildId, Bin);
        _->
            skip
    end,
    {noreply,State};

%% =====================================
%% 公会仓库相关cast
%% =====================================
% handle_cast({'send_guild_depot_info', RoleId, GuildId, DepotScore}, State) ->
%     lib_guild_depot_mod:send_guild_depot_info(RoleId, GuildId, DepotScore),
%     {noreply, State};

% handle_cast({'add_to_depot', RoleId, RoleName, GoodsInfoList, DepotScore}, State) ->
%     lib_guild_depot_mod:add_to_depot(RoleId, RoleName, GoodsInfoList, DepotScore),
%     {noreply, State};

% handle_cast({'exchange_depot_goods', RoleId, RoleName, DepotGoodsId, GoodsTypeId, Num, DepotScore, OneNum, NeedScore}, State) ->
%     case OneNum > 0 of
%         true ->
%             lib_guild_depot_mod:exchange_special_goods(RoleId, RoleName, GoodsTypeId, Num, OneNum, NeedScore, DepotScore);
%         false ->
%             lib_guild_depot_mod:exchange_depot_goods(RoleId, RoleName, DepotGoodsId, Num, DepotScore)
%     end,
%     {noreply, State};

% handle_cast({'destory_depot_goods', RoleId, RoleName, DepotGoodsIds}, State) ->
%     lib_guild_depot_mod:destory_depot_goods(RoleId, RoleName, DepotGoodsIds),
%     {noreply, State};

% handle_cast({'send_guild_depot', RoleId, GuildId, GoodId}, State) ->
%     lib_guild_depot_mod:send_guild_depot(RoleId, GuildId, GoodId),
%     {noreply, State};

%% =====================================
%% 公会技能相关cast
%% =====================================
handle_cast({'send_guild_skill_list', RoleId, GuildId, PlayerGSkillMap, SkillType}, State) ->
    GuildSkillList = lib_guild_skill_data:get_guild_skill_list(GuildId),
    PackSkillList = lib_guild_skill:pack_guild_skill_list(SkillType, PlayerGSkillMap, GuildSkillList),
    {ok, BinData} = pt_400:write(40040, [0, PackSkillList]),
    lib_server_send:send_to_uid(RoleId, BinData),
    {noreply, State};

handle_cast({'research_skill', RoleId, SkillId}, State) ->
    lib_guild_mod:research_skill(RoleId, SkillId),
    {noreply, State};

%% =====================================
%% 公会战相关cast
%% =====================================

handle_cast({'update_guild_division', DivisionIndexMap}, State) ->
    case maps:size(DivisionIndexMap) > 0 of
        true ->
            GuildMap = lib_guild_data:get_guild_map(),
            F = fun(GuildId, Guild) ->
                Division = maps:get(GuildId, DivisionIndexMap, 0),
                Guild#guild{division = Division}
            end,
            NewGuildMap = maps:map(F, GuildMap),
            lib_guild_data:save_guild_map(NewGuildMap);
        false -> skip
    end,
    {noreply, State};

%% =====================================
%% 公会榜单结算逻辑
%% =====================================
handle_cast({'send_guild_rank_reward', PreFirGuildId, CurFirGuildId, DesignationId}, State) ->
    case PreFirGuildId > 0 of
        true ->
            PreFirGuildMIds = lib_guild_data:get_all_role_in_guild(PreFirGuildId);
        false ->
            PreFirGuildMIds = lib_guild_data:get_all_role_in_guild()
    end,
    %% 移除上一次的第一名公会成员称号
    case (PreFirGuildId == 0 orelse PreFirGuildId =/= CurFirGuildId) andalso PreFirGuildMIds =/= [] of
        true ->
            NowTime = utime:unixtime(),
            Sql = io_lib:format(?SQL_DSGT_UPDATE_ETIME, [NowTime, NowTime, DesignationId, util:link_list(PreFirGuildMIds)]),
            db:execute(Sql),
            F = fun(TRoleId) ->
                lib_designation_api:cancel_dsgt_online(TRoleId, DesignationId)
            end,
            lists:foreach(F, PreFirGuildMIds);
        false -> skip
    end,
    CurFirGuildMIds = lib_guild_data:get_all_role_in_guild(CurFirGuildId),
    F1 = fun(TRoleId, AccNum) ->
            case AccNum rem 20 of
                0 -> timer:sleep(100);
                _ -> skip
            end,
            lib_designation_api:active_dsgt_common(TRoleId, DesignationId),
            AccNum + 1
    end,
    spawn(fun() -> lists:foldl(F1, 1, CurFirGuildMIds) end),
    {noreply, State};

handle_cast({check_rename_guild, GuildId, RoleId, OpTy, TmpGuildName,Flag}, State) ->
    Guild = lib_guild_data:get_guild_by_id(GuildId),
    GuildMember = lib_guild_data:get_guild_member_by_role_id(RoleId),
    FlagCheck = lib_guild:check_flag(Flag),
    Res
    = if
        FlagCheck == false -> {false,?ERRCODE(err400_guild_flag_used)};
        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 = GuildId1, position = Position} = GuildMember,
            #guild{name = GuildName0} = Guild,
            GuildName = case OpTy of
                0->
                    GuildName0;
                _->
                    TmpGuildName
            end,
            PermissionList = lib_guild_mod:get_position_permission_list(GuildId, Position),
            GuildNameBin0 = util:make_sure_binary(GuildName0),
            GuildNameBin = util:make_sure_binary(GuildName),
            {NameMin,NameMax} = data_guild:get(guild_name_len),
            CheckList = case OpTy of
                0->
                    [
                        % 校验字符串
                        {fun() -> GuildId == GuildId1 end, ?FAIL},
                        {fun() -> lists:member(?PERMISSION_RENAME, PermissionList) end, ?ERRCODE(err400_no_permission)}
                    ];
                _->
                    [
                        % 校验字符串
                        {fun() -> GuildId == GuildId1 end, ?FAIL},
                        {fun() -> GuildName =/= "" end, ?ERRCODE(err400_guild_name_null)},
                        {fun() -> GuildNameBin0 =/= GuildNameBin end, ?ERRCODE(err400_guild_name_same)},
                        % {fun() -> util:check_length(GuildName, data_guild_m:get_config(guild_name_len)) == true end, ?ERRCODE(err400_guild_name_len)},
                        {fun() -> util:check_length(GuildName, NameMin, NameMax) == true end, ?ERRCODE(err400_guild_name_len)},
                        {fun() -> lib_word:check_keyword(GuildName) == false end, ?ERRCODE(err400_guild_name_sensitive)},
                        {fun() -> lists:member(?PERMISSION_RENAME, PermissionList) end, ?ERRCODE(err400_no_permission)},
                        {fun() ->
                            NewGuildName = string:to_upper(util:make_sure_list(GuildName)),
                            GuildUpperMap = lib_guild_data:match_guild({name_upper, NewGuildName}),
                            is_map(GuildUpperMap) andalso GuildUpperMap == #{}
                        end, ?ERRCODE(err400_guild_name_repeat)}
                    ]
            end,
            util:check_list(CheckList)
    end,
    case Res of
        {false, ErrorCode} ->
            {ok, BinData} = pt_400:write(40000, [ErrorCode]),
            lib_server_send:send_to_uid(RoleId, BinData);
        true ->
            Cost = case OpTy of
                0->
                    data_guild:get(logo_change_cost);
                _->
                    case Flag ==  Guild#guild.flag of
                        true->
                            data_guild:get(rename_cost);
                        _->
                            data_guild:get(rename_cost)++data_guild:get(logo_change_cost)
                    end
            end,
            NGuildName = case OpTy of
                0->
                    Guild#guild.name;
                _->
                    TmpGuildName
            end,
            lib_player:apply_cast(RoleId, ?APPLY_CAST_STATUS, lib_guild, check_rename_guild_pass, [Cost, GuildId, OpTy, NGuildName, Flag])
    end,
    {noreply, State};

handle_cast({get_guild_daily_log,GuildId,RoleID},State)->
    DailyLogMap = lib_guild_data:get_daily_log(),
    LogList = maps:get(GuildId,DailyLogMap,[]),
    {ok,Bin} = pt_404:write(40405,[LogList]),
    lib_server_send:send_to_uid(RoleID,Bin),
    {noreply,State};

handle_cast({rename_guild, GuildId, RoleId, [OpTy,GuildName,Flag,Cost|_]}, State) ->
    Guild = lib_guild_data:get_guild_by_id(GuildId),
    GuildMember = lib_guild_data:get_guild_member_by_role_id(RoleId),
    GuildNameBin = util:make_sure_binary(GuildName),
    Res = 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 ->
            F = fun() ->
                lib_guild_data:db_guild_update_name(GuildId, Flag, GuildNameBin),
                ok
            end,
            case catch db:transaction(F) of
                ok ->
                    % GuildNameBin = util:make_sure_binary(GuildName),
                    GuildMemberMap = lib_guild_data:get_guild_member_map(GuildId),
                    NewGuildMemberMap = maps:map(fun
                        (_, GMember) ->
                            if
                                is_record(GMember, guild_member) ->
                                    if
                                        GMember#guild_member.online_flag =:= ?ONLINE_ON ->
                                            lib_player:apply_cast(GMember#guild_member.id, ?APPLY_CAST_STATUS, lib_guild, update_guild_name, [GuildId,Flag,GuildNameBin]);
                                        true ->
                                            skip
                                    end,
                                    GMember#guild_member{guild_name = GuildNameBin};
                                true ->
                                    GMember
                            end
                    end, GuildMemberMap),
                    NameUpper = string:to_upper(util:make_sure_list(GuildName)),
                    NewGuild = Guild#guild{name = GuildNameBin, name_upper = NameUpper, c_rename = 0, flag = Flag,  c_rename_time = utime:unixtime()},
                    lib_guild_data:update_guild(NewGuild),
                    lib_guild_data:set_guild_member_map(GuildId, NewGuildMemberMap),
                    GMFigure = GuildMember#guild_member.figure,
                    lib_log_api:log_rename_guild(GuildId, RoleId, GMFigure#figure.name, Guild#guild.name, GuildNameBin, Guild#guild.flag, Flag, Cost),
                    {ok, BinData} = pt_400:write(40025, [?SUCCESS, GuildName,Flag]),
                    lib_server_send:send_to_uid(RoleId, BinData),
                    lib_guild_api:change_guild_member(?GEVENT_RENAME, [GuildId, Guild#guild.name, GuildNameBin]),
                    OpTy /= 0 andalso lib_chat:send_TV({all}, ?MOD_GUILD, 10, [Guild#guild.name, GuildNameBin]),
                    true;
                _Error ->
                    {false, ?FAIL}
            end
    end,
    case Res of
        true -> ok;
        {false, Err} -> lib_player:apply_cast(RoleId, ?APPLY_CAST_STATUS, lib_guild, rename_guild_fail, [Cost, Err]);
        _ -> lib_player:apply_cast(RoleId, ?APPLY_CAST_STATUS, lib_guild, rename_guild_fail, [Cost, ?FAIL])
    end,
    {noreply, State};

%% 职位管理界面
handle_cast({'send_position_manage_view', RoleId, GuildId, PageSize, PageNo}, State) ->
    GuildMemberList = lib_guild_data:search_guild_member(GuildId, RoleId, ?sgm_pos_lv_donate, ?sort_flag_desc, ?member_type_all, ?s_special_type_normal),
    case lib_guild_data:get_guild_member_by_role_id(RoleId) of
        [] -> PageTotal=0, PageNo = 0, List = [];
        GuildMember ->
            #guild_member{position = MyPosition} = GuildMember,
            if
                MyPosition == ?POS_CHIEF ->
                    FilterPositionList = [];
                MyPosition == ?POS_DUPTY_CHIEF  ->
                    FilterPositionList = [?POS_CHIEF, ?POS_DUPTY_CHIEF];
                MyPosition == ?POS_DIRECTOR ->
                    FilterPositionList = [?POS_CHIEF, ?POS_DUPTY_CHIEF, ?POS_DIRECTOR];
                true ->
                    FilterPositionList = [?POS_CHIEF, ?POS_DUPTY_CHIEF, ?POS_DIRECTOR, ?POS_ELITE]
            end,
            F = fun(#guild_member{online_flag = OnlineFlag, id = TmpRoleId, figure = Figure, position = Position, labors = HisLabors,last_logout_time = LastLogoutTime}, TmpList) ->
                case lists:member(Position, FilterPositionList) of
                    true -> TmpList;
                    false ->
                        LastOutTime = ?IF(OnlineFlag == ?ONLINE_OFF, LastLogoutTime, 0),
                        [{TmpRoleId, Figure, Position, HisLabors, LastOutTime}|TmpList]
                end
            end,
            FilterMemberList = lists:foldr(F, [], GuildMemberList),
            Len = length(FilterMemberList),
            % 获得分页
            {PageTotal, StartPos, ThisPageSize} = lib_guild_util:calc_page_cache(Len, PageSize, PageNo),
            List = lists:sublist(FilterMemberList, StartPos, ThisPageSize)
    end,
    {ok, BinData} = pt_400:write(40022, [PageTotal, PageNo, List]),
    lib_server_send:send_to_uid(RoleId, BinData),
    {noreply, State};

%% 发送职位数量列表
handle_cast({'send_position_num_list', RoleId, GuildId}, State) ->
    List = lib_guild_mod:get_position_num_list(GuildId),
    {ok, BinData} = pt_400:write(40023, [List]),
    lib_server_send:send_to_uid(RoleId, BinData),
    {noreply, State};

%% 批量任命职位
handle_cast({'bulk_appoint_position', RoleId, Position, AppointeeIdList}, State) ->
    lib_guild_mod:bulk_appoint_position(RoleId, Position, AppointeeIdList),
    {noreply, State};

%% 获取个人贡献
handle_cast({get_role_donate, RoleId}, State) ->
    {ok, BinData} = pt_400:write(40032, [0]),
    lib_server_send:send_to_uid(RoleId, BinData),
    {noreply, State};

%% 增加贡献
handle_cast({'add_donate', RoleId, CfgId, Num, LogNum}, State) ->
    % lib_guild_mod:add_donate(RoleId, AddDonate, ProduceType, Extra),
    lib_guild_mod:add_donate(lib_guild_data:get_guild_member_by_role_id(RoleId), RoleId, CfgId, Num, LogNum),
    {noreply, State};

%% 外部接口增加贡献
handle_cast({'add_donate_api', RoleId, Num}, State) ->
    % lib_guild_mod:add_donate(RoleId, AddDonate, ProduceType, Extra),
    lib_guild_mod:add_donate_api(RoleId, Num),
    {noreply, State};

%% 外部接口减少贡献
handle_cast({'cost_donate_api', RoleId, ConsumeType, Num, Other}, State) ->
    lib_guild_mod:cost_donate_api(RoleId, ConsumeType, Num, Other),
    {noreply, State};

% %% 查看商店界面
% handle_cast({'send_shop_list',RoleId,ShopMap}, State) ->
%     lib_guild_mod:send_shop_list(lib_guild_data:get_guild_member_by_role_id(RoleId), RoleId, ShopMap),
%     {noreply, State};

% %% 购买商品
% handle_cast({'buy_goods',RoleId,GoodId,Num,BuyNum}, State) ->
%     lib_guild_mod:buy_goods(lib_guild_data:get_guild_member_by_role_id(RoleId), RoleId, GoodId, Num, BuyNum),
%     {noreply, State};

% %% 学习技能
% handle_cast({'learn_skill', RoleId, RoleLv, SkillId, SkillLv}, State) ->
%     lib_guild_mod:learn_skill(lib_guild_data:get_guild_member_by_role_id(RoleId), RoleId, RoleLv, SkillId, SkillLv),
%     {noreply, State};

%% 社交获取公会成员
handle_cast({'relationship_get_guild_members', RoleId, GuildId}, State) ->
    GuildMembers = lib_guild_data:search_guild_member(GuildId, RoleId, ?sgm_default, ?sort_flag_asc, ?member_type_all, ?s_special_type_del_me),
    NewGuildMember = [{Id, Name, Career, Sex, Turn, Lv, VipType, Vip, Picture, PictureVer, OnlineFlag, 0, 0, 0, 0, GuildName, LastLogoutTime} ||
                #guild_member{
                    id = Id, online_flag = OnlineFlag, last_logout_time = LastLogoutTime,
                    figure = #figure{name = Name, career = Career, sex = Sex, turn = Turn, guild_name = GuildName,
                                     lv = Lv, vip_type = VipType, vip = Vip, picture = Picture, picture_ver = PictureVer}} <- GuildMembers],
    lib_player:apply_cast(RoleId, ?APPLY_CAST_STATUS, lib_relationship, send_guild_members, [NewGuildMember]),
    {noreply, State};

handle_cast({'send_chief_figure_info', Node, RoleId, GuildId, ArgsMap}, State) ->
    ChiefGuildMember = lib_guild_data:get_chief(GuildId),
    case ChiefGuildMember of
        #guild_member{
            id = ChiefId,
            figure = Figure
        } ->
            #{ser_id := SerId, mod_id := ModId} = ArgsMap,
            {ok, BinData} = pt_130:write(13014, [SerId, GuildId, ModId, ChiefId, Figure]),
            case Node =/= none of
                true ->
                    clusters_node:apply_cast(lib_server_send, send_to_uid, [Node, RoleId, BinData]);
                _ ->
                    lib_server_send:send_to_uid(RoleId, BinData)
            end;
        _ -> skip
    end,
    {noreply, State};

%%发起合并申请
handle_cast({'apply_guild_merge',RoleID,GuildId,Target},State)->
    lib_guild_mod:apply_guild_merge(RoleID,GuildId,Target),
    {noreply,State};

%%查看合并申请
handle_cast({'get_merge_apply',RoleID,GuildId},State)->
    lib_guild_mod:get_merge_apply(RoleID,GuildId),
    {noreply,State};

%%取消申请
handle_cast({'cancle_guild_merge',RoleID,GuildId},State)->
    lib_guild_mod:cancle_guild_merge(RoleID,GuildId),
    {noreply,State};

%%回复合并
handle_cast({'reply_merge_apply',RoleId,GuildId,OpTy,Target},State)->
    lib_guild_mod:reply_merge_apply(RoleId,GuildId,OpTy,Target),
    {noreply,State};

%%团长回来
handle_cast({'chief_reback',GuildId},State)->
    lib_guild_mod:chief_reback(GuildId),
    {noreply,State};

handle_cast({'get_all_guild_ids', From}, State) ->
    GuildMaps = lib_guild_data:get_guild_map(),
    GuildIds = maps:keys(GuildMaps),
    From ! {'all_guild_ids', GuildIds},
    {noreply, State};

handle_cast({add_guild_badge,GuildID,Bid},State)->
    lib_guild_badge:do_add_guild_badge(GuildID,Bid),
    {noreply,State};

handle_cast({update_party_num,GuildID,Num},State)->
    lib_guild_tribe_mod:update_party_num(GuildID,Num),
    {noreply,State};

handle_cast({guild_scene_exchange,DayNight},State)->
    lib_guild_tribe_mod:guild_scene_exchange(DayNight),
    {noreply,State};

%% 默认匹配
handle_cast(Event, State) ->
    catch ?ERR("mod_guild_cast:handle_cast not match: ~p", [Event]),
    {noreply, State}.

%% 自更新
%% p.s.: utime:logic_day_of_week()获得的是当天4天之后在星期中的第几天
%% 若是周一4点前的时间获得逻辑天的第一天需要往前推1周
self_update_week_labor(guild,Guild)->
    #guild{
        week_labor = WLabor,
        week_labor_last = OWLabor,
        week_labor_refresh = WRefresh
    } = Guild,
    LDay = utime:logic_day_of_week(WRefresh),
    Now = case utime:logic_day_of_week()<5 of
        true when LDay>=5-> %% 周一4点之前
            utime:logic_week_start()+86400*4;
        true->              %% 周一4点之后到周五4点之前
            utime:logic_week_start();
        _->                 %% 周五4点之后
            utime:logic_week_start()+86400*4
    end,
    case Now == WRefresh of
        true->
            Guild;
        _->
            %% 如果对应不上上次刷新时间则自行更新
            %% (服务器维护刚好跨越了刷新时间
            %% 或者 其他特殊原因错过刷新时间)
            case utime:logic_day_of_week()<5 of
                true->
                    Guild#guild{
                        week_labor = 0,
                        week_labor_refresh = Now,
                        week_labor_last = max(WLabor-OWLabor,0)
                    };
                _->
                    Guild#guild{
                        week_labor_refresh = Now,
                        week_labor_last = WLabor
                    }
            end
    end;
self_update_week_labor(member,GuildMember)->
    #guild_member{
        week_labor_refresh=MWRefresh
    } = GuildMember,
    Now = utime:logic_week_start(),
    case Now == MWRefresh of
        true->
            GuildMember;
        _->
            GuildMember#guild_member{
                week_labor = 0,
                week_labor_refresh = Now
            }
    end.

%%等级更新
update_guild_lv(Glv,CurExp,Add)->
    case data_guild:get_guild_lv(Glv) of
        #base_guild_lv{exp=Need} when Need>0->
            case CurExp+Add>=Need of
                true->
                    Minus = max(CurExp+Add-Need,0),
                    update_guild_lv(Glv+1,0,Minus);
                _->
                    {Glv,CurExp+Add}
            end;
        _->
            {Glv,CurExp}
    end.