package com.njcn.event.common.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.njcn.advance.api.EventWaveAnalysisFeignClient;
import com.njcn.advance.pojo.dto.waveAnalysis.EntityAdvancedData;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.common.utils.PubUtils;
import com.njcn.device.pq.pojo.vo.AreaLineInfoVO;
import com.njcn.event.common.pojo.dto.EventEigDetail;
import com.njcn.event.common.service.WaveService;
import com.njcn.event.file.component.WaveFileComponent;
import com.njcn.event.file.pojo.dto.WaveDataDTO;
import com.njcn.event.file.pojo.enums.WaveFileResponseEnum;
import com.njcn.event.pojo.po.RmpEventDetailPO;
import com.njcn.oss.constant.GeneralConstant;
import com.njcn.oss.constant.OssPath;
import com.njcn.oss.utils.FileStorageUtil;
import com.njcn.system.api.DicDataFeignClient;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.*;


/**
 * @Author: cdf
 * @CreateTime: 2026-02-26
 * @Description:
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class WaveServiceImpl implements WaveService {

    private final WaveFileComponent waveFileComponent;
    private final FileStorageUtil fileStorageUtil;
    private final EventWaveAnalysisFeignClient eventWaveAnalysisFeignClient;

    /**
     * 根据暂降事件索引获取波形数据
     * 注：当前只考虑本地的波形文件
     *
     * @param eventDetail 暂态事件
     * @param line       监测点
     */
    @Override
    public WaveDataDTO getWavedata(RmpEventDetailPO eventDetail, AreaLineInfoVO line) {
        WaveDataDTO waveDataDTO = null;
        if (ObjectUtil.isNotEmpty(line)) {
            String waveName = eventDetail.getWavePath();
            if (StrUtil.isBlank(waveName)) {
                throw new BusinessException(WaveFileResponseEnum.ANALYSE_WAVE_NOT_FOUND);
            }
            String wavePath = OssPath.WAVE_DIR + line.getIp() + StrUtil.SLASH + waveName;
            try (
                    InputStream cfgStream = fileStorageUtil.getFileStream(wavePath + GeneralConstant.CFG);
                    InputStream datStream = fileStorageUtil.getFileStream(wavePath + GeneralConstant.DAT)
            ) {
                if (Objects.isNull(cfgStream) || Objects.isNull(datStream)) {
                    throw new BusinessException(WaveFileResponseEnum.ANALYSE_WAVE_NOT_FOUND);
                }
                waveDataDTO = waveFileComponent.getComtrade(cfgStream, datStream, 2);
            } catch (Exception e) {
                try {
                    InputStream cfgStreamLower = fileStorageUtil.getFileStream(wavePath + GeneralConstant.CFG_LOWER);
                    InputStream datStreamLower = fileStorageUtil.getFileStream(wavePath + GeneralConstant.DAT_LOWER);
                    if (Objects.isNull(cfgStreamLower) || Objects.isNull(datStreamLower)) {
                        throw new BusinessException(WaveFileResponseEnum.ANALYSE_WAVE_NOT_FOUND);
                    }
                    waveDataDTO = waveFileComponent.getComtrade(cfgStreamLower, datStreamLower, 2);
                } catch (Exception e1) {
                    throw new BusinessException(WaveFileResponseEnum.WAVE_DATA_INVALID);
                }
            }
            waveDataDTO = waveFileComponent.getValidData(waveDataDTO);
            waveDataDTO.setPtType(line.getPtType());
            waveDataDTO.setPt(line.getPt1() * 1.0 / line.getPt2());
            waveDataDTO.setCt(line.getCt1() * 1.0 / line.getCt2());
            waveDataDTO.setMonitorName(line.getLineName());
        }
        return waveDataDTO;
    }

    @Override
    public WaveDataDTO getWavedata2(RmpEventDetailPO eventDetail, AreaLineInfoVO line) {
        WaveDataDTO waveDataDTO = null;
        if (ObjectUtil.isNotEmpty(line)) {
            String waveName = eventDetail.getWavePath();
            if (StrUtil.isBlank(waveName)) {
                throw new BusinessException(WaveFileResponseEnum.ANALYSE_WAVE_NOT_FOUND);
            }
            try (
                    InputStream cfgStream = fileStorageUtil.getFileStream(waveName + GeneralConstant.CFG);
                    InputStream datStream = fileStorageUtil.getFileStream(waveName + GeneralConstant.DAT)
            ) {
                if (Objects.isNull(cfgStream) || Objects.isNull(datStream)) {
                    throw new BusinessException(WaveFileResponseEnum.ANALYSE_WAVE_NOT_FOUND);
                }
                waveDataDTO = waveFileComponent.getComtrade(cfgStream, datStream, 1);
            } catch (Exception e) {
                try {
                    InputStream cfgStreamLower = fileStorageUtil.getFileStream(waveName + GeneralConstant.CFG_LOWER);
                    InputStream datStreamLower = fileStorageUtil.getFileStream(waveName + GeneralConstant.DAT_LOWER);
                    if (Objects.isNull(cfgStreamLower) || Objects.isNull(datStreamLower)) {
                        throw new BusinessException(WaveFileResponseEnum.ANALYSE_WAVE_NOT_FOUND);
                    }
                    waveDataDTO = waveFileComponent.getComtrade(cfgStreamLower, datStreamLower, 1);
                } catch (Exception e1) {
                    throw new BusinessException(WaveFileResponseEnum.WAVE_DATA_INVALID);
                }
            }
            waveDataDTO = waveFileComponent.getValidData(waveDataDTO);
            waveDataDTO.setPtType(line.getPtType());
            waveDataDTO.setPt(line.getPt1() * 1.0 / line.getPt2());
            waveDataDTO.setCt(line.getCt1() * 1.0 / line.getCt2());
            waveDataDTO.setMonitorName(line.getLineName());
        }
        return waveDataDTO;
    }

    @Override
    public List<EventEigDetail> eventDetailEigenvalue(String eventDetailIndex,Integer ptType) {
        List<EventEigDetail> eventInfoDetails = new ArrayList<>();
        EntityAdvancedData entityAdvancedData = eventWaveAnalysisFeignClient.analysis(eventDetailIndex).getData() ;
        if (entityAdvancedData.backNumber != -1) {
            for (int i = 0; i < entityAdvancedData.backNumber; i++) {
                EventEigDetail eventEigDetail = new EventEigDetail();
                eventEigDetail.setHold_time_dq(entityAdvancedData.evt_buf[i].hold_time_dq * 1000);
                eventEigDetail.setPow_a(PubUtils.floatRound(2, entityAdvancedData.evt_buf[i].POW_a));
                eventEigDetail.setPow_b(PubUtils.floatRound(2, entityAdvancedData.evt_buf[i].POW_b));
                eventEigDetail.setPow_c(PubUtils.floatRound(2, entityAdvancedData.evt_buf[i].POW_c));

                eventEigDetail.setVoltagechange_Va(PubUtils.floatRound(2, entityAdvancedData.evt_buf[i].Voltagechange_Va / 1000));
                eventEigDetail.setVoltagechange_Vb(PubUtils.floatRound(2, entityAdvancedData.evt_buf[i].Voltagechange_Vb / 1000));
                eventEigDetail.setVoltagechange_Vc(PubUtils.floatRound(2, entityAdvancedData.evt_buf[i].Voltagechange_Vc / 1000));


                eventEigDetail.setUa_min(PubUtils.floatRound(2, entityAdvancedData.evt_buf[i].ua_min[0]));
                eventEigDetail.setUb_min(PubUtils.floatRound(2, entityAdvancedData.evt_buf[i].ub_min[0]));
                eventEigDetail.setUc_min(PubUtils.floatRound(2, entityAdvancedData.evt_buf[i].ua_min[0]));

                eventEigDetail.setAngle_diff_ap(PubUtils.floatRound(2, entityAdvancedData.evt_buf[i].angle_diff_ap[0]));
                eventEigDetail.setAngle_diff_bp(PubUtils.floatRound(2, entityAdvancedData.evt_buf[i].angle_diff_bp[0]));
                eventEigDetail.setAngle_diff_cp(PubUtils.floatRound(2, entityAdvancedData.evt_buf[i].angle_diff_cp[0]));

                eventEigDetail.setBph_max_value(PubUtils.floatRound(2, entityAdvancedData.evt_buf[i].bph_max_value[0]));
                eventEigDetail.setSagReason(entityAdvancedData.sagReason[0]);//暂降原因，暂降原因都一样
                eventEigDetail.setSagType(entityAdvancedData.sagType[i]);//暂降类型
                eventInfoDetails.add(eventEigDetail);
                eventEigDetail.setPttype(ptType);
            }
        } else {
            eventInfoDetails = null;
        }
        return eventInfoDetails;
    }

    @Override
    public List<EventEigDetail> eventDetailEigenvalue2(String eventDetailIndex,Integer ptType) {
        List<EventEigDetail> eventInfoDetails = new ArrayList<>();
        EntityAdvancedData entityAdvancedData = eventWaveAnalysisFeignClient.analysisWlEvent(eventDetailIndex).getData() ;
        if (entityAdvancedData.backNumber != -1) {
            for (int i = 0; i < entityAdvancedData.backNumber; i++) {
                EventEigDetail eventEigDetail = new EventEigDetail();
                eventEigDetail.setHold_time_dq(entityAdvancedData.evt_buf[i].hold_time_dq * 1000);
                eventEigDetail.setPow_a(PubUtils.floatRound(2, entityAdvancedData.evt_buf[i].POW_a));
                eventEigDetail.setPow_b(PubUtils.floatRound(2, entityAdvancedData.evt_buf[i].POW_b));
                eventEigDetail.setPow_c(PubUtils.floatRound(2, entityAdvancedData.evt_buf[i].POW_c));

                eventEigDetail.setVoltagechange_Va(PubUtils.floatRound(2, entityAdvancedData.evt_buf[i].Voltagechange_Va / 1000));
                eventEigDetail.setVoltagechange_Vb(PubUtils.floatRound(2, entityAdvancedData.evt_buf[i].Voltagechange_Vb / 1000));
                eventEigDetail.setVoltagechange_Vc(PubUtils.floatRound(2, entityAdvancedData.evt_buf[i].Voltagechange_Vc / 1000));


                eventEigDetail.setUa_min(PubUtils.floatRound(2, entityAdvancedData.evt_buf[i].ua_min[0]));
                eventEigDetail.setUb_min(PubUtils.floatRound(2, entityAdvancedData.evt_buf[i].ub_min[0]));
                eventEigDetail.setUc_min(PubUtils.floatRound(2, entityAdvancedData.evt_buf[i].ua_min[0]));

                eventEigDetail.setAngle_diff_ap(PubUtils.floatRound(2, entityAdvancedData.evt_buf[i].angle_diff_ap[0]));
                eventEigDetail.setAngle_diff_bp(PubUtils.floatRound(2, entityAdvancedData.evt_buf[i].angle_diff_bp[0]));
                eventEigDetail.setAngle_diff_cp(PubUtils.floatRound(2, entityAdvancedData.evt_buf[i].angle_diff_cp[0]));

                eventEigDetail.setBph_max_value(PubUtils.floatRound(2, entityAdvancedData.evt_buf[i].bph_max_value[0]));
                eventEigDetail.setSagReason(entityAdvancedData.sagReason[0]);//暂降原因，暂降原因都一样
                eventEigDetail.setSagType(entityAdvancedData.sagType[i]);//暂降类型
                eventInfoDetails.add(eventEigDetail);
                eventEigDetail.setPttype(ptType);
            }
        } else {
            eventInfoDetails = null;
        }
        return eventInfoDetails;
    }


}
