package com.sundot.airport.personnel.listener;

import com.sundot.airport.common.event.PersonnelEvent;
import com.sundot.airport.personnel.domain.PersonnelNonCadreMonthlyAssessment;
import com.sundot.airport.personnel.service.IPersonnelNonCadreMonthlyAssessmentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 非干部月度考核事件监听器
 *
 * @author sundot
 */
@Slf4j
@Component
public class PersonnelEventListener {

    @Autowired
    private IPersonnelNonCadreMonthlyAssessmentService personnelNonCadreMonthlyAssessmentService;

    /**
     * 异步处理事件
     */
    @Async("personnelAsyncExecutor")  // 关键：标记为异步方法
    @EventListener  // 监听PersonnelEvent事件
    public void handlePersonnel(PersonnelEvent event) {
        long start = System.currentTimeMillis();
        String month = event.getMonth();
        log.info("【异步处理】开始非干部月度考核【month={}】", month);
        PersonnelNonCadreMonthlyAssessment query = new PersonnelNonCadreMonthlyAssessment();
        query.setAssessmentMonthStart(month);
        List<PersonnelNonCadreMonthlyAssessment> list = personnelNonCadreMonthlyAssessmentService.selectPersonnelNonCadreMonthlyAssessmentList(query);
        list = list.stream()
                .sorted(Comparator.comparing(PersonnelNonCadreMonthlyAssessment::getAssessmentMonth))
                .collect(Collectors.toList());
        list.forEach(item -> {
            PersonnelNonCadreMonthlyAssessment data = personnelNonCadreMonthlyAssessmentService.selectPersonnelNonCadreMonthlyAssessmentById(item.getId());
            // 完善数据
            personnelNonCadreMonthlyAssessmentService.doImprove(data);
            // 修改非干部月度考核-仅更新主表数据
            personnelNonCadreMonthlyAssessmentService.updatePersonnelNonCadreMonthlyAssessmentOnly(data);
        });
        long end = System.currentTimeMillis();
        log.info("【异步处理】完成非干部月度考核【month={}】,耗时【{}】", month, end - start);
    }
}
