-- 领券失败还原领券数量等传入的数据格式,对于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 skuId = KEYS[6]
local receiveNum = 0


-- 删除优惠券锁定记录,还原库存
if (redis.call('exists', cachePrefix.."lock:"..activityId.."_"..userId.."_"..orderId, tostring(prodCount)) == "1") then
    local isDelete = redis.call('del', cachePrefix.."lock:"..activityId.."_"..userId.."_"..orderId)
    -- 删除锁定标记成功才进行还原领券数量，让方法幂等
    if isDelete > 0 then
        -- 如果有限购，则用户领券数量回退
        if (redis.call('exists', cachePrefix.."receive:".. activityId.."_"..userId) == "1") then
            -- 用户领券数量
            receiveNum = redis.call('get', cachePrefix.."receive:".. activityId.."_"..userId)
            redis.call('set',cachePrefix.."receive:"..activityId.."_"..userId, receiveNum - prodCount)
        end
        -- 库存回退
        if prodCount ~= 0 then
            -- 下面通过get获取当前的库存数量
            local stock = tonumber(redis.call('get', cachePrefix.."stock:".. activityId.."_"..skuId ))
            redis.call('set',cachePrefix.."stock:".. activityId.."_"..skuId,tostring(stock + prodCount))
        end
    end
end

