
local scriptStatusKey = KEYS[1]
local batchScriptSumKey = KEYS[2]
local scriptTaskKey = KEYS[3]
local startTimeKey = KEYS[4]
local waitStatusKey = KEYS[5]
local runStatusKey = KEYS[6]
local scriptIdKey = KEYS[7]
local taskIdKey = KEYS[8]
local clusterPrefixKey = KEYS[9]

local scriptStatus = '0'
local startTime = ARGV[1]
local taskStatus = ARGV[2]
-- 判断脚本状态缓存是否存在
if(redis.call('hexists', scriptStatusKey, scriptIdKey) > 0) then
   -- 脚本状态存在，该脚本任务已开始执行
   scriptStatus = redis.call('hget', scriptStatusKey, scriptIdKey)

   if(scriptStatus == '0') then
    -- 该脚本任务开始执行，等待中脚本数-1，执行中脚本数+1
    redis.call('hincrby', batchScriptSumKey, waitStatusKey, -1)
    redis.call('hincrby', batchScriptSumKey, runStatusKey, 1)
   end

    -- 开始执行，取消，超时，执行成功，执行失败与断言失败
   if(
    scriptStatus == '0'
    or scriptStatus == '1'
    or taskStatus == '5'
    or (taskStatus == '6' and scriptStatus ~= '5')
    or (taskStatus == '2' and (scriptStatus ~= '3' and scriptStatus ~= '5' and scriptStatus ~= '6'))
    or (taskStatus == '3' and (scriptStatus ~= '5' and scriptStatus ~= '6'))
    ) then
        scriptStatus = taskStatus
   end
else
    -- 脚本状态不存在，该脚本任务还未开始执行
    scriptStatus = taskStatus
    -- 该脚本任务开始执行，等待中脚本数-1，执行中脚本数+1
    if(redis.call('hexists', scriptTaskKey, taskIdKey) > 0) then
        redis.call('hincrby', batchScriptSumKey, waitStatusKey, -1)
        redis.call('hincrby', batchScriptSumKey, runStatusKey, 1)
    end
end

-- 更新脚本状态
redis.call('hset', scriptStatusKey, scriptIdKey, scriptStatus)

-- 判断任务是否终态，是则删除脚本任务关联，并统计脚本数据
if (taskStatus == '1') then
    -- 判断是否存在任务开始时间，不存在则插入
    if(redis.call('hexists', batchScriptSumKey, startTimeKey) <= 0) then
        redis.call('hset', batchScriptSumKey, startTimeKey, startTime)
    end
else
    -- 删除脚本任务关联，该关联由任务生成时插入
    if (redis.call('hdel', scriptTaskKey, taskIdKey) > 0 ) then
        -- 判断脚本任务是否全部执行完成
        if (redis.call('hlen', scriptTaskKey) <= 0) then
            -- 删除脚本任务关联缓存
            redis.call('del', scriptTaskKey)
            -- 脚本任务全部执行完成，删除脚本状态
            redis.call('hdel', scriptStatusKey, scriptIdKey)
            -- 脚本中任务全部执行完成，执行中脚本数-1，终态数量+1
            redis.call('hincrby', batchScriptSumKey, runStatusKey, -1)

            scriptStatus = clusterPrefixKey .. scriptStatus
            redis.call('hincrby', batchScriptSumKey, scriptStatus, 1)
        end
    end
end

return true