package com.njcn.prepare.harmonic.service.mysql.Impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.jeffreyning.mybatisplus.service.MppServiceImpl;
import com.njcn.common.pojo.enums.common.DataStateEnum;
import com.njcn.device.biz.pojo.dto.DeptGetBusBarDTO;
import com.njcn.device.pms.pojo.po.Monitor;
import com.njcn.harmonic.pojo.po.RStatOrgBusbarVoltageD;
import com.njcn.harmonic.pojo.po.day.RStatLimitTargetDPO;
import com.njcn.prepare.harmonic.mapper.mysql.RStatOrgBusbarVoltageDMapper;
import com.njcn.prepare.harmonic.mapper.mysql.day.RStatLimitTargetDMapper;
import com.njcn.prepare.harmonic.mapper.mysql.line.PmsMonitorMapper;
import com.njcn.prepare.harmonic.mapper.mysql.line.RMpMonitorEvaluateDMapper;
import com.njcn.prepare.harmonic.pojo.bo.CalculatedParam;
import com.njcn.harmonic.pojo.po.algorithm.line.RMpMonitorEvaluateD;
import com.njcn.prepare.harmonic.service.mysql.IRStatOrgBusbarVoltageDService;
import com.njcn.system.api.DicDataFeignClient;
import com.njcn.system.enums.DicDataEnum;
import com.njcn.system.enums.DicDataTypeEnum;
import com.njcn.system.pojo.po.DictData;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xuyang
 * @since 2024-01-25
 */
@Service
@RequiredArgsConstructor
public class RStatOrgBusbarVoltageDServiceImpl extends MppServiceImpl<RStatOrgBusbarVoltageDMapper, RStatOrgBusbarVoltageD> implements IRStatOrgBusbarVoltageDService {

    private final PmsMonitorMapper pmsMonitorMapper;
    private final DicDataFeignClient dicDataFeignClient;
    private final RStatLimitTargetDMapper limitTargetMapper;
    private final RMpMonitorEvaluateDMapper mpMonitorEvaluateDMapper;

    /**
     * 1.获取单位下母线数量
     * 2.获取母线下监测点个数
     * 3.获取监测点的超标情况
     * @param calculatedParam
     */
    @Override
    @Transactional(rollbackFor = {Exception.class})
    public void busBarHarmonicD(CalculatedParam<DeptGetBusBarDTO> calculatedParam) {
        List<RStatOrgBusbarVoltageD> result = new ArrayList<>();
        //fixme 这边calculatedParam参数传入有问题，应该只传递母线id集合，而不是对象，这边后续调整
        //获取基础数据
        Map<String,List<Monitor>> orgMap = this.getPmsMonitor();
        orgMap.forEach((k,v)->{
            //根据母线分组
            Map<String,List<Monitor>> lineMap = v.stream().collect(Collectors.groupingBy(Monitor::getLineId));
            lineMap.forEach((k1,v1)->{
                RStatOrgBusbarVoltageD busBarD = new RStatOrgBusbarVoltageD();
                busBarD.setOrgNo(k);
                busBarD.setDataDate(LocalDateTimeUtil.parseDate(calculatedParam.getDataDate(), DatePattern.NORM_DATE_PATTERN));
                busBarD.setBusbarId(k1);
                List<String> monitorList = v1.stream().map(Monitor::getId).collect(Collectors.toList());
                busBarD.setMeasurementCount(this.getEffectiveNum(monitorList,calculatedParam.getDataDate()));
                busBarD.setVCount(this.getOverHarmonicV(monitorList,calculatedParam.getDataDate()));
                busBarD.setUnbalanceCount(this.getOverThree(monitorList,calculatedParam.getDataDate()));
                busBarD.setFlickerCount(this.getOverFlicker(monitorList,calculatedParam.getDataDate()));
                busBarD.setVRatio(busBarD.getMeasurementCount()==0?0.0f: Math.min(busBarD.getVCount() * 100.0f / busBarD.getMeasurementCount(), 100.0f));
                busBarD.setUnbalanceRatio(busBarD.getMeasurementCount()==0?0.0f: Math.min(busBarD.getUnbalanceCount() * 100.0f / busBarD.getMeasurementCount(), 100.0f));
                busBarD.setFlickerRatio(busBarD.getMeasurementCount()==0?0.0f: Math.min(busBarD.getFlickerCount()*100.0f/busBarD.getMeasurementCount(), 100.0f));
                result.add(busBarD);
            });
        });
        if (CollectionUtil.isNotEmpty(result)){
            this.saveOrUpdateBatchByMultiId(result,1000);
        }
    }

    /**
     * 获取 在运 && 正常 的监测点信息
     * 根据单位分组
     */
    public Map<String,List<Monitor>> getPmsMonitor() {
        List<DictData> dicDataList = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.LINE_STATE.getCode()).getData();
        DictData dictData = dicDataList.stream().filter(o-> Objects.equals(o.getCode(), DicDataEnum.RUN.getCode())).findFirst().orElse(null);
        LambdaQueryWrapper<Monitor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Monitor::getStatus, DataStateEnum.ENABLE.getCode())
                .eq(Monitor::getMonitorState,dictData.getId());
        List<Monitor> list = pmsMonitorMapper.selectList(lambdaQueryWrapper);
        return list.stream().collect(Collectors.groupingBy(Monitor::getOrgId));
    }

    /**
     * 获取有效接入监测点个数
     */
    public Integer getEffectiveNum(List<String> lineList, String time) {
        LambdaQueryWrapper<RMpMonitorEvaluateD> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.select(RMpMonitorEvaluateD::getMeasurementPointId)
                .eq(RMpMonitorEvaluateD::getDataDate, time)
                .in(RMpMonitorEvaluateD::getMeasurementPointId, lineList)
                .gt(RMpMonitorEvaluateD::getEffectiveMinuteCount, 0);
        List<RMpMonitorEvaluateD> list = mpMonitorEvaluateDMapper.selectList(lambdaQueryWrapper);
        return CollUtil.isEmpty(list)?0: list.stream().distinct().map(RMpMonitorEvaluateD::getMeasurementPointId).collect(Collectors.toList()).size();
    }

    /**
     * 获取谐波电压超标点数
     * 电压总谐波畸变率+2-25次谐波电压
     */
    public Integer getOverHarmonicV(List<String> lineList, String time) {
        LambdaQueryWrapper<RStatLimitTargetDPO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.select(RStatLimitTargetDPO::getLineId)
                .eq(RStatLimitTargetDPO::getTime, time)
                .in(RStatLimitTargetDPO::getLineId, lineList);
        lambdaQueryWrapper.and((wrapper)->{
            wrapper.gt(RStatLimitTargetDPO::getUbalanceOvertime, 0)
                    .or().gt(RStatLimitTargetDPO::getUharm2Overtime,0)
                    .or().gt(RStatLimitTargetDPO::getUharm3Overtime,0)
                    .or().gt(RStatLimitTargetDPO::getUharm4Overtime,0)
                    .or().gt(RStatLimitTargetDPO::getUharm5Overtime,0)
                    .or().gt(RStatLimitTargetDPO::getUharm6Overtime,0)
                    .or().gt(RStatLimitTargetDPO::getUharm7Overtime,0)
                    .or().gt(RStatLimitTargetDPO::getUharm8Overtime,0)
                    .or().gt(RStatLimitTargetDPO::getUharm9Overtime,0)
                    .or().gt(RStatLimitTargetDPO::getUharm10Overtime,0)
                    .or().gt(RStatLimitTargetDPO::getUharm11Overtime,0)
                    .or().gt(RStatLimitTargetDPO::getUharm12Overtime,0)
                    .or().gt(RStatLimitTargetDPO::getUharm13Overtime,0)
                    .or().gt(RStatLimitTargetDPO::getUharm14Overtime,0)
                    .or().gt(RStatLimitTargetDPO::getUharm15Overtime,0)
                    .or().gt(RStatLimitTargetDPO::getUharm16Overtime,0)
                    .or().gt(RStatLimitTargetDPO::getUharm17Overtime,0)
                    .or().gt(RStatLimitTargetDPO::getUharm18Overtime,0)
                    .or().gt(RStatLimitTargetDPO::getUharm19Overtime,0)
                    .or().gt(RStatLimitTargetDPO::getUharm20Overtime,0)
                    .or().gt(RStatLimitTargetDPO::getUharm21Overtime,0)
                    .or().gt(RStatLimitTargetDPO::getUharm22Overtime,0)
                    .or().gt(RStatLimitTargetDPO::getUharm23Overtime,0)
                    .or().gt(RStatLimitTargetDPO::getUharm24Overtime,0)
                    .or().gt(RStatLimitTargetDPO::getUharm25Overtime,0);
        });
        List<RStatLimitTargetDPO> list = limitTargetMapper.selectList(lambdaQueryWrapper);
        return CollUtil.isEmpty(list)?0: list.stream().distinct().map(RStatLimitTargetDPO::getLineId).collect(Collectors.toList()).size();
    }

    /**
     * 三相电压不平衡超标点数
     */
    public Integer getOverThree(List<String> lineList, String time) {
        LambdaQueryWrapper<RStatLimitTargetDPO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.select(RStatLimitTargetDPO::getLineId)
                .eq(RStatLimitTargetDPO::getTime, time)
                .in(RStatLimitTargetDPO::getLineId, lineList)
                .gt(RStatLimitTargetDPO::getUaberranceOvertime, 0);
        List<RStatLimitTargetDPO> list = limitTargetMapper.selectList(lambdaQueryWrapper);
        return CollUtil.isEmpty(list)?0: list.stream().distinct().map(RStatLimitTargetDPO::getLineId).collect(Collectors.toList()).size();
    }

    /**
     * 闪变超标点数
     */
    public Integer getOverFlicker(List<String> lineList,String time) {
        LambdaQueryWrapper<RStatLimitTargetDPO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.select(RStatLimitTargetDPO::getLineId)
                .eq(RStatLimitTargetDPO::getTime, time)
                .in(RStatLimitTargetDPO::getLineId, lineList)
                .gt(RStatLimitTargetDPO::getFlickerOvertime, 0);
        List<RStatLimitTargetDPO> list = limitTargetMapper.selectList(lambdaQueryWrapper);
        return CollUtil.isEmpty(list)?0: list.stream().distinct().map(RStatLimitTargetDPO::getLineId).collect(Collectors.toList()).size();
    }
}
