package com.weather.modules.weather.dailydata;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.weather.common.utils.ConvertUtils;
import com.weather.modules.weather.dailydata.dto.ImportProgress;
import com.weather.modules.weather.dailydata.entity.WeatherDailyDataEntity;
import com.weather.modules.weather.dailydata.service.WeatherDailyDataService;
import com.weather.modules.weather.dailydata.vo.WeatherExcelVO;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDate;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
public class WeatherDataListener extends AnalysisEventListener<WeatherExcelVO> {
    private final WeatherDailyDataService weatherService;
    private final ImportProgress progress;
    private final List<WeatherDailyDataEntity> list = new ArrayList<>();

    private static final int BATCH_COUNT = 2000;

    public WeatherDataListener(WeatherDailyDataService weatherService) {
        this.weatherService = weatherService;
        this.progress = null;
    }

    public WeatherDataListener(WeatherDailyDataService weatherService, ImportProgress progress) {
        this.weatherService = weatherService;
        this.progress = progress;
    }

    @Override
    public void invoke(WeatherExcelVO data, AnalysisContext context) {
        // 同时计数（替代独立的 countListener，避免双次读取）
        if (progress != null) {
            progress.incrementTotalRows();
        }

        WeatherDailyDataEntity entity = ConvertUtils.sourceToTarget(data, WeatherDailyDataEntity.class);

        try {
            LocalDate localDate = LocalDate.of(data.getYear(), data.getMonth(), data.getDay());
            entity.setObserveDate(Date.from(localDate.atStartOfDay(ZoneId.of("GMT+8")).toInstant()));
        } catch (Exception e) {
            log.warn("第{}行日期转换失败: {}年{}月{}日，已跳过", context.readRowHolder().getRowIndex(),
                     data.getYear(), data.getMonth(), data.getDay());
            return;
        }

        list.add(entity);

        if (list.size() >= BATCH_COUNT) {
            saveData();
            list.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        saveData();
        log.info("Excel解析完成，全部数据已入库");
    }

    private void saveData() {
        if (!list.isEmpty()) {
            weatherService.insertBatch(list);
            if (progress != null) {
                progress.getProcessedRows().addAndGet(list.size());
            }
        }
    }
}