package com.yeejoin.amos.boot.module.statistcs.biz.job;

import com.yeejoin.amos.boot.module.jg.api.mapper.JgUseRegistrationMapper;
import com.yeejoin.amos.boot.module.statistics.api.entity.CylinderBusinessStatistics;
import com.yeejoin.amos.boot.module.statistics.api.mapper.CylinderBusinessStatisticsMapper;
import lombok.extern.slf4j.Slf4j;
import net.javacrumbs.shedlock.spring.annotation.SchedulerLock;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 定时任务统计
 *
 * @author LiuLin
 */
@EnableScheduling
@Component
@Slf4j
public class MonthCylinderBusinessStatisticsJob {

    private final JgUseRegistrationMapper useRegistrationMapper;
    private final CylinderBusinessStatisticsMapper businessStatisticsMapper;

    public MonthCylinderBusinessStatisticsJob(JgUseRegistrationMapper useRegistrationMapper,
                                              CylinderBusinessStatisticsMapper businessStatisticsMapper) {
        this.useRegistrationMapper = useRegistrationMapper;
        this.businessStatisticsMapper = businessStatisticsMapper;
    }

    @Scheduled(cron = "0 */5 * * * ?")
    @SchedulerLock(name = "cylinderBusinessStatisticsJob", lockAtMostFor = "PT1H")
    public void cylinderBusinessStatisticsJob() {
        List<Map<String, Object>> useRegisterCountList = useRegistrationMapper.getUseRegisterCountTotal();
        if (!CollectionUtils.isEmpty(useRegisterCountList)) {
            businessStatisticsMapper.deleteAll();
            List<CylinderBusinessStatistics> statisticsList = useRegisterCountList.stream()
                    .map(item -> new CylinderBusinessStatistics(
                            (String) item.get("time"),
                            (String) item.get("supervisionOrgCode")
                    ))
                    .collect(Collectors.toList());
            businessStatisticsMapper.insertBatch(statisticsList);
        }
    }
}
