package com.goomood.phm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.goomood.phm.domain.FaultMonitorA;
import com.goomood.phm.mapper.FaultMonitorAMapper;
import com.goomood.phm.service.FaultMonitorService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 故障监控服务实现
 */
@Service
public class FaultMonitorServiceAImpl implements FaultMonitorService {

    @Resource
    private FaultMonitorAMapper faultMonitorAMapper;

    @Override
    public Map<String, Long> getTop5FaultyPartsNextMonthInThreeYears() {
        LocalDate currentDate = LocalDate.now();
        LocalDate nextMonth = currentDate.plusMonths(1);
        int targetMonth = nextMonth.getMonthValue();

        // 查询近三年数据
        QueryWrapper<FaultMonitorA> queryWrapper = new QueryWrapper<>();
        queryWrapper.between("incident_date",
                toDate(currentDate.minusYears(3)),
                toDate(currentDate));

        List<FaultMonitorA> faultMonitors = faultMonitorAMapper.selectList(queryWrapper);

        return faultMonitors.stream()
                .filter(fault -> isTargetMonth(fault.getIncidentDate(), targetMonth))
                .filter(this::isValidFaultPart)
                .collect(Collectors.groupingBy(
                        FaultMonitorA::getFaultyPartName,
                        Collectors.counting()
                ))
                .entrySet().stream()
                .sorted(Map.Entry.<String, Long>comparingByValue().reversed())
                .limit(5)
                .collect(Collectors.toMap(
                        Map.Entry::getKey,
                        Map.Entry::getValue,
                        (e1, e2) -> e1,
                        LinkedHashMap::new
                ));
    }

    @Override
    public Map<String, Long> getTop5FaultyPartsInSixMonths() {
        LocalDate currentDate = LocalDate.now();

        // 使用MyBatis-Plus查询近半年数据
        QueryWrapper<FaultMonitorA> queryWrapper = new QueryWrapper<>();
        queryWrapper.between("incident_date",
                toDate(currentDate.minusMonths(6)),
                toDate(currentDate));

        List<FaultMonitorA> faultMonitors = faultMonitorAMapper.selectList(queryWrapper);

        return faultMonitors.stream()
                .filter(this::isValidFaultPart)
                .collect(Collectors.groupingBy(
                        FaultMonitorA::getFaultyPartName,
                        Collectors.counting()
                ))
                .entrySet().stream()
                .sorted(Map.Entry.<String, Long>comparingByValue().reversed())
                .limit(5)
                .collect(Collectors.toMap(
                        Map.Entry::getKey,
                        Map.Entry::getValue,
                        (e1, e2) -> e1,
                        LinkedHashMap::new
                ));
    }

    // 辅助方法：LocalDate转Date
    private Date toDate(LocalDate localDate) {
        return Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
    }

    // 检查是否为目标月份的故障
    private boolean isTargetMonth(Date date, int targetMonth) {
        if (date == null) return false;
        return toLocalDate(date).getMonthValue() == targetMonth;
    }

    // 辅助方法：Date转LocalDate
    private LocalDate toLocalDate(Date date) {
        return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
    }

    // 验证故障部件有效性
    private boolean isValidFaultPart(FaultMonitorA fault) {
        return fault != null
                && fault.getFaultyPartName() != null
                && !fault.getFaultyPartName().trim().isEmpty();
    }
}