---
--- Generated by EmmyLua(https://github.com/EmmyLua)
--- Created by jlutt.
--- DateTime: 2020-09-07 16:26
--- 客户余额操作
--- 客户余额的操作基本为单个客户的操作，客户存款，预存款冲抵
---

local key = KEYS[1]
local jsonData = ARGV[2]
local jsonCheckData = ARGV[1]

local material = cjson.decode(jsonData)
local checkMaterial = cjson.decode(jsonCheckData)

local result = {}

result['error'] = 0
result['errorMsg'] = ''

--- 检查能否减少数量
for k, v in pairs(checkMaterial) do
    local numName = v['numName']
    local numKey = v['numKey']
    local numField = v['numField']
    local nowNum = tonumber(redis.call('HGET', numKey, numField))

    if (nowNum == nil) then
        nowNum = 0;
    end

    local incrNum = v['incrNum']

    if ((nowNum == nil or nowNum <= 0) and (incrNum < 0)) then
        result['error'] = 1
        result['errorMsg'] = numName .. '余额不足'
        break ;
    end

    if (nowNum + incrNum) < 0 then
        result['error'] = 1
        result['errorMsg'] = numName .. '余额不足'
        break ;
    end
end

local currIndex2 = 1
local stock = {}
if (result['error'] == 0) then
    --数量都够，可以操作
    for k, v in pairs(material) do
        local numKey = v['numKey']
        local numField = v['numField']
        local incrNum = v['incrNum']

        stock[currIndex2] = {}

        stock[currIndex2]['idClient'] = v['idClient'];

        local iExists = redis.call("HEXISTS", numKey, numField);
        if (iExists == 0) then
            stock[currIndex2]['insert'] = 1
        else
            stock[currIndex2]['insert'] = 0
        end

        local afterNum = redis.call("HINCRBY", numKey, numField, incrNum)

        stock[currIndex2]['beforeNum'] = afterNum - incrNum
        stock[currIndex2]['afterNum'] = afterNum
        stock[currIndex2]['calcNum'] = incrNum

        currIndex2 = currIndex2 + 1
    end
end

local time = redis.call('TIME')
result['time'] = time[1]
result['microseconds'] = time[2]

result['clientList'] = stock

local re = cjson.encode(result);

return re
