-- 累充豪礼
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 PanelDefine = require("broadcast.PanelDefine")
local SceneHandler = require("scene.Handler")
local HaoliExcel = require("excel.present").leichongHaoli

local function checkDB(human)
	human.db.leichongHaoli = human.db.leichongHaoli or {updateTime = 0, day = 0, get = {}}
	local haoliDB = human.db.leichongHaoli
	if haoliDB.day >= #HaoliExcel and not Util.isSameDay(haoliDB.upTime) then
		human.db.leichongHaoli = {updateTime = 0, day = 0, get = {}}
	end
	return human.db.leichongHaoli
end

GET_STATE0 = 0	--不可领取
GET_STATE1 = 1	--未领取
GET_STATE2 = 2	--已经领取

local function getState(haoliDB,id,need)
	if haoliDB.day < need then
		return GET_STATE0
	end
	if haoliDB.get[id] then
		return GET_STATE2
	else
		return GET_STATE1
	end
end

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

	local msgRet = Msg.gc.GC_LEICHONG_HAOLI_QUERY	
	local len = 0
	local len1 = 0
	local net
	for k,v in ipairs(HaoliExcel) do
		len = len + 1
		net = msgRet.list[len]
		net.id = k
		net.need = v.day
		net.state = getState(haoliDB,k,v.day)
		len1 = 0
		for k1,v1 in ipairs(v.reward) do
			len1 = len1 + 1
			Grid.makeItem(net.reward[len1], v1[1], v1[2])
		end
		net.reward[0] = len1
	end
	msgRet.list[0] = len

	Msg.send(msgRet, human.fd)
end

function get(human, id)
    local haoliDB = checkDB(human)	
	local config = HaoliExcel[id]

	if getState(haoliDB,id,config.day) ~= GET_STATE1 then
		return
	end

	-- 改db
	haoliDB.get[id] = 1
	
	--发放奖励 
	BagLogic.sendItemGetList(human, config.reward, "leichongHaoli")
	
	local msgRet = Msg.gc.GC_LEICHONG_HAOLI_GET
	Msg.send(msgRet,human.fd)
    
	for k, v in pairs(funcID) do
        YunYingLogic.updateIcon(YYInfo[k], human)
	    YunYingLogic.sendGroupUpdate(YYInfo[k], human, PanelDefine.PANEL_ID_3305)
        break
    end
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

function isRed(human)
	local haoliDB = checkDB(human)
	for k,v in ipairs(HaoliExcel) do
		if getState(haoliDB,k,v.day) == GET_STATE1 then
			return true
		end
	end
end

MONEY_LIMIT = 6
function onAddMoney(human,money)
	if isOpen(human) ~= true then
		return
	end

	if money < MONEY_LIMIT then
		return
	end
	local haoliDB = checkDB(human)
	if not Util.isSameDay(haoliDB.upTime) then
		haoliDB.upTime = os.time()
		haoliDB.day = haoliDB.day + 1
        
	    for k, v in pairs(funcID) do
            YunYingLogic.updateIcon(YYInfo[k], human)
	        YunYingLogic.sendGroupUpdate(YYInfo[k], human, PanelDefine.PANEL_ID_3305)
            break
        end
	end
end