%% ---------------------------------------------------------------------------
%% @doc mod_guild.erl

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

-include("guild.hrl").
-include("sql_guild.hrl").
-include("common.hrl").
-include("def_id_create.hrl").
-include("errcode.hrl").
-include("figure.hrl").
-include("predefine.hrl").

handle_call({'apply_call', Moudle, Method, Args}, _From, State) ->
    Reply = apply(Moudle, Method, Args),
    {reply, Reply, State};

%% 创建公会
handle_call({'create_guild', Guild, GuildMember}, _From, State) ->
    MatchMap = lib_guild_data:match_guild({name_upper, Guild#guild.name_upper}),
    Size = maps:size(MatchMap),
    Reply = case Size > 0 of
        false ->
            #guild_member{id = RoleId, figure = Figure} = GuildMember,
            F = fun() ->
                GuildId = mod_id_create:get_new_id(?GUILD_ID_CREATE),
                NewGuild = Guild#guild{id = GuildId},
                lib_guild_data:db_guild_insert(NewGuild),
                % 清理请求
                lib_guild_data:db_guild_apply_delete_by_role_id(RoleId),
                % 公会成员加入
                NewGuildMember = GuildMember#guild_member{guild_id = GuildId, figure = Figure#figure{position = ?POS_CHIEF, guild_id = GuildId, guild_name = Guild#guild.name}},
                lib_guild_data:db_guild_member_insert(NewGuildMember),
                {ok, NewGuild, NewGuildMember}
            end,
            case catch db:transaction(F) of
                {ok, #guild{id = GuildId} = NewGuild0, NewGuildMember} ->
	                %% 更新社团历史数量
	                GuildNum = lib_guild_mod:get_history_guild_num(),
	                NewGuildNum = GuildNum + 1,
					lib_guild_mod:update_history_guild_num(NewGuildNum),

	                NewGuild = lib_guild_badge:trigger_badge(NewGuild0,guild_level),
                    lib_guild_data:update_guild(NewGuild),
                    lib_guild_data:add_guild_member(NewGuildMember),
                    lib_guild_data:delete_guild_apply_by_role_id(RoleId),
                    lib_guild_api:create_guild(NewGuild, NewGuildMember),
                    NewGuild2 = lib_guild_data:get_guild_by_id(GuildId),
                    lib_guild_api:join_guild(?GEVENT_CREATE_GUILD, NewGuild2, NewGuildMember),
                    mod_guild_boss_mgr:create_guild(GuildId),
                    guild_collect_mgr:create_guild(GuildId),
                    %% 创建社团任务
                    lib_guild_race_rank_task:trigger_create_guild_task(GuildId, 1),
                    {ok, NewGuild2};
                Error ->
                    ?ERR("M:~p L:~p Error:~p", [?MODULE, ?LINE, Error]),
                    {false, ?FAIL}
            end;
        _ ->
            {false, ?ERRCODE(err400_guild_name_same_not_to_create)}
    end,
    {reply, Reply, State};

handle_call({'is_have_permission', RoleId, PermissionType}, _From, 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 -> 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,
    Reply = lists:member(PermissionType, PermissionList),
    {reply, Reply, State};

handle_call({'get_guild_week_labor_value', GuildId},_From,State)->
    case lib_guild_data:get_guild_by_id(GuildId) of
        [] ->
            Reply = {0,0};
        #guild{week_labor=WeekLabors,week_labor_refresh=Time} ->
            Reply = {WeekLabors,Time}
    end,
    {reply, Reply, State};

% handle_call({'check_move_to_depot', RoleId, GuildId, Num}, _From, State) ->
%     ErrorCode = lib_guild_depot_mod:check_move_to_depot(RoleId, GuildId, Num),
%     {reply, ErrorCode, State};

handle_call({'get_guild_member_max_lv', RoleId}, _From, State) ->
    Guild = lib_guild_data:get_guild_by_role_id(RoleId),
    if
        is_record(Guild, guild) == false -> MaxLv = 0;
        true ->
            #guild{id = GuildId} = Guild,
            GuildMemberMap = lib_guild_data:get_guild_member_map(GuildId),
            F = fun(_K, #guild_member{figure = #figure{lv = Lv} }, List) -> [Lv|List] end,
            LvList = maps:fold(F, [], GuildMemberMap),
            MaxLv = lists:max(LvList)
    end,
    {reply, MaxLv, State};

handle_call({'cost_gfunds', RoleId, CostFunds, Type}, _From, State) ->
     case lib_guild_data:get_guild_by_role_id(RoleId) of
        [] -> Reply = false;
        #guild{id = GuildId, funds = Funds} = Guild ->
            case Funds >= CostFunds of
                true ->
                    NewFunds = Funds - CostFunds,
                    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),
                    lib_log_api:log_consume_gfunds(RoleId, GuildId, Type, CostFunds, NewFunds, utime:unixtime()),
                    Reply = true;
                false ->
                    Reply = false
            end
    end,
    {reply, Reply, State};

%% 学习公会技能
handle_call({'learn_skill', RoleId, SkillId, ExtraData}, _From, State) ->
    Reply = lib_guild_mod:learn_skill(RoleId, SkillId, ExtraData),
    {reply, Reply, State};
handle_call({'get_all_guild'}, _From, State) ->
    {reply, lib_guild_data:get_guild_map(), State};

%% 获取公会人数
handle_call({'get_guild_member_num', GuildId}, _From, State) ->
     case lib_guild_data:get_guild_by_id(GuildId) of
        [] -> Reply = 0;
        #guild{id = GuildId, member_num = MemberNum} -> Reply = MemberNum
    end,
    {reply, Reply, State};

%% 获取公会人数列表[{guild_id,member_num}]
% handle_call({'get_guild_member_num_list'}, _From, State) ->
%     GuildMap = lib_guild_data:get_guild_map(),
%     List = maps:fold(fun(Guild, ListTmp) -> [{Guild#guild.id, Guild#guild.member_num}|ListTmp] end, [], GuildMap),
%     {reply, List, State};

%% 获取指定排名的公会信息
handle_call({'get_specify_ranking_guild', Ranking}, _From, State) ->
    GuildMap = lib_guild_data:get_guild_map(),
    GuildList = maps:values(GuildMap),
    SortList = lib_guild_mod:sort(GuildList, #guild.combat_power, Ranking),
    GuildInfo = hd(lists:reverse(SortList)),
    {reply, GuildInfo, State};

%% 获取公会成员id列表
handle_call({get_guild_member_id, GuildId}, _From, State) ->
    MemberMap = lib_guild_data:get_guild_member_map(GuildId),
    MemberIds = maps:keys(MemberMap),
    {reply, MemberIds, State};

% %% 获取公会活跃度
% handle_call({'get_guild_liveness', GuildId}, _From, State) ->
%     case lib_guild_data:get_guild_by_id(GuildId) of
%         #guild{liveness_list = LiveNessList} ->
%             LiveNum = lib_guild_mod:get_live_num(LiveNessList),
%             {reply, LiveNum, State};
%         _ -> {reply, 0, State}
%     end;

% %% 获取公会活跃度和公会人数
% handle_call({'get_liveness_and_guild_num', GuildId}, _From, State) ->
%     case lib_guild_data:get_guild_by_id(GuildId) of
%         #guild{liveness_list = LiveNessList, member_num = MemberNum} ->
%             LiveNum = lib_guild_mod:get_live_num(LiveNessList),
%             {reply, {LiveNum, MemberNum}, State};
%         _ -> {reply, {0, 0}, State}
%     end;

%% ==================== 秘籍相关 ==================

%% GM修改公会公告
handle_call({'modify_announce_by_gm', GuildId, Announce}, _From, State) ->
    {AMin, AMax} = data_guild:get(announce_len),
    CheckLength = util:check_length(Announce, AMin, AMax),
    CheckKeyWord = lib_word:check_keyword(Announce),
    Reply = if
        GuildId =< 0 -> guild_not_exist;
        CheckLength == false -> announce_len_err;
        CheckKeyWord -> announce_key_word_err;
        true ->
            Guild = lib_guild_data:get_guild_by_id(GuildId),
            if
                is_record(Guild, guild) == false -> guild_not_exist;
                true ->
                    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),
                    ok
            end
    end,
    {reply, {ok, Reply}, State};

%% GM修改公会名字
handle_call({'modify_name_by_gm', GuildId, GuildName}, _From, State) ->
    Guild = lib_guild_data:get_guild_by_id(GuildId),
    Flag  = Guild#guild.flag,
    Reply = if
        is_record(Guild, guild) == false -> not_on_guild;
        true ->
            F = fun() ->
                lib_guild_data:db_guild_update_name(GuildId, Flag, GuildName),
                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, c_rename_time = utime:unixtime()},
                    lib_guild_data:update_guild(NewGuild),
                    lib_guild_data:set_guild_member_map(GuildId, NewGuildMemberMap),
                    lib_guild_api:change_guild_member(?GEVENT_RENAME, [GuildId, Guild#guild.name, GuildNameBin]),
                    lib_chat:send_TV({all}, 400, 10, [Guild#guild.name, GuildNameBin]),
                    true;
                _Error -> fail
            end
    end,
    {reply, {ok, Reply}, State};

%% GM解散公会
handle_call({'disband_guild', DisbandType, GuildId}, _From, State) ->
    Reply = lib_guild_mod:disband_guild(DisbandType, GuildId),
    {reply, {ok, Reply}, State};

%% 获取帮派某项数据
handle_call({guild_data, GuildId, ElemIndex}, _From, State) ->
    Reply = case lib_guild_data:get_guild_by_id(GuildId) of
        Guild = #guild{id = GuildId} when ElemIndex =:= all ->
            Guild;
        Guild = #guild{id = GuildId} when is_integer(ElemIndex) ->
            erlang:element(ElemIndex, Guild);
        _ ->
            no_guild
    end,
    {reply, Reply, State};

%% 默认匹配
handle_call(Event, _From, State) ->
    catch ?ERR("mod_guild_call:handle_call not match: ~p", [Event]),
    {reply, ok, State}.
