---
--- Generated by EmmyLua(https://github.com/EmmyLua)
--- Created by 81460.
--- DateTime: 2020-01-13 14:10
--- 纸张、辅料的库存数量操作

local key = KEYS[1]

local field = ARGV[1]
local incrNum = tonumber(ARGV[2])

local x = {}
local nowNum = tonumber(redis.call('HGET', key, field))

if (nowNum == nil) then
    x['beforeStock'] = 0
    x['insert'] = 1
else
    x['beforeStock'] = nowNum
    x['insert'] = 0
end

if (nowNum == nil) then
    if (incrNum >= 0) then
        --- 入库操作
        redis.call("HSET", key, field, incrNum)
        x['stockNum'] = incrNum
        x['afterStock'] = incrNum
    else
        --- 出库操作
        x['stockNum'] = -1
        x['insert'] = -1
        x['afterStock'] = -1
    end
else
    local afterNum = tonumber(redis.call("HINCRBY", key, field, incrNum))
    if (afterNum >= 0.0) then
        --- 可以操作
        x['stockNum'] = incrNum
        x['afterStock'] = afterNum
        --- return afterNum
    else
        --- 为负了，则加回去，不允许操作
        redis.call("HINCRBY", key, field, -1 * incrNum)
        x['stockNum'] = -1
        x['insert'] = -1
        x['afterStock'] = -1
        --- return -1
    end
end

local time = redis.call('TIME')
x['time'] = time[1]
x['microseconds'] = time[2]
local re = cjson.encode(x);

return re
