%% ---------------------------------------------------------------------------
%% @doc 拍卖行
%% @author hek
%% @since  2016-11-14
%% @deprecated
%% ---------------------------------------------------------------------------

-module (lib_auction_data).
-include ("common.hrl").
-include ("rec_auction.hrl").
-include ("def_fun.hrl").
-include ("def_timer_quest.hrl").
-include ("def_goods.hrl").
-compile (export_all).

%% ------------------------------ init function %% ---------------------------

init() ->
	SqlAuction 		= io_lib:format(?SQL_AUCTION_SELECT, []),
	SqlAuctionInfo  = io_lib:format(?SQL_AUCTION_INFO_SELECT, []),
	SqlAuctionGoods = io_lib:format(?SEL_AUCTION_GOODS_SELECT, []),
	SqlAuctionLog 	= io_lib:format(?SQL_AUCTION_LOG_SELECT, []),
	SqlGuildAward  	= io_lib:format(?SQL_AUCTION_GUILD_AWARD_SELECT, []),
	AwardMap = lists:foldl(
		fun init_guild_award/2, #{}, db:get_all(SqlGuildAward)),
	{AuctionMap, JoinLogMap, _} = lists:foldl(
		fun init_auction_and_join_log/2, { #{}, #{}, AwardMap}, db:get_all(SqlAuction)),
	AuctionInfo = lists:foldl(
		fun init_goods_info/2, #{}, db:get_all(SqlAuctionInfo)),
	{GoodsMap, GuildMap, WorldMap, NewAuctionMap, _AuctionInfo, _WorldLv} = lists:foldl(
		fun init_auction_goods/2,
		{#{}, #{}, #{}, AuctionMap, AuctionInfo, util:get_world_lv()}, db:get_all(SqlAuctionGoods)),

	delete_overtime_guild_award_db(AwardMap, NewAuctionMap),
	{GuildLogMap, WorldLogList} = lists:foldl(
		fun init_auction_log/2, {#{}, []}, db:get_all(SqlAuctionLog)),
	lib_auction_mod:restart_close_auction_timer(NewAuctionMap),
	make(auction_state, [1, NewAuctionMap, GoodsMap, GuildMap, WorldMap, GuildLogMap, WorldLogList, JoinLogMap]).

init_guild_award(Elem, Map) ->
	[AuctionId, GuildId, AwardStatus] = Elem,
	GuildMap = maps:get(AuctionId, Map, #{}),
	NewGuildMap = maps:put(GuildId, AwardStatus, GuildMap),
	maps:put(AuctionId, NewGuildMap, Map).

init_auction_and_join_log(Elem, {AuctionMap, JoinLogMap, AwardMap}) ->
	Auction = make(auction, Elem),
	AuctionId 	= Auction#auction.auction_id,
	AuctionType = Auction#auction.auction_type,
	ModuleId    = Auction#auction.module_id,
	NewJoinLogMap = case AuctionType of
		?AUCTION_GUILD -> init_join_log(ModuleId, JoinLogMap);
		_ -> JoinLogMap
	end,
	GuildAwardMap = maps:get(AuctionId, AwardMap, #{}),
	NewAuction    = Auction#auction{guild_award_map = GuildAwardMap},
	NewAuctionMap = init_auction_join_num(NewAuction, AuctionMap, NewJoinLogMap),
	{NewAuctionMap, NewJoinLogMap, AwardMap}.

init_join_log(ModuleId, JoinLogMap) ->
	LogList = lib_act_join_api:get_join(ModuleId),
	F = fun({PlayerId, GuildId}, AccMap) ->
		maps:put(PlayerId, GuildId, AccMap)
	end,
	JoinLog = lists:foldl(F, #{}, LogList),
	maps:put(ModuleId, JoinLog, JoinLogMap).

init_auction_join_num(Auction, AuctionMap, JoinLogMap) ->
	ModuleId   = Auction#auction.module_id,
	JoinLog    = maps:get(ModuleId, JoinLogMap, #{}),
	GuildJoinNumMap = lib_auction_mod:count_every_guild_join_num(JoinLog),
	NewAuction = Auction#auction{act_join_num_map = GuildJoinNumMap},
	maps:put(NewAuction#auction.auction_id, NewAuction, AuctionMap).

init_goods_info([GoodsId, PlayerId, PriceType, Price, PriceList, Time], Acc) ->
	AuctionInfo = make(auction_info, [PlayerId, PriceType, Price, util:bitstring_to_term(PriceList), Time]),
	InfoList = maps:get(GoodsId, Acc, []),
	maps:put(GoodsId, [AuctionInfo|InfoList], Acc).

init_auction_goods(
	[GoodsId, AuctionId, GoodsType, GoodsNum, Type, AuctionType, CfgId, GuildId, PlayerId, ModuleId, GoodsStatus, TaxRate, StartTime],
	{GoodsMap, GuildMap, WorldMap, AuctionMap, InfoMap, WorldLv}) ->

	InfoList 	 = maps:get(GoodsId, InfoMap, []),
	{NextPrice, NowPrice} = get_price(AuctionType, GoodsType, GoodsNum, WorldLv, InfoList),
	Elem  = [GoodsId, AuctionId, GoodsType, GoodsNum, Type, AuctionType, CfgId, GuildId, PlayerId, ModuleId, GoodsStatus, TaxRate, StartTime, NextPrice, NowPrice, InfoList],
	AuctionGoods = make(auction_goods, Elem),
	NewGoodsMap  = maps:put(GoodsId, AuctionGoods, GoodsMap),
	{NewGuildMap, NewWorldMap} = init_goods_catalog(GuildMap, WorldMap, AuctionGoods),
	NewAuctionMap = init_auction_estimate_bonus(AuctionGoods, AuctionMap),
	Auction = maps:get(AuctionId, NewAuctionMap, false),

	LastAuctionMap = case GoodsStatus =/= ?GOODS_STATUS_SELLOUT andalso Auction=/=false of
		true ->
			NewAuction = Auction#auction{goods_num = Auction#auction.goods_num + 1},
			maps:put(NewAuction#auction.auction_id, NewAuction, NewAuctionMap);
		false -> NewAuctionMap
	end,
	{NewGoodsMap, NewGuildMap, NewWorldMap, LastAuctionMap, InfoMap, WorldLv}.

init_goods_catalog(GuildMap, WorldMap, #auction_goods{goods_status= GoodsStatus} = AuctionGoods) when GoodsStatus == ?GOODS_STATUS_SELL ->
	#auction_goods{
			goods_id 	= GoodsId,
			auction_type= AuctionType,
			type  		= Type,
			guild_id  	= GuildId,
			module_id 	= ModuleId
		} = AuctionGoods,
	case AuctionType of
		?AUCTION_GUILD ->
			{GoodsList, ModuleList} = get_guild_module_goods(GuildId, GuildMap, ModuleId),
			NewGuildMap = update_guild_module_goods(GuildId, GuildMap, ModuleId, ModuleList, [GoodsId|GoodsList]),
			NewWorldMap = WorldMap;
		_ ->
			GoodsList = maps:get(Type, WorldMap, []),
			NewGuildMap =  GuildMap,
			NewWorldMap  = maps:put(Type, [GoodsId|GoodsList], WorldMap)
	end,
	{NewGuildMap, NewWorldMap};
init_goods_catalog(GuildMap, WorldMap, _AuctionGoods) ->
	{GuildMap, WorldMap}.

get_guild_module_goods(GuildId, GuildMap, ModuleId) ->
	ModuleList = maps:get(GuildId, GuildMap, []),
	Module     = lists:keyfind(ModuleId, 1, ModuleList),
	{ModuleId, GoodsList} = ?IF(Module==false, {ModuleId, []}, Module),
	{GoodsList, ModuleList}.

update_guild_module_goods(GuildId, GuildMap, ModuleId, ModuleList, GoodsList) ->
	ModuleList2 = lists:keystore(ModuleId, 1, ModuleList, {ModuleId, GoodsList} ),
	maps:put(GuildId, ModuleList2, GuildMap).

init_auction_estimate_bonus(AuctionGoodsList, AuctionMap) when is_list(AuctionGoodsList) ->
	lists:foldl(
		fun(AuctionGoods, Map) ->
			init_auction_estimate_bonus(AuctionGoods, Map)
		end, AuctionMap, AuctionGoodsList);

init_auction_estimate_bonus(AuctionGoods, AuctionMap) ->
	#auction_goods{
			auction_id 	= AuctionId,
			auction_type= AuctionType,
			guild_id    = GuildId
		} = AuctionGoods,
	Auction = maps:get(AuctionId, AuctionMap, false),
	case AuctionType of
		?AUCTION_GUILD when Auction=/=false ->
			EstimateBonusMap = Auction#auction.estimate_bonus_map,
			OldEstimateBonus = maps:get(GuildId, EstimateBonusMap, 0),
			EstimateBonus    = get_estimate_bonus(AuctionGoods),
			NewEstimateBonusMap = maps:put(GuildId, OldEstimateBonus + EstimateBonus, EstimateBonusMap),
			NewAuction = Auction#auction{estimate_bonus_map = NewEstimateBonusMap},
			maps:put(NewAuction#auction.auction_id, NewAuction, AuctionMap);
		_ -> AuctionMap
	end.

%% 物品可以产出的分红
get_estimate_bonus(AuctionGoodsList) when is_list(AuctionGoodsList)->
	lists:sum([get_estimate_bonus(AuctionGoods)||AuctionGoods<-AuctionGoodsList]);

get_estimate_bonus(AuctionGoods) ->
	#auction_goods{
			now_price   = NowPrice,
			info_list   = InfoList
		} = AuctionGoods,
	SellAwardRatio = lib_auction_data:get_bonus_reward_ratio(AuctionGoods),
	NoSellAwardRatio = lib_auction_data:get_no_sell_reward_ratio(),
	case InfoList of
		[] -> round(NowPrice*SellAwardRatio*NoSellAwardRatio);
		_ -> round(NowPrice*SellAwardRatio)
	end.

get_bonus_reward_ratio(AuctionGoods) ->
	#auction_goods{bonus_tax_rate= TaxRate} = AuctionGoods,
	NewTaxRate = if TaxRate>100 -> 90; TaxRate=<0 -> 10; true -> TaxRate end,
	1 - NewTaxRate/100.

get_no_sell_reward_ratio() ->
	min(?AUCTION_KV_NO_SELL_AWARD_RATIO / 100, 1.0).

init_auction_log([AuctionType, ModuleId, GuildId, GoodsType, GoodsNum, MoneyType, Price, Time, ToWorld], {GuildLogMap, WorldLogList}) ->
	AuctionLog = make(auction_log, [ModuleId, GoodsType, GoodsNum, MoneyType, Price, Time, ToWorld]),
	case AuctionType of
		?AUCTION_GUILD ->
			LogList = maps:get(GuildId, GuildLogMap, []),
			NewLogList = [AuctionLog|LogList],
			NewGuildLogMap = maps:put(GuildId, NewLogList, GuildLogMap),
			NewWorldLogList= WorldLogList;
		_ ->
			NewGuildLogMap = GuildLogMap,
			NewWorldLogList= [AuctionLog|WorldLogList]
	end,
	{NewGuildLogMap, NewWorldLogList}.

%% 重置全部目录
reinit_goods_catalog(reinit_all, {GoodsMap, _GuildMap, _WorldMap}) ->
	lists:foldl(
		fun({_K,  AuctionGoods}, {AccGuildMap, AccWorldMap}) ->
			init_goods_catalog(AccGuildMap, AccWorldMap, AuctionGoods)
		end, {#{}, #{}}, maps:to_list(GoodsMap));

%% 重置目录：公会拍卖拍出时
reinit_goods_catalog(reinit_guild, {_GoodsMap, GuildMap, WorldMap, GuildId, ModuleId, GoodsId}) ->
	ModuleGoodsList = maps:get(GuildId, GuildMap, []),
	Res = lists:keyfind(ModuleId, 1, ModuleGoodsList),
	{_ModuleId, GoodsList} = ?IF(Res == false, {ModuleId, []}, Res),
	NewGoodsList = [Id||Id<-GoodsList, Id=/=GoodsId],
	ModuleGoodsList2 =lists:keystore(ModuleId, 1, ModuleGoodsList, {ModuleId, NewGoodsList}),
	{maps:put(GuildId, ModuleGoodsList2, GuildMap), WorldMap};

%% 重置目录：世界拍卖拍出时
reinit_goods_catalog(reinit_world, {_GoodsMap, GuildMap, WorldMap, Type, GoodsId}) ->
	GoodsList = maps:get(Type, WorldMap, []),
	NewGoodsList = [Id||Id<-GoodsList, Id=/=GoodsId],
	{GuildMap, maps:put(Type, NewGoodsList, WorldMap)};

%% 重置目录：增加个人拍卖物品时
reinit_goods_catalog(reinit_personal_add, {_GoodsMap, GuildMap, WorldMap, Type, GoodsId}) ->
	GoodsList = maps:get(Type, WorldMap, []),
	NewGoodsList = [GoodsId|GoodsList],
	{GuildMap, maps:put(Type, NewGoodsList, WorldMap)};

%% 重置目录：个人拍卖拍出时
reinit_goods_catalog(reinit_personal_reduce, {_GoodsMap, GuildMap, WorldMap, Type, GoodsId}) ->
	GoodsList = maps:get(Type, WorldMap, []),
	NewGoodsList = [Id||Id<-GoodsList, Id=/=GoodsId],
	{GuildMap, maps:put(Type, NewGoodsList, WorldMap)}.

%% {next_price, now_price}
get_price(AuctionType, GoodsType, GoodsNum, WorldLv, InfoList) ->
	case lists:reverse(lists:keysort(#auction_info.price, InfoList)) of
		[#auction_info{price = Price}|_] ->
			{get_next_price(AuctionType, GoodsType, GoodsNum, WorldLv, Price), Price};
		_ ->
			BasePrice = get_base_price(AuctionType, GoodsType, GoodsNum, WorldLv),
			% 变更注释：第一次竞拍时next_price按起拍价格
			{BasePrice, BasePrice}
			% {get_next_price(AuctionType, GoodsType, GoodsNum, WorldLv, BasePrice), BasePrice}
	end.

get_next_price(AuctionType = ?AUCTION_GUILD, GoodsType, GoodsNum, WorldLv, TopPrice) ->
	BasePrice 	= get_base_price(AuctionType, GoodsType, GoodsNum, WorldLv),
	Price 		= get_price_add(AuctionType, GoodsType, GoodsNum, WorldLv) + TopPrice,
	NewPrice 	= min(Price, get_one_price(AuctionType, GoodsType, GoodsNum, WorldLv)),
	max(BasePrice, NewPrice);
get_next_price(AuctionType = ?AUCTION_WORLD, GoodsType, GoodsNum, WorldLv, TopPrice) ->
	BasePrice 	= get_base_price(AuctionType, GoodsType, GoodsNum, WorldLv),
	Price 		= get_price_add(AuctionType, GoodsType, GoodsNum, WorldLv) + TopPrice,
	NewPrice 	= min(Price, get_one_price(AuctionType, GoodsType, GoodsNum, WorldLv)),
	max(BasePrice, NewPrice);
get_next_price(AuctionType, GoodsType, GoodsNum, WorldLv, TopPrice) ->
	BasePrice= get_base_price(AuctionType, GoodsType, GoodsNum, WorldLv),
	Price 	 = get_price_add(AuctionType, GoodsType, GoodsNum, WorldLv) + TopPrice,
	NewPrice = min(Price, get_one_price(AuctionType, GoodsType, GoodsNum, WorldLv)),
	max(BasePrice, NewPrice).

get_one_price(AuctionType, GoodsType, GoodsNum, WorldLv) ->
	case {get_goods_cfg(GoodsType, WorldLv), AuctionType} of
		{#base_auction_goods{guild_one_price = OnePrice}, ?AUCTION_GUILD} -> skip;
		{#base_auction_goods{world_one_price = OnePrice}, ?AUCTION_WORLD} -> skip;
		_ -> OnePrice = 0
	end,
	round(OnePrice*GoodsNum).

%% 获取多件物品的基础价格
get_base_price(AuctionType, GoodsType, GoodsNum, WorldLv) ->
	round(get_every_base_price(AuctionType, GoodsType, WorldLv)*GoodsNum).

%% 获取单件物品基础价格
get_every_base_price(AuctionType, GoodsType, WorldLv) ->
	case {get_goods_cfg(GoodsType, WorldLv), AuctionType} of
		{#base_auction_goods{guild_base_price = BasePrice}, ?AUCTION_GUILD} -> skip;
		{#base_auction_goods{world_base_price = BasePrice}, ?AUCTION_WORLD} -> skip;
		_ -> BasePrice = 0
	end,
	BasePrice.

%% 获取加价额度
get_price_add(AuctionType, GoodsType, GoodsNum, WorldLv) ->
	case {get_goods_cfg(GoodsType, WorldLv), AuctionType} of
		{#base_auction_goods{guild_add_price = AddPrice}, ?AUCTION_GUILD} -> skip;
		{#base_auction_goods{world_add_price = AddPrice}, ?AUCTION_WORLD} -> skip;
		_ -> AddPrice = 0
	end,
	round(AddPrice*GoodsNum).

%% 获取竞拍的价格类型
get_need_money_type(AuctionType, GoodsType, WorldLv) ->
	case {get_goods_cfg(GoodsType, WorldLv), AuctionType} of
		{#base_auction_goods{guild_price_type = NeedPriceType}, ?AUCTION_GUILD} -> skip;
		{#base_auction_goods{world_price_type = NeedPriceType}, ?AUCTION_WORLD} -> skip;
		_ -> NeedPriceType = ?TYPE_GOLD
	end,
	NeedPriceType.

get_goods_cfg(GoodsType, WorldLv) ->
	case data_auction:get_goods(GoodsType, WorldLv) of
		#base_auction_goods{} = BaseGoods -> BaseGoods;
		_ ->
			?ERR("missing cfg:~p~n", [{GoodsType, WorldLv}]),
			#base_auction_goods{}
	end.

get_top_player(NowPrice, InfoList) ->
	case lists:keyfind(NowPrice, #auction_info.price, InfoList) of
		#auction_info{player_id = TopPlayerId} -> skip;
		_ -> TopPlayerId = 0
	end,
	TopPlayerId.

get_auction_goods(State, AuctionId) ->
	F = fun
		(#auction_goods{auction_id = Id} = AuctionGoods, AccList)
			when Id==AuctionId -> [AuctionGoods|AccList];
		(_AuctionGoods, AccList) -> AccList
		end,
	lists:foldl(F, [], maps:values(State#auction_state.goods_map)).

get_auction_endtime(Auction) ->
	#auction{
		auction_type 	= AuctionType,
		cfg_id 			= CfgId,
		time 		 	= StartTime,
		delay_guild_map = DelayGuildMap
	} = Auction,
	DelayList = maps:values(DelayGuildMap),
	case lists:reverse(lists:keysort(2, DelayList)) of
		[{_DelayNum, EndTime}|_] -> EndTime;
		_ -> get_endtime(AuctionType, CfgId, StartTime)
	end.
get_goods_endtime(AuctionGoods) ->
	#auction_goods{
		auction_type	= AuctionType,
		cfg_id 			= CfgId,
		start_time 		= StartTime,
		delay_num 		= DelayNum
	} = AuctionGoods,
	DelayTime = get_total_delay_time(DelayNum),
	get_endtime(AuctionType, CfgId, StartTime) + DelayTime.

get_endtime(AuctionType, CfgId, StartTime) ->
	Duration = get_auction_duration(AuctionType, CfgId),
	StartTime + Duration.

%% 根据延时次数获取总延时时间
get_total_delay_time(DelayNum) when DelayNum> 0->
	lists:sum([lib_auction_mod:get_delay_time(0, Num)||Num<-lists:seq(1, DelayNum)]);
get_total_delay_time(_DelayNum) -> 0.

%% 获取当前配置开服天数时间段
get_opday_slot() ->
	OpenDay = util:get_open_day(),
	get_open_day_helper(data_auction:opday_slot_list(), OpenDay).

get_open_day_helper([], _OpenDay)->{0, 0};
get_open_day_helper([{OpStart, OpEnd}|T], OpenDay) ->
	case OpenDay>=OpStart andalso OpenDay=<OpEnd of
		true -> {OpStart, OpEnd};
		false -> get_open_day_helper(T, OpenDay)
	end.

%% 获取拍卖会持续时长(s)
get_auction_duration(?AUCTION_GUILD, _CfgId) -> ?GUILD_AUCTION_DURATION;
get_auction_duration(?AUCTION_WORLD, CfgId) when CfgId>0 ->
	OpdaySlot = get_opday_slot(),
	case data_auction:get_act(OpdaySlot, CfgId) of
		#base_auction_act{start_time = StartTime, end_time = EndTime} ->
			FormatEndTime = format_time(EndTime),
			FormatStartTime = format_time(StartTime),
			FormatEndTime - FormatStartTime;
		_ ->
			?ERR("missing cfg data_auction:get_act:~p", [{OpdaySlot, CfgId}]),
			?WORLD_AUCTION_DURATION
	end;
%% CfgId=0为公会拍卖流入到世界拍卖，使用默认时长
get_auction_duration(?AUCTION_WORLD, _CfgId) -> ?WORLD_AUCTION_DURATION;
get_auction_duration(?AUCTION_PERSONAL, _CfgId) -> ?PERSONAL_AUCTION_DURATION.

%% 转成当天时间戳
format_time({H,M,_S}) ->
	utime:unixdate() + H*3600+ M*60;
format_time(_Time) ->
	utime:unixdate().

make_module_id(ModuleId, SubModuleId) ->
	ModuleId*100+SubModuleId.

get_module_submodule(ModuleId) when ModuleId < 10000-> {ModuleId, 0};
get_module_submodule(ModuleId) ->
	NewModuleId = ModuleId div 100,
	SubModuleId = ModuleId - NewModuleId*100,
	{NewModuleId, SubModuleId}.

get_module_name(ModuleId) ->
	{NewModuleId, SubModuleId} = get_module_submodule(ModuleId),
	case SubModuleId > 0 of
		true -> data_module:get(NewModuleId, SubModuleId);
		false -> data_module:get(NewModuleId)
	end.

get_keyvalues(Id) ->
	case data_auction:get_keyvalues(Id) of
        #base_auction_keyvalues{value = Value} -> Value;
        _ -> 0
    end.

%% ------------------------------ make function %% ---------------------------

make(auction_state, [FinishInit, AuctionMap, GoodsMap, GuildMap, WorldMap, GuildLogMap, WorldLogList, JoinLogMap]) ->
	#auction_state{
		finish_init 	= FinishInit,
		auction_map 	= AuctionMap,
		goods_map 		= GoodsMap,
		guild_map 		= GuildMap,
		world_map  		= WorldMap,
		guild_log_map 	= GuildLogMap,
		world_log_list 	= WorldLogList,
		join_log_map 	= JoinLogMap
	};
make(auction, [AuctionId, AuctionType, CfgId, ModuleId, AuctionStatus, Time, LastTime]) ->
	#auction{
		auction_id 		= AuctionId,
		auction_type 	= AuctionType,
		cfg_id 			= CfgId,
		module_id 		= ModuleId,
		auction_status  = AuctionStatus,
		time 			= Time,
		last_time 		= LastTime
	};
make(auction_info, [PlayerId, PriceType, Price, PriceList, Time]) ->
	#auction_info{
		player_id  		= PlayerId,
		price_type 		= PriceType,
		price 			= Price,
		price_list 		= PriceList,
		time 			= Time
	};
make(auction_goods, [GoodsId, AuctionId, GoodsType, GoodsNum, Type, AuctionType, CfgId,
		GuildId, PlayerId, ModuleId, GoodsStatus, TaxRate, StartTime, NextPrice, NowPrice, InfoList]) ->
	#auction_goods{
		goods_id 		= GoodsId,
		auction_id 		= AuctionId,
		goods_type 		= GoodsType,
		goods_num 		= GoodsNum,
		type 			= Type,
		auction_type 	= AuctionType,
		cfg_id 			= CfgId,
		guild_id 		= GuildId,
		player_id 		= PlayerId,
		module_id 		= ModuleId,
		goods_status 	= GoodsStatus,
		bonus_tax_rate 	= TaxRate,
		start_time 		= StartTime,
		next_price 		= NextPrice,
		now_price 		= NowPrice,
		info_list 		= InfoList
	};
make(auction_log, [ModuleId, GoodsType, GoodsNum, MoneyType, Price, Time, ToWorld]) ->
	#auction_log{
		module_id 		= ModuleId,
		goods_type 		= GoodsType,
		goods_num 		= GoodsNum,
		money_type 		= MoneyType,
		price 			= Price,
		time 			= Time,
		to_world 		= ToWorld
	};
make(_Atom, _Args) ->
	?ERR("no_match:~p,~p", [_Atom, _Args]),
	no_match.


%% ------------------------------- db function %% ----------------------------

add_auction_db(Elem) ->
	SqlAuction  = io_lib:format(?SQL_AUCTION_INSERT, Elem),
	db:execute(SqlAuction),
	ok.

add_auction_goods_db(Elem) ->
	SqlAuction  = io_lib:format(?SEL_AUCTION_GOODS_INSERT, Elem),
	db:execute(SqlAuction),
	ok.

add_auction_info_db(Elem) ->
	SqlAuction  = io_lib:format(?SQL_AUCTION_INFO_INSERT, Elem),
	db:execute(SqlAuction),
	ok.

add_auction_log_db_batch([], _I) -> ok;
add_auction_log_db_batch([Elem|T], I) ->
	case I rem 20 of
		0 -> timer:sleep(300);
		_ -> skip
	end,
	add_auction_log_db(Elem),
	add_auction_log_db_batch(T, I+1).

add_auction_log_db(Elem) ->
	SqlAuction  = io_lib:format(?SQL_AUCTION_LOG_INSERT, Elem),
	db:execute(SqlAuction),
	ok.

add_guild_award_db_batch([], _I) -> ok;
add_guild_award_db_batch([Elem|T], I) ->
	case I rem 20 of
		0 -> timer:sleep(300);
		_ -> skip
	end,
	add_guild_award_db(Elem),
	add_guild_award_db_batch(T, I+1).

add_guild_award_db(Elem) ->
	SqlAuction  = io_lib:format(?SQL_AUCTION_GUILD_AWARD_INSERT, Elem),
	db:execute(SqlAuction),
	ok.

update_auction_db(Elem) ->
	SqlAuction  = io_lib:format(?SQL_AUCTION_UPDATE, Elem),
	db:execute(SqlAuction),
	ok.

update_auction_goods_db(Elem) ->
	SqlAuction  = io_lib:format(?SQL_AUCTION_GOODS_UPDATE, Elem),
	db:execute(SqlAuction),
	ok.

delete_auction_db(Elem) ->
	SqlAuction  = io_lib:format(?SQL_AUCTION_DELETE, Elem),
	db:execute(SqlAuction),
	ok.

delete_auction_goods_db(Elem) ->
	SqlAuction  = io_lib:format(?SEL_AUCTION_GOODS_DELETE, Elem),
	db:execute(SqlAuction),
	ok.

delete_auction_info_db(Elem) ->
	SqlAuction  = io_lib:format(?SQL_AUCTION_INFO_DELETE, Elem),
	db:execute(SqlAuction),
	ok.

delete_auction_log_db() ->
	SqlAuction  = io_lib:format(?SQL_AUCTION_LOG_TRUNCATE, []),
	db:execute(SqlAuction),
	ok.

delete_guild_award_db(Elem) ->
	SqlAuction  = io_lib:format(?SQL_AUCTION_GUILD_AWARD_DELETE, Elem),
	db:execute(SqlAuction),
	ok.

delete_overtime_guild_award_db(AwardMap, AuctionMap) ->
	AuctionIdList = maps:keys(AwardMap),
	F = fun(AuctionId) ->
		case maps:get(AuctionId, AuctionMap, #{}) of
			#{} -> delete_guild_award_db([AuctionId]);
			_ -> skip
		end
	end,
	lists:foreach(F, AuctionIdList).

delete_close_auction_goods_db(AuctionId) ->
	F = fun() ->
		delete_auction_info_db([AuctionId]),
		delete_auction_goods_db([AuctionId]),
		delete_auction_db([AuctionId]),
		delete_guild_award_db([AuctionId]),
		ok
	end,
	case catch db:transaction(F) of
        ok  -> ok;
        Error -> ?ERR("delete_close_auction_goods_db Error:~p~n", [Error])
    end.

delete_personal_close_goods_db(GoodsId) ->
	SqlAuction1 = io_lib:format(?SEL_AUCTION_GOODS_DELETE2, [GoodsId]),
	SqlAuction2 = io_lib:format(?SQL_AUCTION_INFO_DELETE2, [GoodsId]),
	db:execute(SqlAuction1),
	db:execute(SqlAuction2),
	ok.

delete_personal_close_goods_db_batch([], _I) -> ok;
delete_personal_close_goods_db_batch([Elem|T], I) ->
	case I rem 20 of
		0 -> timer:sleep(300);
		_ -> skip
	end,
	F = fun() -> delete_personal_close_goods_db(Elem) end,
	case catch db:transaction(F) of
        ok  -> ok;
        Error -> ?ERR("delete_personal_close_goods_db Error:~p~n", [Error])
    end,
	delete_personal_close_goods_db_batch(T, I+1).
