%%-----------------------------------------------------------------------------
%% module  :       lib_guild_labor
%% @author  :      zmh
%% Created :       20191207
%% description:    社团活跃  加经验值 升级
%%-----------------------------------------------------------------------------
-module(lib_guild_labor).

-include("server.hrl").
-include("errcode.hrl").
-include("predefine.hrl").
-include("common.hrl").
-include("figure.hrl").
-include("guild.hrl").
-include("def_module.hrl").
-include("def_event.hrl").
-include("def_goods.hrl").
-include("guild_labor.hrl").
-include("goods.hrl").

-compile(export_all).

-export([
    login/1
    ,task_active/2
    ,task_active/3
    ,goods_add/2
    ,fetch_task_award/2
    % active_guard/0,
    % active_guard/1,
    % calc_money/3,
    % finish_dungeon/2
    ]).


%%登录
login(RoleID)->
    Sql = io_lib:format(?SQL_GUILD_LABOR_GET, [RoleID]),
    GuildTasks0 = db:get_all(Sql),
    GuildTasks1 = case GuildTasks0 of
        [[_,_,_,Time]|_T]->
            case utime:is_logic_same_day(Time) of
                true->
                    trans_guild_task(GuildTasks0);
                _->
                    []
            end;
        _->
            []
    end,
    GuildTasks  = fix_guild_task(GuildTasks1),
    GuildTasks.

%%领取奖励
fetch_task_award(TaskId,Status)->
     #player_status{
        id = RoleID,
        guild_task = GuildTasks,
        guild=#status_guild{id=GuildId},
        figure = #figure{name=Name}
    }=Status,
    case lists:keytake(TaskId,#guild_task.id,GuildTasks) of
        {value,#guild_task{state=1}=Task,ReGuildTasks}->
            #guild_task_base{awards=Awards,add=Add,content={Type,_,Max}}=data_guild_labor:get_guild_task(TaskId),
            NewAdd = Add*Max,
            lib_daily:plus_count(RoleID, ?MOD_GUILD_LABOR, 2,NewAdd),
            mod_guild:update_guild_labor(GuildId,RoleID,Name,NewAdd,NewAdd,Type,TaskId),
            Produce = #produce{type = guild_labor, reward=Awards},
            lib_goods_api:send_reward_with_mail(RoleID, Produce, ?MOD_CROSS_LEGION),

            {ok,Bin} = pt_404:write(40401,[TaskId,Type,Max,2]),
            lib_server_send:send_to_uid(RoleID,Bin),
            save_guild_task(RoleID,Task#guild_task{state=2}),
            NewGuildTasks = [Task#guild_task{state=2}|ReGuildTasks],
            {ok,Status#player_status{guild_task=NewGuildTasks}};
        {value,#guild_task{state=0},_ReGuildTasks}->
            {false,?ERRCODE(err114_need_finish_task)};
        {value,#guild_task{state=2},_ReGuildTasks}->
            {false,?ERRCODE(err603_cant_fetch_again)};
        _->
            {false,?ERRCODE(missing_config)}
    end.


%%保存任务
save_guild_task(RoleID,Task)->
    #guild_task{id=Tid,content=Content,state=State,time=Time}=Task,
    SQL = io_lib:format(?SQL_GUILD_LABOR_INSERT, [RoleID,Tid,util:term_to_string(Content),State,Time]),
    db:execute(SQL).

trans_guild_task(GuildTasks)->
    trans_guild_task(GuildTasks,[]).
trans_guild_task([],GuildTasks)->
    GuildTasks;
trans_guild_task([[Tid,Content0,State,Time]|T],GuildTasks)->
    case data_guild_labor:get_guild_task(Tid) of
        #guild_task_base{}->
            Content = util:bitstring_to_term(Content0),
            trans_guild_task(T,[#guild_task{id=Tid,content=Content,state=State,time=Time}|GuildTasks]);
        _->
            trans_guild_task(T,GuildTasks)
    end.

%%任务矫正
fix_guild_task(GuildTasks)->
    Now = utime:unixtime(),
    All = data_guild_labor:get_all_task(),
    fix_guild_task(All,Now,GuildTasks).
fix_guild_task([],_,GuildTasks)->
    GuildTasks;
fix_guild_task([H|T],Now,GuildTasks)->
    case lists:keymember(H,#guild_task.id,GuildTasks) of
        true->
            fix_guild_task(T,Now,GuildTasks);
        _->
            case data_guild_labor:get_guild_task(H) of
                #guild_task_base{content=Content}->
                    Task = #guild_task{id=H,content=Content,time=Now},
                    fix_guild_task(T,Now,[Task|GuildTasks]);
                _->
                    fix_guild_task(T,Now,GuildTasks)
            end
    end.

%%4点清理重置任务
daily_timer()->
    db:execute("TRUNCATE TABLE `player_guild_labor`"),
    util:rand_time_to_delay(1000, ?MODULE, refresh_midnight, []).

refresh_midnight()->
    Pids = lib_player:get_online_pids(),
    [refresh_online_state(Pid)|| Pid <- Pids].

refresh_online_state(Pid) ->
    lib_player:apply_cast(Pid, ?APPLY_CAST_SAVE, ?MODULE, midnight_refresh, []).

%%
midnight_refresh(Status) ->
    {ok, Status#player_status{guild_task=fix_guild_task([])}}.

% finish_dungeon(DunType,RoleID)->
%     case DunType of
%         ?DUNGEON_TYPE_GUILD->
%            task_active(RoleID,?GTASK_TYPE_GUILD_TOWER);
%         _->
%             skip
%     end.

%%任务触发
task_active(RoleID,Type) when is_integer(RoleID)->
    task_active(RoleID,Type,1);
task_active(Status,Type)->
    task_active(Status,Type,1).

task_active(RoleID,Type,Num) when is_integer(RoleID) ->
    lib_player:apply_cast(RoleID, ?APPLY_CAST_SAVE, ?MODULE, task_active, [Type,Num]);
task_active(Status,Type,Num)->
    #player_status{
        id=RoleID,
        guild_task=GuildTasks,
        figure = #figure{name=Name},
        guild=#status_guild{id=GuildId}
    }=Status,
    case GuildId>0 of
        true->
            % Total = lib_week:get_count(RoleID,?MOD_GUILD_LABOR,1),
            % RedList = data_guild_task:get_kv(1),
            {NewGuildTasks,_Add} = active_guild_task(GuildId,Name,Type,Num,RoleID,GuildTasks),
            % Moneys = calc_red_money(Total,Total+Add,RedList,[]),
            % #red_envelopes_cfg{min_num=MinNum}=data_red_envelopes:get(23),
            % [begin
            %     Args = [?RED_ENVELOPES_TYPE_LIVENESS,?GUILD_RED_ENVELOPES,GuildId, RoleID,?NO_SEND, Money, MinNum, 23],
            %     Money>0 andalso mod_red_envelopes:add_red_envelopes(Args)
            % end||Money<-Moneys],
            {ok,Status#player_status{guild_task=NewGuildTasks}};
        _->
            {ok,Status}
    end.

active_guild_task(GuildId,Name,Type,Num,RoleID,GuildTasks)->
    active_guild_task(GuildId,Name,Type,Num,RoleID,GuildTasks,[],0).

active_guild_task(_GuildId,_Name,_,_,_RoleID,[],GuildTasks,Add)->
    {GuildTasks,Add};
active_guild_task(GuildId,Name,Type,Num,RoleID,[Task|T],GuildTasks,Add)->
    case Task of
        #guild_task{id=Tid,content={Type,Pro,Max},state=0} when Pro=<Max->
            NewPro = min(Pro+Num,Max),
            Content = {Type,NewPro,Max},
            State = case NewPro>=Max of
                true->
                    1;
                _->
                    0
            end,
            NewTask = Task#guild_task{content=Content,state=State,time=utime:unixtime()},
            save_guild_task(RoleID,NewTask),
            {ok,Bin} = pt_404:write(40401,[Tid,Type,NewPro,State]),
            lib_server_send:send_to_uid(RoleID,Bin),
            active_guild_task(GuildId,Name,Type,Num,RoleID,T,[NewTask|GuildTasks],Add);
        _->
            active_guild_task(GuildId,Name,Type,Num,RoleID,T,[Task|GuildTasks],Add)
    end.

%%道具配置渠道获得
goods_add(Add,Status)->
    #player_status{
        id=RoleID,
        guild = GuildStatus,
        figure=#figure{name=Name}
    }=Status,
    #status_guild{id=GuildId}=GuildStatus,
    % TypeList = [{?MOD_GUILD_LABOR,0,2}],
    Add > 0 andalso begin
        lib_daily:plus_count(RoleID, ?MOD_GUILD_LABOR, 2,Add),
        mod_guild:update_guild_labor(GuildId,RoleID,Name,Add,Add,?GTASK_TYPE_GUILD_GOODS,?GTASK_TYPE_GUILD_GOODS)
    end,
    Status.
