if redis.call('exists', KEYS[1]) == 0 then
    ---redis.log(redis.LOG_WARNING, 'kkk' .. KEYS[1]);
    return nil
else
    local tableCode = redis.call('get', KEYS[1]);
    if tableCode then
        redis.log(redis.LOG_WARNING, tableCode);
        local x = cjson.decode(tableCode);
        local yearlength = tonumber(x['yearLength']);
        local ntime = ARGV[1];
        if (yearlength == 2) then
            ntime = ARGV[2];
        end
        ---redis.log(redis.LOG_WARNING, 'a' .. ntime);
        local prefixlength = tonumber(x['prefixLength']);
        ---redis.log(redis.LOG_WARNING, 'b' .. prefixlength);
        local datelength = tonumber(x['dateLength']);
        ---redis.log(redis.LOG_WARNING, 'b' .. datelength);
        local currcode = x['currcode'];
        if currcode ~= nil then
            redis.log(redis.LOG_WARNING, 'c' .. currcode);
        end
        local codeprefix = '';
        if (prefixlength > 0) then
            codeprefix = x['codePrefix'];
        end
        ---redis.log(redis.LOG_WARNING, 'd' .. codeprefix);
        local codeFormat = x['codeFormat'];
        local acttime = string.sub(ntime, 1, datelength);
        ---redis.log(redis.LOG_WARNING, 'e' .. codeFormat);
        if (currcode and currcode ~= '') then
            ---redis.log(redis.LOG_WARNING, 'h' .. acttime);
            local codetime = string.sub(currcode, prefixlength + 1, datelength + prefixlength);
            ---redis.log(redis.LOG_WARNING, 'i' .. codetime);
            local codeindex = tonumber(string.sub(currcode, prefixlength + datelength + 1));
            ---redis.log(redis.LOG_WARNING, 'j' .. codeindex);
            if acttime == codetime then
                codeindex = codeindex + 1;
                x['currcode'] = codeprefix .. acttime .. string.format(codeFormat, codeindex);
            else
                codeindex = 1;
                x['currcode'] = codeprefix .. acttime .. string.format(codeFormat, codeindex);
            end
        else
            x['currcode'] = codeprefix .. acttime .. string.format(codeFormat, 1);
        end
        local re = cjson.encode(x);
        redis.call('set', KEYS[1], re);

        return re;
    end
end
return nil
