%%%===================================================================
%%% @author zmh
%%% @doc 灵能
%%% @end
%%%===================================================================
-module(pp_nucleon).
-include("server.hrl").
-include("role_nucleon.hrl").
-include("chat.hrl").
-include("def_module.hrl").
-include("def_goods.hrl").
-include("predefine.hrl").
-include("goods.hrl").
-include("errcode.hrl").
-include("figure.hrl").
-include("common.hrl").
-export([handle/3]).

%%灵能数据
handle(13900,Status,[])->
	#player_status{
		sid=Sid,
		role_nucleon=RoleNucleon
	}=Status,
	#role_nucleon{
		lv = Lv,
		exp = Exp,
		holes  = Holes
	}=RoleNucleon,
	HoleList  = to_hole_list(Holes),
	{ok, Bin} = pt_139:write(13900,[Lv,Exp,HoleList]),
	lib_server_send:send_to_sid(Sid,Bin),
	{ok,Status};

% %%充能
% handle(13901,Status,[])->
% 	#player_status{id=RoleID}=Status,
% 	case lib_role_nucleon:charge_power(Status) of
% 		{ok,[Reports,NStatus]}->
% 			#player_status{role_nucleon=RoleNucleon}=NStatus,
% 			#role_nucleon{lv=Nlv,exp=NExp}=RoleNucleon,
% 			Res = ?SUCCESS;
% 		{false,Res}->
% 			Nlv = 0,NExp=0,Reports=[],
% 			NStatus = Status
% 	end,
% 	{ok,Bin} = pt_139:write(13901,[Res,Nlv,NExp,Reports]),
% 	lib_server_send:send_to_uid(RoleID,Bin),
% 	{ok,NStatus};

% %%激活阶位
% handle(13902,Status,[])->
% 	#player_status{
% 		id=RoleID,
% 		scene = Scene,
%         scene_pool_id = PoolID,
%         copy_id = CopyId,
%         x = X, y = Y
%     }=Status,
% 	case lib_role_nucleon:active_nucleon_title(Status) of
% 		{ok,[Nlv,NStatus0]}->
% 			NStatus1 = lib_role_nucleon:count_nucleon_attr(NStatus0),
% 			NStatus = lib_player:count_player_attribute(NStatus1,?MOD_NUCLEON),
%             lib_player:send_attribute_change_notify(NStatus, ?NOTIFY_ATTR),
%             mod_scene_agent:update(NStatus, [{battle_attr, NStatus#player_status.battle_attr},{role_nucleon,Nlv}]),

% 			%%场景广播
%             {ok, Bin1} = pt_120:write(12016, [?MOD_NUCLEON,0,RoleID,Nlv]),
%             lib_server_send:send_to_area_scene(Scene,PoolID,CopyId,X,Y,Bin1),

% 			Res = ?SUCCESS;
% 		{false,Res}->
% 			Nlv = 0,
% 			NStatus = Status
% 	end,
% 	{ok,Bin} = pt_139:write(13902,[Res,Nlv]),
% 	lib_server_send:send_to_uid(RoleID,Bin),
% 	{ok,NStatus};


%%灵能装甲 穿
handle(13903,Status,[Uid])->
	#player_status{id=RoleID} = Status,
	case lib_role_nucleon:equip_armor(Uid,Status) of
		{ok,NStatus0, UpInfo}->
			NStatus1 = lib_role_nucleon:count_nucleon_attr(NStatus0),
			NStatus = lib_player:count_player_attribute(NStatus1,?MOD_NUCLEON),
            lib_player:send_attribute_change_notify(NStatus, ?NOTIFY_ATTR),
            mod_scene_agent:update(NStatus, [{battle_attr, NStatus#player_status.battle_attr}]),
			lib_task_api:nucleon_equip(NStatus),
			case UpInfo of
				[Pos, LevelPos, Type, OldGoodsId, GoodsId, OldColor, NewColor, OldStar, NewStar] ->
					PromotePower = max(0, NStatus#player_status.combat_power - Status#player_status.combat_power),
					UpInfo1 = [Pos, LevelPos, Type, OldGoodsId, GoodsId, OldColor, NewColor, OldStar, NewStar, PromotePower],
					ta_agent_fire:nucleon_state(NStatus, UpInfo1);
				_ ->
					ignore
			end,
			Res=?SUCCESS;
		{false,Res}->
			NStatus = Status
	end,
	{ok,Bin} = pt_139:write(13903,[Res,Uid]),
	lib_server_send:send_to_uid(RoleID,Bin),
	{ok,NStatus};

%%灵能装甲 分解
handle(13904,Status,[UidList])->
	#player_status{id=RoleID}=Status,
	case lib_role_nucleon:resolve_armor(UidList,Status) of
		{ok,Gains}->
			Res = ?SUCCESS;
		{false,Res}->
			Gains = []
	end,
	GainsL = [{K,V}||{_,K,V}<-Gains],
	{ok,Bin} = pt_139:write(13904,[Res,GainsL]),
	lib_server_send:send_to_uid(RoleID,Bin),
	{ok,Status};

%%槽位 升级
handle(13905,Status,[Pos,AutoBuy,AutoLv])->
	#player_status{id=RoleID}=Status,
	case lib_role_nucleon:nucleon_pos_lv_up(AutoBuy,AutoLv,Pos,Status) of
		{ok,Lv,Exp,NStatus}->
			Res = ?SUCCESS;
		{false,Res}->
			Lv = 0,
			Exp = 0,
			NStatus = Status
	end,
	{ok,Bin} = pt_139:write(13905,[Res,Pos,Lv,Exp]),
	lib_server_send:send_to_uid(RoleID,Bin),
	{ok,NStatus};

%%槽位 突破
handle(13906,Status,[Pos])->
	#player_status{id=RoleID}=Status,
	case lib_role_nucleon:nucleon_pos_grade_up(Pos,Status) of
		{ok,Grade,NextLv,NStatus0}->
			NStatus1 = lib_role_nucleon:count_nucleon_attr(NStatus0),
			NStatus = lib_player:count_player_attribute(NStatus1,?MOD_NUCLEON),
            lib_player:send_attribute_change_notify(NStatus, ?NOTIFY_ATTR),
			Res = ?SUCCESS;
		{false,Res}->
			Grade = 0,
			NextLv = 0,
			NStatus = Status
	end,
	{ok,Bin} = pt_139:write(13906,[Res,Pos,Grade,NextLv,0]),
	lib_server_send:send_to_uid(RoleID,Bin),
	{ok,NStatus};

%%装甲 进化
handle(13907,Status,[Uid,Loc])->
	#player_status{id=RoleID}=Status,
	case lib_role_nucleon:armor_grade_up(Uid,Loc,Status) of
		{ok,ItemID,NStatus0,UpInfo}->
			case Loc of
				?GOODS_LOC_ARMOR_EQUIP->
					NStatus1 = lib_role_nucleon:count_nucleon_attr(NStatus0),
					NStatus = lib_player:count_player_attribute(NStatus1,?MOD_NUCLEON),
		            lib_player:send_attribute_change_notify(NStatus, ?NOTIFY_ATTR);
		        _->
		        	NStatus = NStatus0
		    end,
			case UpInfo of
				[Pos, LevelPos, Option, InItemID, Next, OldColor, NewColor, OldStar, NewStar] ->
					PromotePower = max(0, NStatus#player_status.combat_power - Status#player_status.combat_power),
					UpInfo1 = [Pos, LevelPos, Option, InItemID, Next, OldColor, NewColor, OldStar, NewStar, PromotePower],
					ta_agent_fire:nucleon_state(NStatus, UpInfo1);
				_ ->
					ignore
		    end,
			Res = ?SUCCESS;
		{false,Res}->
			ItemID  = 0,
			NStatus = Status
	end,
	{ok,Bin} = pt_139:write(13907,[Res,Uid,ItemID]),
	lib_server_send:send_to_uid(RoleID,Bin),
	{ok,NStatus};

%%槽位 觉醒
handle(13908,Status,[Pos])->
	#player_status{id=RoleID}=Status,
	case lib_role_nucleon:nucleon_section_up(Pos,Status) of
		{ok,Pos,Sec,GoodsNum,NStatus0}->
			NStatus1 = lib_role_nucleon:count_nucleon_attr(NStatus0),
			NStatus = lib_player:count_player_attribute(NStatus1,?MOD_NUCLEON),
            lib_player:send_attribute_change_notify(NStatus, ?NOTIFY_ATTR),
            ta_agent_fire:nucleon_section_up(NStatus, [Pos, Sec, GoodsNum]),
			Res = ?SUCCESS;
		{false,Res}->
			Sec = 0,
			NStatus = Status
	end,
	{ok,Bin} = pt_139:write(13908,[Res,Pos,Sec]),
	lib_server_send:send_to_uid(RoleID,Bin),
	{ok,NStatus};

%%槽位 洗练
handle(13909,Status,[Pos])->
	#player_status{id=RoleID}=Status,
	case lib_role_nucleon:nucleon_recast_attr(Pos,Status) of
		{ok,Reports,NewAttrs,NStatus0}->
			NStatus1 = lib_role_nucleon:count_nucleon_attr(NStatus0),
			NStatus  = lib_player:count_player_attribute(NStatus1,?MOD_NUCLEON),
            lib_player:send_attribute_change_notify(NStatus, ?NOTIFY_ATTR),
			Res = ?SUCCESS;
		{false,Res}->
			NewAttrs = [],
			Reports  = [],
			NStatus  = Status
	end,
	{ok,Bin} = pt_139:write(13909,[Res,Pos,NewAttrs,Reports]),
	lib_server_send:send_to_uid(RoleID,Bin),
	{ok,NStatus};

%%打开抽奖面板
handle(13910,Status,[])->
	#player_status{id=RoleID,role_nucleon=RoleNucleon}=Status,
	Infos = lib_role_nucleon:get_pane_info(RoleNucleon),
	{ok,Bin}=pt_139:write(13910,[Infos]),
	lib_server_send:send_to_uid(RoleID,Bin),
	{ok,Status};

%%抽奖
handle(13911,Status,[Pool,OpTy])->
	#player_status{
		id=RoleID,
		figure = #figure{name=Name}
	}=Status,
	PoolType = case Pool of
		           1 -> "红钻池";
		           _ -> "彩钻池"
	           end,
	case lib_role_nucleon:do_nucleon_rock(Pool,OpTy,Status) of
		{ok,Awards,NRoleNucleon0}->
			{Cost,ExCost,NRoleNucleon} = lib_role_nucleon:calc_cost(Pool,OpTy,NRoleNucleon0),
			{Orange1, Orange2, SectionPiece} = calc_get_award(Awards),
			case Cost=<0 of %%免费
				true->
					NStatus0 = Status#player_status{role_nucleon=NRoleNucleon},
					[NStatus,Gains] = role_gain(Awards,Pool,NStatus0,[]),
					lib_role_nucleon:save_role_nucleon(RoleID,NRoleNucleon),
					IsFree = 0,
					NCost = [],
					lib_task_api:nucleon_shop(NStatus),
					custom_act_mobilize:update_mobilize_task(RoleID, nucleondraw, 1),
					ta_agent_fire:nucleon_draw(NStatus, [PoolType, "免费", Orange1, Orange2, SectionPiece,
						0, 0, 0, NStatus#player_status.gold, NStatus#player_status.bgold]),
					Res = ?SUCCESS;
				_->%%需要付费 优先道具
					NCost =  case OpTy>1 of
						true->%%十连
							case lib_goods_api:get_goods_num(Status,[ExCost]) of
								[{_,Has}|_] when Has>0->
									[{?TYPE_GOODS,ExCost,1}]; %%十连券够就扣十连券
								_-> %%单抽券存在的情况 持有单抽券 参与十连 9券可十连 依照单前数量补齐
									#pool_base{one=One,cost=CostOne}=data_nucleon:get_pool(Pool),
									case lib_goods_api:get_goods_num(Status,[One]) of
										[{_,Has}|_] when Has>=9->
											[{?TYPE_GOODS,One,9}];
										[{_,Has}|_] when Has>0->
											Cost0 = [{T,K,V*(9-Has)}||{T,K,V}<-CostOne],
											[{?TYPE_GOODS,One,Has}|Cost0];
										_->
											Cost
									end
							end;
						_-> %%单抽无特殊
							case lib_goods_api:get_goods_num(Status,[ExCost]) of
								[{_,Has}|_] when Has>0->
									[{?TYPE_GOODS,ExCost,1}];
								_->
									Cost
							end
					end,
					IsFree = 1,
					case lib_goods_api:cost_object_list_with_check(Status,NCost,rock_nucleon,"nucleon rock") of
						{true,NStatus0,_}->
							NStatus1 = NStatus0#player_status{role_nucleon=NRoleNucleon},
							[NStatus,Gains]  = role_gain(Awards,Pool,NStatus1,[]),
							lib_role_nucleon:save_role_nucleon(RoleID,NRoleNucleon),
							lib_task_api:nucleon_shop(NStatus),
							case OpTy of
								1 -> TaskValue = 1;
								_ -> TaskValue = 10
							end,
							custom_act_mobilize:update_mobilize_task(RoleID, nucleondraw, TaskValue),
							Option = case TaskValue of
								         1 -> "单抽";
								         _ -> "十连"
							         end,
							case lists:keyfind(?TYPE_GOODS, 1, NCost) of
								{_, _, _} -> CostGoods = ExCost;
								_ -> CostGoods = 0
							end,
							CostGold  = max(0, Status#player_status.gold - NStatus#player_status.gold),
							CostBGold = max(0, Status#player_status.bgold - NStatus#player_status.bgold),
							ta_agent_fire:nucleon_draw(NStatus, [PoolType, Option, Orange1, Orange2, SectionPiece,
								CostGoods, CostGold, CostBGold, NStatus#player_status.gold, NStatus#player_status.bgold]),
							Res = ?SUCCESS;
						{false,Res,_}->
							Gains   = [],
							NStatus = Status
					end
			end;
		{false,Res}->
			Gains  = [],
			NCost = [],
			IsFree = 0,
			NStatus = Status
	end,
	Panes = goods_add:get_dict_goods(),
	goods_add:save_dict_goods([]),
	Bin = pack_13911(Res,Pool,OpTy,NStatus#player_status.role_nucleon,Panes++Gains),
	Res == ?SUCCESS andalso lib_log_api:log_nucleon_hunt(RoleID,Name,Pool,OpTy,IsFree,Panes++Gains,NCost),
	lib_server_send:send_to_uid(RoleID,Bin),
	{ok,NStatus};

handle(13912,Status,[SortID,Num])->
	#player_status{id=RoleID}=Status,
	case lib_role_nucleon:nucleon_exchange_goods(Status,SortID,Num) of
		{ok,NStatus}->
			Res = ?SUCCESS;
		{false,Res}->
			NStatus = Status
	end,
	{ok,Bin} = pt_139:write(13912,[Res,SortID]),
	lib_server_send:send_to_uid(RoleID,Bin),
	{ok,NStatus};

handle(13914, Status, []) ->
	#player_status{id = RoleId} = Status,
	Times = lib_pet_api:pet_life_skill_about_nucleon_wash_free(Status),
	FreeTimes = case Times > 0 of
		            true -> case lib_daily:get_count(RoleId, ?MOD_NUCLEON, 1) of
			                    Count when is_integer(Count), Count =:= 0 -> 1;
			                    _ -> 0
		                    end;
		            _ -> 0
	            end,
	lib_server_send:send_to_uid(RoleId, pt_139, 13914, [FreeTimes]),
	{ok, Status};

handle(_Cmd, _Status, _Data) ->
	ok.

%% 计算获得的奖励
calc_get_award(AwardList) ->
	F = fun(AwardId, {TOrange1, TOrange2, TSectionPiece}) ->
		case data_nucleon:nucleon_award(AwardId) of
			#nucleon_award_base{awards = [{_, GoodsId, _}]} ->
				%% 计算碎片数量
				TSectionPiece1 = case GoodsId of
					                 280201 -> TSectionPiece + 1;
					                 _ -> TSectionPiece
				                 end,
				case data_goods_type:get(GoodsId) of
					#ets_goods_type{color = Color} when Color == ?ORANGE ->
						case data_nucleon:nucleon_equip(GoodsId) of
							#nucleon_equip_base{star = Star} -> ok;
							_ -> Star = 0
						end,
						case Star of
							1 ->
								{TOrange1+1, TOrange2, TSectionPiece1};
							2 ->
								{TOrange1, TOrange2+1, TSectionPiece1};
							_ ->
								{TOrange1, TOrange2, TSectionPiece1}
						end;
					_ ->
						{TOrange1, TOrange2, TSectionPiece1}
				end;
			_ ->
				{TOrange1, TOrange2, TSectionPiece}
		end end,
	{Orange1, Orange2, SectionPiece} = lists:foldl(F, {0, 0, 0}, AwardList),
	{Orange1, Orange2, SectionPiece}.

%%道具获得
role_gain([],_Type,Status,Gains)->
	[Status,Gains];
role_gain([AwardID|Awards],Type,Status,ExtGains)->
	#player_status{id=RoleID,figure=#figure{name=Name}}=Status,
	case data_nucleon:nucleon_award(AwardID) of
		#nucleon_award_base{broadcast=Show,awards=Gain0}->
			{ItemID,Add} = case Gain0 of
				[{_,GoodsID,Num}|_]->
					{GoodsID,Num};
				[{_,GoodsID,Num,_}|_]->
					{GoodsID,Num};
				_->
					{0,0}
			end,
			BaseItem = data_nucleon:get(nucleon_equip_lv),
			case data_goods_type:get(ItemID) of
				#ets_goods_type{type=?GOODS_TYPE_X3} when ItemID == BaseItem->
					NewExtGains = [{ItemID,0,Add}|ExtGains];
				 #ets_goods_type{type=?GOODS_TYPE_X3}->
					NewExtGains = ExtGains;
				_->
					NewExtGains = [{ItemID,0,Add}|ExtGains]
			end,
			case data_nucleon:get_pool(Type) of
				#pool_base{base=Gain1}->
					Show >0 andalso lib_chat:send_TV({all}, ?MOD_NUCLEON, 4, [Name,RoleID,ItemID]),
					Produce = #produce{type=nucleon_rock,reward=Gain1++Gain0},
                    {ok,NStatus} = lib_goods_api:send_reward_with_mail(Status, Produce, ?MOD_NUCLEON);
				_->
					Produce = #produce{type=nucleon_rock,reward=Gain0},
					{ok,NStatus} = lib_goods_api:send_reward_with_mail(Status, Produce, ?MOD_NUCLEON)
			end;
		_->
			NewExtGains = ExtGains,
			NStatus = Status
	end,
	role_gain(Awards,Type,NStatus,NewExtGains).

pack_13911(Res,Pool,OpTy,RoleNucleon,Panes)->
	Infos = lib_role_nucleon:get_pane_info(RoleNucleon),
	case lists:keyfind(Pool,1,Infos) of
		{_,IsF,Times,Time,State}->
			ignore;
		_->
			IsF=0,Times=0,Time=0,State=[]
	end,
	{ok,Bin} = pt_139:write(13911,[Res,Pool,OpTy,Panes,IsF,Times,Time,State]),
	Bin.

to_hole_list(Holes)->
	to_hole_list(Holes,[]).
to_hole_list([],HList)->
	HList;
to_hole_list([H|T],HList)->
	#nucleon_hole{
		pos = Pos,
		grade = Grade,
		lv = PLv,
		exp = PExp,
		attrs = PAttrs,
		skill = Skill,
		skill_lv = SkillLv,
		sec_lv   = SecLv
	}=H,
	to_hole_list(T,[{Pos,Grade,PLv,PExp,Skill,SkillLv,SecLv,PAttrs}|HList]).