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


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.nantian.cloud.dbcapp.mapper.jly.EnergyInfoMapper;
import org.apache.commons.lang.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nantian.cloud.dbcapp.dto.ConditionBo;
import com.nantian.cloud.dbcapp.mapper.record.ElectricityMapper;
import com.nantian.cloud.dbcapp.mapper.record.EnergyMapper;
import com.nantian.cloud.dbcapp.service.EnergyService;
import com.nantian.cloud.dbcapp.tool.AreaCode;
import com.nantian.cloud.dbcapp.tool.IndustryCode;
import com.nantian.cloud.dbcapp.unit.CheckoutUtil;
import com.nantian.cloud.dbcapp.unit.TreeVoUtil;
import com.nantian.cloud.dbcapp.vo.*;
import com.nantian.sc.cloud.common.core.util.R;
import com.nantian.sc.cloud.common.data.datascope.DataScope;
import com.nantian.sc.cloud.common.security.service.ScUser;
import com.nantian.sc.cloud.common.security.util.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ForkJoinPool;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static java.util.regex.Pattern.compile;


/**
 * <p>
 * 综合能耗 服务实现类
 * </p>
 *
 * @author zfw
 * @since 2020-08-05
 */
@Service("energyService")
@Transactional
public class EnergyServiceImpl implements EnergyService {

    @Autowired
    private EnergyMapper energyMapper;

    @Autowired
    private AreaCode areaCode;

    @Autowired
    private IndustryCode industryCode;

    @Autowired
    CheckoutUtil checkoutUtil;

    @Autowired
    EnterpriseServiceImpl enterpriseService;

    @Autowired
    TreeVoUtil treeVoUtil;

    @Autowired
    private ElectricityMapper electricityMapper;
    @Autowired
    private EnergyInfoMapper energyInfoMapper;

    /*@Autowired
    private FeignMvService mvService;*/

    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");
    }

    /**
     * @Description: 根据不同的条件查询综合能耗
     * @Param: [area, industry, time]
     * @return: java.lang.Float
     * @Author: zfw
     * @Date: 2020/12/26
     * @Date: 15:00
     */
    @Override
    public Float getTotal(String area, String industry, String time) {
        //time="2019-01-01&2020-12-01";
        //截取时间
        String startTime = null;
        String endTime = null;
        if (time.contains("&")) {
            startTime = time.split("&")[0];
            endTime = time.split("&")[1];
            startTime = startTime.substring(0, 7);
            endTime = endTime.substring(0, 7);

        }
        //匹配地区 昆明市、曲靖市、玉溪市、昭通市、丽江市、普洱市、保山市、临沧市、楚雄州、红河州、迪庆州、文山州、西双版纳州、大理州、德宏州、怒江州
        HashMap<String, String> areaAndIndustryCode = getAreaAndIndustryCode(area, industry);
        String areaCode = (area.trim().equals("53") || area.trim().equals("云南")) ? "53" : areaAndIndustryCode.get("地区");
        int code = Integer.parseInt(areaCode);
        String inde1 = industry.trim().equals("全部") ? null : areaAndIndustryCode.get("行业");
        List<String> companyList = new ArrayList<>();
        Float sum = 0.0f;
        if (Integer.valueOf(startTime.substring(0, 4)) >= 2020) { //查询2020年
            companyList = energyMapper.getAllCompanyList2020(code, inde1);
            if (companyList != null & companyList.size() > 0) {
                sum = energyMapper.getInfo2020(companyList, startTime, endTime);
            } else {
                sum = 0.0f;
            }
        } else if (Integer.valueOf(endTime.substring(0, 4)) < 2020) {//查询2019年
            companyList = energyMapper.getAllCompanyList2019(code, inde1, null);
            if (companyList.size() > 0 && companyList != null) {
                sum = energyMapper.getInfo2019(companyList, area, industry, startTime, endTime);
            }
        } else {//跨年查询
            String timeStr1 = "2019-12";
            String timeStr2 = "2020-01";
            Float sum1 = 0.0f;
            Float sum2 = 0.0f;
            //19年数据
            companyList = energyMapper.getAllCompanyList2019(code, inde1, null);
            if (companyList.size() > 0 && companyList != null) {
                sum1 = energyMapper.getInfo2019(companyList, area, industry, startTime, timeStr1);
            }
            //20年数据
            companyList = energyMapper.getAllCompanyList2020(code, inde1);
            if (companyList != null & companyList.size() > 0) {
                sum2 = energyMapper.getInfo2020(companyList, timeStr2, endTime);
            } else {
                sum2 = 0.0f;
            }
            sum = sum1 + sum2;
        }
        if (sum == null) {
            sum = 0f;
        }
        //sum = sum / 10000; //在sql中进行了处理
        return sum;
    }


    public Map<String,String> getTotalDetail(String area, String industry, String date) {
        //date  "2019-01";
        //截取时间
        String startTime = date.substring(0,4);
        Map<String,String> map = new HashMap<>();
        //匹配地区和行业
        HashMap<String, String> areaAndIndustryCode = getAreaAndIndustryCode(area, industry);
        String areaCode = (area.trim().equals("53") || area.trim().equals("云南")) ? "53" : areaAndIndustryCode.get("地区");
        String industryCode = industry.trim().equals("全部") ? null : areaAndIndustryCode.get("行业");
        if (Integer.valueOf(startTime) >= 2020) { //查询2020年以后，走新表
            map = energyMapper.getDetail(areaCode, industryCode, date);
        } else { //查询2020年以前，走老表
            map = energyMapper.getDetailOld(areaCode, industryCode, date);
        }
        return map;
    }

    /**
     * @Description: 按照地区查询用能单位
     * @Param: [area, industry, time]
     * @return: java.util.List<java.util.Map < java.lang.String, java.lang.String>>
     * @Author: zfw
     * @Date: 2020/12/26
     * @Date: 15:43
     */
    @Override
    public JSONArray getCompanyByArea(String area, String industry, String time) {
        HashMap<String, String> areaAndIndustryCode = getAreaAndIndustryCode(area, industry);
        String areaCode = (area.trim().equals("53") || area.trim().equals("云南")) ? "53" : areaAndIndustryCode.get("地区");
        Integer code = Integer.parseInt(areaCode);
        String inde1 = industry.trim().equals("全部") ? null : areaAndIndustryCode.get("行业");
        JSONArray jsonArray = new JSONArray();
        //截取时间
        String startTime = null;
        String endTime = null;
        if (time.contains("&")) {
            startTime = time.split("&")[0];
            endTime = time.split("&")[1];
            startTime = startTime.substring(0, 7);
            endTime = endTime.substring(0, 7);
        }
        Integer timeStr = Integer.valueOf(startTime.substring(0, 4));
        if (timeStr >= 2020) {
            List<CompanyVO> list = new ArrayList<>();
            List<CompanyVO> listZS = new ArrayList<>();
            if (code == 53) {
                //首先查出州市名称
                listZS = energyMapper.getCompanyByAreaZS2020(area, time);
                if (inde1 == null) {
                    list = listZS;
                } else {
                    list = energyMapper.getCompanyByAreaAll2020(area, inde1, time);
                    //循环吧list里面的加到listZS里面
                    if (list != null && list.size() > 0) {
                        for (int i = 0; i < listZS.size(); i++) {//循环得到的数字
                            listZS.get(i).setValue(0);
                            for (int j = 0; j < list.size(); j++) {
                                if (listZS.get(i).getName().equals(list.get(j).getName())) {
                                    listZS.get(i).setValue(list.get(j).getValue());
                                }
                            }
                        }
                    }
                }
                list = listZS;
                List<CompanyVO> addList = energyMapper.getCompanyNum00("%00", inde1);
                for (int i = 0; i < addList.size(); i++) {
                    CompanyVO companyVO = addList.get(i);
                    for (int j = 0; j < list.size(); j++) {
                        CompanyVO companyVO1 = list.get(j);
                        if (companyVO1.getName().equals(companyVO.getName())) {
                            companyVO1.setValue(companyVO1.getValue() + companyVO.getValue());
                        }
                    }
                }
            } else {//查询州市
                //区县名称
                listZS = energyMapper.getCompanyByAreaQX2020(code.toString() + "00");
                if (inde1 == null) {
                    list = listZS;
                } else {
                    list = energyMapper.getCompanyByAreaAllQX2020(code.toString() + "00", inde1);
                    //循环吧list里面的加到listZS里面
                    if (list != null && list.size() > 0) {
                        for (int i = 0; i < listZS.size(); i++) {//循环得到的数字
                            listZS.get(i).setValue(0);
                            for (int j = 0; j < list.size(); j++) {
                                if (listZS.get(i).getName().equals(list.get(j).getName())) {
                                    listZS.get(i).setValue(list.get(j).getValue());
                                }
                            }
                        }
                    }
                    list = listZS;
                }

            }
            if (list != null && list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    JSONObject jo = new JSONObject();
                    jo.put("name", list.get(i).getName());
                    jo.put("value", list.get(i).getValue());
                    jsonArray.add(jo);
                }

            }

        } else {

            List<CompanyVO> list = new ArrayList<>();
            List<CompanyVO> listZS = new ArrayList<>();
            if (code == 53) {
                //首先查出州市名称
                listZS = energyMapper.getCompanyByAreaZS(area, time);
                if (inde1 == null) {
                    list = listZS;
                } else {
                    list = energyMapper.getCompanyByAreaAll(area, inde1, time);
                    //循环吧list里面的加到listZS里面
                    if (list != null && list.size() > 0) {
                        for (int i = 0; i < listZS.size(); i++) {//循环得到的数字
                            listZS.get(i).setValue(0);
                            for (int j = 0; j < list.size(); j++) {
                                if (listZS.get(i).getName().equals(list.get(j).getName())) {
                                    listZS.get(i).setValue(list.get(j).getValue());
                                }
                            }
                        }
                    }
                }
                list = listZS;
                // 查询市属企业数量
            } else {//查询州市
                //区县名称
                listZS = energyMapper.getCompanyByAreaQX(code.toString() + "00");
                if (inde1 == null) {
                    list = listZS;
                } else {
                    list = energyMapper.getCompanyByAreaAllQX(code.toString() + "00", inde1);
                    //循环吧list里面的加到listZS里面
                    if (list != null && list.size() > 0) {
                        for (int i = 0; i < listZS.size(); i++) {//循环得到的数字
                            listZS.get(i).setValue(0);
                            for (int j = 0; j < list.size(); j++) {
                                if (listZS.get(i).getName().equals(list.get(j).getName())) {
                                    listZS.get(i).setValue(list.get(j).getValue());
                                }
                            }
                        }
                    }
                    list = listZS;
                }
            }
            if (list != null && list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    JSONObject jo = new JSONObject();
                    jo.put("name", list.get(i).getName());
                    jo.put("value", list.get(i).getValue());
                    jsonArray.add(jo);
                }

            }
        }
        return jsonArray;
    }

    @Override
    public JSONArray getConsumption(String area, String industry, String time) throws ParseException {
        //截取时间
        String startTime = null;
        String endTime = null;
        if (time.contains("&")) {
            startTime = time.split("&")[0];
            endTime = time.split("&")[1];
            startTime = startTime.substring(0, 7);
            endTime = endTime.substring(0, 7);
        }
        Integer timeStr = Integer.valueOf(startTime.substring(0, 4));
        Integer timeStr1 = Integer.valueOf(endTime.substring(0, 4));
        Map<String, Double> map = new HashMap<>();
        JSONArray jsonArray = new JSONArray();

        //得到企业id
        List<String> companyList = companyList(area, industry, time);
        Float total = getTotal(area, industry, time);
        HashMap<String, Double> stringDoubleHashMap = new HashMap<>();
        DecimalFormat df = new DecimalFormat(".0000"); //保留4位小数
        if (timeStr >= 2020) {
            //2020年能耗数据
            Double sum = getConsumption2020(area, industry, time, startTime, endTime, stringDoubleHashMap, df);
            // list.sort(Comparator.comparing(KeyValueVO::getValue).reversed());

        } else if (timeStr1 < 2020) { //2019
            if (companyList != null && companyList.size() > 0) {
                getConsumption2019(startTime, endTime, jsonArray, companyList, stringDoubleHashMap, df);
            }
        } else {
            String time1 = "2019-12";
            String time2 = "2020-01";
            //2020年能耗数据
            Double sum = getConsumption2020(area, industry, time, time2, endTime, stringDoubleHashMap, df);
            //2019年能耗数据
            if (companyList != null && companyList.size() > 0) {
                /*List<Integer> companyList1 = getentIdByEnterpriseCode(companyList);
                List<KeyValueVO> listValue = energyMapper.getTotalMaterialByCode(companyList1, startTime, time1);
                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, time1, jsonArray, companyList, 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();
            if (aDouble == null) {
                aDouble = 0.0;
            }
            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, JSONArray jsonArray, List<String> companyList, HashMap<String, Double> stringDoubleHashMap, DecimalFormat df) {
        List<Integer> companyList1 = getentIdByEnterpriseCode(companyList);
        List<KeyValueVO> listValue = energyMapper.getTotalMaterialByCode(companyList1, startTime, endTime);
        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;
        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 area, String industry, String time, String startTime, String endTime, HashMap<String, Double> stringDoubleHashMap, DecimalFormat df) throws ParseException {
        // 获取采集点信息
        /*List<String> dataCodeList = parseFormulToSimpleAndParamsMap(area, industry, time, startTime, endTime, null);
        // 根据公式反推全省能耗消费结构
        List<CoalVo> sumList = new ArrayList<>();
        if( dataCodeList != null && dataCodeList.size() > 0){
            sumList = energyMapper.selectAllEnergyNumByForuml( dataCodeList, startTime, endTime);
        }
        // 合并煤炭、热力、其它燃料
        Double coalEnergy = 0.0, thermalEnergy = 0.0, otherEnergy = 0.0;
        for (CoalVo coalVo : sumList) {
            Double energyValue = StringUtils.isBlank(coalVo.getValue()) ? 0.0 : Double.parseDouble(coalVo.getValue());
            String energyCode = coalVo.getMonth();
            String energyName = coalVo.getValue1();
            if (coalEnergyList.contains(energyCode)) {
                coalEnergy += energyValue;
            }else if (thermalEnergyList.contains(energyCode)) { //热力
                thermalEnergy += energyValue;
            }else if (otherEnergyList.contains(energyCode)) { //其它燃料
                otherEnergy += energyValue;
            }else{
                stringDoubleHashMap.put(energyName, Double.parseDouble(df.format(energyValue)));
            }
        }
        //循环外添加煤、热力、其他燃料
        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)));
        }*/

        // 从中间表 t_energy_consumption 获取能源消耗
        List<CoalVo> sumList = new ArrayList<>();
        Double coalEnergy = 0.0;
        // 获取公司列表
        HashMap<String, String> areaAndIndustryCode = getAreaAndIndustryCode(area, industry);
        String areaName = areaAndIndustryCode.get("地区");
        String industryName = areaAndIndustryCode.get("行业");
        List<String> companyList2020 = getCompanyList2020(areaName, industryName, time, null);
        sumList = energyMapper.selectAllEnergyNumByConsumption( companyList2020, startTime, endTime);
        for (CoalVo coalVo : sumList) {
            Double energyValue = StringUtils.isBlank(coalVo.getValue()) ? 0.0 : Double.parseDouble(coalVo.getValue());
            String energyName = coalVo.getValue1();
            stringDoubleHashMap.put(energyName, Double.parseDouble(df.format(energyValue)));
            if(energyName.equals("煤")){
                coalEnergy += energyValue;
            }
        }
        return coalEnergy;
    }

    //根据公式反推参与计算的采集点
    @Override
    public List<String> parseFormulToSimpleAndParamsMap(String area, String industry, String time, String startTime, String endTime, ArrayList<String> energyCodeList) throws ParseException {
        // 获取公司列表
        HashMap<String, String> areaAndIndustryCode = getAreaAndIndustryCode(area, industry);
        String areaName = areaAndIndustryCode.get("地区");
        String industryName = areaAndIndustryCode.get("行业");
        List<String> companyList2020 = getCompanyList2020(areaName, industryName, time, null);
        String[] statDateList = monthList(startTime, endTime);
        // 需要折标的采集点
        List<AreaVO> dataCodeList = new ArrayList<>();
        List<String> uniqueKey = new ArrayList<>();
        Pattern shouldConvertCompile = compile("#f[0-9A-Z]{16}[*]#r[0-9A-Z]{16}");
        List<AreaVO> formulList = energyMapper.getEpcListByFormul( companyList2020, "综合能耗");
        for (AreaVO formul : formulList) {
            Matcher shouldConvertMatcher = shouldConvertCompile.matcher(formul.getCode());
            //需要折标的采集点从大写字母Z开始
            while (shouldConvertMatcher.find()) {
                //取出需要折标的采集点
                String dataCode = shouldConvertMatcher.group().substring(2, 18);
                if(dataCode.endsWith("11") || dataCode.endsWith("20") || dataCode.endsWith("21") || dataCode.endsWith("10")){
                    //AreaVO vo = new AreaVO(dataCode, formul.getName());
                    //dataCodeList.add(vo);
                    boolean flag = false;
                    if(energyCodeList != null && energyCodeList.size()>0){
                        String energyCode = dataCode.substring(10,14);
                        if(energyCodeList.contains(energyCode)){ //是所筛选的能源
                            flag = true;
                        }
                    }else{ //不用删选能源
                        flag = true;
                    }
                    if(flag){
                        /*for (String date : statDateList) {
                            String tmp = "#4#"+formul.getName()+"#"+date+"#"+dataCode;
                            uniqueKey.add(tmp);
                        }*/
                        String tmp = formul.getName()+"#"+dataCode;
                        uniqueKey.add(tmp);
                    }
                }
            }
        }
        return uniqueKey;
    }

    @Override
    public List<CoalVo> selectEnergyByFormul(List<String> dataCodeList, String startTime, String endTime, String ratio) {
        return energyMapper.selectEnergyByFormul(dataCodeList, startTime, endTime, ratio);
    }

    @Override
    public void renewEnergyConsumptionByForuml(List<String> dataCodeList, String startTime, String endTime) {
        energyMapper.renewEnergyConsumptionByForuml(dataCodeList, startTime, endTime);
    }

    @Override
    public IPage<QualityCalculateLogVo> getPageLogListA(Page page, QualityCalculateLogVo calculateLogVo) {
        return energyMapper.getPageLogListA(page, calculateLogVo);
    }

    @Override
    public IPage<QualityCalculateLogVo> getPageLogListB(Page page, QualityCalculateLogVo calculateLogVo) {
        return energyMapper.getPageLogListB(page, calculateLogVo);
    }

    @Override
    public IPage<QualityCalculateLogVo> getPageLogListC(Page page, QualityCalculateLogVo calculateLogVo) {
        return energyMapper.getPageLogListC(page, calculateLogVo);
    }

    //查询企业接入至今的能耗数据
    private Double getConsumption2020Old(String area, String industry, String time, String startTime, String endTime, HashMap<String, Double> stringDoubleHashMap) {
        // 获取公司列表
        HashMap<String, String> areaAndIndustryCode = getAreaAndIndustryCode(area, industry);
        String areaName = areaAndIndustryCode.get("地区");
        String industryName = areaAndIndustryCode.get("行业");
        List<String> companyList2020 = getCompanyList2020(areaName, industryName, time, null);
        List<CoalVo> energyKindsList = energyMapper.selectEnergyKinds(companyList2020);
        List<CoalVo> sumList = energyMapper.selectAllEnergyNumByKinds(areaName, industryName, null, startTime, endTime);
        HashMap<String, Double> valueMap = new HashMap<>();
        for (int i = 0; i < sumList.size(); i++) {
            valueMap.put(sumList.get(i).getMonth(), Double.parseDouble(sumList.get(i).getValue()));
        }
        for (CoalVo data : energyKindsList) {
            stringDoubleHashMap.put(data.getValue(), valueMap.get(data.getMonth()));
        }
        // 合并煤炭、热力、其它燃料
        Double sum = 0.0, thermalEnergy = 0.0, otherEnergy = 0.0;
        Iterator<Map.Entry<String, Double>> iterator = stringDoubleHashMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, Double> next = iterator.next();
            String key = next.getKey();
            Double aDouble = stringDoubleHashMap.get(key);
            if (aDouble == null) {
                aDouble = 0.0;
            }
            if (key.endsWith("煤")) {
                sum += aDouble;
                iterator.remove();
            }
            if (thermalEnergyList.contains(key)) { //热力
                thermalEnergy += aDouble;
                iterator.remove();
            }
            if (otherEnergyList.contains(key)) { //其它燃料
                otherEnergy += aDouble;
                iterator.remove();
            }
        }
        if (stringDoubleHashMap.size() > 5) {
            Iterator<Map.Entry<String, Double>> iterator1 = stringDoubleHashMap.entrySet().iterator();
            while (iterator1.hasNext()) {
                Map.Entry<String, Double> next = iterator1.next();
                String key = next.getKey();
                Double aDouble = stringDoubleHashMap.get(key);
                if (aDouble == null) {
                    aDouble = 0.0;
                }
                if (aDouble < 1) {
                    iterator1.remove();
                }
            }
        }
        if (sum != 0) {
            stringDoubleHashMap.put("煤", sum);
        }
        if (thermalEnergy != 0) {
            stringDoubleHashMap.put("热力", thermalEnergy);
        }
        if (otherEnergy != 0) {
            stringDoubleHashMap.put("其它燃料", otherEnergy);
        }
        return sum;
    }

    @Override
    public List<Map<String, Object>> getEnergyWarning(String area, String industry, String time) {
        String startTime = time.split("&")[0].substring(0,7);
        String endTime = time.split("&")[1].substring(0,7);

        if(!"全部".equals(industry)){
            HashMap<String, String>  industryMap = industryCode.getIndustryMap();
            industry = industryMap.get(industry);
        }else{
            industry = "";
        }
        if(!"云南".equals(area)){
            HashMap<String, String>  areaMap = areaCode.getAreaMapA();
            area = areaMap.get(area);
        }else{
            area = "";
        }
        List<Map<String, Object>> map = energyMapper.energyMappergetEnergyWarning(area, industry, startTime, endTime);
        return map;
    }

    @Override
    public List<String> getCompanyList2020(String area, String industry, String time, String cmpName) {
        String areaName = area;
        areaName = areaName + "%";
        String industryName = industry;
        if ("".equals(cmpName) || cmpName == null) {
            cmpName = null;
        } else {
            cmpName = "%" + cmpName + "%";
        }
        List<String> companyList = energyMapper.selectCompanyListByAreaAndIndustry(areaName, industryName, cmpName);
        if (companyList.size() == 0) {
            companyList.add("");
        }
        return companyList;
    }

    /**
     * @Description: 2019企业名称
     * @Param: [area, industry, time, cmpName]
     * @return: java.util.List<java.lang.String>
     * @Author: zfw
     * @Date: 2021/1/15
     * @Date: 10:14
     */
    public List<String> getCompanyList2019(String area, String industry, String time, String cmpName) {
        String areaName = area;
        areaName = areaName + "%";
        String industryName = industry;
        if ("".equals(cmpName) || cmpName == null) {
            cmpName = null;
        } else {
            cmpName = "%" + cmpName + "%";
        }
        List<String> companyList = energyMapper.selectCompanyListByAreaAndIndustry2019(areaName, industryName, cmpName);
        if (companyList.size() == 0) {
            companyList.add("");
        }
        return companyList;
    }

    /***
     * @Description: 行业综合能耗
     * @Param: [area, industry, time]
     * @return: java.util.Map<java.lang.String, java.lang.String>
     * @Author: zfw
     * @Date: 2020/12/26
     * @Date: 16:36
     */
    @Override
    public Map<String, Object> getEnergyByIndustry(String area, String industry, String time) {
        Map<String, Object> map = new HashMap<>();
        List<String> indList = new ArrayList<>();
        Float value = 0f;
        area = area.trim();
        industry = industry.trim();
        time = time.trim();
        String timestr = time.substring(0, 4);
        List<String> areaList = new ArrayList<>();
        List<Float> dataValueList = new ArrayList<>();
        if (industry == null || industry.equals("全部")) { //如果为空,查询全部
            indList = energyMapper.findAllIndustry();
        } else {
            indList.add(industry);
        }
        for (int i = 0; i < indList.size(); i++) {
            value = getTotal(area, indList.get(i), time);
            areaList.add(indList.get(i));
            dataValueList.add(value);
        }
        map.put("industry", areaList);
        map.put("dataValue", dataValueList);

       /* //查询
        for(int i=0;i<indList.size();i++){
            value=getTotal(area,indList.get(i),time);
            areaList.add(indList.get(i));
            dataValueList.add(value);
        }*/
        //map.put("industry",areaList);
        // map.put("dataValue",dataValueList);
        return map;
    }

    /**
     * @Description: 地区综合能耗
     * @Param: [area, industry, time]
     * @return: java.util.Map<java.lang.String, java.lang.String>
     * @Author: zfw
     * @Date: 2020/12/26
     * @Date: 17:39
     */
    @Override
    public Map<String, Object> getEnergyByArea(String area, String industry, String time) {
        Map<String, Object> map = new HashMap<>();
        String flage = area;
        List<AreaVO> areaList1 = new ArrayList<>();
        Float value = 0f;
        area = area.trim();
        industry = industry.trim();
        time = time.trim();
        HashMap<String, String> areaAndIndustryCode = getAreaAndIndustryCode(area, industry);
        String areaCode = (area.trim().equals("53") || area.trim().equals("云南")) ? "530000" : areaAndIndustryCode.get("地区");
        int code = areaCode.length()==4 ? Integer.parseInt(areaCode+"00") : Integer.parseInt(areaCode);
        //查询地区
        if (flage.contains("53")) {
            areaList1 = energyMapper.findAllArea1(code);
        } else {
            areaList1 = energyMapper.findAllArea(code);
        }

        List<String> areaList = new ArrayList<>();
        List<Float> dataValueList = new ArrayList<>();
        //查询
        for (int i = 0; i < areaList1.size(); i++) {
            if (code == 530000) {
                value = getTotal(areaList1.get(i).getCode().substring(0, 4), industry, time);
            } else {
                value = getTotal(areaList1.get(i).getCode(), industry, time);
            }
            areaList.add(areaList1.get(i).getName());
            dataValueList.add(value);
        }
        map.put("area", areaList);
        map.put("dataValue", dataValueList);
        return map;
    }

    @Override
    public Map<String,Object> getEnergyByDate(String area, String industry, String time) {
        Map<String, Object> map = new HashMap<>();
        List<String> dateList = new ArrayList<>();        //时间
        List<String> dataValueList = new ArrayList<>();   //能耗
        List<String> epcNumList = new ArrayList<>();      //企业家数

        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String startTime = time.split("&")[0];
            String endTime = time.split("&")[1].substring(0,8)+"01";
            //设置开始时间
            Calendar calBegin = Calendar.getInstance();
            calBegin.setTime(sdf.parse(startTime));

            //查询第一个的综合能耗
            dateList.add(startTime.substring(0,7));
            Map<String, String> detail = getTotalDetail(area, industry, startTime);
            dataValueList.add(detail.get("tce"));
            epcNumList.add(detail.get("epcNum"));

            String tmpTime = "";
            // 每次循环给calBegin加一月，直到calBegin.getTime()时间等于endTime
            while (sdf.parse(endTime).after(calBegin.getTime()))  {
                calBegin.add(Calendar.MONTH, 1);
                tmpTime = sdf.format(calBegin.getTime());
                dateList.add(tmpTime.substring(0,7));
                Map<String, String> tmpDetail = getTotalDetail(area, industry, tmpTime);
                dataValueList.add(tmpDetail.get("tce"));
                epcNumList.add(tmpDetail.get("epcNum"));
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }

        map.put("date", dateList);
        map.put("dataValue", dataValueList);
        map.put("epcNum", epcNumList);
        return map;
    }


    /**
     * 获取有综合能耗的企业
     */
    @Override
    public IPage<Map<String, String>> getEpcDetailByTce(Page page, String area, String industry, String time) {
        //截取时间
        String startTime = time.substring(0,4);
        //匹配地区和行业
        HashMap<String, String> areaAndIndustryCode = getAreaAndIndustryCode(area, industry);
        String areaCode = (area.trim().equals("53") || area.trim().equals("云南")) ? "53" : areaAndIndustryCode.get("地区");
        String industryCode = industry.trim().equals("全部") ? null : areaAndIndustryCode.get("行业");
        if (Integer.valueOf(startTime) >= 2020) { //查询2020年以后，走新表
            IPage<Map<String, String>> data = energyMapper.getEpcDetail(page, areaCode, industryCode, time);
            return data;
        } else { //查询2020年以前，走老表
            IPage<Map<String, String>> data = energyMapper.getEpcDetailOld(page, areaCode, industryCode, time);
            return data;
        }
    }

    /***
     * @Description: 查询 煤消耗量
     * @Param: [area, industry, time]
     * @return: java.util.Map<java.lang.String, java.lang.Object>
     * @Author: zfw
     * @Date: 2020/12/27
     * @Date: 23:16
     */
    @Override
    public Map<String, Object> getCoalConsumption(String area, String industry, String time) throws ParseException {
        //time="2019-01-01&2020-12-01";
        //截取时间
        String startTime = null;
        String endTime = null;
        if (time.contains("&")) {
            startTime = time.split("&")[0];
            endTime = time.split("&")[1];
            startTime = startTime.substring(0, 7);
            endTime = endTime.substring(0, 7);

        }
        Map<String, Object> map = new HashMap<>();
        List<String> areaList = new ArrayList<>();
        List<String> dataValueList = new ArrayList<>();
        Float value = 0.0f;
        Integer timeStr = Integer.valueOf(startTime.substring(0, 4));
        Integer timeStr1 = Integer.valueOf(endTime.substring(0, 4));
        List<String> companyList = companyList(area, industry, time);
        if (timeStr >= 2020) {
            getCoalConsumption2020(area, industry, time, startTime, endTime, areaList, dataValueList);
        } else if (timeStr1 < 2020) { //2019年数据
            List<Integer> list = getentIdByEnterpriseCode(companyList);
            List<CoalVo> coalVoList = energyMapper.foundCoalByMonth(list, startTime, endTime);
            for (int i = 0; i < coalVoList.size(); i++) {
                areaList.add(coalVoList.get(i).getMonth());
                dataValueList.add(coalVoList.get(i).getValue());
            }
        } else {
            String time1 = "2019-12";
            String time2 = "2020-01";
            //2019
            List<Integer> list = getentIdByEnterpriseCode(companyList);
            List<CoalVo> coalVoList = energyMapper.foundCoalByMonth(list, startTime, time1);
            for (int i = 0; i < coalVoList.size(); i++) {
                areaList.add(coalVoList.get(i).getMonth());
                dataValueList.add(coalVoList.get(i).getValue());
            }
            //2020
            getCoalConsumption2020(area, industry, time, time2, endTime, areaList, dataValueList);
        }

        map.put("area", areaList);
        map.put("dataValue", dataValueList);
        return map;
    }

    //查询2020年至今的煤耗数据
    private void getCoalConsumption2020(String area, String industry, String time, String startTime, String endTime, List<String> areaList, List<String> dataValueList) throws ParseException {
        /*//获取采集点信息
        List<String> dataCodeList = parseFormulToSimpleAndParamsMap(area, industry, time, startTime, endTime, coalEnergyList); //获取煤耗编码
        //根据公式反推煤实物量
        List<CoalVo> coalVos = energyMapper.selectEnergyByFormul(dataCodeList, startTime, endTime, "0.0001");*/

        // 从中间表 t_energy_consumption 获取能源消耗
        HashMap<String, String> areaAndIndustryCode = getAreaAndIndustryCode(area, industry);
        String areaName = areaAndIndustryCode.get("地区");
        String industryName = areaAndIndustryCode.get("行业");
        List<String> companyList2020 = getCompanyList2020(areaName, industryName, time, null);
        List<CoalVo> coalVos = energyMapper.selectEnergyByConsumption(companyList2020, startTime, endTime, "煤", "0.0001");
        List<CoalVo> coalVosResult = getMonthAndValue(startTime, endTime, coalVos);
        for (int i = 0; i < coalVosResult.size(); i++) {
            areaList.add(coalVosResult.get(i).getMonth());
            dataValueList.add(coalVosResult.get(i).getValue());
        }
    }

    @Override
    public List<CoalVo> getMonthAndValue(String startTime, String endTime, List<CoalVo> coalVos) {
        Date date = new Date();
        DateFormat format = new SimpleDateFormat("yyyy-MM");
        String systemDate = format.format(date);
        List<CoalVo> coalVosResult = new ArrayList<>();
        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");
            }
            if(!coalVo.getMonth().equals(systemDate)){
                coalVosResult.add(coalVo);
            }
            j++;
        }
        a:
        for (int i = 0; i < coalVosResult.size(); i++) {
            CoalVo coalVo = coalVosResult.get(i);
            for (CoalVo data : coalVos) {
                if (coalVo.getMonth().equals(data.getMonth())) {
                    coalVo.setValue(data.getValue());
                    continue a;
                }
            }
        }
        return coalVosResult;
    }

    /**
     * @Description: 工业水消耗
     * @Param: [area, industry, time]
     * @return: java.util.Map<java.lang.String, java.lang.Object>
     * @Author: zfw
     * @Date: 2020/12/28
     * @Date: 0:03
     */
    @Override
    public Map<String, Object> getWaterConsumption(String area, String industry, String time) {
        //time="2019-01-01&2020-12-01";
        //截取时间
        String startTime = null;
        String endTime = null;
        if (time.contains("&")) {
            startTime = time.split("&")[0];
            endTime = time.split("&")[1];
            startTime = startTime.substring(0, 7);
            endTime = endTime.substring(0, 7);

        }
        Map<String, Object> map = new HashMap<>();
        List<String> areaList = new ArrayList<>();
        List<String> dataValueList = new ArrayList<>();
        Float value = 0.0f;
        //首先查询企业
        List<String> companyList = companyList(area, industry, time);
        Integer timeStr = Integer.valueOf(startTime.substring(0, 4));
        Integer timeStr1 = Integer.valueOf(endTime.substring(0, 4));
        if (timeStr >= 2020) {
            HashMap<String, String> areaAndIndustryCode = getAreaAndIndustryCode(area, industry);
            String areaName = areaAndIndustryCode.get("地区");
            String industryName = areaAndIndustryCode.get("行业");
            List<String> companyList2020 = getCompanyList2020(areaName, industryName, time, null);
            List<CoalVo> coalVos = energyMapper.foundWaterByMonth2020(companyList2020, startTime, endTime);
            List<CoalVo> coalVosResult = getMonthAndValue(startTime, endTime, coalVos);
            for (int i = 0; i < coalVosResult.size(); i++) {
                areaList.add(coalVosResult.get(i).getMonth());
                dataValueList.add(coalVosResult.get(i).getValue());
            }
        } else if (timeStr1 < 2020) {
            List<Integer> list = getentIdByEnterpriseCode(companyList);
            List<CoalVo> coalVoList = energyMapper.foundWaterByMonth(list, startTime, endTime);
            for (int i = 0; i < coalVoList.size(); i++) {
                areaList.add(coalVoList.get(i).getMonth());
                dataValueList.add(coalVoList.get(i).getValue());
            }
        } else {
            String time1 = "2019-12";
            String time2 = "2020-01";
            HashMap<String, String> areaAndIndustryCode = getAreaAndIndustryCode(area, industry);
            String areaName = areaAndIndustryCode.get("地区");
            String industryName = areaAndIndustryCode.get("行业");

            List<Integer> list = getentIdByEnterpriseCode(companyList);
            List<CoalVo> coalVoList = energyMapper.foundWaterByMonth(list, startTime, time1);
            for (int i = 0; i < coalVoList.size(); i++) {
                areaList.add(coalVoList.get(i).getMonth());
                dataValueList.add(coalVoList.get(i).getValue());
            }

            List<String> companyList2020 = getCompanyList2020(areaName, industryName, time, null);
            List<CoalVo> coalVos = energyMapper.foundWaterByMonth2020(companyList2020, time2, endTime);
            List<CoalVo> coalVosResult = getMonthAndValue(time2, endTime, coalVos);
            for (int i = 0; i < coalVosResult.size(); i++) {
                areaList.add(coalVosResult.get(i).getMonth());
                dataValueList.add(coalVosResult.get(i).getValue());
            }

        }
        map.put("area", areaList);
        map.put("dataValue", dataValueList);

        return map;
    }

    //查询你企业list
    @Override
    public List<String> companyList(String area, String industry, String time) {
        //截取时间
        String startTime = null;
        String endTime = null;
        if (time.contains("&")) {
            startTime = time.split("&")[0];
            endTime = time.split("&")[1];
            startTime = startTime.substring(0, 7);
            endTime = endTime.substring(0, 7);

        }
        //匹配地区 昆明市、曲靖市、玉溪市、昭通市、丽江市、普洱市、保山市、临沧市、楚雄州、红河州、迪庆州、文山州、西双版纳州、大理州、德宏州、怒江州
        industry = industry.trim();
        area = area.trim();
        List<String> companyList = new ArrayList<>();
        HashMap<String, String> areaAndIndustryCode = getAreaAndIndustryCode( area, industry);
        String areaCode = (area.trim().equals("53") || area.trim().equals("云南")) ? "53" : areaAndIndustryCode.get("地区");
        String industryCode = industry.trim().equals("全部") ? null : areaAndIndustryCode.get("行业");
        int code = Integer.parseInt(areaCode);
        if (Integer.valueOf(startTime.substring(0, 4)) >= 2020) { //查询2020年
            companyList = energyMapper.getAllCompanyList2020(code, industryCode);
        } else {//查询2019年
            companyList = energyMapper.getAllCompanyList2019(code, industryCode, null);
        }
        return companyList;
    }

    @Override
    public ExceptionIndexInfo getExceptionInfo(String area, String industry, String time, String cmpName, String type, Integer page, Integer size, String collectName, String state, String isForce) {
        String preTime = time.substring(0, 7);
        String endTime = time.substring(11, 18);
        String year = preTime.substring(0, 4);
        if (Integer.parseInt(year) >= 2020 && (StringUtils.isBlank(type) || "1,2".contains(type))) { //采集数据异常
            HashMap<String, String> areaAndIndustryCode = getAreaAndIndustryCode(area, industry);
            String areaName = areaAndIndustryCode.get("地区");
            String industryName = areaAndIndustryCode.get("行业");
            // 获取分页参数
            page = (page - 1) * size;
            List<ExceptionInfoVo> exceptionInfoLists = energyMapper.selectExceptionInfo(areaName, cmpName, type, industryName, preTime, endTime, page, size, collectName, state, isForce);
            //List<Integer> tatal = energyMapper.CountAll(areaName + "%", cmpName, type, industryName, preTime, endTime, collectName, state); //这个sql在这里不适用
            Integer tatal = energyMapper.selectExceptionInfoCount(areaName, cmpName, type, industryName, preTime, endTime, collectName, state);
            ExceptionIndexInfo exceptionIndexInfo = new ExceptionIndexInfo(exceptionInfoLists, 0, 0, 0, 0, 0, page / size + 1, size, tatal, tatal);
//            for (ExceptionInfoVo data : exceptionInfoLists) {
//                switch (data.getExceptionType()) {
//                    case "1":
//                        exceptionIndexInfo.setWave(exceptionIndexInfo.getWave() + 1);
//                        break;
//                    case "2":
//                        exceptionIndexInfo.setConvertRation(exceptionIndexInfo.getConvertRation() + 1);
//                        break;
//                    case "3":
//                        exceptionIndexInfo.setDataValue(exceptionIndexInfo.getDataValue() + 1);
//                        break;
//                    case "4":
//                        exceptionIndexInfo.setIndexValue(exceptionIndexInfo.getIndexValue() + 1);
//                        break;
//                    case "5":
//                        exceptionIndexInfo.setElectricity(exceptionIndexInfo.getElectricity() + 1);
//                        break;
//                }
//            }
            for (int i = 0; i < exceptionInfoLists.size(); i++) {
                ExceptionInfoVo data = exceptionInfoLists.get(i);
//                switch (data.getExceptionGov()){
//                    case "1" : data.setExceptionGov("已处理");break;
//                    case "0" : data.setExceptionGov("未处理");break;
//                }
                //超过五天，置为3
                Calendar calendar1 = Calendar.getInstance();
                SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
                calendar1.add(Calendar.DATE, -5);
                String format = sdf1.format(calendar1.getTime());
                if (data.getExceptionGov().equals("0") && data.getStatDate().compareTo(format) < 0) {
                    data.setExceptionGov("3");
                }
            }
            return exceptionIndexInfo;
        } else {
            return null;
        }
    }

    @Override
    public String getExceptionTotal(String epc, String time) {
        String preTime = time.substring(0, 7);
        String endTime = time.substring(11, 18);
        return energyMapper.getExceptionTotal(epc,preTime,endTime);
    }


    @Override
    public ExceptionIndexInfo getExceptionIndex(String area, String industry, String time, String cmpName, String type, Integer page, Integer size, String collectItemName, String exceptionGov) {
        String preTime = time.split("&")[0].substring(0, 7);
        String endTime = time.split("&")[1].substring(0, 7);
        String year = preTime.substring(0, 4);
        if (Integer.parseInt(year) >= 2020 && (StringUtils.isBlank(type) || "3,4,5".contains(type))) { //指标异常
            HashMap<String, String> areaAndIndustryCode = getAreaAndIndustryCode(area, industry);
            String areaName = areaAndIndustryCode.get("地区");
            String industryName = areaAndIndustryCode.get("行业");
            // 获取分页参数
            page = (page - 1) * size;
            List<ExceptionInfoVo> exceptionInfoLists = energyMapper.selectExceptionIndex(areaName, cmpName, type, industryName, preTime, endTime, page, size, collectItemName, exceptionGov);
            Integer tatal = energyMapper.selectExceptionIndexCount(areaName, cmpName, type, industryName, preTime, endTime, collectItemName, exceptionGov);
            ExceptionIndexInfo exceptionIndexInfo = new ExceptionIndexInfo(exceptionInfoLists, 0, 0, 0, 0, 0, page / size + 1, size, tatal, tatal);
            return exceptionIndexInfo;
        }else{
            return null;
        }
    }

    /**
     * @Description: 按照地区查询综合能耗
     * @Param: [area, time]
     * @return: java.util.List<com.nantian.cloud.dbcapp.vo.KeyValueVO>
     * @Author: zfw
     * @Date: 2021/1/4
     * @Date: 14:06
     */
    @Override
    public List<KeyValueVO> getTceByArea(String area, String time) {
        String startTime = time.split("&")[0];
        String endTime = time.split("&")[1];
        startTime = startTime.substring(0, 7);
        endTime = endTime.substring(0, 7);
        String timeStr = startTime.substring(0, 4);
        List<AreaVO> listArea = energyMapper.findAllArea(530000);
        List<KeyValueVO> list = new ArrayList<KeyValueVO>();
        Float sum = 0.0f;

        if (Integer.valueOf(timeStr) >= 2020) {//2020年
            for (int i = 0; i < listArea.size(); i++) {
                KeyValueVO list1 = new KeyValueVO();
                sum = energyMapper.getTceByArea1(listArea.get(i).getCode().substring(0, 4), startTime, endTime);
                if (sum == null) {
                    sum = 0.0f;
                }
                list1.setKey1(listArea.get(i).getName());
                list1.setValue(sum);
                list.add(list1);
            }


        } else {
            //查询企业code
            for (int i = 0; i < listArea.size(); i++) {
                KeyValueVO list1 = new KeyValueVO();
                sum = energyMapper.getTceByArea(listArea.get(i).getCode().substring(0, 4), startTime, endTime);
                if (sum == null) {
                    sum = 0.0f;
                }
                list1.setKey1(listArea.get(i).getName());
                list1.setValue(sum);
                list.add(list1);
            }
        }

        //排序
        list.sort(Comparator.comparing(KeyValueVO::getValue).reversed());

        return list;
    }

    /**
     * @Description: 按照行业查询综合能耗
     * @Param: [industry, time]
     * @return: java.util.List<com.nantian.cloud.dbcapp.vo.KeyValueVO>
     * @Author: zfw
     * @Date: 2021/1/4
     * @Date: 14:06
     */
    @Override
    public List<KeyValueVO> getTceByIndustry(String industry, String time) {
        String startTime = time.split("&")[0];
        String endTime = time.split("&")[1];
        startTime = startTime.substring(0, 7);
        endTime = endTime.substring(0, 7);
        String timeStr = startTime.substring(0, 4);
        List<AreaVO> listInd = energyMapper.findAllInd();
        List<KeyValueVO> list = new ArrayList<KeyValueVO>();
        Float sum = 0.0f;

        if (Integer.valueOf(timeStr) >= 2020) {//2020年 id pipei
            for (int i = 0; i < listInd.size(); i++) {
                KeyValueVO list1 = new KeyValueVO();
                sum = energyMapper.getTceByIndustry(listInd.get(i).getCode(), startTime, endTime);
                if (sum == null) {
                    sum = 0.0f;
                }
                list1.setKey1(listInd.get(i).getName());
                list1.setValue(sum);
                list.add(list1);
            }


        } else {
            //查询企业code
            for (int i = 0; i < listInd.size(); i++) {
                KeyValueVO list1 = new KeyValueVO();
                sum = energyMapper.getTceByIndustry1(listInd.get(i).getCode(), startTime, endTime);
                if (sum == null) {
                    sum = 0.0f;
                }
                list1.setKey1(listInd.get(i).getName());
                list1.setValue(sum);
                list.add(list1);
            }
        }

        //排序
        list.sort(Comparator.comparing(KeyValueVO::getValue).reversed());

        return list;
    }

    /**
     * @Description: 得到州市县名称
     * @Param: [area]
     * @return: java.util.List<com.nantian.cloud.dbcapp.vo.KeyValueVO>
     * @Author: zfw
     * @Date: 2021/1/8
     * @Date: 10:14
     */
    @Override
    public List<KeyValueVO> getCountyName(String area) {
        Integer code = 0;
        try {
            code = Integer.parseInt(area);
        } catch (Exception e) {
            HashMap<String, String> areaMapA = areaCode.getAreaMapA();
            code = Integer.parseInt(areaMapA.get(area));
        }
        List<KeyValueVO> list = energyMapper.getCountyName(code);
        return list;
    }

    @Override
    public Integer getToolInfo(String area, String industry, String time) {
//        String startTime=time.split("&")[0];
//        String endTime=time.split("&")[1];
//        startTime=startTime.substring(0,7);
//        endTime=endTime.substring(0,7);
//        String timeStr=startTime.substring(0,4);
        /*if(Integer.parseInt(timeStr)>=2020) {*/
        HashMap<String, String> areaAndIndustryCode = getAreaAndIndustryCode(area, industry);
        String areaName = areaAndIndustryCode.get("地区");
        String industryName = areaAndIndustryCode.get("行业");
//            List<String> companyList2020 = getCompanyList2020(areaName, industryName, time, null);
        return energyInfoMapper.selectToolByAreaAndIndustry(areaName + "%", industryName);
        /*}else{
            //查询公司
            List<String> comList=companyList(area,industry,time);
            List<Integer> companyList2019=getentIdByEnterpriseCode(comList);
            return energyMapper.selectToolByAreaAndIndustry2019(companyList2019);
        }*/
    }


    @Override
    public List<CompanyEnergyInfoVo> getCompanyListEnergyInfo(String area, String industry, String time, String cmpName) {
        HashMap<String, String> areaAndIndustryCode = getAreaAndIndustryCode(area, industry);
        String areaName = areaAndIndustryCode.get("地区");
        String industryName = areaAndIndustryCode.get("行业");
        String startTime = time.split("&")[0];
        String endTime = time.split("&")[1];
        startTime = startTime.substring(0, 7);
        endTime = endTime.substring(0, 7);
        String timeStr = startTime.substring(0, 4);
        if (Integer.parseInt(timeStr) >= 2020) {
            List<String> companyList2020 = getCompanyList2020(areaName, industryName, time, cmpName);
            List<CompanyEnergyInfoVo> resultList = energyMapper.getCompanyListEnergyInfo2020(companyList2020, startTime, endTime);
            ArrayList<String> loseList = new ArrayList<>();
            // 查询采集配置点个数
            List<CoalVo> collectList = energyMapper.selectCollectNum(companyList2020);
            for (int i = 0; i < resultList.size(); i++) {
                loseList.add(resultList.get(i).getEnterpriseCode());
            }
            if (companyList2020.size() > loseList.size()) {
                companyList2020.removeAll(loseList);
                // 查询企业名称
                List<CoalVo> list = energyMapper.getEpcName(companyList2020);
                for (int i = 0; i < list.size(); i++) {
                    CoalVo data = list.get(i);
                    resultList.add(new CompanyEnergyInfoVo(data.getMonth(), data.getValue(), 0, 0f));
                }
            }
            for (CoalVo data : collectList) {
                for (CompanyEnergyInfoVo index : resultList) {
                    if (index.getEnterpriseCode().equals(data.getMonth())) {
                        index.setCollectNum(Integer.parseInt(data.getValue()));
                    }
                }
            }
            for (int i = 0; i < resultList.size(); i++) {
                CompanyEnergyInfoVo companyEnergyInfoVo = resultList.get(i);
                if (companyEnergyInfoVo.getCollectNum() == null) {
                    companyEnergyInfoVo.setCollectNum(0);
                }
                if (companyEnergyInfoVo.getEnergyValue() == null) {
                    companyEnergyInfoVo.setEnergyValue(0f);
                }
            }
            return resultList;
        } else {//2019采集点
            //查询公司
            List<String> comList = companyList2019(area, industry, time, cmpName);
            if (comList != null && comList.size() > 0) {
                List<Integer> companyList2019 = getentIdByEnterpriseCode(comList);
                //查询采集点
                List<CompanyEnergyInfoVo> resultList = energyMapper.getCompanyListEnergyInfo2019(companyList2019, startTime, endTime);
                return resultList;
            } else {
                return null;
            }

        }

    }

    @Override
    public List<AreaAndIndustryVo> getEnergyByAreaList(String area, String industry, String time) {
        /*HashMap<String, String> needTime = getNeedTime(time);
        String timeStr = needTime.get("时间期限");
        ArrayList<AreaAndIndustryVo> areaAndIndustryVos = new ArrayList<>();*/

        //HashMap<String, String> needTime = getNeedTime(time);
        //时间节点(本来是通过history_config_endtime表去取得,但是和上面的综合能耗值不相等 ,所以修改为从2020-01 直接截取2-26 zfw)
        //String timeStr1 = needTime.get("时间期限");
        //String timeStr2 = needTime.get("结束时间期限");
        String startTime = time.split("&")[0];
        String endTime = time.split("&")[1];
        startTime = startTime.substring(0, 7);
        endTime = endTime.substring(0, 7);
        String timeStr = startTime.substring(0, 4);
        String timeStr2 = endTime.substring(0, 4);
        //String timeStr1 = needTime.get("时间期限");
        // String timeStr2 = needTime.get("结束时间期限");
        ArrayList<AreaAndIndustryVo> areaAndIndustryVos = new ArrayList<>();

        HashMap<String, String> areaAndIndustryCode = getAreaAndIndustryCode(area, industry);
        String areaName = areaAndIndustryCode.get("地区");
        String industryName = areaAndIndustryCode.get("行业");
        ArrayList<AreaVO> areaList = new ArrayList<>();
        Boolean areaTag = true;
        if ("云南".equals(area) || areaName.equals("53")) {
            areaList = new ArrayList<>(energyMapper.areaList("530000"));
            areaTag = false;
        } else {
            areaList = energyMapper.selectAddressName(areaName + "%");
        }
        //String startTime = needTime.get("开始时间");
        //String endTime = needTime.get("结束时间");
        if (Integer.parseInt(timeStr) >= 2020) {
            areaAndIndustryVos = getCompanyList2020GroupByArea(area, areaList, startTime, endTime, industryName, areaName, true, areaTag);
        } else if (Integer.parseInt(timeStr2) < 2020) {
            areaAndIndustryVos = getCompanyList2019GroupByArea(area, areaList, startTime, endTime, industryName, areaName, true);
        } else {
            ArrayList<AreaAndIndustryVo> areaAndIndustryVos1 = new ArrayList<>();
            ArrayList<AreaAndIndustryVo> areaAndIndustryVos2 = new ArrayList<>();
            String time1 = "2020-01";
            String time2 = "2019-12";
            areaAndIndustryVos1 = getCompanyList2019GroupByArea(area, areaList, startTime, time2, industryName, areaName, true);
            areaAndIndustryVos2 = getCompanyList2020GroupByArea(area, areaList, time1, endTime, industryName, areaName, true, areaTag);
            //合并返回前端
            //areaAndIndustryVos.addAll(areaAndIndustryVos1);
            //areaAndIndustryVos.addAll(areaAndIndustryVos2);

            for (AreaAndIndustryVo a : areaAndIndustryVos1) {
                for (AreaAndIndustryVo b : areaAndIndustryVos2) {
                    if (a.getName().equals(b.getName())) {
                        AreaAndIndustryVo vo = new AreaAndIndustryVo();
                        vo.setName(a.getName());
                        vo.setEnergyValue(a.getEnergyValue() + b.getEnergyValue());
                        vo.setEnterpriseNum(a.getEnterpriseNum() + b.getEnterpriseNum());
                        areaAndIndustryVos.add(vo);
                    }
                }
            }


        }
        // 增加按能耗数据排序
        Collections.sort(areaAndIndustryVos, new Comparator<AreaAndIndustryVo>() {
            @Override
            public int compare(AreaAndIndustryVo o1, AreaAndIndustryVo o2) {
                return o1.getEnergyValue() > o2.getEnergyValue() ? -1 : 1;
            }
        });
        return areaAndIndustryVos;
    }

    @Override
    public List<AreaAndIndustryVo> getEnergyByIndustryList(String area, String industry, String time) {
        //time="2019-01-01&2020-12-01";
        //修改同上
        String startTime = time.split("&")[0];
        String endTime = time.split("&")[1];
        startTime = startTime.substring(0, 7);
        endTime = endTime.substring(0, 7);
        String timeStr = startTime.substring(0, 4);
        String timeStr2 = endTime.substring(0, 4);
        /*HashMap<String, String> needTime = getNeedTime(time);
        String timeStr1 = needTime.get("时间期限");
        String timeStr2 = needTime.get("结束时间期限");*/
        ArrayList<AreaAndIndustryVo> areaAndIndustryVos = new ArrayList<>();

        HashMap<String, String> areaAndIndustryCode = getAreaAndIndustryCode(area, industry);
        String industryName = areaAndIndustryCode.get("行业");
        String areaName = areaAndIndustryCode.get("地区");
        ArrayList<AreaVO> industryList = new ArrayList<>();
        if ("全部".equals(industry)) {
            industryList = new ArrayList<>(energyMapper.industryList());
        } else {
            industryList = energyMapper.selectIndustryList(industryName);
        }
        // String startTime = needTime.get("开始时间");
        //String endTime = needTime.get("结束时间");
        if (Integer.parseInt(timeStr) >= 2020) {
            areaAndIndustryVos = getCompanyList2020GroupByArea(area, industryList, startTime, endTime, industryName, areaName, false, false);
        } else if (Integer.parseInt(timeStr2) < 2020) {
            areaAndIndustryVos = getCompanyList2019GroupByArea(area, industryList, startTime, endTime, industryName, areaName, false);
        } else {
            ArrayList<AreaAndIndustryVo> areaAndIndustryVos1 = new ArrayList<>();
            ArrayList<AreaAndIndustryVo> areaAndIndustryVos2 = new ArrayList<>();
            String time1 = "2020-01";
            String time2 = "2019-12";
            areaAndIndustryVos1 = getCompanyList2020GroupByArea(area, industryList, time1, endTime, industryName, areaName, false, false);
            areaAndIndustryVos2 = getCompanyList2019GroupByArea(area, industryList, startTime, time2, industryName, areaName, false);
            // areaAndIndustryVos.addAll(areaAndIndustryVos1);
            //areaAndIndustryVos.addAll(areaAndIndustryVos2);
            for (AreaAndIndustryVo a : areaAndIndustryVos1) {
                for (AreaAndIndustryVo b : areaAndIndustryVos2) {
                    if (a.getName().equals(b.getName())) {
                        AreaAndIndustryVo vo = new AreaAndIndustryVo();
                        vo.setName(a.getName());
                        vo.setEnergyValue(a.getEnergyValue() + b.getEnergyValue());
                        vo.setEnterpriseNum(a.getEnterpriseNum() + b.getEnterpriseNum());
                        areaAndIndustryVos.add(vo);
                    }
                }
            }
        }
        // 增加按能耗数据排序
        Collections.sort(areaAndIndustryVos, new Comparator<AreaAndIndustryVo>() {
            @Override
            public int compare(AreaAndIndustryVo o1, AreaAndIndustryVo o2) {
                return o1.getEnergyValue() > o2.getEnergyValue() ? -1 : 1;
            }
        });
        return areaAndIndustryVos;

    }

    @Override
    public List<CompanyListVo> getCompanyList(String cmpName, DataScope dataScope) {
        cmpName = judgeEmpty(cmpName);
        List<CompanyListVo> list = energyMapper.getCompanyList(cmpName, dataScope);
        return list;
    }

    @Override
    public CollectCompanyVo getCollectAndElectricityList(String area, String industry, String time, String cmpName) {
        //Integer collectCompanyNum = 0, collectNum = 0, electricityCompanyNUm = 0, electricityNum = 0, updateCountryValue = 0, updateCountryTotal = 0;
        HashMap<String, String> areaAndIndustryCode = getAreaAndIndustryCode(area, industry);
        String areaName = areaAndIndustryCode.get("地区");
        String industryName = areaAndIndustryCode.get("行业");
        //获取在线采集条数
        //collectNum = energyMapper.getCollectNum(areaName,industryName);
        //获取电网电力条数
        //electricityNum = energyMapper.getElectricityNum(areaName,industryName);
        //获取上送国家条数
        //updateCountryValue = energyMapper.getUpdateCountryValue(areaName,industryName);

        /*//在线监测企业数据条数（1：在线采集数据，2：电网数据，3：上送国家数据）
        collectNum = energyMapper.getEpcDataCount(areaName,industryName,"1");
        electricityNum = energyMapper.getEpcDataCount(areaName,industryName,"2");
        updateCountryValue = energyMapper.getEpcDataCount(areaName,industryName,"3");
        //类别（1：重点用能单位，2：电力关口企业，3：对接国家平台，4：老平台企业）
        collectCompanyNum = energyMapper.getEpcDetailCount(areaName,industryName,"1");
        electricityCompanyNUm = energyMapper.getEpcDetailCount(areaName,industryName,"2");
        updateCountryTotal = energyMapper.getEpcDetailCount(areaName,industryName,"3");
        CollectCompanyVo collectCompanyVo = new CollectCompanyVo(collectCompanyNum,collectNum,electricityCompanyNUm,electricityNum,updateCountryValue,updateCountryTotal);*/


        CollectCompanyVo collectCompanyVo = new CollectCompanyVo();
        CompletableFuture.allOf(
                //在线监测企业数据条数（1：在线采集数据，2：电网数据，3：上送国家数据）
                CompletableFuture.runAsync(() -> {
                    collectCompanyVo.setCollectNum(energyMapper.getEpcDataCount(areaName,industryName,"1"));
                }, ForkJoinPool.commonPool()),
                CompletableFuture.runAsync(() -> {
                    collectCompanyVo.setElectricityNum(energyMapper.getEpcDataCount(areaName,industryName,"2"));
                }, ForkJoinPool.commonPool()),
                CompletableFuture.runAsync(() -> {
                    collectCompanyVo.setUpdateCountryValue(energyMapper.getEpcDataCount(areaName,industryName,"3"));
                }, ForkJoinPool.commonPool()),
                //类别（1：重点用能单位，2：电力关口企业，3：对接国家平台，4：老平台企业）
                CompletableFuture.runAsync(() -> {
                   collectCompanyVo.setCollectCompanyNum(energyMapper.getEpcDetailCount(areaName,industryName,"1"));
                }, ForkJoinPool.commonPool()),
                CompletableFuture.runAsync(() -> {
                    collectCompanyVo.setElectricityCompanyNUm(energyMapper.getEpcDetailCount(areaName,industryName,"2"));
                }, ForkJoinPool.commonPool()),
                CompletableFuture.runAsync(() -> {
                    collectCompanyVo.setUpdateCountryTotal(energyMapper.getEpcDetailCount(areaName,industryName,"3"));
                }, ForkJoinPool.commonPool())
        ).join();
        return collectCompanyVo;
    }

    public CollectCompanyVo getCollectAndElectricityListOld(String area, String industry, String time, String cmpName) {
        if (time.length() != 21) {
            String substring = time.substring(0, 7);
            String substring1 = time.substring(8);
            time = substring + "-01-" + substring1 + "-31";
        }
        HashMap<String, String> areaAndIndustryCode = getAreaAndIndustryCode(area, industry);
        String areaName = areaAndIndustryCode.get("地区");
        String industryName = areaAndIndustryCode.get("行业");
        if ("".equals(cmpName) || cmpName == null) {
            cmpName = null;
        } else {
            cmpName = "%" + cmpName + "%";
        }
        // 获取当前系统时间
        Date date = new Date();
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String format1 = format.format(date);
        String day = format1.substring(8);
        String r = format1.substring(0, 4);
        Integer newYear = Integer.parseInt(r) - 1;
        Integer newDay = Integer.parseInt(day) - 1;
        if ("".equals(time) || time == null) {
            time = newYear + format1.substring(4, 10) + "-" + format1;
        }
        String startTime = time.substring(0, 7);
        String endTime = time.substring(11, 18);
        if (newDay < 10) {
            format1 = format1.substring(0, 8) + "0" + newDay;
        } else {
            format1 = format1.substring(0, 8) + newDay;
        }
        //获取在线监测企业数量
        List<String> companyList2020 = getCompanyList2020(areaName, industryName, null, cmpName);
        //获取电网公司企业数量
        List<String> electricityCompanyList2020 = getElectricityCompanyList(areaName, industryName, cmpName);
        // 获取在线监测总检测数量
        // 获取电力总记录数
        List<Integer> numList;
        if ("云南".equals(area) && "全部".equals(industry)) {
            numList = energyMapper.countAllInfo();
        } else {
            numList = energyMapper.countCollectAndEle(areaName, industryName, startTime + "-01 00:00:00", endTime + "-31 23:59:59", startTime + "-01", endTime + "-31");
        }
        Integer collectNum = numList.get(0);
        Integer electricityValue = numList.get(1);
        List<UpdataInfoBo> lists = energyMapper.selectAllInfos(areaName + "%", industryName, cmpName, startTime + "-01", endTime + "-31", format1);
        // 上送国家在线企业情况
        UpdataInfoBo updateCountryCollect = lists.get(0);
        // 上送国家在线企业情况 成功
        UpdataInfoBo updateCountryCollectSuccess = lists.get(1);
        // 上送国家电网企业情况
        UpdataInfoBo updateCountryElectricity = lists.get(2);
        // 上送国家电网企业情况 成功
        UpdataInfoBo updateCountryElectricitySuccess = lists.get(3);
        // 查询最近一天企业上送情况
        Integer updateCountryNumCollect = lists.get(4).getCmpNum();
        Integer updateCountryNumElectricity = lists.get(5).getCmpNum();
        // 上送国家总数（前一天）
        Integer cmpNum0 = updateCountryCollect.getCmpNum();
        Integer cmpNum1 = updateCountryElectricity.getCmpNum();
        Integer updateCountryNUm = updateCountryNumCollect + updateCountryNumElectricity;
        //上送国家记录总数(统计时间内)
        Integer logsNum0 = updateCountryCollect.getLogsNum();
        Integer logsNum1 = updateCountryElectricity.getLogsNum();
        Integer updateCountryValue = logsNum0 + logsNum1;
        //上送国家成功总数（统计时间）
        Integer cmpNum3 = updateCountryCollectSuccess.getCmpNum();
        Integer cmpNum2 = updateCountryElectricitySuccess.getCmpNum();
        Integer updateCountryNUmSuccess = cmpNum2 + cmpNum3;
        // 上送国家失败总数（统计时间内）
        Integer updateCountryNUmFail = cmpNum0 + cmpNum1 - updateCountryNUmSuccess;
        // 查询上传国家平台成功企业
        Integer maxSuccdess = energyMapper.selectMaxSuccess(areaName, industryName);
        int size = companyList2020.size();
        if (companyList2020.contains("")) {
            size = size - 1;
        }
        int size1 = electricityCompanyList2020.size();
        if (electricityCompanyList2020.contains("")) {
            size1 = size1 - 1;
        }
        CollectCompanyVo collectCompanyVo = new CollectCompanyVo(null,size, collectNum, size1, electricityValue,
                null, updateCountryNUm, updateCountryValue, updateCountryNUmSuccess, updateCountryNUmFail,
                updateCountryNumCollect, logsNum0, updateCountryNumElectricity, logsNum1, maxSuccdess);
        return collectCompanyVo;
    }

    @Override
    public CollectCompanyVo getCollectEpcCount(String area, String industry, String time, String cmpName) {
        HashMap<String, String> areaAndIndustryCode = getAreaAndIndustryCode(area, industry);
        String areaName = areaAndIndustryCode.get("地区");
        String industryName = areaAndIndustryCode.get("行业");
        if ("".equals(cmpName) || cmpName == null) {
            cmpName = null;
        } else {
            cmpName = "%" + cmpName + "%";
        }
        // 获取当前系统时间
        Date date = new Date();
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String format1 = format.format(date);
        String day = format1.substring(8);
        String r = format1.substring(0, 4);
        Integer newYear = Integer.parseInt(r) - 1;
        Integer newDay = Integer.parseInt(day) - 1;
        if ("".equals(time) || time == null) {
            time = newYear + format1.substring(4, 10) + "-" + format1;
        }
        String startTime = time.substring(0, 7);
        String endTime = time.substring(11, 18);
        if (newDay < 10) {
            format1 = format1.substring(0, 8) + "0" + newDay;
        } else {
            format1 = format1.substring(0, 8) + newDay;
        }
        Integer total = electricityMapper.getTotal(areaName, industryName);
        //获取在线监测企业数量
        List<String> companyList2020 = getCompanyList2020(areaName, industryName, null, cmpName);
        int collectCompanyNum = companyList2020.size();
        if (companyList2020.contains("")) {
            collectCompanyNum = collectCompanyNum - 1;
        }
        //获取电网公司企业数量
        List<String> electricityCompanyList2020 = getElectricityCompanyList(areaName, industryName, cmpName);
        int electricityCompanyNUm = electricityCompanyList2020.size();
        if (electricityCompanyList2020.contains("")) {
            electricityCompanyNUm = electricityCompanyNUm - 1;
        }
        // 查询上传国家平台成功企业
        Integer updateCountryElectricity = energyMapper.selectMaxSuccess(areaName, industryName);

        List<UpdataInfoBo> lists = energyMapper.selectAllInfos(areaName + "%", industryName, cmpName, startTime + "-01", endTime + "-31", format1);
        // 上送国家在线企业 数据记录
        Integer logsNum0 = lists.get(0).getLogsNum();
        // 上送国家电网企业 数据记录
        Integer logsNum1 = lists.get(2).getLogsNum();
        //上送国家记录总数
        Integer updateCountryValue = logsNum0 + logsNum1;
        //获取电力记录总数
        List<Integer> numList;
        if ("云南".equals(area) && "全部".equals(industry)) {
            numList = energyMapper.countAllInfo();
        } else {
            numList = energyMapper.countCollectAndEle(areaName, industryName, startTime + "-01 00:00:00", endTime + "-31 23:59:59", startTime + "-01", endTime + "-31");
        }
        CollectCompanyVo collectCompanyVo = new CollectCompanyVo(total, collectCompanyNum, electricityCompanyNUm, updateCountryElectricity,updateCountryValue, numList.get(0),numList.get(1));
        return collectCompanyVo;
    }

    @Override
    public List<ProcedureVO> getCmpCollectInfo(String enterpriseCode, String baseCode) {
        /*ArrayList<ProcedureVO> list = new ArrayList<>();
        List<NameValueVO> listGx = energyMapper.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 = energyMapper.getValueByProcedure(enterpriseCode, listGx.get(i).getValue());
            for (ProcedureVO vo : tempList) {
                String configureCode = vo.getConfigureCode();
                String substring = configureCode.substring(8, 10);
                String energyUseType = configureCode.substring(14);
                if (substring.equals("03")) {
                    vo.setType("耗能工质");
                } 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 {

                }
                switch (energyUseType) {
                    case "11":
                        vo.setEnergyUseType("购进已消费");
                        break;
                    case "21":
                        vo.setEnergyUseType("工业生产消费");
                        break;
                    case "20":
                        vo.setEnergyUseType("能源消费合计");
                        break;
                    case "10":
                        vo.setEnergyUseType("购进");
                        break;
                    case "60":
                        vo.setEnergyUseType("外供");
                        break;
                    case "51":
                        vo.setEnergyUseType("期初库存");
                        break;
                    case "52":
                        vo.setEnergyUseType("期末库存");
                        break;
                }
                vo.setName(listGx.get(i).getName());
                list.add(vo);
            }
        }*/
        return energyMapper.getValueByNewProcedure(enterpriseCode, baseCode);
    }

    /***
     * 按月分析异常数据
     */
    @Override
    public List<CoalVo> getExceptionInfoList(String area, String industry, String time, String cmpName, String type) {
        String preTime = time.substring(0, 7);
        String endTime = time.substring(11, 18);
        String substring = preTime.substring(0, 4);
        HashMap<String, String> areaAndIndustryCode = getAreaAndIndustryCode(area, industry);
        String areaName = areaAndIndustryCode.get("地区");
        //String industryName = areaAndIndustryCode.get("行业");
        if(StringUtils.isBlank(type)){
            type = "1,2,3,4,5";
        }
        if(StringUtils.isNotBlank(industry) && industry.contains("全部")){
            industry = "";
        }
        List<CoalVo> exceptionInfoLists = energyMapper.selectExceptionInfoList(areaName + "%", cmpName, type, industry, preTime, endTime);
        return exceptionInfoLists;
    }

    /***
     * 按照异常种类排序
     */
    @Override
    public R getExceptionOrder(String area, String industry, String time, String cmpName, String type) {

        String preTime = time.substring(0, 7);
        String endTime = time.substring(11, 18);
        HashMap<String, String> areaAndIndustryCode = getAreaAndIndustryCode(area, industry);
        String areaName = areaAndIndustryCode.get("地区");
        //String industryName = areaAndIndustryCode.get("行业");
        if(StringUtils.isBlank(type)){
            type = "1,2,3,4,5";
        }
        if(StringUtils.isNotBlank(industry) && industry.contains("全部")){
            industry = "";
        }
        List<CoalVo> list = energyMapper.selectExceptionInOrder(areaName, cmpName, type, industry, preTime, endTime);
        if (list != null && list.size() > 0) {
            return R.ok(list, "查询成功");
        } else {
            return R.failed(null, "暂无数据");
        }

    }

    /**
     * 按照地区查询异常总数并排序
     */
    @Override
    public R getExceptionByAreaOrder(String area, String industry, String time, String cmpName, String type) {
        String preTime = time.substring(0, 7);
        String endTime = time.substring(11, 18);
        HashMap<String, String> areaAndIndustryCode = getAreaAndIndustryCode(area, industry);
        //得到地区，行业编码
        String areaName = areaAndIndustryCode.get("地区");
        //String industryName = areaAndIndustryCode.get("行业");
        if(StringUtils.isBlank(type)){
            type = "1,2,3,4,5";
        }
        if(StringUtils.isNotBlank(industry) && industry.contains("全部")){
            industry = "";
        }
        ArrayList<AreaAndIndustryVo> areaOrder = energyMapper.selectExceptionAreaOrder(areaName, cmpName, type, industry, preTime, endTime);
        /*ArrayList<AreaVO> areaList = new ArrayList<>();
        Boolean areaTag = true;
        //获取地区列表
        if ("云南".equals(area) || "53".equals(areaName)) {
            Collections.addAll(areaList, new AreaVO("5301", "昆明"), new AreaVO("5303", "曲靖"), new AreaVO("5304", "玉溪"), new AreaVO("5305", "保山"), new AreaVO("5306", "昭通"),
                    new AreaVO("5307", "丽江"), new AreaVO("5308", "普洱"), new AreaVO("5309", "临沧"),
                    new AreaVO("5323", "楚雄"), new AreaVO("5325", "红河"), new AreaVO("5326", "文山"), new AreaVO("5328", "版纳"), new AreaVO("5329", "大理"),
                    new AreaVO("5331", "德宏"), new AreaVO("5333", "怒江"), new AreaVO("5334", "迪庆"));
            areaTag = false;
        } else {
            areaList = energyMapper.selectAddressName(areaName + "%");
        }
        String startTime = needTime.get("开始时间");
        String endTime = needTime.get("结束时间");
        areaAndIndustryVos = getCompanyList2020GroupByExceptionArea(area, areaList, startTime + "-01 00:00:00", endTime + "-31 23:59:59", industryName, type, areaName, true, areaTag, cmpName);*/
        return R.ok(areaOrder, "查询成功");
    }

    /**
     * 按照行业查询异常总数并排序
     */
    @Override
    public R getExceptionByIndustryOrder(String area, String industry, String time, String cmpName, String type) {
        String preTime = time.substring(0, 7);
        String endTime = time.substring(11, 18);
        HashMap<String, String> areaAndIndustryCode = getAreaAndIndustryCode(area, industry);
        //得到地区，行业编码
        String areaName = areaAndIndustryCode.get("地区");
        //String industryName = areaAndIndustryCode.get("行业");
        if(StringUtils.isBlank(type)){
            type = "1,2,3,4,5";
        }
        if(StringUtils.isNotBlank(industry) && industry.contains("全部")){
            industry = "";
        }
        ArrayList<AreaAndIndustryVo> industryOrder = energyMapper.selectExceptionByIndustryOrder(areaName, cmpName, type, industry, preTime, endTime);
        return R.ok(industryOrder, "查询成功");
    }

    /**
     * 异常公司排名
     */
    @Override
    public R getExceptionEnterpriseOrder(String area, String industry, String time, String cmpName, String type, String orderFiled) {
        HashMap<String, String> areaAndIndustryCode = getAreaAndIndustryCode(area, industry);
        String areaName = areaAndIndustryCode.get("地区");
        //String industryName = areaAndIndustryCode.get("行业");
        String preTime = time.substring(0, 7);
        String endTime = time.substring(11, 18);
        if(StringUtils.isBlank(orderFiled)){
            orderFiled = "value";
        }
        if(StringUtils.isBlank(type)){
            type = "1,2,3,4,5";
        }
        if(StringUtils.isNotBlank(industry) && industry.contains("全部")){
            industry = "";
        }
        List<EnterpriseExceptionVo> list = energyMapper.selectExceptionEnterpriseInfo(areaName, cmpName, type, industry, preTime, endTime, orderFiled);
        return R.ok(list, "查询成功");
    }

    @Override
    public R getCollectByArea(String area, String industry, String time) {
        ConditionBo condition = getCondition(area, industry, time);
        Integer length = "53".equals(condition.getAreaCode()) ? 4 : 6;
        ArrayList<CoalVo> resultList = energyMapper.getCollectByArea(condition.getAreaCode(), condition.getIndustryCode(), condition.getPreTime(), condition.getEndTime(), length);
        /*ArrayList<AreaVO> areaList = new ArrayList<>();
        ArrayList<CoalVo> resultList = new ArrayList<>();
        areaList = getAreaList(area, areaList, condition);
        // 遍历areaList获取记录
        for (int i = 0; i < areaList.size(); i++) {
            AreaVO areaVO = areaList.get(i);
            CoalVo result = energyMapper.countCollectNUmsByArea(areaVO.getCode(), condition.getIndustryCode(), condition.getPreTime(), condition.getEndTime());
            result.setMonth(areaVO.getName());
            resultList.add(result);
        }
        if (!"云南".equals(area)) {
            CoalVo coalVo = resultList.get(0);
            //coalVo.setMonth("其他");
        }
        AreaVoSort(resultList);*/
        return R.ok(resultList, "查询成功");
    }

    private ArrayList<AreaVO> getAreaList(String area, ArrayList<AreaVO> areaList, ConditionBo condition) {
        if ("云南".equals(area)) {
            areaList = new ArrayList<>(energyMapper.areaList("530000"));
        } else {
            areaList = energyMapper.selectAddressName(condition.getAreaCode() + "%");
        }
        return areaList;
    }

    private void AreaVoSort(ArrayList<CoalVo> resultList) {
        Collections.sort(resultList, new Comparator<CoalVo>() {
            @Override
            public int compare(CoalVo o1, CoalVo o2) {
                return Integer.valueOf(o1.getValue()) > Integer.valueOf(o2.getValue()) ? -1 : 1;
            }
        });
    }

    @Override
    public R getCollectByIndustry(String area, String industry, String time) {
        ConditionBo condition = getCondition(area, industry, time);
        ArrayList<CoalVo> resultLists = energyMapper.getCollectByIndustry(condition.getAreaCode(), condition.getIndustryCode(), condition.getPreTime(), condition.getEndTime());
        /*ArrayList<AreaVO> industryList = new ArrayList<>();
        if ("全部".equals(industry)) {
            industryList = energyMapper.selectAllIndustry();
        } else {
            industryList.add(new AreaVO(condition.getIndustryCode(), industry));
        }
        for (int i = 0; i < industryList.size(); i++) {
            AreaVO industryVo = industryList.get(i);
            CoalVo coalVo = energyMapper.countCollectNUmsByArea(condition.getAreaCode(), industryVo.getCode(), condition.getPreTime(), condition.getEndTime());
            coalVo.setMonth(industryVo.getName());
            resultLists.add(coalVo);
        }
        AreaVoSort(resultLists);*/
        return R.ok(resultLists, "查询成功");
    }

    @Override
    public R getCollectByMonth(String area, String industry, String time) {
        ConditionBo condition = getCondition(area, industry, null);
        ArrayList<CoalVo> resultList = new ArrayList<>();
        getTimeList(time, resultList, 12);
        resultList = energyMapper.getCollectByMonth(condition.getAreaCode(), condition.getIndustryCode(), resultList, time);
        //List<CoalVo> list = energyMapper.countByMonth(condition.getAreaCode(), condition.getIndustryCode(), time);
        //setTimeListValue(list, resultList);
        return R.ok(resultList, "查询成功");
    }

    @Override
    public R getCollectByDay(String area, String industry, String time) {
        ConditionBo condition = getCondition(area, industry, null);
        ArrayList<CoalVo> resultList = new ArrayList<>();
        int day = getDaysOfMonth(time);
        getTimeList(time, resultList, day);
        resultList = energyMapper.getCollectByDay(condition.getAreaCode(), condition.getIndustryCode(), resultList, time);
        //List<CoalVo> list = energyMapper.countByDay(condition.getAreaCode(), condition.getIndustryCode(), time);
        //setTimeListValue(list, resultList);
        return R.ok(resultList);
    }

    private void setTimeListValue(List<CoalVo> list, List<CoalVo> resultList) {
        a:
        for (int i = 0; i < resultList.size(); i++) {
            CoalVo coalVo = resultList.get(i);
            for (int j = 0; j < list.size(); j++) {
                CoalVo coalVo1 = list.get(j);
                if (coalVo.getMonth().equals(coalVo1.getMonth())) {
                    coalVo.setValue(coalVo1.getValue());
                    continue a;
                }
            }
        }
    }

    private void setTimeListValueNew(List<CoalVoNew> list, List<CoalVoNew> resultList) {
        a:
        for (int i = 0; i < resultList.size(); i++) {
            CoalVoNew coalVo = resultList.get(i);
            for (int j = 0; j < list.size(); j++) {
                CoalVoNew coalVo1 = list.get(j);
                if (coalVo.getMonth().equals(coalVo1.getMonth())) {
                    coalVo.setNormalUploadSuccess(coalVo1.getNormalUploadSuccess());
                    coalVo.setNormalUploadFailed(coalVo1.getNormalUploadFailed());
                    coalVo.setRepairUploadSuccess(coalVo1.getRepairUploadSuccess());
                    coalVo.setRepairUploadFailed(coalVo1.getRepairUploadFailed());
                    continue a;
                }
            }
        }
    }

    private void setTimeListValueNewDay(List<CoalVo> list, List<CoalVoNew> resultList,String flag) {
        a:
        for (int i = 0; i < resultList.size(); i++) {
            CoalVoNew coalVo = resultList.get(i);
            for (int j = 0; j < list.size(); j++) {
                CoalVo coalVo1 = list.get(j);
                if (coalVo.getMonth().equals(coalVo1.getMonth())) {
                    if(flag.equals("epclistNormalUploadSuccess")){
                        coalVo.setNormalUploadSuccess(coalVo1.getValue());
                        continue a;
                    }
                    if(flag.equals("epclistNormalUploadFailed")){
                        coalVo.setNormalUploadFailed(coalVo1.getValue());
                        continue a;
                    }
                    if(flag.equals("epclistRepairUploadSuccess")){
                        coalVo.setRepairUploadSuccess(coalVo1.getValue());
                        continue a;
                    }
                    if(flag.equals("epclistRepairUploadFailed")){
                        coalVo.setRepairUploadFailed(coalVo1.getValue());
                        continue a;
                    }

                }
            }
        }
    }

    private void getTimeList(String time, ArrayList<CoalVo> resultList, int i2) {
        for (int i = 1; i <= i2; i++) {
            if (i < 10) {
                CoalVo coalVo = new CoalVo(time + "-0" + i, null);
                resultList.add(coalVo);
            } else {
                CoalVo coalVo = new CoalVo(time + "-" + i, null);
                resultList.add(coalVo);
            }

        }
    }

    private void getTimeListNew(String time, ArrayList<CoalVoNew> resultList, int i2) {
        for (int i = 1; i <= i2; i++) {
            if (i < 10) {
                CoalVoNew coalVo = new CoalVoNew(time + "-0" + i, null);
                resultList.add(coalVo);
            } else {
                CoalVoNew coalVo = new CoalVoNew(time + "-" + i, null);
                resultList.add(coalVo);
            }

        }
    }

    @Override
    public R getUpCollectByArea(String area, String industry, String time) {
        ArrayList<AreaVO> areaList = new ArrayList<>();
        ArrayList<CoalVo> resultList = new ArrayList<>();
        ConditionBo condition = getCondition(area, industry, time);
        areaList = getAreaList(area, areaList, condition);
        // 遍历areaList获取记录
        for (int i = 0; i < areaList.size(); i++) {
            AreaVO areaVO = areaList.get(i);
            CoalVo result = energyMapper.countUpCollectNUmsByArea(areaVO.getCode(), condition.getIndustryCode(), condition.getPreTime(), condition.getEndTime());
            result.setMonth(areaVO.getName());
            resultList.add(result);
        }
        if (!"云南".equals(area)) {
            CoalVo coalVo = resultList.get(0);
            //coalVo.setMonth("其他");
        }
        AreaVoSort(resultList);
        return R.ok(resultList, "查询成功");
    }

    @Override
    public R getUpCollectByIndustry(String area, String industry, String time) {
        ArrayList<AreaVO> industryList = new ArrayList<>();
        ConditionBo condition = getCondition(area, industry, time);
        ArrayList<CoalVo> resultLists = new ArrayList<>();
        if ("全部".equals(industry)) {
            industryList = energyMapper.selectAllIndustry();
        } else {
            industryList.add(new AreaVO(condition.getIndustryCode(), industry));
        }
        for (int i = 0; i < industryList.size(); i++) {
            AreaVO industryVo = industryList.get(i);
            CoalVo coalVo = energyMapper.countUpCollectNUmsByArea(condition.getAreaCode(), industryVo.getCode(), condition.getPreTime(), condition.getEndTime());
            coalVo.setMonth(industryVo.getName());
            resultLists.add(coalVo);
        }
        AreaVoSort(resultLists);
        return R.ok(resultLists, "查询成功");
    }

    @Override
    public R getUpCollectByMonth(String area, String industry, String time) {
        ConditionBo condition = getCondition(area, industry, null);
        List<CoalVo> list = energyMapper.UpCountByMonth(condition.getAreaCode(), condition.getIndustryCode(), time);
        ArrayList<CoalVo> resultList = new ArrayList<>();
        getTimeList(time, resultList, 12);
        setTimeListValue(list, resultList);
        return R.ok(resultList, "查询成功");
    }

    @Override
    public R getUpCollectByMonthNew(String area, String industry, String time) {
        ConditionBo condition = getCondition(area, industry, null);
        List<CoalVoNew> list = energyMapper.UpCountByMonthNew(condition.getAreaCode(), condition.getIndustryCode(), time);
        ArrayList<CoalVoNew> resultList = new ArrayList<>();
        getTimeListNew(time, resultList, 12);
        setTimeListValueNew(list, resultList);
        return R.ok(resultList, "查询成功");
    }

    @Override
    public R getUpCollectByDay(String area, String industry, String time) {
        ConditionBo condition = getCondition(area, industry, null);
        List<CoalVo> list = energyMapper.UpCountByDay(condition.getAreaCode(), condition.getIndustryCode(), time);
        List<CoalVo> epclist = energyMapper.UpCountByDayEpc(condition.getAreaCode(), condition.getIndustryCode(), time);
        ArrayList<CoalVo> resultList = new ArrayList<>();
        ArrayList<CoalVo> resultListepc = new ArrayList<>();
        String month = time.substring(5);
        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;
        }
        getTimeList(time, resultList, day);
        getTimeList(time, resultListepc, day);
        setTimeListValue(list, resultList);
        setTimeListValue(epclist, resultListepc);
        return R.ok(new UpCollectVo(resultList, resultListepc));
    }

    @Override
    public R getUpCollectByDayNew(String area, String industry, String time) {
        ConditionBo condition = getCondition(area, industry, null);
        List<CoalVoNew> list = energyMapper.UpCountByDayNew(condition.getAreaCode(), condition.getIndustryCode(), time);

        List<CoalVo> epclistNormalUploadSuccess = energyMapper.UpCountByDayEpcNormalUploadSuccess(condition.getAreaCode(), condition.getIndustryCode(), time);
        List<CoalVo> epclistNormalUploadFailed = energyMapper.UpCountByDayEpcNormalUploadFailed(condition.getAreaCode(), condition.getIndustryCode(), time);
        List<CoalVo> epclistRepairUploadSuccess = energyMapper.UpCountByDayEpcRepairUploadSuccess(condition.getAreaCode(), condition.getIndustryCode(), time);
        List<CoalVo> epclistRepairUploadFailed = energyMapper.UpCountByDayEpcRepairUploadFailed(condition.getAreaCode(), condition.getIndustryCode(), time);

        ArrayList<CoalVoNew> resultListNew=new ArrayList<CoalVoNew>();
        ArrayList<CoalVoNew> resultListepcNew=new ArrayList<CoalVoNew>();

        String month = time.substring(5);
        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;
        }
        getTimeListNew(time, resultListNew, day);
        getTimeListNew(time, resultListepcNew, day);

        setTimeListValueNew(list, resultListNew);

        setTimeListValueNewDay(epclistNormalUploadSuccess, resultListepcNew,"epclistNormalUploadSuccess");
        setTimeListValueNewDay(epclistNormalUploadFailed, resultListepcNew,"epclistNormalUploadFailed");
        setTimeListValueNewDay(epclistRepairUploadSuccess, resultListepcNew,"epclistRepairUploadSuccess");
        setTimeListValueNewDay(epclistRepairUploadFailed, resultListepcNew,"epclistRepairUploadFailed");

        return R.ok(new UpCollectVoNew(resultListNew, resultListepcNew));
    }

    private ConditionBo getCondition(String area, String industry, String time) {
        HashMap<String, String> areaAndIndustryCode = getAreaAndIndustryCode(area, industry);
        String areaCode = areaAndIndustryCode.get("地区");
        String industryCode = areaAndIndustryCode.get("行业");
        HashMap<String, String> needTime = getNeedTime(time);
        String preTime = null;
        String endTime = null;
        if (needTime != null) {
            preTime = needTime.get("开始时间");
            endTime = needTime.get("结束时间");
        }
        return new ConditionBo(areaCode, industryCode, preTime, endTime);
    }

    public List<String> getElectricityCompanyList(String area, String industry, String cmpName) {
        String areaName = area;
        areaName = areaName + "%";
        String industryName = industry;
        if ("".equals(cmpName) || cmpName == null) {
            cmpName = null;
        } else {
            cmpName = "%" + cmpName + "%";
        }
        List<String> companyList = energyMapper.selectCompanyListByAreaAndIndustryElectricity(areaName, industryName, cmpName);
        if (companyList.size() == 0) {
            companyList.add("");
        }
        return companyList;
    }

    private ArrayList<AreaAndIndustryVo> getCompanyList2020GroupByArea(String area, List<AreaVO> list, String startTime, String endTime, String industryName, String areaName, Boolean tag, Boolean areaTag) {
        // 依据地区列表 获取 综合能耗和企业数量
        ArrayList<AreaAndIndustryVo> areaAndIndustryVos = new ArrayList<>();
        List<CoalVo> groupList = new ArrayList<>();
        // 一次性查询出所有需要的数据
        if (tag) {
            if ("53".equals(areaName)) {
                groupList = energyMapper.selectEnergyByAreaAndIndustry(areaName, industryName, "SUBSTR(b.regionCode,1,4)", startTime, endTime);
            } else {
                groupList = energyMapper.selectEnergyByAreaAndIndustry(areaName, industryName, "b.regionCode", startTime, endTime);
            }
        } else {
            groupList = energyMapper.selectEnergyByAreaAndIndustry(areaName, industryName, "b.tid", startTime, endTime);
        }
        HashMap<String, Float> map = new HashMap<>();
        for (int i = 0; i < groupList.size(); i++) {
            map.put(groupList.get(i).getMonth(), Float.parseFloat(groupList.get(i).getValue()));
        }
        for (AreaVO data : list) {
            String code = data.getCode();
            List<String> companyList2020;
            if (tag) {
                companyList2020 = getCompanyList2020(code, industryName, null, null);

            } else {
                companyList2020 = getCompanyList2020(areaName, code, null, null);
            }
            //Float info1 = energyMapper.getInfo2020(companyList2020, startTime, endTime);
            Float info1 = map.get(code);
            if (info1 == null) {
                info1 = 0f;
            }
            int enterpriseNum = companyList2020.size();
            if (companyList2020.contains("")) {
                enterpriseNum = enterpriseNum - 1;
            }
            AreaAndIndustryVo areaAndIndustryVo = new AreaAndIndustryVo(data.getName(), info1, enterpriseNum);
            areaAndIndustryVos.add(areaAndIndustryVo);
        }
        // 替换名称
        if (tag) {
            ArrayList<String> replaceName = new ArrayList<>();
            Collections.addAll(replaceName, "昆明", "曲靖", "玉溪", "保山", "昭通", "丽江", "普洱", "临沧",
                    "楚雄", "红河", "文山", "版纳", "大理", "德宏", "怒江", "迪庆");
            if (replaceName.contains(area)) {
                AreaAndIndustryVo areaAndIndustryVo = areaAndIndustryVos.get(0);
                //areaAndIndustryVo.setName("其他");
            }
        }
        // 排序
        Collections.sort(areaAndIndustryVos, new Comparator<AreaAndIndustryVo>() {
            @Override
            public int compare(AreaAndIndustryVo o1, AreaAndIndustryVo o2) {
                if (o1.getEnergyValue() - o2.getEnergyValue() > 0) {
                    return -1;
                } else if (o1.getEnergyValue() - o2.getEnergyValue() < 0) {
                    return 1;
                } else {
                    return 0;
                }
            }
        });
        return areaAndIndustryVos;
    }

    /**
     * @Description: 按地区得到异常排序
     * @Param: [area, list, startTime, endTime, industryName, areaName, tag, areaTag]
     * @return: java.util.ArrayList<com.nantian.cloud.dbcapp.vo.AreaAndIndustryVo>
     * @Author: zfw
     * @Date: 2021/2/22
     * @Date: 19:13
     */
    private ArrayList<AreaAndIndustryVo> getCompanyList2020GroupByExceptionArea(String area, List<AreaVO> list, String startTime, String endTime, String industryName, String type, String areaName, Boolean tag, Boolean areaTag, String cmpName) {
        // 依据地区列表 获取 综合能耗和企业数量
        ArrayList<AreaAndIndustryVo> areaAndIndustryVos = new ArrayList<>();
        List<CoalVo> valueList;
        cmpName = judgeEmpty(cmpName);
        // 按地区一次性查询
        if (areaName.equals("53")) {
            valueList = energyMapper.getExceptionToalAll(areaName + "%", industryName, cmpName, type, startTime, endTime, "SUBSTR(regionCode,1,4)");
        } else {
            valueList = energyMapper.getExceptionToalAll(areaName + "%", industryName, cmpName, type, startTime, endTime, "regionCode");
        }
        HashMap<String, Integer> valueMap = new HashMap<>();
        for (int i = 0; i < valueList.size(); i++) {
            CoalVo coalVo = valueList.get(i);
            valueMap.put(coalVo.getMonth(), Integer.valueOf(coalVo.getValue()));
        }
        for (AreaVO data : list) {
            String code = data.getCode();
//            List<String> companyList2020;
//            if(tag){
//                companyList2020 = getCompanyList2020Code(code,industryName,cmpName);
//            }else {
//                companyList2020 = getCompanyList2020(areaName,code,null, cmpName);
//            }
//            //查询异常值
//            Integer info1 = energyMapper.getExceptionToal(companyList2020,type, startTime, endTime);
//            if(info1==null){
//                info1 =0;
//            }
//            int enterpriseNum = companyList2020.size();
//            if(companyList2020.contains("")){
//                enterpriseNum = enterpriseNum - 1;
//            }
            Integer s = valueMap.get(code);
            if (s == null) {
                s = 0;
            }
            AreaAndIndustryVo areaAndIndustryVo = new AreaAndIndustryVo(data.getName(), Float.valueOf(s), null);
            areaAndIndustryVos.add(areaAndIndustryVo);
        }
        // 替换名称
        ArrayList<String> replaceName = new ArrayList<>();
        Collections.addAll(replaceName, "昆明", "曲靖", "玉溪", "保山", "昭通", "丽江", "普洱", "临沧",
                "楚雄", "红河", "文山", "版纳", "大理", "德宏", "怒江", "迪庆");
        if (replaceName.contains(area)) {
            AreaAndIndustryVo areaAndIndustryVo = areaAndIndustryVos.get(0);
            //areaAndIndustryVo.setName("其他");
        }
        // 排序
        Collections.sort(areaAndIndustryVos, new Comparator<AreaAndIndustryVo>() {
            @Override
            public int compare(AreaAndIndustryVo o1, AreaAndIndustryVo o2) {
                if (o1.getEnergyValue() - o2.getEnergyValue() > 0) {
                    return -1;
                } else if (o1.getEnergyValue() - o2.getEnergyValue() < 0) {
                    return 1;
                } else {
                    return 0;
                }
            }
        });
        return areaAndIndustryVos;
    }

    private List<String> getCompanyList2020Code(String area, String industry, String enterpriseCode) {
        String areaName = area;
        areaName = areaName + "%";
        String industryName = industry;
        if ("".equals(enterpriseCode) || enterpriseCode == null) {
            enterpriseCode = null;
        }
        List<String> companyList = energyMapper.selectCompanyListByAreaAndIndustryAndCode(areaName, industryName, enterpriseCode);
        if (companyList.size() == 0) {
            companyList.add("");
        }
        return companyList;
    }

    private ArrayList<AreaAndIndustryVo> getCompanyList2019GroupByArea(String area, List<AreaVO> list, String startTime, String endTime, String industryName, String areaName, Boolean tag) {
        // 依据地区列表 获取 综合能耗和企业数量
        ArrayList<AreaAndIndustryVo> areaAndIndustryVos = new ArrayList<>();
        for (AreaVO data : list) {
            String code = data.getCode();
            List<String> companyList2019;
            if (tag) {
                companyList2019 = getCompanyList2019(code, industryName, null, null);
            } else {
                companyList2019 = getCompanyList2019(areaName, code, null, null);
            }
            /*List<Integer> entList = getentIdByEnterpriseCode(companyList2019);
            Float info1 = 0f;
            if (entList != null && entList.size() > 0) {
                info1 = energyMapper.getInfo2019ByEntList(entList, startTime, endTime);
            }*/
            Float info1 = 0f;
            if(companyList2019 != null && companyList2019.size() > 0){
                info1 = energyMapper.getInfo2019( companyList2019, area, industryName, startTime, endTime);
            }

           /* if(info1==null){
                info1 =0f;
            }*/
            AreaAndIndustryVo areaAndIndustryVo = new AreaAndIndustryVo(data.getName(), info1, companyList2019.size());
            areaAndIndustryVos.add(areaAndIndustryVo);
        }
        // 替换名称
        /*ArrayList<String> replaceName = new ArrayList<>();
        Collections.addAll(replaceName, "昆明", "曲靖", "玉溪", "保山", "昭通", "丽江", "普洱", "临沧",
                "楚雄", "红河", "文山", "版纳", "大理", "德宏", "怒江", "迪庆");
        if (replaceName.contains(area)) {
            AreaAndIndustryVo areaAndIndustryVo = areaAndIndustryVos.get(0);
            //areaAndIndustryVo.setName("其他");
        }*/
        // 排序
        Collections.sort(areaAndIndustryVos, new Comparator<AreaAndIndustryVo>() {
            @Override
            public int compare(AreaAndIndustryVo o1, AreaAndIndustryVo o2) {
                if (o1.getEnergyValue() - o2.getEnergyValue() > 0) {
                    return -1;
                } else if (o1.getEnergyValue() - o2.getEnergyValue() < 0) {
                    return 1;
                } else {
                    return 0;
                }
            }
        });
        return areaAndIndustryVos;
    }

    private HashMap<String, String> getNeedTime(String time) {
        if (time != null) {
            HashMap<String, String> stringStringHashMap = new HashMap<>();
            String startTime = time.split("&")[0];
            String endTime = time.split("&")[1];
            startTime = startTime.substring(0, 7);
            endTime = endTime.substring(0, 7);
            String timeStr = startTime.substring(0, 4);
            String timeStr1 = endTime.substring(0, 4);
            stringStringHashMap.put("时间期限", timeStr);
            stringStringHashMap.put("结束时间期限", timeStr1);
            stringStringHashMap.put("开始时间", startTime);
            stringStringHashMap.put("结束时间", endTime);
            return stringStringHashMap;
        } else {
            return null;
        }
    }

    @Override
    public HashMap<String, String> getAreaAndIndustryCode(String area, String industry) {
        HashMap<String, String> map = new HashMap<>();
        HashMap<String, String> areaMapA = areaCode.getAreaMapA();
        String areaName = "";
        if (isNUm(area)) {
            areaName = area;
        } else {
            areaName = areaMapA.get(area);
        }
        if(StringUtils.isNotBlank(area) && StringUtils.isBlank(areaName)){ //area不为空，进行翻译
            areaName = energyMapper.getDictRegionCode(area);
        }
        areaName = areaName.replaceAll("0000","").replaceAll("00","");
        map.put("地区", areaName);

        HashMap<String, String> industryMap = industryCode.getIndustryMap();
        String industryName = "";
        if(StringUtils.isNotBlank(industry)){
            industryName = industryMap.get(industry);
        }
        map.put("行业", industryName);
        return map;
    }

    private Boolean isNUm(String area) {
        Pattern pattern = Pattern.compile("[0-9]*");
        return pattern.matcher(area).matches();
    }

    @Override
    public List<Integer> getentIdByEnterpriseCode(List<String> companyList) {
        return energyMapper.getentIdByEnterpriseCode(companyList);
    }

    @Override
    public List<OtherCompanyListVo> getCountyNameList(String area, String industry) {
        List<OtherCompanyListVo> result = new ArrayList<>();
        // 获取地区 行业列表
        HashMap<String, String> areaAndIndustryCode = getAreaAndIndustryCode(area, industry);
        String areaName = areaAndIndustryCode.get("地区");
        String industryName = areaAndIndustryCode.get("行业");
        ArrayList<AreaVO> areaList = new ArrayList<>();
        ArrayList<AreaVO> industryList = new ArrayList<>();
        if (areaName.equals("53")) {
            areaList = new ArrayList<>(energyMapper.areaList("530000"));
        } else {
            areaList = energyMapper.selectAddressName(areaName + "%");
        }
        if ("全部".equals(industry)) {
            industryList = new ArrayList<>(energyMapper.industryList());
        } else {
            industryList = energyMapper.selectIndustryList(industryName);
        }

        //分地区 行业查询 电力关口企业明细
       /* List<AreaVO> voList;
        if (areaName.equals("53")) {
            voList = energyMapper.selectCountNumByAreaAndIndustry(areaName, industryName, "electric_enterprise_info", "SUBSTR(regionCode,1,4)", "industry_code");
        } else {
            voList = energyMapper.selectCountNumByAreaAndIndustry(areaName, industryName, "electric_enterprise_info", "regionCode", "industry_code");
        }
        List<EpcVo> nameList = energyMapper.selectEcpName(areaName, industryName, "cmpName", "electric_enterprise_info", "regionCode", "industry_code");*/
        List<AreaVO> voList = energyMapper.getEpcInfo(areaName,industryName,"2");
        List<EpcVo> nameList = energyMapper.getEpcDetailInfo(areaName,industryName,"2");
        OtherCompanyListVo epcResultList = getEpcResultList(areaList, industryList, voList, nameList);
        result.add(epcResultList);

        //分地区 行业查询 上送国家企业明细
        List<AreaVO> voList1;
        if (areaName.equals("53")) {
            voList1 = energyMapper.selectCountNumByAreaAndIndustryUpLoad(areaName, industryName, "SUBSTR(regionCode,1,4)");
        } else {
            voList1 = energyMapper.selectCountNumByAreaAndIndustryUpLoad(areaName, industryName, "regionCode");
        }
        List<EpcVo> nameList1 = energyMapper.selectEcpNameUpLoad(areaName, industryName);
        OtherCompanyListVo epcResultList1 = getEpcResultList(areaList, industryList, voList1, nameList1);
        result.add(epcResultList1);

        // 分地区 ，行业查询 在线监测企业明细
        /*List<AreaVO> voList2;
        if (areaName.equals("53")) {
            voList2 = energyMapper.selectCountNumByAreaAndIndustryAll(areaName, industryName, "SUBSTR(regionCode,1,4)");
        } else {
            voList2 = energyMapper.selectCountNumByAreaAndIndustryAll(areaName, industryName, "regionCode");
        }
        List<EpcVo> nameList2 = energyMapper.selectEcpNameAll(areaName, industryName);*/
        List<AreaVO> voList2 = energyMapper.getEpcInfo(areaName,industryName,"");
        List<EpcVo> nameList2 = energyMapper.getEpcDetailInfo(areaName,industryName,"");
        OtherCompanyListVo epcResultList2 = getEpcResultList(areaList, industryList, voList2, nameList2);
        result.add(epcResultList2);
        return result;
    }

    /*@Override
    @Transactional
    public R updateException(List<ExceptionInfoVo> datas) {
        //处理异常 1.波动异常需多数据源修改数据 2.传输异常需要补录数据  处理异常的工作交给 mv完成
        Integer state = 0, staus = 0;
        for (int i = 0; i < datas.size(); i++) {
            ExceptionInfoVo data = datas.get(i);
            String id = data.getId();
            // 若非传输异常，同步修改采集表.否则补传数据
            if (data.getExceptionType() != null && !"4".equals(data.getExceptionType())) {
                //energyMapper.updateInfoByEpcDcSd(data);
                R r = mvService.updateWaveException(data);
                staus = r.getCode();
            } else {
                //传输异常,需补传数据
                if(data.getDataValue()==null){
                    data.setDataValue("0");
                }
                if(data.getConvertRation()==null){
                    data.setConvertRation("0");
                }
                R r = mvService.updateTransException(data);
                staus = r.getCode();
            }
            if(staus == 0){ //成功
                state = energyMapper.updateExceptionInfo(data);
            }
        }
        if (state == 0) {
            return R.ok("no", "修改失败");
        } else {
            return R.ok("yes", "修改成功");
        }
    }*/

    @Override
    public R waveExceptionList(String enterpriseCode, String dataCode, String time) {
        //获取当前近一月时间
        String pre;
        String end;
        if (time == null || time.equals("")) {
            pre = getAnyTime(-30);
            end = getAnyTime(0);
            time = pre + "&" + end;
        } else {
            HashMap<String, String> needTime = getNeedTime(time);
            pre = needTime.get("开始时间") + "-01";
            end = needTime.get("结束时间") + "-31";
        }
        List<CoalVo> list = energyMapper.waveExceptionList(enterpriseCode, dataCode, pre + " 00:00:00", end + " 23:59:59");
        return R.ok(list, "查询成功");
    }

    @Override
    public R updateExceptionAll(ExceptionInfoVo data) {
        Integer state = 0;
        state = energyMapper.updateExceptionInfoAll(data);
        // 若非传输异常，同步修改采集表.否则补传数据
        if (!"4".equals(data.getExceptionType())) {
            // energyMapper.updateInfoByEpcDcSd(data);
        }
        if ("2".equals(data.getExceptionType())) {
            // 将该企业该采集点添加，此后不再视为该企业该折标系数为折标系数异常记录
            energyMapper.insertExceptionRation(data);
        }
        if (state == 0) {
            return R.ok("no", "修改失败");
        } else {
            return R.ok("yes", "修改成功");
        }
    }

    @Override
    public EnergyCalculateCommonVo getEnergyCalculateInfo(Page page, String enterpriseCode, String statDate, String state) {
        enterpriseCode = judgeEmpty(enterpriseCode);
        statDate = judgeEmpty(statDate);
        state = judgeEmpty(state);
        //Page<Object> objects = PageHelper.startPage(Integer.valueOf(current), Integer.valueOf(size));
        IPage<CalculateLogsVo> energyCalculateInfoPage = energyMapper.getEnergyCalculateInfo(page, enterpriseCode, statDate, state);
        //PageInfo<CalculateLogsVo> objectPageInfo = new PageInfo(objects.getResult());
        //Integer total = Math.toIntExact(objectPageInfo.getTotal());
        return new EnergyCalculateCommonVo(energyCalculateInfoPage.getRecords(), energyCalculateInfoPage.getTotal());
    }

    private String judgeEmpty(String enterpriseCode) {
        if ("".equals(enterpriseCode)) {
            enterpriseCode = null;
        }
        return enterpriseCode;
    }

    @Override
    public EnergyCalculateCommonVo getEnergyCalculateAddInfo(Page page, String enterpriseCode, String statDate, String dataCode) {
        enterpriseCode = judgeEmpty(enterpriseCode);
        statDate = judgeEmpty(statDate);
        dataCode = judgeEmpty(dataCode);
        //Page<Object> page = PageHelper.startPage(Integer.valueOf(current), Integer.valueOf(size));
        IPage<EnergyCalculateAddInfo> calculateAddInfoPage = energyMapper.getEnergyCalculateAddInfo( page, enterpriseCode, statDate, dataCode);
        //PageInfo pageInfo = new PageInfo(page.getResult());
        //long total = pageInfo.getTotal();
        return new EnergyCalculateCommonVo(calculateAddInfoPage.getRecords(), calculateAddInfoPage.getTotal());
    }

    @Override
    public R upDateEnterpriseRegionCode(String enterpriseCode, String regionCode) {
        Integer result = energyMapper.upDateEnterpriseRegionCode(enterpriseCode, regionCode);
        if (result > 0) {
            return R.ok("success", "修改成功");
        } else {
            return R.ok("fail", "修改失败");
        }
    }

    @Override
    public R getCollectEnterpriseInfo(String area, String industry, String cmpName) {
        HashMap<String, String> areaAndIndustryCode = getAreaAndIndustryCode(area, industry);
        String areaCode = areaAndIndustryCode.get("地区");
        String industryCode = areaAndIndustryCode.get("行业");
        List<EpcVo> list = energyMapper.selectCollectEnterpriseInfo(areaCode, industryCode, cmpName);
        return R.ok(list);
    }

    @Override
    public R getRegionTrees(String regionCode) {
        if ("".equals(regionCode) || regionCode == null) {
            regionCode = "53000";
        }
        List<TreeVo> dictRegionTree;
        dictRegionTree = energyMapper.getDictRegionTree(regionCode);
        dictRegionTree = treeVoUtil.findTree(dictRegionTree, regionCode);
        return R.ok(dictRegionTree);
    }

    @Override
    public R saveExceptionalLog(TExceptionHandlingLogVo tExceptionHandlingLogVo) {
        ScUser u = SecurityUtils.getUser();
        if (u.getId() != null) {
            tExceptionHandlingLogVo.setUserid(u.getId());
        }
        tExceptionHandlingLogVo.setUpdateTime(new Date());
        tExceptionHandlingLogVo.setDelFlag("1");
        tExceptionHandlingLogVo.setDeptId(u.getDeptId());
        tExceptionHandlingLogVo.setCreatTime(new Date());
        tExceptionHandlingLogVo.setName(u.getUsername());
        Integer integer = energyMapper.saveExceptionalLog(tExceptionHandlingLogVo);
        if (integer != 0) {
            return R.ok("success");
        } else {
            return R.ok("fail");
        }

    }

    @Override
    public EnergyCalculateCommonVo getExceptionalLog(Page page, String epc) {
        //Page<Object> page = PageHelper.startPage(Integer.valueOf(current), Integer.valueOf(size));
        IPage<TExceptionHandlingLogVo> exceptionalLogPage = energyMapper.getExceptionalLog( page, epc);
        //PageInfo pageInfo = new PageInfo(exceptionalLog);
        //long total = pageInfo.getTotal();
        return new EnergyCalculateCommonVo(exceptionalLogPage.getRecords(), exceptionalLogPage.getTotal());
    }

    @Override
    public Object updateDateCodeState(String enterpriseCode, String dataCode, Integer state) {
        Integer states = energyMapper.updateDataCodeState(enterpriseCode, dataCode, state);
        energyMapper.updateDataCodeStateNew(enterpriseCode, dataCode, state);
        return null;
    }

    @Override
    public List<Integer> getEnergyTableEpc(String statDate) {
        return energyMapper.getEnergyTableEpc(statDate);
    }

    @Override
    public List<CoalVo> getEnergyTableEpcTotal(String statDate, String area, String industry) {
        HashMap<String, String> areaAndIndustryCode = getAreaAndIndustryCode(area, industry);
        String areaCode = areaAndIndustryCode.get("地区");
        String industryCode = areaAndIndustryCode.get("行业");
        List<String> epcLists = energyMapper.selectEpcByTime(statDate, areaCode, industryCode);
        //Float monthValue = energyMapper.getInfo2020(epcLists, statDate, statDate);
        // 循环查询
        String year = statDate.substring(0, 4);
        Integer maxMonth = Integer.valueOf(statDate.substring(5, 7));
        //Float  yearValue = 0.0f;
        ArrayList<CoalVo> floats = new ArrayList<>();
        for (int i = 1; i <= maxMonth; i++) {
            String baseTime = null;
            if (i < 10) {
                baseTime = year + "-0" + i;
            } else {
                baseTime = year + "-" + i;
            }
            List<String> strings = energyMapper.selectEpcByTime(baseTime, areaCode, industryCode);
            Float infoValue = energyMapper.getInfo2020(strings, baseTime, baseTime);
            floats.add(new CoalVo(baseTime, String.valueOf(infoValue)));
        }
        return floats;
    }

    @Override
    public HashMap<String, List<CoalVo>> getEnergyTableOutput(String statDate, String area, String industry) {
        HashMap<String, String> areaAndIndustryCode = getAreaAndIndustryCode(area, industry);
        String areaCode = areaAndIndustryCode.get("地区");
        String industryCode = areaAndIndustryCode.get("行业");
        String preTime = statDate.substring(0, 4) + "-01";
        List<CoalVo> value1 = new ArrayList<>();
        List<CoalVo> value2 = new ArrayList<>();
        List<CoalVo> value3 = new ArrayList<>();
        for (int i = 1; i <= Integer.valueOf(statDate.substring(5, 7)); i++) {
            String base = statDate.substring(0, 4);
            if (i < 10) {
                base = base + "-0" + i;
            } else {
                base = base + "-" + i;
            }
            CoalVo outputValue = energyMapper.selectOutputValue(preTime, base, areaCode, industryCode, "sum(outputValue)");
            if (outputValue != null) {
                value1.add(outputValue);
            } else {
                value1.add(new CoalVo(base, null));
            }
            CoalVo energyOutputValue = energyMapper.selectOutputValue(preTime, base, areaCode, industryCode, "sum(energyOutputValue)");
            if (energyOutputValue != null) {
                value2.add(energyOutputValue);
            } else {
                value2.add(new CoalVo(base, null));
            }
            if (outputValue != null && energyOutputValue != null) {
                value3.add(new CoalVo(outputValue.getMonth(), String.valueOf(Float.valueOf(outputValue.getValue()) * Float.valueOf(energyOutputValue.getValue()))));
            } else {
                value3.add(new CoalVo(base, null));
            }
        }
        HashMap<String, List<CoalVo>> stringListHashMap = new HashMap<>();
        stringListHashMap.put("总产值", value1);
        stringListHashMap.put("产值能耗", value2);
        stringListHashMap.put("综合能耗", value3);
        return stringListHashMap;
    }

    @Override
    public HashMap<String, List<CoalVo>> getEnergyTableOutputOrder(String statDate, String area, String industry) {
        // 按企业排序
        HashMap<String, List<CoalVo>> stringListHashMap = new HashMap<>();
        List<String> epcLists = getStrings(statDate, area, industry);
        if (epcLists.size() > 0) {
            List<CoalVo> listEpcDesc = energyMapper.selectMaxValue(epcLists, "enterprise_id", "desc", statDate);
            List<AreaVO> areaLists = getAreaLists(area, industry);
            Map<String, String> collect = areaLists.stream().collect(Collectors.toMap(AreaVO::getCode, AreaVO::getName));
            List<CoalVo> listArea;
            if ("53".equals(area) || "云南".equals(area)) {
                listArea = energyMapper.getEffectiveAreaOrder(epcLists, "substring(regionCode,1,4)", statDate);
                setEffectAreaName(collect, listArea);
            } else {
                listArea = energyMapper.getEffectiveAreaOrder(epcLists, "regionCode", statDate);
                setEffectAreaName(collect, listArea);
            }
            List<AreaVO> effectiveIndustryList = energyMapper.industryList();
            Map<String, String> collect1 = effectiveIndustryList.stream().collect(Collectors.toMap(AreaVO::getCode, AreaVO::getName));
            List<CoalVo> listIndustry = energyMapper.getEffectiveAreaOrder(epcLists, "tid", statDate);
            setEffectAreaName(collect1, listIndustry);
            stringListHashMap.put("enterpriseOrder", listEpcDesc);
            stringListHashMap.put("areaOrder", listArea);
            stringListHashMap.put("industryOrder", listIndustry);
            HashMap<String, String> areaAndIndustryCode = getAreaAndIndustryCode(area, industry);
            String areaCode = areaAndIndustryCode.get("地区");
            String industryCode = areaAndIndustryCode.get("行业");
            List<CoalVo> listEpcOutputDesc = energyMapper.selectMaxOutValue(statDate, areaCode, industryCode);
            stringListHashMap.put("outputValueEpcOrder", listEpcOutputDesc);
            List<CoalVo> listOutArea;
            if ("53".equals(area) || "云南".equals(area)) {
                listOutArea = energyMapper.getEffectiveAreaOutOrder("substring(regionCode,1,4)", statDate, areaCode, industryCode);
                setEffectAreaName(collect, listOutArea);
            } else {
                listOutArea = energyMapper.getEffectiveAreaOutOrder("regionCode", statDate, areaCode, industryCode);
                setEffectAreaName(collect, listOutArea);
            }
            stringListHashMap.put("outPutValueAreaOrder", listOutArea);
            List<CoalVo> listOutIndustry = energyMapper.getEffectiveAreaOutOrder("tid", statDate, areaCode, industryCode);
            setEffectAreaName(collect1, listOutIndustry);
            stringListHashMap.put("outPutValueIndustryOrder", listOutIndustry);
            return stringListHashMap;
        } else {
            return stringListHashMap;
        }
    }

    private void setEffectAreaName(Map<String, String> collect, List<CoalVo> listArea) {
        for (int i = 0; i < listArea.size(); i++) {
            CoalVo coalVo = listArea.get(i);
            String month = coalVo.getMonth();
            String s = collect.get(month);
            coalVo.setMonth(s);
        }
    }

    private List<AreaVO> getAreaLists(String area, String industry) {
        HashMap<String, String> areaAndIndustryCode = getAreaAndIndustryCode(area, industry);
        String areaName = areaAndIndustryCode.get("地区");
        List<AreaVO> areaList = new ArrayList<>();
        if ("云南".equals(area) || areaName.equals("53")) {
            areaList = energyMapper.areaList("530000");
        } else {
            areaList = energyMapper.selectAddressName(areaName + "%");
        }
        return areaList;
    }

    @Override
    public HashMap<String, CovalVoInfo> getEnergyTableEpcKinds(String statDate, String area, String industry) {
        HashMap<String, List<String>> stringListHashMap = new HashMap<>();
        stringListHashMap.put("煤", Arrays.asList("0100", "0102", "0103", "0104", "0105"));
        stringListHashMap.put("电", Arrays.asList("3300"));
        stringListHashMap.put("柴油", Arrays.asList("2100"));
        stringListHashMap.put("天然气", Arrays.asList("1500", "1600"));
        stringListHashMap.put("焦炭", Arrays.asList("0900"));
        HashMap<String, CovalVoInfo> resultMap = new HashMap<>();
        String preTime = statDate.substring(0, 4);
        ArrayList<CoalVo> coalVos = new ArrayList<>();
        ArrayList<CoalVo> endMonth = new ArrayList<>();
        for (String data : stringListHashMap.keySet()) {
            ArrayList<CoalVo> values = new ArrayList<>();
            for (int i = 1; i <= Integer.valueOf(statDate.substring(5, 7)); i++) {
                String base;
                if (i < 10) {
                    base = preTime + "-0" + i;
                } else {
                    base = preTime + "-" + i;
                }
                List<String> epcLists = getStrings(base, area, industry);
                CoalVo value = energyMapper.selectValueByKinds(epcLists, base, stringListHashMap.get(data), preTime);
                if (value != null) {
                    values.add(value);
                } else {
                    CoalVo coalVo = new CoalVo(base, "0");
                    values.add(coalVo);
                }
                if (i == Integer.valueOf(statDate.substring(5, 7))) {
                    if (value != null) {
                        String v = value.getValue();
                        endMonth.add(new CoalVo(data, v));
                    } else {
                        endMonth.add(new CoalVo(data, "0"));
                    }
                }
            }
            Float sum = 0.0f;
            for (int i = 0; i < values.size(); i++) {
                CoalVo coalVo = values.get(i);
                if (coalVo != null) {
                    String value1 = coalVo.getValue();
                    sum = sum + Float.valueOf(value1);
                }
            }
            resultMap.put(data, new CovalVoInfo(values, sum));
            CoalVo coalVo = new CoalVo(data, String.valueOf(sum));
            coalVos.add(coalVo);
        }
        resultMap.put("能源消费结构", new CovalVoInfo(coalVos, null));
        resultMap.put("当月能源消费结构", new CovalVoInfo(endMonth, null));
        return resultMap;
    }

    private List<String> getStrings(String statDate, String area, String industry) {
        HashMap<String, String> areaAndIndustryCode = getAreaAndIndustryCode(area, industry);
        String areaCode = areaAndIndustryCode.get("地区");
        String industryCode = areaAndIndustryCode.get("行业");
        return energyMapper.selectEpcByTime(statDate, areaCode, industryCode);
    }

    private String getAnyTime(Integer i) {
        Calendar calendar1 = Calendar.getInstance();
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
        calendar1.add(Calendar.DATE, i);
        String pre = sdf1.format(calendar1.getTime());
        return pre;
    }

    private OtherCompanyListVo getEpcResultList(ArrayList<AreaVO> areaList, ArrayList<AreaVO> industryList, List<AreaVO> voList, List<EpcVo> nameList) {
        HashMap<String, String> stringStringHashMap = new HashMap<>();
        List<AreaVO> areaVoS = CheckoutUtil.deepCopy(areaList);
        List<AreaVO> industryVos = CheckoutUtil.deepCopy(industryList);
        for (AreaVO data : voList) {
            stringStringHashMap.put(data.getCode(), data.getName());
        }
        for (int i = 0; i < areaVoS.size(); i++) {
            getEnterpriseNum(areaVoS, stringStringHashMap, i, areaList);
        }
        for (int i = 0; i < industryVos.size(); i++) {
            getEnterpriseNum(industryVos, stringStringHashMap, i, industryList);
        }
        //排序
        simpleSort(areaVoS);
        simpleSort(industryVos);
        OtherCompanyListVo otherCompanyListVo = new OtherCompanyListVo();
        otherCompanyListVo.setAreaList(areaVoS);
        otherCompanyListVo.setIndustryList(industryVos);
        otherCompanyListVo.setCmpNameList(nameList);
        return otherCompanyListVo;
    }

    private void simpleSort(List<AreaVO> areaList) {
        Collections.sort(areaList, new Comparator<AreaVO>() {
            @Override
            public int compare(AreaVO o1, AreaVO o2) {
                return Integer.valueOf(o1.getCode()) > Integer.valueOf(o2.getCode()) ? -1 : 1;
            }
        });
    }

    private void getEnterpriseNum(List<AreaVO> areaList, HashMap<String, String> stringStringHashMap, int i, List<AreaVO> baseList) {
        AreaVO areaVO = areaList.get(i);
        AreaVO baseAreaVO = baseList.get(i);
        String s = stringStringHashMap.get(baseAreaVO.getCode());
        if (s != null) {
            areaVO.setCode(s);
        } else {
            areaVO.setCode("0");
        }
    }

    //查询你企业list带单位搜索
    public List<String> companyList2019(String area, String industry, String time, String cmpName) {
        //截取时间
        String startTime = null;
        String endTime = null;
        if (time.contains("&")) {
            startTime = time.split("&")[0];
            endTime = time.split("&")[1];
            startTime = startTime.substring(0, 7);
            endTime = endTime.substring(0, 7);

        }
        //匹配地区 昆明市、曲靖市、玉溪市、昭通市、丽江市、普洱市、保山市、临沧市、楚雄州、红河州、迪庆州、文山州、西双版纳州、大理州、德宏州、怒江州
        HashMap<String, String> areaAndIndustryCode = getAreaAndIndustryCode(area, industry);
        String areaCode = (area.trim().equals("53") || area.trim().equals("云南")) ? "53" : areaAndIndustryCode.get("地区");
        int code = Integer.parseInt(areaCode);
        String inde1 = industry.trim().equals("全部") ? null : areaAndIndustryCode.get("行业");

        List<String> companyList = new ArrayList<>();
        if (Integer.valueOf(startTime.substring(0, 4)) >= 2020) { //查询2020年
            companyList = energyMapper.getAllCompanyList2020(code, inde1);
        } else {//查询2019年
            companyList = energyMapper.getAllCompanyList2019(code, inde1, cmpName);
        }
        return companyList;
    }

    @Override
    public R getEnergyTableInfos(String statDate, String epcStr) throws ParseException {
        //statDate取值 2021-08
        Map<String, Object> result = new HashMap();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        String startTime = statDate.substring(0,4)+"-01";
        String[] statDateList = monthList(startTime, statDate);

        Calendar cal = Calendar.getInstance();
        cal.setTime(sdf.parse(statDate));
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH) + 1;

        //获取企业每月的综合能耗(单位万tce)
        energyMapper.deleteEnergyTce(year); //清空表
        List<EnterpriseTce> energyEpc = energyMapper.getEnergyInfoByEpc(statDateList, year);
        //energyMapper.insertEnergyTce(energyEpc);
        energyMapper.updateEnergyTce(); //设置合计值、能耗为0出现次数

        //地区每月综合能耗(单位万tce)
        List<EnterpriseTce> regionTce = energyMapper.getEnergyInfoByRegion(year);
        List<EnterpriseTce> newRegionTce = new ArrayList<>();
        for (EnterpriseTce tce : regionTce) {
            newRegionTce.add(tce.monthGroupConcat(tce));
        }
        result.put("region",newRegionTce);

        //行业每月综合能耗(单位万tce)
        String tradeStr = "'钢铁', '水泥', '铝冶炼', '铜冶炼', '铅锌冶炼', '铁合金冶炼', '硅冶炼', '钛白粉', '合成氨', '磷肥制造', '炼焦', '电石', '火力发电', '平板玻璃制造', '其他玻璃制造', '造纸'";
        List<EnterpriseTce> tradeTce = energyMapper.getEnergyInfoByTrade(year, tradeStr);
        List<EnterpriseTce> newTradeTce = new ArrayList<>();
        for (EnterpriseTce tce : tradeTce) {
            newTradeTce.add(tce.monthGroupConcat(tce));
        }
        result.put("trade",newTradeTce);

        //查询新增企业综合能耗(单位tce)
        List<Map<String, Object>> newEnterpriseTce = energyMapper.getNewEnterpriseTce(statDate, year);
        result.put("newCount", newEnterpriseTce.size());
        result.put("newEnterprise", newEnterpriseTce);
        /*//查询异常企业综合能耗(单位tce)
        //异常企业指采集点数据未传齐的企业（异常编码为0101），其中异常企业不包含本月新增、停工停产的企业，不包含注销企业
        List<Map<String, Object>> exceptionEnterpriseTce = new ArrayList<>();
        String applyDate = statDate+"-31 23:59:59";
        if (epcStr != null && !"".equals(epcStr)) {
            exceptionEnterpriseTce = energyMapper.getExceptionEnterpriseTce(applyDate, year, month, epcStr.split(","));
        } else {
            exceptionEnterpriseTce = energyMapper.getExceptionEnterpriseTce(applyDate, year, month, null);
        }
        result.put("exceptionCount",exceptionEnterpriseTce.size());
        result.put("exceptionEnterprise",exceptionEnterpriseTce);*/
        //行业前五名综合能耗，本月值、合计值(单位万tce)
        result.put("tradeTotal",energyMapper.getTradeTotalTce(year, tradeStr));
        result.put("tradeCurrent",energyMapper.getTradeCurrentTce(year, month, tradeStr));
        return R.ok(result);
    }

    private String[] monthList(String startTime, String endTime) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        StringBuilder tmpTime = new StringBuilder().append(startTime);
        Calendar calBegin = Calendar.getInstance();
        calBegin.setTime(sdf.parse(startTime));
        while (sdf.parse(endTime).after(calBegin.getTime()))  {
            calBegin.add(Calendar.MONTH, 1);
            tmpTime.append(","+sdf.format(calBegin.getTime()));
        }
        return tmpTime.toString().split(",");
    }

    @Override
    public R getEnergyExceptionInfos(String statDate, String epcStr) throws ParseException {
        //statDate取值 2021-08
        Map<String, Object> result = new HashMap();
        //查询异常企业综合能耗(单位tce)
        String applyDate = statDate+"-01 00:00:00";
        List<String> exceptionEnterprise = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        String[] epcArr = (epcStr != null && !"".equals(epcStr)) ? epcStr.split(",") : null;
        if(sdf.parse(statDate).after(sdf.parse("2021-12"))){
            //2022年1月开始，异常企业走异常记录表取出
            exceptionEnterprise = energyMapper.getExceptionEnterpriseCodeNew(statDate, epcArr);
        }else if(sdf.parse(statDate).after(sdf.parse("2021-06"))) {
            //2021年7月开始，异常企业走 在线采集月报告异常企业信息 exception_enterprise_info 表查出
            exceptionEnterprise = energyMapper.getExceptionEnterpriseCode(statDate);
        }else{
            //2021年6月至以前，异常企业指统计周期综合能耗为0的企业，其中异常企业不包含本月新增、停工停产的企业，不包含注销企业
            exceptionEnterprise = energyMapper.getExceptionEnterprise0(applyDate, statDate, epcArr);
        }
        //获取企业综合能耗
        List<Map<String, Object>> exceptionEnterpriseTce = new ArrayList<>();
        if (exceptionEnterprise != null && exceptionEnterprise.size() > 0) {
            //查询综合能耗为0和负数的企业
            exceptionEnterpriseTce = energyMapper.getTceByEnterprise(statDate.substring(0, 4) + "-01", statDate, String.join(",", exceptionEnterprise));
        }
        result.put("exceptionCount",exceptionEnterpriseTce.size());
        result.put("exceptionEnterprise",exceptionEnterpriseTce);
        return R.ok(result);
    }

    @Override
    public R getExceptionEnterpriseInfos(ExceptionEnterpriseInfos enterpriseInfos) {
        return R.ok(energyMapper.getExceptionEnterpriseInfos(enterpriseInfos));
    }

    @Override
    public R upExceptionEnterpriseInfos(ExceptionEnterpriseInfos enterpriseInfos) {
        ScUser u= SecurityUtils.getUser();
        enterpriseInfos.setUserId(u.getId());
        enterpriseInfos.setUpdateTime(new Date());
        return R.ok(energyMapper.upExceptionEnterpriseInfos(enterpriseInfos));
    }

    @Override
    public R getEnergyEnterpriseCount(String statDate) {
        statDate = statDate + "-31 23:59:59";
        return R.ok(energyMapper.getEnergyEnterpriseCount(statDate));
    }

    @Override
    public R getExceptionDict() {
        return R.ok(energyMapper.getExceptionDict());
    }

    @Override
    public IPage<QualityCalculateLogVo> getPageLogList(Page page, QualityCalculateLogVo calculateLogVo) {
        return energyMapper.getPageLogList(page, calculateLogVo);
    }

    @Override
    public IPage<QualityCalculateLogVo> getPageInfoList(Page page, QualityCalculateLogVo calculateLogVo) {
        return energyMapper.getPageInfoList(page, calculateLogVo);
    }

    @Override
    public List<ExceptionInfoNumVo> getExceptionNum(String epc, String startDate, String endDate, String dataCode, String collectItemName) {
        return energyMapper.getExceptionNum(epc, startDate, endDate, dataCode, collectItemName);
    }

    @Override
    public Map<String, Integer> getExceptionClass(String epc,String time) {
        String startTime = time.split("&")[0].substring(0, 7);
        String endTime = time.split("&")[1].substring(0, 7);
        Map<String,Integer> map = new HashMap<>(5);
        map.put("综合能耗异常",energyMapper.getComprehensiveExTotal(epc,startTime,endTime));
        map.put("单位产品能耗异常",energyMapper.getUnitComprehensiveExTotal(epc,startTime,endTime));
        map.put("电力数据异常",energyMapper.getElectricExTotal(epc,startTime,endTime));
        map.put("数据传输异常",energyMapper.getDataCollectExTotal(epc,startTime,endTime));
        map.put("数据波动异常",energyMapper.getDataValueExTotal(epc,startTime,endTime));
        return map;
    }

    @Override
    public IPage<ExceptionIndexVo> getComprehensiveExDetail(Page page, String epc, String time) {
        String startTime = time.split("&")[0].substring(0, 7);
        String endTime = time.split("&")[1].substring(0, 7);
        return energyMapper.getComprehensiveExDetail(page,epc,startTime,endTime);
    }

    @Override
    public IPage<ExceptionIndexVo> getUnitComprehensiveExDetail(Page page, String epc, String time) {
        String startTime = time.split("&")[0].substring(0, 7);
        String endTime = time.split("&")[1].substring(0, 7);
        return energyMapper.getUnitComprehensiveExDetail(page,epc,startTime,endTime);
    }

    @Override
    public IPage<ExceptionIndexVo> getElectricExDetail(Page page, String epc, String time) {
        String startTime = time.split("&")[0].substring(0, 7);
        String endTime = time.split("&")[1].substring(0, 7);
        return energyMapper.getElectricExDetail(page, epc, startTime, endTime);
    }

    @Override
    public IPage<ExceptionDataVo> getDataValueExDetail(Page page, String epc, String time,String dataCode) {
        String startTime = time.split("&")[0].substring(0, 7);
        String endTime = time.split("&")[1].substring(0, 7);
        return energyMapper.getDataValueExDetail(page,epc,startTime,endTime,dataCode);
    }

    @Override
    public IPage<ExceptionDataVo> getDataCollectExDetail(Page page, String epc, String time) {
        String startTime = time.split("&")[0].substring(0, 7);
        String endTime = time.split("&")[1].substring(0, 7);
        return energyMapper.getDataCollectExDetail(page,epc,startTime,endTime);
    }


    //根据月份获取天数
    public static int getDaysOfMonth(String date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        Calendar calendar = Calendar.getInstance();
        try {
            calendar.setTime(sdf.parse(date));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
    }

}

