package com.aucma.report.service.impl;

import com.aucma.report.domain.DeviceFaultAnalysisReport;
import com.aucma.report.domain.DeviceOeeReport;
import com.aucma.report.domain.RepairHoursReport;
import com.aucma.report.mapper.DmsReportMapper;
import com.aucma.report.service.IDmsReportService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * DMS 设备报表 Service 实现
 */
@Service
public class DmsReportServiceImpl implements IDmsReportService {

    @Autowired
    private DmsReportMapper dmsReportMapper;

    @Override
    public List<DeviceFaultAnalysisReport> deviceFaultAnalysisList(Map<String, Object> params) {
        return dmsReportMapper.deviceFaultAnalysisList(params);
    }

    @Override
    public List<RepairHoursReport> repairHoursReportList(Map<String, Object> params) {
        return dmsReportMapper.repairHoursReportList(params);
    }

    @Override
    public List<DeviceOeeReport> deviceOeeReportList(Map<String, Object> params) {
        List<DeviceOeeReport> list = dmsReportMapper.deviceOeeReportList(params);
        long plannedMinutes = calculatePlannedMinutes(params);
        if (plannedMinutes <= 0) {
            // 默认按一天 24 小时计算
            plannedMinutes = 24L * 60L;
        }
        for (DeviceOeeReport item : list) {
            if (item == null) {
                continue;
            }
            item.setPLANNED_TIME_MINUTES(plannedMinutes);
            Long downtime = item.getDOWNTIME_MINUTES();
            if (downtime == null) {
                downtime = 0L;
            }
            double availability;
            if (plannedMinutes <= 0) {
                availability = 1.0D;
            } else {
                availability = (double) (plannedMinutes - downtime) / (double) plannedMinutes;
                if (availability < 0) {
                    availability = 0;
                }
                if (availability > 1) {
                    availability = 1;
                }
            }
            // 当前版本暂不从生产/质量模块获取性能与良品率，先按 1 处理，可后续扩展
            double performance = 1.0D;
            double quality = 1.0D;

            item.setAVAILABILITY(round(availability, 4));
            item.setPERFORMANCE(round(performance, 4));
            item.setQUALITY(round(quality, 4));
            item.setOEE(round(availability * performance * quality, 4));
        }
        return list;
    }

    /**
     * 根据前端传入的 beginTime/endTime 计算计划时间（分钟）
     */
    private long calculatePlannedMinutes(Map<String, Object> params) {
        if (params == null) {
            return 0L;
        }
        Object beginObj = params.get("beginTime");
        Object endObj = params.get("endTime");
        if (beginObj == null || endObj == null) {
            return 0L;
        }
        String beginStr = String.valueOf(beginObj);
        String endStr = String.valueOf(endObj);
        if (beginStr.isEmpty() || endStr.isEmpty()) {
            return 0L;
        }
        // 统一补上时间，按自然日计算
        if (beginStr.length() == 10) {
            beginStr = beginStr + " 00:00:00";
        }
        if (endStr.length() == 10) {
            endStr = endStr + " 23:59:59";
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date begin = sdf.parse(beginStr);
            Date end = sdf.parse(endStr);
            if (begin == null || end == null) {
                return 0L;
            }
            long diffMillis = end.getTime() - begin.getTime();
            if (diffMillis <= 0) {
                return 0L;
            }
            return diffMillis / (1000L * 60L);
        } catch (ParseException e) {
            return 0L;
        }
    }

    private double round(double value, int scale) {
        if (scale < 0) {
            return value;
        }
        double factor = Math.pow(10, scale);
        return Math.round(value * factor) / factor;
    }
}
