%% ---------------------------------
%% desc     :跨服战团
%% module   :lib_role_legion
%% author   :zmh
%% ---------------------------------

-module(lib_role_legion).

-export([
	login/2,
	handle_event/2,      %%事件处理
	fetch_awards/3,      %%领取
	get_role_task/0,     %%获得任务
	trigger_task/3,      %%触发任务
	trigger_task/4,
	check/1,
	click_rank_role/2,    %%膜拜
	get_legion/1,	      %%获得玩家当前战功
	get_process/1,			%% 获得玩家当前活跃度
	add_legion_score/2,   %%增加战功
	add_legion_arms/2,    %%增加军备值
	fetch_day_awards/1,
	fetch_advance_awards/2,
	pack_rank_data/2,
	pack_last_rank_data/2,
	pack_history_director/3,
	upload_figure/1,       %%上传形象
	req_upload_figure/2,
	center_upload_figure/3,
	upgrade_post/1,
	check_legion/2,
	get_attr/1,
	pack_task/2,
	update_role_legion/3,
	cost_legion_arms/4,          %%军备值扣取
	is_enough_arms/2,            %%军备值判断
	clean_rank_score/0,           %%重置数据库数据
	reset_rank_score/1          %%赛季重置玩家个人数据
]).
-include("errcode.hrl").
-include("def_goods.hrl").
-include("def_module.hrl").
-include("predefine.hrl").
-include("goods.hrl").
-include("kf_legion.hrl").
-include("rec_event.hrl").
-include("def_event.hrl").
-include("server.hrl").
-include("guild.hrl").
-include("figure.hrl").
-include("role.hrl").


%%登录加载
login(RoleID, Figure)->
	{IsSave,RoleLegion,Tasks} = load_role_legion(RoleID),
	save_all_task(Tasks),
	IsSave andalso save_role_legion(RoleID,RoleLegion),
	#role_legion{post = Post} = RoleLegion,
	NFigure = Figure#figure{post = Post},
	{RoleLegion, NFigure}.

%%判断军备值是否足够
is_enough_arms(_Status,Num) when Num=<0->
	false;
is_enough_arms(Status,Num)->
	#player_status{role_legion=RoleLegion}=Status,
	RoleLegion#role_legion.arms>=Num.

%%扣费
cost_legion_arms(Status, GoodsNum, Type, _About) ->
    #player_status{
    	id = RoleId, sid = Sid,
    	role_legion=RoleLegion,
    	figure = #figure{lv = RoleLv, vip = VipLv}
    } = Status,
    #role_legion{arms=Arms}=RoleLegion,
    NArms = max(0, round(Arms-GoodsNum)),
    NewRoleLegion = RoleLegion#role_legion{arms=NArms},
    update_role_legion(RoleId,arms,NewRoleLegion),
    NewStatus = Status#player_status{role_legion = NewRoleLegion},
    lib_log_api:log_consume_currency(RoleId, RoleLv, VipLv, Type, ?TYPE_LEGION, GoodsNum, NArms, _About),
    lib_server_send:send_to_sid(Sid, pt_603, 60303, [[{3,NArms}]]),
    NewStatus.

%%重置数据库数据
%%在线的在沙盘处理
clean_rank_score()->
	db:execute(?SQL_ROLE_LEGION_RESET).
%%重置在线玩家个人身上数据
reset_rank_score(Status)->
	#player_status{
    	id = RoleID,
    	role_legion=RoleLegion
    } = Status,
    RoleLegion0 = check_legion(RoleID,RoleLegion),
    NRoleLegion = RoleLegion0#role_legion{rank_score=0,arms=0},
    update_role_legion(RoleID,reset,NRoleLegion),
    {ok,Bin} = pt_603:write(60303,[[{3,0}]]),
    lib_server_send:send_to_uid(RoleID,Bin),
    Status#player_status{role_legion=NRoleLegion}.


%%数据加载
load_role_legion(RoleID)->
	case db:get_row(io_lib:format(?SQL_ROLE_LEGION_GET, [RoleID])) of
        [Post,Score,RankScore,Arms,Process,DotList,CRole,DStatus,Tasks0,LTime,UTime,StrDaysList] ->
        	DaysList =  util:bitstring_to_term(StrDaysList),
        	case utime:is_logic_same_day(LTime) of
        		true->
            		Tasks1 =  util:bitstring_to_term(Tasks0),
            		Tasks  =  to_record_task(Tasks1),
					DotList1 =  util:bitstring_to_term(DotList),
					CRole1 =  util:bitstring_to_term(CRole),
            		RoleLegion = #role_legion{
            			post = Post,
            			score = Score,
            			rank_score = RankScore,
            			arms = Arms,
            			process = Process,
            			dot_list = DotList1,
            			click_role = CRole1,
            			day_award = DStatus,
            			ltime = LTime,
			            post_utime = UTime,
			            advance_awards = DaysList
            		},
            		{false,RoleLegion,Tasks};
            	_->
            		RoleLegion = #role_legion{
            			post = Post,
            			score = Score,
            			rank_score = RankScore,
            			arms = Arms,
            			ltime = utime:unixtime(),
            			advance_awards = DaysList
            		},
            		Tasks = init_task(),
            		{true,RoleLegion,Tasks}
            end;
        _ ->
        	Tasks = init_task(),
        	{true,#role_legion{ltime = utime:unixtime()},Tasks}
    end.

%%转任务结构
to_record_task(Tasks)->
 	case is_list(Tasks) of
 		true->
 			to_record_task(Tasks,[]);
 		_-> %%数据库字段不够溢出？
 			[]
 	end.

to_record_task([],Tasks)->
 	Tasks;
to_record_task([{Id,Bar,Status}|T],Tasks)->
 	to_record_task(T,[#legion_task{id=Id,bar=Bar,state=Status}|Tasks]).

%%分发
center_upload_figure(RoleID,ASerId,Aim)->
	clusters_center:apply_cast(ASerId,{?MODULE,req_upload_figure,[RoleID,Aim]}).

req_upload_figure(RoleID,Aim)->
	Zone = czone_api:env_get_zone_id(),
    Fact = czone_api:env_get_faction(),
   	case lib_role:get_role_show(Aim) of
   		#ets_role_show{figure=Figure}->
   			clusters_node:apply_cast(mod_legion_mgr, res_upload_figure, [Zone,Fact,RoleID,Figure]);
   		_->
   			skip
   	end.

%%上传形象
upload_figure(RoleID)->
	Zone = czone_api:env_get_zone_id(),
    Fact = czone_api:env_get_faction(),
   	case lib_role:get_role_show(RoleID) of
   		#ets_role_show{figure=Figure}->
   			clusters_node:apply_cast(mod_legion_mgr, upload_figure, [Zone,Fact,Figure]);
   		_->
   			skip
   	end.

%%获得玩家当前战功
get_legion(Status) ->
	#player_status{
		role_legion=RoleLegion
	}=Status,
	#role_legion{
		rank_score = ORankScore
	}=RoleLegion,
	ORankScore.

%% 获得玩家当前活跃度
get_process(Status) ->
	#player_status{
		role_legion=RoleLegion
	}=Status,
	#role_legion{
		process = Pro
	}=RoleLegion,
	Pro.

%%增加战功
add_legion_score(RoleID,Add) when is_integer(RoleID)->
	Pid = misc:get_player_process(RoleID),
	case misc:is_process_alive(Pid) of
		true->
			lib_player:apply_cast(Pid,?APPLY_CAST_STATUS,?MODULE, add_legion_score,[Add]);
		_->
			offline_add_legion_score(RoleID,Add)
	end;
add_legion_score(Status,Add)->
	#player_status{
		id = RoleID,
		role_legion=RoleLegion
	}=Status,
	#role_legion{
        score = OScore,
        rank_score = ORankScore
    }=RoleLegion,
    Score = OScore+Add,
    RankScore = ORankScore+Add,
    NRoleLegion = RoleLegion#role_legion{score=Score,rank_score = RankScore},
    NStatus = Status#player_status{role_legion=NRoleLegion},
    case RankScore >= data_legion:get(min_score) of
    	true->
    		LegionRankRole = to_legion_rank_role(Status,RankScore),
    		clusters_node:apply_cast(mod_legion_rank_mgr, update_legion_role, [LegionRankRole]);
    	_->
    		skip
    end,
    update_role_legion(RoleID,score,NRoleLegion),
    lib_server_send:send_to_uid(RoleID, pt_603, 60303, [[{4,Score},{5,RankScore}]]),
	{ok,NStatus}.


offline_add_legion_score(RoleID,Add)->
	{_IsSave,RoleLegion,_Tasks} = load_role_legion(RoleID),
	#role_legion{
        score = OScore,
        rank_score = ORankScore
    }=RoleLegion,
	Score = OScore+Add,
    RankScore = ORankScore+Add,
    NRoleLegion = RoleLegion#role_legion{score=Score,rank_score = RankScore},
    update_role_legion(RoleID,score,NRoleLegion),
    case RankScore >= data_legion:get(min_score) of
    	true->
    		case lib_role:get_role_show(RoleID) of
    			#ets_role_show{figure=Figure}->
		    		Status = #player_status{
		    			id=RoleID,
		    			figure=Figure,
		    			server_id=config:get_server_id(),
		    			server_num=config:get_server_num(),
		    			guild = #status_guild{name=Figure#figure.guild_name}
		    		},
		    		LegionRankRole = to_legion_rank_role(Status,RankScore),
		    		clusters_node:apply_cast(mod_legion_rank_mgr, update_legion_role, [LegionRankRole]);
		    	_->
		    		skip
		    end;
    	_->
    		skip
    end.

%%增加军备值
add_legion_arms(Status,Num)->
	#player_status{id=RoleID,sid=Sid,role_legion=RoleLegion}=Status,
	NRoleLegion = check_legion(RoleID,RoleLegion),
	#role_legion{
        arms = Arms
    }=NRoleLegion,
    NArms = Arms+Num,
    NewRoleLegion = NRoleLegion#role_legion{arms=NArms},
    update_role_legion(RoleID,arms,NewRoleLegion),
    NStatus = Status#player_status{role_legion=NewRoleLegion},
    lib_server_send:send_to_sid(Sid, pt_603, 60303, [[{3,NArms}]]),
    NStatus.

handle_event(Status,#event_callback{type_id = ?EVENT_MONEY_CONSUME})->
    {ok, Status};
handle_event(Status,#event_callback{type_id = ?EVENT_RECHARGE})->
    {ok, Status};
handle_event(Status,#event_callback{type_id = ?EVENT_FOUR_CLOCK})->
	#player_status{id=RoleID,role_legion=RoleLegion}=Status,
	NRoleLegion = check_legion(RoleID,RoleLegion),
	NStatus = Status#player_status{role_legion=NRoleLegion},
	#role_legion{
        process = Pro,
        arms = Arms,
        dot_list = DotList,
        post = Post,
        rank_score = RankScore
    }=NRoleLegion,
    Tasks = get_role_task(),
    TaskL = pack_task(Tasks,[]),
    {ok,Bin} = pt_603:write(60301,[Pro,DotList,Arms,Post,RankScore,TaskL]),
    lib_server_send:send_to_uid(RoleID,Bin),
    save_role_legion(RoleID,NRoleLegion),
	{ok,NStatus};
handle_event(Status, _) ->
    {ok, Status}.


%%数据矫正
check_legion(RoleID,RoleLegion)->
	#role_legion{
		ltime = Ltime
	}=RoleLegion,
	case utime:is_logic_same_day(Ltime) of
		true->
			RoleLegion;
		_->%%跨天需要重置任务
			NRoleLegion = RoleLegion#role_legion{
				process = 0,
				dot_list = [],

				click_role = [],
				day_award = 0,
				ltime = utime:unixtime()
			},
			NTasks = init_task(),
			save_all_task(NTasks),
			save_role_legion(RoleID,NRoleLegion),
			NRoleLegion
	end.


%%获取任务
get_role_task()->
	Tasks =  get_all_task(),
	case length(Tasks)=<0 of
		true->
			NTasks = init_task(),
			save_all_task(NTasks),
			NTasks;
		_->
			Tasks
	end.

%%左边栏领取
fetch_awards(Status,0,Did)->
	#player_status{
		id = RoleID,
		role_legion = RoleLegion
	}=Status,
	#role_legion{
		process = CurPro,
		dot_list = CurDotList
	}=RoleLegion,
	Config = data_legion:get_active_awards(Did),
	CKlist = [
		{check_cfg,Config,base_legion_active_award},
		{check_active,Config,CurPro},
		{check_is_get,CurDotList,Did}
	],
	case util:check_lists(?MODULE,CKlist) of
		true->
			#base_legion_active_award{awards=Awards}=Config,
			Produce = #produce{type = cross_legion, reward=Awards},
            lib_goods_api:send_reward_with_mail(RoleID, Produce, ?MOD_CROSS_LEGION),
            NRoleLegion = RoleLegion#role_legion{dot_list=[Did|CurDotList]},
            NStatus = Status#player_status{role_legion=NRoleLegion},
            {ok,Bin} = pt_603:write(60303,[[{2,Did}]]),
            lib_server_send:send_to_uid(RoleID,Bin),
            update_role_legion(RoleID,awards,NRoleLegion),
            {ok,NStatus};
        {false,Err}->
        	{false,Err}
     end;
%%任务领取
fetch_awards(Status,1,Tid)->
	#player_status{
		id = RoleID,
		role_legion = RoleLegion
	}=Status,
	Tasks  = get_all_task(),
	Config = data_legion:get_task(Tid),
	Task   = lists:keyfind(Tid,#legion_task.id,Tasks),
	#role_legion{
		process=CurPro
	}=RoleLegion,
	CKlist = [
		{check_cfg,Config,base_legion_task},
		{check_task_status,Task}
	],
	case util:check_lists(?MODULE,CKlist) of
		true->
			#legion_task{bar=Bar}=Task,
			#base_legion_task{awards=Awards,active=Add}=Config,
			NPro = CurPro+Add,
			Produce = #produce{type = cross_legion, reward=Awards},
            lib_goods_api:send_reward_with_mail(RoleID, Produce, ?MOD_CROSS_LEGION),
            NRoleLegion = RoleLegion#role_legion{process=NPro},
            NTask = Task#legion_task{state=?LEGION_GOT},
            NTasks = lists:keystore(Tid,#legion_task.id,Tasks,NTask),
            save_all_task(NTasks),
            {ok,Bin0} = pt_603:write(60302,[Tid,Bar,?LEGION_GOT]),
            {ok,Bin1} = pt_603:write(60303,[[{1,NPro}]]),
            Bin = <<Bin0/binary,Bin1/binary>>,
            lib_server_send:send_to_uid(RoleID,Bin),
            NStatus = Status#player_status{role_legion=NRoleLegion},
            update_role_legion(RoleID,task,NRoleLegion),
            {ok,NStatus};
        {false,Err}->
        	{false,Err}
     end.

%%膜拜
click_rank_role(Aim,Status)->
	#player_status{
        id = RoleID,
        role_legion = RoleLegion
    }=Status,
    NRoleLegion0 = check_legion(RoleID,RoleLegion),
    #role_legion{
        click_role = CRidList
    }=NRoleLegion0,
	Zone = czone_api:env_get_zone_id(),
    Fact = czone_api:env_get_faction(),
	ARank = clusters_node:apply_call(mod_legion_rank_mgr, get_click_role_rank, [Zone,Fact,Aim]),
	CKlist = [
		{check_click_done,Aim,CRidList},
		{check_click_rank,ARank}
	],
	case util:check_lists(?MODULE,CKlist) of
		true->
			Awards = data_legion:get(like_reward),
			NRoleLegion = NRoleLegion0#role_legion{click_role=[Aim|CRidList]},
			NStatus = Status#player_status{role_legion=NRoleLegion},
			Produce = #produce{type = cross_legion, reward=Awards},
            lib_goods_api:send_reward_with_mail(RoleID, Produce, ?MOD_CROSS_LEGION),
            update_role_legion(RoleID,click,NRoleLegion),
			{ok,NStatus};
		{false,Err}->
			{false,Err}
	end.

%%领取前一天的排名奖励
fetch_day_awards(Status)->
	#player_status{
        id = RoleID,
        role_legion = RoleLegion
    }=Status,
    NRoleLegion0 = check_legion(RoleID,RoleLegion),
    #role_legion{
        day_award = FStatus
    }=NRoleLegion0,
	Zone = czone_api:env_get_zone_id(),
    Fact = czone_api:env_get_faction(),
	LRank = clusters_node:apply_call(mod_legion_rank_mgr, get_last_role_rank, [Zone,Fact,RoleID]),
	CKlist = [
		{check_fetch_done,FStatus},
		{check_last_rank,LRank}
	],
	case util:check_lists(?MODULE,CKlist) of
		true->
			Awards = data_legion:get_rank_awards(LRank),
			NRoleLegion = NRoleLegion0#role_legion{day_award=1},
			NStatus = Status#player_status{role_legion=NRoleLegion},
			Produce = #produce{type = cross_legion, reward=Awards},
            lib_goods_api:send_reward_with_mail(RoleID, Produce, ?MOD_CROSS_LEGION),
            update_role_legion(RoleID,awards,NRoleLegion),
			{ok,NStatus};
		{false,Err}->
			{false,Err}
	end.

%%领取预告奖励
fetch_advance_awards(FetchDay,Status)->
	#player_status{
        id = RoleID,
        role_legion = RoleLegion
    }=Status,
    NRoleLegion0 = check_legion(RoleID,RoleLegion),
    #role_legion{
        advance_awards = DaysList
    }=NRoleLegion0,
    OpDay = util:get_open_day(),
    All = data_legion:get_days(),
	CKlist = [
		{check_advance_args,FetchDay,OpDay,All},
		{check_advance_fetch_done,FetchDay,DaysList}
	],
	case util:check_lists(?MODULE,CKlist) of
		true->
			Awards = data_legion:get_day_advance_awards(FetchDay),
			NRoleLegion = NRoleLegion0#role_legion{advance_awards=[FetchDay|DaysList]},
			NStatus = Status#player_status{role_legion=NRoleLegion},
			Produce = #produce{type = cross_legion, reward=Awards},
            lib_goods_api:send_reward_with_mail(RoleID, Produce, ?MOD_CROSS_LEGION),
            update_role_legion(RoleID,advance_awards,NRoleLegion),
			{ok,NStatus};
		{false,Err}->
			{false,Err}
	end.


%%军衔进阶
upgrade_post(Status)->
	#player_status{
		id = RoleID,
		sid = Sid,
		role_legion = RoleLegion
		,figure = Figure
		,server_num = ServerNum
		,scene = Scene
		,scene_pool_id = PoolID
		,copy_id = CopyId
		,x = X, y = Y
	} = Status,
	NRoleLegion0 = check_legion(RoleID,RoleLegion),
	#role_legion{post=CurPost}=NRoleLegion0,
	Config = data_legion:get_legion_post(CurPost),
	#figure{power=Power}=Figure,
	CKlist = [
		{check_cfg,Config,base_legion_post},
		{check_post_max,Config},
		{check_post_power,Config,Power},
		{check_post_cost,Config,Status}
	],
	case util:check_lists(?MODULE,CKlist) of
		{ok,NStatus0}->
			#base_legion_post{next=NPost}=Config,
			NRoleLegion = NRoleLegion0#role_legion{post=NPost,post_utime=utime:unixtime()},
			NFigure = Figure#figure{post = NPost},
			NStatus1 = NStatus0#player_status{role_legion=NRoleLegion, figure = NFigure},
			update_role_legion(RoleID,post,NRoleLegion),
			%% 更新跨服榜单
			case mod_military_rank_mgr:check_in_center() of
				true ->
					{ZoneId, RoleInfo} = mod_military_rank_mgr:get_role_info(RoleID, Figure, ServerNum),
					clusters_node:apply_cast(mod_military_rank_mgr, update_military_pos,
						[ZoneId, RoleInfo, NPost, utime:unixtime()]);
				_ -> ignore
			end,
			lib_server_send:send_to_sid(Sid, pt_603, 60303, [[{4,0}]]),
			{ok, BinData} = pt_120:write(12016, [?MOD_CROSS_LEGION, 0, RoleID, NPost]),
			lib_server_send:send_to_area_scene(Scene,PoolID,CopyId,X,Y,BinData),

			NStatus = lib_player:count_player_attribute(NStatus1),
            lib_player:send_attribute_change_notify(NStatus, ?NOTIFY_ATTR),

			{ok,NPost,NStatus};
		{false,Err}->
			{false,Err}
	end.

%%获得属性
get_attr(Status)->
    #player_status{
    	role_legion=RoleLegion,
    	figure = #figure{lv=Lv}
    }=Status,
    case Lv>=lib_module:get_open_lv(?MOD_CROSS_LEGION) of
    	true->
		    #role_legion{post=Post}=RoleLegion,
		    case data_legion:get_legion_post(Post) of
		       #base_legion_post{attr=Attrs}->
		            skip;
		        _->
		            Attrs = []
		    end,
		    Attrs;
		_->
			[]
	end.

get_all_task()->
	case get(legion_task) of
		Tasks when is_list(Tasks)->
			Tasks;
		_->
			[]
	end.

save_all_task(Tasks)->
	put(legion_task,Tasks).

%%任务初始化
init_task()->
	All = data_legion:get_all(),
	init_task(All,[]).

init_task([],Tasks)->
	Tasks;
init_task([H|T],Tasks)->
	case data_legion:get_task(H) of
		#base_legion_task{}->
			init_task(T,[#legion_task{id=H}|Tasks]);
		_->
			init_task(T,Tasks)
	end.

%%打包任务
pack_task([],Tasks)->
	Tasks;
pack_task([H|T],Tasks)->
	#legion_task{
		id = Id,
		bar = Bar,
		state = Status
	}=H,
	pack_task(T,[{Id,Bar,Status}|Tasks]).

%%任务触发
trigger_task(RoleID,Mod,SubMod) when is_integer(RoleID)->
	lib_player:apply_cast(RoleID,?APPLY_CAST_STATUS,?MODULE,trigger_task,[Mod,SubMod]);
trigger_task(Status,Mod,SubMod)->
	trigger_task(Status,Mod,SubMod,1).

trigger_task(Status,Mod,SubMod,Add)->
	#player_status{id=RoleID,role_legion=RoleLegion}=Status,
	Tasks = get_all_task(),
	{NTasks,Bin} = do_trigger_task(Tasks,Mod,SubMod,Add,[],<<>>),
	if
		NTasks =/= Tasks ->
			save_all_task(NTasks),
			update_role_legion(RoleID,task,RoleLegion);
		true -> skip
	end,
	Bin /= <<>> andalso lib_server_send:send_to_uid(RoleID,Bin),
	Status.

do_trigger_task([],_Mod,_SubMod,_Add,Tasks,Bin)->
	{Tasks,Bin};
do_trigger_task([H|T],Mod,SubMod,Add,Tasks,OBin)->
	#legion_task{
		id = Tid,
		bar = CurV,
		state = CurS
	}=H,
	case data_legion:get_task(Tid) of
		#base_legion_task{content={Mod,SubMod,Max}} when CurS =:= ?LEGION_INIT->
			NBar = min(CurV+Add,Max),
			NStatus = case NBar>=Max of
				true->
					?LEGION_FINISH;
				_->
					CurS
			end,
			NewH = H#legion_task{bar=NBar,state=NStatus},
			{ok,Bin} = pt_603:write(60302,[Tid,NBar,NStatus]),
			NBin = <<Bin/binary,OBin/binary>>,
			do_trigger_task(T,Mod,SubMod,Add,[NewH|Tasks],NBin);
		_->
			do_trigger_task(T,Mod,SubMod,Add,[H|Tasks],OBin)
	end.

check({check_advance_args,FetchDay,OpDay,All})->
	case lists:member(FetchDay,All) of
		true->
			case FetchDay=<OpDay of
				true->
					true;
				_->
					{false,?ERRCODE(err603_opday_not_enough)}
			end;
		_->
			{false,?ERRCODE(args_error)}
	end;

check({check_advance_fetch_done,FetchDay,DaysList})->
	case lists:member(FetchDay,DaysList) of
		true->
			{false,?ERRCODE(err603_cant_fetch_again)};
		_->
			true
	end;

check({check_post_cost,Config,Status})->
	#base_legion_post{cost=Cost} = Config,
	case lib_goods_api:cost_object_list_with_check(Status, Cost, kf_legion, ["legion post"]) of
		{true,NStatus,_}->
			{ok,NStatus};
		 {false,Err,_}->
		 	{false,Err}
	end;
check({check_post_max,Config})->
	#base_legion_post{next=Next} = Config,
	case Next /= 0 of
		true->
			true;
		_->
			{false,?ERRCODE(err603_post_max_now)}
	end;
check({check_last_rank,LRank})->
	case LRank /= 0 of
		true->
			true;
		_->
			{false,?ERRCODE(err603_try_again_tommorow)}
	end;
check({check_fetch_done,Status})->
	case Status == 0 of
		true->
			true;
		_->
			{false,?ERRCODE(err603_cant_fetch_again)}
	end;
check({check_click_rank,ARank})->
	case ARank=<data_legion:get(click_rank) of
		true->
			true;
		_->
			{false,?ERRCODE(err603_need_high_rank)}
	end;
check({check_click_done,Aim,CRidList})->
	CanClick = length(CRidList) < 5,
	case lists:member(Aim, CRidList) of
		true->
			{false,?ERRCODE(err603_cant_same_people)};
		_ when CanClick ->
			true;
		_->
			{false,?ERRCODE(err603_has_click_done)}
	end;
check({check_active,Config,CurPro})->
	#base_legion_active_award{active=Need}=Config,
	case CurPro>=Need of
		true->
			true;
		_->
			{false,?ERRCODE(err603_need_more_active)}
	end;
check({check_task_status,Task})->
	case Task of
		#legion_task{state=?LEGION_FINISH}->
			true;
		#legion_task{state=?LEGION_GOT}->
			{false,?ERRCODE(err603_cant_fetch_again)};
		_->
			{false,?ERRCODE(err603_need_finish_task)}
	end;
check({check_cfg,Config,Atom})->
	case is_record(Config,Atom) of
		true->
			true;
		_->
			{false,?ERRCODE(missing_config)}
	end;
check({check_post_power,Config,Power})->
	#base_legion_post{need=Need}=Config,
	case Power>=Need of
		true->
			true;
		_->
			{false,?ERRCODE(err144_power_unreach)}
	end;
check({check_is_get,CurDotList,Did})->
	case lists:member(Did,CurDotList) of
		true->
			{false,?ERRCODE(err603_cant_fetch_again)};
		_->
			true
	end.

%%榜单数据转化
to_legion_rank_role(Status,Score)->
	#player_status{
		figure=Figure,
		server_id = SerID,
		server_num = SerNum,
		guild = StatusGuild
	}=Status,
	#status_guild{name=GName}=StatusGuild,
	#figure{
        id = RoleID,
        name = Name,
        sex = Sex,
        career = Career,
        turn = Turn,
        vip_type = VType,
        vip = Vip,
        sup_vip = SupVipType,
        lv = Lv,
        power = Power,
        picture = Picture,
        picture_ver = PictureVer,
        profile_photo_id = ProfilePhotoId,
        dress_list = DressList,
        post = Post
    }=Figure,
    MinFigure = #figure{
        id = RoleID,
        name = Name,
        sex = Sex,
        career = Career,
        turn = Turn,
        vip_type = VType,
        vip = Vip,
        sup_vip = SupVipType,
        lv = Lv,
        power = Power,
        picture = Picture,
        picture_ver = PictureVer,
        profile_photo_id = ProfilePhotoId,
        dress_list = DressList,
        post = Post
    },
    Zone = czone_api:env_get_zone_id(),
    Fact = czone_api:env_get_faction(),
    #legion_rank{
    	id = RoleID,
    	zone = Zone,
    	fact = Fact,
    	server_id = SerID,
    	server_num = SerNum,
    	figure = MinFigure,
    	gname = GName,
    	score = Score,
    	time  = utime:unixtime()
    }.

%%打包榜单
pack_rank_data([], DataList) ->
    DataList;
pack_rank_data([RankRole | T], DataList) ->
    #legion_rank{
        id = RoleId, gname = GName,
        server_num = SerNum,score = Score,
        rank = Ranking,figure=Figure
    } = RankRole,
    %% 排名大于0才是真正上榜
    #figure{post=Post}=Figure,
    DataList2 = case Ranking > 0 of
        true -> [{Ranking, RoleId, SerNum, Figure, GName, Post, Score} | DataList];
        false -> DataList
    end,
    pack_rank_data(T, DataList2).

%%打包榜单
pack_last_rank_data([], DataList) ->
    DataList;
pack_last_rank_data([RankRole | T], DataList) ->
    #legion_rank{
        id = RoleId,server_num = SerNum,score = Score,
        rank = Ranking,figure=Figure
    } = RankRole,
    #figure{vip=Vip,sup_vip=SVip,name=Name}=Figure,
    %% 排名大于0才是真正上榜
    DataList2 = case Ranking > 0 of
        true -> [{Ranking, RoleId, Vip, SVip,SerNum, Name, Score} | DataList];
        false -> DataList
    end,
    pack_last_rank_data(T, DataList2).

%%历史名单
pack_history_director(_,[],DataList)->
	DataList;
pack_history_director(OpTy,[H|T],DataList)->
	#time_history{time=Issue,servers=ServerLogs}=H,
	LogList = pack_server_logs(OpTy,ServerLogs,[]),
	pack_history_director(OpTy,T,[{Issue,LogList}|DataList]).

pack_server_logs(_OpTy,[],LogList)->
	LogList;
pack_server_logs(OpTy,[H|T],LogList)->
	#server_log{server_num=SerNum,logs=Logs}=H,
	LogsL = case OpTy of
		0->
			[{Rid,Pos,Time,Figure}||#history_role{id=Rid,pos=Pos,time=Time,figure=Figure}<-Logs];
		1->
		    [{Rid,Pos,Time,Figure}||#history_role{id=Rid,pos=Pos,time=Time,figure=Figure}<-Logs,Pos=<3];
		2->
			[{Rid,Pos,Time,Figure}||#history_role{id=Rid,pos=Pos,time=Time,figure=Figure}<-Logs,Pos>3]
	end,
	pack_server_logs(OpTy,T,[{SerNum,LogsL}|LogList]).

%%全保存
save_role_legion(RoleID,RoleLegion)->
	#role_legion{
		post = Post,        %%军衔
		score = Score,       %%升级使用军功

		rank_score = RankScore,  %%榜单军功值 随赛季重置
		arms = Arms,        %%军备值 随赛季重置

		process= Pro,      %%活跃进度
		dot_list  = DotList1,       %%已领取的节点id列表

		click_role = CRole1,  %%膜拜人
		day_award  = DStatus,  %%每日领取情况

		ltime = LTime        %%上次更新
		,post_utime = UTime
		,advance_awards = DaysList
	}=RoleLegion,
	Tasks0 = get_all_task(),
	Tasks1 = [{Id,Bar,State}||#legion_task{id=Id,bar=Bar,state=State}<-Tasks0],
	Tasks  = util:term_to_bitstring(Tasks1),
	DotList  = util:term_to_bitstring(DotList1),
	CRole  = util:term_to_bitstring(CRole1),
	StrDaysList  = util:term_to_bitstring(DaysList),
	Sql = io_lib:format(?SQL_ROLE_LEGION_INS,[RoleID,Post,Score,RankScore,Arms,Pro,DotList,CRole,DStatus,Tasks,LTime,UTime,StrDaysList]),
	db:execute(Sql).

update_role_legion(RoleID,task,RoleLegion)->
	#role_legion{process=Pro, ltime=LTime}=RoleLegion,
	Tasks0 = get_all_task(),
	Tasks1 = [{Id,Bar,State}||#legion_task{id=Id,bar=Bar,state=State}<-Tasks0],
	Tasks  = util:term_to_bitstring(Tasks1),
	Sql = io_lib:format(?SQL_ROLE_LEGION_UPDATE1,[Pro,Tasks,LTime,RoleID]),
	db:execute(Sql);
update_role_legion(RoleID,score,RoleLegion)->
	#role_legion{score=Score,rank_score=RankScore,ltime=LTime,post_utime = PostUTime}=RoleLegion,
	Sql = io_lib:format(?SQL_ROLE_LEGION_UPDATE2,[RankScore,Score,LTime,PostUTime,RoleID]),
	db:execute(Sql);
update_role_legion(RoleID,post,RoleLegion)->
	#role_legion{post=Post,score=Score,post_utime = PostUTime}=RoleLegion,
	Sql = io_lib:format(?SQL_ROLE_LEGION_UPDATE7,[Post,Score,PostUTime,RoleID]),
	db:execute(Sql);
update_role_legion(RoleID,awards,RoleLegion)->
	#role_legion{process=Pro,dot_list=DotList1,day_award=DStatus,ltime=LTime}=RoleLegion,
	DotList  = util:term_to_bitstring(DotList1),
	Sql = io_lib:format(?SQL_ROLE_LEGION_UPDATE3,[Pro,DotList,DStatus,LTime,RoleID]),
	db:execute(Sql);
update_role_legion(RoleID,click,RoleLegion)->
	#role_legion{click_role=CRole1,ltime=LTime}=RoleLegion,
	CRole  = util:term_to_bitstring(CRole1),
	Sql = io_lib:format(?SQL_ROLE_LEGION_UPDATE4,[CRole,LTime,RoleID]),
	db:execute(Sql);
update_role_legion(RoleID,arms,RoleLegion)->
	#role_legion{arms=Arms}=RoleLegion,
	Sql = io_lib:format(?SQL_ROLE_LEGION_UPDATE5,[Arms,RoleID]),
	db:execute(Sql);
update_role_legion(RoleID,reset,_RoleLegion)->
	Sql = io_lib:format(?SQL_ROLE_LEGION_UPDATE6,[0,0,RoleID]),
	db:execute(Sql);
update_role_legion(RoleID,advance_awards,RoleLegion)->
	#role_legion{advance_awards=DaysList}=RoleLegion,
	StrDaysList  = util:term_to_bitstring(DaysList),
	Sql = io_lib:format(?SQL_ROLE_LEGION_UPDATE8,[StrDaysList,RoleID]),
	db:execute(Sql);
update_role_legion(RoleID,_,RoleLegion)->
	save_role_legion(RoleID,RoleLegion).