%%%-------------------------------------------------------------------
%%% @doc 衣橱-市场
%%% Module: wardrobe_store
%%% Created : 2020-11-19
%%% @Author: tyl
%%% @end
%%%-------------------------------------------------------------------
-module(wardrobe_store).

-include("server.hrl").
-include("figure.hrl").
-include("common.hrl").
-include("errcode.hrl").
-include("def_fun.hrl").
-include("def_goods.hrl").
-include("def_module.hrl").
-include("wardrobe.hrl").
-include("goods.hrl").

%% API
-export([send_store_goods/2, buy_goods/4]).

%% 查询商品列表
send_store_goods(#player_status{id = RoleId, sid = Sid, figure = Figure}, StoreId) ->
	#figure{lv = RoleLv, career = Career} = Figure,
	OrderList = data_wardrobe:get_all_goods(StoreId),
	F = fun({Pos, GoodsId}, GoodsList) ->
		case data_wardrobe:get_store_goods(StoreId, GoodsId) of
			#base_wardrobe_store{
				career       = CareerCfg
				,condition   = Condition
				,limit_type  = LimitType
			} ->
				CheckCareer = case CareerCfg of
					              [0] -> true;
					              List when is_list(List) ->
						              case lists:member(Career, List) of
							              true -> true;
							              _ -> false
						              end;
					              _ -> false
				              end,
				CheckLv = case Condition of
							  [{lv, LvLow, LvHigh}|_] when RoleLv >= LvLow, LvHigh >= RoleLv -> true;
							  _ -> false
				          end,
				if
					not CheckCareer -> GoodsList;
					not CheckLv -> GoodsList;
					true ->
						case LimitType of
							?WARDROBE_STORE_NOT_LIMIT ->
								[{Pos, GoodsId, 0}|GoodsList];
							_ ->
								ExchangeCounts = get_buy_counts(RoleId, GoodsId, LimitType),
								[{Pos, GoodsId, ExchangeCounts}|GoodsList]
						end end;
			_ -> GoodsList
		end end,
	SendGoodsList = lists:foldl(F, [], OrderList),
	lib_server_send:send_to_sid(Sid, pt_422, 42202, [StoreId, SendGoodsList]).

%% 商品购买
buy_goods(#player_status{id = RoleId, sid = Sid, figure = Figure, wardrobe = Wardrobe} = Player,
		StoreId, GoodTypeId, Times) ->
	#status_wardrobe{stage = Stage}   = Wardrobe,
	#figure{lv = Lv, career = Career} = Figure,
	case data_wardrobe:get_store_goods(StoreId, GoodTypeId) of
		#base_wardrobe_store{
			 money_type = MoneyType
			,price      = Price
			,goods_num  = GoodsNum
			,limit_type = LimType
			,limit_num  = BuyLim
			,discount   = Discount
			,career     = CareerCfg
			,condition  = LvCondition
			,pos        = Pos
		} = _GoodConfig ->
			BuyCounts = get_buy_counts(RoleId, GoodTypeId, LimType),
			case Times =< 0 of
				%% 次数错误
				true ->lib_server_send:send_to_sid(Sid, pt_422, 42203, [?ERRCODE(err422_buy_times_err), StoreId, Pos, GoodTypeId, BuyCounts]);
				false ->
					%% 计算折扣
					CostMoney = round(Price*Times*(Discount/100)),
					CostList  = [{MoneyType, 0, CostMoney}],
					GiveGoods = [{0, GoodTypeId, GoodsNum*Times}],
					CheckList = case LimType of
			            ?WARDROBE_STORE_NOT_LIMIT ->
				            [
					            {store_open, StoreId, Stage},
					            {price_check, CostMoney},
					            {lv, Lv, LvCondition},{career, Career, CareerCfg}
				            ];
			            _ ->
				            [
					            {store_open, StoreId, Stage},
					            {price_check, CostMoney},
					            {lv, Lv, LvCondition},{career, Career, CareerCfg},
					            {buy_counts, BuyLim, BuyCounts, Times}
				            ]
		            end,
					case check_can_buy(CheckList, Player) of
						true ->
							%% 扣除 和 发放奖励
							case lib_goods_api:cost_object_list_with_check(Player, CostList, wardrobe_store_cost, "") of
								{true, Player1, _} ->
									%% 增加次数
									add_buy_counts(RoleId, GoodTypeId, LimType, Times),
									Content = utext:get(4220001), Title = utext:get(4220002),
									Produce = #produce{type = wardrobe_store, title = Title, content = Content, reward = GiveGoods, show_tips = 1},
									{ok, Player2} = lib_goods_api:send_reward_with_mail(Player1, Produce),
									lib_server_send:send_to_sid(Sid, pt_422, 42203, [?SUCCESS, StoreId, Pos, GoodTypeId, BuyCounts+Times]),
									{ok, Player2};
								{false, ErrCode, _} ->
									lib_server_send:send_to_sid(Sid, pt_422, 42203, [ErrCode, StoreId, Pos, GoodTypeId, BuyCounts]),
									{ok, Player}
							end;
						Res ->  %% 条件不满足
							lib_server_send:send_to_sid(Sid, pt_422, 42203, [Res, StoreId, Pos, GoodTypeId, BuyCounts]),
							{ok, Player}
					end
			end;
		_ ->  %% 配置错误
			{ok, Player}
	end.

%% ----------------------------------------------------------
%% 获取已经购买的次数
get_buy_counts(RoleId, KeyId, LimitType) ->
	if
		LimitType == ?WARDROBE_STORE_DAY_LIMIT -> lib_daily:get_count(RoleId, ?MOD_WARDROBE, 1, KeyId);
		LimitType == ?WARDROBE_STORE_WEEK_LIMIT -> lib_week:get_count(RoleId, ?MOD_WARDROBE, 1, KeyId);
		true -> lib_counter:get_count(RoleId, ?MOD_WARDROBE, 1, KeyId)
	end.

%% 增加购买的次数
add_buy_counts(RoleId, KeyId, LimitType, ExchangeTimes) ->
	if
		LimitType == ?WARDROBE_STORE_DAY_LIMIT -> lib_daily:plus_count(RoleId, ?MOD_WARDROBE, 1, KeyId, ExchangeTimes);
		LimitType == ?WARDROBE_STORE_WEEK_LIMIT -> lib_week:plus_count(RoleId, ?MOD_WARDROBE, 1, KeyId, ExchangeTimes);
		true -> lib_counter:plus_count(RoleId, ?MOD_WARDROBE, 1, KeyId, ExchangeTimes)
	end.

check_can_buy([], _Player) -> true;
check_can_buy([Check|T], Player) ->
	case do_check(Check, Player) of
		true ->
			check_can_buy(T, Player);
		{false, Err} -> Err
	end.
%% 检查货柜是否开启
do_check({store_open, StoreId, Stage}, _Player) ->
	case data_wardrobe:get_store_open(StoreId) of
		StageCfg when is_integer(StageCfg), Stage >= StageCfg -> true;
		_ -> {false, ?ERRCODE(err422_store_not_open)}
	end;
%% 检查玩家等级是否满足
do_check({lv, Lv, LvCondition}, _Player) ->
	case lists:keyfind(lv, 1, LvCondition) of
		{_, Low, High} when Low =< Lv, High >= Lv -> true;
		_ -> {false, ?ERRCODE(err422_lv_not_enough)}
	end;
%% 职业是否满足
do_check({career, Career, CareerCfg}, _Player) ->
	case CareerCfg of
		[0] ->
			true;
		List when is_list(List) ->
			case lists:member(Career, List) of
				true -> true;
				_ -> {false, ?ERRCODE(err422_career_err)}
			end;
		_ ->
			{false, ?ERRCODE(err422_career_cfg_err)}
	end;
%% 购买次数是否足够
do_check({buy_counts, BuyLim, BuyCounts, Times}, _Player) ->
	case BuyLim >= BuyCounts + Times of
		true -> true;
		false -> {false, ?ERRCODE(err422_buy_times_not_enough)}
	end;
%% 判断价格配置是否正常
do_check({price_check, CostMoney}, _Player) ->
	case CostMoney > 0 of
		true -> true;
		false -> {false, ?ERRCODE(err422_store_price_err)}
	end;
do_check(_, _Player) ->
	{false, ?FAIL}.