package com.prolog.eis.schedule;

import com.prolog.eis.constants.sys.SysParamConstants;
import com.prolog.eis.model.sys.SysParam;
import com.prolog.eis.service.sys.SysParamService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@RequiredArgsConstructor
public class SysSchedule {

    private final SysParamService sysParamService;
    private final RedisTemplate redisTemplate;

    @Scheduled(initialDelay = 1000, fixedDelay = 10000)
    public void doUpdateSysParam() {
        checkSysParam();
    }

    private void checkSysParam() {
        List<SysParam> sysParams = sysParamService.findNeedRefresh();
        if (sysParams.isEmpty()) {
            return;
        }
        updateCache(sysParams);
        sysParamService.refresh(sysParams);
    }

    private void updateCache(List<SysParam> sysParams) {
        for (SysParam sysParam : sysParams) {
            redisTemplate.opsForValue().set(SysParamConstants.SYSPRE_FIX + sysParam.getParamNo(), sysParam.getParamValue());
        }
    }
}
