package com.tofly.xrtygis.custom.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tofly.common.core.util.Date8Util;
import com.tofly.common.core.util.DateUtil;
import com.tofly.common.oauth.exception.ToflyDeniedException;
import com.tofly.common.oauth.util.SecurityUtils;
import com.tofly.xrtygis.config.WaterFeign;
import com.tofly.xrtygis.custom.entity.dto.IndexInfoDto;
import com.tofly.xrtygis.custom.entity.dto.RealValDto;
import com.tofly.xrtygis.custom.entity.dto.RelationshipCostDto;
import com.tofly.xrtygis.custom.entity.dto.WisdomDisplayDto;
import com.tofly.xrtygis.custom.entity.marketing.CustomerDto;
import com.tofly.xrtygis.custom.entity.marketing.CustomerInfo;
import com.tofly.xrtygis.custom.entity.marketing.CustomerWaterVo;
import com.tofly.xrtygis.custom.entity.marketing.WaterVolume;
import com.tofly.xrtygis.custom.entity.vo.WaterCruxIndexVo;
import com.tofly.xrtygis.custom.mapper.CustomDisplayMapper;
import com.tofly.xrtygis.custom.service.CustomDisplayService;
import com.tofly.xrtygis.custom.util.CallAPIUtil;
import com.tofly.xrtygis.custom.util.CommonMethod;
import com.tofly.xrtygis.custom.util.Date7Utils;
import com.tofly.xrtygis.entity.*;
import com.tofly.xrtygis.entity.vo.PipeMaterialStatisticalVo;
import com.tofly.xrtygis.service.*;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.awt.geom.Point2D;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 自定义智慧综合展示相关
 *
 * @author 陈浩
 * @date 2021-3-25
 */
@Service
@AllArgsConstructor
public class CustomDisplayServiceImpl implements CustomDisplayService {

    private final ScadastaitemService scadastaitemService;
    private final LayerfieldService layerfieldService;
    private final CustomDisplayMapper customDisplayMapper;
    private final VideoconfigService videoconfigService;
    private final WatermeterService watermeterService;
    private final PipelinktableService pipelinktableService;
    private final DensityconfigService densityconfigService;
    private final WarnService warnService;
    private final ScadastationService scadastationService;

    private final WaterFeign waterFeign;


    /**
     * 添加动态标识
     *
     * @param layerfield 动态标识
     * @return true or false
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean insertDynamicLogo(Layerfield layerfield) {
        Layerfield layer = layerfieldService.getOne(Wrappers.<Layerfield>lambdaQuery()
                .eq(Layerfield::getLayerEn, layerfield.getLayerEn())
                .eq(Layerfield::getCreateUser, SecurityUtils.getUserId()));

        layerfield.setCreateTime(new Date());

        if (layer != null) {
            layerfield.setId(layer.getId());
            layerfieldService.updateById(layerfield);
        } else {
            layerfieldService.save(layerfield);
        }
        return true;
    }

    /**
     * 删除动态标注
     *
     * @param id 动态标识id
     * @return true of false
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteDynamicLogo(Long id) {
        return layerfieldService.removeById(id);
    }

    /**
     * 查看动态标注
     *
     * @param page page
     * @return page
     */
    @Override
    public Page viewDynamicLogo(Page page) {
        Long userId = SecurityUtils.getUserId();
        return layerfieldService.page(page, Wrappers.<Layerfield>lambdaQuery()
                .eq(Layerfield::getCreateUser, SecurityUtils.getUserId()));
    }

    /**
     * 获取多个测站指标
     *
     * @param stids 测站id集合
     * @return map
     */
    @Override
    public Map<Long, Map<Long, Object>> getSiteInfos(String stids) {
        if (stids.isEmpty()) {
            throw new ToflyDeniedException("请传入测站");
        }

        Map<Long, Map<Long, Object>> infoMap = new HashMap<>();

        List<Long> stationId = scadastationService.list(Wrappers.<Scadastation>lambdaQuery()
                .in(Scadastation::getId, Arrays.asList(stids.split(",")))
                .eq(Scadastation::getState, 1)
                .select(Scadastation::getId))
                .stream().filter(Objects::nonNull)
                .map(Scadastation::getId)
                .collect(Collectors.toList());

        if (CollectionUtil.isEmpty(stationId)) {
            throw new ToflyDeniedException("所选站点皆未启用");
        }

        //查询所传测站下的指标编号
        List<Scadastaitem> scadastaitems = scadastaitemService.list(Wrappers.<Scadastaitem>lambdaQuery()
                .select(Scadastaitem::getId, Scadastaitem::getItcd, Scadastaitem::getStationId)
                .eq(Scadastaitem::getState, 1)
                .in(Scadastaitem::getStationId, stationId));
        //根据测站的id对数据进行分组
        Map<Long, List<Scadastaitem>> collect = scadastaitems.stream().filter(Objects::nonNull).collect(Collectors.groupingBy(Scadastaitem::getStationId));

        List<String> itcdList = scadastaitems.stream().filter(Objects::nonNull).map(Scadastaitem::getItcd).collect(Collectors.toList());
        if (CollectionUtil.isEmpty(itcdList)) {
            return infoMap;
        }
        //将查询出来的指标数据按编号分组
        Map<String, List<IndexInfoDto>> realVal = customDisplayMapper.getRealtime(itcdList)
                .stream().filter(Objects::nonNull).collect(Collectors.groupingBy(IndexInfoDto::getItcd));
        String tableName = "TF_YWPN_SCADAHISTORY_R_" + DateUtil.getDateFormat(new Date(), "yyyyMM");
        Map<String, List<IndexInfoDto>> hisVal = customDisplayMapper.getMaxHistoryVal(itcdList, tableName)
//        Map<String, List<IndexInfoDto>> hisVal = customDisplayMapper.getMaxHistoryVal(itcdList, "TF_YWPN_SCADAHISTORY_R_202302")
                .stream().filter(Objects::nonNull).collect(Collectors.groupingBy(IndexInfoDto::getItcd));

        List<Warn> warnList = warnService.list();
        List<String> warnItcdList = null;
        if (warnList != null && !warnList.isEmpty()) {
            warnItcdList = warnList.stream()
                    .map(Warn::getItcd).collect(Collectors.toList());
        }

        List<String> finalWarnItcdList = warnItcdList;
        collect.forEach((k, l) -> {
            Map<Long, Object> itemMap = new HashMap<>();

            //遍历编号，查出对应实时指标
            for (Scadastaitem item : l) {

                RealValDto dto = new RealValDto();
                if (realVal.containsKey(item.getItcd())) {
                    Double real = realVal.get(item.getItcd()).get(0).getItval();
                    dto.setRealVal(real);
                    dto.setIsWarn("1");
                    if (finalWarnItcdList != null) {
                        if (finalWarnItcdList.contains(item.getItcd())) {
                            dto.setIsWarn("0");
                        }
                    }

                    if (hisVal.containsKey(item.getItcd())) {
                        String mark;
                        Double his = hisVal.get(item.getItcd()).get(0).getItval();
                        if (his > real) {
                            mark = "0";
                        } else if (his < real) {
                            mark = "2";
                        } else {
                            mark = "1";
                        }
                        dto.setMark(mark);
                    } else {
                        dto.setMark("2");
                    }
                    itemMap.put(item.getId(), dto);
                } else {
                    itemMap.put(item.getId(), null);
                }
            }

            infoMap.put(k, itemMap);
        });

        return infoMap;
    }

    /**
     * 进取水趋势
     *
     * @param page      page
     * @param scid      测站id
     * @param code      0：按日查看  1：按月查看 2：同期比对
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @return page
     */
    @Override
    public Page waterVolumeTrend(Page page, Long scid, String code, String startTime, String endTime) {

        Page<Map> resultPage = null;

        switch (code) {
            case "0":
                resultPage = customDisplayMapper.waterByHour(page, scid, startTime, endTime);
                break;
            case "1":
                resultPage = customDisplayMapper.waterByDay(page, scid, startTime, endTime);
                break;
            case "2":
                resultPage = customDisplayMapper.waterByMonth(page, scid, startTime, endTime);
                break;
            case "3":
                List<String> list = new ArrayList<>();
                for (String year : startTime.split(",")) {
                    for (String month : endTime.split(",")) {
                        list.add(year + month);
                    }
                }
                resultPage = customDisplayMapper.waterContrast(page, scid, list);
                break;
            default:
                throw new ToflyDeniedException("CODE ERROR");
        }
        return resultPage;
    }

    /**
     * 查询视频监控的分组名
     */
    @Override
    public List getGroupName() {
        return videoconfigService.list(Wrappers.<Videoconfig>lambdaQuery().select(Videoconfig::getGroupName));
    }

    /**
     * 获取视频监控信息
     *
     * @return list
     */
    @Override
    public List getAllVideo() {
        return videoconfigService.list();
    }

    /**
     * 模糊查询视频地址
     *
     * @param add 地址
     * @return list
     */
    @Override
    public List likeVideo(String add) {

        List<Videoconfig> list = videoconfigService.list(Wrappers.<Videoconfig>lambdaQuery()
                .like(Videoconfig::getAddress, add)
                .orderByAsc(Videoconfig::getAddress));

        if (list.isEmpty()) {
            throw new ToflyDeniedException("未找到相关信息");
        }

        return list;
    }

    /**
     * 修该监控视频大屏显示
     *
     * @param videoId 视频id
     * @return true of false
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateVideo(String videoId) {
        if (videoId == null || "".equals(videoId)) {
            throw new ToflyDeniedException("请选择监控视频");
        }
        List<String> videoIdList = Arrays.asList(videoId.trim().split(","));

        List<Videoconfig> videoconfigList = videoconfigService.list(Wrappers.<Videoconfig>lambdaQuery()
                .select(Videoconfig::getId, Videoconfig::getIsshow, Videoconfig::getAddress)
                .in(Videoconfig::getId, videoIdList));

        videoconfigList.forEach(video -> {
            video.setIsshow("1");
            videoconfigService.updateById(video);
        });

        return true;
    }

    /**
     * 停水区域查询
     *
     * @param valve 阀门编号
     * @return
     */
    @Override
    public Page waterStopArea(Page page, String valve) {
        return waterFeign.viewWaterCut(page, valve);
    }

    /**
     * 营销信息-获取客户用水量
     *
     * @param page        page
     * @param customerNum 客户编码
     * @return list
     */
    @Override
    public Page getUseWater(Page page, String customerNum) {
        return waterFeign.viewUseWater(customerNum);
    }

    /**
     * 营销信息-查看客户历史用水量
     *
     * @param page    page
     * @param khbh    客户编号
     * @param strTime 开始时间
     * @param endTime 结束时间
     * @return page
     */
    @Override
    public Page getUserHistroy(Page page, String khbh, String strTime, String endTime) {
        return waterFeign.useWaterHistory(page, khbh, strTime, endTime);
    }

    /**
     * 营销信息-客户用水量监控
     *
     * @param page
     * @return page
     */
    @Override
    public Page waterMonitoring(Page page) {
        return waterFeign.waterMonitoring(page);
    }

    /**
     * @param page    page
     * @param lon     区域各顶点的横坐标数组
     * @param lat     区域各顶点的纵坐标数组
     * @param strTime 开始时间
     * @param endTime 结束时间
     * @param code    0:查看全部   1：同期比对
     * @return map
     */
    @Override
    public Map<String, Object> getTableInArea(Page page, Double[] lon, Double[] lat, String strTime, String endTime, String code) {
        if (lon == null || lat == null) {
            throw new ToflyDeniedException("区域范围不能为空");
        }
        //查询所有表位过滤坐标为空的数据
        List<Watermeter> watermeterList = watermeterService.list().stream().filter(wm -> {
            return wm.getX() != null && wm.getY() != null;
        }).collect(Collectors.toList());

        if (watermeterList.isEmpty()) {
            throw new ToflyDeniedException("请先上传水表坐标");
        }

        //存放返回结果
        Map<String, Object> result = new HashMap<>();
        //存放点坐标的集合
        List<Point2D.Double> pointList = new ArrayList<>();

        for (int i = 0; i < lon.length; i++) {
            pointList.add(new Point2D.Double(lon[i], lat[i]));
        }
        //循环有坐标的水表
        Iterator<Watermeter> it = watermeterList.iterator();


        Point2D.Double point;
        //在范围内添加到一个新的集合，否则删除
        while (it.hasNext()) {
            Watermeter next = it.next();
            point = new Point2D.Double(next.getX(), next.getY());
            if (!IsPtInPoly(point, pointList)) {
                it.remove();
            }
        }
        //取出水表编号
        List<String> sid = watermeterList.stream().map(Watermeter::getSid).collect(Collectors.toList());

        if (sid.isEmpty()) {
            throw new ToflyDeniedException("未查询到相关信息");
        }

        String sidStr = sid.toString();
        String substring = sidStr.substring(1, sidStr.lastIndexOf("]"));

        WaterVolume waterVolume = new WaterVolume();
        waterVolume.setSBBH(substring);
        //传入时间为空区间设置为三年前
        if (strTime != null || endTime != null) {
            waterVolume.setCWYF_START(strTime);
            waterVolume.setCWYF_END(endTime);
        } else {
            waterVolume.setCWYF_START(DateUtil.getDateFormat(Date7Utils.addNextPeriod(-36, new Date()), "yyyyMM"));
            waterVolume.setCWYF_END(Date8Util.getYearMonth());
        }

        waterVolume.setACTION("query");

        Map map = null;

        try {
            //查询区域类所有水表信息
            map = CallAPIUtil.callAPIUtil(waterVolume, "api/Business/GetCustomerWater");
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (null != map.get("data")) {
            List<CustomerWaterVo> data = JSONObject.parseArray(map.get("data").toString(), CustomerWaterVo.class);
            //根据月份分组
            Map<String, List<CustomerWaterVo>> collect = data.stream().collect(Collectors.groupingBy(CustomerWaterVo::getCWYF));
            //拿出月份
            List<String> cwyfList = new ArrayList(collect.keySet());
            //存放区域水量
            Map<String, Object> mapSum = new HashMap<>();

            List pageList = new ArrayList();

            for (String month : cwyfList) {
                double sum = 0;
                if ("0".equals(code)) {
                    //计算截取区域的用水总和
                    sum = collect.get(month).stream().mapToDouble(CustomerWaterVo::getYSL).sum();
                } else {
                    String mon = strTime.substring(4, 6);
                    if (mon.equals(month.substring(4, 6))) {
                        sum = collect.get(month).stream().mapToDouble(CustomerWaterVo::getYSL).sum();
                    }
                }
                mapSum.put(month, sum);
            }
            //获取坐标
            List<Map> coordinate = customDisplayMapper.getCoordinate(sid);

            pageList.add(mapSum);

            result.put("areaSum", CommonMethod.listToPage(page, pageList));
            result.put("coordinate", coordinate);
        }
        return result;
    }

    /**
     * 通过管线编号查询客户信息
     *
     * @param page  page
     * @param pipes 管线编号
     * @return page
     */
    @Override
    public Page pipeToCustomers(Page page, String pipes) {

        String[] pipeArr = pipes.split(",");
        if (pipeArr.length == 0) {
            throw new ToflyDeniedException("请重新选择管线编号");
        }
        Map<String, Object> customer = new HashMap();
        for (String pipe : pipeArr) {
            Pipelinktable pipetable = pipelinktableService.getById(pipe);
            //关联表为空或者客户编号为空时返回空
            if (null == pipetable || null == pipetable.getTableId()) {
                customer.put(pipe, null);
                continue;
            }

            CustomerDto customerDto = new CustomerDto();
            customerDto.setYHBH(pipetable.getTableId());
            customerDto.setACTION("query");

            Map map = new HashMap();
            try {
                map = CallAPIUtil.callAPIUtil(customer, "api/Business/GetCustomerData");
            } catch (Exception e) {
                e.printStackTrace();
            }

            List<CustomerInfo> infos = JSONObject.parseArray(map.get("data").toString(), CustomerInfo.class);

            if (null == infos || infos.size() == 0) {
                customer.put(pipe, null);
                continue;
            }
            for (CustomerInfo info : infos) {
                Map<String, Double> coordinateInfo = customDisplayMapper.getCoordinateInfo(info.getSBBH());
                if (!coordinateInfo.isEmpty()) {
                    info.setX(coordinateInfo.get("x"));
                    info.setY(coordinateInfo.get("y"));
                }
            }
            customer.put(pipe, infos);
        }
        List<Map> pageList = new ArrayList<>();
        pageList.add(customer);
        return CommonMethod.listToPage(page, pageList);
    }

    /**
     * 多因子关系成本图
     *
     * @param dto dto
     * @return map
     */
    @Override
    public Map<String, Object> relationshipCost(RelationshipCostDto dto) {
        if (dto == null) {
            throw new ToflyDeniedException("数据不能为空");
        }

        if (StringUtils.isEmpty(dto.getCode())) {
            throw new ToflyDeniedException("范围不能为空");
        }
//        Densityconfig config = densityconfigService.getById(1);
//
//        if (null == config) {
//            throw new ToflyDeniedException("请先配置浓度信息");
//        }
        Map<String, Object> result = new HashMap<>();

        //原水数据
        if (!StringUtils.isEmpty(dto.getPrimary())) {
            List<Map<String, Object>> primaryInfo = customDisplayMapper.getPrimaryInfo(Arrays.asList(dto.getPrimary().split(",")), dto.getStart(), dto.getEnd());
            if (!primaryInfo.isEmpty()) {
                result.put("primary", primaryInfo.stream().collect(Collectors.groupingBy(m -> m.get("createTime"))));
            } else {
                result.put("primary", null);
            }
        }
        //过程水数据
        if (!StringUtils.isEmpty(dto.getProcess())) {
            List<Map<String, Object>> primaryInfo = customDisplayMapper.getPrimaryInfo(Arrays.asList(dto.getProcess().split(",")), dto.getStart(), dto.getEnd());
            if (!primaryInfo.isEmpty()) {
                result.put("process", primaryInfo.stream().collect(Collectors.groupingBy(m -> m.get("createTime"))));
            } else {
                result.put("process", null);
            }
        }
        Map<String, List<Map<String, Object>>> map = new HashMap<>();
        //pac单耗
        if (!StringUtils.isEmpty(dto.getPacOne())) {
            map.put("pacOne", customDisplayMapper.getPacDensity(dto.getStart(), dto.getEnd(), "PACDH_ONE"));
        }
        //pam单耗
        if (!StringUtils.isEmpty(dto.getPamTwo())) {
            map.put("pamTwo", customDisplayMapper.getPacDensity(dto.getStart(), dto.getEnd(), "PAMDH"));
        }
        //食盐
        if (!StringUtils.isEmpty(dto.getSyOne())) {
            map.put("syOne", customDisplayMapper.getPacDensity(dto.getStart(), dto.getEnd(), "SYDH_ONE"));
        }
        //高锰酸钾单耗
        if (!StringUtils.isEmpty(dto.getGmsj())) {
            map.put("gmsj", customDisplayMapper.getPacDensity(dto.getStart(), dto.getEnd(), "GMSJFHYDH"));
        }
        //液氯单耗
        if (!StringUtils.isEmpty(dto.getYl())) {
            map.put("yl", customDisplayMapper.getPacDensity(dto.getStart(), dto.getEnd(), "YLDH_TWO"));
        }
        if (!StringUtils.isEmpty(dto.getPacTwo())) {
            map.put("pacTwo", customDisplayMapper.getPacDensity(dto.getStart(), dto.getEnd(), "PACDH_TWO"));
        }
        if (!StringUtils.isEmpty(dto.getZsdhOne())) {
            map.put("zsdhOne", customDisplayMapper.getPacDensity(dto.getStart(), dto.getEnd(), "DH_ONE"));
        }
        if (!StringUtils.isEmpty(dto.getZsdhTwo())) {
            map.put("zsdhTwo", customDisplayMapper.getPacDensity(dto.getStart(), dto.getEnd(), "DH_TWO"));
        }
        if (!StringUtils.isEmpty(dto.getCndhTwo())) {
            map.put("cndhTwo", customDisplayMapper.getPacDensity(dto.getStart(), dto.getEnd(), "CNDH_TWO"));
        }

        //总耗
        map.put("total", customDisplayMapper.totalConsumption(dto));

        result.put("unit", map);
        if (!StringUtils.isEmpty(dto.getParam())) {
            String sql = "round((nvl(PACZFY_ONE,0) + nvl(PACZFY_TWO,0)) / (decode(GSL_TOTAL,0,null,GSL_TOTAL) * 10),4)    paccb_total,";

            StringBuilder sb = new StringBuilder();
            for (String s : dto.getParam().split(",")) {
                sb.append("round(").append(s).append(",4) ").append(s).append(",");
            }

            String param = sb.toString();

            if ("2".equals(dto.getCode())) {
                param += sql;
            }
            List<Map<String, Object>> costAndWater = customDisplayMapper.getCostAndWater(param, dto.getStart(), dto.getEnd());
            result.put("costAndWater", costAndWater != null ? costAndWater.stream().collect(Collectors.groupingBy(m -> m.get("upDate"))) : null);
        }
        List<Map<String, Object>> waterVolume = customDisplayMapper.getWaterVolume(dto.getCode(), dto.getStart(), dto.getEnd());
        result.put("waterVloum", waterVolume != null ? waterVolume.stream().collect(Collectors.groupingBy(m -> m.get("upDate"))) : null);

        return result;
    }

    /**
     * 多因子浓度配置
     *
     * @param config config
     * @return boolean
     */
    @Override
    public boolean concentrationConfig(Densityconfig config) {
        if (null == config) {
            throw new ToflyDeniedException("数据不允许为空");
        }
        if (null != densityconfigService.getById(1)) {
            densityconfigService.update(Wrappers.<Densityconfig>lambdaUpdate()
                    .eq(Densityconfig::getId, 1)
                    .set(Densityconfig::getGmsjNd, config.getGmsjNd())
                    .set(Densityconfig::getPacNd, config.getPacNd())
                    .set(Densityconfig::getPamNd, config.getPamNd()));
        } else {
            densityconfigService.save(config);
        }
        return true;
    }

    /**
     * 查看配置信息
     *
     * @return Densityconfig
     */
    @Override
    public Densityconfig viewConfig() {
        return densityconfigService.getById(1);
    }

    /**
     * 水表关联查询
     *
     * @param page page
     * @param khbh 客户编号
     * @return page
     */
    @Override
    public Page<Map> viewTable(Page page, String khbh, String khxm, String khdz) {
        return waterFeign.viewTable(page, khbh, khxm, khdz);
    }

    /**
     * 获得编码表详细消息
     *
     * @param pcid pcid
     * @return list
     */
    @Override
    public List<Map<String, Object>> getCodeInfo(String pcid) {
        return customDisplayMapper.getCodeInfo(Arrays.asList(pcid.split(",")));
    }

    @Override
    public WaterCruxIndexVo viewWaterCruxIndex(WisdomDisplayDto wisdomDisplayDto, List<String> codes) {
        WaterCruxIndexVo waterCruxIndexVo = new WaterCruxIndexVo();
        SimpleDateFormat sdfMonth = new SimpleDateFormat("yyyy-MM");
        SimpleDateFormat sdfymd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        //计算总供水用户数量
        waterCruxIndexVo.setSupplyWaterUsers(customDisplayMapper.getTableUserListNum());

//        //计算总制水量
//        Map<String,Object> totalIndexMap = customDisplayMapper.getStatisticalGroupYear(new WisdomDisplayDto());
//        if(totalIndexMap != null && totalIndexMap.get("waterSupply") != null){
//            waterCruxIndexVo.setTotalWaterSupply(new BigDecimal(String.valueOf(totalIndexMap.get("waterSupply"))).divide(BigDecimal.valueOf(10000),2, RoundingMode.HALF_UP));
//        }else {
//            waterCruxIndexVo.setTotalWaterSupply(BigDecimal.ZERO);
//        }

        //计算管网总长度
        List<PipeMaterialStatisticalVo> pipeMaterialStatisticalVos = warnService.getPipeMaterialStatistical();
        BigDecimal pipeLength = BigDecimal.ZERO;
        for(PipeMaterialStatisticalVo one : pipeMaterialStatisticalVos){
            if(one.getNum() != null){
                pipeLength = pipeLength.add(one.getNum());
            }
        }
        pipeLength = pipeLength.setScale(2, RoundingMode.HALF_UP);
        waterCruxIndexVo.setPipeLength(pipeLength);

        //计算设计供水能力
        waterCruxIndexVo.setDesignProcessingCapacity(customDisplayMapper.getDesignProcessCapacity(null).divide(BigDecimal.valueOf(10000),2,RoundingMode.HALF_UP));
//        waterCruxIndexVo.setOtDesignProcessingCapacity(customDisplayMapper.getDesignProcessCapacity("一二期").divide(BigDecimal.valueOf(10000),2,RoundingMode.HALF_UP));
//        waterCruxIndexVo.setTDesignProcessingCapacity(customDisplayMapper.getDesignProcessCapacity("三期").divide(BigDecimal.valueOf(10000),2,RoundingMode.HALF_UP));

//        //计算今年供水量
//        Calendar cal = Calendar.getInstance();
//        SimpleDateFormat sdfYear = new SimpleDateFormat("yyyy");
//        String startDateYW = sdfYear.format(cal.getTime()) + "-01";
//        String endDateYW = sdfMonth.format(cal.getTime());
//        WisdomDisplayDto wi = new WisdomDisplayDto();
//        wi.setStartMonth(startDateYW);
//        wi.setEndMonth(endDateYW);
//        Map<String, Object> yy = customDisplayMapper.getStatisticalGroupYear(wi);
//        if(yy != null && yy.get("waterSupply") != null){
//            waterCruxIndexVo.setYearSupplyWater(new BigDecimal(String.valueOf(yy.get("waterSupply"))).divide(BigDecimal.valueOf(10000),2,RoundingMode.HALF_UP));
//        }else {
//            waterCruxIndexVo.setYearSupplyWater(BigDecimal.ZERO);
//        }
//        if(yy != null && yy.get("userWater") != null){
//            waterCruxIndexVo.setYearUserWater(new BigDecimal(String.valueOf(yy.get("userWater"))).divide(BigDecimal.valueOf(10000),2,RoundingMode.HALF_UP));
//        }else {
//            waterCruxIndexVo.setYearUserWater(BigDecimal.ZERO);
//        }
//
//        //计算上月供水量
//        Map<String,Object> lastMonthIndex = customDisplayMapper.getLeakOverview();
//        if(lastMonthIndex != null){
//            waterCruxIndexVo.setLastMonthSupplyWater(new BigDecimal(String.valueOf(lastMonthIndex.get("waterSupply"))).divide(BigDecimal.valueOf(10000),2,RoundingMode.HALF_UP));
//        }else {
//            waterCruxIndexVo.setLastMonthSupplyWater(BigDecimal.ZERO);
//        }
//        //计算上月售水量
//        if(lastMonthIndex != null){
//            waterCruxIndexVo.setLastMonthUserWater(new BigDecimal(String.valueOf(lastMonthIndex.get("billingWaterVolume"))).divide(BigDecimal.valueOf(10000),2,RoundingMode.HALF_UP));
//        }else {
//            waterCruxIndexVo.setLastMonthUserWater(BigDecimal.ZERO);
//        }
//
        //计算昨日供水量
//        waterCruxIndexVo.setYesterdaySupplyWater(customDisplayMapper.getYesterdaySupplyWater(codes, null).divide(BigDecimal.valueOf(10000),2,RoundingMode.HALF_UP));

//        //计算昨日取水量
//        waterCruxIndexVo.setYesterdayUserWater(customDisplayMapper.getYesterdayUserWater(codes).divide(BigDecimal.valueOf(10000),2,RoundingMode.HALF_UP));
//
//        WisdomDisplayDto wisLastMonth = new WisdomDisplayDto();
//        Calendar cc = Calendar.getInstance();
//        cc.add(Calendar.MONTH, -1);
//        wisLastMonth.setCensusMonth(sdfMonth.format(cc.getTime()));
//        //计算同比增长
//        List<Map<String, Object>> lastMonthDmaIndex = this.getDmaStatisticalMonth(wisLastMonth);
//        for(Map<String, Object> one : lastMonthDmaIndex){
//            //计算供水量同比增长率
//            if(one.get("yearOnYearMarginRate") != null){
//                waterCruxIndexVo.setYearOnYearRateWaterSupply(Float.parseFloat(String.valueOf(one.get("yearOnYearMarginRate"))));
//            }
//            //计算供水量同比增长值
//            if(one.get("yearOnYearMarginValueWaterSupply") != null){
//                waterCruxIndexVo.setYearOnYearValueWaterSupply(new BigDecimal(String.valueOf(one.get("yearOnYearMarginValueWaterSupply"))).divide(BigDecimal.valueOf(10000),2,RoundingMode.HALF_UP));
//            }
//            //计算售水量同比增长率
//            if(one.get("yearOnYearMarginRateUserWater") != null){
//                waterCruxIndexVo.setYearOnYearRateUserWater(Float.parseFloat(String.valueOf(one.get("yearOnYearMarginRateUserWater"))));
//            }
//            //计算售水量同比增长值
//            if(one.get("yearOnYearMarginValueUserWater") != null){
//                waterCruxIndexVo.setYearOnYearValueUserWater(new BigDecimal(String.valueOf(one.get("yearOnYearMarginValueUserWater"))).divide(BigDecimal.valueOf(10000),2,RoundingMode.HALF_UP));
//            }
//        }
//        if(waterCruxIndexVo.getYearOnYearRateWaterSupply() == null){
//            waterCruxIndexVo.setYearOnYearRateWaterSupply(0.00f);
//        }
//        if(waterCruxIndexVo.getYearOnYearValueWaterSupply() == null){
//            waterCruxIndexVo.setYearOnYearValueWaterSupply(BigDecimal.ZERO);
//        }
//        if(waterCruxIndexVo.getYearOnYearRateUserWater() == null){
//            waterCruxIndexVo.setYearOnYearRateUserWater(0.00f);
//        }
//        if(waterCruxIndexVo.getYearOnYearValueUserWater() == null){
//            waterCruxIndexVo.setYearOnYearValueUserWater(BigDecimal.ZERO);
//        }
//
//        //计算电耗同比增长
//        wisLastMonth.setType("1");
//        wisLastMonth.setCensusYear(sdfYear.format(new Date()));
//        List<Map<String, Object>> powerLossCensusList = this.viewLossCensus(wisLastMonth);
//        for(Map<String, Object> lossCensusOne : powerLossCensusList){
//            if(lossCensusOne.get("yearOnYearMarginRate") != null){
//                waterCruxIndexVo.setYearOnYearRatePower(Float.parseFloat(String.valueOf(lossCensusOne.get("yearOnYearMarginRate"))));
//            }
//            if(lossCensusOne.get("yearOnYearMarginValue") != null){
//                waterCruxIndexVo.setYearOnYearValuePower(new BigDecimal(String.valueOf(lossCensusOne.get("yearOnYearMarginValue"))));
//            }
//        }
//        if(waterCruxIndexVo.getYearOnYearRatePower() == null){
//            waterCruxIndexVo.setYearOnYearRatePower(0.00f);
//        }
//        if(waterCruxIndexVo.getYearOnYearValuePower() == null){
//            waterCruxIndexVo.setYearOnYearValuePower(BigDecimal.ZERO);
//        }
//
//        //计算药耗同比增长
//        wisLastMonth.setType("2");
//        wisLastMonth.setCensusYear(sdfYear.format(new Date()));
//        List<Map<String, Object>> drugLossCensusList = this.viewLossCensus(wisLastMonth);
//        for(Map<String, Object> lossCensusOne : drugLossCensusList){
//            if(lossCensusOne.get("yearOnYearMarginRate") != null){
//                waterCruxIndexVo.setYearOnYearRateDrug(Float.parseFloat(String.valueOf(lossCensusOne.get("yearOnYearMarginRate"))));
//            }
//            if(lossCensusOne.get("yearOnYearMarginValue") != null){
//                waterCruxIndexVo.setYearOnYearValueDrug(new BigDecimal(String.valueOf(lossCensusOne.get("yearOnYearMarginValue"))));
//            }
//        }
//        if(waterCruxIndexVo.getYearOnYearRateDrug() == null){
//            waterCruxIndexVo.setYearOnYearRateDrug(0.00f);
//        }
//        if(waterCruxIndexVo.getYearOnYearValueDrug() == null){
//            waterCruxIndexVo.setYearOnYearValueDrug(BigDecimal.ZERO);
//        }
//
//        //计算安全生产天数
//        List<TfWaterInfo> waterInfoList = customDisplayMapper.getWaterInfo();
//        if(waterInfoList.size() != 0){
//            Date blowInTime = waterInfoList.get(0).getBlowInTime();
//            Date nowTime = new Date();
//            if(blowInTime != null){
//                waterCruxIndexVo.setSafeMakeDays(differentDays(blowInTime, nowTime));
//            }
//        }
//
//        //计算视频监控数量
//        waterCruxIndexVo.setCameraMonitorAmount(customDisplayMapper.getCameraAmount());

        //计算制水厂数量
        waterCruxIndexVo.setWaterPlantAmount(customDisplayMapper.getWaterAmount("1"));

//        //计算加压站数量
//        waterCruxIndexVo.setPressStationAmount(customDisplayMapper.getPipeDevice(null,"5",null));
//
//        //计算远控阀门数量
//        waterCruxIndexVo.setRemoteControlValveNum(customDisplayMapper.getPipeDevice("2","8",null));
//
//        //计算管网水质监测点
//        waterCruxIndexVo.setPipeWaterMonitorAmount(customDisplayMapper.getPipeDevice("2","6",null));
//
//        //计算管网压力监测点
//        waterCruxIndexVo.setPipePressMonitorAmount(customDisplayMapper.getPipeDevice("2","1",null));
//
//        //计算管网流量监测点
//        waterCruxIndexVo.setFlowMonitorAmount(customDisplayMapper.getPipeDevice("2","3",null));
//
//        //计算噪音检测仪
//        waterCruxIndexVo.setNoiseCheckAmount(customDisplayMapper.getNoiseCheckAmount());
//
//        //计算设备完好率
//        int runningDevice = customDisplayMapper.getPipeDevice(null,null,"1");
//        int freeDevice = customDisplayMapper.getPipeDevice(null,null,"2");
//        int allDevice = customDisplayMapper.getPipeDevice(null,null,null);
//        int sumGoodDevice = runningDevice + freeDevice;
//        if(allDevice != 0 && sumGoodDevice != 0){
//            float deviceIntactRate = new BigDecimal((float)sumGoodDevice / allDevice).multiply(BigDecimal.valueOf(100)).setScale(2, RoundingMode.HALF_UP).floatValue();
//            waterCruxIndexVo.setDeviceIntactRate(deviceIntactRate);
//        }else {
//            waterCruxIndexVo.setDeviceIntactRate(0.00f);
//        }

        //计算近一年的漏损率和产销差和近三年的漏损率
        Calendar c = Calendar.getInstance();
        c.add(Calendar.MONTH, -1);
        //上个月时间
        String endDate = sdfMonth.format(c.getTime());
        Date endDateFormat = null;
        try {
            endDateFormat = sdfymd.parse(sdfymd.format(c.getTime()));
        } catch (ParseException e) {
            e.printStackTrace();
        }

        c.add(Calendar.YEAR, -1);
        c.add(Calendar.MONTH, +1);
        //去年这个月时间
        String startDate = sdfMonth.format(c.getTime());
        Date startDateFormat = null;
        try {
            startDateFormat = sdfymd.parse(sdfymd.format(c.getTime()));
        } catch (ParseException e) {
            e.printStackTrace();
        }

        c.add(Calendar.YEAR, -2);
        //三年前这个月时间
        String startDateThree = sdfMonth.format(c.getTime());
        List<Map<String,Double>> nearYearStaticalList = customDisplayMapper.getNearYearStatistical(startDate, endDate);
        if(nearYearStaticalList.size() == 0){
            waterCruxIndexVo.setNearYearLeakRate(0.00);
            waterCruxIndexVo.setNearYearNrw(0.00);
        }else {
            Map<String,Double> leakNrwAvg = getLeakNrwAvg(nearYearStaticalList);
            waterCruxIndexVo.setNearYearLeakRate(leakNrwAvg.get("leakageRate"));
            waterCruxIndexVo.setNearYearNrw(leakNrwAvg.get("poorProductionRate"));
        }
        List<Map<String,Double>> nearThreeYearStaticalList = customDisplayMapper.getNearYearStatistical(startDateThree, endDate);
        if(nearThreeYearStaticalList.size() == 0){
            waterCruxIndexVo.setNearThreeYearLeakRate(0.00);
        }else {
            Map<String,Double> leakNrwAvg = getLeakNrwAvg(nearThreeYearStaticalList);
            waterCruxIndexVo.setNearThreeYearLeakRate(leakNrwAvg.get("leakageRate"));
        }

//        //计算水质合格率
//        int qualityWaterCount = customDisplayMapper.getWaterQualityDevice("0");
//        int AllWaterCount = customDisplayMapper.getWaterQualityDevice(null);
//        if(qualityWaterCount != 0 && AllWaterCount != 0){
//            float deviceIntactRate = new BigDecimal((float)qualityWaterCount / AllWaterCount).multiply(BigDecimal.valueOf(100)).setScale(2, RoundingMode.HALF_UP).floatValue();
//            waterCruxIndexVo.setWaterQualityRate(deviceIntactRate);
//        }else {
//            waterCruxIndexVo.setWaterQualityRate(0.00f);
//        }
//
//        //计算管网总表数量
//        waterCruxIndexVo.setPipeTableAmount(customDisplayMapper.getPipeTableAmount());
//
//        //计算ILI漏损指数
//        if(wisdomDisplayDto.getStartDate() == null && wisdomDisplayDto.getEndDate() == null){
//            Calendar c1 = Calendar.getInstance();
//            c1.add(Calendar.MONTH, -1);
//            wisdomDisplayDto.setEndMonth(sdfMonth.format(c1.getTime()));
//
//            c1.add(Calendar.YEAR, -1);
//            c1.add(Calendar.MONTH, +1);
//            //去年这个月时间
//            wisdomDisplayDto.setStartMonth(sdfMonth.format(c1.getTime()));
//        }
//        Map<String, Object> statisticalMap = customDisplayMapper.getStatisticalGroupYear(wisdomDisplayDto);
//        if(statisticalMap != null && statisticalMap.get("lossWaterVolume") != null && statisticalMap.get("outflowWaterVolume") != null){
//            double outflowWaterVolume = Double.parseDouble(String.valueOf(statisticalMap.get("outflowWaterVolume")));
//            double lossWaterVolume = Double.parseDouble(String.valueOf(statisticalMap.get("lossWaterVolume")));
//            if(outflowWaterVolume != 0 && lossWaterVolume != 0){
//                BigDecimal b1 = new BigDecimal(Double.toString(lossWaterVolume));
//                BigDecimal b2 = new BigDecimal(Double.toString(outflowWaterVolume));
//                BigDecimal ILILeakageIndex = b2.divide(b1, 2, RoundingMode.HALF_UP);
//                waterCruxIndexVo.setILILeakageIndex(ILILeakageIndex);
//            }
//        }
//        if(waterCruxIndexVo.getILILeakageIndex() == null){
//            waterCruxIndexVo.setILILeakageIndex(BigDecimal.ZERO);
//        }
//
//        //计算巡检相关数据
//        WisdomDisplayDto wis = new WisdomDisplayDto();
//        //计算巡检总人数
//        waterCruxIndexVo.setInspectPersonNum(customDisplayMapper.getInspectPersonNum());
//        //计算当月统计数据
//        wis.setCensusMonth(sdfMonth.format(new Date()));
//        Map<String, Object> monthInspectData = customDisplayMapper.viewInspectCensus(wis);
//        if(monthInspectData != null && monthInspectData.get("orderNum") != null){
//            waterCruxIndexVo.setCmOrderNum(Integer.parseInt(String.valueOf(monthInspectData.get("orderNum"))));
//            if(monthInspectData.get("completeOrderNum") != null){
//                BigDecimal completeOrderNum = new BigDecimal(String.valueOf(monthInspectData.get("completeOrderNum")));
//                BigDecimal orderNum = new BigDecimal(String.valueOf(monthInspectData.get("orderNum")));
//                if(!orderNum.equals(BigDecimal.ZERO) && !completeOrderNum.equals(BigDecimal.ZERO)){
//                    waterCruxIndexVo.setCmCompleteOrderRate(Float.parseFloat(String.valueOf(completeOrderNum.divide(orderNum,4, RoundingMode.HALF_UP).multiply(BigDecimal.valueOf(100)))));
//                }else {
//                    waterCruxIndexVo.setCmCompleteOrderRate(0.00f);
//                }
//            }
//        }
//        if(monthInspectData != null && monthInspectData.get("handleOrderNum") != null){
//            waterCruxIndexVo.setCmHandleOrderNum(Integer.parseInt(String.valueOf(monthInspectData.get("handleOrderNum"))));
//        }
//        Long monthAllOrderData = customDisplayMapper.viewOrderCensus(wis);
//        if(monthAllOrderData != null && monthAllOrderData != 0L) {
//            //获得当月工单总数
//            waterCruxIndexVo.setCmOrderNum(monthAllOrderData);
//            //设置为归档
//            wis.setProcessNode(45L);
//            Long monthCompleteOrderData = customDisplayMapper.viewOrderCensus(wis);
//            if(monthCompleteOrderData != null && monthCompleteOrderData != 0L) {
//                //获得当月正在处理工单数
//                waterCruxIndexVo.setCmHandleOrderNum(monthAllOrderData - monthCompleteOrderData);
//                Float completeOrderRate = BigDecimal.valueOf(monthCompleteOrderData).divide(BigDecimal.valueOf(monthAllOrderData),4, RoundingMode.HALF_UP).multiply(BigDecimal.valueOf(100)).floatValue();
//                //获得当月工单完成率
//                waterCruxIndexVo.setCmCompleteOrderRate(completeOrderRate);
//            }else {
//                waterCruxIndexVo.setCmHandleOrderNum(monthAllOrderData);
//                waterCruxIndexVo.setCmCompleteOrderRate(00.00f);
//            }
//        }else {
//            waterCruxIndexVo.setCmOrderNum(0L);
//            waterCruxIndexVo.setCmHandleOrderNum(0L);
//            waterCruxIndexVo.setCmCompleteOrderRate(00.00f);
//        }
//        //计算近十二个月统计数据
//        wis.setStartMonth(startDate);
//        wis.setEndMonth(endDate);
//        wis.setCensusMonth(null);
//        wis.setProcessNode(null);
//        Map<String, Object> yearInspectData = customDisplayMapper.viewInspectCensus(wis);
//        if(yearInspectData != null && yearInspectData.get("orderNum") != null){
//            waterCruxIndexVo.setYearOrderNum(Integer.parseInt(String.valueOf(yearInspectData.get("orderNum"))));
//            if(yearInspectData.get("completeOrderNum") != null){
//                BigDecimal completeOrderNum = new BigDecimal(String.valueOf(yearInspectData.get("completeOrderNum")));
//                BigDecimal orderNum = new BigDecimal(String.valueOf(yearInspectData.get("orderNum")));
//                if(!orderNum.equals(BigDecimal.ZERO) && !completeOrderNum.equals(BigDecimal.ZERO)){
//                    waterCruxIndexVo.setYearCompleteOrderRate(Float.parseFloat(String.valueOf(completeOrderNum.divide(orderNum,4, RoundingMode.HALF_UP).multiply(BigDecimal.valueOf(100)))));
//                }else {
//                    waterCruxIndexVo.setYearCompleteOrderRate(0.00f);
//                }
//            }
//        }
//        if(yearInspectData != null && yearInspectData.get("inspectNum") != null){
//            waterCruxIndexVo.setYearInspectNum(Integer.parseInt(String.valueOf(yearInspectData.get("inspectNum"))));
//        }
//        if(yearInspectData != null && yearInspectData.get("planTotalDistance") != null){
//            waterCruxIndexVo.setYearInspectDistance(new BigDecimal(String.valueOf(yearInspectData.get("planTotalDistance"))));
//        }
//        if(yearInspectData != null && yearInspectData.get("findTroubleNum") != null){
//            waterCruxIndexVo.setYearFindTroubleNum(Integer.parseInt(String.valueOf(yearInspectData.get("findTroubleNum"))));
//        }
//        Long yearAllOrderData = customDisplayMapper.viewOrderCensus(wis);
//        if(yearAllOrderData != null) {
//            //获得近一年工单总数
//            waterCruxIndexVo.setYearOrderNum(yearAllOrderData);
//            //设置为归档
//            wis.setProcessNode(45L);
//            Long yearCompleteOrderData = customDisplayMapper.viewOrderCensus(wis);
//            if(yearCompleteOrderData != null) {
//                Float completeOrderRate = BigDecimal.valueOf(yearCompleteOrderData).divide(BigDecimal.valueOf(yearAllOrderData),4, RoundingMode.HALF_UP).multiply(BigDecimal.valueOf(100)).floatValue();
//                //获得近一年工单完成率
//                waterCruxIndexVo.setYearCompleteOrderRate(completeOrderRate);
//            }else {
//                waterCruxIndexVo.setYearCompleteOrderRate(00.00f);
//            }
//        }else {
//            waterCruxIndexVo.setYearOrderNum(0L);
//            waterCruxIndexVo.setYearCompleteOrderRate(00.00f);
//        }
//        Long yearInspectNum = customDisplayMapper.viewInspectPlanCensus(wis);
//        if(yearInspectNum != null) {
//            //获得近一年巡检次数
//            waterCruxIndexVo.setYearInspectNum(yearInspectNum);
//        }else {
//            waterCruxIndexVo.setYearInspectNum(0L);
//        }
//        Long yearTroubleNum = customDisplayMapper.viewTroubleCensus(wis);
//        if(yearTroubleNum != null && yearTroubleNum != 0) {
//            //获得近一年发现隐患次数
//            waterCruxIndexVo.setYearFindTroubleNum(yearTroubleNum);
//            wis.setTroubleState("2");
//            Long yearHandleTroubleNum = customDisplayMapper.viewTroubleCensus(wis);
//            if(yearHandleTroubleNum != null && yearHandleTroubleNum != 0L) {
//                waterCruxIndexVo.setYearHandleTroubleNum(yearHandleTroubleNum);
//                waterCruxIndexVo.setYearNotHandleTroubleNum(yearTroubleNum - yearHandleTroubleNum);
//            }else {
//                waterCruxIndexVo.setYearHandleTroubleNum(0L);
//                waterCruxIndexVo.setYearNotHandleTroubleNum(yearTroubleNum);
//            }
//        }else {
//            waterCruxIndexVo.setYearFindTroubleNum(0L);
//        }
        // 计算近一年巡检公里数
        // 根据时间范围 查询对应巡检用户的 巡检里程
//        EsQueryDto pram = new EsQueryDto();
//        pram.setStartDate(startDateFormat);
//        pram.setEndDate(endDateFormat);
//        List<Long> inspectPersonList = customDisplayMapper.getInspectPersonList();
//        BigDecimal yearInspectDistance = BigDecimal.ZERO;
//        if(inspectPersonList != null && inspectPersonList.size() != 0){
//            StringBuilder inspectPersonText = new StringBuilder();
//            inspectPersonList.forEach(inspectPersonText::append);
//            pram.setUserIds(inspectPersonText.toString());
//            List<GpsUpload> all = esClient.getAll(pram).getResult();
//            if(all != null && all.size() != 0){
//                // 用户分组
//                Map<Long, List<GpsUpload>> collect = all.stream().collect(Collectors.groupingBy(GpsUpload::getUserId));
//                collect.forEach((k, v) -> {
//                    // 计算个人巡检里程
//                    BigDecimal totalMileage = v.stream().map(GpsUpload::getDistance).reduce(BigDecimal.ZERO, BigDecimal::add).divide(BigDecimal.valueOf(1000), 4, RoundingMode.HALF_UP);
//                    yearInspectDistance.add(totalMileage);
//                });
//            }
//        }
//        waterCruxIndexVo.setYearInspectDistance(yearInspectDistance);

//        Calendar c2 = Calendar.getInstance();
//
//        WisdomDisplayDto wisHotLine = new WisdomDisplayDto();
//        wisHotLine.setCensusYear(sdfYear.format(c2.getTime()));
//        //计算今年热线来电数量
//        wisHotLine.setCallType(1);
//        waterCruxIndexVo.setThisYearHotLineInNum(pltCalllist1000Mapper.viewNewHotLineNum(wisHotLine));
//        //计算今年热线去电数量
//        wisHotLine.setCallType(2);
//        waterCruxIndexVo.setThisYearHotLineOutNum(pltCalllist1000Mapper.viewNewHotLineNum(wisHotLine));
//        //计算今年热线好评率
//        waterCruxIndexVo.setHotLinePraiseRate(getHotLineRate(sdfYear.format(c2.getTime()),"1"));
//        //计算上一年热线来电数量
//        c2.add(Calendar.YEAR, -1);
//        wisHotLine.setCensusYear(sdfYear.format(c2.getTime()));
//        wisHotLine.setCallType(1);
//        waterCruxIndexVo.setLastYearHotLineInNum(pltCalllist1000Mapper.viewNewHotLineNum(wisHotLine));
//        //计算上一年热线去电数量
//        wisHotLine.setCallType(2);
//        waterCruxIndexVo.setLastYearHotLineOutNum(pltCalllist1000Mapper.viewNewHotLineNum(wisHotLine));
//        //计算上一年热线好评率
//        waterCruxIndexVo.setLastYearHotLinePraiseRate(getHotLineRate(sdfYear.format(c2.getTime()),"1"));

        return waterCruxIndexVo;
    }

    @Override
    public Page<Map<String, Object>> reportFormCensus(Page page, WisdomDisplayDto wisdomDisplayDto) {
        String censusDateType = wisdomDisplayDto.getCensusDateType();
        String deviceType = wisdomDisplayDto.getDeviceType();
        if(org.apache.commons.lang3.StringUtils.isBlank(censusDateType)){
            throw new ToflyDeniedException("时间统计类型不能为空");
        }
//        if(StringUtils.isBlank(deviceType)){
//            throw new ToflyDeniedException("设备类型不能为空");
//        }
        switch (censusDateType) {
            case "1":
                return customDisplayMapper.reportFormCensusY(page, wisdomDisplayDto);
            case "2":
                return customDisplayMapper.reportFormCensusM(page, wisdomDisplayDto);
            case "3":
                return customDisplayMapper.reportFormCensusD(page, wisdomDisplayDto);
            default:
                throw new ToflyDeniedException("时间统计类型传入数据有误");
        }
    }

    @Override
    public List<Map<String, Object>> getDmaStatisticalList(String startDate, String endDate, List<Long> dmaIdList, Integer statisticsType) {
        return customDisplayMapper.getDmaStatisticalList(startDate, endDate, dmaIdList, statisticsType);
    }



    /* ***************************************************自定义方法******************************************** */


    /**
     * 判断点是否在多边形内
     *
     * @param point 检测点
     * @param pts   多边形的顶点
     * @return 点在多边形内返回true, 否则返回false
     */
    public static boolean IsPtInPoly(Point2D.Double point, List<Point2D.Double> pts) {
        int N = pts.size();
        boolean boundOrVertex = true; //如果点位于多边形的顶点或边上，也算做点在多边形内，直接返回true
        int intersectCount = 0;
        double precision = 2e-10; //浮点类型计算时候与0比较时候的容差
        Point2D.Double p1, p2;
        Point2D.Double p = point; //当前点

        p1 = pts.get(0);
        for (int i = 1; i <= N; ++i) {
            if (p.equals(p1)) {
                return boundOrVertex;
            }
            p2 = pts.get(i % N);
            if (p.x < Math.min(p1.x, p2.x) || p.x > Math.max(p1.x, p2.x)) {
                p1 = p2;
                continue;
            }

            if (p.x > Math.min(p1.x, p2.x) && p.x < Math.max(p1.x, p2.x)) {
                if (p.y <= Math.max(p1.y, p2.y)) {
                    if (p1.x == p2.x && p.y >= Math.min(p1.y, p2.y)) {
                        return boundOrVertex;
                    }

                    if (p1.y == p2.y) {
                        if (p1.y == p.y) {
                            return boundOrVertex;
                        } else {
                            ++intersectCount;
                        }
                    } else {
                        double xinters = (p.x - p1.x) * (p2.y - p1.y) / (p2.x - p1.x) + p1.y;
                        if (Math.abs(p.y - xinters) < precision) {
                            return boundOrVertex;
                        }

                        if (p.y < xinters) {
                            ++intersectCount;
                        }
                    }
                }
            } else {
                if (p.x == p2.x && p.y <= p2.y) {
                    Point2D.Double p3 = pts.get((i + 1) % N);
                    if (p.x >= Math.min(p1.x, p3.x) && p.x <= Math.max(p1.x, p3.x)) {
                        ++intersectCount;
                    } else {
                        intersectCount += 2;
                    }
                }
            }
            p1 = p2;
        }

        if (intersectCount % 2 == 0) {
            return false;
        } else {
            return true;
        }
    }

    public static Map<Object, List<Map<String, Object>>> groupByData(List<Map<String, Object>> list, String key) {
        Map<Object, List<Map<String, Object>>> result = null;
        if (list != null) {
            result = list
                    .stream().collect(Collectors.groupingBy(yl -> yl.get(key)));
        }
        return result;
    }

    private Map<Object, List<Object>> handleUnitMap(Map<String, List<Map<String, Object>>> map) {
        Map<Object, List<Object>> result = new HashMap<>();

        List<Map<String, Object>> pacOne = map.get("pacOne");
        List<Map<String, Object>> pamTwo = map.get("pamTwo");
        List<Map<String, Object>> gmsjTwo = map.get("gmsjTwo");
        List<Map<String, Object>> yl = map.get("yl");
        List<Map<String, Object>> pacTwo = map.get("pacTwo");

        if (pacOne != null && pacOne.size() > 0) {
            handleMap(result, pacOne, "time", "pacOne");
        }
        if (pamTwo != null && pamTwo.size() > 0) {
            handleMap(result, pamTwo, "time", "pam");
        }
        if (gmsjTwo != null && gmsjTwo.size() > 0) {
            handleMap(result, gmsjTwo, "time", "gmsj");
        }
        if (yl != null && yl.size() > 0) {
            handleMap(result, yl, "time", "yl");
        }
        if (pacTwo != null && pacTwo.size() > 0) {
            handleMap(result, pacTwo, "time", "pacTwo");
        }

        return result;
    }

    private void handleMap(Map<Object, List<Object>> result, List<Map<String, Object>> unit, String key, String name) {
        unit.forEach(m -> {
            m.put("name", name);
            if (result.containsKey(m.get(key))) {
                result.get(m.get(key)).add(m);
            } else {
                List<Object> list = new ArrayList<>();
                list.add(m);
                result.put(m.get(key), list);
            }
        });
    }

    /**
     * 获取漏损率和产销差平均值
     * @param nearYearStaticalList
     * @return
     */
    public Map<String,Double> getLeakNrwAvg(List<Map<String,Double>> nearYearStaticalList) {
        Map<String,Double> leakNrwAvgMap = new HashMap<>();
        double leakRate = 0.0;
        double poorProductionRate = 0.0;
        int leakRateCount = 0;
        int poorProductionRateCount = 0;
        for(Map<String,Double> one : nearYearStaticalList){
            if(one.get("leakageRate") != null){
                leakRate += Double.parseDouble(String.valueOf(one.get("leakageRate")));
                leakRateCount ++;
            }
            if(one.get("poorProductionRate") != null){
                poorProductionRate += Double.parseDouble(String.valueOf(one.get("poorProductionRate")));
                poorProductionRateCount ++;
            }
        }
        if(leakRateCount != 0){
            leakRate = new BigDecimal(leakRate / leakRateCount).setScale(2, RoundingMode.HALF_UP).doubleValue();
        }
        if(poorProductionRateCount != 0){
            poorProductionRate = new BigDecimal(poorProductionRate / poorProductionRateCount).setScale(2, RoundingMode.HALF_UP).doubleValue();
        }

        leakNrwAvgMap.put("leakageRate",leakRate);
        leakNrwAvgMap.put("poorProductionRate",poorProductionRate);
        return leakNrwAvgMap;
    }
}
