---
--- Generated by EmmyLua(https://github.com/EmmyLua)
--- Created by jlutt.
--- DateTime: 2020-09-03 9:38
--- 库存调整精度
---

local key = KEYS[1]
local virualKey = KEYS[2]

local field = ARGV[1]..'-*'
local oldPrecise = tonumber(ARGV[2])
local newPrecise = tonumber(ARGV[3])

local scanTable = {}
local scanVirsualTable = {}
local cursor = 0

repeat
    local rep = redis.call('HSCAN', key, cursor, 'MATCH', field)
    cursor = rep[1]
    for k, v in pairs(rep[2]) do
        --- lua中k为序号，从1开始
        if k % 2 == 0 then
            local numField = rep[2][k -1]
            local numValue = v

            ---hscan的缺点：同一个元素可能会被返回多次
            if (scanTable[numField] == nil) then
                ---不能在hscan中直接调用hset命令，报错replicate_commands
                ---local newValue = v * (10 ^ (newPrecise - oldPrecise))
                ---redis.call("HSET", key, numField, newValue)
                ---redis.log(redis.LOG_WARNING, 'c----' ..numField..'='.. numValue..'=='..newValue);
                scanTable[numField] = numValue
            end
        end
    end
until cursor == '0'

cursor = 0
repeat
    local rep = redis.call('HSCAN', virualKey, cursor, 'MATCH', field)
    cursor = rep[1]
    for k, v in pairs(rep[2]) do
        --- lua中k为序号，从1开始
        if k % 2 == 0 then
            local numField = rep[2][k -1]
            local numValue = v

            ---hscan的缺点：同一个元素可能会被返回多次
            if (scanVirsualTable[numField] == nil) then
                ---不能在hscan中直接调用hset命令，报错replicate_commands
                ---local newValue = v * (10 ^ (newPrecise - oldPrecise))
                ---redis.call("HSET", key, numField, newValue)
                ---redis.log(redis.LOG_WARNING, 'c----' ..numField..'='.. numValue..'=='..newValue);
                scanVirsualTable[numField] = numValue
            end
        end
    end
until cursor == '0'

---https://redis.io/commands/EVAL#replicating-commands-instead-of-scripts
redis.replicate_commands()

local stock = {}
local currIndex2 = 1
local x = {}
for k, v in pairs(scanTable) do
    local newValue = math.floor(v * (10 ^ (newPrecise - oldPrecise)))
    redis.call("HSET", key, k, newValue)

    stock[currIndex2] = {}
    stock[currIndex2]['stockKey'] = k
    stock[currIndex2]['stockNum'] = newValue

    ---redis.log(redis.LOG_WARNING, 'b----' ..k..'='.. v .. '==='..newValue)

    currIndex2 = currIndex2 + 1
end

local currIndex3 = 1
for k, v in pairs(scanVirsualTable) do
    local newValue = math.floor(v * (10 ^ (newPrecise - oldPrecise)))
    redis.call("HSET", virualKey, k, newValue)

    ---redis.log(redis.LOG_WARNING, 'b----' ..k..'='.. v .. '==='..newValue)

    currIndex3 = currIndex3 + 1
end

---释放变量
scanTable = nil
scanVirsualTable = nil

---返回值
local time = redis.call('TIME')
x['time'] = time[1]
x['microseconds'] = time[2]
x['stockList'] = stock
local re = cjson.encode(x);

return re
