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

%% @author  hjh
%% @email  hejiahua@163.com
%% @since  2016-12-15
%% @deprecated 公会进程
%% ---------------------------------------------------------------------------
-module(mod_guild).

-export([
        create_guild/2
        , search_guild_by_name_upper/1
        , apply_call/4
        , apply_cast/3
    ]).

-export([
        search_guild_list/5
        , search_guild_flag_list/1
        , apply_join_guild/3
        , apply_join_guild_multi/2
        , send_guild_info/3
        , approve_guild_apply/4
        , get_all_guild/0
        , get_guild_week_labor/3
        , get_guild_week_labor_value/1
        , get_guild_member_id_list/1
        , get_guild_data/2
    ]).


-export([
        day_clear/2
    ]).

-compile(export_all).

-export([start_link/0]).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]).

-include("guild.hrl").
-include("common.hrl").
-include("errcode.hrl").

%% ---------------------- call -------------------------------

%% 创建公会
create_guild(Guild, GuildMember) ->
    case catch gen_server:call(?GUILD_PID, {'create_guild', Guild, GuildMember}) of
        {ok, NewGuild} -> {ok, NewGuild};
        {false, ErrorCode} -> {false, ErrorCode};
        _ -> {false, ?FAIL}
    end.

%% 根据公会大写名字查公会
search_guild_by_name_upper(NameUpper) ->
    case catch apply_call(lib_guild_data, match_guild, [{name_upper, NameUpper}], 7000) of
        Reply when is_map(Reply) -> Reply;
        _ -> false
    end.

%% 社团数量
get_guild_num() ->
    case catch apply_call(lib_guild_mod, get_guild_num, [], 3000) of
        Reply when is_integer(Reply) -> Reply;
        _ -> 999
    end.

%%获取社团周劳务值
get_guild_week_labor_value(GuildId)->
    case catch gen_server:call(?GUILD_PID, {'get_guild_week_labor_value', GuildId}) of
        {Value,_Time} ->
            Value;
        _ ->
            0
    end.

%%判断旗帜是否可用
search_guild_flag(Flag)->
    case util:is_merge_game() of
        true->
            true;
        _->
            case catch apply_call(lib_guild_data, match_guild, [{flag_use, Flag}], 7000) of
                Reply when is_map(Reply) ->
                    true;
                _ ->
                    false
            end
    end.


%% 是否有该权限
is_have_permission(RoleId, PermissionType) ->
    case catch gen_server:call(?GUILD_PID, {'is_have_permission', RoleId, PermissionType}) of
        Bool when is_boolean(Bool) -> Bool;
        _ -> false
    end.

%% 检测放入公会仓库
check_move_to_depot(RoleId, GuildId, Num) ->
    gen_server:call(?GUILD_PID, {'check_move_to_depot', RoleId, GuildId, Num}, 2000).

%% 获取指定排名的公会信息
get_specify_ranking_guild(Ranking) ->
    gen_server:call(?GUILD_PID, {'get_specify_ranking_guild', Ranking}).

apply_call(Moudle, Method, Args, Timeout) ->
    gen_server:call(?GUILD_PID, {'apply_call', Moudle, Method, Args}, Timeout).

%% ---------------------- cast -------------------------------

cast_to_guild(Msg) ->
    gen_server:cast(?GUILD_PID, Msg).
call_to_guild(Msg) ->
    gen_server:call(?GUILD_PID, Msg).

%% 搜索公会列表
search_guild_list(RoleId, GuildName, Filter, PageSize, PageNo) ->
    gen_server:cast(?GUILD_PID, {'search_guild_list', RoleId, GuildName, Filter, PageSize, PageNo}).

search_guild_flag_list(RoleID)->
    case util:is_merge_game() of
        true->
            {ok,Bin} = pt_400:write(40020,[1,[]]),
            lib_server_send:send_to_uid(RoleID,Bin);
        _->
            gen_server:cast(?GUILD_PID, {'search_guild_flag_list', RoleID})
    end.

%% 申请加入公会
apply_join_guild(RoleId, RoleInfoMap, GuildId) ->
    gen_server:cast(?GUILD_PID, {'apply_join_guild', RoleId, RoleInfoMap, GuildId}).

%%团长回来
chief_reback(GuildId)->
    gen_server:cast(?GUILD_PID, {'chief_reback',GuildId}).

%% 批量申请
apply_join_guild_multi(RoleId, RoleInfoMap) ->
    gen_server:cast(?GUILD_PID, {'apply_join_guild_multi', RoleId, RoleInfoMap}).

%% 申请帮派职位
apply_guild_position(RoleId, Position, GuildId) ->
    gen_server:cast(?GUILD_PID, {apply_guild_position, RoleId, Position, GuildId}).

%% 获取公会信息界面-基础信息
send_guild_info(RoleId, GuildId, SalaryStatus) ->
    gen_server:cast(?GUILD_PID, {'send_guild_info', RoleId, GuildId, SalaryStatus}).

%% 获取公会信息界面-成员列表
send_guild_member_short_info(RoleId, GuildId, PageSize, PageNo, SortType, SortFlag, MemberType, SpecialType) ->
    gen_server:cast(?GUILD_PID, {'send_guild_member_short_info', RoleId, GuildId, PageSize, PageNo, SortType, SortFlag, MemberType, SpecialType}).

% %% 获取成员列表界面
% send_guild_member_info(RoleId, Figure, GuildId, PageSize, PageNo, SortType, SortFlag, MemberType, SpecialType) ->
%     gen_server:cast(?GUILD_PID, {'send_guild_member_info', RoleId, Figure, GuildId, PageSize, PageNo, SortType, SortFlag, MemberType, SpecialType}).

%% 退出公会
quit_guild(RoleId) ->
    gen_server:cast(?GUILD_PID, {'quit_guild', RoleId}).

%% 申请列表
send_guild_apply_list(RoleId, GuildId) ->
    gen_server:cast(?GUILD_PID, {'send_guild_apply_list', RoleId, GuildId}).

%% 审批公会请求
approve_guild_apply(RoleId, ApplyRoleId, ApplyRoleInfoMap, Type) ->
    gen_server:cast(?GUILD_PID, {'approve_guild_apply', RoleId, ApplyRoleId, ApplyRoleInfoMap, Type}).

%% 审批设置界面
send_approve_setting_view(RoleId, GuildId) ->
    gen_server:cast(?GUILD_PID, {'send_approve_setting_view', RoleId, GuildId}).

%% 设置审批
setting_approve(RoleId, ApproveType, AutoApproveLv, AutoApprovePower) ->
    gen_server:cast(?GUILD_PID, {'setting_approve', RoleId, ApproveType, AutoApproveLv, AutoApprovePower}).

%% 编辑宣言
modify_tenet(RoleId, Tenet) ->
    gen_server:cast(?GUILD_PID, {'modify_tenet', RoleId, Tenet}).

%% 公告编辑界面
send_announce_view_info(Sid, GuildId) ->
    gen_server:cast(?GUILD_PID, {'send_announce_view_info', Sid, GuildId}).

%% 编辑公告
modify_announce(RoleId, Announce, Type) ->
    gen_server:cast(?GUILD_PID, {'modify_announce', RoleId, Announce, Type}).

%% 职位管理界面
send_position_manage_view(RoleId, GuildId, PageSize, PageNo) ->
    gen_server:cast(?GUILD_PID, {'send_position_manage_view', RoleId, GuildId, PageSize, PageNo}).

%% 任命职位
appoint_position(RoleId, AppointeeId, Position) ->
    gen_server:cast(?GUILD_PID, {'appoint_position', RoleId, AppointeeId, Position}).

%% 踢出公会
kick_out_guild(RoleId, LeaveId) ->
    gen_server:cast(?GUILD_PID, {'kick_out_guild', RoleId, LeaveId}).

%% 重新命名职位名称
rename_position(RoleId, Position, PositionName) ->
    gen_server:cast(?GUILD_PID, {'rename_position', RoleId, Position, PositionName}).

%% 职位权限界面
send_position_permission_list(RoleId, Position) ->
    gen_server:cast(?GUILD_PID, {'send_position_permission_list', RoleId, Position}).

%% 取消申请加入公会
cancel_apply(RoleId, GuildId) ->
    gen_server:cast(?GUILD_PID, {'cancel_apply', RoleId, GuildId}).

%% 发送职位数量列表
send_position_num_list(RoleId, GuildId) ->
    gen_server:cast(?GUILD_PID, {'send_position_num_list', RoleId, GuildId}).

%% 修改职位权限
modify_position_permission(RoleId, Position, PermissionType, IsAllow) ->
    gen_server:cast(?GUILD_PID, {'modify_position_permission', RoleId, Position, PermissionType, IsAllow}).

%% 清空申请列表
clean_all_guild_apply_on_this_guild(RoleId) ->
    gen_server:cast(?GUILD_PID, {'clean_all_guild_apply_on_this_guild', RoleId}).

%% 全部批准入会
approve_all_guild_apply_on_this_guild(RoleId) ->
    gen_server:cast(?GUILD_PID, {'approve_all_guild_apply_on_this_guild', RoleId}).

%% 玩家拥有的权限列表
send_role_permission_list(RoleId) ->
    gen_server:cast(?GUILD_PID, {'send_role_permission_list', RoleId}).

% %% 发送公会资金信息
% send_gfunds_info(RoleId, GuildId) ->
%     gen_server:cast(?GUILD_PID, {'send_gfunds_info', RoleId, GuildId}).

%% 增加资金
%% @param RoleId 玩家id(可以为空)
%% @param Type 产出类型 见 data_goods:get_produce_type/1
add_gfunds(RoleId, GuildId, AddGfunds, Type) ->
    gen_server:cast(?GUILD_PID, {'add_gfunds', RoleId, GuildId, AddGfunds, Type}).

%% 增加公会成长值 20200312 废弃
%% @param RoleId 玩家id(可以为空)
add_growth(_RoleId, _GuildId, _AddGrowth, _ProduceType, _Extra) -> ok.
    % gen_server:cast(?GUILD_PID, {'add_growth', RoleId, GuildId, AddGrowth, ProduceType, Extra}).

%% 更新公会成员属性
update_guild_member_attr(RoleId, AttrList) ->
    gen_server:cast(?GUILD_PID, {'update_guild_member_attr', RoleId, AttrList}).

%% 所有职位权限的信息
send_all_position_permission_list(RoleId) ->
    gen_server:cast(?GUILD_PID, {'send_all_position_permission_list', RoleId}).

%% 自动任命为会长
auto_appoint_to_chief(DelaySec) ->
    gen_server:cast(?GUILD_PID, {'auto_appoint_to_chief', DelaySec}).

%% 自动任命为会长
auto_appoint_to_chief_by_guild_id(GuildId) ->
    gen_server:cast(?GUILD_PID, {'auto_appoint_to_chief_by_guild_id', GuildId}).

% %% 手动解散公会
% do_disband_guild(GuildId, RoleId) ->
%     gen_server:cast(?GUILD_PID, {'do_disband_guild', GuildId, RoleId}).

%% 解散公会
disband_guild(DisbandType, GuildId) ->
    gen_server:cast(?GUILD_PID, {'disband_guild', DisbandType, GuildId}).

%% 升级公会
upgrade_building(RoleId, BuildingType) ->
    gen_server:cast(?GUILD_PID, {'upgrade_building', RoleId, BuildingType}).

%% 检测是否需要解散帮派
check_auto_disband_guild(IsInGWar,GuildId) ->
    gen_server:cast(?GUILD_PID, {'check_auto_disband_guild', IsInGWar,GuildId}).

%%获取社团本周劳务
get_guild_week_labor(GuildId,RoleID,Stage)->
    gen_server:cast(?GUILD_PID, {'get_guild_week_labor', GuildId,RoleID,Stage}).

%% @doc 定制活动定时奖励发放
%% @param ModuleSub:定制活动ID
%% @param AcSub:定制活动子项
%% @param GuildList:[{guild_id, rank}|...]
%% @return Map:{rank=>[{role_id, job, create_time}|...]}
%% job:帮会最高职务。
%% enter_time:入帮时间
ac_custom_timer_reward(ModuleSub, AcSub, GuildList) ->
    gen_server:cast(?GUILD_PID, {'ac_custom_timer_reward', ModuleSub, AcSub, GuildList}).

%% 更新玩家战力
update_guild_member_power(RoleId, CombatPower) ->
    gen_server:cast(?GUILD_PID, {'update_guild_member_power', RoleId, CombatPower}).

%% cast到副本
apply_cast(Moudle, Method, Args) ->
    gen_server:cast(?GUILD_PID, {'apply_cast', Moudle, Method, Args}).

%% 指定帮派id的成员cast方式执行MFA
%% @param  MemberType 0: 所有成员 1: 在线成员 2: 离线成员
apply_cast_guild_member(GuildId, MemberType, Module, Method, Args) ->
    gen_server:cast(?GUILD_PID, {'apply_cast_guild_member', GuildId, MemberType, Module, Method, Args}).

%% 改名检查
check_rename_guild(GuildId, RoleId, OpTy, GuildName, Flag) ->
    gen_server:cast(?GUILD_PID, {check_rename_guild, GuildId, RoleId, OpTy, GuildName, Flag}).

%% 是否有免费改名次数
check_rename_guild_free(GuildId, RoleId) ->
    gen_server:cast(?GUILD_PID, {check_rename_guild_free, GuildId, RoleId}).

%% 帮派改名
rename_guild(GuildId, RoleId, RenameArgs) ->
    gen_server:cast(?GUILD_PID, {rename_guild,GuildId, RoleId, RenameArgs}).

%% ====================
%% 接口
%% ====================

%% 发送公会邮件
send_guild_mail_by_role_id(RoleId, Title, Content, CmAttachment, ExcludeIdList) ->
    gen_server:cast(?GUILD_PID, {'send_guild_mail_by_role_id', RoleId, Title, Content, CmAttachment, ExcludeIdList}).

%% 发送公会邮件
send_guild_mail_by_guild_id(GuildId, Title, Content, CmAttachment, ExcludeIdList) ->
    gen_server:cast(?GUILD_PID, {'send_guild_mail_by_guild_id', GuildId, Title, Content, CmAttachment, ExcludeIdList}).

%% 小红点
send_red_point(RoleId, Type) ->
    gen_server:cast(?GUILD_PID, {'send_red_point', RoleId, Type}).

%% 获得公会成员的最高等级
get_guild_member_max_lv(RoleId) ->
    gen_server:call(?GUILD_PID, {'get_guild_member_max_lv', RoleId}).

%% 扣除公会资金
cost_gfunds(RoleId, CostGfunds, Type) ->
    gen_server:call(?GUILD_PID, {'cost_gfunds', RoleId, CostGfunds, Type}).

%% 根据公会id获得公会领袖信息
get_guild_chief_info_by_id(GuildId) ->
    case catch apply_call(lib_guild_data, get_guild_chief_info_by_id, [GuildId], 5000) of
        {ChiefId, ChiefName} -> {ChiefId, ChiefName};
        _ -> {0, ""}
    end.

%% 获取所有公会
get_all_guild()->
    gen_server:call(?GUILD_PID, {'get_all_guild'}).

get_all_guild_ids(From) ->
    gen_server:cast(?GUILD_PID, {'get_all_guild_ids', From}).

%% 获得公会成员id列表
get_guild_member_id_list(GuildId) ->
    gen_server:call(?GUILD_PID, {get_guild_member_id, GuildId}).

%% 获取帮派某项数据
get_guild_data(GuildId, ElemIndex)->
    gen_server:call(?GUILD_PID, {guild_data, GuildId, ElemIndex}).

%% 清理
day_clear(Clock, DelaySec) ->
    RandTime = urand:rand(1, 1000),
    spawn(fun() -> timer:sleep(RandTime), gen_server:cast(?GUILD_PID, {'day_clear', Clock, DelaySec}) end).

%% 更新公会的创建时间
update_guild_create_time(GuildId, CreateTime) ->
    gen_server:cast(?GUILD_PID, {'update_guild_create_time', GuildId, CreateTime}).

%% 获取公会人数
get_guild_member_num(GuildId) ->
    gen_server:call(?GUILD_PID, {'get_guild_member_num', GuildId}).

%% 获取公会人数列表[{guild_id,member_num}]
get_guild_member_num_list() ->
    gen_server:call(?GUILD_PID, {'get_guild_member_num_list'}).

%% 计算公会战力
count_guild_combat_power() ->
    gen_server:cast(?GUILD_PID, {'count_guild_combat_power'}).

%% 公会金库界面
send_king_donate(RoleId,GuildId,Count1,Count2) ->
    gen_server:cast(?GUILD_PID, {'send_king_donate', RoleId, GuildId, Count1,Count2}).

%% 增加贡献
add_donate(RoleId, CfgId, Num, LogNum) ->
    gen_server:cast(?GUILD_PID, {'add_donate', RoleId, CfgId, Num, LogNum}).

%% 外部接口调用
add_donate_api(RoleId, Num) ->
    gen_server:cast(?GUILD_PID, {'add_donate_api', RoleId, Num}).

cost_donate_api(RoleId, ConsumeType, Num, Other) ->
    gen_server:cast(?GUILD_PID, {'cost_donate_api', RoleId, ConsumeType, Num, Other}).

%% 获取公会活跃度
get_guild_liveness(GuildId, Time) ->
    gen_server:call(?GUILD_PID, {'get_guild_liveness', GuildId}, Time).

%% 获取公会活跃度和公会人数
get_liveness_and_guild_num(GuildId) ->
    gen_server:call(?GUILD_PID, {'get_liveness_and_guild_num', GuildId}, 2000).

%% 增加活跃度
add_liveness(RoleId, AddLiveness, ExtraLiveness) ->
    gen_server:cast(?GUILD_PID, {'add_liveness', RoleId, AddLiveness, ExtraLiveness}).
add_liveness(RoleId, AddLiveness) ->
    gen_server:cast(?GUILD_PID, {'add_liveness', RoleId, AddLiveness, 0}).

update_guild_labor(GuildId,RoleID,Name,Total,Add,Type,Tid)->
    gen_server:cast(?GUILD_PID, {'update_guild_labor', GuildId,RoleID,Name,Total,Add,Type,Tid}).

get_guild_daily_log(GuildId, RoleID)->
    gen_server:cast(?GUILD_PID,{get_guild_daily_log,GuildId, RoleID}).

%% ================ 公会仓库 =====================

send_guild_depot_info(RoleId, GuildId, DepotScore) ->
    gen_server:cast(?GUILD_PID, {'send_guild_depot_info', RoleId, GuildId, DepotScore}).

add_to_depot(RoleId, RoleName, GoodsInfoList, DepotScore) ->
    gen_server:cast(?GUILD_PID, {'add_to_depot', RoleId, RoleName, GoodsInfoList, DepotScore}).

exchange_depot_goods(RoleId, RoleName, DepotGoodsId, GoodsTypeId, Num, DepotScore, OneNum, NeedScore) ->
    gen_server:cast(?GUILD_PID, {'exchange_depot_goods', RoleId, RoleName, DepotGoodsId, GoodsTypeId, Num, DepotScore, OneNum, NeedScore}).

destory_depot_goods(RoleId, RoleName, DepotGoodsIds) ->
    gen_server:cast(?GUILD_PID, {'destory_depot_goods', RoleId, RoleName, DepotGoodsIds}).

send_guild_depot(RoleId, GuildId, GoodId) ->
    gen_server:cast(?GUILD_PID, {'send_guild_depot', RoleId, GuildId, GoodId}).

%% ================ 公会仓库 =====================

%% ================ 公会技能 =====================

send_guild_skill_list(RoleId, GuildId, PlayerGSkillMap, SkillType) ->
    gen_server:cast(?GUILD_PID, {'send_guild_skill_list', RoleId, GuildId, PlayerGSkillMap, SkillType}).

research_skill(RoleId, SkillId) ->
    gen_server:cast(?GUILD_PID, {'research_skill', RoleId, SkillId}).

%% Call操作 避免异步造成玩家身上的技能数据不同步
learn_skill(RoleId, SkillId, ExtraData) ->
    gen_server:call(?GUILD_PID, {'learn_skill', RoleId, SkillId, ExtraData}, 500).

%% ================ 公会技能 =====================

%% ================ 公会战 =====================

sync_guild_list_to_gwar() ->
    gen_server:cast(?GUILD_PID, {'sync_guild_list_to_gwar'}).

update_guild_division(DivisionIndexMap) ->
    gen_server:cast(?GUILD_PID, {'update_guild_division', DivisionIndexMap}).

%% ================ 公会战 =====================

%% ================ 公会榜单结算逻辑 =====================

send_guild_rank_reward(PreFirGuildId, CurFirGuildId, DesignationId) ->
    gen_server:cast(?GUILD_PID, {'send_guild_rank_reward', PreFirGuildId, CurFirGuildId, DesignationId}).

%% ================ 公会榜单结算逻辑 =====================

send_chief_figure_info(Node, RoleId, GuildId, ArgsMap) ->
    gen_server:cast(?GUILD_PID, {'send_chief_figure_info', Node, RoleId, GuildId, ArgsMap}).

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

%% GM编辑公告
modify_announce_by_gm(GuildId, Announce) ->
    gen_server:call(?GUILD_PID, {'modify_announce_by_gm', GuildId, Announce}).

%% GM改公会名字
modify_name_by_gm(GuildId, Name) ->
    gen_server:call(?GUILD_PID, {'modify_name_by_gm', GuildId, Name}).

%% GM解散公会
disband_guild_by_gm(GuildId) ->
    gen_server:call(?GUILD_PID, {'disband_guild', ?DISBAND_REASON_GM, GuildId}).

%% GM增加上周公会活跃度
gm_add_last_liveness(RoleId, AddLiveness) ->
    gen_server:cast(?GUILD_PID, {'gm_add_last_liveness',RoleId, AddLiveness}).

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

start_link() ->
    gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).

init([]) ->
    process_flag(trap_exit, true),
    lib_guild_mod:init(),
    % erlang:send_after(3*1000, self(), {sync_guild_msg}),
    %% 等待排行榜初始化之后再同步数据
    erlang:send_after(10*1000, self(), {sync_guild_create_time}),
    init_guild_scene(),
    {ok, []}.

handle_call(Request, From, State) ->
    case catch mod_guild_call:handle_call(Request, From, State) of
        {reply, Reply, NewState} ->
            {reply, Reply, NewState};
        Reason ->
            ?ERR("mod_guild_call error: ~p, Reason=~p~n",[Request, Reason]),
            {reply, error, State}
    end.

handle_cast(Msg, State) ->
    case catch mod_guild_cast:handle_cast(Msg, State)of
        {noreply, NewState} ->
            {noreply, NewState};
        Reason ->
            ?ERR("mod_guild_cast error: ~p, Reason:=~p~n",[Msg, Reason]),
            {noreply, State}
    end.

handle_info(Info, State) ->
    case catch mod_guild_info:handle_info(Info, State) of
        {noreply, NewState} ->
            {noreply, NewState};
        Reason ->
            ?ERR("mod_guild_info error: ~p, Reason:=~p~n",[Info, Reason]),
            {noreply, State}
    end.

terminate(_Reason, _State) ->
    ok.

code_change(_OldVsn, State, _Extra) ->
    {ok, State}.

%%主动启动驻地场景进程
init_guild_scene()->
    DScene = data_guild:get(guild_scene),
    NScene = data_guild:get(guild_scene_night),
    List = lists:seq(0,?GUILD_REM-1),
    L1 = [{DScene,N}||N<-List],
    L2 = [{NScene,N}||N<-List],
    L  = L1++L2,
    spawn(fun()->init_guild_scene(L) end).

init_guild_scene([])->
    ok;
init_guild_scene([{Scene,Pool}|T])->
    mod_scene_agent:get_scene_pid(Scene,Pool),
    timer:sleep(2000),
    init_guild_scene(T).