package com.yeejoin.amos.boot.module.jg.biz.data.fix.patcher;

import com.yeejoin.amos.boot.module.jg.biz.service.impl.IdxBizJgUseInfoServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.util.StopWatch;

import java.util.List;
import java.util.Map;

@Slf4j
public abstract class FullBatchDataPatcher implements HistoricalDataPatcher<Map<String, Object>> {

    private final ApplicationContext applicationContext;

    protected FullBatchDataPatcher(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    @Override
    public Integer patchBatchData(Map<String, Object> params) {
        StopWatch watch = new StopWatch();
        watch.start();
        IdxBizJgUseInfoServiceImpl useInfoService = applicationContext.getBean(IdxBizJgUseInfoServiceImpl.class);
        Integer maxVersion = useInfoService.getBaseMapper().selectMaxVersion();
        Integer nextVersion = maxVersion + 1;
        List<String> refreshRecords = useInfoService.getBaseMapper().selectUseInfoOfOneVersionAll(nextVersion);
        while (!refreshRecords.isEmpty()) {
            refreshRecords.parallelStream().forEach(record -> {
                try {
                    beforePatching(record);
                    patchSingleRecord(record);
                    afterPatching(record);
                } catch (Exception e) {
                    // 异常数据跳过
                    log.error("数据修补失败,设备:{}", record, e);
                }
            });
            useInfoService.getBaseMapper().updateVersionBatch(refreshRecords, nextVersion);
            refreshRecords = useInfoService.getBaseMapper().selectUseInfoOfOneVersionAll(nextVersion);
        }
        watch.stop();
        log.info("数据修补完成，共处理{}条记录，耗时: {}秒", refreshRecords, watch.getTotalTimeSeconds());
        return null;
    }

    protected abstract void beforePatching(String record);

    protected abstract void patchSingleRecord(String record);

    protected abstract void afterPatching(String record);

}
