%%%-------------------------------------------------------------------
%%% @doc    孩子-API接口
%%% Module  : lib_child_api.erl
%%% Created : 2020-02-17
%%% @Author : tyl
%%%-------------------------------------------------------------------
-module(lib_child_api).

-include("common.hrl").
-include("server.hrl").
-include("child.hrl").
-include("figure.hrl").
-include("skill.hrl").
-include("predefine.hrl").
-include("rec_event.hrl").
-include("def_event.hrl").
-include("def_module.hrl").
-include("attr.hrl").
-include("def_daily.hrl").
-include("errcode.hrl").

%% API
-export([
	login/1                %% 登录
	,handle_event/2        %% 事件处理

	%% 技能
	,check_have_learn_skill/2     %% 检查是否激活了该技能
	,get_child_active_skills/1    %% 获取孩子主动技能
	,get_child_passive_skills/1   %% 获取孩子被动技能

	,get_child_battle_attr/1      %% 获取宝宝战斗属性
	,get_baby_power/1		      %% 获得孩子战力
]).


login(Player) ->
	#player_status{id = RoleId, figure = Figure} = Player,
	%% 孩子基础信息
	case lib_child_util:get_db_child_info(RoleId) of
		[] ->
			StatusChild = #status_child{};
		InfoList ->
			StatusChild = lib_child:make_list(child, InfoList)
	end,
	case StatusChild#status_child.child_sex == 0 of
		true ->
			%% 还没领养孩子也需要读取任务数据
			DailyTaskList = case lib_child_util:get_db_child_daily_task(RoleId) of
				                [] -> [];
				                DailyTaskInfos ->
					                lib_child:make_list(child_daily_task, DailyTaskInfos)
			                end,
			%% 点赞玩家列表
			VoteIdList =
				case lib_child_util:get_vote_role_list(RoleId) of
					[] -> [];
					VoteList -> lists:usort(lists:flatten(VoteList))
				end,
			StatusChild1 = StatusChild#status_child{daily_task = DailyTaskList, vote_role_list = VoteIdList},
			Player#player_status{status_child = StatusChild1};
		_    ->
			%% 每日任务数据
			DailyTaskList =
				case lib_child_util:get_db_child_daily_task(RoleId) of
					[] -> [];
					DailyTaskInfos ->
						lib_child:make_list(child_daily_task, DailyTaskInfos)
				end,
			%% 被点赞记录
			BeVotedLogList =
				case lib_child_util:get_db_child_vote_log(RoleId) of
					[] -> [];
					VoteLogInfos ->
						lib_child:make_list(child_vote_log, VoteLogInfos)
				end,
			%% 点赞玩家列表
			VoteIdList =
				case lib_child_util:get_vote_role_list(RoleId) of
					[] -> [];
					VoteList -> lists:usort(lists:flatten(VoteList))
				end,
			%% 载具
			Vehicles =
				case lib_child_util:get_db_child_vehicle(RoleId) of
					[] -> [];
					VehicleList -> [{VehicleId, VehicleStage}||[VehicleId, VehicleStage]<- VehicleList]
				end,
			%% 载具激活的被动技能
			PassiveSkills = lib_child:get_active_passive_skill(Vehicles),
			%% 玩具
			SuitMap = lib_child_items:init_suit_map(RoleId),
			%% 计算目前承载的玩具重量
			% CarryWeight = lib_child_items:calc_toy_weight(Toys),
			%% 打造位
			% ForgeSlots =
			%	case lib_child_util:get_db_forge_slot_info(RoleId) of
			%		[] -> [];
			%		ForgeList -> [
			%			#forge_slot{slot_id = SlotId, start_time = StartTime, status = Status, select_id = SelectId}
			%			||[SlotId, StartTime, Status, SelectId]<-ForgeList]
			%	end,
			%% 时装
			{FashionList, DressUps} =
				case lib_child_util:get_db_child_fashion(RoleId) of
					[] -> {[], []};
					FashionInfos -> lib_child_items:trans_to_fashion(FashionInfos)
				end,
			%% 计算可以承载的玩具重量
			% CanCarry = lib_child_items:calc_can_carry_weight(
			%	StatusChild#status_child.child_age_year, StatusChild#status_child.child_age_month,
			%	Vehicles, FashionList),
			%% 技能列表
			SkillList =
				case lib_child_util:get_db_child_skill(RoleId) of
					[] -> [];
					TSkillList -> [{SkillId, SkillLv}||[SkillId, SkillLv]<- TSkillList]
				end,
			ActiveSkillList  = get_child_skills_type(SkillList, 1),
			PassiveSkillList = get_child_skills_type(SkillList, 2),
			%% 每日分享/昨日榜奖励
			case lib_child_util:get_db_child_reward(RoleId) of
				[ShareReward, YestRank, YestReward] -> ok;
				_ -> ShareReward = 0, YestRank = 0, YestReward = 0
			end,
 			%% 计算属性战力
			StatusChild1 = StatusChild#status_child{
				toy_suit      = SuitMap,
				vehicle       = Vehicles,
				fashion_list  = FashionList,
				dress_up_fashion = DressUps,
				active_skill  = SkillList,
				passive_skill = PassiveSkills++PassiveSkillList},  %% 技能属性加成包含入内
			SumAttrList  = lib_child:calc_child_attr(StatusChild1),
			ChildPower   = lib_child:calc_child_power(SumAttrList),
			NewStatusChild = StatusChild1#status_child{
				daily_task     = DailyTaskList,
				be_voted_log   = BeVotedLogList,
				attr_list      = SumAttrList,
				child_power    = ChildPower,
				extra_power    = lib_skill:count_skill_power(ActiveSkillList++ [{SkillId, 1}||SkillId <- StatusChild1#status_child.passive_skill]),
				vote_role_list = VoteIdList
				,share_reward  = ShareReward
				,yest_rank     = YestRank
				,yest_reward   = YestReward
				% can_carry      = CanCarry,
				% carry_weight   = CarryWeight,
				% forge_list     = ForgeSlots
			},
			%% 更新形象,场景使用
			NewFigure = Figure#figure{
				 baby_if_show =
					[NewStatusChild#status_child.is_follow, NewStatusChild#status_child.child_sex,
				 		NewStatusChild#status_child.child_age_month],
				 baby_vehicle = NewStatusChild#status_child.show_vehicle,
				 baby_model   = NewStatusChild#status_child.dress_up_fashion
			},
			Player#player_status{figure = NewFigure, status_child = NewStatusChild}
	end.

%% 登录刷新榜单
handle_event(Player, #event_callback{type_id = ?EVENT_LOGIN_CAST}) when is_record(Player, player_status) ->
	#player_status{id = RoleId, status_child = StatusChild} = Player,
	#status_child{child_sex = ChildSex, vote_times = _VoteTimes, adopt_time = AdoptTime,
		show_off_times = _ShowOffTimes, refresh_time = _RefreshTime, heart_reward = HeartReward} = StatusChild,
	%% 刷新当天被点赞数
	%{NewVoteTimes, NewShowOffTimes} = lib_child:refresh_vote_count(RoleId, RefreshTime, VoteTimes, ShowOffTimes),
	NewStatusChild = StatusChild, % #status_child{vote_times = NewVoteTimes, show_off_times = NewShowOffTimes},
	case ChildSex > 0 of
		true ->
			%% 已领取孩子：
			%% 检测同心奖励是否已经领取完,根据孩子领养时间
			%% 跨天邮件发放未领取的奖励,已领取完则不予理会
			AdoptDate = case AdoptTime of 0 -> 0; _ -> utime:unixdate(AdoptTime) end,
			NowDate   = utime:unixdate(),
			F = fun(AwardId) ->
				case lists:keyfind(AwardId, 1, HeartReward) of
					{_, _} -> true;
					_ -> false
				end end,
			case NowDate > AdoptDate of
				true ->
					AllRewardId = data_child:get_all_reward(),
					case lists:all(F, AllRewardId) of
						true -> {ok, Player#player_status{status_child = NewStatusChild}};
						_ ->
							%% 发放奖励
							AwardIdList = [TAwardId||TAwardId<-AllRewardId, lists:keyfind(TAwardId, 1, AllRewardId) == false],
							SendFun = fun(TRewardId1, TList) ->
								case data_child:get_child_link_heart_cfg(TRewardId1) of
									#child_link_heart_cfg{reward = Reward} -> Reward ++ TList;
									_ -> TList
								end end,
							AllReward = lists:foldl(SendFun, [], AwardIdList),
							Title = utext:get(1650003), Content = utext:get(1650004),
							lib_mail_api:send_sys_mail([RoleId], ?MOD_CHILD, Title, Content, AllReward),
							NewHeartReward = [{TRewardId2, 1}||TRewardId2<-AllRewardId],
							NewStatusChild1 = NewStatusChild#status_child{heart_reward = NewHeartReward},
							lib_child_util:update_db_child_link_heart_reward(RoleId, NewHeartReward),
							NewPlayer = Player#player_status{status_child = NewStatusChild1},
							{ok, NewPlayer}
					end;
				_ ->
					{ok, Player#player_status{status_child = NewStatusChild}}
			end;
		_ ->
			{ok, Player#player_status{status_child = NewStatusChild}}
	end;

%% 战力刷新检查排行榜更新
handle_event(Player, #event_callback{type_id = ?EVENT_COMBAT_POWER}) when is_record(Player, player_status) ->
	#player_status{id = RoleId, figure = Figure, status_child = StatusChild} = Player,
	case StatusChild#status_child.child_sex > 0 of
		true ->
			mod_child_vote_mgr:change_player_power(RoleId, Figure#figure.power);
		_ ->
			skip
	end,
	{ok, Player};

%% 达到指定等级激活玩具/打造槽位(不使用)
handle_event(Player, #event_callback{type_id = ?EVENT_LV_UP}) when is_record(Player, player_status) ->
	{ok, NewPlayer} = lib_child_items:check_if_active_toy_slot(Player, ?SLOT_OPEN_TYPE_ROLE_LV),
	OldSlotL = Player#player_status.status_child#status_child.toy_list,
	NewSlotL = NewPlayer#player_status.status_child#status_child.toy_list,
	AddSlotL = [TSlotId || {TSlotId, _} <- NewSlotL, lists:keymember(TSlotId, 1, OldSlotL) == false],
	F = fun(SlotId, Ack) ->
		lib_child:send_msg(Player#player_status.sid, 16532, [1, SlotId]),
		Ack
	end,
	lists:foldl(F, ok, AddSlotL),
	{ok, NewPlayer};

handle_event(Player, #event_callback{type_id = ?EVENT_ADD_LIVENESS}) when is_record(Player, player_status) ->
	SumLive = lib_daily:get_count(Player#player_status.id, ?MOD_ACTIVITY, ?ACTIVITY_LIVE_DAILY),
	NewPlayer = lib_child_task:finish_add_liveness(Player, SumLive),
	{ok, NewPlayer};

handle_event(Player, #event_callback{type_id = ?EVENT_CLIENT_LOGIN_SUCCESS}) when is_record(Player, player_status) ->
	SumLive = lib_daily:get_count(Player#player_status.id, ?MOD_ACTIVITY, ?ACTIVITY_LIVE_DAILY),
	NewPlayer = lib_child_task:finish_add_liveness(Player, SumLive),
	{ok, NewPlayer};

%% 完成任务激活宝宝系统记录初始的经验值
handle_event(Player, #event_callback{type_id = ?EVENT_FINISH_TASK, data = TaskId}) ->
	case TaskId of
		2060001 ->
			ta_agent_fire:child_heart(Player, ["激活任务", 0, 0, 0, 0]);
		_ ->
			ignore
	end,
	{ok, Player};

handle_event(Player, #event_callback{}) ->
	{ok, Player}.

%% 获取宝宝战斗属性
get_child_battle_attr(Player) ->
	#player_status{status_child = StatusChild} = Player,
	#status_child{attr_list = AttrList} = StatusChild,
	Attr = attr_conv:to_attr_record(AttrList),
	#battle_attr{attr = Attr}.

%% 检测是否学习了对应技能
check_have_learn_skill(Player, StrikeSkillId) ->
	#player_status{status_child = StatusChild} = Player,
	#status_child{child_sex = ChildSex, active_skill = SkillList} = StatusChild,
	HasActiveSkill =
	case ChildSex > 0 of
		true ->
			F = fun({SkillId, Lv}, TList) ->
				Sequence = lib_child:get_skill_sequence(SkillId),
				case data_child:get_child_skill_cfg(Sequence, Lv) of
					#child_skill_cfg{active_skill = ActiveSkill = [{TSkill, TLv}]} -> ok;
					_ -> ActiveSkill = [], TSkill = 0, TLv = 0
				end,
				case data_skill:get(TSkill, TLv) of
					#skill{type = ?SKILL_TYPE_ACTIVE} ->
						ActiveSkill++TList;
					_ ->
						TList
				end end,
			lists:foldl(F, [], SkillList);
		_ ->
			[]
	end,
	Result =
	case lists:keyfind(StrikeSkillId, 1, HasActiveSkill) of
		{_, _} -> true;
		_ -> false
	end,
	Result.

%% 获取孩子主动技能(需要对技能筛选一遍,因为含有部分被动技能)
get_child_active_skills(Player) ->
	#player_status{status_child = StatusChild} = Player,
	#status_child{child_sex = ChildSex, active_skill = SkillList} = StatusChild,
	case ChildSex > 0 of
		true ->
			F = fun({SkillId, Lv}, TList) ->
				Sequence = lib_child:get_skill_sequence(SkillId),
				case data_child:get_child_skill_cfg(Sequence, Lv) of
					#child_skill_cfg{active_skill = ActiveSkill = [{TSkill, TLv}]} -> ok;
					_ -> ActiveSkill = [], TSkill = 0, TLv = 0
				end,
				case data_skill:get(TSkill, TLv) of
					#skill{type = ?SKILL_TYPE_ACTIVE} ->
						ActiveSkill++TList;
					_ ->
						TList
				end
			end,
			lists:foldl(F, [], SkillList);
		_ ->
			[]
	end.

%% 获取孩子被动技能
get_child_passive_skills(Player) ->
	#player_status{status_child = StatusChild} = Player,
	#status_child{child_sex = ChildSex, passive_skill = SkillList, active_skill = ActiveSkillL} = StatusChild,
	case ChildSex > 0 of
		true ->
			lists:foldl(fun(SkillId, TList) ->
				Sequence = lib_child:get_skill_sequence(SkillId),
				case lists:keyfind(SkillId, 1, ActiveSkillL) of
					{_, Lv} -> skip;
					_ -> Lv = 1
				end,
				case data_child:get_child_skill_cfg(Sequence, Lv) of
					#child_skill_cfg{active_skill = ASkill = [{TSkill, TLv}]} -> ok;
					_ -> ASkill = [], TSkill = 0, TLv = 0
				end,
				case data_skill:get(TSkill, TLv) of
					#skill{type = ?SKILL_TYPE_PASSIVE} ->
						ASkill++TList;
					_ ->
						TList
				end end,
			[], SkillList);
		_ ->
			[]
	end.

%% 获取孩子特定技能列表
get_child_skills_type(SkillList, Type) ->
	F = fun({SkillId, Lv}, TList) ->
		Sequence = lib_child:get_skill_sequence(SkillId),
		case data_child:get_child_skill_cfg(Sequence, Lv) of
			#child_skill_cfg{active_skill = ActiveSkill = [{TSkill, TLv}]} -> ok;
			_ -> ActiveSkill = [], TSkill = 0, TLv = 0
		end,
		case data_skill:get(TSkill, TLv) of
			#skill{type = SkillType} when SkillType == Type ->
				case Type of
					1 -> ActiveSkill++TList;
					2 -> [TSkill|TList];
					_ -> TList
				end;
			_ ->
				TList
		end end,
	lists:foldl(F, [], SkillList).

get_baby_power(Player) ->
	case Player#player_status.status_child of
		#status_child{extra_power = ExtraPower, child_power = ChildPower} ->
			ChildPower + ExtraPower;
		_ ->
			0
	end.