%% ---------------------------------------------------------------------------
%% @doc 交易市场数据库操作
%% @author zhaoyu
%% @since  2019-12-25
%% ---------------------------------------------------------------------------
-module(market_db).

-include("market.hrl").
-include("common.hrl").
-include("goods.hrl").
-include("equipment.hrl").

-export([
        save_market_goods/1                 %% 保存交易市场出售的商品信息
        ,batch_save_market_goods/1          %% 保存交易市场出售的商品信息
        ,load_market_goods/1                %% 加载交易市场出售的商品信息
        ,del_market_goods/1                 %% 删除交易市场玩家出售物品信息
        ,save_market_bid/1                  %% 保存交易市场玩家出价信息
        ,load_market_bid_infos/0            %% 加载交易市场玩家出价信息
        ,del_market_bid_info/1              %% 删除交易市场玩家出价信息
        ,del_market_bid_infos/1             %% 删除交易市场玩家出价信息

        ,save_market_like_info/1            %% 保存玩家关注商品信息
        ,load_market_like_infos/1           %% 加载玩家关注商品信息
        ,del_market_like_info/1             %% 删除玩家关注商品信息

        ,format_save_market_goods_sql/1     %% 构建保存交易市场出售商品信息的sql 
        ,save_deal_log/1                    %% 保存交易市场成交记录
        ,load_deal_log/1                    %% 加载交易市场成交记录
        ,del_deal_log/1                     %% 删除交易市场成交记录
        ,del_deal_log/0                     %% 删除交易市场成交记录
        ,save_role_deal_log/1               %% 保存角色交易市场成交记录
        ,load_role_deal_log/1               %% 加载角色交易市场成交记录
        ,del_role_deal_log/1                %% 删除角色交易市场成交记录
        ,del_role_deal_log/2                %% 删除角色交易市场成交记录
        ,save_reminder_info/2               %% 保存交易市场入库提醒订阅信息 
        ,load_reminder_info/1               %% 加载交易市场入库提醒订阅信息 
        ,del_reminder_info/1                %% 删除角色入库提醒订阅信息 
        ,save_market_supply/1               %% 保存交易市场系统补给商品数据 
        ,batch_save_market_supply/1         %% 保存交易市场系统补给商品数据 
        ,load_market_supply/0               %% 加载交易市场系统补给商品数据
    ]).



%% ---------------------------------------------------------------------------
%% @doc 保存交易市场出售的商品信息
-spec save_market_goods(Goods) -> ok when
    Goods       :: #market_goods{}.
%% ---------------------------------------------------------------------------
save_market_goods(Goods) ->
    db:execute(format_save_market_goods_sql(Goods)),
    ok.


%% ---------------------------------------------------------------------------
%% @doc 构建保存交易市场出售商品信息的sql
-spec format_save_market_goods_sql(Goods) -> list() when
    Goods       :: #market_goods{}.
%% ---------------------------------------------------------------------------
format_save_market_goods_sql(Goods) ->
    #market_goods{
        id = Id, role_id = RoleId, goods_id = GoodsId, goods_type_id = GoodsTypeId
        ,num = Num, lev = Lev, color = Color, price = Price, sell_type = SellType
        ,guild_id = GuildId, time = Time, off_time = OffTime, extra_attr = ExtraAttr
        ,is_to_world = IsToWorld, bidder_id = BidderId, sys_buyback_time = BuybackTime
        ,sys_buyback_count = BuyBackCount, off_shelf = OffShelf
    } = Goods,
    Data = [
        Id, RoleId, GoodsId, GoodsTypeId, Num, Lev, Color, Price, SellType, GuildId
        ,Time, OffTime, BuybackTime, IsToWorld, BidderId, util:term_to_string(ExtraAttr), BuyBackCount
        ,OffShelf
    ],
    io_lib:format(?SAVE_MARKET_GOODS, Data).


%% ---------------------------------------------------------------------------
%% @doc 保存交易市场出售的商品信息
-spec batch_save_market_goods(GoodsList) -> ok when
    GoodsList     :: [#market_goods{}].
%% ---------------------------------------------------------------------------
batch_save_market_goods([]) ->
    ok;
batch_save_market_goods(GoodsList) ->
    DbList = format_goods_list_sql(GoodsList, []),
    ArgsString = string:join(DbList, ","),
    Sql = io_lib:format(?BATCH_SAVE_MARKET_GOODS, [ArgsString]),
    db:execute(Sql),
    ok.

format_goods_list_sql([], DbList) ->
    DbList;
format_goods_list_sql([Goods | T], DbList) ->
    #market_goods{
        id = Id, role_id = RoleId, goods_id = GoodsId, goods_type_id = GoodsTypeId
        ,num = Num, lev = Lev, color = Color, price = Price, sell_type = SellType
        ,guild_id = GuildId, time = Time, off_time = OffTime, extra_attr = ExtraAttr
        ,is_to_world = IsToWorld, bidder_id = BidderId, sys_buyback_time = BuybackTime
        ,sys_buyback_count = BackCount, off_shelf = OffShelf
    } = Goods,
    Data = [
        Id, RoleId, GoodsId, GoodsTypeId, Num, Lev, Color, Price, SellType, GuildId
        ,Time, OffTime, BuybackTime, IsToWorld, BidderId, util:term_to_string(ExtraAttr), BackCount
        ,OffShelf
    ],
    Log = io_lib:format(
        "(~p, ~p, ~p, ~p, ~p, ~p, ~p, ~p, ~p, ~p, ~p, ~p, ~p, ~p, ~p, '~ts',~p,~p)", Data
    ),
    format_goods_list_sql(T, [Log | DbList]).


%% ---------------------------------------------------------------------------
%% @doc 加载交易市场出售的商品信息
-spec load_market_goods(MarketMgr) -> NewMarketMgr when
    MarketMgr       :: #market_mgr{},
    NewMarketMgr    :: #market_mgr{}.
%% ---------------------------------------------------------------------------
load_market_goods(MarketMgr) ->
    case db:get_all(?LOAD_MARKET_GOODS) of
        DataList when is_list(DataList) andalso DataList =/= [] ->
            load_market_goods_do(MarketMgr, DataList);
        _ ->
            MarketMgr
    end.

load_market_goods_do(MarketMgr, []) ->
    MarketMgr;
load_market_goods_do(MarketMgr, [DataOne | T]) ->
    [
        Id, RoleId, GoodsId, GoodsTypeId, Num, Lev, Color, Price, SellType
        ,GuildId, Time, OffTime, BuybackTime, IsToWorld, BidderId, ExtraAttrBin
        ,BuyBackCount, OffShelf
    ] = DataOne,
    ExtraAttr = util:bitstring_to_term(ExtraAttrBin),
    GoodsCfg = case data_goods_type:get(GoodsTypeId) of
        #ets_goods_type{} = GCfg -> GCfg;
        _ -> #ets_goods_type{}
    end,
    #ets_goods_type{
        sell_category = SellCategory, sell_subcategory = SellSubCategory
        ,buyout_price = BuyoutPrice, sex = Sex
    } = GoodsCfg,
    Series  = equipment_api:get_equipment_series(GoodsTypeId),
    Careers = equipment_api:get_equipment_careers(GoodsTypeId),
    Goods = #market_goods{
        id = Id, role_id = RoleId, goods_id = GoodsId, goods_type_id = GoodsTypeId
        ,num = Num, lev = Lev, color = Color, price = Price, sell_type = SellType
        ,guild_id = GuildId, time = Time, off_time = OffTime, extra_attr = ExtraAttr
        ,is_to_world = IsToWorld, type = SellCategory, sub_type = SellSubCategory
        ,buyout_price = BuyoutPrice, career = Careers, sex = Sex, bidder_id = BidderId
        ,series = Series, sys_buyback_time = BuybackTime, sys_buyback_count = BuyBackCount
        , off_shelf = OffShelf
    },
    ets:insert(?MARKET_GOODS_ETS, Goods),
    %% 更新各种倒计时
    MarketMgr2 = update_time_list(MarketMgr, Goods),
    load_market_goods_do(MarketMgr2, T).

%% 更新每个竞拍子类里最早结束的时间戳和系统回购倒计时
update_time_list(MarketMgr, MarketGoods) ->
    #market_goods{
        off_time = OffTime, type = Type, sub_type = SubType
        ,goods_type_id = GoodsTypeId, sys_buyback_time = BuybackTime
    } = MarketGoods,
    #market_mgr{off_time_list = OffTimeList, buyback_time_list = BackList} = MarketMgr,
    %% 更新每个竞拍子类里最早结束的时间戳
    Key = {Type, SubType},
    OffTimeList2 = case lists:keyfind(Key, #m_off_time_info.key, OffTimeList) of
        Info = #m_off_time_info{min_off_time = MinTime} when OffTime < MinTime ->
            OffTimeInfo = Info#m_off_time_info{min_off_time = OffTime},
            lists:keystore(Key, #m_off_time_info.key, OffTimeList, OffTimeInfo);
        false ->
            OffTimeInfo = #m_off_time_info{key = Key, min_off_time = OffTime},
            [OffTimeInfo | OffTimeList];
        _ ->
            OffTimeList
    end,
    %% 系统回购倒计时
    BackKeyPos = #m_buyback_time_info.goods_type_id,
    BackList2 = case lists:keyfind(GoodsTypeId, BackKeyPos, BackList) of
        BackInfo = #m_buyback_time_info{
            min_time = BackMinTime
        } when BuybackTime < BackMinTime andalso BuybackTime > 0 ->
            TimeInfo = BackInfo#m_buyback_time_info{min_time = BuybackTime},
            lists:keystore(GoodsTypeId, BackKeyPos, BackList, TimeInfo);
        false when BuybackTime > 0 ->
            TimeInfo = #m_buyback_time_info{
                goods_type_id = GoodsTypeId, min_time = BuybackTime
            },
            [TimeInfo | BackList];
        _ ->
            BackList
    end,
    MarketMgr#market_mgr{off_time_list = OffTimeList2, buyback_time_list = BackList2}.


%% ---------------------------------------------------------------------------
%% @doc 删除交易市场玩家出售物品信息
-spec del_market_goods(Goods) -> ok when
    Goods       :: #market_goods{}.
%% ---------------------------------------------------------------------------
del_market_goods(Goods) ->
    #market_goods{id = Id, role_id = RoleId} = Goods,
    db:execute(io_lib:format(?DEL_MARKET_GOODS, [Id, RoleId])),
    ok.


%% ---------------------------------------------------------------------------
%% @doc 保存交易市场玩家出价信息
-spec save_market_bid(BidInfo) -> ok when
    BidInfo       :: #market_bid{}.
%% ---------------------------------------------------------------------------
save_market_bid(BidInfo) ->
    #market_bid{
        id = Id, role_id = RoleId, role_name = RoleName, price = Price, time = Time
    } = BidInfo,
    db:execute(io_lib:format(?SAVE_MARKET_BID, [Id, RoleId, RoleName, Price, Time])),
    ok.


%% ---------------------------------------------------------------------------
%% @doc 加载交易市场玩家出价信息
-spec load_market_bid_infos() -> ok.
%% ---------------------------------------------------------------------------
load_market_bid_infos() ->
    case db:get_all(?LOAD_MARKET_BID) of
        DataList when is_list(DataList) andalso DataList =/= [] ->
            load_market_bid_info(DataList);
        _ ->
            ok
    end.

load_market_bid_info([]) ->
    ok;
load_market_bid_info([DataOne | T]) ->
    [Id, RoleId, RoleName, Price, Time] = DataOne,
    BidInfo = #market_bid{
        key = {RoleId, Id}, id = Id, role_id = RoleId, role_name = RoleName
        ,price = Price, time = Time
    },
    ets:insert(?MARKET_BID_ETS, BidInfo),
    load_market_bid_info(T).


%% ---------------------------------------------------------------------------
%% @doc 删除交易市场玩家出价信息 
-spec del_market_bid_info(BidInfo) -> ok when
    BidInfo       :: #market_bid{}.
%% ---------------------------------------------------------------------------
del_market_bid_info(BidInfo) ->
    #market_bid{id = Id, role_id = RoleId} = BidInfo,
    db:execute(io_lib:format(?DEL_ROLE_MARKET_BID, [Id, RoleId])),
    ok.


%% ---------------------------------------------------------------------------
%% @doc 删除交易市场玩家出价信息 
-spec del_market_bid_infos(MarketId) -> ok when
    MarketId       :: integer().
%% ---------------------------------------------------------------------------
del_market_bid_infos(MarketId) ->
    db:execute(io_lib:format(?DEL_MARKET_BID, [MarketId])),
    ok.


%% ---------------------------------------------------------------------------
%% @doc 保存玩家关注商品信息
-spec save_market_like_info(LikeInfo) -> ok when
    LikeInfo       :: #market_like{}.
%% ---------------------------------------------------------------------------
save_market_like_info(LikeInfo) ->
    #market_like{id = Id, role_id = RoleId, time = Time} = LikeInfo,
    db:execute(io_lib:format(?SAVE_MARKET_LIKE, [Id, RoleId, Time])),
    ok.


%% ---------------------------------------------------------------------------
%% @doc 加载玩家关注商品信息
-spec load_market_like_infos(RoleId) ->  LikeInfoList when 
    RoleId          :: integer(), 
    LikeInfoList    :: [#market_like{}].
%% ---------------------------------------------------------------------------
load_market_like_infos(RoleId) ->
    case db:get_all(io_lib:format(?LOAD_MARKET_LIKE, [RoleId])) of
        DataList when is_list(DataList) andalso DataList =/= [] ->
            load_market_like_infos(DataList, []);
        _ ->
            []
    end.

load_market_like_infos([], LikeInfoList) ->
    LikeInfoList;
load_market_like_infos([DataOne | T], LikeInfoList) ->
    [Id, RoleId, Time] = DataOne,
    LikeInfo = #market_like{id = Id, role_id = RoleId, time = Time},
    load_market_like_infos(T, [LikeInfo | LikeInfoList]).


%% ---------------------------------------------------------------------------
%% @doc 删除玩家关注商品信息 
-spec del_market_like_info(LikeInfo) -> ok when
    LikeInfo       :: #market_like{} | integer().
%% ---------------------------------------------------------------------------
del_market_like_info(LikeInfo = #market_like{}) ->
    #market_like{id = Id, role_id = RoleId} = LikeInfo,
    db:execute(io_lib:format(?DEL_MARKET_LIKE, [Id, RoleId])),
    ok;
del_market_like_info(MarketId) ->
    db:execute(io_lib:format(?DEL_MARKET_LIKE_BY_ID, [MarketId])),
    ok.


%% ---------------------------------------------------------------------------
%% @doc 保存交易市场成交记录
-spec save_deal_log(DealLogList) -> ok when
    DealLogList     :: [#market_deal_log{}].
%% ---------------------------------------------------------------------------
save_deal_log([]) ->
    ok;
save_deal_log(DealLogList) ->
    DbList = format_deal_log_list(DealLogList, []),
    ArgsString = string:join(DbList, ","),
    Sql = io_lib:format(?SAVE_MARKET_DEAL_LOG, [ArgsString]),
    db:execute(Sql),
    ok.

format_deal_log_list([], DbList) ->
    DbList;
format_deal_log_list([DealLog | T], DbList) ->
    #market_deal_log{
        id = Id, role_id = RoleId, get_role_id = GetRoleId, get_role_name = GetRoleName
        ,goods_id = GoodsId, goods_type_id = GoodsTypeId, num = Num, lev = Lev
        ,color = Color, price = Price, sell_type = SellType, guild_id = GuildId
        ,time = Time, deal_time = DealTime, deal_type = DealType, log_type = LogType
        ,extra_attr = ExtraAttr
    } = DealLog,
    Data = [
        Id, RoleId, GetRoleId, GetRoleName, GoodsId, GoodsTypeId, Num, Lev, Color
        ,Price, SellType, GuildId, Time, DealTime, DealType, LogType
        ,util:term_to_string(ExtraAttr)
    ],
    Log = io_lib:format(
        "(~p, ~p, ~p, '~ts', ~p, ~p, ~p, ~p, ~p, ~p, ~p, ~p, ~p, ~p, ~p, ~p, '~ts')", Data
    ),
    format_deal_log_list(T, [Log | DbList]).



%% ---------------------------------------------------------------------------
%% @doc 加载交易市场成交记录
-spec load_deal_log(MarketMgr) -> NewMarketMgr when
    MarketMgr       :: #market_mgr{},
    NewMarketMgr    :: #market_mgr{}.
%% ---------------------------------------------------------------------------
load_deal_log(MarketMgr) ->
    case db:get_all(?LOAD_MARKET_DEAL_LOG) of
        DataList when is_list(DataList) andalso DataList =/= [] ->
            AllLogList = load_deal_log_do([], DataList),
            MarketMgr#market_mgr{all_deal_log_list = AllLogList};
        _ ->
            MarketMgr
    end.

load_deal_log_do(AllLogList, []) ->
    AllLogList;
load_deal_log_do(AllLogList, [DataOne | T]) ->
    [
        Id, RoleId, GetRoleId, GetRoleName, GoodsId, GoodsTypeId, Num, Lev, Color
        ,Price, SellType, GuildId, Time, DealTime, DealType, LogTypeId, ExtraAttrBin
    ] = DataOne,
    ExtraAttr = util:bitstring_to_term(ExtraAttrBin),
    {SellCategory, SellSubCategory} = case data_goods_type:get(GoodsTypeId) of
        #ets_goods_type{
            sell_category = SCategory, sell_subcategory = SSubCategory
        } -> {SCategory, SSubCategory};
        _ -> {0, 0}
    end,

    DealLog = #market_deal_log{
        id = Id, role_id = RoleId, get_role_id = GetRoleId, get_role_name = GetRoleName
        ,goods_id = GoodsId, goods_type_id = GoodsTypeId, num = Num, lev = Lev
        ,color = Color, price = Price, sell_type = SellType, guild_id = GuildId
        ,time = Time, deal_time = DealTime, log_type = LogTypeId, extra_attr = ExtraAttr
        ,type = SellCategory, sub_type = SellSubCategory, deal_type = DealType
    },
    LogKey = {SellType, LogTypeId},
    AllLogList2 = case lists:keytake(LogKey, #deal_log_type.log_key, AllLogList) of
        {value, TypeLog = #deal_log_type{log_list = LogList}, RestAllList} ->
            LogList2 = [DealLog | LogList],
            LogList3 = lists:keysort(#market_deal_log.deal_time, LogList2),
            LogList4 = lists:reverse(LogList3),
            LogType2 = TypeLog#deal_log_type{log_list = LogList4},
            [LogType2 | RestAllList];
        _ ->
            TypeLog = #deal_log_type{log_key = LogKey, log_list = [DealLog]},
            [TypeLog | AllLogList]
    end,
    load_deal_log_do(AllLogList2, T).


%% ---------------------------------------------------------------------------
%% @doc 删除交易市场成交记录
-spec del_deal_log(DealLog) -> ok when
    DealLog       :: #market_deal_log{}.
%% ---------------------------------------------------------------------------
del_deal_log(DealLog) ->
    #market_deal_log{id = Id} = DealLog,
    db:execute(io_lib:format(?DEL_MARKET_DEAL_LOG, [Id])),
    ok.


%% ---------------------------------------------------------------------------
%% @doc 删除交易市场成交记录
-spec del_deal_log() -> ok.
%% ---------------------------------------------------------------------------
del_deal_log() ->
    db:execute(?DEL_ALL_MARKET_DEAL_LOG),
    ok.



%% ---------------------------------------------------------------------------
%% @doc 保存角色交易市场成交记录
-spec save_role_deal_log(RoleDealLogList) -> ok when
    RoleDealLogList       :: [#market_role_deal_log{}].
%% ---------------------------------------------------------------------------
save_role_deal_log([]) ->
    ok;
save_role_deal_log(RoleDealLogList) ->
    DbList = format_role_deal_log_list(RoleDealLogList, []),
    ArgsString = string:join(DbList, ","),
    Sql = io_lib:format(?SAVE_M_ROLE_DEAL_LOG, [ArgsString]),
    db:execute(Sql),
    ok.

format_role_deal_log_list([], DbList) ->
    DbList;
format_role_deal_log_list([RoleDealLog | T], DbList) ->
    #market_role_deal_log{
        id = Id, role_id = RoleId, rela_role_id = RelaRoleId, goods_type_id = GoodsTypeId
        ,num = Num, price = Price, sell_type = SellType, guild_id = GuildId, time = Time
        ,deal_time = DealTime, deal_type = DealType, extra_attr = ExtraAttr
    } = RoleDealLog,
    Data = [
        Id, RoleId, RelaRoleId, GoodsTypeId, Num, Price, SellType
        ,GuildId, Time, DealTime, DealType, util:term_to_string(ExtraAttr)
    ],
    Log = io_lib:format("(~p, ~p, ~p, ~p, ~p, ~p, ~p, ~p, ~p, ~p, ~p, '~ts')", Data),
    format_role_deal_log_list(T, [Log | DbList]).


%% ---------------------------------------------------------------------------
%% @doc 加载角色交易市场成交记录
-spec load_role_deal_log(RoleId) -> RoleDealLogList when
    RoleId              :: integer(),
    RoleDealLogList     :: [#market_role_deal_log{}].
%% ---------------------------------------------------------------------------
load_role_deal_log(RoleId) ->
    case db:get_all(io_lib:format(?LOAD_M_ROLE_DEAL_LOG, [RoleId])) of
        DataList when is_list(DataList) andalso DataList =/= [] ->
            load_role_deal_log_do([], DataList);
        _ ->
            []
    end.

load_role_deal_log_do(LogList, []) ->
    LogList;
load_role_deal_log_do(LogList, [DataOne | T]) ->
    [
        Id, RoleId, RelaRoleId, GoodsTypeId, Num, Price, SellType
        ,GuildId, Time, DealTime, DealType, ExtraAttrBin
    ] = DataOne,
    ExtraAttr = util:bitstring_to_term(ExtraAttrBin),
    RoleDealLog = #market_role_deal_log{
        id = Id, role_id = RoleId, rela_role_id = RelaRoleId, goods_type_id = GoodsTypeId
        ,num = Num, price = Price, sell_type = SellType, guild_id = GuildId, time = Time
        ,deal_time = DealTime, deal_type = DealType, extra_attr = ExtraAttr
    },
    load_role_deal_log_do([RoleDealLog | LogList], T).


%% ---------------------------------------------------------------------------
%% @doc 删除角色交易市场成交记录
-spec del_role_deal_log(RoleDealLog) -> ok when
    RoleDealLog       :: #market_role_deal_log{}.
%% ---------------------------------------------------------------------------
del_role_deal_log(DealLog) ->
    #market_role_deal_log{id = Id, role_id = RoleId} = DealLog,
    db:execute(io_lib:format(?DEL_M_ROLE_DEAL_LOG, [Id, RoleId])),
    ok.


%% ---------------------------------------------------------------------------
%% @doc 删除角色交易市场成交记录
-spec del_role_deal_log(RoleId, DealTime) -> ok when
    RoleId       :: integer(),
    DealTime     :: integer().
%% ---------------------------------------------------------------------------
del_role_deal_log(RoleId, DealTime) ->
    db:execute(io_lib:format(?DEL_M_ROLE_DEAL_LOG_BY_TIME, [RoleId, DealTime])),
    ok.



%% ---------------------------------------------------------------------------
%% @doc 保存交易市场入库提醒订阅信息
-spec save_reminder_info(RoleId, ReminderList) -> ok when
    RoleId              :: integer(),
    ReminderList        :: [#market_goods{}].
%% ---------------------------------------------------------------------------
save_reminder_info(RoleId, ReminderList) ->
    Data = [RoleId, util:term_to_string(ReminderList)],
    db:execute(io_lib:format(?SAVE_MARKET_REMINDER, Data)),
    ok.


%% ---------------------------------------------------------------------------
%% @doc 加载交易市场入库提醒订阅信息
-spec load_reminder_info(RoleId) -> ReminderList when
    RoleId          :: integer(),
    ReminderList    :: [GoodsTypeId :: integer()].
%% ---------------------------------------------------------------------------
load_reminder_info(RoleId) ->
    case db:get_all(io_lib:format(?LOAD_MARKET_REMINDER, [RoleId])) of
        DataList when is_list(DataList) andalso DataList =/= [] ->
            load_reminder_info(RoleId, DataList);
        _ ->
            []
    end.

load_reminder_info(_RoleId, []) ->
    [];
load_reminder_info(RoleId, [DataOne | _T]) ->
    [ReminderListStr] = DataOne,
    ReminderList = util:to_term(ReminderListStr),
    ReminderInfoList = [
        #market_reminder{
            key = {RoleId, TypeId}, role_id = RoleId, goods_type_id = TypeId
        } || TypeId <- ReminderList
    ],
    case ReminderInfoList of
        [] -> ok;
        _ -> ets:insert(?MARKET_REMINDER_ETS, ReminderInfoList)
    end,
    ReminderList.


%% ---------------------------------------------------------------------------
%% @doc 删除角色入库提醒订阅信息
-spec del_reminder_info(RoleId) -> ok when
    RoleId       :: integer().
%% ---------------------------------------------------------------------------
del_reminder_info(RoleId) ->
    db:execute(io_lib:format(?DEL_MARKET_REMINDER, [RoleId])),
    ok.



%% ---------------------------------------------------------------------------
%% @doc 保存交易市场系统补给商品数据
-spec save_market_supply(MarketSupply) -> ok when
    MarketSupply        :: #market_supply{}.
%% ---------------------------------------------------------------------------
save_market_supply(MarketSupply) ->
    #market_supply{
        goods_type_id = GoodsTypeId, num = Num, supply_num = SupplyNum, time = Time
    } = MarketSupply,
    db:execute(io_lib:format(?SAVE_MARKET_SUPPLY, [GoodsTypeId, Num, SupplyNum, Time])),
    ok.


%% ---------------------------------------------------------------------------
%% @doc 保存交易市场系统补给商品数据
-spec batch_save_market_supply(MarketSupplyList) -> ok when
    MarketSupplyList     :: [#market_supply{}].
%% ---------------------------------------------------------------------------
batch_save_market_supply([]) ->
    ok;
batch_save_market_supply(MarketSupplyList) ->
    DbList = format_supply_list_sql(MarketSupplyList, []),
    ArgsString = string:join(DbList, ","),
    Sql = io_lib:format(?BATCH_SAVE_MARKET_SUPPLY, [ArgsString]),
    db:execute(Sql),
    ok.

format_supply_list_sql([], DbList) ->
    DbList;
format_supply_list_sql([MarketSupply | T], DbList) ->
    #market_supply{
        goods_type_id = GoodsTypeId, num = Num, supply_num = SupplyNum, time = Time
    } = MarketSupply,
    Log = io_lib:format("(~p, ~p, ~p, ~p)", [GoodsTypeId, Num, SupplyNum, Time]),
    format_goods_list_sql(T, [Log | DbList]).


%% ---------------------------------------------------------------------------
%% @doc 加载交易市场系统补给商品数据
-spec load_market_supply() -> ok.
%% ---------------------------------------------------------------------------
load_market_supply() ->
    case db:get_all(io_lib:format(?LOAD_MARKET_SUPPLY, [])) of
        DataList when is_list(DataList) andalso DataList =/= [] ->
            load_market_supply(DataList);
        _ ->
            []
    end.

load_market_supply([]) ->
    ok;
load_market_supply([DataOne | T]) ->
    [GoodsTypeId, Num, SupplyNum, Time] = DataOne,
    MarketSupply = #market_supply{
        goods_type_id = GoodsTypeId, num = Num, supply_num = SupplyNum, time = Time
    },
    ets:insert(?MARKET_SUPPLY_ETS, MarketSupply),
    load_market_supply(T).


