local Lang = require("common.Lang")
local Util = require("common.Util")
local Msg = require("core.Msg")
local ObjHuman = require("core.ObjHuman")
local ShopExcel = require("excel.shop")
local Broadcast = require("broadcast.Broadcast")
local ItemDefine = require("bag.ItemDefine")
local BagLogic = require("bag.BagLogic")
local Grid = require("bag.Grid")
local ShopDefine = require("shop.ShopDefine")
local ChatPaoMaLogic = require("chat.ChatPaoMaLogic")
local GuideLogic = require("guide.GuideLogic")
local VipLogic = require("vip.VipLogic")
local MoshouLogic = require("moshou.MoshouLogic")
local UnionLivenessLogic = require("union.UnionLivenessLogic")
local UnionDefine = require("union.UnionDefine")
local ChengjiuLogic = require("chengjiu.ChengjiuLogic")
local ChengjiuDefine = require("chengjiu.ChengjiuDefine")
local EquipLogic = require("equip.EquipLogic")
local FuwenGrid = require("fuwen.FuwenGrid")
local HeroGrowUp = require("absAct.HeroGrowUp")
local YunYingLogic = require("yunying.YunYingLogic")
local Config = require("Config")
local TriggerDefine = require("trigger.TriggerDefine")
local TriggerLogic = require("trigger.TriggerLogic")
local WeekTaskLogic = require("dailyTask.WeekTaskLogic")
local MonthCard = require("present.MonthCard")


local function inServerIndex(svrIndexs)
	for i = 1, #svrIndexs do
		local index1 = svrIndexs[i][1]
		local index2 = svrIndexs[i][2]
		if Config.SVR_INDEX >= index1 and Config.SVR_INDEX <= index2 then
			return true
		end
	end
end

local function initGoodsDb(human, shopType, index, refreshTs)
   if not human.db.shop[shopType].goods then return end

   -- 存在旧的，用旧的数据
   local bChose = 0
   if human.db.shop[shopType].goods[index] and human.db.shop[shopType].goods[index].bChose then
        bChose = human.db.shop[shopType].goods[index].bChose
   end

   human.db.shop[shopType].goods[index] = {}
   human.db.shop[shopType].goods[index].nowBuy = 0
   human.db.shop[shopType].goods[index].bChose = bChose
   human.db.shop[shopType].goods[index].index = index
   human.db.shop[shopType].goods[index].refreshTs = refreshTs
end

local function ShopLogic_GetChose(human, shopType, index)
    if not human.db.shop[shopType].goods then 
        return 0
    end

    if not human.db.shop[shopType].goods[index] then
        return 0
    end

    if not human.db.shop[shopType].goods[index].bChose then
        human.db.shop[shopType].goods[index].bChose = 0
    end

    return human.db.shop[shopType].goods[index].bChose
end

local function ShopLogic_SetChose(human, shopType, index, nValue)
    if not human.db.shop[shopType].goods or not human.db.shop[shopType].goods[index] then
        return false
    end

    if not human.db.shop[shopType].goods[index].bChose then
        human.db.shop[shopType].goods[index].bChose = 0
    end

    human.db.shop[shopType].goods[index].bChose = nValue
    
    return true
end

-- 花费刷新总次数
function getCostCntMax(human, shopType)
    if shopType == ShopDefine.SHOP_TYPE_BLACKMARKET then
        return VipLogic.getPowerArgs(human, VipLogic.VIP_POWER4) or 0
    end

    local config = ShopExcel.shop[shopType]
    if not config then return 0 end
    return config.costCnt 
end

-- 剩余花费刷新次数
function getLeftCostCnt(human, shopType)
    local maxCnt = getCostCntMax(human, shopType)
    local shopData = human.db.shop[shopType]
    local useCnt = shopData and shopData.costCnt or 0
    return math.max(maxCnt - useCnt, 0)
end

-- 清除删掉的商品 增加限制的数据
function cleanShopGoods(human, shopType)
   local shopTypeConfig = ShopExcel.shop[shopType]
   if not shopTypeConfig then return end
   local shopConfig = ShopExcel[shopType]
   if not shopConfig then return end
   if not human.db.shop then return end
   if not human.db.shop[shopType] then return end
   if not human.db.shop[shopType].goods then return end

   local shopBuy = GuideLogic.getGuideSkip(human, GuideLogic.SKIPTYPE_JUMP_SHOPBUY)
   if shopType == ShopDefine.SHOP_TYPE_BLACKMARKET and not shopBuy then
      for k,v in pairs(human.db.shop[shopType].goods) do
          human.db.shop[shopType].goods[k].index = 0
          break
      end
   end

   -- 清除没有的
   for k,v in pairs(human.db.shop[shopType].goods) do
      local tempConfig = shopConfig[v.index]
      if not tempConfig then
         human.db.shop[shopType].goods[k] = nil
      end
   end

   -- 加入新增的
   if shopTypeConfig.refreshType == ShopDefine.SHOP_REFRESH_TYPE0 then
      for index, v in pairs(shopConfig) do
         if not human.db.shop[shopType].goods[index] then
            if v.limitType ~= ShopDefine.SHOP_LIMIT_TYPE0 then
               initGoodsDb(human, shopType, index, 0)
            end
         end
      end
   end
end


-- 查询商店物品
function query(human, shopType)
	local shopTypeConfig = ShopExcel.shop[shopType]
	if not shopTypeConfig then return end
    if not inServerIndex(shopTypeConfig.serverIndex) then return end

	local msgRet = Msg.gc.GC_SHOP_QUERY
    msgRet.shopInfo.shopType = shopType
    msgRet.shopInfo.mainType = shopTypeConfig.mainType
    msgRet.shopInfo.refreshType = shopTypeConfig.refreshType
    msgRet.shopInfo.name = shopTypeConfig.name
    msgRet.shopInfo.icon = shopTypeConfig.icon
    msgRet.shopList[0] = 0
    for stype, sconfig in pairs(ShopExcel.shop) do
        if sconfig.mainType == shopTypeConfig.mainType and inServerIndex(sconfig.serverIndex) then
            msgRet.shopList[0] = msgRet.shopList[0] + 1
            local net = msgRet.shopList[msgRet.shopList[0]]
            net.shopType = stype
            net.mainType = sconfig.mainType
            net.refreshType = sconfig.refreshType
            net.name = sconfig.name
            net.icon = sconfig.icon
        end
    end

	Grid.makeItem(msgRet.refreshItem, shopTypeConfig.refreshItemID, shopTypeConfig.refreshItemCnt)

	local shopConfig = ShopExcel[shopType]
	if not shopConfig then return end

	local now = os.time()

    initHumanShopDB(human, shopType)
    checkFreeCnt(human, shopType)

	msgRet.nextRefreshTime = 0

    if human.db.shop[shopType].refreshTs > now then
        msgRet.nextRefreshTime = human.db.shop[shopType].refreshTs - now
    end

    cleanShopGoods(human, shopType)

    -- 自动购买
    AutoBuyChoseItem(human, shopType)

    msgRet.freeCnt = human.db.shop[shopType].freeCnt
	msgRet.freeMax = shopTypeConfig.freeCnt
	msgRet.costCnt = getLeftCostCnt(human, shopType)
	msgRet.costMax = getCostCntMax(human, shopType)

    -- 先把所有商品数据收集到临时表
    local allGoods = {}

    -- 不刷新的没有记录的 走配置
    if shopTypeConfig.refreshType == ShopDefine.SHOP_REFRESH_TYPE0 then
        for index, v in pairs(shopConfig) do
            if not human.db.shop[shopType].goods[index] then
                local tempConfig = v
                allGoods[#allGoods + 1] = {
                    itemID      = tempConfig.itemID,
                    itemCnt     = tempConfig.cnt,
                    itemIndex   = index,
                    needItemID  = tempConfig.needItemID,
                    needItemCnt = tempConfig.price,
                    maxCanBuy   = tempConfig.limitBuyCnt,
                    nowBuy      = 0,
                    zhekou      = tempConfig.zhekou,
                    order       = tempConfig.order,
                    needVipLv   = tempConfig.needVipLv,
                    rare        = tempConfig.rare,
                    limitType   = tempConfig.limitType,
                    bCanChose   = tempConfig.isquickbuy and tempConfig.isquickbuy or 0,
                    bChose      = 0,
                }
            end
        end
    end

    for _, v in pairs(human.db.shop[shopType].goods) do
        local tempConfig = shopConfig[v.index]
        allGoods[#allGoods + 1] = {
            itemID      = tempConfig.itemID,
            itemCnt     = tempConfig.cnt,
            itemIndex   = v.index,
            needItemID  = tempConfig.needItemID,
            needItemCnt = tempConfig.price,
            maxCanBuy   = tempConfig.limitBuyCnt,
            nowBuy      = v.nowBuy,
            zhekou      = tempConfig.zhekou,
            order       = tempConfig.order,
            needVipLv   = tempConfig.needVipLv,
            rare        = tempConfig.rare,
            limitType   = tempConfig.limitType,
            bCanChose   = tempConfig.isquickbuy and tempConfig.isquickbuy or 0,
            bChose      = ShopLogic_GetChose(human, shopType, v.index),
        }
    end

    -- 分批发送，每批最多 15 条
    local BATCH_SIZE = 15
    local total = #allGoods
    local totalBatches = math.max(math.ceil(total / BATCH_SIZE), 1)

    for batchIdx = 1, totalBatches do
        local startIdx = (batchIdx - 1) * BATCH_SIZE + 1
        local endIdx   = math.min(batchIdx * BATCH_SIZE, total)

        msgRet.isStart = (batchIdx == 1) and 1 or 0
        msgRet.isEnd   = (batchIdx == totalBatches) and 1 or 0

        -- 非第一批不重复发送商店列表等头部信息
        -- if batchIdx > 1 then
        --     msgRet.shopList[0] = 0
        -- end

        local cnt = 0
        for i = startIdx, endIdx do
            cnt = cnt + 1
            local item = allGoods[i]
            Grid.makeItem(msgRet.list[cnt].itemData, item.itemID, item.itemCnt)
            msgRet.list[cnt].itemIndex  = item.itemIndex
            Grid.makeItem(msgRet.list[cnt].needItem, item.needItemID, item.needItemCnt)
            msgRet.list[cnt].maxCanBuy  = item.maxCanBuy
            msgRet.list[cnt].nowBuy     = item.nowBuy
            msgRet.list[cnt].zhekou     = item.zhekou
            msgRet.list[cnt].order      = item.order
            msgRet.list[cnt].needVipLv  = item.needVipLv
            msgRet.list[cnt].rare       = item.rare
            msgRet.list[cnt].limitType  = item.limitType
            msgRet.list[cnt].bCanChose  = item.bCanChose
            msgRet.list[cnt].bChose     = item.bChose
        end
        msgRet.list[0] = cnt

        Msg.send(msgRet, human.fd)
    end
end

-- 刷新物品
function refresh(human, shopType)
	local shopConfig = ShopExcel.shop[shopType]
	if not shopConfig then return end
    if not inServerIndex(shopConfig.serverIndex) then return end
	
    cleanShopGoods(human, shopType)

    -- 是否可刷新
    -- 不是主动刷新，主动+日，主动+购完
    if shopConfig.refreshType ~= ShopDefine.SHOP_REFRESH_TYPE1 
    and shopConfig.refreshType ~= ShopDefine.SHOP_REFRESH_TYPE2 
    and shopConfig.refreshType ~= ShopDefine.SHOP_REFRESH_TYPE7 then
        return
    end

    -- 主动+日 主动+购完重置 主动刷新不判断时间
    if shopConfig.refreshType ~= ShopDefine.SHOP_REFRESH_TYPE2 
    or shopConfig.refreshType ~= ShopDefine.SHOP_REFRESH_TYPE7 then
        local now = os.time()
        if human.db.shop[shopType].refreshTs > now  -- 刷新时间未到
           and human.db.shop[shopType].freeCnt <= 0     -- 免费刷新次数小于0
           and human.db.shop[shopType].costCnt >= ShopExcel.shop[shopType].costCnt
           and ShopExcel.shop[shopType].costCnt ~= -1 then -- 花费刷新次数小于0
            return              
        end
    end

	local isFree = nil -- 是否免费

    -- 不需要刷新物品，则可免费刷新
	if shopConfig.refreshItemID == 0 then
        isFree = true
    else
        -- 需要物品，且可免费次数不等于0，且有剩余可免费次数
        if shopConfig.freeCnt ~= 0 and human.db.shop[shopType].freeCnt > 0 then
            isFree = true
        end
    end

	-- 判断道具
	local needItemID = shopConfig.refreshItemID
	local needItemCnt = shopConfig.refreshItemCnt
	
    -- 需要道具
	if isFree ~= true then
        -- 判断剩余刷新次数
        if getCostCntMax(human, shopType) ~= 0 and getCostCntMax(human, shopType) ~= -1 and getLeftCostCnt(human, shopType) < 1 then
            return Broadcast.sendErr(human, Lang.SHOP_REFRESH_ERR_CNT)
        end

        -- 判断道具
		local nowItemCnt = BagLogic.getItemCnt(human, needItemID)
		if nowItemCnt < needItemCnt then
			return Broadcast.sendErr(human, Util.format(Lang.SHOP_ERR_NOITEM,ItemDefine.getValue(needItemID,"name")))
		end

        -- 扣除道具
		BagLogic.delItem(human, needItemID, needItemCnt, "shop_refresh")
        human.db.shop[shopType].costCnt = human.db.shop[shopType].costCnt + 1
    else
        if shopConfig.refreshItemID ~= 0 then
            human.db.shop[shopType].freeCnt = human.db.shop[shopType].freeCnt - 1
        end
	end
	
    -- 刷新
    initHumanShopDB(human,shopType,true)

    if isFree then
        -- 如果没有免费刷新了则刷新时间置0
        if human.db.shop[shopType].freeCnt >= shopConfig.freeCnt then
            human.db.shop[shopType].refreshTs = 0
        end
    end


    -- 自动购买
    if (shopType == ShopDefine.SHOP_MAIN_TYPE_1 or shopType == ShopDefine.SHOP_TYPE_XUYUAN) and human.db.shop[shopType].recordList then
        BuyItemBtAuto(human, shopType)
    end

    
	-- 通知客户端
	query(human, shopType)
end

function buyAllItemsRefresh(human,shopType)
    for itemIndex in pairs(human.db.shop[shopType].goods) do
        local tempConfig = ShopExcel[shopType][itemIndex]
        if tempConfig == nil then
            return
        end
        local maxCanBuy = tempConfig.limitBuyCnt
        if maxCanBuy ~= 0 then 
            local nowBuy = human.db.shop[shopType].goods[itemIndex].nowBuy
            if nowBuy < maxCanBuy then 
                return
            end
        end
    end

    initHumanShopDB(human,shopType,true)

    return true
end

-- 购买物品
function buy(human, shopType, itemID, itemIndex, buyCnt)
	if buyCnt < 1 then return end --购买数量不该小于1呀

    if buyCnt > 30000 then
        return
    end	

    local tempConfig = ShopExcel[shopType][itemIndex]
	if tempConfig == nil then
		return
	end

    -- 商店强制效验
    if tempConfig.itemID ~= itemID then
	    return Broadcast.sendErr(human, Lang.ITEM_BUY_ERROR)
	end

    if tempConfig.needVipLv ~= 0 and VipLogic.getVipLv(human) < tempConfig.needVipLv then
	    return Broadcast.sendErr(human, Lang.VIP_LV_TOO_LOW)
	end

    -- 装备检测数量
    if ItemDefine.isEquip(itemID) then
       if not EquipLogic.checkEmptyCnt(human, buyCnt * tempConfig.cnt) then
          return
       end
    end

    -- 符文检测数量
    if ItemDefine.isFuwen(itemID) then
       if not FuwenGrid.checkEmptyCnt(human, buyCnt * tempConfig.cnt) then
          return
       end
    end

    cleanShopGoods(human, shopType)

	-- 判断上限
	local maxCanBuy = tempConfig.limitBuyCnt
    local dbIndex = itemIndex
	local nowBuy = 0
    for k,v in pairs(human.db.shop[shopType].goods) do
        if v.index == itemIndex then
            nowBuy = v.nowBuy
            dbIndex = k
            break
        end
    end
	
	if maxCanBuy ~= 0 and maxCanBuy - nowBuy < buyCnt then 
		return
	end
	
    if dbIndex == 0 then
        return
    end
	-- 道具判断
	local needItemID = tempConfig.needItemID
	local needItemCnt = tempConfig.price * buyCnt
    
	local nowItemCnt = BagLogic.getItemCnt(human, needItemID)
	
	if nowItemCnt < needItemCnt then
		return Broadcast.sendErr(human, Util.format(Lang.SHOP_ERR_NOITEM,ItemDefine.getValue(needItemID,"name")))
	end

    -- 改db
	if human.db.shop[shopType].goods and human.db.shop[shopType].goods[dbIndex] then
		human.db.shop[shopType].goods[dbIndex].nowBuy = human.db.shop[shopType].goods[dbIndex].nowBuy + buyCnt
        local refreshType = ShopExcel.shop[shopType].refreshType 
        if refreshType == ShopDefine.SHOP_REFRESH_TYPE6 
        or refreshType == ShopDefine.SHOP_REFRESH_TYPE7 then
            buyAllItemsRefresh(human,shopType)
        end
	end

	-- 先删
	BagLogic.delItem(human, needItemID, needItemCnt, "shop_buy", nil, itemID, buyCnt * tempConfig.cnt)
	
	-- 后加
	BagLogic.addItem(human, itemID, buyCnt * tempConfig.cnt, "shop_buy")
	
	-- 加道具
	--ChatPaoMaLogic.trigger(human, ChatPaoMaLogic.TRIGGER_TYPE_1, itemID, buyCnt * tempConfig.cnt, needItemID, needItemCnt)
	
	--通知客户端
	local rewardID = itemID
	local rewardCnt = tempConfig.cnt * buyCnt
	local msgRet = Msg.gc.GC_SHOP_BUY
	msgRet.shopType = shopType
    if ItemDefine.isEquip(rewardID) then
        EquipLogic.makeEquipItemOne(human, msgRet.item)
    else
       	Grid.makeItem(msgRet.item, rewardID, rewardCnt)
    end
	Msg.send(msgRet, human.fd)
	
	query(human, shopType)

	GuideLogic.setDoSpecialGuide(human, GuideLogic.SKIPTYPE_JUMP_SHOPBUY)

    -- 商店购买物品回调
    if shopType == ShopDefine.SHOP_TYPE_UNION then
        UnionLivenessLogic.touchLiveness(human,UnionDefine.UNION_LIVENESS_SHOP,1)
    end

    if shopType == ShopDefine.SHOP_TYPE_BLACKMARKET then
        ChengjiuLogic.onCallback(human,ChengjiuDefine.CJ_TASK_TYPE_4,1)
	    HeroGrowUp.onCallback(human, HeroGrowUp.TASKTYPE10, 1)
        YunYingLogic.onCallBack(human, "onShopBuy",1)  
	    TriggerLogic.PublishEvent(TriggerDefine.EVENT_TYPE_SHOPBUY, human.db._id, 1)
    end
    
    WeekTaskLogic.recordWeekTaskFinishCnt(human, WeekTaskLogic.WEEK_TASK_ID_7, 1)
end


-- 初始化玩家商店数据
function initHumanShopDB(human, shopType,refresh)
	local shopTypeConfig = ShopExcel.shop[shopType]
	local shopConfig = ShopExcel[shopType]
	if not shopConfig then return end
    if not shopTypeConfig then return end
    if not inServerIndex(shopTypeConfig.serverIndex) then return end

    -- 下次刷新时间
    local initDb = nil
    if not human.db.shop or not human.db.shop[shopType] or not human.db.shop[shopType].goods then
        -- 初始化
        initDb = true
    elseif refresh == nil then
        -- 不是初始化也不是刷新
        return
    end

    human.db.shop = human.db.shop or {}
	human.db.shop[shopType] =  human.db.shop[shopType] or {}
    human.db.shop[shopType].freeCnt = human.db.shop[shopType].freeCnt or shopTypeConfig.freeCnt -- 免费刷新次数
	human.db.shop[shopType].costCnt = human.db.shop[shopType].costCnt or 0                      -- 钻石刷新次数
	human.db.shop[shopType].refreshTs = human.db.shop[shopType].refreshTs or 0   
    human.db.shop[shopType].goods = human.db.shop[shopType].goods or {}
    
    -- 固定物品，重置类型
    local now = os.time()
    if shopTypeConfig.refreshGoods == 1 then
	    -- 随机物品，刷新类型
        human.db.shop[shopType].goods = {}
        getRandShopGoods(human,shopType)
    else
       for i, v in pairs(shopConfig) do
            -- 刷新时，活动物品不重置
            local refreshTs = v.refreshTs * 60 * 60
            local goodsRefreshTs = human.db.shop[shopType].goods[i] and human.db.shop[shopType].goods[i].refreshTs or 0
            local endRefreshTs = 0
            if initDb == true or refresh ~= nil then                -- 初始化
                endRefreshTs = now + refreshTs
            else                                -- 其他
                local resetCnt = 0
                if v.limitType == ShopDefine.SHOP_LIMIT_TYPE2 then                -- 日限购
                    local sameDay = Util.isSameDayByTimes(now, goodsRefreshTs)
                    if sameDay ~= true then
                        local dayStart = Util.getDayStartTime(now)
                        endRefreshTs = dayStart + refreshTs
                    end
                elseif v.limitType == ShopDefine.SHOP_LIMIT_TYPE3 then        -- 周限购
                    local sameWeek = Util.isSameWeek(now, goodsRefreshTs)
                    if sameWeek ~= true then
                        local weekStart = Util.getWeekStartTime(now)
                        endRefreshTs = weekStart + refreshTs
                    end
                elseif v.limitType == ShopDefine.SHOP_LIMIT_TYPE4 then        -- 月限购
                    local sameMonth = Util.isSameMonth(now, goodsRefreshTs)
                    if sameMonth ~= true then
                        local monthStart = Util.getMonthStartTime(now)
                        endRefreshTs = monthStart + refreshTs
                    end
                end
            end

            if v.limitType ~= ShopDefine.SHOP_LIMIT_TYPE0 and endRefreshTs > 0 then
               initGoodsDb(human, shopType, i, endRefreshTs)
            end
	    end
    end

    -- 设置免费刷新时间
    if refresh ~= nil then
        if shopTypeConfig.refreshType == ShopDefine.SHOP_REFRESH_TYPE1 
           and human.db.shop[shopType].refreshTs == 0 then
            human.db.shop[shopType].refreshTs = os.time() + shopTypeConfig.refreshTs * 60 * 60
        end
    end
    
    -- 设置商店重置时间
    if shopTypeConfig.refreshType == ShopDefine.SHOP_REFRESH_TYPE3 
    or shopTypeConfig.refreshType == ShopDefine.SHOP_REFRESH_TYPE2 then
        -- 每日自动刷新 或 主动刷新+日刷新
        local dayStart = Util.getDayStartTime(now)
        human.db.shop[shopType].refreshTs = dayStart + 24*60*60            -- 下次刷新时间
    elseif shopTypeConfig.refreshType == ShopDefine.SHOP_REFRESH_TYPE4 then
        -- 周刷新
        local weekStart = Util.getWeekStartTime(now)
        human.db.shop[shopType].refreshTs = weekStart + 7*24*60*60            -- 下次刷新时间
    elseif shopTypeConfig.refreshType == ShopDefine.SHOP_REFRESH_TYPE5 then
        -- 月刷新
        local monthStart = Util.getMonthStartTime(now)
        human.db.shop[shopType].refreshTs = monthStart + 30*24*60*60          -- 下次刷新时间
    end
end

-- 刷新商店物品
local specialTb = {1,5,6,7,8}
function getRandShopGoods(human,shopType)
    local net = human.db.shop[shopType].goods
	local shopTypeConfig = ShopExcel.shop[shopType]
    if not inServerIndex(shopTypeConfig.serverIndex) then return end 
    if shopTypeConfig.refreshGoods ~= 1 then
        return
    end

	local shopConfig = ShopExcel[shopType]
    if not shopConfig then return end
    
    local now = os.time()
    local indexTb = {}

    -- 需要随机物品次数
    local count = 0
    local totalWeight = 0
    local totalWeight1 = 0
    local totalWeight2 = 0
    for k, v in pairs(shopConfig) do
        totalWeight = totalWeight + v.weight

        if v.itemType == 1 then
           totalWeight1 = totalWeight1 + v.weight
        end

        if v.itemType == 2 then
           totalWeight2 = totalWeight2 + v.weight
        end
    end

    for i = 1,shopTypeConfig.goodsCnt do
        local randomNum = math.random(1,totalWeight)
        for j, v in pairs(shopConfig) do
            if indexTb[j] == nil then
                if randomNum <= v.weight then
                    count = count + 1
                    net[count] = {}
                    net[count].nowBuy = 0
                    net[count].index = j
                    net[count].refreshTs = now + shopTypeConfig.refreshTs * 60 * 60
                    indexTb[j] = true
                    totalWeight = totalWeight - v.weight
                    break
                else
                    randomNum = randomNum - v.weight
                end
            end
        end
    end

    -- 特殊商店刷新
     if shopType == ShopDefine.SHOP_TYPE_XUYUAN then
        local len = #shopConfig
        for _,v in pairs(specialTb) do
            local randomNum = 0
            if v == 1 then
               randomNum = math.random(1, totalWeight1)
            else
               randomNum = math.random(1, totalWeight2)
            end
            
            for j, b in pairs(shopConfig) do
                if v == b.itemType or
                  (v ~= 1 and b.itemType == 2) then
                    if randomNum <= b.weight then
                        net[v] = {}
                        net[v].nowBuy = 0
                        net[v].index = j
                        net[v].refreshTs = now + shopTypeConfig.refreshTs * 60 * 60
                        break
                    else
                        randomNum = randomNum - b.weight
                    end
                end
            end
        end
    end
end

function updateDaily(human)
    local shopTypeConfig = ShopExcel.shop
    local len = #shopTypeConfig

    local now = os.time()
    for i ,v in pairs(shopTypeConfig) do

        if inServerIndex(v.serverIndex) then
        -- 日刷新 or 主动+日
          cleanShopGoods(human, i)
          
          if i == ShopDefine.SHOP_TYPE_BLACKMARKET and human.db.shop and human.db.shop[i] then
              human.db.shop[i].costCnt = 0
          end
          
          if v.refreshType == ShopDefine.SHOP_REFRESH_TYPE3 
          or v.refreshType == ShopDefine.SHOP_REFRESH_TYPE2 then
              initHumanShopDB(human,i,true)
          -- 周刷新
          elseif v.refreshType == ShopDefine.SHOP_REFRESH_TYPE4 then
              if human.db.shop and human.db.shop[i] then
                  local sameWeek = Util.isSameWeek(now,human.db.shop[i].refreshTs)
                  if sameWeek ~= true then
                      initHumanShopDB(human,i,true)
                  end
              else
                  initHumanShopDB(human,i,true)
              end
          -- 月刷新
          elseif v.refreshType == ShopDefine.SHOP_REFRESH_TYPE5 then
              if human.db.shop and human.db.shop[i] then
                  local sameMonth = Util.isSameMonth(now,human.db.shop[i].refreshTs)
                  if sameMonth ~= true then
                      initHumanShopDB(human,i,true)
                  end
              else
                  initHumanShopDB(human,i,true)
              end
          -- 没配刷新类型，则根据道具类型来刷新
          else
              if human.db.shop and human.db.shop[i] then
                  for k, v in pairs(human.db.shop[i].goods) do
                      local config = ShopExcel[i][v.index]
                      -- 日限购
                      if config.limitType == ShopDefine.SHOP_LIMIT_TYPE2 then
                          local dayStart = Util.getDayStartTime(now)
                          v.nowBuy = 0
                          v.refreshTs = dayStart + config.refreshTs * 60 * 60
                      -- 周限购
                      elseif config.limitType == ShopDefine.SHOP_LIMIT_TYPE3 then
                          local sameWeek = Util.isSameWeek(now,v.refreshTs)
                          if sameWeek ~= true then
                              local weekStart = Util.getWeekStartTime(now)
                              v.nowBuy = 0
                              v.refreshTs = weekStart + config.refreshTs * 60 * 60
                          end
                      -- 月限购
                      elseif config.limitType == ShopDefine.SHOP_LIMIT_TYPE4 then
                          local sameMonth = Util.isSameMonth(now,v.refreshTs)
                          if sameMonth ~= true then
                              local monthStart = Util.getMonthStartTime(now)
                              v.nowBuy = 0
                              v.refreshTs = monthStart + config.refreshTs * 60 * 60
                          end
                      end
                  end
              end
          end
       end
    end
end

function checkFreeCnt(human,shopType)
    local shopConfig = ShopExcel.shop[shopType]
    if not shopConfig then return end
    if not inServerIndex(shopConfig.serverIndex) then return end

    local now = os.time()
    -- 当前商店免费刷新次数不是满的
    local freeCnt = shopConfig.freeCnt - human.db.shop[shopType].freeCnt
    if freeCnt > 0 then
        local opTs = human.db.shop[shopType].refreshTs - shopConfig.refreshTs*60*60
        local overTime = now - opTs
        local cnt = math.floor(overTime/(shopConfig.refreshTs*60*60))
        if cnt == 0 then
            return
        end
        if cnt >= freeCnt then
            human.db.shop[shopType].freeCnt = shopConfig.freeCnt
            human.db.shop[shopType].refreshTs = 0
        else
            human.db.shop[shopType].freeCnt = human.db.shop[shopType].freeCnt + cnt
            human.db.shop[shopType].refreshTs = human.db.shop[shopType].refreshTs + (shopConfig.refreshTs*60*60*cnt)
        end
    end
end


local function getItemSubBuyCnt(human, recordList, itemCfg, itemInfo)
    if not itemCfg or not table.find(recordList, itemInfo.index) then
        return -1
    end

    local subBuyCnt = itemCfg.limitBuyCnt - itemInfo.nowBuy
    if subBuyCnt <= 0 then
        return subBuyCnt
    end

    if itemCfg.needVipLv ~= 0 and VipLogic.getVipLv(human) < itemCfg.needVipLv then
        return -1
	end

    -- 装备检测数量
    if ItemDefine.isEquip(itemCfg.itemID) then
       if not EquipLogic.checkEmptyCnt(human, subBuyCnt * itemCfg.cnt) then
            return -1
        end
    end

    -- 符文检测数量
    if ItemDefine.isFuwen(itemCfg.itemID) then
       if not FuwenGrid.checkEmptyCnt(human, subBuyCnt * itemCfg.cnt) then
            return -1
        end
    end

    -- 消耗道具检测
    local needItemID = itemCfg.needItemID
	local needItemCnt = itemCfg.price * subBuyCnt
	local nowItemCnt = BagLogic.getItemCnt(human, needItemID)
	if nowItemCnt < needItemCnt then
		return -1
	end

    return subBuyCnt
end


-- 自动购买基础商店中随机商店里被记录的商品
function BuyItemBtAuto(human, shopType)
    local recordList = human.db.shop[shopType] and human.db.shop[shopType].recordList
    if not recordList or not next(recordList) then
        print("[BuyItemBtAuto] 不存在对应数据")
        return
    end

    local shopConfig = ShopExcel[shopType]
    local goods = human.db.shop[shopType].goods

	if not shopConfig or not goods then
        print("[BuyItemBtAuto] 没有对应物品数据")
        return
    end

    cleanShopGoods(human, shopType)

    local len = 0
    local itemVector = {}

    for k, itemInfo in pairs(goods) do
        local itemCfg = shopConfig[itemInfo.index]
        local subBuyCnt = getItemSubBuyCnt(human, recordList, itemCfg, itemInfo)
        if subBuyCnt > 0 then
            -- 更新次数
            goods[k].nowBuy = goods[k].nowBuy + subBuyCnt

            -- 先删
            local itemID = itemCfg.itemID
            local itemCnt = subBuyCnt * itemCfg.cnt
	        BagLogic.delItem(human, itemCfg.needItemID, itemCfg.price * subBuyCnt, "shop_buy", nil, itemID, itemCnt)

            -- 累积奖励
            len = len + 1
            itemVector[len] = {itemID, itemCnt}

            -- 触发事件
            WeekTaskLogic.recordWeekTaskFinishCnt(human, WeekTaskLogic.WEEK_TASK_ID_7, 1)

            if ShopDefine.SHOP_MAIN_TYPE_1 == ShopDefine.SHOP_TYPE_BLACKMARKET then
                ChengjiuLogic.onCallback(human,ChengjiuDefine.CJ_TASK_TYPE_4,1)
                HeroGrowUp.onCallback(human, HeroGrowUp.TASKTYPE10, 1)
                YunYingLogic.onCallBack(human, "onShopBuy",1)
                TriggerLogic.PublishEvent(TriggerDefine.EVENT_TYPE_SHOPBUY, human.db._id, 1)
            end
        end
    end

    if len == 0 then
        Broadcast.sendCenter(human, Lang.ITEM_BUY_DEFAULT)
    else
        print("[BuyItemBtAuto] 开始给奖励")

        BagLogic.addItemList(human, itemVector, "shop_buy")
    end

end




-- 查询记录基础商店中随机商店的道具Idx列表
function RecordItems_Query(human, shopType)
    local shopData = human.db.shop
    local recordList = (shopData and shopData[shopType]) and shopData[shopType].recordList

    local msgRet = Msg.gc.GC_SHOP_RECORD_QUERY
    local itemIdxList = msgRet.itemIdxList
    itemIdxList[0] = 0

    if recordList then
        for k, idx in ipairs(recordList) do
            itemIdxList[0] = k
            itemIdxList[k] = idx
        end
    end

	Msg.send(msgRet, human.fd)
end


-- 记录基础商店中随机商店的道具Idx列表
function RecordItems(human, itemIdxStr, shopType)
    local isBuyCard = MonthCard.IsBuyEverlastingCard(human)

    if not isBuyCard then
        return Broadcast.sendErr(human, Lang.EVERLASTING_CARD_UNACTIVE)
    end

    local itemIdxList = {}
    if itemIdxStr == "" or tonumber(itemIdxStr) == -1 then
        itemIdxList = nil
    else
        itemIdxList = Util.split(itemIdxStr, ",", true)
    end


    human.db.shop[shopType].recordList = itemIdxList

    RecordItems_Query(human, shopType)

    Broadcast.sendCenter(human, Lang.EQUIP_WASH_SAVE_SUC)
end

-- 查询记录基础商店中随机商店的所有道具
function AllItem_Query(human, shopType)
	local shopConfig = ShopExcel[shopType]
	if not shopConfig then return end

    local cnt = 0
    local msgRet = Msg.gc.GC_SHOP_ALL_ITEM_QUERY

    msgRet.isCanRecord = 0

    if MonthCard.IsBuyEverlastingCard(human) then
        msgRet.isCanRecord = 1
    end

    for idx, itemInfo in ipairs(shopConfig) do
        cnt = cnt + 1
        Grid.makeItem(msgRet.itemList[cnt].itemData, itemInfo.itemID, itemInfo.cnt)
        msgRet.itemList[cnt].itemIndex = idx
        Grid.makeItem(msgRet.itemList[cnt].needItem, itemInfo.needItemID, itemInfo.price)
		msgRet.itemList[cnt].maxCanBuy = itemInfo.limitBuyCnt
		msgRet.itemList[cnt].nowBuy = 0
		msgRet.itemList[cnt].zhekou  = itemInfo.zhekou
		msgRet.itemList[cnt].order  = itemInfo.order
        msgRet.itemList[cnt].needVipLv = itemInfo.needVipLv
        msgRet.itemList[cnt].rare = itemInfo.rare
        msgRet.itemList[cnt].limitType = itemInfo.limitType
        msgRet.itemList[cnt].bCanChose = itemInfo.isquickbuy and itemInfo.isquickbuy or 0
        msgRet.itemList[cnt].bChose = ShopLogic_GetChose(human, shopType, idx)
    end

	msgRet.itemList[0] = cnt
	Msg.send(msgRet, human.fd)
end

-- 选中物品
function ChoseItem(human, shopType, bChose, itemIndex)
    local isBuyCard = MonthCard.IsBuyEverlastingCard(human)
    if not isBuyCard then
        return Broadcast.sendErr(human, Lang.EVERLASTING_CARD_UNACTIVE)
    end

    local tempConfig = ShopExcel[shopType][itemIndex]
	if tempConfig == nil then
        print("[ChoseItem] 不存在对应的配置")
		return
	end

    local nNowChose = ShopLogic_GetChose(human, shopType, itemIndex)
    if nNowChose == bChose then
        return
    end

    local bRet = ShopLogic_SetChose(human, shopType, itemIndex, bChose)
    if false == bRet then
        print("[ChoseItem] 设置失败")
        return
    end

    --query(human, shopType)
end

-- 自动购买勾选的物品
function AutoBuyChoseItem(human, shopType, bCanBuy)
    local isBuyCard = MonthCard.IsBuyEverlastingCard(human)
    if not isBuyCard then
        return
    end

    if shopType == ShopDefine.SHOP_TYPE_XUYUAN then
        if nil == bCanBuy or false == bCanBuy then
            return
        end
    end

    local tItemList = {}
    local tDelItemList = {}
    for k,v in pairs(human.db.shop[shopType].goods) do
        if v.bChose and 1 == v.bChose then
            local nIndex = v.index
            local tempConfig = ShopExcel[shopType][nIndex]
            local nowBuy = v.nowBuy
            if tempConfig and tempConfig.limitBuyCnt - nowBuy > 0 then
                local nItemID = tempConfig.itemID
                -- 装备检测数量
                if ItemDefine.isEquip(itemID) then
                    if not EquipLogic.checkEmptyCnt(human, buyCnt * tempConfig.cnt) then
                        break
                    end
                end
            
                -- 符文检测数量
                if ItemDefine.isFuwen(itemID) then
                    if not FuwenGrid.checkEmptyCnt(human, buyCnt * tempConfig.cnt) then
                        break
                    end
                end

                local nBuyCnt = tempConfig.limitBuyCnt - nowBuy
                local needItemID = tempConfig.needItemID
                local needItemCnt = tempConfig.price * nBuyCnt
                local nowItemCnt = BagLogic.getItemCnt(human, needItemID)
                if nowItemCnt >= needItemCnt then
                    v.nowBuy = v.nowBuy + nBuyCnt
                    local refreshType = ShopExcel.shop[shopType].refreshType
                    if refreshType == ShopDefine.SHOP_REFRESH_TYPE6
                        or refreshType == ShopDefine.SHOP_REFRESH_TYPE7 then
                        buyAllItemsRefresh(human,shopType)
                    end

                    -- 先删
                    BagLogic.delItem(human, needItemID, needItemCnt, "shop_buy", nil, itemID, nBuyCnt * tempConfig.cnt)

                    if not tItemList[tempConfig.itemID] then
                        tItemList[tempConfig.itemID] = 0
                    end

                    tItemList[tempConfig.itemID] = tItemList[tempConfig.itemID] + nBuyCnt * tempConfig.cnt
                else
                    break
                end
            end
        end
    end

    if nil ~= _G.next(tItemList) then
        local tGoods = {}
        for k, v in pairs(tItemList) do
            table.insert(tGoods, {k,v})
        end
        BagLogic.addItemList(human, tGoods, "shop_buy")
    end
end

function GetBuyLiftTimeCard(human)
    local tMsgData = Msg.gc.GC_BUY_LIFTTIME_CARD
    tMsgData.bBuy = 0
    if MonthCard.IsBuyEverlastingCard(human) then
        tMsgData.bBuy = 1
    end

    Msg.send(tMsgData, human.fd)
end