%% ---------------------------------------------------------------------------
%% @doc 每日提升目标
%% @author yanweifan
%% @since  2019-04-24
%% @deprecated 用于定制活动-每日目标
%% ---------------------------------------------------------------------------

-module(lib_daily_power_up).
-include("def_event.hrl").
-include("rec_event.hrl").
-include("server.hrl").
-include("common.hrl").
-include("def_fun.hrl").
-include("predefine.hrl").
-export ([
	handle_event/2
	,power_update/0
	,date_power_update/2
	]).

-define(NEED_UPDATE, [0, 1]). %% 需要更新的数据 0玩家最高战力 1时装星数（激活算1星）

%% 登录延后
handle_event(PS, #event_callback{type_id = ?EVENT_LOGIN_CAST}) when is_record(PS, player_status) ->
	#player_status{id = RoleId} = PS,
	DateTime = utime:unixdate(),
	%% 从数据库中获取数据
	Sql1 = io_lib:format(<<"select `type`, `num`, `time` from `player_date_hightest_power` where `role_id` = ~p and `type` in (~s) limit ~p">>, [RoleId, ulists:implode(",", ?NEED_UPDATE), erlang:length(?NEED_UPDATE)]),
	All = db:get_all(Sql1),
	Fun1 = fun([Type, Num, Time], AccMap) ->
		IsNeed = lists:member(Type, ?NEED_UPDATE),
		SelfNum = get_self_num(PS, Type),
		if
			Time >= DateTime andalso IsNeed -> AccMap#{Type => Num};
			IsNeed ->
				replace_player_date_hightest_power(RoleId, Type, SelfNum, DateTime),
				AccMap#{Type => SelfNum};
			true -> AccMap
		end
	end,
	TmpGrowthMap = lists:foldl(Fun1, #{}, All),

	%% 修复未持久处理的数据
	Fun2 = fun(Type, AccMap) ->
		SelfNum = get_self_num(PS, Type),
		AlreadyHave = maps:is_key(Type, AccMap),
		if
			AlreadyHave -> AccMap;
			true ->
				replace_player_date_hightest_power(RoleId, Type, SelfNum, DateTime),
				AccMap#{Type => SelfNum}
		end
	end,
	GrowthMap = lists:foldl(Fun2, TmpGrowthMap, ?NEED_UPDATE),
	NewPS = PS#player_status{daily_growth = GrowthMap},
	{ok, NewPS};
handle_event(PS, _) -> {ok, PS}.

power_update() ->
	OnlineList = ets:tab2list(?ETS_ONLINE),
	NowTime = utime:unixtime(),
	[begin
		timer:sleep(100), lib_player:apply_cast(RoleId, ?APPLY_CAST_SAVE, ?MODULE, date_power_update, [NowTime])
	 end
	 || #ets_online{id = RoleId}<-OnlineList].
date_power_update(PS, NowTime) ->
	#player_status{id = RoleId} = PS,
	Fun = fun(Type, AccMap) ->
		SelfNum = get_self_num(PS, Type),
		replace_player_date_hightest_power(RoleId, Type, SelfNum, NowTime), %% 目前每个玩家只有两条数据，暂时不用批量写入了
		AccMap#{Type => SelfNum}
	end,
	GrowthMap = lists:foldl(Fun, #{}, ?NEED_UPDATE),
	NewPS = PS#player_status{daily_growth = GrowthMap},
	{ok, NewPS}.

get_self_num(PS, Type) ->
	#player_status{hightest_combat_power = HightestCombatPower} = PS,
	case Type of
		0 -> HightestCombatPower;
		1 -> lib_fashion:get_fashion_total_star(PS) + lib_fashion:get_fashion_active_num(PS);
		_ -> 0
	end.

replace_player_date_hightest_power(RoleId, Type, Num, Time) ->
	Sql = io_lib:format(<<"replace into `player_date_hightest_power`(`role_id`, `type`, `num`, `time`) values (~p, ~p, ~p, ~p)">>, [RoleId, Type, Num, Time]),
	db:execute(Sql).
