package com.njcn.product.advance.responsility.service.impl;


import com.njcn.product.advance.responsility.calculator.HarmonicCalculationEngine;
import com.njcn.product.advance.responsility.model.HarmonicData;
import com.njcn.product.advance.responsility.pojo.constant.CalculationMode;
import com.njcn.product.advance.responsility.pojo.constant.HarmonicConstants;
import com.njcn.product.advance.responsility.service.IHarmonicResponsibilityService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

/**
 * 谐波责任计算服务实现类
 * 
 * @author hongawen
 * @version 1.0
 */
@Service
public class HarmonicResponsibilityServiceImpl implements IHarmonicResponsibilityService {
    
    private static final Logger logger = LoggerFactory.getLogger(HarmonicResponsibilityServiceImpl.class);

    private final HarmonicCalculationEngine engine;
    
    public HarmonicResponsibilityServiceImpl() {
        this.engine = new HarmonicCalculationEngine();
    }
    
    @Override
    public boolean calculate(HarmonicData data) {
        if (data == null) {
            logger.error("Input data is null");
            return false;
        }
        
        String validationError = validateData(data);
        if (validationError != null) {
            logger.error("Data validation failed: {}", validationError);
            return false;
        }
        
        long startTime = System.currentTimeMillis();
        boolean result = engine.calculate(data);
        long endTime = System.currentTimeMillis();
        
        logger.info("Calculation completed in {} ms, result: {}", (endTime - startTime), result);
        
        return result;
    }
    
    @Override
    public HarmonicData fullCalculation(float[] harmonicData, float[][] powerData,
                                        int harmonicCount, int powerCount, int nodeCount,
                                        int windowSize, float threshold) {
        logger.info("Starting full calculation with harmonicCount={}, powerCount={}, nodeCount={}, windowSize={}",
                   harmonicCount, powerCount, nodeCount, windowSize);
        
        HarmonicData data = new HarmonicData.Builder()
            .calculationMode(CalculationMode.FULL_CALCULATION)
            .harmonicCount(harmonicCount)
            .powerCount(powerCount)
            .powerNodeCount(nodeCount)
            .windowSize(windowSize)
            .harmonicThreshold(threshold)
            .harmonicData(harmonicData)
            .powerData(powerData)
            .build();
        
        calculate(data);
        
        return data;
    }
    
    @Override
    public HarmonicData partialCalculation(float[] harmonicData, float[][] fkData, float[][] hkData,
                                           int harmonicCount, int nodeCount, int windowSize,
                                           int responsibilityCount, float threshold) {
        logger.info("Starting partial calculation with harmonicCount={}, nodeCount={}, windowSize={}, responsibilityCount={}",
                   harmonicCount, nodeCount, windowSize, responsibilityCount);
        
        HarmonicData data = new HarmonicData();
        data.setCalculationMode(CalculationMode.PARTIAL_RECALCULATION);
        data.setHarmonicCount(harmonicCount);
        data.setPowerNodeCount(nodeCount);
        data.setWindowSize(windowSize);
        data.setResponsibilityDataCount(responsibilityCount);
        data.setHarmonicThreshold(threshold);
        data.setHarmonicData(harmonicData);
        data.setFkData(fkData);
        data.setHkData(hkData);
        
        // 初始化输出数组
        data.setSumFKData(new float[nodeCount]);
        data.setSumHKData(new float[nodeCount + 1]);
        
        calculate(data);
        
        return data;
    }
    
    @Override
    public String validateData(HarmonicData data) {
        if (data == null) {
            return "Data object is null";
        }
        
        // 验证基本参数
        if (data.getHarmonicCount() <= 0 || data.getHarmonicCount() > HarmonicConstants.MAX_HARM_NUM) {
            return String.format("Invalid harmonic count: %d (should be 1-%d)", 
                               data.getHarmonicCount(), HarmonicConstants.MAX_HARM_NUM);
        }
        
        if (data.getCalculationMode() == CalculationMode.FULL_CALCULATION) {
            // 完整计算模式验证
            if (data.getPowerCount() <= 0 || data.getPowerCount() > HarmonicConstants.MAX_P_NUM) {
                return String.format("Invalid power count: %d (should be 1-%d)", 
                                   data.getPowerCount(), HarmonicConstants.MAX_P_NUM);
            }
            
            if (data.getPowerNodeCount() <= 0 || data.getPowerNodeCount() > HarmonicConstants.MAX_P_NODE) {
                return String.format("Invalid power node count: %d (should be 1-%d)", 
                                   data.getPowerNodeCount(), HarmonicConstants.MAX_P_NODE);
            }
            
            // 验证数据对齐
            int ratio = data.getHarmonicCount() / data.getPowerCount();
            if (ratio * data.getPowerCount() != data.getHarmonicCount()) {
                return String.format("Harmonic count %d is not aligned with power count %d", 
                                   data.getHarmonicCount(), data.getPowerCount());
            }
            
            // 验证数据数组
            if (data.getHarmonicData() == null || data.getHarmonicData().length < data.getHarmonicCount()) {
                return "Harmonic data array is null or insufficient";
            }
            
            if (data.getPowerData() == null || data.getPowerData().length < data.getPowerCount()) {
                return "Power data array is null or insufficient";
            }
            
        } else if (data.getCalculationMode() == CalculationMode.PARTIAL_RECALCULATION) {
            // 部分计算模式验证
            if (data.getResponsibilityDataCount() + data.getWindowSize() != data.getHarmonicCount()) {
                return String.format("Data length mismatch: resNum(%d) + winSize(%d) != harmCount(%d)",
                                   data.getResponsibilityDataCount(), data.getWindowSize(), data.getHarmonicCount());
            }
            
            if (data.getFkData() == null || data.getHkData() == null) {
                return "FK or HK data is null for partial calculation";
            }
        }
        
        // 验证窗口大小
        if (data.getWindowSize() < HarmonicConstants.MIN_WIN_LEN || 
            data.getWindowSize() > HarmonicConstants.MAX_WIN_LEN) {
            return String.format("Invalid window size: %d (should be %d-%d)", 
                               data.getWindowSize(), HarmonicConstants.MIN_WIN_LEN, HarmonicConstants.MAX_WIN_LEN);
        }
        
        return null; // 验证通过
    }
}