-- 限时抢购
local Util = require("common.Util")
local CommonDB = require("common.CommonDB")
local Msg = require("core.Msg")
local ObjHuman = require("core.ObjHuman")
local BagLogic = require("bag.BagLogic")
local Grid = require("bag.Grid")
local YunYingLogic = require("yunying.YunYingLogic")
local SceneHandler = require("scene.Handler")
local LimitBuyExcel = require("excel.limitBuy").limitBuy

local function checkDB(human)
	human.db.limitBuy = human.db.limitBuy or {startTime = 0, get = {}}
	local limitBuyDB = human.db.limitBuy
	local weekStartTime = Util.getWeekStartTime(os.time())
	if weekStartTime ~= limitBuyDB.startTime then
		limitBuyDB.startTime = weekStartTime
		limitBuyDB.get = {}
	end
	return human.db.limitBuy
end

function query(human) 
    local limitBuyDB = checkDB(human)

	local msgRet = Msg.gc.GC_LIMITBUY_QUERY	
	local len = 0
	local len1 = 0
	local net
	for k,v in ipairs(LimitBuyExcel) do
		len = len + 1
		net = msgRet.list[len]
		net.id = k
		net.nowCnt = limitBuyDB.get[k] or 0
		net.maxCnt = v.cnt
		net.desc = v.desc
		len1 = 0
		for k1,v1 in ipairs(v.items) do
			len1 = len1 + 1
			Grid.makeItem(net.reward[len1], v1[1], v1[2])
		end
		net.reward[0] = len1
		BuyLogic.fontBuyItem(human,net.buyItem,v.buyID)
	end
	msgRet.list[0] = len

	local now = os.time()
	msgRet.leftTime = Util.getWeekStartTime(now) - now + 604800  
	Msg.send(msgRet, human.fd)
end

function buy(human, id)
	if true then
		return
	end
	
    local limitBuyDB = checkDB(human)
	local config = LimitBuyExcel[id]

	if limitBuyDB.get[id] and limitBuyDB.get[id] >= config.cnt then
		return
	end

	-- 改db
	limitBuyDB.get[id] =  limitBuyDB.get[id] or 0
	limitBuyDB.get[id] =  limitBuyDB.get[id] + 1
	
	--发放奖励 
	BagLogic.addItemList(human, config.items, "limitBuy")
	
	query(human) 
end

function isOpen(human)
	if true then
		return
	end

	if not SceneHandler.canCharge(human) then
		return
	end

	if not CommonDB.getServerOpenDay() then
		return 
	end
	return true
end