%%%-------------------------------------------------------------------
%%% @doc    社团 - 感谢信
%%% Module  : guild_thank.erl
%%% Created : 2020-08-17
%%% @Author : tyl
%%%-------------------------------------------------------------------
-module(guild_thank).

-include("server.hrl").
-include("predefine.hrl").
-include("def_goods.hrl").
-include("def_module.hrl").
-include("role.hrl").
-include("figure.hrl").
-include("rec_dress_up.hrl").
-include("guild.hrl").
-include("guild_support.hrl").
-include("goods.hrl").
-include("errcode.hrl").
-include("common.hrl").

%% API
-export([
	login_load_data/1

	%% ----- 通用 -----
	,get_thank_packet_info/1
	,get_log_info/1
	,thank_member/4
	,receive_reward/3

	%% ----- 协助 -----
	,add_thank_packet/7                     %% 请求方

	,add_thank_support_log_on_player/2      %% 接单方

	,get_support_thank_list/1               %% 内存数据处理
	,get_support_log_list/1
	,save_support_thank_list/2
	,save_support_log_list/2

	%% ----- 拼单 -----
	,add_order_thank_packet/7              %% 发起方

	,add_thank_order_log_on_player/2        %% 接单方

	,get_order_thank_list/1                 %% 内存数据处理
	,get_order_log_list/1
	,save_order_thank_list/2
	,save_order_log_list/2

	,get_reward_cfg/2

]).

%% 登录加载数据
login_load_data(RoleId) ->
	init_dict_data(RoleId),
	ok.

init_dict_data(RoleId) ->
	%% 协助感谢信
	DbThankList = db_select_support_thank(RoleId),
	GuildThankList = make_support_thank_list(DbThankList, []),
	save_support_thank_list(RoleId, GuildThankList),
	%% 协助记录
	DbLogList = db_select_support_log(RoleId),
	GuildLogList = make_support_log_list(DbLogList, []),
	save_support_log_list(RoleId, GuildLogList),

	%% 拼单感谢信
	DbOrderThankList = db_select_order_thank(RoleId),
	GuildOrderThankList = make_order_thank_list(DbOrderThankList, []),
	save_order_thank_list(RoleId, GuildOrderThankList),
	%% 拼单记录
	DbThankLogList = db_select_order_log(RoleId),
	GuildOrderLogList = make_order_log_list(DbThankLogList, []),
	save_order_log_list(RoleId, GuildOrderLogList),

	ok.

make_support_thank_list([], GuildThankList) -> GuildThankList;
make_support_thank_list([Info|L], RoleThankList) ->
	case Info of
		[SupportId, _GuildId, AskId, SupportCfgId, RoleListStr, ContentStr, IsSend, Time] ->
			RoleList = util:bitstring_to_term(RoleListStr),
			Content  = util:bitstring_to_term(ContentStr),
			ThankPacket = #guild_thank_packet{
				support_id = SupportId,
				ask_id     = AskId,
				role_list  = RoleList,
				content    = Content,
				is_send    = IsSend,
				time       = Time,
				support_cfg_id = SupportCfgId
			},
			NewRoleThankList = [ThankPacket|RoleThankList],
			make_support_thank_list(L, NewRoleThankList);
		_ ->
			make_support_thank_list(L, RoleThankList)
	end.

make_support_log_list([], RoleLogList) -> RoleLogList;
make_support_log_list([Info|L], RoleLogList) ->
	case Info of
		[SupportId, _GuildId, _RoleId, AskId, SupportCfgId, ContentStr, ChatMsg, IsReceive, Time] ->
			Content  = util:bitstring_to_term(ContentStr),
			ThankLog = #guild_thank_log{
				support_id = SupportId,
				ask_id     = AskId,
				content    = Content,
				chat_msg   = ChatMsg,
				is_receive = IsReceive,
				time       = Time,
				support_cfg_id = SupportCfgId
			},
			NewRoleLogList = [ThankLog|RoleLogList],
			make_support_log_list(L, NewRoleLogList);
		_ ->
			make_support_log_list(L, RoleLogList)
	end.

make_order_thank_list([], GuildThankList) -> GuildThankList;
make_order_thank_list([Info|L], RoleThankList) ->
	case Info of
		[OrderId, _GuildId, AskId, CfgId, RoleListStr, ContentStr, IsSend, Time] ->
			RoleList = util:bitstring_to_term(RoleListStr),
			Content  = util:bitstring_to_term(ContentStr),
			ThankPacket = #guild_order_thank_packet{
				order_id   = OrderId,
				ask_id     = AskId,
				role_list  = RoleList,
				content    = Content,
				is_send    = IsSend,
				time       = Time,
				order_cfg_id = CfgId
			},
			NewRoleThankList = [ThankPacket|RoleThankList],
			make_order_thank_list(L, NewRoleThankList);
		_ ->
			make_order_thank_list(L, RoleThankList)
	end.

make_order_log_list([], RoleLogList) -> RoleLogList;
make_order_log_list([Info|L], RoleLogList) ->
	case Info of
		[OrderId, _GuildId, _RoleId, AskId, CfgId, ContentStr, ChatMsg, IsReceive, Time] ->
			Content  = util:bitstring_to_term(ContentStr),
			ThankLog = #guild_order_thank_log{
				order_id   = OrderId,
				ask_id     = AskId,
				content    = Content,
				chat_msg   = ChatMsg,
				is_receive = IsReceive,
				time       = Time,
				order_cfg_id = CfgId
			},
			NewRoleLogList = [ThankLog|RoleLogList],
			make_order_log_list(L, NewRoleLogList);
		_ ->
			make_order_log_list(L, RoleLogList)
	end.

%% 记录奖励红包(需要分在线和离线讨论)
add_thank_packet(Player, GuildId, SupportId, AskerId, SupportRoleList, SupportCfgId, SupportContent) ->
	NowTime = utime:unixtime(),
	Pid = misc:get_player_process(AskerId),
	case is_pid(Pid) andalso misc:is_process_alive(Pid) of
		true ->
			ThankList = get_support_thank_list(AskerId),
			GuildThank = #guild_thank_packet{
				ask_id = AskerId, support_id = SupportId, support_cfg_id = SupportCfgId,
				role_list = SupportRoleList, content = SupportContent, time = NowTime
			},
			db_save_support_thank(SupportId, GuildId, AskerId, SupportCfgId, SupportRoleList, SupportContent, 0, NowTime),
			NewThankList = [GuildThank|ThankList],
			save_support_thank_list(AskerId, NewThankList),
			OrderThankList = get_order_thank_list(AskerId),
			NotSendList  = [1||#guild_thank_packet{is_send = TIsSend}<-NewThankList, TIsSend == 0],
			NotSendList1 = [1||#guild_order_thank_packet{is_send = TIsSend1}<-OrderThankList, TIsSend1 == 0],
			{ok, Bin1} = pt_400:write(40056, [2, lists:sum(NotSendList++NotSendList1)]),
			{ok, Bin2} = pt_400:write(40048, [1, 1, SupportId]),
			Bin = <<Bin1/binary, Bin2/binary>>,
			%% 推送给请求者
			lib_server_send:send_to_uid(AskerId, Bin);
		_ ->
			db_save_support_thank(SupportId, GuildId, AskerId, SupportCfgId, SupportRoleList, SupportContent, 0, NowTime)
	end,
	{ok, Player}.

%% 记录拼单奖励红包(需要分在线和离线讨论)
add_order_thank_packet(Player, GuildId, OrderId, AskerId, OrderRoleList, CfgId, OrderContent) ->
	NowTime = utime:unixtime(),
	Pid = misc:get_player_process(AskerId),
	case is_pid(Pid) andalso misc:is_process_alive(Pid) of
		true ->
			OrderThankList = get_order_thank_list(AskerId),
			GuildOrderThank = #guild_order_thank_packet{
				ask_id = AskerId, order_id = OrderId, order_cfg_id = CfgId,
				role_list = OrderRoleList, content = OrderContent, time = NowTime
			},
			db_save_order_thank(OrderId, GuildId, AskerId, CfgId, OrderRoleList, OrderContent, 0, NowTime),
			NewOrderThankList = [GuildOrderThank|OrderThankList],
			save_order_thank_list(AskerId, NewOrderThankList),
			NotSendList = [1||#guild_order_thank_packet{is_send = TIsSend}<-NewOrderThankList, TIsSend == 0],
			SupportThankList = get_support_thank_list(AskerId),
			NotSendList1 = [1||#guild_thank_packet{is_send = TIsSend1}<-SupportThankList, TIsSend1 == 0],
			{ok, Bin1} = pt_400:write(40056, [2, lists:sum(NotSendList++NotSendList1)]),
			{ok, Bin2} = pt_400:write(40048, [2, 1, OrderId]),
			Bin = <<Bin1/binary, Bin2/binary>>,
			%% 推送给请求者
			lib_server_send:send_to_uid(AskerId, Bin);
		_ ->
			db_save_support_thank(OrderId, GuildId, AskerId, CfgId, OrderRoleList, OrderContent, 0, NowTime)
	end,
	{ok, Player}.

%% 获取所有奖励红包信息
get_thank_packet_info(#player_status{id = RoleId}) ->
	%% 协助
	SupportThankList = get_support_thank_list(RoleId),
	SupportPackList  = pack_support_thank_packet(SupportThankList, []),

	%% 拼单
	OrderThankList = get_order_thank_list(RoleId),
	OrderPackList  = pack_order_thank_packet(OrderThankList, []),

	lib_server_send:send_to_uid(RoleId, pt_400, 40068, [SupportPackList ++ OrderPackList]),
	ok.

pack_support_thank_packet([], PackList) -> PackList;
pack_support_thank_packet([#guild_thank_packet{} = GuildThank|L], PackList) ->
	#guild_thank_packet{support_id = SupportId, support_cfg_id = SupportCfgId,
		content = Content, role_list = RoleList, is_send = IsSend
	} = GuildThank,
	case Content of
		{_, {_, BossId}} -> ExtraValue = [{1, BossId}];
		{_, BossId} -> ExtraValue = [{1, BossId}];
		_ -> ExtraValue = []
	end,
	F = fun(RoleId, TList) ->
		case lib_role:get_role_show(RoleId) of
			#ets_role_show{figure = Figure} -> ok;
			_ -> Figure = #figure{}
		end,
		#figure{name = Name, sex = Sex, profile_photo_id = Picture,
			vip = Vip, sup_vip = SupVip, dress_list = DressList
		} = Figure,
		case lists:keyfind(?DRESS_UP_FRAME, 1, DressList) of
			{_, FrameId} -> ok;
			_ -> FrameId = 0
		end,
		RoleInfo = {RoleId, Name, Sex, Picture, FrameId, Vip, SupVip},
		[RoleInfo|TList]
	end,
	RoleInfoList = lists:foldl(F, [], RoleList),
	Info = {?THANK_TYPE_SUPPORT, SupportId, SupportCfgId, ExtraValue, RoleInfoList, IsSend},
	pack_support_thank_packet(L, [Info|PackList]);
pack_support_thank_packet([_|L], PackList) ->
	pack_support_thank_packet(L, PackList).

pack_order_thank_packet([], PackList) -> PackList;
pack_order_thank_packet([#guild_order_thank_packet{} = GuildThank|L], PackList) ->
	#guild_order_thank_packet{order_id = OrderId, order_cfg_id = OrderCfgId,
		content = Content, role_list = RoleList, is_send = IsSend
	} = GuildThank,
	case Content of
		{_, {_, BossId}} -> ExtraValue = [{1, BossId}];
		{_, BossId} -> ExtraValue = [{1, BossId}];
		_ -> ExtraValue = []
	end,
	F = fun(RoleId, TList) ->
		case lib_role:get_role_show(RoleId) of
			#ets_role_show{figure = Figure} -> ok;
			_ -> Figure = #figure{}
		end,
		#figure{name = Name, sex = Sex, profile_photo_id = Picture,
			vip = Vip, sup_vip = SupVip, dress_list = DressList
		} = Figure,
		case lists:keyfind(?DRESS_UP_FRAME, 1, DressList) of
			{_, FrameId} -> ok;
			_ -> FrameId = 0
		end,
		RoleInfo = {RoleId, Name, Sex, Picture, FrameId, Vip, SupVip},
		[RoleInfo|TList]
	    end,
	RoleInfoList = lists:foldl(F, [], RoleList),
	Info = {?THANK_TYPE_ORDER, OrderId, OrderCfgId, ExtraValue, RoleInfoList, IsSend},
	pack_order_thank_packet(L, [Info|PackList]);
pack_order_thank_packet([_|L], PackList) ->
	pack_order_thank_packet(L, PackList).

%% -------------------------------------------------------------------
%% @doc 请求者发送感谢信 Type: 1-协助 2-拼单 @end
%% -------------------------------------------------------------------
thank_member(Player, Type, UniqueId, ChatMsg) ->
	#player_status{id = RoleId, guild = StatusGuild} = Player,
	#status_guild{id = GuildId} = StatusGuild,
	case Type of
		?THANK_TYPE_SUPPORT ->
			thank_support_member(RoleId, GuildId, UniqueId, ChatMsg);
		_ ->
			thank_order_member(RoleId, GuildId, UniqueId, ChatMsg)
	end,
	ok.

thank_support_member(RoleId, GuildId, SupportId, ChatMsg) ->
	ThankList = get_support_thank_list(RoleId),
	case lists:keyfind(SupportId, #guild_thank_packet.support_id, ThankList) of
		#guild_thank_packet{
			support_cfg_id = SupportCfgId, role_list = RoleList, content = Content, is_send = IsSend
		} = ThankPacket ->
			case IsSend of
				1 ->
					lib_server_send:send_to_uid(RoleId, pt_400, 40050,
						[?ERRCODE(err400_has_thank)]
					);
				_ ->
					%% 请求者自己领取奖励，协助者收到感谢信
					after_thank_support_member(RoleId, SupportCfgId),
					db_update_support_thank(SupportId, RoleId),
					add_thank_support_log(GuildId, SupportId, RoleId, RoleList, SupportCfgId, Content, ChatMsg),
					NewThankPacket = ThankPacket#guild_thank_packet{is_send = 1},
					NewThankList = lists:keystore(SupportId, #guild_thank_packet.support_id, ThankList, NewThankPacket),
					save_support_thank_list(RoleId, NewThankList),
					OrderThankList = get_order_thank_list(RoleId),
					NotSendList  = [1||#guild_thank_packet{is_send = TIsSend}<-NewThankList, TIsSend == 0],
					NotSendList1 = [1||#guild_order_thank_packet{is_send = TIsSend1}<-OrderThankList, TIsSend1 == 0],
					{ok, Bin1} = pt_400:write(40056, [2, lists:sum(NotSendList++NotSendList1)]),
					{ok, Bin2} = pt_400:write(40050, [?SUCCESS]),
					Bin = <<Bin1/binary, Bin2/binary>>,
					lib_server_send:send_to_uid(RoleId, Bin)
			end;
		_ ->
			lib_server_send:send_to_uid(RoleId, pt_400, 40050,
				[?ERRCODE(err400_support_thank_overdue)]
			)
	end.

thank_order_member(RoleId, GuildId, OrderId, ChatMsg) ->
	ThankList = get_order_thank_list(RoleId),
	case lists:keyfind(OrderId, #guild_order_thank_packet.order_id, ThankList) of
		#guild_order_thank_packet{
			order_cfg_id = OrderCfgId, role_list = RoleList, content = Content, is_send = IsSend
		} = ThankPacket ->
			case IsSend of
				1 ->
					lib_server_send:send_to_uid(RoleId, pt_400, 40050,
						[?ERRCODE(err400_has_thank)]
					);
				_ ->
					%% 请求者自己领取奖励，接单者收到感谢信
					after_thank_order_member(RoleId, OrderCfgId),
					db_update_order_thank(OrderId, RoleId),
					add_thank_order_log(GuildId, OrderId, RoleId, RoleList, OrderCfgId, Content, ChatMsg),
					NewThankPacket = ThankPacket#guild_order_thank_packet{is_send = 1},
					NewThankList = lists:keystore(OrderId, #guild_order_thank_packet.order_id, ThankList, NewThankPacket),
					save_order_thank_list(RoleId, NewThankList),
					SupportThankList = get_support_thank_list(RoleId),
					NotSendList  = [1||#guild_order_thank_packet{is_send = TIsSend}<-NewThankList, TIsSend == 0],
					NotSendList1 = [1||#guild_thank_packet{is_send = TIsSend1}<-SupportThankList, TIsSend1 == 0],
					{ok, Bin1} = pt_400:write(40056, [2, lists:sum(NotSendList++NotSendList1)]),
					{ok, Bin2} = pt_400:write(40050, [?SUCCESS]),
					Bin = <<Bin1/binary, Bin2/binary>>,
					lib_server_send:send_to_uid(RoleId, Bin)
			end;
		_ ->
			lib_server_send:send_to_uid(RoleId, pt_400, 40050,
				[?ERRCODE(err400_support_thank_overdue)]
			)
	end.

%% ----------------------------------------
%% @doc 感谢协助相关处理 @end
%% ----------------------------------------
after_thank_support_member(AskerId, CfgId) ->
	%% 请求者领取感谢奖励
	case data_guild:get_guild_support_cfg(CfgId) of
		#base_guild_support{thank_reward = TankReward} ->
			Produce = #produce{
				title = utext:get(13), content = utext:get(14),
				type = thank_reward, reward = TankReward,
				show_tips = 1, remark = ""
			},
			lib_goods_api:send_reward_with_mail(AskerId, Produce, ?MOD_GUILD),
			lib_achievement_api:async_event(AskerId, lib_achievement_api, guild_thank_event, 1);
		_ ->
			lib_server_send:send_to_uid(AskerId, pt_400, 40000, ?ERRCODE(err400_support_cfgid_not_exits))
	end.

%% 增加感谢记录
add_thank_support_log(GuildId, SupportId, AskerId, SupportRoleList, SupportCfgId, SupportContent, ChatMsg) ->
	NowTime = utime:unixtime(),
	%% 批量写库
	batch_save_support_log(
		GuildId, SupportId, AskerId, SupportRoleList, SupportCfgId, SupportContent, ChatMsg, NowTime
	),
	LogInfo = {SupportId, AskerId, SupportCfgId, SupportContent, ChatMsg},
	F = fun(RoleId) ->
		PId = misc:get_player_process(RoleId),
		case is_pid(PId) andalso misc:is_process_alive(PId) of
			true -> lib_player:apply_cast(RoleId, ?APPLY_CAST_STATUS, ?MODULE, add_thank_support_log_on_player, [LogInfo]);
			_ -> ignore
		end end,
	lists:map(F, SupportRoleList),
	ok.

add_thank_support_log_on_player(#player_status{id = RoleId} = Player, LogInfo) ->
	{SupportId, AskerId, SupportCfgId, SupportContent, ChatMsg} = LogInfo,
	OrderLogList = get_order_log_list(RoleId),
	LogList = get_support_log_list(RoleId),
	NowTime = utime:unixtime(),
	GuildLog = #guild_thank_log{
		ask_id = AskerId, support_cfg_id = SupportCfgId, chat_msg = ChatMsg,
		support_id = SupportId, content = SupportContent, time = NowTime
	},
	NewLogList = [GuildLog|LogList],
	save_support_log_list(RoleId, NewLogList),
	NotReceiveList  = [1||#guild_thank_log{is_receive = TIsReceive}<-NewLogList, TIsReceive == 0],
	NotReceiveList1 = [1||#guild_order_thank_log{is_receive = TIsReceive1}<-OrderLogList, TIsReceive1 == 0],
	{ok, Bin1} = pt_400:write(40056, [3, lists:sum(NotReceiveList++NotReceiveList1)]),
	{ok, Bin2} = pt_400:write(40048, [1, 2, SupportId]),
	Bin = <<Bin1/binary, Bin2/binary>>,
	lib_server_send:send_to_uid(RoleId, Bin),
	{ok, Player}.

%% ----------------------------------------
%% @doc 感谢拼单相关处理 @end
%% ----------------------------------------
after_thank_order_member(AskerId, CfgId) ->
	%% 请求者领取感谢奖励
	case data_guild:get_order_base(CfgId) of
		#base_guild_order{thank_reward = TankReward} ->
			Produce = #produce{
				title = utext:get(13), content = utext:get(14),
				type = thank_reward, reward = TankReward,
				show_tips = 1, remark = ""
			},
			lib_goods_api:send_reward_with_mail(AskerId, Produce, ?MOD_GUILD),
			lib_achievement_api:async_event(AskerId, lib_achievement_api, guild_thank_event, 1);
		_ ->
			lib_server_send:send_to_uid(AskerId, pt_400, 40000, ?ERRCODE(err400_support_cfgid_not_exits))
	end.

%% 增加感谢记录
add_thank_order_log(GuildId, OrderId, AskerId, RoleList, CfgId, OrderContent, ChatMsg) ->
	NowTime = utime:unixtime(),
	%% 批量写库
	batch_save_order_log(
		GuildId, OrderId, AskerId, RoleList, CfgId, OrderContent, ChatMsg, NowTime
	),
	LogInfo = {OrderId, AskerId, CfgId, OrderContent, ChatMsg},
	F = fun(RoleId) ->
		PId = misc:get_player_process(RoleId),
		case is_pid(PId) andalso misc:is_process_alive(PId) of
			true -> lib_player:apply_cast(RoleId, ?APPLY_CAST_STATUS, ?MODULE, add_thank_order_log_on_player, [LogInfo]);
			_ -> ignore
		end end,
	lists:map(F, RoleList),
	ok.

add_thank_order_log_on_player(#player_status{id = RoleId} = Player, LogInfo) ->
	{OrderId, AskerId, CfgId, OrderContent, ChatMsg} = LogInfo,
	SupportLogList = get_support_log_list(RoleId),
	OrderLogList   = get_order_log_list(RoleId),
	NowTime = utime:unixtime(),
	GuildOrderLog = #guild_order_thank_log{
		ask_id = AskerId, order_cfg_id = CfgId, chat_msg = ChatMsg,
		order_id = OrderId, content = OrderContent, time = NowTime
	},
	NewOrderLogList = [GuildOrderLog|OrderLogList],
	save_order_log_list(RoleId, NewOrderLogList),
	NotReceiveOrderList   = [1||#guild_order_thank_log{is_receive = TIsReceive}<-NewOrderLogList, TIsReceive == 0],
	NotReceiveSupportList = [1||#guild_thank_log{is_receive = TIsReceive1}<-SupportLogList, TIsReceive1 == 0],
	{ok, Bin1} = pt_400:write(40056, [3, lists:sum(NotReceiveOrderList++NotReceiveSupportList)]),
	{ok, Bin2} = pt_400:write(40048, [2, 2, OrderId]),
	Bin = <<Bin1/binary, Bin2/binary>>,
	lib_server_send:send_to_uid(RoleId, Bin),
	lib_achievement_api:async_event(RoleId, lib_achievement_api, support_event, 1),
	{ok, Player}.

%% -------------------------------------------------------------------------------------
%% @doc 获取所有感谢信信息 @end
get_log_info(#player_status{id = RoleId}) ->
	%% 协助
	SupportLogList  = get_support_log_list(RoleId),
	SupportPackList = pack_support_thank_log(SupportLogList, []),

	%% 拼单
	OrderLogList  = get_order_log_list(RoleId),
	OrderPackList = pack_order_thank_log(OrderLogList, []),

	lib_server_send:send_to_uid(RoleId, pt_400, 40069, [SupportPackList++OrderPackList]),
	ok.

pack_support_thank_log([], PackList) -> PackList;
pack_support_thank_log([#guild_thank_log{} = GuildThank|L], PackList) ->
	#guild_thank_log{support_id = SupportId, support_cfg_id = SupportCfgId,
		ask_id = AskId, content = Content, chat_msg = ChatMsg, is_receive = IsRecv
	} = GuildThank,
	case Content of
		{_, {_, BossId}} -> ExtraValue = [{1, BossId}];
		{_, BossId} -> ExtraValue = [{1, BossId}];
		_ -> ExtraValue = []
	end,
	case lib_role:get_role_show(AskId) of
		#ets_role_show{figure = Figure} -> ok;
		_ -> Figure = #figure{}
	end,
	#figure{name = Name, sex = Sex, profile_photo_id = Picture,
		dress_list = DressList, vip = Vip, sup_vip = SupVip
	} = Figure,
	case lists:keyfind(?DRESS_UP_FRAME, 1, DressList) of
		{_, FrameId} -> ok;
		_ -> FrameId = 0
	end,
	Info = {?THANK_TYPE_SUPPORT, SupportId, SupportCfgId, ExtraValue, ChatMsg,
		AskId, Name, Sex, Picture, FrameId, Vip, SupVip, IsRecv
	},
	pack_support_thank_log(L, [Info|PackList]);
pack_support_thank_log([_|L], PackList) ->
	pack_support_thank_log(L, PackList).

pack_order_thank_log([], PackList) -> PackList;
pack_order_thank_log([#guild_order_thank_log{} = GuildThankLog|L], PackList) ->
	#guild_order_thank_log{order_id = OrderId, order_cfg_id = OrderCfgId,
		ask_id = AskId, content = Content, chat_msg = ChatMsg, is_receive = IsRecv
	} = GuildThankLog,
	case Content of
		{_, {_, BossId}} -> ExtraValue = [{1, BossId}];
		{_, BossId} -> ExtraValue = [{1, BossId}];
		_ -> ExtraValue = []
	end,
	case lib_role:get_role_show(AskId) of
		#ets_role_show{figure = Figure} -> ok;
		_ -> Figure = #figure{}
	end,
	#figure{name = Name, sex = Sex, profile_photo_id = Picture,
		dress_list = DressList, vip = Vip, sup_vip = SupVip
	} = Figure,
	case lists:keyfind(?DRESS_UP_FRAME, 1, DressList) of
		{_, FrameId} -> ok;
		_ -> FrameId = 0
	end,
	Info = {?THANK_TYPE_ORDER, OrderId, OrderCfgId, ExtraValue, ChatMsg,
		AskId, Name, Sex, Picture, FrameId, Vip, SupVip, IsRecv
	},
	pack_order_thank_log(L, [Info|PackList]);
pack_order_thank_log([_|L], PackList) ->
	pack_order_thank_log(L, PackList).

%% -------------------------------------------------------------------------------------
%% @doc 收取答谢 @end
receive_reward(#player_status{id = RoleId}, Type, UniqueId) ->
	case Type of
		1 -> receive_support_reward(RoleId, UniqueId);
		_ -> receive_order_reward(RoleId, UniqueId)
	end.

%% 领取协助答谢
receive_support_reward(RoleId, SupportId) ->
	LogList = get_support_log_list(RoleId),
	case lists:keyfind(SupportId, #guild_thank_log.support_id, LogList) of
		#guild_thank_log{
			ask_id = AskId, support_cfg_id = CfgId, is_receive = IsReceive
		} = ThankLog ->
			case IsReceive of
				1 -> lib_server_send:send_to_uid(RoleId, pt_400, 40000, ?ERRCODE(err400_support_thank_has_receive));
				_ ->
					case data_guild:get_guild_support_cfg(CfgId) of
						#base_guild_support{support_reward = GiftList} -> ok;
						_ -> GiftList = []
					end,
					case lib_role:get_role_show(AskId) of
						#ets_role_show{figure = Figure} -> skip;
						_ -> Figure = #figure{}
					end,
					case GiftList =/= [] of
						true ->
							Produce = #produce{
								title = utext:get(4000008), content = utext:get(4000009, [Figure#figure.name]),
								type = support_reward, reward = GiftList,
								show_tips = 1, remark = ""
							},
							lib_goods_api:send_reward_with_mail(RoleId, Produce, ?MOD_GUILD),
							NewThankLog = ThankLog#guild_thank_log{is_receive = 1},
							db_update_support_log(SupportId, RoleId),
							NewLogList = lists:keystore(SupportId, #guild_thank_log.support_id, LogList, NewThankLog),
							save_support_log_list(RoleId, NewLogList),
							OrderLogList = get_order_log_list(RoleId),
							NotReceiveList  = [1||#guild_thank_log{is_receive = TIsReceive}<-NewLogList, TIsReceive == 0],
							NotReceiveList1 = [1||#guild_order_thank_log{is_receive = TIsReceive1}<-OrderLogList, TIsReceive1 == 0],
							{ok, Bin1} = pt_400:write(40056, [3, lists:sum(NotReceiveList++NotReceiveList1)]),
							{ok, Bin2} = pt_400:write(40070, [?SUCCESS]),
							Bin = <<Bin1/binary, Bin2/binary>>,
							lib_server_send:send_to_uid(RoleId, Bin);
						_ ->
							lib_server_send:send_to_uid(RoleId, pt_400, 40000, ?ERRCODE(err400_support_reward_not_exits))
					end
			end;
		_ ->
			lib_server_send:send_to_uid(RoleId, pt_400, 40000, ?ERRCODE(err400_support_thank_has_receive))
	end.

%% 领取拼单答谢
receive_order_reward(RoleId, OrderId) ->
	LogList = get_order_log_list(RoleId),
	case lists:keyfind(OrderId, #guild_order_thank_log.order_id, LogList) of
		#guild_order_thank_log{
			ask_id = AskId, order_cfg_id = CfgId, is_receive = IsReceive
		} = ThankLog ->
			case IsReceive of
				1 -> lib_server_send:send_to_uid(RoleId, pt_400, 40000, ?ERRCODE(err400_support_thank_has_receive));  %% todo
				_ ->
					case data_guild:get_order_base(CfgId) of
						#base_guild_order{order_reward = GiftList} -> ok;
						_ -> GiftList = []
					end,
					case lib_role:get_role_show(AskId) of
						#ets_role_show{figure = Figure} -> skip;
						_ -> Figure = #figure{}
					end,
					case GiftList =/= [] of
						true ->
							Produce = #produce{
								title = utext:get(4000008), content = utext:get(4000009, [Figure#figure.name]),
								type = order_reward, reward = GiftList,
								show_tips = 1, remark = ""
							},
							lib_goods_api:send_reward_with_mail(RoleId, Produce, ?MOD_GUILD),
							NewThankLog = ThankLog#guild_order_thank_log{is_receive = 1},
							db_update_order_log(OrderId, RoleId),
							NewLogList = lists:keystore(OrderId, #guild_order_thank_log.order_id, LogList, NewThankLog),
							save_order_log_list(RoleId, NewLogList),
							SupportLogList = get_support_log_list(RoleId),
							NotReceiveList  = [1||#guild_order_thank_log{is_receive = TIsReceive}<-NewLogList, TIsReceive == 0],
							NotReceiveList1 = [1||#guild_thank_log{is_receive = TIsReceive1}<-SupportLogList, TIsReceive1 == 0],
							{ok, Bin1} = pt_400:write(40056, [3, lists:sum(NotReceiveList++NotReceiveList1)]),
							{ok, Bin2} = pt_400:write(40070, [?SUCCESS]),
							Bin = <<Bin1/binary, Bin2/binary>>,
							lib_server_send:send_to_uid(RoleId, Bin);
						_ ->
							lib_server_send:send_to_uid(RoleId, pt_400, 40000, ?ERRCODE(err400_support_reward_not_exits))  %% todo
					end
			end;
		_ ->
			lib_server_send:send_to_uid(RoleId, pt_400, 40000, ?ERRCODE(err400_support_thank_has_receive))
	end.

%% -------------------------------------------------------------------------
%% @doc 旧的逻辑(礼包为载体进行感谢)
%% -------------------------------------------------------------------------
%% 获取奖励配置Id
get_reward_cfg(Type, CfgId) ->
	case Type of
		1 ->
			case data_guild:get_guild_support_cfg(CfgId) of
				#base_guild_support{support_reward = [{_, GoodsTypeId, _}]} ->
					GoodsTypeId;
				_ ->
					0
			end;
		2 ->
			case data_guild:get_order_base(CfgId) of
				#base_guild_order{order_reward = [{_, GoodsTypeId, _}]} ->
					GoodsTypeId;
				_ ->
					0
			end;
		_ ->
			0
	end.

%% --------------------------- builtin func ----------------------------------------
%% @doc 协助 @end
%% 获得社团感谢礼包数据
get_support_thank_list(_RoleId) ->
	case get(?P_GUILD_SUPPORT_THANK) of
		undefined -> SupportThankList = [];
		SupportThankList -> ok
	end,
	SupportThankList.

%% 保存感谢礼包数据
save_support_thank_list(_RoleId, SupportThankList) ->
	put(?P_GUILD_SUPPORT_THANK, SupportThankList).

%% 清理感谢礼包数据
%%clean_support_thank_map(GuildId) ->
%%	erase(?P_GUILD_SUPPORT_THANK(GuildId)).

%% 获得社团感谢记录数据
get_support_log_list(_RoleId) ->
	case get(?P_GUILD_SUPPORT_LOG) of
		undefined -> SupportLogList = [];
		SupportLogList -> ok
	end,
	SupportLogList.

%% 保存感谢记录数据
save_support_log_list(_RoleId, SupportLogList) ->
	put(?P_GUILD_SUPPORT_LOG, SupportLogList).

%% 清理感谢记录数据
%%clean_support_log_map(GuildId) ->
%%	erase(?P_GUILD_SUPPORT_LOG(GuildId)).

%% @doc 拼单 @end
%% 获得社团拼单感谢礼包数据
get_order_thank_list(_RoleId) ->
	case get(?P_GUILD_ORDER_THANK) of
		undefined -> OrderThankList = [];
		OrderThankList -> ok
	end,
	OrderThankList.

%% 保存拼单感谢礼包数据
save_order_thank_list(_RoleId, OrderThankList) ->
	put(?P_GUILD_ORDER_THANK, OrderThankList).

%% 获得社团拼单感谢记录数据
get_order_log_list(_RoleId) ->
	case get(?P_GUILD_ORDER_LOG) of
		undefined -> OrderLogList = [];
		OrderLogList -> ok
	end,
	OrderLogList.

%% 保存拼单感谢记录数据
save_order_log_list(_RoleId, OrderLogList) ->
	put(?P_GUILD_ORDER_LOG, OrderLogList).


%% --------------------------- db操作 ----------------------------------------
%% @doc 协助 @end
db_save_support_thank(SupportId, GuildId, AskId, SupportCfgId, RoleList, Content, IsSend, Time) ->
	RoleListStr = util:term_to_string(RoleList),
	ContentStr  = util:term_to_string(Content),
	Sql = io_lib:format(?SAVE_SUPPORT_THANK, [SupportId, GuildId, AskId, SupportCfgId, RoleListStr, ContentStr, IsSend, Time]),
	db:execute(Sql),
	ok.

db_select_support_thank(RoleId) ->
	NowTime  = utime:unixtime(),
	LastTime = NowTime - 86400 * 2,
	Sql = io_lib:format(?SELECT_SUPPORT_THANK, [RoleId, LastTime]),
	db:get_all(Sql).

db_update_support_thank(SupportId, RoleId) ->
	Sql = io_lib:format(<<"UPDATE guild_support_thank SET `is_send`=1 WHERE `support_id` = ~p AND `ask_id` = ~p">>,
		[SupportId, RoleId]),
	db:execute(Sql),
	ok.

batch_save_support_log(GuildId, SupportId, AskId, RoleList, SupportCfgId, Content, ChatMsg, Time) ->
	ContentStr  = util:term_to_string(Content),
	F = fun(RoleId, TSqlList) ->
		TSql = io_lib:format(?BATCH_SAVE_SUPPORT_LOG_VALUE, [SupportId, GuildId, RoleId, AskId, SupportCfgId, ContentStr, ChatMsg, 0, Time]),
		[TSql|TSqlList]
	    end,
	NewSQLs = lists:foldl(F, [], RoleList),
	if
		NewSQLs =/= [] ->
			NewValues = util:join_bitstring(NewSQLs, <<", ">>),
			FinalSql = io_lib:format(?BATCH_SAVE_SUPPORT_LOG, [NewValues]),
			db:execute(FinalSql);
		true -> skip
	end.

db_select_support_log(RoleId) ->
	NowTime  = utime:unixtime(),
	LastTime = NowTime - 86400 * 2,
	Sql = io_lib:format(?SELECT_SUPPORT_LOG, [RoleId, LastTime]),
	db:get_all(Sql).

db_update_support_log(SupportId, RoleId) ->
	Sql = io_lib:format(<<"UPDATE guild_support_log SET `is_receive`=1 WHERE `support_id` = ~p AND `role_id` = ~p">>,
		[SupportId, RoleId]),
	db:execute(Sql),
	ok.

%% @doc 拼单 @end
db_save_order_thank(OrderId, GuildId, AskId, OrderCfgId, RoleList, Content, IsSend, Time) ->
	RoleListStr = util:term_to_string(RoleList),
	ContentStr  = util:term_to_string(Content),
	Sql = io_lib:format(?SAVE_ORDER_THANK, [OrderId, GuildId, AskId, OrderCfgId, RoleListStr, ContentStr, IsSend, Time]),
	db:execute(Sql),
	ok.

db_select_order_thank(RoleId) ->
	NowTime  = utime:unixtime(),
	LastTime = NowTime - 86400 * 2,
	Sql = io_lib:format(?SELECT_ORDER_THANK, [RoleId, LastTime]),
	db:get_all(Sql).

db_update_order_thank(OrderId, RoleId) ->
	Sql = io_lib:format(<<"UPDATE guild_order_thank SET `is_send`=1 WHERE `order_id` = ~p AND `ask_id` = ~p">>,
		[OrderId, RoleId]),
	db:execute(Sql),
	ok.

batch_save_order_log(GuildId, OrderId, AskId, RoleList, CfgId, Content, ChatMsg, Time) ->
	ContentStr  = util:term_to_string(Content),
	F = fun(RoleId, TSqlList) ->
		TSql = io_lib:format(?BATCH_SAVE_ORDER_LOG_VALUE, [OrderId, GuildId, RoleId, AskId, CfgId, ContentStr, ChatMsg, 0, Time]),
		[TSql|TSqlList]
	    end,
	NewSQLs = lists:foldl(F, [], RoleList),
	if
		NewSQLs =/= [] ->
			NewValues = util:join_bitstring(NewSQLs, <<", ">>),
			FinalSql = io_lib:format(?BATCH_SAVE_ORDER_LOG, [NewValues]),
			db:execute(FinalSql);
		true -> skip
	end.

db_select_order_log(RoleId) ->
	NowTime  = utime:unixtime(),
	LastTime = NowTime - 86400 * 2,
	Sql = io_lib:format(?SELECT_ORDER_LOG, [RoleId, LastTime]),
	db:get_all(Sql).

db_update_order_log(SupportId, RoleId) ->
	Sql = io_lib:format(<<"UPDATE guild_order_log SET `is_receive`=1 WHERE `order_id` = ~p AND `role_id` = ~p">>,
		[SupportId, RoleId]),
	db:execute(Sql),
	ok.
