package com.steerinfo.meterwork.meterworkmonitor.rtdb;

import com.steerinfo.meterwork.meterworkmonitor.mapper.MeterWorkMonitorMapper;
import com.steerinfo.meterwork.meterworkmonitor.model.MeterWorkMonitor;
import com.steerinfo.meterwork.rtdb.RtdbPoolProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;

/**
 * 冷启动：Oracle → Tarantool 全量灌数（_dirty=false）。
 */
@Component
@Order(100)
@ConditionalOnExpression("'${rtdb.monitor.enabled:true}' == 'true' && '${rtdb.monitor.bootstrap-enabled:false}' == 'true'")
public class MeterWorkMonitorRtdbBootstrap implements ApplicationRunner {

    private static final Logger log = LoggerFactory.getLogger(MeterWorkMonitorRtdbBootstrap.class);

    @Resource
    private MeterWorkMonitorMapper meterWorkMonitorMapper;

    @Resource
    private MeterWorkMonitorRtdbRepository meterWorkMonitorRtdbRepository;

    @Resource
    private RtdbPoolProperties rtdbPoolProperties;

    @Override
    public void run(ApplicationArguments args) {
        if (rtdbPoolProperties == null || !rtdbPoolProperties.getMonitor().isBootstrapEnabled()) {
            return;
        }
        long start = System.currentTimeMillis();
        int ok = 0;
        int fail = 0;
        try {
            List<MeterWorkMonitor> rows = meterWorkMonitorMapper.selectByParameters(new HashMap<String, Object>());
            log.info("METER_WORK_MONITOR bootstrap start, oracleRows={}", rows == null ? 0 : rows.size());
            if (rows == null) {
                return;
            }
            for (MeterWorkMonitor row : rows) {
                try {
                    meterWorkMonitorRtdbRepository.replace(row, false);
                    ok++;
                } catch (Exception e) {
                    fail++;
                    log.error("bootstrap replace failed, pointNo={}", row.getPointNo(), e);
                }
            }
        } catch (Exception e) {
            log.error("METER_WORK_MONITOR bootstrap failed", e);
        } finally {
            log.info("METER_WORK_MONITOR bootstrap done, ok={}, fail={}, costMs={}",
                    ok, fail, System.currentTimeMillis() - start);
        }
    }
}
