%% ---------------------------------------------------------------------------
%% @doc lib_guild_tribe_mod.erl
%% @author  zmh
%% @since  2020-02-25
%% @deprecated 社团驻地
%% ---------------------------------------------------------------------------
-module(lib_guild_tribe_mod).
-export([]).
-compile(export_all).

-include("guild.hrl").
-include("sql_guild.hrl").
-include("errcode.hrl").
-include("common.hrl").
-include("figure.hrl").
-include("def_fun.hrl").
-include("def_module.hrl").
-include("def_event.hrl").
-include("def_goods.hrl").
-include("rec_event.hrl").
-include("server.hrl").
-include("predefine.hrl").
-include("scene.hrl").
-include("guild_tribe.hrl").
-include("guild_labor.hrl").


handle_event(Status,#event_callback{type_id = ?EVENT_LV_UP})->
    #player_status{id=RoleID,figure=#figure{lv=RLv},guild=#status_guild{id=GuildID}}=Status,
    GuildID>0 andalso mod_guild_tribe_mgr:role_lv_up(GuildID,RoleID,RLv),
    {ok, Status};
handle_event(Status,#event_callback{type_id = ?EVENT_DISCONNECT})->
    #player_status{id=RoleID,guild=#status_guild{id=GuildID}}=Status,
    GuildID>0 andalso mod_guild_tribe_mgr:role_logout(GuildID,RoleID),
    {ok, Status};
handle_event(Status, _R) ->
    {ok, Status}.


check({check_guilded,GuildID})->
    case GuildID>0 of
        true->
            true;
        _->
            {false,?ERRCODE(err400_not_on_guild_to_station)}
    end;
check({check_repeate_enter,Scene})->
	InGuild = lib_guild_api:check_in_guild_scene(Scene),
	case InGuild of
		true->
			{false,?ERRCODE(err400_already_in_tribe)};
		_->
			true
	end;
check({check_enter_lv,Lv})->
	NeedLv = data_guild:get(grade_limit),
	case Lv>= NeedLv of
		true->
			true;
		_->
			{false,?ERRCODE(err400_lv_unreachable_enter)}
	end;
check({check_transferable,Status})->
	case lib_scene:is_transferable(Status) of
        {true, _ErrCode} ->
           true;
        {false, ErrCode} ->
            {false,ErrCode}
    end.


%%白夜转换
guild_scene_exchange(DayNight)->
    {OScene,NScene} = case DayNight of
        0->
            {data_guild:get(guild_scene_night),data_guild:get(guild_scene)};
        _->
            {data_guild:get(guild_scene),data_guild:get(guild_scene_night)}
    end,
    GuildMap = lib_guild_data:get_guild_map(),
    GuildList = lib_guild_mod:get_guild_list(GuildMap, 0),
    guild_scene_exchange(GuildList,OScene,NScene).

guild_scene_exchange([],_OScene,_NScene)->
    ok;
guild_scene_exchange([H|T],OScene,NScene)->
    #guild{id=GuildID}=H,
    Pool = ?GUILD_REM_POOL(GuildID),
    mod_scene_agent:apply_cast(OScene,Pool,lib_scene_agent,player_apply_cast,[GuildID, ?APPLY_CAST_SAVE, ?MODULE, player_do_change_scene, [NScene,Pool]]),
    guild_scene_exchange(T,OScene,NScene).

player_do_change_scene(Status,Scene,Pool)->
    #player_status{
        x=X,
        y=Y,
        copy_id=CopyID,
        id=RoleID
    }=Status,
    %% 切换场景
    lib_scene:change_player_scene(RoleID, Scene, Pool, CopyID, X,Y, false, []),
	Status.
%%活动开启
guild_act_start(Scene,Act,SubAct)->
	GuildMap = lib_guild_data:get_guild_map(),
    GuildList = lib_guild_mod:get_guild_list(GuildMap, 0),
    guild_act_start(Scene,GuildList,Act,SubAct).

guild_act_start(_,[],_Act,_SubAct)->
    ok;
guild_act_start(SceneID,[H|T],Act,SubAct)->
    #guild{id=GuildID}=H,
    Pool = ?GUILD_REM_POOL(GuildID),
    mod_scene_agent:apply_cast(SceneID,Pool,lib_scene_agent,player_apply_cast,[GuildID, ?APPLY_CAST_SAVE, ?MODULE, player_do_enter_logic, [Act,SubAct]]),
    guild_act_start(SceneID,T,Act,SubAct).

player_do_enter_logic(Status,Act,SubAct) ->
    #player_status{id = RoleID, guild = GuildStatus,figure=#figure{lv=Lv}} = Status,
    #status_guild{id = GuildId, name = GName} = GuildStatus,
    if
        GuildId>0 ->
            mod_guild_tribe_mgr:enter_scene_logic(RoleID,GuildId,GName,Lv,Act,SubAct),
            if
                SubAct == 7 ->
                    case lib_daily:get_count(RoleID, ?MOD_GUILD, 4) of
                        Value when is_integer(Value), Value > 0 -> ignore;
                        _ ->
                            lib_daily:increment(RoleID, ?MOD_GUILD, 4),
                            lib_achievement_api:guild_feast_event(Status, 1)
                    end,
                    {ok, NStatus} = lib_seven_days_goal:do_finish_task(Status, ?MOD_GUILD, 7),
                    {ok, Status1} = lib_guild_labor:task_active(NStatus, ?GTASK_TYPE_PARTY, 1);
                true ->
                    Status1 = Status
            end;
        true -> Status1 = Status
    end,
    Status1.

add_role(GRoles,RData)->
     #tribe_role{
        id = RoleID,
        lv = Lv
    } = RData,
    OData   = lists:keyfind(RoleID,#tribe_role.id,GRoles),
    case is_record(OData,tribe_role) of
        true->
            NowTime = utime:unixtime(),
            lists:keystore(RoleID,#tribe_role.id,GRoles,OData#tribe_role{lv=Lv,online=1,in_scene=1,enter_time=NowTime});
        _->
            lists:keystore(RoleID,#tribe_role.id,GRoles,RData)
    end.


update_role(GRoles,RData)->
    #tribe_role{
        id = RoleID
    } = RData,
    NGRoles = lists:keystore(RoleID,#tribe_role.id,GRoles,RData),
    NGRoles.


add_exp([],_Now,_Num, GuildRoles)->
    GuildRoles;
add_exp([H|T],Now,Num, GuildRoles)->
    #tribe_role{
        id = RoleID,
        online = IsOn,
        in_scene = InScene,
        last_time = LastTime
    } = H,
    case IsOn > 0 of
        true->
            lib_player:apply_cast(RoleID, ?APPLY_CAST_STATUS, ?MODULE, player_add_exp, [Now,Num]),
            NewGuildRoles =
            case InScene of
                1 ->
                    GapTime = case data_guild:get(click_add_exp) of
                                  TTime when is_integer(TTime) -> TTime;
                                  _ -> 0
                              end,
                    NewTribeRole = H#tribe_role{last_time = LastTime + GapTime},
                    lists:keystore(RoleID, #tribe_role.id, GuildRoles, NewTribeRole);
                _ ->
                    GuildRoles
            end,
            add_exp(T,Now,Num, NewGuildRoles);
        _ ->
            add_exp(T,Now,Num, GuildRoles)
    end.

player_add_exp(Status,Now,Num)->
    #player_status{
        id = RoleID,
        guild = GuildStatus,
        figure=#figure{lv=Lv}
    }=Status,
    #status_guild{id = GuildId, position=Pos} = GuildStatus,
    ExpValue0 = data_exp_base:get(Lv),
    LvExtra = data_award_exp:get_exp_extra(?MOD_GUILD,7,Lv),
    Extra   = data_guild:get(dance_extra),
    Extra0  = data_guild:get_num_radio(Num),
    case custom_unite_buff:check_buff(Status,extra_exp) of
        {ok,Extra1}->
            skip;
        _->
            Extra1 = 0
    end,
    ExpValue = case Pos>0 of
        true->
            round(ExpValue0*LvExtra/10000*(1+Extra/10000+Extra0/10000+Extra1/100));
        _->
            round(ExpValue0*LvExtra/10000*(1+Extra0/10000+Extra1/100))
    end,
    {ok,Bin} = pt_400:write(40059,[ExpValue,Now]),
    lib_server_send:send_to_uid(RoleID,Bin),
    Add = [{?TYPE_EXP,?GOODS_ID_EXP,ExpValue}],
    NewStatus = lib_goods_api:send_reward(Status, Add, guild_fire),
    spawn(fun()->timer:sleep(urand:rand(1000,2500)),mod_guild_tribe_mgr:add_click_exp(GuildId,RoleID,ExpValue) end),
    NewStatus.


%%参与人数更新
update_party_num(GuildID,Num)->
    Guild = lib_guild_data:get_guild_by_id(GuildID),
    case is_record(Guild, guild) of
        true->
            #guild{fire_num=CurNum}=Guild,
            case Num>CurNum of
                true->
                    NewGuild = Guild#guild{fire_num=Num},
                    lib_guild_data:db_guild_update_party_num(GuildID,Num),
                    lib_guild_data:update_guild(NewGuild);
                _->
                    ok
            end;
        _->
            ok
    end.

update_guild_assist(GuildID)->
    %% 增加周协助次数
    Guild = lib_guild_data:get_guild_by_id(GuildID),
    case is_record(Guild, guild) of
        true->
            #guild{fire_num=PartyN,war_win=WarWin,assist = Assist,last_renew=Time} = Guild,
            AssistN = Assist + 1,
            NewGuild = Guild#guild{assist = AssistN},
            lib_guild_data:db_guild_update_badge_need(GuildID,PartyN,AssistN,WarWin,Time),
            lib_guild_data:update_guild(NewGuild);
        _->
            ok
    end.

%% ------------------------------------------------------------------
%% @doc 玩法过程中
%% ------------------------------------------------------------------
change_scene_callback(Player, _OldSceneInfo, OldSceneData, NewSceneData) ->
    #ets_scene{id=OldScene}=OldSceneData,
    #ets_scene{id=NewScene}=NewSceneData,
    DScene = data_guild:get(guild_scene),
    NScene = data_guild:get(guild_scene_night),
    OldIs  = lists:member(OldScene,[DScene,NScene]),
    NewIs  = lists:member(NewScene,[DScene,NScene]),
    NewPlayer = change_scene(Player,OldIs,NewIs),
    {ok,NewPlayer}.

%%离开驻地
change_scene(Player,true,false)->
    #player_status{id=RoleID,guild = GuildStatus}=Player,
     #status_guild{id = GuildID} = GuildStatus,
    lib_player_event:async_remove_listener(RoleID,?EVENT_DISCONNECT, ?MODULE, handle_event),
    lib_player_event:async_remove_listener(RoleID,?EVENT_LV_UP,?MODULE, handle_event),
    mod_guild_tribe_mgr:role_logout(GuildID,RoleID),
    Player;
%%白夜转换
change_scene(Player,true,true)->
    Player;
%%进入驻地
change_scene(Player,false,true)->
    #player_status{id=RoleID,guild = GuildStatus,figure=Figure}=Player,
    #status_guild{id = GuildId, name = GName} = GuildStatus,
    #figure{lv=Rlv}=Figure,
    lib_player_event:async_add_listener(RoleID,?EVENT_DISCONNECT, ?MODULE, handle_event, []),
    lib_player_event:async_add_listener(RoleID,?EVENT_LV_UP, ?MODULE, handle_event, []),
    mod_guild_tribe_mgr:enter_scene_logic(RoleID,GuildId,GName,Rlv),
    Player;
change_scene(Player,_,_)->
    Player.

%%活动触发
trigger_act_event(RoleID, Act, SubAct)->
    case {Act, SubAct} of
        {?MOD_GUILD, 7} ->
            lib_player:apply_cast(RoleID, ?APPLY_CAST_SAVE, ?MODULE, trigger_guild_feast_event, [SubAct]);
        _ -> ignore
    end,
    case Act of
        ?MOD_GUILD_BOSS ->
            lib_player:apply_cast(RoleID, ?APPLY_CAST_SAVE, ?MODULE, trigger_act_event_on_player, [SubAct]);
        _->
            lib_activitycalen_api:role_success_end_activity(RoleID, Act, SubAct),
            ignore
    end.

trigger_guild_feast_event(Player, SubAct) ->
    #player_status{id = RoleId} = Player,
    case SubAct of
        7 ->
            case lib_daily:get_count(RoleId, ?MOD_GUILD, 4) of
                Value when is_integer(Value), Value > 0 -> ignore;
                _ ->
                    lib_daily:increment(RoleId, ?MOD_GUILD, 4),
                    lib_achievement_api:guild_feast_event(Player, 1)
            end,
            NewPlayer = lib_activity_reserve:enter_act(Player, {?MOD_GUILD, SubAct, 1});
        _ ->
            NewPlayer = Player
    end,
    {ok,NewPlayer}.

trigger_act_event_on_player(#player_status{id = RoleId, guild = StatusGuild} = Player, SubAct) ->
    case StatusGuild#status_guild.position == ?POS_CHIEF of
        true ->
            lib_guild_race_rank_task:trigger_guild_boss_task(StatusGuild#status_guild.id, 1);
        _ ->
            ignore
    end,
    case SubAct of
        1 ->
            case lib_daily:get_count(RoleId, ?MOD_GUILD_BOSS, SubAct, 1) of
                Count when is_integer(Count), Count >= 1 -> ignore;
                _ ->
                    %% 第一次进入
                    lib_activitycalen_api:role_success_end_activity(RoleId, ?MOD_GUILD_BOSS, 1),
                    lib_achievement_api:guild_boss_event(Player, 1),
                    lib_daily:increment(RoleId, ?MOD_GUILD_BOSS, SubAct, 1)
            end,
            Player1 = Player, % lib_child_task:finish_guild_noon_boss(Player),
            {ok, Player2} = lib_guild_labor:task_active(Player1, ?GTASK_TYPE_NOON, 1),
            {ok, Player3} = custom_act_contract:do_trigger_contract_task(Player2, guildboss, 1, [1]),
            Player4 = lib_activity_reserve:enter_act(Player3, {?MOD_GUILD_BOSS, 1, SubAct}),
            {ok, Player4};
        _ ->
            case lib_daily:get_count(RoleId, ?MOD_GUILD_BOSS, SubAct, 1) of
                Count when is_integer(Count), Count >= 1 -> ignore;
                _ ->
                    %% 第一次进入
                    lib_activitycalen_api:role_success_end_activity(RoleId, ?MOD_GUILD_BOSS, 1),
                    lib_achievement_api:guild_boss_event(Player, 1),
                    lib_daily:increment(RoleId, ?MOD_GUILD_BOSS, SubAct, 1)
            end,
            Player1 = Player, % lib_child_task:finish_guild_night_boss(Player),
            {ok, Player2} = lib_guild_labor:task_active(Player1, ?GTASK_TYPE_NIGHT, 1),
            {ok, Player3} = custom_act_contract:do_trigger_contract_task(Player2, guildboss, 1, [1]),
            Player4 = lib_activity_reserve:enter_act(Player3, {?MOD_GUILD_BOSS, 1, SubAct}),
            {ok, Player4}
    end.

%%获取开放中的活动
calc_open_act(Type,ActList)->
    calc_open_act(Type,ActList,[]).
calc_open_act(_,[],Opens)->
    Opens;
calc_open_act(mod,[{Act,Mod}|T],Opens)->
    case lib_activitycalen_api:check_ac_start(Act,Mod) of
        true->
            calc_open_act(mod,T,[{Act,Mod}|Opens]);
        _->
            calc_open_act(mod,T,Opens)
    end;
calc_open_act(sub,[{Act,SubMod,SubAct}|T],Opens)->
    case lib_activitycalen_api:check_mod_ac_start(Act,SubMod,SubAct) of
        true->
            calc_open_act(sub,T,[{Act,SubAct}|Opens]);
        _->
            calc_open_act(sub,T,Opens)
    end.
