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 lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

@Slf4j
@Component
@RequiredArgsConstructor
public class SysSchedule {

    private final SysParamService sysParamService;
    private final JdbcTemplate jdbcTemplate;
    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());
//            EisCache.SYS_PARAM_MAP.put(sysParam.getParamNo(), sysParam.getParamValue());
        }
    }
    @Scheduled(cron = "0 0 3 * * ?")
    public void deleteLog() {
        try {
            jdbcTemplate.execute("delete from plg_fx_api_log where P_START_TIME < DATE_SUB(now(),INTERVAL 30 day)");
        } catch (Exception e) {
            log.error("删除日志失败：{}", e.getMessage(), e);
        }
    }
}
