package com.nantian.cloud.dbcapp.service.impl;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nantian.cloud.dbcapp.entity.ConfigureDataCollect;
import com.nantian.cloud.dbcapp.entity.EnterpriseState;
import com.nantian.cloud.dbcapp.entity.SettlementDataConfig;
import com.nantian.cloud.dbcapp.mapper.jly.EnterpriseHaltMapper;
import com.nantian.cloud.dbcapp.mapper.record.ConfigureDataCollectMapper;
import com.nantian.cloud.dbcapp.mapper.record.EnergyMapper;
import com.nantian.cloud.dbcapp.mapper.record.EnterpriseMapper;
import com.nantian.cloud.dbcapp.mapper.record.TEnterpriseQuotaMapper;
import com.nantian.cloud.dbcapp.service.EnergyService;
import com.nantian.cloud.dbcapp.service.EnterpriseService;
import com.nantian.cloud.dbcapp.service.ISettlementDataConfigService;
import com.nantian.cloud.dbcapp.unit.DateUtil;
import com.nantian.cloud.dbcapp.vo.*;
import com.nantian.sc.cloud.common.core.util.R;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;


/**
 * <p>
 * 企业端 服务实现类
 * </p>
 *
 * @author zfw
 * @since 2020-08-05
 */
@Service("enterpriseService")
public class EnterpriseServiceImpl implements EnterpriseService {

    @Autowired
    private EnterpriseMapper enterpriseMapper;

    @Autowired
    private TEnterpriseQuotaMapper tEnterpriseQuotaMapper;

    @Autowired
    private ConfigureDataCollectMapper configureDataCollectMapper;

    @Autowired
    private EnergyService energyService;

    @Autowired
    private EnergyMapper energyMapper;

    @Autowired
    private EnterpriseHaltMapper haltMapper;

    @Autowired
    private ISettlementDataConfigService settlementDataConfigService;


    private static final ArrayList<String> coalEnergyList = new ArrayList<>(); //归为煤的能源品种
    private static final ArrayList<String> otherEnergyList = new ArrayList<>(); //归为其它燃料的能源品种
    private static final ArrayList<String> thermalEnergyList = new ArrayList<>(); //归为热力的能源品种
    static {
        Collections.addAll(coalEnergyList, "0100", "0101", "0102", "0103", "0104", "0105", "0600", "0700", "0800");
        Collections.addAll(otherEnergyList, "3900", "4000", "4200", "4300", "4500", "4600", "4700");
        Collections.addAll(thermalEnergyList, "3200", "4400", "4401", "4402", "4403", "4404");
    }

    @Override
    public Map<String,Object> getTotalZhnh(String enterpriseCode, String time) throws ParseException {
        Map<String,Object> resultMap = new HashMap<>();
        HashMap<String, String> needTime = getNeedTime(time);
        String startTime = needTime.get("开始时间");
        String endTime = needTime.get("结束时间");
        Float sum = 0.0f;
        Map<String, String> jzTime = timeStr(enterpriseCode);
        String timeStr = jzTime.get("截止日期");
        String timeStr1 = jzTime.get("下一阶段的开始时间");
        //@Author: dengjian @DATE: 2024/1/22 15:03 @Description:修改查询不到数据，为空时报错
        if(StringUtils.isNotBlank(timeStr1)){
            if (startTime.compareTo(timeStr1) >= 0) { //时间截点大于等于开始时间则查询新平台能耗数据
                sum = enterpriseMapper.getTceTotal2020(enterpriseCode, startTime, endTime);
            } else if (endTime.compareTo(timeStr) <= 0) {//时间截点小于结束时间 则查询历史数据
                sum = enterpriseMapper.getTceTotal2019(enterpriseCode, startTime, endTime);
            }else {
                Float sum1 = 0f;
                Float sum2 = 0f;
                sum1 = enterpriseMapper.getTceTotal2020(enterpriseCode, timeStr1, endTime);
                sum2 = enterpriseMapper.getTceTotal2019(enterpriseCode, startTime, timeStr);
                sum = sum1 + sum2;
            }
        }else {
            Float sum1 = 0f;
            Float sum2 = 0f;
            sum1 = enterpriseMapper.getTceTotal2020(enterpriseCode, timeStr1, endTime);
            sum2 = enterpriseMapper.getTceTotal2019(enterpriseCode, startTime, timeStr);
            sum = sum1 + sum2;
        }
//        if (startTime.compareTo(timeStr1) >= 0) { //时间截点大于等于开始时间则查询新平台能耗数据
//            sum = enterpriseMapper.getTceTotal2020(enterpriseCode, startTime, endTime);
//        } else if (endTime.compareTo(timeStr) <= 0) {//时间截点小于结束时间 则查询历史数据
//            sum = enterpriseMapper.getTceTotal2019(enterpriseCode, startTime, endTime);
//        } else {
//            Float sum1 = 0f;
//            Float sum2 = 0f;
//            sum1 = enterpriseMapper.getTceTotal2020(enterpriseCode, timeStr1, endTime);
//            sum2 = enterpriseMapper.getTceTotal2019(enterpriseCode, startTime, timeStr);
//            sum = sum1 + sum2;
//        }
        //获取企业指定时间周期内的综合能耗异常数量
        Integer exTotal = energyMapper.getComprehensiveExTotal(enterpriseCode, startTime, endTime);
        resultMap.put("dataValue", sum);
        resultMap.put("isException", exTotal == 0 ? "false" : "true");
        //查询综合能耗

        return resultMap;
    }

    /**
     * @Description: 查询采集点
     * @Param: [enterpriseCode, time]
     * @return: java.lang.Integer
     * @Author: zfw
     * @Date: 2020/12/28
     * @Date: 13:56
     */

    @Override
    public Integer getCollection(String enterpriseCode, String time) {
        //截取时间
        String startTime = time.split("&")[0];
        String endTime = time.split("&")[1];
        startTime = startTime.substring(0, 7);
        endTime = endTime.substring(0, 7);
        Integer timeStr = Integer.valueOf(startTime.substring(0, 4));
        Integer number = 0;
        if (timeStr >= 2020) {
            //2020
            number = enterpriseMapper.getCollection2020(enterpriseCode);
        } else {
            //首先查询enterpriseCode 对应的entId
            Integer entID = getEntIdByenterpriseCode(enterpriseCode);
            number = enterpriseMapper.getCollection(entID, time);
        }
        return number;
    }

    /**
     * @Description: 计量器具
     * @Param: [enterpriseCode, time]
     * @return: java.lang.Integer
     * @Author: zfw
     * @Date: 2020/12/28
     * @Date: 14:45
     */
    //
    @Override
    public Integer getInstrument(String enterpriseCode, String time) {
        //截取时间
        String startTime = time.split("&")[0];
        String endTime = time.split("&")[1];
        startTime = startTime.substring(0, 7);
        endTime = endTime.substring(0, 7);
        Integer timeStr = Integer.valueOf(startTime.substring(0, 4));
        Integer number = 0;
        if (timeStr >= 2020) {
            //2020
            number = enterpriseMapper.getInstrument2020(enterpriseCode);
        } else {
            Integer entID = getEntIdByenterpriseCode(enterpriseCode);
            number = enterpriseMapper.getInstrument(entID, time);
        }
        return number;
    }

    /**
     * @Description: 能源消费结构
     * @Param: [enterpriseCode, time]
     * @return: com.alibaba.fastjson.JSONArray
     * @Author: zfw
     * @Date: 2020/12/28
     * @Date: 14:49
     */
    @Override
    public JSONArray getConsumption(String enterpriseCode, String time) throws ParseException {
        HashMap<String, String> needTime = getNeedTime(time);
        String startTime = needTime.get("开始时间");
        String endTime = needTime.get("结束时间");
        Map<String, String> jzTime = timeStr(enterpriseCode);
        String timeStr = jzTime.get("截止日期");
        String timeStr1 = jzTime.get("下一阶段的开始时间");
        //Integer timeStr=Integer.valueOf(startTime.substring(0,4));
        Integer entId = getEntIdByenterpriseCode(enterpriseCode);
        JSONArray jsonArray = new JSONArray();
        float totalZhnh = (float)getTotalZhnh(enterpriseCode, time).get("dataValue");
        HashMap<String, Double> stringDoubleHashMap = new HashMap<>();
        DecimalFormat df = new DecimalFormat(".0000"); //保留4位小数
        if (startTime.compareTo(timeStr1) >= 0) { //新平台数据
            Double sum = getConsumption2020(enterpriseCode, endTime, startTime, stringDoubleHashMap, df);
        } else if (endTime.compareTo(timeStr) <= 0) { //历史数据
            getConsumption2019(startTime, endTime, entId, jsonArray, stringDoubleHashMap, df);
        } else {
            //2020年的数据
            Double sum = getConsumption2020(enterpriseCode, endTime, timeStr1, stringDoubleHashMap, df);
            // 合并截止日期以前的数据========================================
            /*List<KeyValueVO> listValue = enterpriseMapper.selectEnergyValues2019(entId, startTime, timeStr);
            for (KeyValueVO a : listValue) {
                if (stringDoubleHashMap.containsKey(a.getKey1())) {
                    Double aDouble = stringDoubleHashMap.get(a.getKey1());
                    double tmpNum = (aDouble == null ? 0.0d : aDouble) + Double.valueOf(a.getValue());
                    stringDoubleHashMap.put(a.getKey1(), Double.parseDouble(df.format(tmpNum)));
                } else if (a.getKey1().endsWith("煤")) { //合并煤
                    double tmpNum = sum + Double.valueOf(a.getValue());
                    stringDoubleHashMap.put("煤", Double.parseDouble(df.format(tmpNum)));
                } else if (a.getKey1().contains("电")) { //合并电  老系统有的存的是电 有的是电力
                    Double aDouble = stringDoubleHashMap.get("电力");
                    double tmpNum = (aDouble == null ? 0.0d : aDouble) + Double.valueOf(a.getValue());
                    stringDoubleHashMap.put("电力", Double.parseDouble(df.format(tmpNum)));
                } else if (!a.getKey1().endsWith("水")) {
                    stringDoubleHashMap.put(a.getKey1(), Double.parseDouble(df.format(a.getValue())));
                }
            }*/
            HashMap<String, Double> newMap = new HashMap<>();
            getConsumption2019(startTime, timeStr, entId, jsonArray, newMap, df);
            for (Map.Entry<String, Double> entry : newMap.entrySet()) {
                String entryKey = entry.getKey();
                Double entryValue = entry.getValue();
                if (stringDoubleHashMap.containsKey(entryKey)) {
                    Double aDouble = stringDoubleHashMap.get(entryKey);
                    double tmpNum = (aDouble == null ? 0.0d : aDouble) + entryValue;
                    stringDoubleHashMap.put(entryKey, Double.parseDouble(df.format(tmpNum)));
                } else if (entryKey.endsWith("煤")) { //合并煤
                    double tmpNum = sum + entryValue;
                    stringDoubleHashMap.put("煤", Double.parseDouble(df.format(tmpNum)));
                } else if (entryKey.contains("电")) { //合并电  老系统有的存的是电 有的是电力
                    Double aDouble = stringDoubleHashMap.get("电力");
                    double tmpNum = (aDouble == null ? 0.0d : aDouble) + entryValue;
                    stringDoubleHashMap.put("电力", Double.parseDouble(df.format(tmpNum)));
                } else if (!entryKey.endsWith("水")) {
                    stringDoubleHashMap.put(entryKey, Double.parseDouble(df.format(entryValue)));
                }
            }
        }
        //合并返回前端
        for (String data : stringDoubleHashMap.keySet()) {
            Double aDouble = stringDoubleHashMap.get(data);
            JSONObject jo = new JSONObject();
            jo.put("name", data);
            jo.put("value", aDouble);
            jsonArray.add(jo);
        }
        jsonArray.sort(Comparator.comparing(obj -> ((JSONObject) obj).getDouble("value")).reversed());
        return jsonArray;
    }

    //查询企业历史能耗数据
    private void getConsumption2019(String startTime, String endTime, Integer entId, JSONArray jsonArray, HashMap<String, Double> stringDoubleHashMap, DecimalFormat df) {
        double num = 0.0d, num1 = 0.0d, num2 = 0.0d, num3 = 0.0d, num4 = 0.0d, num5 = 0.0d, num6 = 0.0d, num7 = 0.0d, num8 = 0.0d;
        List<KeyValueVO> listValue = enterpriseMapper.selectEnergyValues2019(entId, startTime, endTime);
        for (int i = 0; i < listValue.size(); i++) {
            Float value = listValue.get(i).getValue();
            String energyName = listValue.get(i).getKey1();
            if (energyName.contains("煤") && !energyName.contains("煤气")) { //合并煤
                num += value;
            }else if (energyName.contains("电")) { //合并电
                num1 += value;
            }else if (energyName.contains("焦")) { //合并焦
                num2 += value;
            }else if (energyName.contains("天然气")) { //合并天然气
                num3 += value;
            }else if (energyName.contains("煤气")) { //合并煤气
                num4 += value;
            }else if (energyName.contains("蔗渣")) { //合并蔗渣
                num5 += value;
            }/*else if (energyName.contains("油")) { //合并石油制品
                num6 += value;
            }*/else if (energyName.contains("生物质")) { //合并生物质
                num7 += value;
            }else if (energyName.contains("蒸汽")) { //合并蒸汽
                num8 += value;
            }else if (!energyName.endsWith("水")){
                stringDoubleHashMap.put(energyName, Double.parseDouble(df.format(value)));
            }
        }
        if (num != 0) {
            stringDoubleHashMap.put("煤", Double.parseDouble(df.format(num)));
        }
        if (num1 != 0) {
            stringDoubleHashMap.put("电力", Double.parseDouble(df.format(num1)));
        }
        if (num2 != 0) {
            stringDoubleHashMap.put("焦", Double.parseDouble(df.format(num2)));
        }
        if (num3 != 0) {
            stringDoubleHashMap.put("天然气", Double.parseDouble(df.format(num3)));
        }
        if (num4 != 0) {
            stringDoubleHashMap.put("煤气", Double.parseDouble(df.format(num4)));
        }
        if (num5 != 0) {
            stringDoubleHashMap.put("蔗渣", Double.parseDouble(df.format(num5)));
        }
        /*if (num6 != 0) {
            stringDoubleHashMap.put("石油制品", Double.parseDouble(df.format(num6);
        }*/
        if (num7 != 0) {
            stringDoubleHashMap.put("生物质", Double.parseDouble(df.format(num7)));
        }
        if (num8 != 0) {
            stringDoubleHashMap.put("蒸汽", Double.parseDouble(df.format(num8)));
        }
    }

    //查询企业自接入平台至今的能耗数据
    private Double getConsumption2020(String enterpriseCode, String endTime, String startTime, HashMap<String, Double> stringDoubleHashMap, DecimalFormat df ) {
        List<CoalVo> energyKindsList = enterpriseMapper.selectEnergyKinds(enterpriseCode, "00000000");
        // 合并煤、热力、其它燃料
        Double coalEnergy = 0.0, thermalEnergy = 0.0, otherEnergy = 0.0;
        for (CoalVo data : energyKindsList) {
            String energyCode = data.getMonth();
            String energyName = data.getValue();
            Double sum = enterpriseMapper.selectEnergyValues(enterpriseCode, energyCode, startTime, endTime);
            if (sum != null && sum != 0) {
                if(coalEnergyList.contains(energyCode)){ //煤
                    coalEnergy += sum;
                } else if(thermalEnergyList.contains(energyCode)){ //热力
                    thermalEnergy += sum;
                } else if(otherEnergyList.contains(energyCode)){ //其他燃料
                    otherEnergy += sum;
                } else {
                    stringDoubleHashMap.put(energyName, Double.parseDouble(df.format(sum)));
                }
            }
        }
        if (coalEnergy != 0) {
            stringDoubleHashMap.put("煤", Double.parseDouble(df.format(coalEnergy)));
        }
        if (thermalEnergy != 0) {
            stringDoubleHashMap.put("热力", Double.parseDouble(df.format(thermalEnergy)));
        }
        if (otherEnergy != 0) {
            stringDoubleHashMap.put("其它燃料", Double.parseDouble(df.format(otherEnergy)));
        }
        return coalEnergy;
    }

    /***
     * @Description: 查询企业电力
     * @Param: [enterpriseCode, time]
     * @return: java.util.Map<java.lang.String, java.lang.Object>
     * @Author: zfw
     * @Date: 2020/12/28
     * @Date: 17:12
     */
    @Override
    public Map<String, Object> getElectricity(String enterpriseCode, String time) {
        //截取时间
        String startTime = time.split("&")[0];
        String endTime = time.split("&")[1];
        startTime = startTime.substring(0, 7);
        endTime = endTime.substring(0, 7);
        Integer timeStr = Integer.valueOf(startTime.substring(0, 4));
        List<CoalVo> list;
        //查询
        if (timeStr < 2020) {
            list = enterpriseMapper.getElectricity(enterpriseCode, startTime, endTime);
        } else {
            list = enterpriseMapper.getElectricity2020(enterpriseCode, startTime, endTime);
        }
        Map<String, Object> map = new HashMap<>();

        List<String> monthList = new ArrayList<>();
        List<String> dataValueList = new ArrayList<>();

/*        BigDecimal num = new BigDecimal(String.valueOf(sum));
        DecimalFormat df = new DecimalFormat("0.00");
        String res = df.format(num);
        return list;*/

        for (int i = 0; i < list.size(); i++) {

            monthList.add(list.get(i).getMonth());
            dataValueList.add(list.get(i).getValue());
        }
        map.put("industry", monthList);
        map.put("dataValue", dataValueList);
        return map;

    }

    /**
     * @Description: 查询企业产品
     * @Param: [enterpriseCode]
     * @return: java.util.List<java.lang.String>
     * @Author: zfw
     * @Date: 2020/12/28
     * @Date: 17:12
     */
    @Override
    public JSONArray getProduct(String enterpriseCode) {
        //通过id,查询产品
        List<ProductNameAndIdVO> productList = enterpriseMapper.getProductName(enterpriseCode);
        JSONArray jsonArray = new JSONArray();
        for (int i = 0; i < productList.size(); i++) {
            JSONObject j0 = new JSONObject();
            j0.put("id", productList.get(i).getId());
            j0.put("name", productList.get(i).getName());
            jsonArray.add(j0);
        }
        return jsonArray;
    }


    @Override
    public List<String> getProductByEpc(String enterpriseCode, String time) throws ParseException {
        if(StringUtils.isBlank(time)){
            return enterpriseMapper.getProductNameByEpc(enterpriseCode);
        }else{
            List<String> productList = new ArrayList<>(), newProduct = new ArrayList<>(), oldProduct = new ArrayList<>();
            HashMap<String, String> needTime = getNeedTime(time);
            String startTime = needTime.get("开始时间");
            String endTime = needTime.get("结束时间");
            Map<String, String> jzTime = timeStr(enterpriseCode);
            String timeStr = jzTime.get("截止日期");
            String timeStr1 = jzTime.get("下一阶段的开始时间");
            //@Author: dengjian @DATE: 2024/1/22 15:06 @Description:修改查询不到数据，返回为null会报错
            if (StringUtils.isNotBlank(timeStr1)){
                if (startTime.compareTo(timeStr1) >= 0) { //查询新平台数据
                    newProduct = enterpriseMapper.getProductNameByEpc(enterpriseCode);
                } else if (endTime.compareTo(timeStr) <= 0) { //查询历史数据
                    oldProduct = enterpriseMapper.getOldProductNameByEpc(enterpriseCode);
                }else{
                    newProduct = enterpriseMapper.getProductNameByEpc(enterpriseCode);
                    oldProduct = enterpriseMapper.getOldProductNameByEpc(enterpriseCode);
                }
            }else{
                newProduct = enterpriseMapper.getProductNameByEpc(enterpriseCode);
                oldProduct = enterpriseMapper.getOldProductNameByEpc(enterpriseCode);
            }
//            if (startTime.compareTo(timeStr1) >= 0) { //查询新平台数据
//                newProduct = enterpriseMapper.getProductNameByEpc(enterpriseCode);
//            } else if (endTime.compareTo(timeStr) <= 0) { //查询历史数据
//                oldProduct = enterpriseMapper.getOldProductNameByEpc(enterpriseCode);
//            }else{
//                newProduct = enterpriseMapper.getProductNameByEpc(enterpriseCode);
//                oldProduct = enterpriseMapper.getOldProductNameByEpc(enterpriseCode);
//            }


            if(newProduct != null && newProduct.size() > 0){
                productList.addAll(newProduct);
            }
            if(oldProduct != null && oldProduct.size() > 0){
                productList.addAll(oldProduct);
            }
            return productList;
        }
    }

    @Override
    public Map getAccessEnergysTructure(String enterpriseCode) {
        AccessTimeRangeVo accessEnergysTructure = enterpriseMapper.getAccessEnergysTructure(enterpriseCode);
        AccessTimeRangeVo old = enterpriseMapper.getOld(enterpriseCode);
        AccessTimeRangeVo collect = enterpriseMapper.getEnergyDateByCollect(enterpriseCode);
        AccessTimeRangeVo mobile = enterpriseMapper.getEnergyDateByMobile(enterpriseCode);
        AccessTimeRangeVo accessMode = enterpriseMapper.getFillingMethodByOld(enterpriseCode);
        if(accessMode == null){
            accessMode = enterpriseMapper.getFillingMethod(enterpriseCode);
        }
        Map map = new HashMap();
        map.put("延期企业",accessEnergysTructure);
        map.put("老平台企业",old);
        map.put("在线采集企业",collect);
        map.put("公众号填报企业",mobile);
        map.put("接入方式",accessMode);
        return map;
    }

    @Override
    public List<SuperEpcVo> getAllEpc(String[] enterpriseCode) {
        return enterpriseMapper.getAllEpc(enterpriseCode);
    }


    /**
     * @Description: 查询企业产品单耗
     * @Param: [enterpriseCode]
     * @return: java.util.List<java.lang.String>
     * @Author: zfw
     * @Date: 2020/12/28
     * @Date: 17:12
     */
    @Override
    public JSONArray getProductQuota(Integer id) {
        //通过id,查询产品
        List<ProductNameAndIdVO> productList = enterpriseMapper.getProductQuota(id);
        JSONArray jsonArray = new JSONArray();
        for (int i = 0; i < productList.size(); i++) {
            JSONObject j0 = new JSONObject();
            j0.put("id", productList.get(i).getId());
            j0.put("name", productList.get(i).getName());
            j0.put("unit", productList.get(i).getUnitName());
            jsonArray.add(j0);
        }

        return jsonArray;
    }

    /**
     * @Description: 根据企业社会信用代码及产品名称获取指标名称和单位
     * @Author: suixin
     * @Date: 2022/7/28
     * @Return: com.alibaba.fastjson.JSONArray
     * @Param: [enterpriseCode, productName]
     */
    @Override
    public JSONArray getProductQuotaByEpc(String enterpriseCode, String productName, String time) {
        JSONArray jsonArray = new JSONArray();
        if(productName.contains("(历史)")){ //查询历史企业指标
            List<ProductNameAndIdVO> productList =  enterpriseMapper.getOldProductQuotaByEpc(enterpriseCode, productName);
            for (int i = 0; i < productList.size(); i++) {
                JSONObject j0 = new JSONObject();
                j0.put("id", productList.get(i).getId());
                j0.put("name", productList.get(i).getName());
                j0.put("lable", productList.get(i).getName());
                j0.put("unit", productList.get(i).getUnitName());
                jsonArray.add(j0);
            }
        }else{
            String startDate = time.split("&")[0];
            String endDate = time.split("&")[1];
            List<ProductNameAndIdVO> productQuotaList = enterpriseMapper.getProductQuotaByEpc(enterpriseCode, productName,startDate,endDate);
            Map<String, List<ProductNameAndIdVO>> productQuotaGroup = productQuotaList.stream().collect(Collectors.groupingBy(ProductNameAndIdVO::getUseDateStart));
            List<String> list = new ArrayList<>();
            productQuotaList.forEach(r->{
                if (!list.contains(r.getUseDateStart())){
                    list.add(r.getUseDateStart());
                }
            });
            String maxDate = Collections.max(list);
            for (ProductNameAndIdVO productNameAndIdVO : productQuotaList) {
                JSONObject productQuota = new JSONObject();
                productQuota.put("name", productNameAndIdVO.getName());
                String unitName = productNameAndIdVO.getUnitName();
                if(StringUtils.isBlank(unitName)){
                    //产品名称为电、电力时，单耗指标单位默认为 kgce/kW·h
                    unitName = "电".equals(productName) || "电力".equals(productName) ? "kgce/kW·h" : "kgce/t";
                }
                productQuota.put("unit", unitName);
                if (productQuotaGroup.size()>1&&productNameAndIdVO.getUseDateStart().equals(maxDate)){
                    productQuota.put("lable", productNameAndIdVO.getName()+"(新标)");
                    productQuota.put("time", maxDate);
                }else {
                    productQuota.put("lable", productNameAndIdVO.getName());
                }
                jsonArray.add(productQuota);
            }
        }
        return jsonArray;
    }

    @Override
    public JSONArray getUnitConsumption(String enterpriseCode, String quotaName, String time) throws ParseException {
        //查询企业屏蔽指标的月份
        String shieldTimeStr = enterpriseMapper.getQuotaShield(enterpriseCode);
        HashMap<String, String> needTime = getNeedTime(time);
        String startTime = needTime.get("开始时间");
        String endTime = needTime.get("结束时间");
        Map<String, String> jzTime = timeStr(enterpriseCode);
        String timeStr = jzTime.get("截止日期");
        String timeStr1 = jzTime.get("下一阶段的开始时间");
        //通过企业id查询行业
        String code = enterpriseMapper.getHyCodeById(enterpriseCode);//行业代码
//        String quotaCode=tEnterpriseQuotaMapper.getQuota(enterpriseCode,quotaName);//产品代码
//        Float avgDataValue = 0.0f;
//        if(quotaCode!=null){
//             avgDataValue=  enterpriseMapper.getEnergyData(enterpriseCode,quotaCode,startTime, endTime);
//        }
        Float f = 0.0f, f1 = 0.0f, f2 = 0.0f;
        Float product = 0f, tce = 0f;
        if (startTime.equals(endTime) && shieldTimeStr.contains(startTime)) {
            //企业查询的指标为单月的，且该月指标已屏蔽
        } else {
            String[] shieldList = shieldTimeStr.split(",");
            if (!quotaName.contains("(历史)")) { //查询新平台数据  startTime.compareTo(timeStr1) >= 0
                //企业单位产品能耗，用加权平均算法 取指标值不为0的月份的数据 指标*产量/总产量；除去被屏蔽月份
                try {
                    f = enterpriseMapper.getUnitConsumptionWeightedMean(enterpriseCode, quotaName, startTime, endTime, shieldList);

                }catch (Exception e){
                    e.printStackTrace();
                }
               /* List<KeyValueVO> num=enterpriseMapper.getUnitConsumption(enterpriseCode,quotaName,startTime,endTime);
                if(num != null && num.size()>0){
                    for(int i=0;i<num.size();i++){
                        //f += num.get(i).getValue();
                        tce += num.get(i).getChildVal() == null ? 0 : num.get(i).getChildVal();
                        product += num.get(i).getParentVal() == null ? 0 : num.get(i).getParentVal();
                    }
                    //f=f/num.size();
                    if(product==0){
                        f=0f;
                    }else{
                        f=tce/product;
                    }
                }else{
                    f=0.0f;
                }*/
            } else { //查询历史数据 endTime.compareTo(timeStr) <= 0
                //Integer unitId = enterpriseMapper.getunitIdByCode(enterpriseCode, quotaName);
                List<KeyValueVO> num = enterpriseMapper.getUnitConsumption2019(0, quotaName, startTime, endTime, enterpriseCode);
                if (num != null && num.size() > 0) {
                    for (int i = 0; i < num.size(); i++) {
                        if(num.get(i) != null){
                            if (num.get(i).getKey1() != null && num.get(i).getKey1().contains("吨标准煤")) {
                                f += num.get(i).getValue() * 1000;
                            } else {
                                f += num.get(i).getValue();
                            }
                        }
                    }
                    f = f / num.size();
                } else {
                    f = 0.0f;
                }
            }
            /*else {
                //截止日期以后的数据
                //企业单位产品能耗，用加权平均算法 取指标值不为0的月份的数据 指标*产量/总产量；除去被屏蔽月份
                f1 = enterpriseMapper.getUnitConsumptionWeightedMean(enterpriseCode, quotaName, startTime, endTime, shieldList);
               */
            /* List<KeyValueVO> num=enterpriseMapper.getUnitConsumption(enterpriseCode,quotaName,timeStr1,endTime);
                if(num != null && num.size()>0){
                    for(int i=0;i<num.size();i++){
                        //f1 += num.get(i).getValue();
                        tce += num.get(i).getChildVal() == null ? 0 : num.get(i).getChildVal();
                        product += num.get(i).getParentVal() == null ? 0 : num.get(i).getParentVal();
                    }
                    //f1=f1/num.size();
                    if(product==0){
                        f1=0f;
                    }else{
                        f1=tce/product;
                    }
                }else{
                    f1=0.0f;
                }*/
            /*
                //截止日期以前的数据
                Integer unitId = enterpriseMapper.getunitIdByCode(enterpriseCode, quotaName);
                List<KeyValueVO> num1 = enterpriseMapper.getUnitConsumption2019(unitId, quotaName, startTime, timeStr);
                if (num1 != null && num1.size() > 0) {

                    for (int i = 0; i < num1.size(); i++) {
                        if (num1.get(i).getKey1() != null && num1.get(i).getKey1().contains("吨标准煤")) {
                            f2 += num1.get(i).getValue() * 1000;
                        } else {
                            f2 += num1.get(i).getValue();
                        }
                    }
                    f2 = f2 / num1.size();
                } else {
                    f2 = 0.0f;
                }
                if (f1 != 0.0f && f2 != 0.0f) {
                    f = (f1 + f2) / 2;
                }

                if (f1 != 0.0f && f2 == 0.0f) {
                    f = f1;
                }

                if (f2 != 0.0f && f1 == 0.0f) {
                    f = f2;
                }

            }*/
        }

        JSONArray jsonArray = new JSONArray();
        ConfigureDataCollect configureDataCollect = configureDataCollectMapper.getListDataNewMap(enterpriseCode, quotaName);
        Float avgDataValue = 0.0f;
        if (configureDataCollect != null) {
            avgDataValue = enterpriseMapper.getEnergyData(enterpriseCode, configureDataCollect.getDataCode(), startTime, endTime);
            f = avgDataValue;
        }
        //查询行业标准
        JSONObject j = new JSONObject();
        StandardVO standard = enterpriseMapper.getStandardByType(code, quotaName);
        if (standard != null) {
            //添加入炉品位影响因子，根据入炉品位来调节对标限额,判断该企业是否属于铁合金行业，并且已上报合金入炉品位
            double adjustedValue = 0;
            if (standard.getFurnaceGrade() != null || standard.getAdjustedValue() != null){
                //铁合金企业只会有一个类型或产品，不同的工艺，不可能同时有两个,编码为含量百分比（%）	00000000100203%
                Double enterpriseFurnaceGradeValue = energyMapper.getEnterpriseFurnaceGradeValue(enterpriseCode,startTime,endTime);
                if (enterpriseFurnaceGradeValue != null){
                    adjustedValue = (enterpriseFurnaceGradeValue - standard.getFurnaceGrade()) * standard.getAdjustedValue();
                }
            }
            boolean flag = false;
            if (StringUtils.isNotBlank(standard.getImplementData())){
                int year = Integer.parseInt(standard.getImplementData().substring(0,4));
                flag = year >= 2020;
            }
            //标准实施日期20年以后的新标按1级，2级，3级能效
            j.put("限定值(企业对标值)", Double.parseDouble(standard.getLimitValue()) - adjustedValue);
            j.put("先进值(企业对标值)", Double.parseDouble(standard.getAdvancedValue()) - adjustedValue);
            j.put("准入值(企业对标值)", Double.parseDouble(standard.getAdmitValue()) - adjustedValue);
            j.put("标杆水平", standard.getBenchmarkingLevel());
            j.put("基准水平", standard.getDatumPlane());
            j.put(flag ? "3级(地方标准)" : "限定值(地方标准)", StringUtils.isNotBlank(standard.getDbLimitValue()) ? Double.parseDouble(standard.getDbLimitValue()) - adjustedValue : standard.getDbLimitValue());
            j.put(flag ? "1级(地方标准)" : "先进值(地方标准)", StringUtils.isNotBlank(standard.getDbAdvancedValue()) ? Double.parseDouble(standard.getDbAdvancedValue()) - adjustedValue : standard.getDbAdvancedValue());
            j.put(flag ? "2级(地方标准)" : "准入值(地方标准)", StringUtils.isNotBlank(standard.getDbAdmitValue()) ? Double.parseDouble(standard.getDbAdmitValue()) - adjustedValue : standard.getDbAdmitValue());
            j.put("企业产品单位能耗", f);
            j.put("standardType",standard.getStandardTypeName());
            if("国标".equals(standard.getStandardTypeName())){
                j.put(flag ? "3级" : "限定值", standard.getLimitValue());
                j.put(flag ? "1级":"先进值", standard.getAdvancedValue());
                j.put(flag ? "2级" : "准入值", standard.getAdmitValue());
            }else{
                j.put(flag ? "(行标)3级" : "(行标)限定值", standard.getLimitValue());
                j.put(flag ? "(行标)1级":"(行标)先进值", standard.getAdvancedValue());
                j.put(flag ? "(行标)2级" : "(行标)准入值", standard.getAdmitValue());
            }


            if (startTime.equals(endTime)){
                j.put("时间周期", startTime);
            }else {
                j.put("时间周期", startTime + "至" + endTime);
            }
            jsonArray.add(j);
        }else {
            //无国家标准的单耗不进行对标，只展示企业实际值
            j.put("企业产品单位能耗", f);
            if (startTime.equals(endTime)){
                j.put("时间周期", startTime);
            }else {
                j.put("时间周期", startTime + "至" + endTime);
            }
            jsonArray.add(j);
        }

        //查询行业标准，这个方法默认取第一条记录为国标，第二条为省标，不合理，需修改
        /*List<StandardVO> list=enterpriseMapper.getStandardVO(code,quotaName);
        if (list != null && list.size()>0){
            JSONObject j0 = new JSONObject();
            j0.put("product",list.get(0).getType());
            j0.put("限定值",list.get(0).getLimitValue());
            j0.put("先进值",list.get(0).getAdvancedValue());
            j0.put("企业产品单位能耗",f);
            jsonArray.add(j0);
            if(list.size()>1){
                JSONObject j1 = new JSONObject();
                j1.put("product",list.get(1).getType());
                j1.put("限定值",list.get(1).getLimitValue());
                j1.put("先进值",list.get(1).getAdvancedValue());
                j1.put("企业产品单位能耗",f);
                jsonArray.add(j1);
            }else {
                JSONObject j1 = new JSONObject();
                j1.put("product","省级标准");
                j1.put("限定值",null);
                j1.put("先进值",null);
                j1.put("企业产品单位能耗",f);
                jsonArray.add(j1);
            }
        }else {
            JSONObject j0 = new JSONObject();
            j0.put("product","国家标准");
            j0.put("限定值",null);
            j0.put("先进值",null);
            j0.put("企业产品单位能耗",f);
            jsonArray.add(j0);
            JSONObject j1 = new JSONObject();
            j1.put("product","省级标准");
            j1.put("限定值",null);
            j1.put("先进值",null);
            j1.put("企业产品单位能耗",f);
            jsonArray.add(j1);
        }*/

        /*//判断行业标准(后期做成字典)
        if (code.equals("001")){ //水泥
           // JSONArray jsonArray = new JSONArray();
            JSONObject j0 = new JSONObject();
            j0.put("product","国家标准");
            if(quotaName.equals("可比熟料综合煤耗")){
                j0.put("限定值",112);
                j0.put("先进值",103);
            }else if(quotaName.equals("可比熟料综合电耗")){
                j0.put("限定值",64);
                j0.put("先进值",56);
            }else if(quotaName.equals("可比熟料综合能耗")){
                j0.put("限定值",120);
                j0.put("先进值",110);
            }else if(quotaName.equals("可比水泥综合电耗")){
                j0.put("限定值",90);
                j0.put("先进值",85);
            }else {
                j0.put("限定值",98);
                j0.put("先进值",88);
            }
            j0.put("企业产品单位能耗",f);
            jsonArray.add(j0);
            JSONObject j1 = new JSONObject();
            j1.put("product","省级标准");
            if(quotaName.equals("可比熟料综合煤耗")){
                j1.put("限定值",110);
                j1.put("先进值",103);
            }else if(quotaName.equals("可比熟料综合电耗")){
                j1.put("限定值",64);
                j1.put("先进值",56);
            }else if(quotaName.equals("可比熟料综合能耗")){
                j1.put("限定值",118);
                j1.put("先进值",110);
            }else if(quotaName.equals("可比水泥综合电耗")){
                j1.put("限定值",90);
                j1.put("先进值",85);
            }else {
                j1.put("限定值",98);
                j1.put("先进值",88);
            }
            j1.put("企业产品单位能耗",f);
            jsonArray.add(j1);
        } else if (code.equals("003")){ //黄磷
            JSONObject j0 = new JSONObject();
            j0.put("product","国家标准");
            if(quotaName.equals("黄磷单位产品综合耗能")){
                j0.put("限定值",3.2);
                j0.put("先进值",2.5);
            }else if(quotaName.equals("黄磷单位产品电耗")){
                j0.put("限定值",13500);
                j0.put("先进值",12300);
            }else if(quotaName.equals("黄磷单位产品电炉电耗")){
                j0.put("限定值",13300);
                j0.put("先进值",12100);
            }
            j0.put("企业产品单位能耗",f);
            jsonArray.add(j0);
            JSONObject j1 = new JSONObject();
            j1.put("product","省级标准");
            if(quotaName.equals("黄磷单位产品综合耗能")){
                j1.put("限定值",3.2);
                j1.put("先进值",3);
            }else if(quotaName.equals("黄磷单位产品电耗")){
                j1.put("限定值",13900);
                j1.put("先进值",13200);
            }else if(quotaName.equals("黄磷单位产品电炉电耗")){
                j1.put("限定值",13700);
                j1.put("先进值",12900);
            }
            j1.put("企业产品单位能耗",f);
            jsonArray.add(j1);
        }else if (code.equals("002")){ //钢铁
            JSONObject j0 = new JSONObject();
            j0.put("product","国家标准");
            if(quotaName.equals("烧结工序")){
                j0.put("限定值",65);
                j0.put("先进值",55);
            }else if(quotaName.equals("高炉工序")){
                j0.put("限定值",460);
                j0.put("先进值",390);
            }else if(quotaName.equals("转炉工序")){
                j0.put("限定值",-10);
                j0.put("先进值",-8);
            }
            j0.put("企业产品单位能耗",f);
            jsonArray.add(j0);
            JSONObject j1 = new JSONObject();
            j1.put("product","省级标准");
            if(quotaName.equals("烧结工序")){
                j1.put("限定值",55);
                j1.put("先进值",47);
            }else if(quotaName.equals("高炉工序")){
                j1.put("限定值",440);
                j1.put("先进值",380);
            }else if(quotaName.equals("转炉工序")){
                j1.put("限定值",-4);
                j1.put("先进值",-20);
            }
            j1.put("企业产品单位能耗",f);
            jsonArray.add(j1);
        }else if (code.equals("004")){ //铜冶炼
            JSONObject j0 = new JSONObject();
            j0.put("product","国家标准");
            if(quotaName.equals("铜冶炼工艺(铜精矿-阴极铜)")){
                j0.put("限定值",400);
                j0.put("先进值",260);
            }else if(quotaName.equals("粗铜工艺(铜精矿-粗铜)")){
                j0.put("限定值",280);
                j0.put("先进值",140);
            }else if(quotaName.equals("阳极铜工艺(铜精矿-阳极铜)")){
                j0.put("限定值",320);
                j0.put("先进值",180);
            }else if(quotaName.equals("电解工序(阳极铜-阴极铜)")){
                j0.put("限定值",110);
                j0.put("先进值",80);
            }else if(quotaName.equals("阳极铜工艺(杂铜-阳极铜)")){
                j0.put("限定值",360);
                j0.put("先进值",280);
            }else if(quotaName.equals("阳极铜工艺(粗铜-阳极铜)")){
                j0.put("限定值",290);
                j0.put("先进值",220);
            }else if(quotaName.equals("铜精炼工艺(杂铜-阴极铜)")){
                j0.put("限定值",430);
                j0.put("先进值",350);
            }else if(quotaName.equals("铜精炼工艺(粗铜-阴极铜)")){
                j0.put("限定值",370);
                j0.put("先进值",310);
            }else if(quotaName.equals("硫酸产品单位能耗")){
                j0.put("限定值",16);
                j0.put("先进值",-30);
            }else if(quotaName.equals("吨酸电耗")){
                j0.put("限定值",130);
                j0.put("先进值",100);
            }
            j0.put("企业产品单位能耗",f);
            jsonArray.add(j0);
            JSONObject j1 = new JSONObject();
            j1.put("product","省级标准");
            if(quotaName.equals("铜冶炼工艺(铜精矿-阴极铜)")){
                j1.put("限定值",330);
                j1.put("先进值",270);
            }else if(quotaName.equals("粗铜工艺(铜精矿-粗铜)")){
                j1.put("限定值",280);
                j1.put("先进值",150);
            }else if(quotaName.equals("阳极铜工艺(铜精矿-阳极铜)")){
                j1.put("限定值",320);
                j1.put("先进值",180);
            }
//            else if(quotaName.equals("电解工序(阳极铜-阴极铜)")){
//                j1.put("限定值",0);
//                j1.put("先进值",-8);
//            }
//            else if(quotaName.equals("阳极铜工艺(杂铜-阳极铜)")){
//                j1.put("限定值",-10);
//                j1.put("先进值",-8);
//            }
//            else if(quotaName.equals("阳极铜工艺(粗铜-阳极铜)")){
//                j1.put("限定值",-10);
//                j1.put("先进值",-8);
//            }
//            else if(quotaName.equals("铜精炼工艺(杂铜-阴极铜)")){
//                j1.put("限定值",-10);
//                j1.put("先进值",-8);
//            }
//            else if(quotaName.equals("铜精炼工艺(粗铜-阴极铜)")){
//                j1.put("限定值",-10);
//                j1.put("先进值",-8);
//            }
            j1.put("企业产品单位能耗",f);
            jsonArray.add(j1);
        }*/
        return jsonArray;
    }

    @Override
    public Map<String, Object> getProductOutput(String enterpriseCode, Integer productId, String time) {
        //截取时间
//        String startTime=time.split("&")[0];
//        String endTime=time.split("&")[1];
//        startTime=startTime.substring(0,7);
//        endTime=endTime.substring(0,7);
//        Integer timeStr=Integer.valueOf(startTime.substring(0,4));
        // 获取当前年份
        //time="2020";
        if (time == null || "".equals(time)) {
            time = String.valueOf(Calendar.getInstance().get(Calendar.YEAR));
        }
        Integer endYear = Integer.parseInt(time);
        //根据id 查询code
        List<CoalVo> list = new ArrayList<>();
        List<String> list1;
        List<String> list2;
        Integer startYear = endYear - 4;
        if (endYear < 2020) {
            list1 = enterpriseMapper.getCodeByProductId(enterpriseCode, productId);
            for (int i = 0; i < 4; i++) {
                CoalVo coalVo = enterpriseMapper.getValueByProductCodeByYear(enterpriseCode, list1, startYear + i + "%");
                if (coalVo != null) {
                    giveValue(coalVo, startYear + i);
                    list.add(coalVo);
                }
            }
        } else if (startYear < 2020 && endYear >= 2020) {
            list2 = enterpriseMapper.getCodeByProductId2020(enterpriseCode, productId);
            list1 = enterpriseMapper.getCodeByProductId(enterpriseCode, productId);
            for (int i = 0; i < 2020 - startYear; i++) {
                if (list1 != null && list1.size() > 0) {
                    CoalVo coalVo = enterpriseMapper.getValueByProductCodeByYear(enterpriseCode, list1, startYear + i + "%");
                    if (coalVo != null) {
                        giveValue(coalVo, startYear + i);
                        list.add(coalVo);
                    }
                }

            }
            for (int i = 0; i <= endYear - 2020; i++) {
                Integer baseYear = 2020;
                if (list2 != null && list2.size() > 0) {
                    CoalVo coalVo = enterpriseMapper.getValueByProductCodeByYear2020(enterpriseCode, list2, (baseYear + i) + "%");
                    if (coalVo != null) {
                        giveValue(coalVo, endYear + i);
                        list.add(coalVo);
                    }
                }
            }
        } else {
            list1 = enterpriseMapper.getCodeByProductId2020(enterpriseCode, productId);
            for (int i = 0; i < 4; i++) {
                CoalVo coalVo = enterpriseMapper.getValueByProductCodeByYear2020(enterpriseCode, list1, endYear + i + "%");
                if (coalVo != null) {
                    giveValue(coalVo, startYear + i);
                    list.add(coalVo);
                }
            }
        }
        //查询
        Map<String, Object> map = new HashMap<>();

        List<String> monthList = new ArrayList<>();
        List<String> dataValueList = new ArrayList<>();

        for (int i = 0; i < list.size(); i++) {
            monthList.add(list.get(i).getMonth());
            dataValueList.add(list.get(i).getValue());
        }
        map.put("industry", monthList);
        map.put("dataValue", dataValueList);
        // 查询单位
        String unitName = enterpriseMapper.selectUnitByProductId(productId);
        if (!unitName.contains("万")) {
            unitName = "万" + unitName;
        }
        map.put("unitName", unitName);
        return map;
    }

    private void giveValue(CoalVo coalVo, Integer year) {
        if (coalVo.getMonth() == null) {
            coalVo.setMonth(year.toString());
        }
        if (coalVo.getValue() == null) {
            coalVo.setValue(null);
        }
    }

    /***
     * @Description: 按月统计综合能耗(企业端)(暂时没用)
     * @Param: [enterpriseCode, time]
     * @return: java.util.Map<java.lang.String, java.lang.Object>
     * @Author: zfw
     * @Date: 2020/12/30
     * @Date: 15:27
     */
    @Override
    public Map<String, Object> getZhnhByMonth(String enterpriseCode, String time) {
        //截取时间
        String startTime = time.split("&")[0];
        String endTime = time.split("&")[1];
        startTime = startTime.substring(0, 7);
        endTime = endTime.substring(0, 7);

        Integer timeStr = Integer.valueOf(startTime.substring(0, 4));
        Integer number = 0;
        Map<String, Object> map = new HashMap<>();
        List<String> monthList = new ArrayList<>();
        List<String> dataValueList = new ArrayList<>();
        List<CoalVo> list = new ArrayList<>();
        if (timeStr >= 2020) {
            //2020
            list = enterpriseMapper.getZhnhByMonth1(enterpriseCode, startTime, endTime);
            for (int i = 0; i < list.size(); i++) {
                monthList.add(list.get(i).getMonth());
                dataValueList.add(list.get(i).getValue());
            }
            map.put("industry", monthList);
            map.put("dataValue", dataValueList);
        } else {
            //查询
            list = enterpriseMapper.getZhnhByMonth2019(enterpriseCode, startTime, endTime);

            for (int i = 0; i < list.size(); i++) {
                monthList.add(list.get(i).getMonth());
                dataValueList.add(list.get(i).getValue());
            }
            map.put("industry", monthList);
            map.put("dataValue", dataValueList);
        }

        return map;
    }

    /***
     * @Description: 按月统计综合能耗(企业端二级页面list)
     * @Param: [enterpriseCode, time]
     * @return: java.util.Map<java.lang.String, java.lang.Object>
     * @Author: zfw
     * @Date: 2020/12/30
     * @Date: 15:27
     */
    @Override
    public List<ZhnhListVo> getZhnhByMonthList(String enterpriseCode, String time, String baseCode) throws ParseException {
        HashMap<String, String> needTime = getNeedTime(time);
        String startTime = needTime.get("开始时间");
        String endTime = needTime.get("结束时间");
        Float sum = 0.0f;
        Map<String, String> jzTime = timeStr(enterpriseCode);
        String timeStr = jzTime.get("截止日期");
        String timeStr1 = jzTime.get("下一阶段的开始时间");
        //查询
        List<ZhnhListVo> list = new ArrayList<>();
        List<ZhnhListVo> list1 = new ArrayList<>();
        List<ZhnhListVo> list2 = new ArrayList<>();

        /* 产品产量的查询走 getProductByMonthList 方法，此方法只返回企业每月综合能耗
        if (startTime.compareTo(timeStr)>=0){
            String productCode =  enterpriseMapper.selectProductById(enterpriseCode,baseCode);
            // 按月查询产量信息
            List<CoalVo> pruductNum = enterpriseMapper.selectProductNum(enterpriseCode,productCode,startTime,endTime);
            // 查询指标名称和单位
            CoalVo productInfo =enterpriseMapper.selectProductInfo(enterpriseCode,baseCode);
            // 按月查询能耗信息
            list=enterpriseMapper.getZhnhListByMonth2020(enterpriseCode,startTime,endTime,baseCode+"000000");
            // 遍历组合
            if(productCode!=null&&pruductNum!=null){
                for (int i = 0; i < list.size(); i++) {
                    String month = list.get(i).getMonth();
                    for (int j = 0; j < pruductNum.size(); j++) {
                        CoalVo coalVo = pruductNum.get(j);
                        if(month.equals(coalVo.getMonth())){
                            list.get(i).setYieldValue(pruductNum.get(j).getValue());
                        }
                    }
                    if(productInfo!=null){
                        list.get(i).setYieldName(productInfo.getMonth());
                        list.get(i).setUnitName(productInfo.getValue());
                    }
                }
            }
        }else if(endTime.compareTo(timeStr)<=0){ //2019
            Integer entID=getEntIdByenterpriseCode(enterpriseCode);
            list=enterpriseMapper.getZhnhListByMonth(entID,startTime,endTime,baseCode);

        }else{
            Integer entID=getEntIdByenterpriseCode(enterpriseCode);
            //通过新平台的核算单元查询老数据的对应的id
            Integer unitId=enterpriseMapper.getUnitIdByBaseCode(enterpriseCode,baseCode);
            if("00".equals(baseCode)){ //全厂
                unitId=entID;
            }
           if(unitId!=null){
               list2=enterpriseMapper.getZhnhListByMonth(entID,startTime,timeStr,unitId.toString());
               list.addAll(list2);
            }
            String productCode =  enterpriseMapper.selectProductById(enterpriseCode,baseCode);
            // 按月查询产量信息
            List<CoalVo> pruductNum = enterpriseMapper.selectProductNum(enterpriseCode,productCode,timeStr1,endTime);
            // 查询指标名称和单位
            CoalVo productInfo =enterpriseMapper.selectProductInfo(enterpriseCode,baseCode);
            // 按月查询能耗信息
            list1=enterpriseMapper.getZhnhListByMonth2020(enterpriseCode,timeStr1,endTime,baseCode+"000000");
            // 遍历组合
            if(productCode!=null&&pruductNum!=null){
                for (int i = 0; i < list1.size(); i++) {
                    String month = list1.get(i).getMonth();
                    for (int j = 0; j < pruductNum.size(); j++) {
                        CoalVo coalVo = pruductNum.get(j);
                        if(month.equals(coalVo.getMonth())){
                            list1.get(i).setYieldValue(pruductNum.get(j).getValue());
                        }
                    }
                    if(productInfo!=null){
                        list1.get(i).setYieldName(productInfo.getMonth());
                        list1.get(i).setUnitName(productInfo.getValue());
                    }
                }
            }
            list.addAll(list1);
        }
        产品产量的查询走 getProductByMonthList 方法，此方法只返回企业每月综合能耗 */

        // 按月查询能耗信息
        if (startTime.compareTo(timeStr1) >= 0) { //查询新平台数据
            list = enterpriseMapper.getZhnhListByMonth2020(enterpriseCode, startTime, endTime, baseCode + "000000");
        } else if (endTime.compareTo(timeStr) <= 0) { //查询历史数据
            //Integer entID = getEntIdByenterpriseCode(enterpriseCode);
            list = enterpriseMapper.getZhnhListByMonth(enterpriseCode, startTime, endTime, baseCode);
        } else {
            Integer entID = getEntIdByenterpriseCode(enterpriseCode);
            //通过新平台的核算单元查询老数据的对应的id
            Integer unitId = enterpriseMapper.getUnitIdByBaseCode(enterpriseCode, baseCode);
            if ("00".equals(baseCode)) { //全厂
                unitId = entID;
            }
            if (unitId != null) {
                list2 = enterpriseMapper.getZhnhListByMonth(enterpriseCode, startTime, timeStr, unitId.toString());
                list.addAll(list2);
            }
            // 按月查询能耗信息
            list1 = enterpriseMapper.getZhnhListByMonth2020(enterpriseCode, timeStr1, endTime, baseCode + "000000");
            list.addAll(list1);
        }

        return list;
    }

    @Override
    public R getProductByMonthList(String enterpriseCode, String time) {
        String timeStr1 = time.split("&")[0];
        String endTime = time.split("&")[1];
        timeStr1 = timeStr1.substring(0, 7);
        endTime = endTime.substring(0, 7);
        List<String> productCode = enterpriseMapper.selectProductByIds(enterpriseCode);
        List<String> newProduct = new ArrayList<>();
        Map<String, List<StructureVo>> newProductValue = new HashMap<>();
        Map<String, Object> map = new HashMap<>();
        if (productCode != null && productCode.size() > 0) {
            for (int i = 0; i < productCode.size(); i++) {
                String productName = enterpriseMapper.selectProductName(enterpriseCode, productCode.get(i));
                if (productName != null && !"".equals(productName)) {
                    List<StructureVo> pruductNum = enterpriseMapper.selectProductNums(enterpriseCode, productCode.get(i), timeStr1, endTime);
                    newProduct.add(productName);
                    newProductValue.put(productName, pruductNum);
                }
            }
        }
        if (newProduct.size() < 1) {
            return R.failed("企业没有产品!");
        }
        map.put("name", newProduct);
        map.put("value", newProductValue);
        return R.ok(map);
    }

    @Override
    public R getMaterielProductByMonthList(String enterpriseCode, String time) throws ParseException {
        String startTime = time.split("&")[0].substring(0, 7);
        String endTime = time.split("&")[1].substring(0, 7);
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        calendar.setTime(sdf.parse(startTime));
        List<String> dateList = new ArrayList<>();
        dateList.add(startTime);
        while (sdf.parse(endTime).after(calendar.getTime())) {
            calendar.add(Calendar.MONTH, 1);
            dateList.add(sdf.format(calendar.getTime()));
        }
        //根据企业信用代码，获取企业停产周期。如果停产周期不为空，则将停产周期内的月份从dateList中移除


        List<String> newProduct = new ArrayList<>();
        Map<String, List<StructureVo>> newProductValue = new HashMap<>();
        Map<String, Object> map = new HashMap<>();
        List<MaterialVo> materielProduct = enterpriseMapper.selectMaterielProduct(enterpriseCode);
        if (materielProduct != null && materielProduct.size() > 0) {
            for (MaterialVo product : materielProduct) {
                List<StructureVo> pruductNum = new ArrayList<>();
                if("04".equals(product.getType())){ //非能源类产品
                    String outPut = enterpriseMapper.getProductOutPutCode(enterpriseCode, product.getCode());//产品产量编码
                    String consumption = enterpriseMapper.getProductConsumptionCode(enterpriseCode, product.getCode());//产品消耗量编码
                    pruductNum = enterpriseMapper.selectMaterielProductValue(enterpriseCode, outPut, consumption, product.getUnit(), dateList);
                }else{ //能源类产品
                    pruductNum = enterpriseMapper.selectEnergyProductValue(enterpriseCode, product.getCode(), product.getUnit(), dateList);
                }
                if(StringUtils.isNotEmpty(product.getName())){
                    String productName = StringUtils.isNotEmpty(product.getCategory()) ? product.getName()+"("+product.getCategory()+")": product.getName();
                    newProduct.add(productName);
                    newProductValue.put(productName, pruductNum);
                }
            }
        } else {
            return R.failed("企业没有产品!");
        }
        map.put("name", newProduct);
        map.put("value", newProductValue);
        return R.ok(map);
    }


    /***
     * @Description: 按月统计实物量
     * @Param: [enterpriseCode, time]
     * @return: java.util.Map<java.lang.String, java.lang.Object>
     * @Author: zfw
     * @Date: 2020/12/30
     * @Date: 15:27
     */
    @Override
    public Map<String, Object> getMaterialValue(String enterpriseCode, String code, String time, String baseCode) throws ParseException {
        // time="2020-01-01&2020-12-01";
        HashMap<String, String> needTime = getNeedTime(time);
        String startTime = needTime.get("开始时间");
        String endTime = needTime.get("结束时间");
        Map<String, String> jzTime = timeStr(enterpriseCode);
        String timeStr = jzTime.get("截止日期");
        String timeStr1 = jzTime.get("下一阶段的开始时间");
        //查询
        List<CoalVo> list = new ArrayList<>();
        List<CoalVo> list1 = new ArrayList<>();
        List<CoalVo> list2 = new ArrayList<>();
        if (endTime.compareTo(timeStr) <= 0) { //查询历史数据
            Integer entID = getEntIdByenterpriseCode(enterpriseCode);
            list = enterpriseMapper.getMaterialValue(baseCode, code, startTime, endTime);
        } else if (startTime.compareTo(timeStr1) >= 0) { //查询新平台数据
            getMaterialValue2020(enterpriseCode, code, baseCode, startTime, endTime, list);
        } else {
            //查询历史数据
            Integer entID = getEntIdByenterpriseCode(enterpriseCode);
            //通过新平台的核算单元查询老数据的对应的id
            Integer unitId = enterpriseMapper.getUnitIdByBaseCode(enterpriseCode, baseCode);
            if ("00".equals(baseCode)) { //全厂
                unitId = entID;
            }
            if (unitId != null) {
                list = enterpriseMapper.getMaterialValue1(unitId.toString(), code, startTime, timeStr);
            }
            if (list == null || list.size() == 0) {
                // 按月遍历
                String start = startTime.substring(0, 4);
                String end = timeStr.substring(0, 4);
                Integer startNum = Integer.parseInt(startTime.substring(5, 7));
                Integer endNum = Integer.parseInt(timeStr.substring(5, 7));
                if (!start.equals(end)) {
                    endNum = endNum + 12 * (Integer.parseInt(end) - Integer.parseInt(start));
                }
                Integer temp = Integer.parseInt(start);
                Integer j = startNum;
                for (int i = startNum; i <= endNum; i++) {
                    CoalVo coalVo;
                    if (j > 12) {
                        j = j - 12;
                        temp = temp + 1;
                    }
                    if (i < 10) {
                        coalVo = new CoalVo(temp + "-0" + j, "0");
                    } else {
                        coalVo = new CoalVo(temp + "-" + j, "0");
                    }

                    list.add(coalVo);
                    j++;
                }
            }
            //查询新平台数据
            getMaterialValue2020(enterpriseCode, code, baseCode, timeStr1, endTime, list);
        }

        Map<String, Object> map = new HashMap<>();
        List<String> monthList = new ArrayList<>();
        List<String> dataValueList = new ArrayList<>();

        for (int i = 0; i < list.size(); i++) {
            monthList.add(list.get(i).getMonth());
            dataValueList.add(list.get(i).getValue());
        }
        map.put("industry", monthList);
        map.put("dataValue", dataValueList);
        return map;
    }

    //查询企业接入至今的能耗数据
    private void getMaterialValue2020(String enterpriseCode, String code, String baseCode, String startTime, String endTime, List<CoalVo> list) {
        List<CoalVo> materialValue = new ArrayList<>();
        if ("00".equals(baseCode) && code.equals("3300")) {
            //全厂电力 直接取能源消耗量，优先级为 11>20>21>10
            materialValue = enterpriseMapper.getMaterialElectric(enterpriseCode, code, startTime, endTime, baseCode + "000000");
        } else {
            /*if("3200".equals(code)){ //热力
                code = "3200,4400,4401,4402,4403,4404";
            }
            if("3900".equals(code)){ //其他燃料
                code = "3900,4000,4200,4300,4500,4600,4700";
            }*/
            materialValue = enterpriseMapper.getMaterialValue2020(enterpriseCode, code, startTime, endTime, baseCode + "000000");
            //@Author: dengjian @DATE: 2024/1/16 9:55 @Description:前台呈现的的电力数据单位是万千瓦时，不知道这个转换出于什么考虑，应用户要求。暂时不转换
//            if (code.equals("3300")) {
//                for (int i = 0; i < materialValue.size(); i++) {
//                    CoalVo coalVo = materialValue.get(i);
//                    String value = coalVo.getValue();
//                    Double nValue = Double.parseDouble(value) * 10000;
//                    coalVo.setValue(nValue.toString());
//                }
//            }
        }
        // 按月遍历
        String start = startTime.substring(0, 4);
        String end = endTime.substring(0, 4);
        Integer startNum = Integer.parseInt(startTime.substring(5, 7));
        Integer endNum = Integer.parseInt(endTime.substring(5, 7));
        if (!start.equals(end)) {
            endNum = endNum + 12 * (Integer.parseInt(end) - Integer.parseInt(start));
        }
        Integer temp = Integer.parseInt(start);
        Integer j = startNum;
        for (int i = startNum; i <= endNum; i++) {
            CoalVo coalVo;
            if (j > 12) {
                j = j - 12;
                temp = temp + 1;
            }
            if (j < 10) {
                coalVo = new CoalVo(temp + "-0" + j, "0");
            } else {
                coalVo = new CoalVo(temp + "-" + j, "0");
            }
            for (CoalVo data : materialValue) {
                if (coalVo.getMonth().equals(data.getMonth())) {
                    coalVo.setValue(data.getValue());
                }
            }
            list.add(coalVo);
            j++;
        }
    }


    /***
     * @Description: 获取能源实物量品种
     * @Param: [enterpriseCode, time]
     * @return: java.util.Map<java.lang.String, java.lang.Object>
     * @Author: zfw
     * @Date: 2020/12/30
     * @Date: 15:27
     */
    @Override
    public List<MaterialVo> getMaterial(String enterpriseCode, String time, String baseCode) throws ParseException {
        //time="2020-01-01&2020-12-01";
        HashMap<String, String> needTime = getNeedTime(time);
        String startTime = needTime.get("开始时间");
        String endTime = needTime.get("结束时间");
        Map<String, String> jzTime = timeStr(enterpriseCode);
        String timeStr = jzTime.get("截止日期");

        List<MaterialVo> list = new ArrayList<>();
        if (endTime.compareTo(timeStr) <= 0) { //查询历史数据
            Integer entID = getEntIdByenterpriseCode(enterpriseCode);
            //查询
            list = enterpriseMapper.getMaterial(entID, baseCode);
        } else {
            if("00".equals(baseCode)){
                baseCode = "00000000";
            }
            list = enterpriseMapper.getMaterial2020(enterpriseCode, baseCode, startTime, endTime);
            /*MaterialVo materialVo = new MaterialVo("综合能耗", "0000", null);
            MaterialVo materialVo1 = new MaterialVo("余热余压", "3700", null);
            //MaterialVo materialVo2 = new MaterialVo("热力", "3200", null);
            if (list.contains(materialVo)) {
                list.remove(materialVo);
            }
            if (list.contains(materialVo1)) {
                list.remove(materialVo1);
            }*/
        }

        return list;
    }

    /***
     * @Description: 得到近三年的单耗
     * @Param: [enterpriseCode]
     * @return: java.util.List<java.util.Map < java.lang.String, java.lang.String>>
     * @Author: zfw
     * @Date: 2020/12/30
     * @Date: 17:39
     */
    @Override
    public List<Map<String, String>> getDhThreeYears(String enterpriseCode) throws ParseException {
        //获取截止时间
        Map<String, String> jzTime = timeStr(enterpriseCode);
        String timeStr = jzTime.get("截止日期");
        String timeStr1 = jzTime.get("下一阶段的开始时间");
        //得到时间
        String nowYear = String.valueOf(Calendar.getInstance().get(Calendar.YEAR));
        //去年
        int lastYear = Integer.valueOf(nowYear) - 1;
        //前年
        int qYear = Integer.valueOf(nowYear) - 2;

        List<Map<String, String>> list2 = new ArrayList<>();
        List<Integer> listYears = new ArrayList<Integer>();
        listYears.add(Integer.valueOf(nowYear));
        listYears.add(lastYear);
        listYears.add(qYear);


        //查询指标值
        for (int y = 0; y < listYears.size(); y++) {
            if (listYears.get(y) >= 2020) { //2020年以后的
                //首先查询指标
                List<ZbVo> listZB = enterpriseMapper.getZbByenterpriseCode(enterpriseCode);
                List<ZbVo> listZB2019 = enterpriseMapper.getZbByenterpriseCode2019(enterpriseCode);
                String preTime = null;
                String startTime = null;
                String endTime = null;
                String finallyTime = null;
                if (listYears.get(y) == 2020) {
                    preTime = listYears.get(y).toString() + "-01";
                    startTime = timeStr;
                    endTime = timeStr1;
                    finallyTime = listYears.get(y).toString() + "-12";
                } else {
                    startTime = listYears.get(y).toString() + "-01";
                    endTime = listYears.get(y).toString() + "-12";
                }
                if (listZB != null && listZB.size() > 0) {
                    for (int i = 0; i < listZB.size(); i++) {
                        Map<String, String> map = new HashMap<>();
                        map.put("year", listYears.get(y).toString());
                        //查询单耗
                        List<DHVo> dhList = new ArrayList<>();
                        List<DHVo> dhList1 = new ArrayList<>();
                        List<DHVo> dhList2 = new ArrayList<>();
                        if (!(listYears.get(y) == 2020)) {
                            dhList = enterpriseMapper.getDhByName(enterpriseCode, listZB.get(i).getZb(), startTime, endTime);
                        } else {
                            if (listZB.size() > 0) {
                                dhList1 = enterpriseMapper.getDhByName(enterpriseCode, listZB.get(i).getZb(), endTime, finallyTime);
                            }
                            if (listZB2019.size() > 0) {
                                dhList2 = enterpriseMapper.getDhByName2019(enterpriseCode, listZB2019.get(i).getProductId(), listZB2019.get(i).getZb(), preTime, startTime);
                            }
                            if (dhList1.size() > 0 && dhList2.size() > 0) {
                                DHVo dhVo = dhList1.get(0);
                                DHVo dhVo1 = dhList2.get(0);
                                String value = dhVo.getValue();
                                String value1 = dhVo1.getValue();
                                Float values = (Float.valueOf(value) + Float.valueOf(value1)) / 2;
                                DHVo dhVo2 = new DHVo(dhVo.getUnit(), dhVo.getZb(), String.valueOf(values), dhVo.getUnitName());
                                dhList.add(dhVo2);
                            } else if (dhList1.size() == 0 && dhList2.size() > 0) {
                                dhList.add(dhList2.get(0));
                            } else if (dhList2.size() == 0 && dhList1.size() > 0) {
                                dhList.add(dhList1.get(0));
                            } else {

                            }
                        }
                        //list.add("",dh.getZb());
                        if (dhList != null & dhList.size() > 0) {
                            for (int j = 0; j < dhList.size(); j++) {
                                map.put("unitEnergyConsumption", dhList.get(j).getValue());
                                if (listZB.get(i).getUnit() == null) {
                                    map.put("unitEnergyConsumptionUnit", "tce");
                                } else {
                                    map.put("unitEnergyConsumptionUnit", listZB.get(i).getUnit());
                                }
                                //查询产品消耗量
                                float value = 0f;
                                List<DHVo> cpList = new ArrayList<>();
                                List<DHVo> cpList2020 = new ArrayList<>();
                                List<DHVo> cpList2019 = new ArrayList<>();
                                if (!(listYears.get(y) == 2020)) {
                                    cpList2020 = enterpriseMapper.getCpByproductId(enterpriseCode, listZB.get(i).getProductId(), startTime, endTime);
                                    cpList = cpList2020;
                                } else {
                                    if (listZB.size() > 0) {
                                        cpList2020 = enterpriseMapper.getCpByproductId(enterpriseCode, listZB.get(i).getProductId(), endTime, finallyTime);
                                    }
                                    if (listZB2019.size() > 0) {
                                        cpList2019 = enterpriseMapper.getCpByproductId2019(enterpriseCode, listZB2019.get(i).getProductId(), preTime, startTime);
                                    }
                                    cpList.addAll(cpList2020);
                                    cpList.addAll(cpList2019);
                                }
                                for (int k = 0; k < cpList.size(); k++) {
                                    map.put("productZbName", listZB.get(i).getZb());
                                    map.put("productName", listZB.get(i).getProductName());
                                    value += Float.valueOf(cpList.get(k).getValue());
                                    //查询单位
                                    String unitName = enterpriseMapper.selectUnitByProductId(Integer.valueOf(listZB.get(i).getProductId()));
                                    map.put("yieldUnit", unitName);
                                }
                                map.put("yieldNum", String.valueOf(value));
                                list2.add(map);

                            }
                        }
                    }
                }
            } else {//19年以前的
                //首先查询指标
                List<ZbVo> listZB = enterpriseMapper.getZbByenterpriseCode2019(enterpriseCode);
                String startTime = listYears.get(y).toString() + "-01";
                String endTime = listYears.get(y).toString() + "-12";
                if (listZB != null && listZB.size() > 0) {
                    for (int i = 0; i < listZB.size(); i++) {
                        if (listZB.get(i).getProductId() != null && listZB.get(i).getZb() != null) {
                            Map<String, String> map = new HashMap<>();
                            map.put("year", listYears.get(y).toString());

                            //查询单耗
                            List<DHVo> dhList = enterpriseMapper.getDhByName2019(enterpriseCode, listZB.get(i).getProductId(), listZB.get(i).getZb(), startTime, endTime);
                            //list.add("",dh.getZb());
                            Float unitEnergyConsumption = 0f;
                            if (dhList != null & dhList.size() > 0) {
                                for (int j = 0; j < dhList.size(); j++) {
//                                if(dhList.get(j).getUnitName()!=null && dhList.get(j).getUnitName().contains("吨标准煤")){
//                                    unitEnergyConsumption=Float.valueOf(dhList.get(j).getValue())*1000;
//                                }else{
                                    unitEnergyConsumption = Float.valueOf(dhList.get(j).getValue());
                                    //}
                                    map.put("unitEnergyConsumption", unitEnergyConsumption.toString());
                                    map.put("unitEnergyConsumptionUnit", dhList.get(j).getUnit());
                                    //查询产品消耗量
                                    float value = 0f;
                                    List<DHVo> cpList = enterpriseMapper.getCpByproductId2019(enterpriseCode, listZB.get(i).getProductId(), startTime, endTime);
                                    for (int k = 0; k < cpList.size(); k++) {
                                        map.put("productName", listZB.get(k).getProductName());
                                        map.put("productZbName", listZB.get(k).getZb());
                                        value += Float.valueOf(cpList.get(k).getValue());
                                        map.put("yieldUnit", "吨");
                                    }
                                    map.put("yieldNum", String.valueOf(value));
                                    list2.add(map);

                                }

                            }
                        }
                    }
                }

            }


        }

        //得到产量code

        //查询产品产量

        //最后和在一起

        return list2;
    }

    /***
     * @Description: 查询企业各种能耗信息
     * @Param: [enterpriseCode, time]
     * @return: java.util.Map<java.lang.String, java.lang.Object>
     * @Author: zfw
     * @Date: 2020/12/30
     * @Date: 15:27
     */
    @Override
    public List<ListValueVO> getListValue(String enterpriseCode, String time, String baseCode) throws ParseException {
        Map<String, String> jzTime = timeStr(enterpriseCode);
        String timeStr = jzTime.get("截止日期");
        String timeStr1 = jzTime.get("下一阶段的开始时间");
        //String tiemStr=time.trim().substring(0,4);
        time = time.trim();

        List<ListValueVO> list = new ArrayList<>();
        if (time.compareTo(timeStr1) >= 0) { //2020年数据
            //能源消耗
            List<ListValueVO> tmpList = enterpriseMapper.getListValue2020(enterpriseCode, time, baseCode + "000000");
            //原料用能
            List<ListValueVO> materialList = enterpriseMapper.getForMaterial(enterpriseCode, time, baseCode + "000000");
            Map<String,ListValueVO> materialMap = new HashMap<>();
            for (ListValueVO listValueVO : materialList) {
                materialMap.put(listValueVO.getCode(),listValueVO);
            }

            //合并热力、其它燃料
            Float thermalEnergy = 0f, otherEnergy = 0f, thermalMaterial = 0f, otherMaterial = 0f;
            boolean thermalFlag = false, otherFlag = false;
            for (ListValueVO vo : tmpList) {
                if(materialMap.containsKey(vo.getCode())){ //原料用能
                    ListValueVO tmpVo = materialMap.get(vo.getCode());
                    Float materials = 0f;
                    if(tmpVo.getForMaterials()!=0f){
                        if(vo.getRatio()!=null){
                            materials = ( tmpVo.getForMaterials() * tmpVo.getRatio() ) / ( vo.getRatio()==0f ? 1 : vo.getRatio() );
                        }else{
                            vo.setRatio(tmpVo.getRatio());
                            materials = tmpVo.getForMaterials();
                        }
                    }
                    vo.setForMaterials(materials);
                    materialMap.remove(vo.getCode());
                }

                if (thermalEnergyList.contains(vo.getCode())) { //热力
                    thermalEnergy += vo.getStandardValue(); //能源消耗折标量
                    if(vo.getForMaterials() != null){
                        thermalMaterial += vo.getForMaterials() * vo.getRatio(); //原料用能折标量
                    }
                    thermalFlag = true;
                } else if (otherEnergyList.contains(vo.getCode())) { //其它燃料
                    otherEnergy += vo.getStandardValue(); //能源消耗折标量
                    if(vo.getForMaterials() != null){
                        otherMaterial += vo.getForMaterials() * vo.getRatio(); //原料用能折标量
                    }
                    otherFlag = true;
                } else{
                    list.add(vo);
                }
            }
            if(materialMap.size()>0){ //不在综合能耗公式中的能源的原料用能
                for (String key : materialMap.keySet()) {
                    ListValueVO vo = materialMap.get(key);
                    if(thermalEnergyList.contains(vo.getCode())) { //热力
                        thermalMaterial += vo.getForMaterials() * vo.getRatio(); //原料用能折标量
                        thermalFlag = true;
                    }else if(otherEnergyList.contains(vo.getCode())) { //其它燃料
                        otherMaterial += vo.getForMaterials() * vo.getRatio(); //原料用能折标量
                        otherFlag = true;
                    }else{
                        list.add(vo);
                    }
                }
            }
            if (thermalFlag) {
                thermalEnergy = thermalEnergy!=0f ? thermalEnergy/0.0341f : thermalEnergy; //实物量
                thermalMaterial = thermalMaterial!=0f ? thermalMaterial/0.0341f : thermalMaterial; //原料用能
                ListValueVO vo = new ListValueVO("热力","3200",thermalEnergy,0.0341f,"吨标准煤",thermalEnergy);
                vo.setForMaterials(thermalMaterial);
                list.add(vo);
            }
            if (otherFlag) {
                ListValueVO vo = new ListValueVO("其他燃料","3900",otherEnergy,1f,"吨标准煤",otherEnergy);
                vo.setForMaterials(otherMaterial);
                list.add(vo);
            }
        } else if (Integer.valueOf(time.substring(0, 4)) > 2019 && time.compareTo(timeStr) <= 0) {
            Integer entID = getEntIdByenterpriseCode(enterpriseCode);
            Integer unitId = enterpriseMapper.getUnitIdByBaseCode(enterpriseCode, baseCode);
            if ("00".equals(baseCode)) { //全厂
                unitId = entID;
                baseCode = unitId.toString();
            }
            if (unitId != null) {
                baseCode = unitId.toString();
                ListValueVO vo = new ListValueVO();
                Float sum1 = 0.0f;
                list = enterpriseMapper.getListValue1(entID, baseCode, time);
                if (list != null && list.size() > 0) {
                    for (ListValueVO tem : list) {
                        if ("3300".equals(tem.getCode()) && "千瓦·时".equals(tem.getUnit())) { //把电转为万
                            Float a = tem.getTotal() / 10000;
                            tem.setTotal(a);
                            tem.setUnit("万千瓦·时");
                        }
                    }

                }
                //添加综合能耗合计值
                vo.setCode("0000");
                sum1 = enterpriseMapper.getTotalZhnh2019(baseCode, time);
                vo.setTotal(sum1);
                vo.setName("综合能耗");
                list.add(vo);
            }

        } else {
            Integer entID = getEntIdByenterpriseCode(enterpriseCode);
           /* Integer unitId=enterpriseMapper.getUnitIdByBaseCode(enterpriseCode,baseCode);
            if("00".equals(baseCode)){ //全厂
                unitId=entID;
                baseCode=unitId.toString();
            }*/
            if (baseCode != null) {
                baseCode = baseCode.toString();
                ListValueVO vo = new ListValueVO();
                Float sum1 = 0.0f;
                list = enterpriseMapper.getListValue1(entID, baseCode, time);
                if (list != null && list.size() > 0) {
                    for (ListValueVO tem : list) {
                        if ("3300".equals(tem.getCode()) && "千瓦·时".equals(tem.getUnit())) { //把电转为万
                            Float a = tem.getTotal() / 10000;
                            tem.setTotal(a);
                            tem.setUnit("万千瓦·时");
                        }
                    }
                }
                //添加综合能耗合计值
                vo.setCode("0000");
                sum1 = enterpriseMapper.getTotalZhnh2019(baseCode, time);
                vo.setTotal(sum1);
                vo.setName("综合能耗");
                list.add(vo);
            }
        }

        return list;
    }

    /***
     * @Description: 按分工序查询企业耗能情况
     * @Param: [enterpriseCode, time]
     * @return: java.util.Map<java.lang.String, java.lang.Object>
     * @Author: zfw
     * @Date: 2020/12/30
     * @Date: 15:27
     */
    @Override
    public List<ProcedureVO> getValueByProcedure(String enterpriseCode, String baseCode, String time, String energyType, String energyUseType, String configureName,String configureCode) throws ParseException {
        String startTime = time.trim();
        String endTime = time.trim();
        Map<String, String> jzTime = timeStr(enterpriseCode);
        String timeStr = jzTime.get("截止日期");
        String timeStr1 = jzTime.get("下一阶段的开始时间");
        time = time.trim();



        List<ProcedureVO> list = new ArrayList<>();
        if (time.compareTo(timeStr) >= 0) { //2020年数据
            list = enterpriseMapper.getValueByNewProcedure(enterpriseCode, startTime, endTime, energyType, energyUseType, configureName,configureCode);
            /* //首先查询所有的工序
            List<NameValueVO> listGx = enterpriseMapper.getAllGxByCode(enterpriseCode);
            ArrayList<String> strings = new ArrayList<>();
            for (int i = 0; i < listGx.size(); i++) {
                NameValueVO nameValueVO = listGx.get(i);
                strings.add(nameValueVO.getValue());
            }
            if (!strings.contains("00")) {
                NameValueVO process = new NameValueVO("全厂", "00");
                listGx.add(0, process);
            }
            List<ProcedureVO> tempList = new ArrayList<>();
            for (int i = 0; i < listGx.size(); i++) {
                tempList = enterpriseMapper.getValueByProcedure(enterpriseCode, listGx.get(i).getValue(), startTime, endTime);
                list.addAll(tempList);
                //处理08-71/72 start
                for(int t=0;t<tempList.size();t++){
                    String strCode01=tempList.get(t).getConfigureCode().substring(8,10);
                    String strCode02=tempList.get(t).getConfigureCode().substring(14,16);
                    if(strCode01.equals("08")&&(strCode02.equals("71")||strCode02.equals("72"))){
                    List<CoalVo> listTemp;
                    listTemp = enterpriseMapper.selectDetailByDataCodeName(enterpriseCode, tempList.get(t).getConfigureCode(), time);
                        if(!listTemp.isEmpty()) {
                            Double total = 0.00;
                            for (int k = 0; k < listTemp.size(); k++) {
                                total = total + Double.parseDouble(listTemp.get(k).getValue());
                            }//for end
                            Double avg = total / listTemp.size();
                            DecimalFormat df = new DecimalFormat("#.0000");
                            String str = df.format(avg);
                            tempList.get(t).setValue(str);
                        }
                    }//if end
                }//for end
                //处理08-71/72 end

                for (ProcedureVO vo : tempList) {
                    String configureCode = vo.getConfigureCode();
                    String substring = configureCode.substring(8, 10);
                    String energyUseType = configureCode.substring(14);
                    String energyType = configureCode.substring(10, 14);
                    String collectType = vo.getCollectType();
                    if (substring.equals("03")) {
                        String subName = enterpriseMapper.selectSubName(energyType);
                        vo.setType(subName);
                    } else if (substring.equals("04")) {
                        vo.setType("非能源类产品");
                    } else if (substring.equals("05")) {
                        vo.setType("一次能源折标系数");
                    } else if (substring.equals("06")) {
                        vo.setType("二次能源折标系数");
                    } else if (substring.equals("07")) {
                        vo.setType("耗能工质折标系数");
                    } else if (substring.equals("08")) {
                        vo.setType("能效指标");
                    } else if (substring.equals("09")) {
                        vo.setType("经济指标");
                    } else if (substring.equals("10")) {
                        vo.setType("其它数据");
                    } else if (substring.equals("21")) {
                        vo.setType("企业自定义物料编码");
                    } else if (substring.equals("22")) {
                        vo.setType("质量参数");
                    } else {

                    }
                    if (energyUseType != null) {
                        switch (energyUseType) {
                            case "10":
                                vo.setEnergyUseType("购进");
                                break;
                            case "11":
                                vo.setEnergyUseType("购进已消费");
                                break;
                            case "12":
                                vo.setEnergyUseType("购进未消费");
                                break;
                            case "20":
                                vo.setEnergyUseType("能源消费合计");
                                break;
                            case "21":
                                vo.setEnergyUseType("工业生产消费");
                                break;
                            case "22":
                                vo.setEnergyUseType("非工业生产消费");
                                break;
                            case "23":
                                vo.setEnergyUseType("工业生产消费用作原材料");
                                break;
                            case "24":
                                vo.setEnergyUseType("分摊用电量");
                                break;
                            case "30":
                                vo.setEnergyUseType("产出");
                                break;
                            case "31":
                                vo.setEnergyUseType("产出用于工业");
                                break;
                            case "32":
                                vo.setEnergyUseType("产出用于非工业");
                                break;
                            case "33":
                                vo.setEnergyUseType("能源类产品产出");
                                break;
                            case "34":
                                vo.setEnergyUseType("外售");
                                break;
                            case "44":
                                vo.setEnergyUseType("回收利用");
                                break;
                            case "51":
                                vo.setEnergyUseType("期初库存");
                                break;
                            case "52":
                                vo.setEnergyUseType("期末库存");
                                break;
                            case "60":
                                vo.setEnergyUseType("外供");
                                break;
                            case "71":
                                vo.setEnergyUseType("验证指标");
                                break;
                            case "72":
                                vo.setEnergyUseType("考核指标");
                                break;
                            case "80":
                                vo.setEnergyUseType("其他");
                                break;
                            case "81":
                                vo.setEnergyUseType("运输工具消费");
                                break;
                            case "90":
                                vo.setEnergyUseType("其他加工转换投入");
                                break;
                            case "91":
                                vo.setEnergyUseType("火力发电");
                                break;
                            case "92":
                                vo.setEnergyUseType("供热");
                                break;
                            case "93":
                                vo.setEnergyUseType("原煤入洗");
                                break;
                            case "94":
                                vo.setEnergyUseType("炼焦");
                                break;
                            case "95":
                                vo.setEnergyUseType("炼油及煤制油");
                                break;
                            case "96":
                                vo.setEnergyUseType("制气");
                                break;
                            case "97":
                                vo.setEnergyUseType("天然气液化");
                                break;
                            case "99":
                                vo.setEnergyUseType("加工煤制品");
                                break;
                        }
                    }
                    if (collectType != null) {
                        switch (collectType) {
                            case "1":
                                vo.setCollectType("天");
                                break;
                            case "2":
                                vo.setCollectType("月");
                                break;
                            case "3":
                                vo.setCollectType("年");
                                break;
                        }
                    }
                    vo.setName(listGx.get(i).getName());
                    list.add(vo);
                }
            }*/
        } else {
            Integer entID = getEntIdByenterpriseCode(enterpriseCode);
            list = enterpriseMapper.getValueByProcedure1(entID, time);
        }
        return list;
    }




    /***
     * @Description: 查询计量器具
     * @Param: [enterpriseCode, time]
     * @return: java.util.Map<java.lang.String, java.lang.Object>
     * @Author: zfw
     * @Date: 2020/12/30
     * @Date: 15:27
     */
    @Override
    public List<CollectValueVO> getCollectionValue(String enterpriseCode, String code, String time) throws ParseException {
        Map<String, String> jzTime = timeStr(enterpriseCode);
        String timeStr = jzTime.get("截止日期");
        String timeStr1 = jzTime.get("下一阶段的开始时间");
        time = time.trim();
        List<CollectValueVO> list = new ArrayList<>();
        if (time.compareTo(timeStr) >= 0) { //2020年数据
            list = enterpriseMapper.getCollectionValue(enterpriseCode, code);

        } else {
            //传unitid 核算单元id
            //code="510";
            Integer entID = getEntIdByenterpriseCode(enterpriseCode);
            list = enterpriseMapper.getCollectionValue1(entID, code);
        }


        return list;
    }

    @Override
    public InstrumentVO getInstrumentById(String id, String time) {
        Integer tiemStr = Integer.valueOf(time.trim().substring(0, 4));
        InstrumentVO instrumentVO = new InstrumentVO();
        if (tiemStr >= 2020) {
            instrumentVO = enterpriseMapper.getInstrumentById2020(id);
        } else {
            instrumentVO = enterpriseMapper.getInstrumentById2019(id);
        }
        return instrumentVO;
    }


    @Override
    public List<OutputValueVo> getUnitEnergyConsumption(String enterpriseCode, String year) {
        //本年
        if (year == null || "".equals(year)) {
            year = String.valueOf(Calendar.getInstance().get(Calendar.YEAR));
        }
        List<OutputValueVo> list = new ArrayList<OutputValueVo>();

        for (int i = 0; i <= 4; i++) {
            Integer tempYear = Integer.parseInt(year) - i;
            OutputValueVo vo = enterpriseMapper.getUnitEnergyConsumption(enterpriseCode, tempYear);
            if (vo == null) {
                vo = new OutputValueVo();
                vo.setRecordCircle(tempYear.toString());
            }
            list.add(vo);
        }

        if (list.size() > 0) { //查询的结果集大于0，进行排序
            list.stream().sorted(Comparator.comparing(OutputValueVo::getRecordCircle));
        }
        return list;
    }

    @Override
    public Map<String, Object> getExceptionInfo(String enterpriseCode, String time) {
        String startTime = time.split("&")[0];
        String endTime = time.split("&")[1];
        /*startTime=startTime.substring(0,7);
        endTime=endTime.substring(0,7);*/

        Map<String, Object> map = new HashMap<String, Object>();

        List<ExceptionInfoVo> e1 = enterpriseMapper.getExceptionInfo(enterpriseCode, startTime, endTime, "1"); //采集点未送数据
        map.put("list1", e1); //传输异常预警

        List<ExceptionInfoVo> results = enterpriseMapper.getExceptionInfo(enterpriseCode, startTime, endTime, "2"); //波动异常
        /*List<ExceptionInfoVo> e2 = enterpriseMapper.getExceptionInfo(enterpriseCode, startTime, endTime, "2"); //折标异常
        List<ExceptionInfoVo> e3 = enterpriseMapper.getExceptionInfo(enterpriseCode, startTime, endTime, "3"); //采集数值过大
        if (e2.size() > 0) {
            results.addAll(e2);
        }
        if (e3.size() > 0) {
            results.addAll(e3);
        }*/
        map.put("list2", results); //数据异常预警

        return map;
    }

    @Override
    public EnterpriseInfoVO getEnterpriseInfo(String enterpriseCode) {
        EnterpriseInfoVO evo = new EnterpriseInfoVO();
        evo = enterpriseMapper.selectInfoBycode(enterpriseCode);
        if (evo == null) {
            //去查old表
            evo = enterpriseMapper.selectInfoBycode1(enterpriseCode);
        }
        if (evo == null){
            //查询延期企业表
            evo = enterpriseMapper.selectInfoByAccess(enterpriseCode);
        }
        /*String addName = evo.getRegionCode().substring(0, 4);
        HashMap<String, String> areaAndIndustryCode = energyService.getAreaAndIndustryCode(addName, null);
        addName = addName.equals("5300") ? "云南省" : areaAndIndustryCode.get("地区");
        evo.setAddName(addName);*/
        return evo;
    }

    @Override
    public List<QuotaVO> getOrderByQuota(String addressCode, String enterpriseCode, String quotaName, String time) throws ParseException {
        HashMap<String, String> needTime = getNeedTime(time);
        String startTime = needTime.get("开始时间");
        String endTime = needTime.get("结束时间");
        Map<String, String> jzTime = timeStr(enterpriseCode);
        String timeStr = jzTime.get("截止日期");
        String timeStr1 = jzTime.get("下一阶段的开始时间");
        List<QuotaVO> list = new ArrayList<>();
        List<QuotaVO> list1 = new ArrayList<>();
        List<QuotaVO> list2 = new ArrayList<>();

        if (addressCode.trim().contains("0000")) {
            addressCode = addressCode.trim().substring(0, 2);
        } else if (addressCode.trim().length() > 4) {
            addressCode = addressCode.trim().substring(0, 4);
        }

        //查询企业屏蔽指标的月份
        List<QuotaShieldVo> quotaShieldList = enterpriseMapper.getQuotaShieldList(addressCode);
        List<QuotaShieldVo> newShieldList = new ArrayList<>();
        if (quotaShieldList != null && quotaShieldList.size() > 0) {
            for (QuotaShieldVo shieldVo : quotaShieldList) {
                String[] shieldArr = shieldVo.getShieldStr().split(",");
                if (shieldArr.length > 0) {
                    for (String shield : shieldArr) {
                        newShieldList.add(new QuotaShieldVo(shieldVo.getEnterpriseCode(), shield));
                    }
                }
            }
        }

        if (startTime.compareTo(timeStr1) >= 0) { //查询新平台数据
            list = enterpriseMapper.getOrderByQuota(addressCode, quotaName, startTime, endTime, newShieldList);
        } else if (endTime.compareTo(timeStr) <= 0) { //查询历史数据
            list = enterpriseMapper.getOrderByQuota1(addressCode, quotaName, startTime, endTime);
        } else {
            list1 = enterpriseMapper.getOrderByQuota(addressCode, quotaName, timeStr1, endTime, newShieldList);
            list2 = enterpriseMapper.getOrderByQuota1(addressCode, quotaName, startTime, timeStr);
            list.addAll(list1);
            list.addAll(list2);
        }
        String temp = "";
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                temp = list.get(i).getCode();
                for (int j = i + 1; j < list.size(); j++) {
                    if (temp.equals(list.get(j).getCode())) {
                        Float a = (list.get(i).getValue() + list.get(j).getValue()) / 2;
                        list.get(i).setValue(a);
                        list.remove(list.get(j));
                    }
                }

            }
        }
        //排序
        list.sort(Comparator.comparing(QuotaVO::getValue));
        for (int i = 0; i < list.size(); i++) {
            QuotaVO quotaVO = list.get(i);
            quotaVO.setSort(i + 1);
            quotaVO.setIndex(i + 1);
        }
        return list;
    }

    @Override
    public List<EnterpriseProcessVo> getIndexName(String enterpriseCode, String time) throws ParseException {
        ArrayList<EnterpriseProcessVo> list = new ArrayList<>();
        String startTime = "";
        String endTime = "";
        if (time.contains("&")) {
            HashMap<String, String> needTime = getNeedTime(time);
            startTime = needTime.get("开始时间");
            endTime = needTime.get("结束时间");
        } else {
            endTime = startTime = time;
        }

        Float sum = 0.0f;
        Map<String, String> jzTime = timeStr(enterpriseCode);
        String timeStr = jzTime.get("截止日期");
        String timeStr1 = jzTime.get("下一阶段的开始时间");
        if (endTime.compareTo(timeStr) <= 0) { //查询历史数据
            Integer entID = getEntIdByenterpriseCode(enterpriseCode);
            list = enterpriseMapper.getIndexName2019(entID);
        } else {
            list = enterpriseMapper.getIndexName2020(enterpriseCode);
            ArrayList<String> strings = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                EnterpriseProcessVo processVo = list.get(i);
                strings.add(processVo.getProcessCode());
            }
            if (!strings.contains("00")) {
                EnterpriseProcessVo process = new EnterpriseProcessVo("全厂", "00");
                list.add(0, process);
            }
        }
        /*else{
            list=enterpriseMapper.getIndexName2020(enterpriseCode);
            ArrayList<String> strings = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                EnterpriseProcessVo processVo = list.get(i);
                strings.add(processVo.getProcessCode());
            }
            if(!strings.contains("00")){
                EnterpriseProcessVo process = new EnterpriseProcessVo("全厂", "00");
                list.add(0,process);
            }

         *//*   Integer entID=getEntIdByenterpriseCode(enterpriseCode);

            list2=enterpriseMapper.getIndexName2019(entID);
            list.addAll(list1);
            list.addAll(list2);*//*
        }*/
        return list;
    }

    @Override
    public List<CoalVo> getDetailByDataCodeName(String enterpriseCode, String time, String dataCode) {
//        Float tag = enterpriseMapper.selectUpdateTag(enterpriseCode,time,dataCode);
        List<CoalVo> list = new ArrayList<>();
//        if(tag == null){
        //获取一下当前企业是否配置自定义结算周期。
        SettlementDataConfig settlementData = settlementDataConfigService.isCheckEntSettlement(enterpriseCode, "全厂", time);
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
        List<String> dayList = new ArrayList<>();
        if (null != settlementData){
            try {
                if(DateUtil.belongCalendar(new SimpleDateFormat("yyyy-MM").parse(time),
                        sdf2.parse(settlementData.getUseStartDate()),
                        sdf2.parse(settlementData.getUseEndDate()))
                && settlementDataConfigService.isCheckSettleMonth(settlementData,time)){
                    Map<String, String> customTime = DateUtil.getCustomTime(time, settlementData.getStartDate(),
                            settlementData.getEndDate(), settlementData.getIsMonth(),
                            settlementData.getCustomStartDate(), settlementData.getCustomEndDate());
                    String startTime = customTime.get("startDate");
                    String endTime = customTime.get("endDate");
                    //获取日期，用于判断数据是否缺失，取开始时间和结束时间
                    dayList = DateUtil.getBetweenDateStr(startTime,endTime);
                    list = enterpriseMapper.selectDetailByDataCodeNameAndSettlementDataConfig(enterpriseCode, dataCode, startTime, endTime);
                }else{
                    list = enterpriseMapper.selectDetailByDataCodeName(enterpriseCode, dataCode, time);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else{
            list = enterpriseMapper.selectDetailByDataCodeName(enterpriseCode, dataCode, time);
        }
        if (dayList.isEmpty()){
            dayList = DateUtil.getBetweenDateStr(DateUtil.getFirstDayOfMonth(time),DateUtil.getLastDayOfMonth(time));
        }
        //补全日期，将缺失的数据也补齐，用作前台折线图展示
        Map<String,String> CoalMap = new HashMap<>();
        for (CoalVo coalVo : list) {
            CoalMap.put(coalVo.getMonth(),coalVo.getValue());
        }
        for (String day : dayList){
            if (!CoalMap.containsKey(day)){
                CoalVo coalVo = new CoalVo(day,null);
                list.add(coalVo);
            }
        }
        list.sort(Comparator.comparing(CoalVo::getMonth));

        /*int days = getDays(time);
        List<String> monthList = new ArrayList<>();
        for (int i = 1; i <= days; i++) {
            monthList.add(time.substring(0,7)+(i<10?"-0":"-")+i);
        }
        list = enterpriseMapper.selectDetailByDataCodeName1(enterpriseCode, dataCode, monthList);*/
        /*Double total=0.00;
        for(int i=0;i<list.size();i++){
            total=total+Double.parseDouble(list.get(i).getValue());
        }//for end
        Double avg=total/list.size();
        DecimalFormat df=new DecimalFormat("#.0000");
        String str=df.format(avg);
        for(int j=0;j<list.size();j++){
            CoalVo coalVo=new CoalVo();
            coalVo.setMonth(list.get(j).getMonth());
            coalVo.setValue(str);
            list.set(j,coalVo);
        }//for end*/
        String unit= enterpriseMapper.selectUnit(dataCode.substring(10,14));
        CoalVo coalVo=new CoalVo();
        coalVo.setMonth("unit");
        coalVo.setValue(unit);
        //list.add(list.size(),coalVo);
//        }else {
//            list = enterpriseMapper.selectElectricityDetail(enterpriseCode,time);
//        }
        //return getAllDate(time, list);
//        List<CoalVo> coalVoList=getAllDate(time, list);
//        coalVoList.add(coalVoList.size(),coalVo);
        list.add(coalVo);
        return list;
    }

    /**
     * 月数据
     *
     * @param enterpriseCode
     * @param time
     * @param dataCode
     * @return
     */
    @Override
    public List<CoalVo> getDetailMonthByDataCodeName(String enterpriseCode, String time, String dataCode) {
        Calendar cal = Calendar.getInstance();
        List<String> monthList = new ArrayList<>();
        String yearTmp = cal.get(Calendar.YEAR)+"";
        int num = time.substring(0,4).equals(yearTmp) ? cal.get(Calendar.MONTH)+1 : 12;
        for(int i=1; i<=num; i++){
            monthList.add(time.substring(0,4)+(i<10?"-0":"-")+i);
        }
        //判断是否配置了自定义结算时间，这里参数是按年-月的参数传递的，直接按照年~月统计
        SettlementDataConfig settlementData = settlementDataConfigService.isCheckEntSettlement(enterpriseCode, "全厂", time);
        //根据配置的自定义结算时间，获取结算周期，并根据结算周期
        List<CoalVo> list = new ArrayList<>();
        if(null != settlementData){
            //根据获取到的时间，拼接结算时间，按照年份获取
            List<SettlementDataConfig> settlementConfigList = settlementDataConfigService.getSettleMonthByEnterpriseCode(enterpriseCode,time);
            List<Map<String,String>> params = new ArrayList<>();
            Boolean flag = true;
            for (String month : monthList) {
                String monthStr = month.substring(5, 7);
                String yearStr = month.substring(0, 4);
                for (SettlementDataConfig configInfo : settlementConfigList) {
                    //判断当前月份，是否处于结算周期，如果处于结算周期，则获取结算时间，否则获取默认结算时间
                    //判断配置的月份是否包含当前月份
                    if (configInfo.getMonth().contains(monthStr)) {
                        flag = false;
                        //获取月份
                        Map<String, String> settleStartAndEndDate = DateUtil.getCustomTime(month, configInfo.getStartDate(), configInfo.getEndDate(),
                                configInfo.getIsMonth(), configInfo.getCustomStartDate(), configInfo.getCustomEndDate());
                        settleStartAndEndDate.put("month", month);
                        params.add(settleStartAndEndDate);
                        break;
                    }
                }
                //如果当前月份没有匹配到自定义结算的时间，则取当月的第一天和最后一天结算
                if (flag){
                    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                    Map<String, String> settleStartAndEndDate = new HashMap<>();
                    YearMonth yearMonth = YearMonth.of(Integer.valueOf(yearStr), Integer.valueOf(monthStr));
                    String startDate = yearMonth.atDay(1).format(dtf);
                    String endDate = yearMonth.atEndOfMonth().format(dtf);
                    settleStartAndEndDate.put("startDate", startDate);
                    settleStartAndEndDate.put("endDate", endDate);
                    settleStartAndEndDate.put("month", month);
                    params.add(settleStartAndEndDate);
                }
            }

            list = enterpriseMapper.selectDetailByDataCodeName3(enterpriseCode,dataCode,params);
        }else{
            list = enterpriseMapper.selectDetailByDataCodeName1(enterpriseCode, dataCode, monthList);
        }
        //List<CoalVo> list = enterpriseMapper.selectDetailMonthByDataCodeName(enterpriseCode, dataCode, time);//已改

        //处理08-71/72 start
        String strCode01=dataCode.substring(8,10);
        String strCode02=dataCode.substring(14,16);
        if(strCode01.equals("08")&&(strCode02.equals("71")||strCode02.equals("72"))){
            if(!list.isEmpty()) {
                for (int k = 0; k < list.size(); k++) {
                    Double total =  Double.parseDouble(list.get(k).getValue());
                    Double avg = total / this.getDays(list.get(k).getMonth());
                    DecimalFormat df = new DecimalFormat("#.0000");
                    String str = df.format(avg);
                    list.get(k).setValue(str);
                }//for end
            }
        }//if end
        //处理08-71/72 end


//        int tag = enterpriseMapper.selectMonthUpdateTag(enterpriseCode,time,dataCode);//已改
//        List<CoalVo> list ;
//        //if(tag == null){
//        if(tag == 0){
//            list = enterpriseMapper.selectDetailMonthByDataCodeName(enterpriseCode,dataCode,time);//已改
//        }else {
//            list = enterpriseMapper.selectMonthElectricityDetail(enterpriseCode,time);//已改
//        }
        //return getAllDate(time, list);
         return this.dealCoalVoList(list);
    }//getDetailMonthByDataCodeName end


    public int getDays(String yearMonth){
        int year = Integer.parseInt(yearMonth.substring(0,4));
        int month = Integer.parseInt(yearMonth.substring(5,7));
        int result=1;
        switch (month){
            case 1:
            case 3:
            case 5:
            case 7:
            case 8:
            case 10:
            case 12:
                result=31;
                break;
            case 2:
                if(year%4==0 && year%100!=0 || year%400==0){
                    result=29;
                }else{
                    result=28;
                }
                break;
            case 4:
            case 6:
            case 9:
            case 11:
                result=30;
                break;
            default:
                break;
        }
        return result;
    }//getDays end

    public List<CoalVo> dealCoalVoList(List<CoalVo> list){
       DecimalFormat dec=new DecimalFormat("0.0000");
        for(int i=0;i<list.size();i++){
            if(!"-".equals(list.get(i).getValue())){
                Double value= Double.valueOf(list.get(i).getValue());
                list.get(i).setValue(dec.format(value));
            }
        }//for end
         return list;
    }//dealCoalVoList

    @Override
    public List<CoalVo> getDetailHaveOne(String enterpriseCode, String time, String dataCode) {
        Calendar cal = Calendar.getInstance();
        List<String> monthList = new ArrayList<>();
        String yearTmp = cal.get(Calendar.YEAR)+"";
        int num = time.substring(0,4).equals(yearTmp) ? cal.get(Calendar.MONTH)+1 : 12;
        for(int i=1; i<=num; i++){
            monthList.add(time.substring(0,4)+(i<10?"-0":"-")+i);
        }
        Float tag = enterpriseMapper.selectUpdateTag1(enterpriseCode, time, dataCode);
        List<CoalVo> list;
        if (tag == null) {
            list = enterpriseMapper.selectDetailByDataCodeName1(enterpriseCode, dataCode, monthList);
        } else {
            list = enterpriseMapper.selectElectricityDetail1(enterpriseCode, monthList);
        }
        String unit= enterpriseMapper.selectUnit(dataCode.substring(10,14));
        CoalVo coalVo=new CoalVo();
        coalVo.setMonth("unit");
        coalVo.setValue(unit);
        list.add(list.size(),coalVo);
        return list;
    }

    @Override
    public List<String> getyearshavada(String enterpriseCode, String dataCode) {
        Float tag = enterpriseMapper.selectUpdateTag2(enterpriseCode, dataCode);//
        List<String> list;
        if (tag == null) {
            list = enterpriseMapper.selectDetailByDataCodeName2(enterpriseCode, dataCode);
        } else {
            list = enterpriseMapper.selectElectricityDetail2(enterpriseCode);
        }
        return list;
    }

    @Override
    public List<CoalVo> sall(String enterpriseCode, String dataCode) {
//        Float tag = enterpriseMapper.selectUpdateTagall(enterpriseCode,dataCode);//
        List<CoalVo> list;
//        if(tag == null){
        list = enterpriseMapper.selectDetailByDataCodeNameall(enterpriseCode, dataCode);
//        }else {
//            list = enterpriseMapper.selectElectricityDetailall(enterpriseCode);
//        }
        return list;
    }

    @Override
    public String stattype(String enterpriseCode, String dataCode) {
        String stattp = enterpriseMapper.getstatType(enterpriseCode, dataCode);
        return stattp;
    }

    @Override
    public R isSuper(String enterpriseCode) {
        Boolean resultBoolean = null;
        List<CoalVo> list = null;
        if ("".equals(enterpriseCode) || enterpriseCode == null) {
            return R.ok("enterpriseCode is null !!!");
        } else {
            List<String> superEnterpriseList = enterpriseMapper.getSuperEnterpriseList();
            resultBoolean = superEnterpriseList.contains(enterpriseCode);
        }
        if (resultBoolean) {
            list = enterpriseMapper.selectTreeEpc(enterpriseCode);
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("isSuper", resultBoolean);
        map.put("treeList", list);
        return R.ok(map);
    }

    @Override
    public R superTotal(String enterpriseCode, String time) {
        // 首先判断是否为集团 若为集团 则先查询出子企业列表
        List<String> epcList = getSuperEpcList(enterpriseCode);
        HashMap<String, String> needTime = getNeedTime(time);
        String beginTime = needTime.get("开始时间");
        String endTime = needTime.get("结束时间");
        if (epcList.size() > 0) {
            Float total = enterpriseMapper.superTotal(epcList, beginTime, endTime);
            return R.ok(total);
        } else {
            return R.ok(0.0);
        }
    }

    @Override
    public R superEnergyKinds(String enterpriseCode, String time) {
        HashMap<String, String> needTime = getNeedTime(time);
        String beginTime = needTime.get("开始时间");
        String endTime = needTime.get("结束时间");
        List<String> superEpcList = getSuperEpcList(enterpriseCode);
        if (superEpcList.size() > 0) {
            List<StringAndFolat> list = enterpriseMapper.superEnergyKinds(superEpcList, beginTime, endTime);
            if (list.size() > 0) {
                StringAndFolat coalNewVo = new StringAndFolat("煤", 0.0f);
                for (int i = 0; i < list.size(); i++) {
                    StringAndFolat coalVo = list.get(i);
                    String key = coalVo.getMonth();
                    Float value = coalVo.getValue();
                    if (key.endsWith("煤")) {
                        coalNewVo.setValue(coalNewVo.getValue() + (value == null ? 0 : value));
                        list.remove(i);
                        i--;
                    }
                }
                list.add(0, coalNewVo);
            }
            return R.ok(list);
        } else {
            return R.ok(null, "暂无数据");
        }
    }

    @Override
    public R superElectricConsume(String enterpriseCode, String time) {
        HashMap<String, String> needTime = getNeedTime(time);
        String beginTime = needTime.get("开始时间");
        String endTime = needTime.get("结束时间");
        List<String> superEpcList = getSuperEpcList(enterpriseCode);
        // 查询在线监测电力
        List<StringAndFolat> listCollect = enterpriseMapper.superElectricConsume(superEpcList, beginTime, endTime);
        // 查询电网公司电力消耗
        List<StringAndFolat> listCollectElectric = enterpriseMapper.superElectricConsumeCompany(superEpcList, beginTime, endTime);

        HashMap<String, Float> mapCollect = new HashMap<>();
        HashMap<String, Float> mapElectric = new HashMap<>();
        for (int i = 0; i < listCollect.size(); i++) {
            mapCollect.put(listCollect.get(i).getMonth(), listCollect.get(i).getValue());
        }
        for (int i = 0; i < listCollectElectric.size(); i++) {
            mapElectric.put(listCollectElectric.get(i).getMonth(), listCollectElectric.get(i).getValue());
        }
        ArrayList<StringAndFolat> stringAndCollect = new ArrayList<>();
        ArrayList<StringAndFolat> stringAndElectric = new ArrayList<>();
        for (int i = 1; i <= 12; i++) {
            String base = time.substring(0, 4);
            if (i < 10) {
                base = base + "-0" + i;
            } else {
                base = base + "-" + i;
            }
            stringAndCollect.add(new StringAndFolat(base, mapCollect.get(base)));
            stringAndElectric.add(new StringAndFolat(base, mapElectric.get(base)));
        }
        HashMap<String, List> stringListHashMap = new HashMap<>();
        stringListHashMap.put("在线监测", stringAndCollect);
        stringListHashMap.put("电网公司", stringAndElectric);
        return R.ok(stringListHashMap);
    }

    @Override
    public R superCollectData(String enterpriseCode, String time) {
        HashMap<String, String> needTime = getNeedTime(time);
        String beginTime = needTime.get("开始时间");
        String endTime = needTime.get("结束时间");
        List<String> superEpcList = getSuperEpcList(enterpriseCode);
        //查询总计量器具个数，总采集点个数
        Integer collectNum = enterpriseMapper.getCollectNum(superEpcList);
        Integer toolNum = enterpriseMapper.getToolNum(superEpcList);
        Integer exceptionNum = enterpriseMapper.exceptionNum(superEpcList, beginTime, endTime);
        HashMap<String, Integer> stringIntegerHashMap = new HashMap<>();
        stringIntegerHashMap.put("采集点", collectNum);
        stringIntegerHashMap.put("计量器具", toolNum);
        stringIntegerHashMap.put("异常个数", exceptionNum);
        return R.ok(stringIntegerHashMap);
    }

    @Override
    public R superProduct(String enterpriseCode, String time) {
        List<String> superEpcList = getSuperEpcList(enterpriseCode);
        // 查询企业产品 产量编码信息
        HashMap<String, SuperProductInfoBo> map = new HashMap<>();
        ArrayList<CoalVo> productList = new ArrayList<>();
        ArrayList<SuperProductVo> superProductVos = new ArrayList<>();
        for (int i = 0; i < superEpcList.size(); i++) {
            String epc = superEpcList.get(i);
            List<SuperProductInfoBo> infos = enterpriseMapper.selectSuperProductInfo(epc);
            if (infos != null) {
                for (int j = 0; j < infos.size(); j++) {
                    SuperProductInfoBo info = infos.get(j);
                    map.put(info.getEnterpriseCode() + info.getProductId(), info);
                    CoalVo coalVo = new CoalVo(info.getProductId(), info.getProductName());
                    if (!productList.contains(coalVo)) {
                        productList.add(coalVo);
                    }
                }
            }
        }
        HashMap<String, String> needTime = getNeedTime(time);
        String beginTime = needTime.get("开始时间");
        String endTime = needTime.get("结束时间");
        // 遍历产品列表
        for (int i = 0; i < productList.size(); i++) {
            CoalVo coalVo = productList.get(i);
            String productId = coalVo.getMonth();
            String productName = coalVo.getValue();
            Float productValue = 0.0f;
            SuperProductVo superProductVo = new SuperProductVo();
            ArrayList<CoalVo> coalVos = new ArrayList<>();
            String unit = null;
            for (int j = 0; j < superEpcList.size(); j++) {
                String epc = superEpcList.get(j);
                SuperProductInfoBo superProductInfoBo = map.get(epc + productId);
                if (superProductInfoBo != null && productId.equals(superProductInfoBo.getProductId())) {
                    // 查询该企业在所选时间段的产品产量
                    String dataCode = superProductInfoBo.getDataCode();
                    Float epcTotal = enterpriseMapper.selectProductValue(epc, dataCode, beginTime, endTime);
                    if (epcTotal == null) {
                        epcTotal = 0.0f;
                    }
                    CoalVo coalVo1 = new CoalVo(superProductInfoBo.getCmpName(), String.valueOf(epcTotal));
                    productValue = productValue + epcTotal;
                    coalVos.add(coalVo1);
                    unit = superProductInfoBo.getUnit();
                }
            }
            superProductVo.setId(productId);
            superProductVo.setName(productName);
            superProductVo.setUnit(unit);
            superProductVo.setTotal(productValue);
            superProductVo.setList(coalVos);
            superProductVos.add(superProductVo);
        }
        return R.ok(superProductVos);
    }

    @Override
    public R superProductValueOut(String enterpriseCode, String time) {
        List<String> superEpcList = getSuperEpcList(enterpriseCode);
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        int preYear = year - 5;
        ArrayList<CoalVo> coalVos = new ArrayList<>();
        for (int i = preYear; i <= year; i++) {
            CoalVo coalVo = enterpriseMapper.superProductValueOut(superEpcList, String.valueOf(i));
            if (coalVo != null) {
                String value = coalVo.getValue();
                Float newValue = Float.valueOf(value) / (superEpcList.size());
                coalVo.setValue(String.valueOf(newValue));
            }
            coalVos.add(coalVo);
        }
        return R.ok(coalVos);
    }


    @Override
    public R superExceptionList(String enterpriseCode, String time, Page page, Integer type, String collectName, String state) {
        String beginTime = null;
        String endTime = null;
        if (time != null && !"".equals(time)) {
            beginTime = time.split("/")[0];
            endTime = time.split("/")[1];
        } else {
            return R.failed("请输入查询时间范围！");
        }
        List<String> superEpcList = getSuperEpcList(enterpriseCode);
        IPage page1 = enterpriseMapper.getSuperExceptionList(page, superEpcList, beginTime, endTime, type, collectName, state);
        return R.ok(page1);
    }

    private List<String> getSuperEpcList(String enterpriseCode) {
        List<String> epcList = enterpriseMapper.getSonEpcList(enterpriseCode);
        epcList.add(0, enterpriseCode);
        return epcList;
    }


    public List<CoalVo> getAllDate(String time, List<CoalVo> list) {
        HashMap<String, String> stringStringHashMap = new HashMap<>();
        ArrayList<CoalVo> resultList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            CoalVo coalVo = list.get(i);
            stringStringHashMap.put(coalVo.getMonth(), coalVo.getValue());
        }
        String month = time.substring(5);
        Integer day = getInteger(month);
        String newTime;
        for (int i = 1; i <= day; i++) {
            if (i < 10) {
                newTime = time + "-0" + i;
            } else {
                newTime = time + "-" + i;
            }
            resultList.add(new CoalVo(newTime, stringStringHashMap.get(newTime)));
        }
        return resultList;
    }

    public Integer getInteger(String month) {
        Integer day = 31;
        Integer integer = Integer.valueOf(month);
        if (integer == 4 || integer == 6 || integer == 9 || integer == 11) {
            day = 30;
        } else if (integer == 2) {
            day = 28;
        }
        return day;
    }


    /**
     * @Description: 通过enterpriseCode查询entid
     * @Param: [enterpriseCode]
     * @return: java.lang.Integer
     * @Author: zfw
     * @Date: 2020/12/28
     * @Date: 14:01
     */
    public Integer getEntIdByenterpriseCode(String enterpriseCode) {

        Integer entId = enterpriseMapper.getEntId(enterpriseCode);
        return entId;
    }

    /**
     * @Description: 返回企业新老系统的截止时间 (数据库得到的时间需要处理  timeStr  计算在后面的区间中 所有需要 -1)
     * @Param: [enterpriseCode]
     * @return: java.lang.Integer
     * @Author: zfw
     * @Date: 2021/1/16
     * @Date: 16:20
     */
    public Map<String, String> timeStr(String enterpriseCode) throws ParseException {
        Map<String, String> map = new HashMap<>();
        String timeStr = enterpriseMapper.getEndTime(enterpriseCode);
        //下一阶段的开始时间
        //String starTime = timeStr;
        /*String time21 = timeStr.substring(0, 5);
        String time22 = "";
        Integer num1 = Integer.valueOf(timeStr.substring(5, 7));
        Integer num2 = num1 - 1;
        if (num2.toString().length() == 1) {
            time22 = "0" + num2.toString();
        } else {
            time22 = num2.toString();
        }
        //截止日期
        String end = time21 + time22;*/
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        Calendar calBegin = Calendar.getInstance();
        calBegin.setTime(sdf.parse(timeStr));
        calBegin.add(Calendar.MONTH, -1);
        String end = sdf.format(calBegin.getTime());
        map.put("截止日期", end);
        map.put("下一阶段的开始时间", timeStr);
        return map;
    }

    /**
     * @Description: 处理时间
     * @Param: [time]
     * @return: java.util.HashMap<java.lang.String, java.lang.String>
     * @Author: zfw
     * @Date: 2021/1/16
     * @Date: 17:03
     */
    public HashMap<String, String> getNeedTime(String time) {
        HashMap<String, String> stringStringHashMap = new HashMap<>();
        String[] timeSplit = time.split("&");
        String startTime = timeSplit.length >= 1 ? timeSplit[0] : "2021-01-01";
        String endTime = timeSplit.length >= 2 ? timeSplit[1] : startTime;
        startTime = startTime.substring(0, 7);
        endTime = "".equals(endTime) ? startTime : endTime.substring(0, 7);
        String timeStr = startTime.substring(0, 4);
        stringStringHashMap.put("时间期限", timeStr);
        stringStringHashMap.put("开始时间", startTime);
        stringStringHashMap.put("结束时间", endTime);
        return stringStringHashMap;
    }

    @Override
    public List<OldEnergyDataVo> getOldDataByEpc(String enterpriseCode,String time) {
        return enterpriseMapper.getOldDataByEpc(enterpriseCode,time);
    }

    @Override
    public List<String> getEpcById(String enterpriseCode) {
        return enterpriseMapper.getEpcById(enterpriseCode);
    }

    @Override
    public Map<String,Object> getEnterpriseStatusChange(String enterpriseCode) {
        List<String> remark = new ArrayList<>();
        Map<String,Object> map = new HashMap<>();
        String haltType = "";

        EnterpriseHaltVo haltVo = haltMapper.getHaltCompanyByCode( enterpriseCode);
        String haltStartTime = haltVo != null ? haltVo.getStartTime() : "";
        if(StringUtils.isNotEmpty(haltStartTime)){ //企业停产
            haltType = "1";
            map.put("haltDate",haltStartTime+"至今");
        }else{
            haltType = "0";
            map.put("haltDate","");
        }

        float ratio = 5.0f;
        if("1".equals(haltType)){ //企业停产中，判断是否恢复生产
            //根据综合能耗判断
            Map<String, String> tceMap = enterpriseMapper.getTceStatusChange(haltStartTime, enterpriseCode);
            if(tceMap != null && Double.parseDouble(tceMap.get("ratio")) > ratio){
                remark.add("综合能耗指标值升高");
            }
            //根据电力数据判断
            List<Map<String, String>> eleMap = enterpriseMapper.getEleStatusChange(haltStartTime, enterpriseCode);
            if(eleMap != null && eleMap.size()>0 && Double.parseDouble(eleMap.get(0).get("ratio")) > ratio){
                remark.add("电力消耗升高");
            }
            //根据企业产品数据判断
            List<Map<String, String>> productMap = enterpriseMapper.getProductStatusChange(haltStartTime, enterpriseCode);
            if(productMap != null && productMap.size() > 0 && Double.parseDouble(productMap.get(0).get("ratio")) > ratio){
                remark.add("产品产量升高");
            }
        }else{ //企业正常生产中，判断是否停产（取近2个月数据判断）
            Calendar cal = Calendar.getInstance();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
            /*int day = cal.get(Calendar.DAY_OF_MONTH);
            if(day >= 5){
                cal.add(Calendar.MONTH, -1);
            }else{
                cal.add(Calendar.MONTH, -2); //数据自动结算以前
            }*/
            cal.add(Calendar.MONTH, -1);
            String endDate = sdf.format(cal.getTime());
            cal.add(Calendar.MONTH, -1);
            String startDate = sdf.format(cal.getTime());
            //根据综合能耗判断
            Map<String, String> tceMap = enterpriseMapper.getTceStatusChange2(startDate, endDate, enterpriseCode);
            if(tceMap != null && Double.parseDouble(tceMap.get("ratio")) > ratio){
                remark.add("综合能耗指标值下降");
            }
            //根据电力数据判断
            List<Map<String, String>> eleMap = enterpriseMapper.getEleStatusChange2(startDate, endDate, enterpriseCode);
            if(eleMap != null && eleMap.size()>0 && Double.parseDouble(eleMap.get(0).get("ratio")) > ratio){
                remark.add("电力消耗下降");
            }
            //根据企业产品数据判断
            List<Map<String, String>> productMap = enterpriseMapper.getProductStatusChange2(startDate, endDate, enterpriseCode);
            if(productMap != null && productMap.size() > 0 && Double.parseDouble(productMap.get(0).get("ratio")) > ratio){
                remark.add("产品产量下降");
            }
        }

        map.put("haltType",haltType);
        map.put("remark",remark);
        return map;
    }

    @Override
    public Object saveEnterpriseState(EnterpriseState enterpriseState) {
        return null;
    }



    @Override
    public R<List<StructureDescVo>> getMaterielProductByMonthListDesc(String enterpriseCode, String time) throws ParseException {
        String startTime = time.split("&")[0].substring(0, 7);
        String endTime = time.split("&")[1].substring(0, 7);
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        calendar.setTime(sdf.parse(startTime));
        List<String> dateList = new ArrayList<>();
        dateList.add(startTime);
        while (sdf.parse(endTime).after(calendar.getTime())) {
            calendar.add(Calendar.MONTH, 1);
            dateList.add(sdf.format(calendar.getTime()));
        }

        List<String> newProduct = new ArrayList<>();
        Map<String, List<StructureVo>> newProductValue = new HashMap<>();
        Map<String, Object> map = new HashMap<>();
        List<MaterialVo> materielProduct = enterpriseMapper.selectMaterielProduct(enterpriseCode);
        HashMap<String,Float>  total = new HashMap<>();
        if (materielProduct != null && materielProduct.size() > 0) {
            for (MaterialVo product : materielProduct) {
                Float totalNum = 0f;
                List<StructureVo> pruductNum = new ArrayList<>();
                if("04".equals(product.getType())){ //非能源类产品
                    String outPut = enterpriseMapper.getProductOutPutCode(enterpriseCode, product.getCode());//产品产量编码
                    String consumption = enterpriseMapper.getProductConsumptionCode(enterpriseCode, product.getCode());//产品消耗量编码
                    pruductNum = enterpriseMapper.selectMaterielProductValue(enterpriseCode, outPut, consumption, product.getUnit(), dateList);
                    for (StructureVo structureVo : pruductNum) {
                        if (StringUtils.isNotBlank(structureVo.getValue())){
                            totalNum += Float.valueOf(structureVo.getValue());
                        }
                        if (StringUtils.isNotBlank(structureVo.getConsumption())){
                            totalNum += Float.valueOf(structureVo.getConsumption());
                        }
                    }
                }else{ //能源类产品
                    pruductNum = enterpriseMapper.selectEnergyProductValue(enterpriseCode, product.getCode(), product.getUnit(), dateList);
                    for (StructureVo structureVo : pruductNum) {
                        if (StringUtils.isNotBlank(structureVo.getValue())){
                            totalNum += Float.valueOf(structureVo.getValue());
                        }
                        if (StringUtils.isNotBlank(structureVo.getConsumption())){
                            totalNum += Float.valueOf(structureVo.getConsumption());
                        }
                    }
                }
                if(StringUtils.isNotEmpty(product.getName())){
                    String productName = StringUtils.isNotEmpty(product.getCategory()) ? product.getName()+"("+product.getCategory()+")": product.getName();
                    newProduct.add(productName);
                    newProductValue.put(productName, pruductNum);
                    total.put(productName,totalNum);
                }

            }
        } else {
            return R.failed("企业没有产品!");
        }

        List<Map.Entry<String, Float>> list = new ArrayList<>(total.entrySet());
        Collections.sort(list, new Comparator<Map.Entry<String, Float>>() {
            @Override
            public int compare(Map.Entry<String, Float> o1, Map.Entry<String, Float> o2) {
                return o2.getValue().compareTo(o1.getValue());
            }
        });
        List<String> newProduct1 = new ArrayList<>();
        LinkedHashMap<String, Float> sortedMap = new LinkedHashMap<>();
        List<StructureDescVo> descVo = new ArrayList<>();
        for (int i = 0; i < Math.min(3, list.size()); i++) {
            Map.Entry<String, Float> entry = list.get(i);
            sortedMap.put(entry.getKey(), entry.getValue());
            newProduct1.add(entry.getKey());
        }
        for (int i = 0; i < newProduct1.size(); i++) {
            if (i == 0){
                //第一个
                List<StructureVo> structureVos = newProductValue.get(newProduct1.get(i));
                for (StructureVo structureVo : structureVos) {
                    StructureDescVo structureDescVo = new StructureDescVo();
                    structureDescVo.setName(newProduct1.get(i));
                    structureDescVo.setMonth(structureVo.getMonth());
                    structureDescVo.setValue(structureVo.getValue());
                    structureDescVo.setUnit(structureVo.getUnit());
                    structureDescVo.setConsumption(structureVo.getConsumption());
                    descVo.add(structureDescVo);
                }
            }
            if (i == 1){
                //第二个
                List<StructureVo> structureVos = newProductValue.get(newProduct1.get(i));
                if (descVo.size() == structureVos.size()){
                    for (int j = 0; j < descVo.size(); j++) {
                        descVo.get(j).setName1(newProduct1.get(i));
                        descVo.get(j).setValue1(structureVos.get(j).getValue());
                        descVo.get(j).setConsumption1(structureVos.get(j).getConsumption());
                        descVo.get(j).setUnit1(structureVos.get(j).getUnit());
                    }
                }
            }
            if (i == 2){
                //第三个
                List<StructureVo> structureVos = newProductValue.get(newProduct1.get(i));
                if (descVo.size() == structureVos.size()){
                    for (int j = 0; j < descVo.size(); j++) {
                        descVo.get(j).setName2(newProduct1.get(i));
                        descVo.get(j).setValue2(structureVos.get(j).getValue());
                        descVo.get(j).setConsumption2(structureVos.get(j).getConsumption());
                        descVo.get(j).setUnit2(structureVos.get(j).getUnit());
                    }
                }
            }
        }


//        map.put("name", newProduct1);
//        map.put("value", newProductValue1);

        return R.ok(descVo);
    }



    @Override
    public List<Map<String,String>> getEnergyTypeByProcedure(String enterpriseCode, String baseCode, String time, String energyUseType, String configureName,String configureCode) throws ParseException{

        String startTime = time.trim();
        Map<String, String> jzTime = timeStr(enterpriseCode);
        String timeStr = jzTime.get("截止日期");
        time = time.trim();
        List<Map<String,String>> list = new ArrayList<>();
        if (time.compareTo(timeStr) >= 0) { //2020年数据
            list = enterpriseMapper.getEnergyTypeByProcedure(enterpriseCode, startTime,energyUseType, configureName,configureCode);
        } else {
            Integer entID = getEntIdByenterpriseCode(enterpriseCode);
            list = enterpriseMapper.getEnergyTypeByProcedure1(entID, time);
        }
        return list;
    }

    @Override
    public int updateDianliFlag(String dianliFlag, String enterpriseCode) {
        return enterpriseMapper.updateDianliFlag(dianliFlag,enterpriseCode);
    }



}

