-- 下单锁库传入的数据格式,对于redis来说,lua是原子性的,有事务的

-- 检验库存信息 这里的key是
local cachePrefix = KEYS[1]
local orderId = KEYS[2]
local activityId = KEYS[3]
local prodCount = tonumber(KEYS[4])
local userId = KEYS[5]
local orderInfo = KEYS[6]
local maxNum = tonumber(KEYS[7])
local skuId = KEYS[8]
local pointId = KEYS[9]
local boughtNum = 0

-- 限购
if maxNum ~= -1 then
    if (redis.call('exists', cachePrefix.."buy:".. activityId.."_"..userId) == "1") then
        -- 用户已购数量
        boughtNum = tonumber(redis.call('get', cachePrefix.."buy:".. activityId.."_"..userId))
    end
    if maxNum < (boughtNum + prodCount) then
        return "-2"
    end
end

-- 因为有可能库存从别的地方扣减，这里只做锁定和订单的记录
local mgetSkuKeys = {}
local msetSkuKV = {}
if prodCount > 0 then
    -- 下面通过get获取当前的库存数量
    table.insert(mgetSkuKeys, cachePrefix.."stock:"..activityId.."_"..skuId)
    table.insert(mgetSkuKeys, cachePrefix.."stock:"..activityId.."_"..skuId.."_"..pointId)
    local stockStr = redis.call('mget', unpack(mgetSkuKeys));

    local stock = tonumber(stockStr[1])
    local pointStock = tonumber(stockStr[2])



    if pointStock == nil or prodCount > pointStock then
        -- 库存不足返回-1
        return "-1"
    end

    -- 批量更新剩余库存

    -- 总库存
    table.insert(msetSkuKV, cachePrefix.."stock:"..activityId.."_"..skuId)
    table.insert(msetSkuKV, stock - prodCount)
    -- 区域库存
    table.insert(msetSkuKV, cachePrefix.."stock:"..activityId.."_"..skuId.."_"..pointId)
    table.insert(msetSkuKV, pointStock - prodCount)
end

-- 保存锁定记录
table.insert(msetSkuKV, cachePrefix.."lock:"..orderId)
table.insert(msetSkuKV, tostring(prodCount))
-- 更新购买数量
table.insert(msetSkuKV, cachePrefix.."buy:"..activityId.."_"..userId)
table.insert(msetSkuKV, boughtNum + prodCount)
redis.call('mset',unpack(msetSkuKV))
-- 保存订单记录map  key=userId value={(status+订单id)：1未付款, (info+订单id)：orderInfo}
redis.call('HMSET',cachePrefix.."order:"..userId, "status:"..orderId, 1, "info:"..orderId, orderInfo)

return "1"
