package com.njcn.device.pms.service.distribution.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import com.njcn.common.pojo.constant.BizParamConstant;
import com.njcn.common.pojo.dto.SimpleDTO;
import com.njcn.common.pojo.param.StatisticsBizBaseParam;
import com.njcn.device.pms.mapper.distribution.PwROperatingIndexMapper;
import com.njcn.device.pms.mapper.majornetwork.RQualityParameterMapper;
import com.njcn.device.pms.pojo.dto.PmsGeneralDeviceDTO;
import com.njcn.device.pms.pojo.param.PmsDeviceInfoParam;
import com.njcn.device.pms.pojo.po.RQualityParameterPO;
import com.njcn.device.pms.pojo.vo.PwRDnOperatingVO;
import com.njcn.device.pms.pojo.vo.PwRQualityParameterVO;
import com.njcn.device.pms.pojo.vo.RQualityParameterPollVO;
import com.njcn.device.pms.service.distribution.PwDataQualityStatService;
import com.njcn.device.pms.service.majornetwork.IPmsGeneralDeviceService;
import com.njcn.system.api.DicDataFeignClient;
import com.njcn.system.enums.DicDataEnum;
import com.njcn.user.api.DeptFeignClient;
import com.njcn.user.pojo.dto.DeptDTO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 配网数据质量-数据质量统计
 *
 * @author yzh
 * @date 2022/11/4
 */

@Service
@Slf4j
@RequiredArgsConstructor
public class PwDataQualityStatServiceImpl implements PwDataQualityStatService {

    private final IPmsGeneralDeviceService iPmsGeneralDeviceService;

    private final DicDataFeignClient dicDataFeignClient;

    private final DeptFeignClient deptFeignClient;

    private final PwROperatingIndexMapper rOperatingIndexMapper;

    private final RQualityParameterMapper rQualityParameterMapper;

    private final DecimalFormat df = new DecimalFormat("###.00");

    /**
     * 获取配网数据质量-台账数据质量统计
     *
     * @param param 条件参数
     * @return java.util.List<com.njcn.event.pojo.vo.RQualityParameterVO>
     * @author yzh
     * @date 2022/11/4
     */
    @Override
    public List<PwRQualityParameterVO> getPwLedgerDataQualityStat(StatisticsBizBaseParam param) {
        // 获取单位的子单位信息
//        List<PmsGeneralDeviceDTO> data = getDeptInfo(param);
//        if (CollUtil.isEmpty(data)) {
//            return Collections.emptyList();
//        }
        /*获取直接下属子单位*/
        List<DeptDTO> deptDTOList = deptFeignClient.getDepSonDetailByDeptId (param.getId ()).getData ( );
        if (CollUtil.isEmpty(deptDTOList)) {
            return Collections.emptyList();
        }
        List<String> deptIdList = deptDTOList.stream().map(DeptDTO::getCode).collect(Collectors.toList());
        Map<String, DeptDTO> deptDTOMap = deptDTOList.stream().collect(Collectors.toMap(DeptDTO::getCode, deptDTO -> deptDTO));

        // 获取配网字典id
        String distributionPoint = dicDataFeignClient.getDicDataByCode(DicDataEnum.DISTRIBUTION_POINT.getCode()).getData().getId();
//        // 获取单位id
//        List<String> deptIdList = data.stream().map(PmsGeneralDeviceDTO::getIndex).collect(Collectors.toList());
        // 获取配网数据质量-台账数据质量统计
        List<RQualityParameterPO> pos = rQualityParameterMapper.getLedgerDataQualityStat(param, deptIdList, distributionPoint);
        if (CollUtil.isEmpty(pos)) {
            return Collections.emptyList();
        }
        //将单位信息转为map集合 key: 单位id  value: 单位实体
//        Map<String, PmsGeneralDeviceDTO> dataMap = getDataMap(data);
        // 属性赋值
        return pos.stream().map(po -> {
            PwRQualityParameterVO vo = new PwRQualityParameterVO();
            BeanUtils.copyProperties(po, vo);
            vo.setOrgName(deptDTOMap.get(vo.getOrgNo()).getName());
            vo.setMeasurementCompleteQuantity(Double.toString(
                    Integer.parseInt(po.getMeasurementCount()) * po.getMonitoringIntegrityRate()
            ));
            return vo;
        }).collect(Collectors.toList());
    }

    /**
     * 获取配网数据质量-监测指标数据质量统计
     *
     * @param param 条件参数
     * @return java.util.List<com.njcn.event.pojo.vo.PwROperatingIndexVO>
     * @author yzh
     * @date 2022/11/4
     */
    @Override
    public List<PwRDnOperatingVO> getPwMonitoringIndexDataQualityStat(StatisticsBizBaseParam param) {
        // 获取单位的子单位信息
//        List<PmsGeneralDeviceDTO> data = getDeptInfo(param);
//        if (CollUtil.isEmpty(data)) {
//            return Collections.emptyList();
//        }
        /*获取直接下属子单位*/
        List<DeptDTO> deptDTOList = deptFeignClient.getDepSonDetailByDeptId (param.getId ()).getData ( );
        if (CollUtil.isEmpty(deptDTOList)) {
            return Collections.emptyList();
        }
        List<String> deptIdList = deptDTOList.stream().map(DeptDTO::getCode).collect(Collectors.toList());
        Map<String, DeptDTO> deptDTOMap = deptDTOList.stream().collect(Collectors.toMap(DeptDTO::getCode, deptDTO -> deptDTO));

        // 创建集合封装数据
        List<PwRDnOperatingVO> result = new ArrayList<>();
        // 日期条件
        switch (param.getType().toString()) {
            // 年
            case BizParamConstant.STAT_BIZ_YEAR:
                result = rOperatingIndexMapper.getYearInfo(param,
                        deptIdList);
                break;
            // 季
            case BizParamConstant.STAT_BIZ_QUARTER:
                //获取时间月
                Date startDate=DateUtil.parse(param.getStartTime(),"yyyy-MM-dd");
                Date endDate=DateUtil.parse(param.getEndTime(),"yyyy-MM-dd");
                // 声明保存日期集合
                List<String> dates = new ArrayList<>();
                Calendar calendar = Calendar.getInstance();
                while (startDate.getTime() <= endDate.getTime()) {
                    // 设置日期Calendar.YEAR
                    calendar.setTime(startDate);
                    dates.add(calendar.get(Calendar.MONTH)+1+"");
                    //把月数增加 1
                    calendar.add(Calendar.MONTH, 1);
                    // 获取增加后的日期
                    startDate = calendar.getTime();
                }
                result = rOperatingIndexMapper.getSeasonInfo(param,
                        deptIdList,dates);
                break;
            // 月
            case BizParamConstant.STAT_BIZ_MONTH:
                result = rOperatingIndexMapper.getMonthInfo(param,
                        deptIdList);
                break;
            default:
                break;
        }
        if (CollUtil.isEmpty(result)) {
            return Collections.emptyList();
        }
        //将单位信息转为map集合 key: 单位id  value: 单位实体
//        Map<String, PmsGeneralDeviceDTO> dataMap = getDataMap(data);
        // 属性赋值
        return result.stream().peek(vo -> {
            vo.setOrgName(deptDTOMap.get(vo.getOrgNo()).getName());
        }).collect(Collectors.toList());

    }

    /**
     * 获取配网数据质量-监测指标数据质量问题汇总统计
     *
     * @param param 条件参数
     * @return java.util.List<com.njcn.event.pojo.vo.RQualityParameterPollVO>
     * @author yzh
     * @date 2022/11/7
     */
    @Override
    public List<RQualityParameterPollVO> getPwSummaryStatOfMonitoringIndexDataQualityProblems(StatisticsBizBaseParam param) {
        // 获取单位的子单位信息
//        List<PmsGeneralDeviceDTO> data = getDeptInfo(param);
//        if (CollUtil.isEmpty(data)) {
//            return Collections.emptyList();
//        }
//        // 取出单位id
//        List<String> deptIds = data.stream().map(PmsGeneralDeviceDTO::getIndex).collect(Collectors.toList());
        /*获取直接下属子单位*/
        List<DeptDTO> deptDTOList = deptFeignClient.getDepSonDetailByDeptId (param.getId ()).getData ( );
        if (CollUtil.isEmpty(deptDTOList)) {
            return Collections.emptyList();
        }
        List<String> deptIds = deptDTOList.stream().map(DeptDTO::getCode).collect(Collectors.toList());
        Map<String, DeptDTO> deptDTOMap = deptDTOList.stream().collect(Collectors.toMap(DeptDTO::getCode, deptDTO -> deptDTO));

        // 获取配网字典id
        String distributionPoint = dicDataFeignClient.getDicDataByCode(DicDataEnum.DISTRIBUTION_POINT.getCode()).getData().getId();
        // 获取配网数据质量-监测指标数据质量问题汇总统计
        List<RQualityParameterPO> pos = rQualityParameterMapper.getLedgerDataQualityStat(param, deptIds, distributionPoint);
        if (CollUtil.isEmpty(pos)) {
            return Collections.emptyList();
        }
        //将单位信息转为map集合 key: 单位id  value: 单位实体
//        Map<String, PmsGeneralDeviceDTO> dataMap = getDataMap(data);
        return pos.stream().map(po -> {
            RQualityParameterPollVO vo = new RQualityParameterPollVO();
            BeanUtils.copyProperties(po, vo);
            vo.setOrgId(po.getOrgNo());
            vo.setOrgName(deptDTOMap.get(vo.getOrgId()).getName());
            vo.setProblemProportion(Double.parseDouble(df.format((po.getProblem() * 1.0) / (po.getEffectiveAccessMeasurementCount() * 1.0))) * 100);
            if (po.getProblemYearOnYear() == null) {
                vo.setProblemYearOnYear("3.14159");
            } else {
                vo.setProblemYearOnYear(po.getProblemYearOnYear());
            }
            return vo;
        }).collect(Collectors.toList());
    }

    /**
     * 获取单位的子单位信息
     */
    private List<PmsGeneralDeviceDTO> getDeptInfo(StatisticsBizBaseParam param) {
        PmsDeviceInfoParam pmsDeviceInfoParam = new PmsDeviceInfoParam();
        pmsDeviceInfoParam.setDeptIndex(param.getId());
        pmsDeviceInfoParam.setStatisticalType(new SimpleDTO());
        return iPmsGeneralDeviceService.getPmsDeviceInfoWithInOrg(pmsDeviceInfoParam);
    }

    /**
     * 将单位信息转为map集合 key: 单位id  value: 单位实体
     */
    private Map<String, PmsGeneralDeviceDTO> getDataMap(List<PmsGeneralDeviceDTO> data) {
        return data
                .stream()
                .collect(Collectors.toMap(PmsGeneralDeviceDTO::getIndex, PmsGeneralDeviceDTO -> PmsGeneralDeviceDTO));
    }


}
