package org.wcs.helper;

import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.wcs.constant.ConstantData;
import org.wcs.utils.AppStringUtils;

@Component
@RequiredArgsConstructor
public class PlcTaskIdHelper {

    private final AppConfigHelper appConfigHelper;
    private final StringRedisTemplate stringRedisTemplate;

    private static final int MAX_COUNT = 100; // 最大任务ID数
    private static final String KEY_TASK_ID = ConstantData.SYSTEM_NAME + ":config";

    /**
     * 获取新的任务ID
     * @return 任务ID
     */
    public Integer newTaskId()
    {
        String plcTaskIdRedisKet = KEY_TASK_ID + ":plcTaskId";
        Long size = stringRedisTemplate.opsForList().size(plcTaskIdRedisKet);
        if(size == null || size < MAX_COUNT - 80) {
            String plcTaskId = appConfigHelper.getConfig("PLC_TASK_ID");
            if (plcTaskId == null) {
                return null;
            }
            if(!AppStringUtils.isNumber(plcTaskId)) {
                return null;
            }
            int plcTaskIdInt = Integer.parseInt(plcTaskId);
            if(plcTaskIdInt > 150000000) {
                plcTaskIdInt = 100000;
            }
            int maxPlcTaskId = plcTaskIdInt + MAX_COUNT;
            String setResult = appConfigHelper.SetConfig("PLC_TASK_ID", String.valueOf(maxPlcTaskId));
            if(AppStringUtils.isNotEmpty(setResult)) {
                return null; // 设置数据库失败
            }
            for(int i = plcTaskIdInt; i < plcTaskIdInt + MAX_COUNT; i++) {
                stringRedisTemplate.opsForList().rightPush(plcTaskIdRedisKet, String.valueOf(i));
            }
        }
        String plcTaskIdString = stringRedisTemplate.opsForList().leftPop(plcTaskIdRedisKet);
        if(plcTaskIdString == null) {
            return null; // 获取redis数据失败
        }
        return Integer.parseInt(plcTaskIdString);
    }

}
