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.DateUtil;
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.RStatOrgBusbarVoltageM;
import com.njcn.harmonic.pojo.po.day.RStatLimitTargetDPO;
import com.njcn.prepare.harmonic.mapper.mysql.RStatOrgBusbarVoltageDMapper;
import com.njcn.prepare.harmonic.mapper.mysql.RStatOrgBusbarVoltageMMapper;
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.IRStatOrgBusbarVoltageMService;
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 com.njcn.user.api.DeptFeignClient;
import com.njcn.user.pojo.po.Dept;
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 RStatOrgBusbarVoltageMServiceImpl extends MppServiceImpl<RStatOrgBusbarVoltageMMapper, RStatOrgBusbarVoltageM> implements IRStatOrgBusbarVoltageMService {

    private final RStatOrgBusbarVoltageDMapper statOrgBusbarVoltageDMapper;
    private final RMpMonitorEvaluateDMapper mpMonitorEvaluateDMapper;
    private final RStatLimitTargetDMapper limitTargetMapper;
    private final PmsMonitorMapper pmsMonitorMapper;
    private final DicDataFeignClient dicDataFeignClient;
    private final DeptFeignClient deptFeignClient;

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public void busBarHarmonicM(CalculatedParam<DeptGetBusBarDTO> calculatedParam) {
        List<RStatOrgBusbarVoltageM> result = new ArrayList<>();
        String beginMonth = DateUtil.beginOfMonth(DateUtil.parse(calculatedParam.getDataDate(), DatePattern.NORM_DATE_PATTERN)).toString(DatePattern.NORM_DATE_PATTERN);
        String endMonth = DateUtil.endOfMonth(DateUtil.parse(calculatedParam.getDataDate(), DatePattern.NORM_DATE_PATTERN)).toString(DatePattern.NORM_DATE_PATTERN);
        //获取基础数据
        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)->{
                RStatOrgBusbarVoltageM busBarM = new RStatOrgBusbarVoltageM();
                busBarM.setOrgNo(k);
                busBarM.setDataDate(LocalDateTimeUtil.parseDate(beginMonth, DatePattern.NORM_DATE_PATTERN));
                busBarM.setBusbarId(k1);
                List<String> monitorList = v1.stream().map(Monitor::getId).collect(Collectors.toList());
                busBarM.setMeasurementCount(this.getEffectiveNum(monitorList,beginMonth,endMonth));
                //获取日表数据
                List<RStatOrgBusbarVoltageD> dayList = getDayData(k1,beginMonth,endMonth);
                busBarM.setVAverage(Math.min(new Double(dayList.stream().mapToDouble(RStatOrgBusbarVoltageD::getVRatio).average().orElse(0.0f)).floatValue(),100.0f));
                busBarM.setVAccrued(busBarM.getMeasurementCount()==0?0.0f:Math.min(this.getOverHarmonicV(monitorList,beginMonth,endMonth)*100.0f/busBarM.getMeasurementCount(),100.0f));

                busBarM.setUnbalanceAverage(Math.min(new Double(dayList.stream().mapToDouble(RStatOrgBusbarVoltageD::getUnbalanceRatio).average().orElse(0.0f)).floatValue(),100.0f));
                busBarM.setUnbalanceAccrued(busBarM.getMeasurementCount()==0?0.0f:Math.min(this.getOverThree(monitorList,beginMonth,endMonth)*100.0f/busBarM.getMeasurementCount(),100.0f));

                busBarM.setFlickerAverage(Math.min(new Double(dayList.stream().mapToDouble(RStatOrgBusbarVoltageD::getFlickerRatio).average().orElse(0.0f)).floatValue(),100.0f));
                busBarM.setFlickerAccrued(busBarM.getMeasurementCount()==0?0.0f:Math.min(this.getOverFlicker(monitorList,beginMonth,endMonth)*100.0f/busBarM.getMeasurementCount(),100.0f));

                result.add(busBarM);
            });
        });
        if (CollectionUtil.isNotEmpty(result)){
            //获取省级部门ids
            Dept dept = deptFeignClient.getRootDept().getData();
            String code = deptFeignClient.getDepSonDetailByDeptId(dept.getId()).getData().get(0).getCode();
            this.remove(new LambdaQueryWrapper<RStatOrgBusbarVoltageM>()
                    .eq(RStatOrgBusbarVoltageM::getOrgNo,code));
            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 List<RStatOrgBusbarVoltageD> getDayData(String busBar, String startTime, String endTime){
        LambdaQueryWrapper<RStatOrgBusbarVoltageD> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.between(RStatOrgBusbarVoltageD::getDataDate,startTime,endTime)
                        .eq(RStatOrgBusbarVoltageD::getBusbarId, busBar);
        return statOrgBusbarVoltageDMapper.selectList(lambdaQueryWrapper);
    }

    /**
     * 获取有效接入监测点个数
     */
    public Integer getEffectiveNum(List<String> lineList, String startTime, String endTime) {
        LambdaQueryWrapper<RMpMonitorEvaluateD> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.select(RMpMonitorEvaluateD::getMeasurementPointId)
                .between(RMpMonitorEvaluateD::getDataDate, startTime, endTime)
                .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 startTime, String endTime) {
        LambdaQueryWrapper<RStatLimitTargetDPO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.select(RStatLimitTargetDPO::getLineId)
                .between(RStatLimitTargetDPO::getTime, startTime, endTime)
                .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 startTime, String endTime) {
        LambdaQueryWrapper<RStatLimitTargetDPO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.select(RStatLimitTargetDPO::getLineId)
                .between(RStatLimitTargetDPO::getTime, startTime, endTime)
                .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 startTime, String endTime) {
        LambdaQueryWrapper<RStatLimitTargetDPO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.select(RStatLimitTargetDPO::getLineId)
                .between(RStatLimitTargetDPO::getTime, startTime, endTime)
                .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();
    }

}
