package com.aucma.report.service.impl;

import com.aucma.report.domain.vo.*;
import com.aucma.report.mapper.Board5Mapper;
import com.aucma.report.service.IBoard5Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Board5看板数据Service业务层处理
 * 设备保养与故障分析看板
 *
 * @author YinQ
 */
@Service
public class Board5ServiceImpl implements IBoard5Service {

    @Autowired
    private Board5Mapper board5Mapper;

    /**
     * 获取工单统计（总数、已完成、完成率、停机）
     */
    @Override
    public Board5OrderWorkStatisticsVo getOrderWorkStatistics() {
        // 初始化返回对象
        Board5OrderWorkStatisticsVo vo = new Board5OrderWorkStatisticsVo();
        // 查询工单统计数据
        HashMap<String, Object> stats = board5Mapper.selectOrderWorkStatistics();
        if (stats != null) {
            // 安全转换各统计数
            Long totalCount = getLongValue(stats.get("TOTAL_COUNT"));
            Long completeCount = getLongValue(stats.get("COMPLETE_COUNT"));
            Long stopCount = getLongValue(stats.get("STOP_COUNT"));
            // 设置统计结果
            vo.setTotalCount(totalCount);
            vo.setCompleteCount(completeCount);
            vo.setStopCount(stopCount);
            // 完成率=完成/总数，返回不带“%”
            if (totalCount > 0) {
                vo.setCompleteRate(String.valueOf(Math.round(completeCount * 100.0 / totalCount)));
            } else {
                vo.setCompleteRate("0");
            }
        } else {
            // 无数据时返回0
            vo.setTotalCount(0L);
            vo.setCompleteCount(0L);
            vo.setStopCount(0L);
            vo.setCompleteRate("0");
        }
        return vo;
    }

    /**
     * 获取维修时间统计（平均响应时间、平均维修时间）
     * 时间口径为全量历史，不限定日期范围
     */
    @Override
    public Board5RepairTimeStatisticsVo getRepairTimeStatistics() {
        // 初始化返回对象
        Board5RepairTimeStatisticsVo vo = new Board5RepairTimeStatisticsVo();
        // 查询平均响应/维修时间
        HashMap<String, Object> stats = board5Mapper.selectRepairTimeStatistics();
        if (stats != null) {
            // 直接返回字符串，避免精度丢失
            vo.setAvgResponseTime(getStringValue(stats.get("AVG_RESPONSE_TIME")));
            vo.setAvgRepairTime(getStringValue(stats.get("AVG_REPAIR_TIME")));
        } else {
            // 无数据时返回0
            vo.setAvgResponseTime("0");
            vo.setAvgRepairTime("0");
        }
        return vo;
    }

    /**
     * 获取保养执行情况统计
     * 时间口径为全量历史，不限定日期范围
     */
    @Override
    public Board5MaintStatisticsVo getMaintStatistics() {
        // 初始化返回对象
        Board5MaintStatisticsVo vo = new Board5MaintStatisticsVo();
        // 查询保养统计
        HashMap<String, Object> stats = board5Mapper.selectMaintStatistics();
        if (stats != null) {
            // 安全转换各状态数量
            Long planCount = getLongValue(stats.get("PLAN_COUNT"));
            Long completeCount = getLongValue(stats.get("COMPLETE_COUNT"));
            Long waitingCount = getLongValue(stats.get("WAITING_COUNT"));
            Long doingCount = getLongValue(stats.get("DOING_COUNT"));
            Long verifyCount = getLongValue(stats.get("VERIFY_COUNT"));

            // 设置数量字段
            vo.setPlanCount(planCount);
            vo.setCompleteCount(completeCount);
            vo.setWaitingCount(waitingCount);
            vo.setDoingCount(doingCount);
            vo.setVerifyCount(verifyCount);

            // 计算各状态比例，返回不带“%”
            if (planCount > 0) {
                vo.setWaitingRate(String.valueOf(Math.round(waitingCount * 100.0 / planCount)));
                vo.setDoingRate(String.valueOf(Math.round(doingCount * 100.0 / planCount)));
                vo.setVerifyRate(String.valueOf(Math.round(verifyCount * 100.0 / planCount)));
                vo.setCompleteRate(String.valueOf(Math.round(completeCount * 100.0 / planCount)));
            } else {
                vo.setWaitingRate("0");
                vo.setDoingRate("0");
                vo.setVerifyRate("0");
                vo.setCompleteRate("0");
            }
        } else {
            // 无数据默认0
            vo.setPlanCount(0L);
            vo.setCompleteCount(0L);
            vo.setWaitingCount(0L);
            vo.setDoingCount(0L);
            vo.setVerifyCount(0L);
            vo.setWaitingRate("0");
            vo.setDoingRate("0");
            vo.setVerifyRate("0");
            vo.setCompleteRate("0");
        }
        return vo;
    }

    /**
     * 获取巡检执行情况统计
     * 时间口径为全量历史，不限定日期范围
     */
    @Override
    public Board5InspectStatisticsVo getInspectStatistics() {
        // 初始化返回对象
        Board5InspectStatisticsVo vo = new Board5InspectStatisticsVo();
        // 查询巡检统计
        HashMap<String, Object> stats = board5Mapper.selectInspectStatistics();
        if (stats != null) {
            // 安全转换应检/已检数量
            Long deviceCount = getLongValue(stats.get("DEVICE_COUNT"));
            Long completeCount = getLongValue(stats.get("COMPLETE_COUNT"));
            // 设置应检数量
            vo.setDeviceCount(deviceCount);
            // 完成率=已检/应检
            if (deviceCount > 0) {
                vo.setCompleteRate(String.valueOf(Math.round(completeCount * 100.0 / deviceCount)));
            } else {
                vo.setCompleteRate("0");
            }
        } else {
            vo.setDeviceCount(0L);
            vo.setCompleteRate("0");
        }
        return vo;
    }

    /**
     * 获取设备状态分布
     * 统计有效设备全量，不限定日期范围
     */
    @Override
    public Board5DeviceStatusDistributionVo getDeviceStatusDistribution() {
        // 初始化返回对象
        Board5DeviceStatusDistributionVo vo = new Board5DeviceStatusDistributionVo();
        // 查询设备状态分布
        HashMap<String, Object> stats = board5Mapper.selectDeviceStatusDistribution();
        if (stats != null) {
            // 安全转换各状态数量
            Long totalCount = getLongValue(stats.get("TOTAL_COUNT"));
            Long normalCount = getLongValue(stats.get("NORMAL_COUNT"));
            Long abnormalCount = getLongValue(stats.get("ABNORMAL_COUNT"));
            Long scrapCount = getLongValue(stats.get("SCRAP_COUNT"));
            Long experimentCount = getLongValue(stats.get("EXPERIMENT_COUNT"));

            // 计算分布比例，返回不带“%”
            if (totalCount > 0) {
                vo.setExperimentPercent(Math.round(experimentCount * 100.0 / totalCount));
                vo.setUncheckedPercent(Math.round(scrapCount * 100.0 / totalCount));
                vo.setNormalPercent(Math.round(normalCount * 100.0 / totalCount));
                vo.setAbnormalPercent(Math.round(abnormalCount * 100.0 / totalCount));
            } else {
                vo.setExperimentPercent(0L);
                vo.setUncheckedPercent(0L);
                vo.setNormalPercent(0L);
                vo.setAbnormalPercent(0L);
            }
        } else {
            vo.setExperimentPercent(0L);
            vo.setUncheckedPercent(0L);
            vo.setNormalPercent(0L);
            vo.setAbnormalPercent(0L);
        }
        return vo;
    }

    /**
     * 获取故障来源分布
     * 时间口径为全量历史，不限定日期范围
     */
    @Override
    public Board5FaultSourceDistributionVo getFaultSourceDistribution() {
        // 初始化返回对象
        Board5FaultSourceDistributionVo vo = new Board5FaultSourceDistributionVo();
        // 查询故障来源统计
        HashMap<String, Object> stats = board5Mapper.selectFaultSourceDistribution();
        if (stats != null) {
            // 安全转换各来源数量
            Long totalCount = getLongValue(stats.get("TOTAL_COUNT"));
            Long maintainCount = getLongValue(stats.get("MAINTAIN_COUNT"));
            Long runningCount = getLongValue(stats.get("RUNNING_COUNT"));
            Long naturalCount = getLongValue(stats.get("NATURAL_COUNT"));

            // 计算来源比例，返回不带“%”
            if (totalCount > 0) {
                vo.setMaintainPercent(Math.round(maintainCount * 100.0 / totalCount));
                vo.setRunningPercent(Math.round(runningCount * 100.0 / totalCount));
                vo.setNaturalPercent(Math.round(naturalCount * 100.0 / totalCount));
            } else {
                vo.setMaintainPercent(0L);
                vo.setRunningPercent(0L);
                vo.setNaturalPercent(0L);
            }
        } else {
            vo.setMaintainPercent(0L);
            vo.setRunningPercent(0L);
            vo.setNaturalPercent(0L);
        }
        return vo;
    }

    /**
     * 获取故障数量曲线
     * 近30天（含今天），按自然日统计
     */
    @Override
    public List<Board5FaultTrendVo> getFaultTrendList() {
        // 查询近30天故障数量
        List<Board5FaultTrendVo> list = board5Mapper.selectFaultTrendList();
        return list != null ? list : new ArrayList<>();
    }

    /**
     * 获取产量机台TOP5
     * 当天（00:00-23:59）按 RT 实时累计产量统计
     */
    @Override
    public List<Board5ProductionTopVo> getProductionTop5() {
        // 查询TOP5产量机台
        List<Board5ProductionTopVo> list = board5Mapper.selectProductionTop5();
        if (list == null || list.isEmpty()) {
            return new ArrayList<>();
        }
        // 查询 RT 中当天最大产量用于比例计算，
        // 这样可以保证 TOP5 排名值和进度条百分比都来自同一份实时事实数据。
        Long maxProduction = board5Mapper.selectMaxProduction();
        if (maxProduction == null || maxProduction == 0) {
            // 避免出现分母为 0 的情况，前端进度条仍可安全展示。
            maxProduction = 1L;
        }
        // 逐条计算百分比
        for (Board5ProductionTopVo vo : list) {
            if (vo.getProduction() != null && vo.getProduction() > 0) {
                vo.setPercent(Math.round(vo.getProduction() * 100.0 / maxProduction));
            } else {
                vo.setPercent(0L);
            }
        }
        return list;
    }

    /**
     * 安全获取Long值
     */
    private Long getLongValue(Object obj) {
        // 空值保护
        if (obj == null) {
            return 0L;
        }
        // 数值类型直接转换
        if (obj instanceof Number) {
            return ((Number) obj).longValue();
        }
        // 字符串安全解析
        try {
            return Long.parseLong(obj.toString());
        } catch (NumberFormatException e) {
            return 0L;
        }
    }

    /**
     * 安全获取String值
     */
    private String getStringValue(Object obj) {
        // 空值返回字符串0
        if (obj == null) {
            return "0";
        }
        return obj.toString();
    }
}
