package com.njcn.harmonic.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.common.config.GeneralInfo;
import com.njcn.common.pojo.constant.BizParamConstant;
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.device.pms.api.MonitorClient;
import com.njcn.device.pms.api.PmsGeneralDeviceInfoClient;
import com.njcn.device.pms.api.StatationStatClient;
import com.njcn.device.pms.pojo.dto.PmsGeneralDeviceDTO;
import com.njcn.device.pms.pojo.dto.PmsStatationStatInfoDTO;
import com.njcn.device.pms.pojo.param.PmsDeviceInfoParam;
import com.njcn.device.pms.pojo.param.PmsStatationStatInfoParam;
import com.njcn.device.pms.pojo.po.Monitor;
import com.njcn.device.pq.api.GeneralDeviceInfoClient;
import com.njcn.device.pq.api.LineFeignClient;
import com.njcn.device.pq.api.SubstationFeignClient;
import com.njcn.device.pq.pojo.dto.*;
import com.njcn.harmonic.constant.Param;
import com.njcn.harmonic.mapper.*;
import com.njcn.harmonic.pojo.dto.PublicDTO;
import com.njcn.harmonic.pojo.param.HarmonicPublicParam;
import com.njcn.harmonic.pojo.param.PollutionSubstationQuryParam;
import com.njcn.harmonic.pojo.po.*;
import com.njcn.harmonic.pojo.vo.PollutionSubstationVO;
import com.njcn.harmonic.pojo.vo.PollutionVO;
import com.njcn.harmonic.service.PollutionSubstationService;
import com.njcn.user.api.DeptFeignClient;
import com.njcn.user.pojo.po.Dept;
import com.njcn.web.utils.RequestUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 *
 * Description:
 * 接口文档访问地址：http://serverIP:port/swagger-ui.html
 * Date: 2022/10/13  8:56【需求编号】
 *
 * @author clam
 * @version V1.0.0
 */
@Slf4j
@Service
@AllArgsConstructor
public class PollutionSubstationServiceImpl extends ServiceImpl<RStatPollutionSubstationMMapper, RStatPollutionSubstationM> implements PollutionSubstationService {


    private final SubstationFeignClient substationFeignClient;

    private final PmsGeneralDeviceInfoClient pmsGeneralDeviceInfoClient;
    private final StatationStatClient statationStatClient;
    private final MonitorClient monitorClient;
    private final DeptFeignClient deptFeignClient;

    private final RStatPollutionSubstationMMapper pollutionSubstationMMapper;
    private final RStatPollutionSubstationYPOMapper pollutionSubstationYPOMapper;
    private final RStatPollutionSubstationQPOMapper pollutionSubstationQPOMapper;
    private final RStatPollutionSubstationDPOMapper pollutionSubstationDPOMapper;


    private final GeneralDeviceInfoClient generalDeviceInfoClient;

    private final LineFeignClient lineFeignClient;

    private final GeneralInfo generalInfo;


    private final RStatPollutionOrgMPOMapper rStatPollutionOrgMPOMapper;
    private final RStatPollutionOrgYPOMapper rStatPollutionOrgYPOMapper;
    private final RStatPollutionOrgQPOMapper rStatPollutionOrgQPOMapper;
    private final RStatPollutionOrgDPOMapper rStatPollutionOrgDPOMapper;

    private final RMpPollutionDPOMapper rMpPollutionDPOMapper;

    /**
     * @param pollutionSubstationQuryParam
     * @Description: getPollutionSubstationData
     * @Param: [pollutionSubstationQuryParam]
     * @return: java.util.List<com.njcn.harmonic.pojo.vo.PollutionSubstationVO>
     * @Author: clam
     * @Date: 2022/10/13
     */
    @Override
    public List<PollutionSubstationVO> getPollutionSubstationData(PollutionSubstationQuryParam pollutionSubstationQuryParam) {

        List<PollutionSubstationVO> pollutionSubstationVOList = new ArrayList<> ();
        /*根据部门获取变电站详情*/
        HarmonicPublicParam harmonicPublicParam = new HarmonicPublicParam();
        BeanUtils.copyProperties (pollutionSubstationQuryParam, harmonicPublicParam);
        harmonicPublicParam.setServerName(generalInfo.getMicroServiceName());
        List<PollutionSubstationDTO> pollutionSubstationDTOList = new ArrayList<>();
        List<GeneralDeviceDTO> sub = generalDeviceInfoClient.getPracticalRunDeviceInfoAsSubstation(harmonicPublicParam).getData();

        sub.forEach(item->{
            PollutionSubstationDTO pollutionSubstationDTO = lineFeignClient.getSubstationInfo(item.getIndex()).getData();

            pollutionSubstationDTOList.add(pollutionSubstationDTO);
        });
        List<String> collect = pollutionSubstationDTOList.stream ( ).map (PollutionSubstationDTO::getId).collect (Collectors.toList ( ));
        List<SubstationDTO> locationData = substationFeignClient.getSubstationById (collect).getData ( );
        /*todo 后期可以把locationData存入redis*/
        /*把所有的变电站的污染指数查出来*/
        QueryWrapper<RStatPollutionSubstationM> wrapper = new QueryWrapper<> ();
        wrapper.in ("substation_id",collect).
                eq ("pollution_type", pollutionSubstationQuryParam.getPollutionStatis ().getId ()).
                eq("DATE_FORMAT( data_date ,'%Y-%m')",pollutionSubstationQuryParam.getLocalDate ());
        List<RStatPollutionSubstationM> rStatPollutionSubstationMList = pollutionSubstationMMapper.selectList (wrapper);

        pollutionSubstationDTOList.forEach (substationInfo ->{

            Integer lineCount = lineFeignClient.getLineCountBySubstation (substationInfo.getId ( )).getData ( );
            Integer deviceCount = lineFeignClient.getDeviceCountBySubstation (substationInfo.getId ()).getData ();
            PollutionSubstationVO pollutionSubstationVO =new PollutionSubstationVO ();
            pollutionSubstationVO.setSubstationId (substationInfo.getId ());
            pollutionSubstationVO.setSubstationName (substationInfo.getName ());
            pollutionSubstationVO.setDeviceCount (deviceCount);
            pollutionSubstationVO.setLineCount (lineCount);
            /*todo 添加经纬度接口返回数据暂时没有*/
            List<SubstationDTO> substationDTOList = locationData.stream ( )
                    .filter (temp -> Objects.equals (substationInfo.getId ( ), temp.getId ( )))
                    .collect (Collectors.toList ( ));

            SubstationDTO substationDTO = new SubstationDTO ();
            if(CollectionUtils.isEmpty (substationDTOList)){
                throw new BusinessException (CommonResponseEnum.INTERNAL_ERROR);
            }else{
                substationDTO = substationDTOList.get (0);
            }

            pollutionSubstationVO.setLatitude (substationDTO.getLat ());
            pollutionSubstationVO.setLongitude (substationDTO.getLng ());

            List<RStatPollutionSubstationM> rStatPollutionSubstationMS = rStatPollutionSubstationMList.stream ( ).
                    filter (temp -> Objects.equals (substationInfo.getId ( ), temp.getSubstationId ( )))
                    .collect (Collectors.toList ( ));

            Double value = 3.14159;
            if(!CollectionUtils.isEmpty (rStatPollutionSubstationMS)){
                value = rStatPollutionSubstationMS.get (0).getValue ();
            }
            pollutionSubstationVO.setPollutionData (value);
            pollutionSubstationVO.setPollutionStatis ( pollutionSubstationQuryParam.getStatisticalType ().getName ());
            pollutionSubstationVOList.add (pollutionSubstationVO);
        });
        List<PollutionSubstationVO> result = pollutionSubstationVOList.stream ( ).sorted (Comparator.comparing (PollutionSubstationVO::getPollutionData).reversed ( )).collect (Collectors.toList ( ));

        return result;
    }

    /**
     * @Description: getDeptSubstationRelations
     * @Param: [param]
     * @return: java.util.List<com.njcn.harmonic.pojo.vo.PollutionVO>
     * @Author: clam
     * @Date: 2022/11/3
     */
    @Override
    public List<PollutionVO> getDeptSubstationRelations(HarmonicPublicParam harmonicPublicParam) {
        List<PollutionVO> list = new ArrayList<>();
        String pollutionType = harmonicPublicParam.getStatisticalType ().getId ();
        String searchBeginTime = harmonicPublicParam.getSearchBeginTime ().substring (0,10);
        if (StringUtils.isBlank(RequestUtil.getDeptIndex())) {
            return list;
        }
        if (harmonicPublicParam.getType() != 0) {
            PmsDeviceInfoParam pmsDeviceInfoParam = new PmsDeviceInfoParam();
            pmsDeviceInfoParam.setDeptIndex(harmonicPublicParam.getDeptIndex());
            //获取统计类型
            pmsDeviceInfoParam.setStatisticalType(harmonicPublicParam.getStatisticalType());
            //获取主网台账信息
            List<PmsGeneralDeviceDTO> orgList = pmsGeneralDeviceInfoClient.getPmsDeviceInfoWithInOrg(pmsDeviceInfoParam).getData();
            orgList.forEach(temp -> {
                PollutionVO pollutionVO = new PollutionVO ();
                String detpid = temp.getIndex ();
                String name =temp.getName ();
                List<String> powers = temp.getPowerrIdList ( );
                pollutionVO.setId (detpid);
                pollutionVO.setName (name+"\n("+temp.getMonitorIdList().size()+")");
                pollutionVO.setData (3.14159);
                setData(harmonicPublicParam, pollutionType, searchBeginTime,harmonicPublicParam.getSearchEndTime(), pollutionVO, detpid);
                if(CollectionUtil.isNotEmpty(powers)) {
                    //子集变电站
                    List<PollutionVO> powersVO = new ArrayList<>();
                    PmsStatationStatInfoParam param=new PmsStatationStatInfoParam();
                    param.setPowerIds(powers);
                    List<PmsStatationStatInfoDTO> data = statationStatClient.getStatationStatInfo(param).getData();
                    //去重解决重复数据
                    ArrayList<PmsStatationStatInfoDTO> dsData = data.stream().collect(Collectors.collectingAndThen
                            (Collectors.toCollection(() ->
                                    new TreeSet<>(Comparator.comparing(o -> o.getPowerId()))), ArrayList::new));
                    Map<String, Double> stringDoubleMap = setPmsSubData(harmonicPublicParam, pollutionType, searchBeginTime, powers);
                    if(CollectionUtil.isNotEmpty(data)) {
                        dsData.forEach(power->{
                            PollutionVO pollutionsubVO = new PollutionVO ();
                            pollutionsubVO.setId (power.getPowerId());
                            pollutionsubVO.setName ( power.getPowerName ());
                            pollutionsubVO.setPid (temp.getIndex ());
                            if(CollectionUtil.isNotEmpty(stringDoubleMap)){
                                if(stringDoubleMap.containsKey(power.getPowerId())){
                                    pollutionsubVO.setData(stringDoubleMap.get(power.getPowerId()));
                                }
                            }
                            powersVO.add (pollutionsubVO) ;
                        });
                    }
                    powersVO.sort((item1, item2) -> item2.getData().compareTo(item1.getData()));
                    pollutionVO.setChildren (powersVO);
                }
                list.add (pollutionVO);
            });

        } else {
            harmonicPublicParam.setServerName(generalInfo.getMicroServiceName());
            List<GeneralDeviceDTO> sub = generalDeviceInfoClient.getPracticalRunDeviceInfo(harmonicPublicParam).getData();
            for (GeneralDeviceDTO temp : sub) {
                List<String> subIndexes = temp.getSubIndexes();
                if(CollectionUtil.isEmpty(subIndexes)){
                    continue;
                }
                PollutionVO pollutionVO = new PollutionVO();
                String detpid = temp.getIndex();
                String name = temp.getName();

                pollutionVO.setId(detpid);
                pollutionVO.setName(name+"\n("+temp.getLineIndexes().size()+")");
                pollutionVO.setData(3.14159);
                setData(harmonicPublicParam, pollutionType, searchBeginTime,harmonicPublicParam.getSearchEndTime(), pollutionVO, detpid);
                List<PollutionVO> subPollutionVO = new ArrayList<>();
                subIndexes.forEach(subIndex -> {
                    PollutionVO pollutionsubVO = new PollutionVO();
                    PollutionSubstationDTO pollutionSubstationDTO = lineFeignClient.getSubstationInfo(subIndex).getData();
                    String id = pollutionSubstationDTO.getId();
                    pollutionsubVO.setId(id);
                    pollutionsubVO.setName(pollutionSubstationDTO.getName());
                    pollutionsubVO.setPid(temp.getIndex());
                    pollutionsubVO.setData(3.14159);
                    setSubData(harmonicPublicParam, pollutionType, searchBeginTime,harmonicPublicParam.getSearchEndTime(), pollutionsubVO, id);
                    subPollutionVO.add(pollutionsubVO);
                });
                pollutionVO.setChildren(subPollutionVO);

                list.add(pollutionVO);
            }
        }
        if (!CollectionUtils.isEmpty(list)){
            return list.stream().sorted(Comparator.comparing(PollutionVO::getData).reversed().thenComparing(PollutionVO::getName)).collect(Collectors.toList());
        }
        return list;
    }

    private Map<String,Double> setPmsSubData(HarmonicPublicParam harmonicPublicParam, String pollutionType, String searchBeginTime, List<String> id) {
        if(Objects.equals (harmonicPublicParam.getReportFlag (), BizParamConstant.STAT_BIZ_YEAR) ){
            QueryWrapper<RStatPollutionSubstationYPO> wrapper = new QueryWrapper<> ();
            wrapper.in ("substation_id",id).
                    eq ("pollution_type", pollutionType).
                    eq("DATE_FORMAT( data_date ,'%Y-%m-%d')",searchBeginTime);
            List<RStatPollutionSubstationYPO> s = pollutionSubstationYPOMapper.selectList(wrapper);
             return s.stream().collect(Collectors.toMap(RStatPollutionSubstationYPO::getSubstationId, RStatPollutionSubstationYPO::getValue));
        }else if(Objects.equals (harmonicPublicParam.getReportFlag (),BizParamConstant.STAT_BIZ_QUARTER)){
            QueryWrapper<RStatPollutionSubstationQPO> wrapper = new QueryWrapper<> ();
            wrapper.in ("substation_id",id).
                    eq ("pollution_type", pollutionType).
                    eq("DATE_FORMAT( data_date ,'%Y-%m-%d')",searchBeginTime);
            List<RStatPollutionSubstationQPO> s = pollutionSubstationQPOMapper.selectList(wrapper);
            return s.stream().collect(Collectors.toMap(RStatPollutionSubstationQPO::getSubstationId, RStatPollutionSubstationQPO::getValue));

        }else if(Objects.equals (harmonicPublicParam.getReportFlag (),BizParamConstant.STAT_BIZ_MONTH)){
            QueryWrapper<RStatPollutionSubstationM> wrapper = new QueryWrapper<> ();
            wrapper.in ("substation_id",id).
                    eq ("pollution_type", pollutionType).
                    eq("DATE_FORMAT( data_date ,'%Y-%m-%d')",searchBeginTime);
            List<RStatPollutionSubstationM> s = pollutionSubstationMMapper.selectList(wrapper);
            return s.stream().collect(Collectors.toMap(RStatPollutionSubstationM::getSubstationId, RStatPollutionSubstationM::getValue));
        }else if(Objects.equals (harmonicPublicParam.getReportFlag (),BizParamConstant.STAT_BIZ_DAY)){
            QueryWrapper<RStatPollutionSubstationDPO> wrapper = new QueryWrapper<> ();
            wrapper.in ("substation_id",id).
                    eq ("pollution_type", pollutionType).
                    eq("DATE_FORMAT( data_date ,'%Y-%m-%d')",searchBeginTime);
            List<RStatPollutionSubstationDPO> s = pollutionSubstationDPOMapper.selectList(wrapper);
            return s.stream().collect(Collectors.toMap(RStatPollutionSubstationDPO::getSubstationId, RStatPollutionSubstationDPO::getValue));
        }
        return null;
    }

    private void setSubData(HarmonicPublicParam harmonicPublicParam, String pollutionType, String searchBeginTime,String searchEndTime, PollutionVO pollutionsubVO, String id) {
        if(Objects.equals (harmonicPublicParam.getReportFlag (), BizParamConstant.STAT_BIZ_YEAR) ){
            QueryWrapper<RStatPollutionSubstationYPO> wrapper = new QueryWrapper<> ();
            wrapper.eq ("substation_id",id).
                    eq ("pollution_type", pollutionType).
                    eq("DATE_FORMAT( data_date ,'%Y-%m-%d')",searchBeginTime);
            RStatPollutionSubstationYPO rStatPollutionSubstationYPO = pollutionSubstationYPOMapper.selectOne (wrapper);

            Optional.ofNullable (rStatPollutionSubstationYPO).ifPresent (t->pollutionsubVO.setData (t.getValue ()));
        }else if(Objects.equals (harmonicPublicParam.getReportFlag (),BizParamConstant.STAT_BIZ_QUARTER)){
            QueryWrapper<RStatPollutionSubstationQPO> wrapper = new QueryWrapper<> ();
            wrapper.eq ("substation_id",id).
                    eq ("pollution_type", pollutionType).
                    eq("DATE_FORMAT( data_date ,'%Y-%m-%d')",searchBeginTime);
            RStatPollutionSubstationQPO rStatPollutionSubstationQPO = pollutionSubstationQPOMapper.selectOne (wrapper);

            Optional.ofNullable (rStatPollutionSubstationQPO).ifPresent (t->pollutionsubVO.setData (t.getValue ()));
        }else if(Objects.equals (harmonicPublicParam.getReportFlag (),BizParamConstant.STAT_BIZ_MONTH)){
            QueryWrapper<RStatPollutionSubstationM> wrapper = new QueryWrapper<> ();
            wrapper.eq ("substation_id",id).
                    eq ("pollution_type", pollutionType).
                    eq("DATE_FORMAT( data_date ,'%Y-%m-%d')",searchBeginTime);
            RStatPollutionSubstationM rStatPollutionSubstationM = pollutionSubstationMMapper.selectOne (wrapper);

            Optional.ofNullable (rStatPollutionSubstationM).ifPresent (t->pollutionsubVO.setData (t.getValue ()));

        }else if(Objects.equals (harmonicPublicParam.getReportFlag (),BizParamConstant.STAT_BIZ_DAY)){
            QueryWrapper<RStatPollutionSubstationDPO> wrapper = new QueryWrapper<> ();
            wrapper.eq ("substation_id",id).
                    eq ("pollution_type", pollutionType).
                    eq("DATE_FORMAT( data_date ,'%Y-%m-%d')",searchBeginTime);
            RStatPollutionSubstationDPO rStatPollutionSubstationDPO = pollutionSubstationDPOMapper.selectOne (wrapper);

            Optional.ofNullable (rStatPollutionSubstationDPO).ifPresent (t->pollutionsubVO.setData (t.getValue ()));
        }else if(Objects.equals (harmonicPublicParam.getReportFlag (),BizParamConstant.STAT_BIZ_WEEK)){
            QueryWrapper<RStatPollutionSubstationDPO> wrapper = new QueryWrapper<> ();
            wrapper.eq ("substation_id",id).
                    eq ("pollution_type", pollutionType).
                    between("DATE_FORMAT( data_date ,'%Y-%m-%d')",searchBeginTime,searchEndTime)
            .orderByDesc("value").last(" limit 1");
            RStatPollutionSubstationDPO rStatPollutionSubstationDPO = pollutionSubstationDPOMapper.selectOne (wrapper);
            Optional.ofNullable (rStatPollutionSubstationDPO).ifPresent (t->pollutionsubVO.setData (t.getValue ()));

        }
    }

    private void setData(HarmonicPublicParam harmonicPublicParam, String pollutionType, String searchBeginTime,String searchEndTime, PollutionVO pollutionVO, String detpid) {

        if(Objects.equals (harmonicPublicParam.getReportFlag (), BizParamConstant.STAT_BIZ_YEAR) ) {
            QueryWrapper<RStatPollutionOrgYPO> rStatPollutionOrgYPOQueryWrapper = new QueryWrapper<> ();
            rStatPollutionOrgYPOQueryWrapper.eq ("org_id", detpid).
                    eq ("pollution_type", pollutionType).
                    eq("DATE_FORMAT( data_date ,'%Y-%m-%d')",searchBeginTime);
            RStatPollutionOrgYPO rStatPollutionOrgYPO = rStatPollutionOrgYPOMapper.selectOne (rStatPollutionOrgYPOQueryWrapper);
            Optional.ofNullable (rStatPollutionOrgYPO).ifPresent (a->pollutionVO.setData (BigDecimal.valueOf(a.getValue()).setScale(2, RoundingMode.UP).doubleValue()));
        } else if (Objects.equals (harmonicPublicParam.getReportFlag (),BizParamConstant.STAT_BIZ_QUARTER)) {
            QueryWrapper<RStatPollutionOrgQPO> rStatPollutionOrgQPOQueryWrapper = new QueryWrapper<> ();
            rStatPollutionOrgQPOQueryWrapper.eq ("org_id", detpid).
                    eq ("pollution_type", pollutionType).
                    eq("DATE_FORMAT( data_date ,'%Y-%m-%d')",searchBeginTime);
            RStatPollutionOrgQPO rStatPollutionOrgQPO = rStatPollutionOrgQPOMapper.selectOne (rStatPollutionOrgQPOQueryWrapper);
            Optional.ofNullable (rStatPollutionOrgQPO).ifPresent (a->pollutionVO.setData (BigDecimal.valueOf(a.getValue()).setScale(2, RoundingMode.UP).doubleValue()));
        } else if (Objects.equals (harmonicPublicParam.getReportFlag (),BizParamConstant.STAT_BIZ_MONTH)) {
            QueryWrapper<RStatPollutionOrgMPO> rStatPollutionOrgMPOQueryWrapper = new QueryWrapper<> ();
            rStatPollutionOrgMPOQueryWrapper.eq ("org_id", detpid).
                    eq ("pollution_type", pollutionType).
                    eq("DATE_FORMAT( data_date ,'%Y-%m-%d')",searchBeginTime);
            RStatPollutionOrgMPO rStatPollutionOrgMPO = rStatPollutionOrgMPOMapper.selectOne (rStatPollutionOrgMPOQueryWrapper);
            Optional.ofNullable (rStatPollutionOrgMPO).ifPresent (a->pollutionVO.setData (BigDecimal.valueOf(a.getValue()).setScale(2, RoundingMode.UP).doubleValue()));
        } else if (Objects.equals (harmonicPublicParam.getReportFlag (),BizParamConstant.STAT_BIZ_DAY)) {
            QueryWrapper<RStatPollutionOrgDPO> rStatPollutionOrgDPOQueryWrapper = new QueryWrapper<> ();
            rStatPollutionOrgDPOQueryWrapper.eq ("org_id", detpid).
                    eq ("pollution_type", pollutionType).
                    between("DATE_FORMAT( data_date ,'%Y-%m-%d')",searchBeginTime,searchEndTime)
                    .orderByDesc("value").last(" limit 1");
            RStatPollutionOrgDPO rStatPollutionOrgDPO = rStatPollutionOrgDPOMapper.selectOne (rStatPollutionOrgDPOQueryWrapper);
            Optional.ofNullable (rStatPollutionOrgDPO).ifPresent (a->pollutionVO.setData (BigDecimal.valueOf(a.getValue()).setScale(2, RoundingMode.UP).doubleValue()));
        }else if(Objects.equals (harmonicPublicParam.getReportFlag (),BizParamConstant.STAT_BIZ_WEEK)){
            QueryWrapper<RStatPollutionOrgDPO> rStatPollutionOrgDPOQueryWrapper = new QueryWrapper<> ();
            rStatPollutionOrgDPOQueryWrapper.eq ("org_id", detpid).
                    eq ("pollution_type", pollutionType).
                    between("DATE_FORMAT( data_date ,'%Y-%m-%d')",searchBeginTime,searchEndTime)
                    .orderByDesc("value").last(" limit 1");
            RStatPollutionOrgDPO rStatPollutionOrgDPO = rStatPollutionOrgDPOMapper.selectOne (rStatPollutionOrgDPOQueryWrapper);
            Optional.ofNullable (rStatPollutionOrgDPO).ifPresent (a->pollutionVO.setData (BigDecimal.valueOf(a.getValue()).setScale(2, RoundingMode.UP).doubleValue()));

        }
    }


    /**
     * @Description: getSubstationInfoById
     * @Param: [param]
     * @return: java.util.List<com.njcn.device.pq.pojo.dto.PollutionSubstationDTO>
     * @Author: clam
     * @Date: 2022/11/3
     */
    @Override
    public List<PollutionSubstationDTO> getSubstationInfoById(HarmonicPublicParam deptParam) {
        String pollutionType = deptParam.getStatisticalType ( ).getId ();
        String searchBeginTime = deptParam.getSearchBeginTime ( ).substring (0,10);
        List<PollutionSubstationDTO> list = new ArrayList<>();

        if (deptParam.getType() != 0) {
            PmsDeviceInfoParam pmsDeviceInfoParam = new PmsDeviceInfoParam();
            //根据部门code获取部门id
            Dept dept = deptFeignClient.getDeptByCode(deptParam.getDeptIndex()).getData();
            if(ObjectUtil.isNull(dept)){
                return list;
            }
            pmsDeviceInfoParam.setDeptIndex(dept.getId());
            //获取统计类型
            pmsDeviceInfoParam.setStatisticalType(deptParam.getStatisticalType());
            //获取主网台账信息
            List<PmsGeneralDeviceDTO> deviceList = pmsGeneralDeviceInfoClient.getPmsDeviceInfoWithInOrg(pmsDeviceInfoParam).getData();
            deviceList.forEach(temp->{
                List<String> powers = temp.getPowerrIdList ( );
                //变电站不为空
                if(CollectionUtil.isNotEmpty(powers)){
                    PmsStatationStatInfoParam param=new PmsStatationStatInfoParam();
                    param.setPowerIds(powers);
                    List<PmsStatationStatInfoDTO> data = statationStatClient.getStatationStatInfo(param).getData();
                    //去重解决重复数据
                    ArrayList<PmsStatationStatInfoDTO> dsData = data.stream().collect(Collectors.collectingAndThen
                            (Collectors.toCollection(() ->
                                    new TreeSet<>(Comparator.comparing(o -> o.getPowerId()))), ArrayList::new));
                    Map<String, Double> stringDoubleMap = setPmsSubData(deptParam, pollutionType, searchBeginTime, powers);
                    if(CollectionUtil.isNotEmpty(data)){
                        dsData.forEach(power->{
                            PollutionSubstationDTO dto=new PollutionSubstationDTO();
                            dto.setId(power.getPowerId());
                            dto.setName(power.getPowerName());
                            dto.setVoltageLevel(power.getPowerVoltageLevel());
                            if(CollectionUtil.isNotEmpty(stringDoubleMap)){
                                if(stringDoubleMap.containsKey(power.getPowerId())){
                                    dto.setData(stringDoubleMap.get(power.getPowerId()));
                                }
                            }
                            list.add (dto) ;
                        });
                    }
                }

            });
        }else{
            deptParam.setServerName(generalInfo.getMicroServiceName());
            List<GeneralDeviceDTO> sub = generalDeviceInfoClient.getPracticalRunDeviceInfoAsSubstation(deptParam).getData();
            sub.forEach(item->{
                PollutionSubstationDTO pollutionSubstationDTO = lineFeignClient.getSubstationInfo(item.getIndex()).getData();
                String id = pollutionSubstationDTO.getId ();
                if(Objects.equals (deptParam.getReportFlag (),BizParamConstant.STAT_BIZ_YEAR) ){
                    QueryWrapper<RStatPollutionSubstationYPO> wrapper = new QueryWrapper<> ();
                    wrapper.eq ("substation_id",id).
                            eq ("pollution_type", pollutionType).
                            eq("DATE_FORMAT( data_date ,'%Y-%m-%d')",searchBeginTime);
                    RStatPollutionSubstationYPO rStatPollutionSubstationYPO = pollutionSubstationYPOMapper.selectOne (wrapper);

                    Optional.ofNullable (rStatPollutionSubstationYPO).ifPresent (t->pollutionSubstationDTO.setData (t.getValue ()));
                }else if(Objects.equals (deptParam.getReportFlag (),BizParamConstant.STAT_BIZ_QUARTER)){
                    QueryWrapper<RStatPollutionSubstationQPO> wrapper = new QueryWrapper<> ();
                    wrapper.eq ("substation_id",id).
                            eq ("pollution_type", pollutionType).
                            eq("DATE_FORMAT( data_date ,'%Y-%m-%d')",searchBeginTime);
                    RStatPollutionSubstationQPO rStatPollutionSubstationQPO = pollutionSubstationQPOMapper.selectOne (wrapper);

                    Optional.ofNullable (rStatPollutionSubstationQPO).ifPresent (t->pollutionSubstationDTO.setData (t.getValue ()));
                }else if(Objects.equals (deptParam.getReportFlag (),BizParamConstant.STAT_BIZ_MONTH)){
                    QueryWrapper<RStatPollutionSubstationM> wrapper = new QueryWrapper<> ();
                    wrapper.eq ("substation_id",id).
                            eq ("pollution_type", pollutionType).
                            eq("DATE_FORMAT( data_date ,'%Y-%m-%d')",searchBeginTime);
                    RStatPollutionSubstationM rStatPollutionSubstationM = pollutionSubstationMMapper.selectOne (wrapper);

                    Optional.ofNullable (rStatPollutionSubstationM).ifPresent (t->pollutionSubstationDTO.setData (t.getValue ()));

                }else if(Objects.equals (deptParam.getReportFlag (),BizParamConstant.STAT_BIZ_DAY)){
                    QueryWrapper<RStatPollutionSubstationDPO> wrapper = new QueryWrapper<> ();
                    wrapper.eq ("substation_id",id).
                            eq ("pollution_type", pollutionType).
                            eq("DATE_FORMAT( data_date ,'%Y-%m-%d')",searchBeginTime);
                    RStatPollutionSubstationDPO rStatPollutionSubstationDPO = pollutionSubstationDPOMapper.selectOne (wrapper);

                    Optional.ofNullable (rStatPollutionSubstationDPO).ifPresent (t->pollutionSubstationDTO.setData (t.getValue ()));
                }

                list.add(pollutionSubstationDTO);
            });
        }
        if (!CollectionUtils.isEmpty(list)){
            return list.stream().sorted(Comparator.comparing(PollutionSubstationDTO::getData).reversed().thenComparing(PollutionSubstationDTO::getName)).collect(Collectors.toList());
        }
        return list;
    }

    /**
     * @Description: getLineInfoById
     * @Param: [param]
     * @return: java.util.List<com.njcn.device.pq.pojo.dto.PollutionLineDTO>
     * @Author: clam
     * @Date: 2022/11/3
     */
    @Override
    public List<PollutionLineDTO> getLineInfoById(HarmonicPublicParam harmonicPublicParam) {
        harmonicPublicParam.setServerName(generalInfo.getMicroServiceName());
        List<PollutionLineDTO> list = new ArrayList<>();

        String pollutionType = harmonicPublicParam.getStatisticalType ( ).getId ();
        PollutionParamDTO paramDTO = new PollutionParamDTO();
        if (StringUtils.isBlank(RequestUtil.getDeptIndex())){
            return list;
        }
        if (harmonicPublicParam.getType() != 0) {
            PmsStatationStatInfoParam param=new PmsStatationStatInfoParam();
            param.setPowerIds(Arrays.asList(harmonicPublicParam.getId()));
            //获取变电站详情
            List<PmsStatationStatInfoDTO> data = statationStatClient.getStatationStatInfo(param).getData();
            if(CollectionUtil.isNotEmpty(data)){
                List<String> monitorId = data.stream().map(PmsStatationStatInfoDTO::getMonitorId).collect(Collectors.toList());
                List<RMpPollutionDPO> lineData = rMpPollutionDPOMapper.selectMaxList ( monitorId,pollutionType,harmonicPublicParam.getSearchBeginTime(),harmonicPublicParam.getSearchEndTime());
                Map<String, Double> lineMap = lineData.stream().collect(Collectors.toMap(RMpPollutionDPO::getLineId, RMpPollutionDPO::getValue));
                PollutionLineDTO dto;
                for (PmsStatationStatInfoDTO power : data) {
                    dto=new PollutionLineDTO();
                    dto.setId(power.getMonitorId());
                    dto.setName(power.getMonitorName());
                    dto.setPowerCompany(power.getOrgName());
                    dto.setSubstation(power.getPowerName());
                    dto.setSubstationId(power.getPowerId());
                    if(CollectionUtil.isNotEmpty(lineMap)){
                        if(lineMap.containsKey(power.getMonitorId())){
                            dto.setData(lineMap.get(power.getMonitorId()));
                        }
                    }
                    list.add (dto) ;
                }
            }
        }else{
            List<String> line = new ArrayList<>();
            List<GeneralDeviceDTO> sub = generalDeviceInfoClient.getPracticalRunDeviceInfoAsSubstation(harmonicPublicParam).getData();
            sub.forEach(item->{
                if (Objects.equals(harmonicPublicParam.getId(),item.getIndex())){
                    if (!CollectionUtils.isEmpty(item.getLineIndexes())){
                        line.addAll(item.getLineIndexes());
                    }
                }
            });
            if (!CollectionUtils.isEmpty(line)){
                paramDTO.setLineList(line);
                list = lineFeignClient.getLineInfo(paramDTO).getData();
                List<RMpPollutionDPO> lineData = rMpPollutionDPOMapper.selectMaxList ( line,pollutionType,harmonicPublicParam.getSearchBeginTime(),harmonicPublicParam.getSearchEndTime());
                if (!CollectionUtils.isEmpty(lineData)){
                    list.stream().map(list1->lineData.stream().filter(list2-> Objects.equals(list1.getId(),list2.getLineId ())).findAny().map(m->{
                        list1.setData (m.getValue ());
                        return list1;
                    })).collect(Collectors.toList());
                }
            } else {
                return list;
            }
        }
        return list.stream().sorted(Comparator.comparing(PollutionLineDTO::getData).reversed().thenComparing(PollutionLineDTO::getName)).collect(Collectors.toList());
    }


    @Override
    public List<PollutionLineDTO> getLineRankTop10 (HarmonicPublicParam param) {
        List<PollutionLineDTO> list=  new ArrayList<>();
        String pollutionType = param.getStatisticalType ( ).getId ();
        if(param.getType()==0) {
            param.setServerName(generalInfo.getMicroServiceName());
            List<String> lineList = new ArrayList<>();
            PollutionParamDTO paramDTO = new PollutionParamDTO();
            if (StringUtils.isBlank(RequestUtil.getDeptIndex())) {
                return list;
            }
            List<GeneralDeviceDTO> deviceList = generalDeviceInfoClient.getPracticalRunDeviceInfo(param).getData();
            deviceList.forEach(item -> {
                if (!CollectionUtils.isEmpty(item.getLineIndexes())) {
                    lineList.addAll(item.getLineIndexes());
                }
            });
            if (!CollectionUtils.isEmpty(lineList)) {
                paramDTO.setLineList(lineList);
                list = lineFeignClient.getLineInfo(paramDTO).getData();
                List<PublicDTO> result =rMpPollutionDPOMapper.getTop10Line(lineList,DateUtil.beginOfDay(DateUtil.parse(param.getSearchBeginTime())),DateUtil.endOfDay(DateUtil.parse(param.getSearchEndTime())), param.getStatisticalType().getId());
                if (!CollectionUtils.isEmpty(result)) {
                    list.stream().map(list1 -> result.stream().filter(list2 -> Objects.equals(list1.getId(), list2.getId())).findAny().map(m -> {
                        list1.setData(m.getData());
                        return list1;
                    })).collect(Collectors.toList());
                }
            }
            list.sort((item1, item2) -> item2.getData().compareTo(item1.getData()));
            if (list.size() > Param.UP_LIMIT) {
                return list.subList(Param.DOWN_LIMIT, Param.UP_LIMIT);
            }
            return list;
        }
        PmsDeviceInfoParam pmsDeviceInfoParam = new PmsDeviceInfoParam();
        pmsDeviceInfoParam.setDeptIndex(param.getDeptIndex());
        //获取统计类型
        pmsDeviceInfoParam.setStatisticalType(param.getStatisticalType());
        //获取主网台账信息
        List<PmsGeneralDeviceDTO> deviceList = pmsGeneralDeviceInfoClient.getPmsDeviceInfoWithInOrg(pmsDeviceInfoParam).getData();
        List<String> monitorIdList=new ArrayList<>();
        deviceList.forEach(dept -> {
            monitorIdList.addAll(dept.getMonitorIdList());
        });

        if(CollectionUtil.isNotEmpty(monitorIdList)){
            //获取监测点数据
            List<RMpPollutionDPO> lineData = rMpPollutionDPOMapper.selectMaxList ( monitorIdList,pollutionType,param.getSearchBeginTime(),param.getSearchEndTime());

            if(CollectionUtil.isEmpty(lineData)){
                return list;
            }

            //获取主网监测点信息
            List<Monitor> data = monitorClient.getMonitorList(monitorIdList).getData();
            Map<String, Monitor> monitorMap = data.stream().collect(Collectors.toMap(Monitor::getId, Function.identity(), (key1, kye2) -> key1));
            lineData.sort((item1, item2) -> item2.getValue().compareTo(item1.getValue()));
            if (lineData.size() > Param.UP_LIMIT) {
                lineData = lineData.subList(Param.DOWN_LIMIT, Param.UP_LIMIT);
            }

            PollutionLineDTO dto;
            for (RMpPollutionDPO lineDatum : lineData) {
                if(monitorMap.containsKey(lineDatum.getLineId())){
                    Monitor monitor = monitorMap.get(lineDatum.getLineId());
                    dto=new PollutionLineDTO();
                    dto.setId(monitor.getId());
                    dto.setName(monitor.getName());
                    dto.setPowerCompany(monitor.getOrgName());
                    dto.setSubstation(monitor.getPowerrId());
                    dto.setSubstationId(monitor.getPowerrName());
                    dto.setBusBar(monitor.getLineName());
                    dto.setData(lineDatum.getValue());
                    list.add(dto);
                }
            }
        }
        return list;
    }

}
