-- 取消订单还原购买数量等传入的数据格式,对于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 pointId = KEYS[7]
--local zoneNo = KEYS[7]
local boughtNum = 0


-- 删除订单锁定记录,还原库存（订单未支付前取消订单）
if (redis.call('exists', cachePrefix.."lock:"..orderId, tostring(prodCount)) == "1") then
    local isDelete = redis.call('del', cachePrefix.."lock:"..orderId)
    -- 删除锁定标记成功才进行还原购买数量，让方法幂等
    if isDelete > 0 then
        -- 如果有限购，则用户已购数量回退
        if (redis.call('exists', cachePrefix.."buy:".. activityId.."_"..userId) == "1") then
            -- 用户已购数量
            boughtNum = redis.call('get', cachePrefix.."buy:".. activityId.."_"..userId)
            redis.call('set',cachePrefix.."buy:"..activityId.."_"..userId, boughtNum - prodCount)
        end
        -- 库存回退
        if prodCount ~= 0 then
            -- 下面通过get获取当前的库存数量
            -- multiDecrementBO.getCachePrefix() + STOCK + multiDecrementBO.getActivityId() + StrUtil.C_UNDERLINE + multiDecrementBO.getSkuId()
            local stock = tonumber(redis.call('get', cachePrefix.."stock:".. activityId.."_"..skuId.."_"..pointId ))
            redis.call('set',cachePrefix.."stock:".. activityId.."_"..skuId,tostring(stock + prodCount))
            redis.call('set',cachePrefix.."stock:".. activityId.."_"..skuId.."_"..pointId,tostring(stock + prodCount))
        end
        -- 删除订单记录map  key=userId value={(status+订单id)：1未付款, (info+订单id)：orderInfo}
        --redis.call('HDEL',cachePrefix.."order:"..userId, "status:"..orderId, "info:"..orderId)
    end
end


-- 还原库存（订单支付后退款取消）
if (redis.call('exists', cachePrefix.."lock:"..orderId, tostring(prodCount)) ~= "1") then
    -- 如果有限购，则用户已购数量回退
    if (redis.call('exists', cachePrefix.."buy:".. activityId.."_"..userId) == "1") then
        -- 用户已购数量
        boughtNum = redis.call('get', cachePrefix.."buy:".. activityId.."_"..userId)
        redis.call('set',cachePrefix.."buy:"..activityId.."_"..userId, boughtNum - prodCount)
    end
    -- 库存回退
    if prodCount ~= 0 then
        -- 下面通过get获取当前的库存数量
        -- multiDecrementBO.getCachePrefix() + STOCK + multiDecrementBO.getActivityId() + StrUtil.C_UNDERLINE + multiDecrementBO.getSkuId()
        local stock = tonumber(redis.call('get', cachePrefix.."stock:".. activityId.."_"..skuId.."_"..pointId ))
        redis.call('set',cachePrefix.."stock:".. activityId.."_"..skuId,tostring(stock + prodCount))
        redis.call('set',cachePrefix.."stock:".. activityId.."_"..skuId.."_"..pointId,tostring(stock + prodCount))
    end
end

