package com.ruoyi.fire.service.impl;

import com.ruoyi.fire.domain.FireFacilityReport;
import com.ruoyi.fire.service.IFireFacilityReportService;
import com.ruoyi.fire.mapper.FireFacilityReportMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.*;

@Service
public class FireFacilityReportServiceImpl extends ServiceImpl<FireFacilityReportMapper, FireFacilityReport> implements IFireFacilityReportService {

    // 状态常量定义
    public static final int STATUS_NORMAL = 0;         // 正常
    public static final int STATUS_WILL_EXPIRE = 1;    // 即将过期
    public static final int STATUS_EXPIRED = 2;        // 已过期
    public static final int STATUS_REPAIRING = 3;      // 维修中
    public static final int STATUS_REPLACED = 4;       // 已更换
    public static final int STATUS_SCRAPPED = 5;       // 已报废

    @Override
    public List<FireFacilityReport> selectFireFacilityReportList(FireFacilityReport fireFacilityReport) {
        return baseMapper.selectFireFacilityReportList(fireFacilityReport);
    }

    @Override
    @Transactional
    public int updateExpiryStatus() {
        return 0; // 已废弃
    }

    /**
     * 支持按设施类型筛选的统计数据
     */
    @Override
    public List<Map<String, Object>> getReportData(String facilityType) { // 接收设施类型参数
        // 1. 按设施类型筛选数据
        FireFacilityReport query = new FireFacilityReport();
        query.setFacilityType(facilityType); // 应用前端筛选条件
        List<FireFacilityReport> list = selectFireFacilityReportList(query);

        // 2. 计算动态状态和状态文本
        for (FireFacilityReport facility : list) {
            Integer dynamicStatus = calculateDynamicStatus(facility.getExpiryDate(), facility.getStatus());
            facility.setDynamicStatus(dynamicStatus);
            facility.setStatusText(getStatusText(dynamicStatus));
        }

        // 3. 按【动态状态+设施类型】分组统计
        Map<String, Map<String, Integer>> statsMap = new HashMap<>(16);
        for (FireFacilityReport facility : list) {
            String statusKey = String.valueOf(facility.getDynamicStatus());
            String typeKey = facility.getFacilityType();
            if (typeKey == null) typeKey = "未知类型"; // 处理空类型

            statsMap.computeIfAbsent(statusKey, k -> new HashMap<>(16));
            Integer currentTotal = statsMap.get(statusKey).getOrDefault(typeKey, 0);
            statsMap.get(statusKey).put(typeKey, currentTotal + (facility.getQuantity() == null ? 1 : facility.getQuantity()));
        }

        // 4. 按优先级排序组装结果
        List<Map<String, Object>> resultList = new ArrayList<>();
        Integer[] priorityOrder = {STATUS_REPAIRING, STATUS_REPLACED, STATUS_SCRAPPED, STATUS_NORMAL, STATUS_WILL_EXPIRE, STATUS_EXPIRED};

        for (Integer status : priorityOrder) {
            Map<String, Integer> typeCountMap = statsMap.get(String.valueOf(status));
            if (typeCountMap == null || typeCountMap.isEmpty()) continue;

            for (Map.Entry<String, Integer> entry : typeCountMap.entrySet()) {
                Map<String, Object> reportItem = new HashMap<>(8);
                reportItem.put("status", status);
                reportItem.put("statusText", getStatusText(status));
                reportItem.put("facilityType", entry.getKey());
                reportItem.put("total", entry.getValue());
                resultList.add(reportItem);
            }
        }

        return resultList;
    }

    @Override
    public Integer calculateDynamicStatus(Date expiryDate, Integer originalStatus) {
        // 优先处理特殊状态
        if (originalStatus != null) {
            if (originalStatus == STATUS_REPAIRING || originalStatus == STATUS_REPLACED || originalStatus == STATUS_SCRAPPED) {
                return originalStatus;
            }
        }

        // 无过期日期默认正常
        if (expiryDate == null) {
            return STATUS_NORMAL;
        }

        // 日期转换（处理时区）
        LocalDate today = LocalDate.now();
        LocalDate expiryLocalDate = expiryDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        long daysDiff = ChronoUnit.DAYS.between(today, expiryLocalDate);

        if (daysDiff < 0) {
            return STATUS_EXPIRED;
        } else if (daysDiff <= 30) {
            return STATUS_WILL_EXPIRE;
        } else {
            return STATUS_NORMAL;
        }
    }

    @Override // 实现接口方法
    public String getStatusText(Integer status) {
        if (status == null) {
            return "未知状态";
        }
        switch (status) {
            case STATUS_NORMAL: return "正常";
            case STATUS_WILL_EXPIRE: return "即将过期";
            case STATUS_EXPIRED: return "已过期";
            case STATUS_REPAIRING: return "维修中";
            case STATUS_REPLACED: return "已更换";
            case STATUS_SCRAPPED: return "已报废";
            default: return "未知状态";
        }
    }
}