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

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nantian.cloud.jljc.entity.*;
import com.nantian.cloud.jljc.mapper.TReportMapper;
import com.nantian.cloud.jljc.service.*;
import com.nantian.cloud.jljc.vo.TReportUnitenergy;
import com.nantian.cloud.jljc.vo.*;
import com.nantian.cloud.jljc.vo.comAnalysis.AEnergyIndexVo;
import com.nantian.cloud.jljc.vo.comAnalysis.EnergyInfoVo;
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 java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;

/**
 * 能源报表信息 服务实现类
 *
 * @author stz
 * @since 2020-09-16
 */
@Service("tReportService")
public class TReportServiceImpl extends ServiceImpl<TReportMapper, TReport> implements TReportService {

    @Autowired
    private EnterpriseInfoService enterpriseInfoService;
    @Autowired
    private EnergyInfoService energyInfoService;
    @Autowired
    private EnergyIndexService energyIndexService;
    @Autowired
    private DictRegionService dictRegionService;
    @Autowired
    private TReportEnergyProjectService tReportEnergyProjectService;

    @Override
    public IPage<ReportModifyVo> getModifyRecords(Page page, String cmpName, String status) {
        return baseMapper.getModifyRecords(page, cmpName, status, new DataScope());
    }

    @Override
    public TReport getInfoByType(String enterpriseCode, String year, String type) {
        return baseMapper.getInfoByType(enterpriseCode, year, type);
    }

    @Override
    public boolean addTReport(TReport addReport) {
        return baseMapper.addTReport(addReport);
    }

    @Override
    public long getTReportIdByType(String enterpriseCode, String year, String type, ScUser u) {

        TReport tReport = baseMapper.getInfoByType(enterpriseCode, year, type);
        if (tReport == null) { //信息不存在，新增报表信息，并返回reportId
            TReport addReport = new TReport();
            addReport.setEnterpriseCode(enterpriseCode);
            addReport.setYear(Integer.parseInt(year));
            addReport.setType(type);
            addReport.setDate(new Date());
            addReport.setUserid(u.getId());
            addReport.setUpdateTime(new Date());
            //addReport.setDeptId(u.getDeptId());
            //获取企业信息
            EnterpriseInfo info = enterpriseInfoService.getInfoByCode(u.getEnterpriseCode());
            //企业端新增信息，添加deptid
            int deptId = 0;
            if (info != null && info.getRegionCode() != null) {
                deptId = Integer.parseInt(info.getRegionCode());
            } else {
                deptId = u.getDeptId();
            }
            addReport.setDeptId(deptId);
            addReport.setDelFlag("1");
            if("530000".equals(deptId)){ //企业区域直属省级
                addReport.setProvStatus("1"); //企业所填报表，省级可直接查看、审核
            }
            /*boolean b = baseMapper.addTReport(addReport);
            return b ? addReport.getId() : 0;*/
            int b = baseMapper.insert(addReport);
            return b>0 ? addReport.getId() : 0;
        } else { //信息存在，返回reportId
            return tReport.getId();
        }
    }

    /**
     * 查询参数说明
     * state 填报状态(0企业已填报，1企业未填报)
     * type 报表类型(取值1至5 对应表1至表5)
     * item 能耗级别
     * source 企业名单年份
     * nbState 审核状态(1区县未审，2区县审核通过，3区县审核退回，4州市未审，5州市审核通过，6州市审核退回，7省级未审，8省级审核通过，9省级审核退回)
     *         审核通过：企业所有报表审核通过；审核退回：企业有一张报表退回；未审核：企业报表无退回且报表未全部审核通过
     */
    @Override
    public IPage<Map<String, Object>> queryState(Page page, Query query) {
        String tmpArea = query.getArea();
        if(StringUtils.isNotEmpty(tmpArea)){
            if(!tmpArea.contains(",")){ //单个地区
                String area = tmpArea.replaceAll("0000","").replaceAll("00","");
                query.setArea(area);
            }
        }
        String[] list = StringUtils.isNotEmpty(query.getSource()) ? query.getSource().split(",") : null; //名单年度
        return baseMapper.getListPage(page, query, list, new DataScope());
    }

    @Override
    public IPage<Map<String, Object>> getNoAuditPage(Page page, Query query) {
        //return baseMapper.getNoAuditPage(page, query, new DataScope());
        String deptId = SecurityUtils.getUser().getDeptId().toString();
        if(deptId.contains("0000")){ //省级部门 只展示已经上报到省级的报告
            query.setContent(1);
        }
        if(StringUtils.isEmpty(query.getNbState())){ //未审核状态为空
            if(deptId.contains("0000")){
                query.setNbState("7"); //省级未审核
            }else if(deptId.contains("00")){
                query.setNbState("4"); //州市未审核
            }else{
                query.setNbState("1"); //区县未审核
            }
        }
        return queryState(page, query);
    }

    @Override
    public List<TReport> listByAuditorJudge(TReport tReport) {
        return baseMapper.listByAuditorJudge(tReport);
    }

    @Override
    public List<EnergyInfoVo> getEnergyData() {
        return baseMapper.getEnergyData();
    }

    @Override
    public List<Map<String, Object>> getReturnDetail(String epc, String year) {
        return baseMapper.getReturnDetail(epc,year);
    }

    @Override
    public void renewReportRegion(String enterpriseCode, String regionCode) {
        baseMapper.renewReportRegion(enterpriseCode,regionCode);
    }

    @Override
    public IPage<Map<String, Object>> queryCustom(Page page, Query query) {
        //企业类别
        String[] list = query.getType()!=null ? query.getType().split(",") : null;
        return baseMapper.queryCustom(page, query, new DataScope(),list);
    }

    @Override
    public IPage<Map<String, Object>> getEnergyConsumptionByCom(Page page, Query query) {
        return baseMapper.getEnergyConsumptionByCom(page, query,new DataScope());
    }

    @Override
    public List<Map<String, Object>> getEnergyConsumptionByArea(Query query) {
        return baseMapper.getEnergyConsumptionByArea(query);
    }

    @Override
    public List<Map<String, Object>> getEnergyConsumptionByTrade(Query query) {
        return baseMapper.getEnergyConsumptionByTrade(query);
    }

    @Override
    public IPage<Map<String, Object>> unitConsumptionRanking(Page page, String year, String productCode) {
        return baseMapper.unitConsumptionRanking(page, year, productCode);
    }

    @Override
    public List<Map<String, Object>> unitConsumptionTop3(String year, String productCode) {
        return baseMapper.unitConsumptionTop3(year, productCode);
    }

    @Override
    public IPage<Map<String, Object>> queryCustomReport(Page page, Query query) {
        return baseMapper.queryCustomReport(page, query, new DataScope());
    }

    @Override
    public List<QueryCustomReportSummaryVo> queryCustomReportSummary(Query query) {
        return baseMapper.queryCustomReportSummary(query);
    }

    @Override
    public List<QueryCustomReportSummaryVo> queryCustomReportSummaryByAllArea(Query query) {
        return baseMapper.queryCustomReportSummaryByAllArea(query);
    }

    @Override
    public List<Map<String, Object>> energyConsumptionByAreas(String year, String area) {
        String state = "";
        if (area.contains("0000")) { //省
            state = "1";
        } else if (area.contains("00")) {  //州市
            state = "2";
        } else { //区县
            state = "3";
        }
        return baseMapper.energyConsumptionByAreas(state, year, extractAreaTmp(area));
    }

    @Override
    public Map<String, Object> totalByReport(String year, String area) {
        return baseMapper.totalByReport(year, extractAreaTmp(area));
    }

    @Override
    public List<EnergyInfoConsumptionVo> energyConsumptionByEnergy(Query query) {
        query.setPArea(extractAreaTmp(query.getArea()));

        List<EnergyInfo> energyInfoList = energyInfoService.energyListAndChild();
        DecimalFormat df = new DecimalFormat(".00"); //保留2位小数
        List<EnergyInfoConsumptionVo> energyMix = new ArrayList<EnergyInfoConsumptionVo>();

        for (EnergyInfo energyInfo : energyInfoList) {
            float number = 0; //该能源的综合能源消费量

            if (energyInfo.getChilds() != null) {
                String[] childList = energyInfo.getChilds().split(",");
                for (String c : childList) {
                    query.setCode(c);
                    number += energyConsumptionByCode(query, number);
                }
            } else {
                query.setCode(energyInfo.getId().toString());
                number += energyConsumptionByCode(query, number);
            }

            //if(number!=0 && number/10000 > 1){
            if (number != 0) {
                EnergyInfoConsumptionVo energyInfoConsumptionVo = new EnergyInfoConsumptionVo();
                energyInfoConsumptionVo.setName(energyInfo.getEnergyName());
                energyInfoConsumptionVo.setNum(Float.parseFloat(df.format(number / 10000)));
                energyInfoConsumptionVo.setUnit("万tce");
                energyMix.add(energyInfoConsumptionVo);
            }

        }

        return energyMix;
    }

    @Override
    public IPage<Map<String, Object>> comAnalysisList(Page page, Query query) {
        query.setArea(extractAreaTmp(query.getArea()));
        return baseMapper.comAnalysisList(page, query);
    }

    @Override
    public IPage<Map<String, Object>> energyBenchmarkingPage(Page page, String year, String energyId, DataScope dataScope) {
        return baseMapper.energyBenchmarkingPage(page, year, energyId,dataScope);
    }

    @Override
    public Map<String, String> energyBenchmarkingGov(String year, String energyId, Integer area) {
        return baseMapper.energyBenchmarkingGov(year, energyId, area);
    }

    @Override
    public Map<String, String> energyBenchmarkingLocal(String year, String energyId, Integer area) {
        return baseMapper.energyBenchmarkingLocal(year, energyId, area);
    }

    @Override
    public Map<String, Object> energyBenchmarking(Page page, String year, String energyId) {
        //根据id获取指标的先进值、准入值、限定值
        EnergyIndex energyIndex = energyIndexService.getInfoByEnergyId(energyId);

        String areaStr = SecurityUtils.getUser().getDeptId().toString();
        Integer area = Integer.parseInt(extractAreaTmp(areaStr));

        //分页获取能效对标企业名单
        IPage<Map<String, Object>> benchmarkingPage = baseMapper.energyBenchmarkingPage(page, year, energyId, new DataScope());

        //获取能效对标饼图
        Map<String, String> benchmarkingGov = baseMapper.energyBenchmarkingGov(year, energyId, area);
        Map<String, String> benchmarkingLocal = baseMapper.energyBenchmarkingLocal(year, energyId, area);

        List<AEnergyIndexVo> newbenchmarkingGov = new ArrayList<>();
        if(benchmarkingGov!=null){
            if (!"-".equals(energyIndex.getGovGood()) && !"-".equals(energyIndex.getGovLimit())) { //有先进值、限额值
                newbenchmarkingGov.add(AEnergyIndexVo.builder().name("低于先进值").value(String.valueOf(benchmarkingGov.get("lqGovGood"))).build());
                newbenchmarkingGov.add(AEnergyIndexVo.builder().name("高于先进值、低于限额值").value(String.valueOf(benchmarkingGov.get("lqGovLimit"))).build());
                newbenchmarkingGov.add(AEnergyIndexVo.builder().name("高于限额值").value(String.valueOf(benchmarkingGov.get("gGovLimit"))).build());
            } else if (!"-".equals(energyIndex.getGovGood())) { //只有先进值
                newbenchmarkingGov.add(AEnergyIndexVo.builder().name("低于先进值").value(String.valueOf(benchmarkingGov.get("lqGovGood"))).build());
                newbenchmarkingGov.add(AEnergyIndexVo.builder().name("高于先进值").value(String.valueOf(benchmarkingGov.get("gGovGood"))).build());
            } else if (!"-".equals(energyIndex.getGovLimit())) { //只有限额值
                newbenchmarkingGov.add(AEnergyIndexVo.builder().name("低于限额值").value(String.valueOf(benchmarkingGov.get("lqGovLimit"))).build());
                newbenchmarkingGov.add(AEnergyIndexVo.builder().name("高于限额值").value(String.valueOf(benchmarkingGov.get("gGovLimit"))).build());
            }
        }

        List<AEnergyIndexVo> newbenchmarkingLocal = new ArrayList<>();
        if(benchmarkingLocal!=null) {
            if (!"-".equals(energyIndex.getLocalGood()) && !"-".equals(energyIndex.getLocalLimit())) { //有先进值、限额值
                newbenchmarkingLocal.add(AEnergyIndexVo.builder().name("低于先进值").value(String.valueOf(benchmarkingLocal.get("lqLocalGood"))).build());
                newbenchmarkingLocal.add(AEnergyIndexVo.builder().name("高于先进值、低于限额值").value(String.valueOf(benchmarkingLocal.get("lqLocalLimit"))).build());
                newbenchmarkingLocal.add(AEnergyIndexVo.builder().name("高于限额值").value(String.valueOf(benchmarkingLocal.get("gLocalLimit"))).build());
            } else if (!"-".equals(energyIndex.getLocalGood())) { //只有先进值
                newbenchmarkingLocal.add(AEnergyIndexVo.builder().name("低于先进值").value(String.valueOf(benchmarkingLocal.get("lqLocalGood"))).build());
                newbenchmarkingLocal.add(AEnergyIndexVo.builder().name("高于先进值").value(String.valueOf(benchmarkingLocal.get("gLocalGood"))).build());
            } else if (!"-".equals(energyIndex.getLocalLimit())) { //只有限额值
                newbenchmarkingLocal.add(AEnergyIndexVo.builder().name("低于限额值").value(String.valueOf(benchmarkingLocal.get("lqLocalLimit"))).build());
                newbenchmarkingLocal.add(AEnergyIndexVo.builder().name("高于限额值").value(String.valueOf(benchmarkingLocal.get("gLocalLimit"))).build());
            }
        }

        Map<String, Object> map = new HashMap<>();
        map.put("energyIndex", energyIndex);
        map.put("benchmarkingPage", benchmarkingPage);
        //map.put("benchmarkingGov", benchmarkingGov);
        //map.put("benchmarkingLocal", benchmarkingLocal);
        map.put("newbenchmarkingGov", newbenchmarkingGov);
        map.put("newbenchmarkingLocal", newbenchmarkingLocal);
        return map;
    }

    @Override
    public int noProvStatusLog() {
        return baseMapper.noProvStatusLog();
    }

    @Override
    public int upProvStatus(String date) {
        return baseMapper.upProvStatus(date);
    }

    @Override
    public List<Map<String, Object>> noticeListByReport(Query query, String deptId) {
        return baseMapper.noticeListByReport( query, deptId, new DataScope());
    }

    @Override
    public List<Map<String, Object>> exceptionInfoByReport1(Query query, String deptId) {
        return baseMapper.exceptionInfoByReport1(query, deptId);
    }

    @Override
    public List<Map<String, Object>> exceptionInfoByReport2(Query query, String deptId) {
        return baseMapper.exceptionInfoByReport2(query, deptId);
    }

    @Override
    public List<Map<String, Object>> reportSummaryAndAudit(Query query) {
        return baseMapper.reportSummaryAndAudit(query);
    }

    @Override
    public Map<String, Object> queryCustomRank(Page page, Query query) {
        //查询条件（企业名称name、地区area、企业类别type、行业industry、年份year、id查询内容1、id2显示样式(1地区,2行业,3企业)、变化率范围low1,high1、数值范围low2,high2、指标编码source）
        Map<String, Object> result = new HashMap<>();
        //获取能源代码list
        List<EnergyInfo> energyCodes = energyInfoService.energyCodeList();
        //获取地区码list
        List<DictRegion> areaCode = dictRegionService.getDictRegion();
        //获取耗能指标信息list
        List<EnergyIndex> energyIndexList = energyIndexService.getEnergyIndexList();
        //获取节能项目类型
        List<TReportEnergyProject> energyProjectTypeList = tReportEnergyProjectService.getProjectTypeList();
        //上年值
        query.setPrevYear(query.getYear()-1);
        //企业类别
        String[] split = query.getType()!=null ? query.getType().split(",") : null;
        //加数据权限
        String areaStr = SecurityUtils.getUser().getDeptId().toString();
        query.setCode(areaStr);

        if("61".equals(query.getId())){ //工业总产值综合能耗 (单位产值综合能耗 采用参考折标系数计算)
            if("1".equals(query.getId2())){ //地区
                List<Map<String, Object>> maps = baseMapper.queryCustomRank61_1(query, split);
                maps.add(baseMapper.queryCustomRank61_4( query, split));
                result.put("result", maps);
            }else if("2".equals(query.getId2())){ //行业
                List<Map<String, Object>> maps = baseMapper.queryCustomRank61_2(query, split);
                maps.add(baseMapper.queryCustomRank61_4( query, split));
                result.put("result",maps);
            }else if("3".equals(query.getId2())){ //企业
                result.put("result",baseMapper.queryCustomRank61_3(page, query, split));
            }
        } else if("31".equals(query.getId()) || "33".equals(query.getId()) || "34".equals(query.getId()) || "36".equals(query.getId()) || "37".equals(query.getId()) || "38".equals(query.getId())){
            //企业经营指标 31能源消费成本,33企业销售收入,34工业总产值,36上缴利锐,37从业人员,38能源管理师
            if("1".equals(query.getId2())){ //地区
                List<Map<String, Object>> maps = baseMapper.queryCustomRank31_1(query, split);
                maps.add(baseMapper.queryCustomRank31_4( query, split));
                result.put("result", maps);
            }else if("2".equals(query.getId2())){ //行业
                List<Map<String, Object>> maps = baseMapper.queryCustomRank31_2(query, split);
                maps.add(baseMapper.queryCustomRank31_4( query, split));
                result.put("result", maps);
            }else if("3".equals(query.getId2())){ //企业
                result.put("result",baseMapper.queryCustomRank31_3(page, query, split));
            }
        }else if("21".equals(query.getId())|| "22".equals(query.getId())){ //节能量
            ArrayList list = new ArrayList();
            if(query.getYear()%5==0){
                list.add(query.getYear().toString());
                list.add((query.getYear()-1));
                list.add((query.getYear()-2));
                list.add((query.getYear()-3));
                list.add((query.getYear()-4));
            }else if(query.getYear()%5==1){
                list.add(query.getYear());
            }else if(query.getYear()%5==2){
                list.add(query.getYear());
                list.add(query.getYear()-1);
            }else if(query.getYear()%5==3){
                list.add(query.getYear());
                list.add(query.getYear()-1);
                list.add(query.getYear()-2);
            }else if(query.getYear()%5==4){
                list.add(query.getYear());
                list.add(query.getYear()-1);
                list.add(query.getYear()-2);
                list.add(query.getYear()-3);
            }
            String[] years = new String[list.size()];
            for (int i=0;i<list.size();i++){
                years[i]=list.get(i).toString();
            }
            if("1".equals(query.getId2())){ //地区
                if("21".equals(query.getId())) {
                    List<Map<String, Object>> maps = baseMapper.queryCustomRank21_1(query, years,split);
                    result.put("result", maps);
                }else if("22".equals(query.getId())){
                    List<Map<String, Object>> maps = baseMapper.queryCustomRank22_1(query, years,split);
                    result.put("result", maps);
                }
            }else if("2".equals(query.getId2())){ //行业
                if("21".equals(query.getId())) {
                    List<Map<String, Object>> maps = baseMapper.queryCustomRank21_2(query, years,split);
                    result.put("result", maps);
                }else if("22".equals(query.getId())){
                    List<Map<String, Object>> maps = baseMapper.queryCustomRank22_2(query, years,split);
                    result.put("result", maps);
                }
            }else if("3".equals(query.getId2())){ //企业
                if("21".equals(query.getId())) {
                    List<Map<String, Object>> maps = baseMapper.queryCustomRank21_3(query, years,split);
                    result.put("result", maps);
                }else if("22".equals(query.getId())){
                    List<Map<String, Object>> maps = baseMapper.queryCustomRank22_3(query, years,split);
                    result.put("result", maps);
                }
            }
        } else if("32".equals(query.getId()) || "35".equals(query.getId())){ //企业经营指标 32企业生产成本,35产品产量
            if("1".equals(query.getId2())){ //地区
                List<Map<String, Object>> maps = baseMapper.queryCustomRank32_1(query, split);
                maps.add(baseMapper.queryCustomRank32_4( query, split));
                result.put("result", maps);
            }else if("2".equals(query.getId2())){ //行业
                List<Map<String, Object>> maps = baseMapper.queryCustomRank32_2(query, split);
                maps.add(baseMapper.queryCustomRank32_4( query, split));
                result.put("result", maps);
            }else if("3".equals(query.getId2())){ //企业
                result.put("result",baseMapper.queryCustomRank32_3(page, query, split));
            }
        }else if("42".equals(query.getId())){ //能源消费、产出、回收 42综合能源消费量
            if("1".equals(query.getId2())){ //地区
                List<Map<String, Object>> maps = baseMapper.queryCustomRank42_1(query, split);
                maps.add(baseMapper.queryCustomRank42_4( query, split));
                result.put("result", maps);
            }else if("2".equals(query.getId2())){ //行业
                List<Map<String, Object>> maps = baseMapper.queryCustomRank42_2(query, split);
                maps.add(baseMapper.queryCustomRank42_4( query, split));
                result.put("result", maps);
            }else if("3".equals(query.getId2())){ //企业
                result.put("result",baseMapper.queryCustomRank42_3(page, query, split));
            }
            //能源消费、产出、回收 41能源消费量合计 44工业生产消费量 45非工业生产消费量
        }else if("44".equals(query.getId()) || "41".equals(query.getId()) || "45".equals(query.getId())){
            if (energyCodes!=null && energyCodes.size()>0) {
                    if("1".equals(query.getId2())){ //地区
                        ArrayList maps =new ArrayList<>();
                        for (int i = 0; i < energyCodes.size(); i++) {
                            String code = energyCodes.get(i).getCode();
                            List<Map<String, Object>> list = baseMapper.queryCustomRank44_1(query, split,code);
                            Map totalMap=baseMapper.queryCustomRank44_4( query, split,code);
                            if(totalMap.containsKey("energyName")){
                                list.add(totalMap);
                                maps.add(list);
                            }
                        }
                        result.put("result", maps);
                    }else if("2".equals(query.getId2())){ //行业
                        ArrayList maps =new ArrayList<>();
                        for (int i = 0; i < energyCodes.size(); i++) {
                            String code = energyCodes.get(i).getCode();
                            List<Map<String, Object>> list = baseMapper.queryCustomRank44_2(query, split, code);
                            Map totalMap=baseMapper.queryCustomRank44_4( query, split,code);
                            if(totalMap.containsKey("energyName")){
                                list.add(totalMap);
                                maps.add(list);
                            }
                        }
                        result.put("result", maps);
                    }else if("3".equals(query.getId2())){ //企业
                        result.put("result",baseMapper.queryCustomRank44_3(page, query, split));
                    }
            }
            //能源消费、产出、回收 43能源回收利用量 46加工转换产出能源量 47加工转换投入能源量
        }else if("43".equals(query.getId()) || "46".equals(query.getId()) || "47".equals(query.getId())){
            if (energyCodes!=null && energyCodes.size()>0) {
                if("1".equals(query.getId2())){ //地区
                    ArrayList maps =new ArrayList<>();
                    for (int i = 0; i < energyCodes.size(); i++) {
                        String code = energyCodes.get(i).getCode();
                        List<Map<String, Object>> list = baseMapper.queryCustomRank43_1(query, split,code);
                        Map totalMap=baseMapper.queryCustomRank43_4( query, split,code);
                        if(totalMap.containsKey("energyName")){
                            list.add(totalMap);
                            maps.add(list);
                        }
                    }
                    result.put("result", maps);
                }else if("2".equals(query.getId2())){ //行业
                    ArrayList maps =new ArrayList<>();
                    for (int i = 0; i < energyCodes.size(); i++) {
                        String code = energyCodes.get(i).getCode();
                        List<Map<String, Object>> list = baseMapper.queryCustomRank43_2(query, split, code);
                        Map totalMap=baseMapper.queryCustomRank43_4( query, split,code);
                        if(totalMap.containsKey("energyName")){
                            list.add(totalMap);
                            maps.add(list);
                        }
                    }
                    result.put("result", maps);
                }else if("3".equals(query.getId2())){ //企业
                    result.put("result",baseMapper.queryCustomRank43_3(page, query, split));
                }
            }
            //能源消费、产出、回收 48能源加工转换效率
    }else if("48".equals(query.getId())){
            if("1".equals(query.getId2())){ //地区
                List<Map<String, Object>> maps = baseMapper.queryCustomRank48_1(query, split);
                maps.add(baseMapper.queryCustomRank48_4( query, split));
                result.put("result", maps);
            }else if("2".equals(query.getId2())){ //行业
                List<Map<String, Object>> maps = baseMapper.queryCustomRank48_2(query, split);
                maps.add(baseMapper.queryCustomRank48_4( query, split));
                result.put("result", maps);
            }else if("3".equals(query.getId2())){ //企业
                result.put("result",baseMapper.queryCustomRank48_3(page, query, split));
            }
            //单位产品综合能耗 51单位产品综合能耗 52可比单位产品综合能耗
        } else if("51".equals(query.getId())||"52".equals(query.getId())) {
            if("1".equals(query.getId2())){ //地区
                List<TReportUnitenergy> list = new ArrayList<>();
                if("51".equals(query.getId())) {
                    list = baseMapper.queryCustomRank51_1(query, split);
                }else if("52".equals(query.getId())){
                    list = baseMapper.queryCustomRank52_1(query, split);
                }
                if (list!=null && list.size()>0) {
                for (int i=0;i<list.size();i++){
                    //同期个数
                    String[] tongqiNum=list.get(i).getTongqiNum().split(",");
                    //同期数值
                    String[] tongqiArr = list.get(i).getTongqi().split(",");
                    BigDecimal tongqiNums = new BigDecimal(0);//同期总记录个数
                    BigDecimal tongqiAve;//同期平均
                    String[] benqiNum=list.get(i).getBenqiNum().split(",");
                    String[] benqiArr = list.get(i).getBenqi().split(",");
                    BigDecimal benqiNums = new BigDecimal(0);
                    BigDecimal benqiAve;
                    BigDecimal rateave;
                    for (int j=0;j<tongqiNum.length;j++){
                        BigDecimal temp = new BigDecimal(tongqiNum[j]);
                        tongqiNums=tongqiNums.add(temp);
                    }
                    BigDecimal tongqiSum = new BigDecimal(0);//
                    for (int k=0;k<tongqiArr.length;k++){
                        BigDecimal temp = new BigDecimal(tongqiArr[k]);
                        tongqiSum=tongqiSum.add(temp);
                    }
                    if (tongqiNums.compareTo(BigDecimal.ZERO)==0){
                        tongqiAve = tongqiSum;
                    }else {
                        if (tongqiArr.length==1){
                            tongqiAve = tongqiSum;
                        }else {
                            tongqiAve = tongqiSum.divide(tongqiNums,2,BigDecimal.ROUND_HALF_UP);
                        }
                    }
                    for (int j=0;j<benqiNum.length;j++){
                        BigDecimal temp = new BigDecimal(benqiNum[j]);
                        benqiNums=benqiNums.add(temp);
                    }
                    BigDecimal benqiSum = new BigDecimal(0);
                    for (int k=0;k<benqiArr.length;k++){
                        BigDecimal temp = new BigDecimal(benqiArr[k]);
                        benqiSum=benqiSum.add(temp);
                    }
                    if (benqiNums.compareTo(BigDecimal.ZERO)==0){
                        benqiAve = benqiSum;
                    }else {
                        if (tongqiArr.length==1) {
                            benqiAve = benqiSum;
                        }else{
                            benqiAve = benqiSum.divide(benqiNums,2,BigDecimal.ROUND_HALF_UP);
                    }
                    }
                    if(tongqiAve.compareTo(BigDecimal.ZERO)==0){
                        rateave=new BigDecimal(0);
                    }else {
                        BigDecimal temp = benqiAve.divide(tongqiAve,6,BigDecimal.ROUND_HALF_UP).subtract(BigDecimal.ONE);
                        BigDecimal hundred = new BigDecimal(100);
                        rateave = temp.multiply(hundred).setScale(2,BigDecimal.ROUND_HALF_UP);
                    }
                    list.get(i).setTongqiAverage(tongqiAve);
                    list.get(i).setBenqiAverage(benqiAve);
                    list.get(i).setRateAverage(rateave);
                }}
                result.put("result", list);
            }else if("2".equals(query.getId2())){ //行业
                List<TReportUnitenergy> list = new ArrayList<>();
                if("51".equals(query.getId())) {
                    list = baseMapper.queryCustomRank51_2(query, split);
                }else if("52".equals(query.getId())){
                    list = baseMapper.queryCustomRank52_2(query, split);
                }
                if (list!=null && list.size()>0) {
                    for (int i=0;i<list.size();i++){
                        String[] tongqiNum=list.get(i).getTongqiNum().split(",");
                        String[] tongqiArr = list.get(i).getTongqi().split(",");
                        BigDecimal tongqiNums = new BigDecimal(0);
                        BigDecimal tongqiAve;
                        String[] benqiNum=list.get(i).getBenqiNum().split(",");
                        String[] benqiArr = list.get(i).getBenqi().split(",");
                        BigDecimal benqiNums = new BigDecimal(0);
                        BigDecimal benqiAve;
                        BigDecimal rateave;
                        for (int j=0;j<tongqiNum.length;j++){
                            BigDecimal temp = new BigDecimal(tongqiNum[j]);
                            tongqiNums=tongqiNums.add(temp);
                        }
                        BigDecimal tongqiSum = new BigDecimal(0);
                        for (int k=0;k<tongqiArr.length;k++){
                            BigDecimal temp = new BigDecimal(tongqiArr[k]);
                            tongqiSum=tongqiSum.add(temp);
                        }
                        if (tongqiNums.compareTo(BigDecimal.ZERO)==0){
                            tongqiAve = tongqiSum;
                        }else {
                            if (tongqiArr.length==1){
                                tongqiAve = tongqiSum;
                            }else {
                                tongqiAve = tongqiSum.divide(tongqiNums,2,BigDecimal.ROUND_HALF_UP);
                            }
                        }
                        for (int j=0;j<benqiNum.length;j++){
                            BigDecimal temp = new BigDecimal(benqiNum[j]);
                            benqiNums=benqiNums.add(temp);
                        }
                        BigDecimal benqiSum = new BigDecimal(0);
                        for (int k=0;k<benqiArr.length;k++){
                            BigDecimal temp = new BigDecimal(benqiArr[k]);
                            benqiSum=benqiSum.add(temp);
                        }
                        if (benqiNums.compareTo(BigDecimal.ZERO)==0){
                            benqiAve = benqiSum;
                        }else {
                            if (tongqiArr.length==1) {
                                benqiAve = benqiSum;
                            }else{
                                benqiAve = benqiSum.divide(benqiNums,2,BigDecimal.ROUND_HALF_UP);
                            }
                        }
                        if(tongqiAve.compareTo(BigDecimal.ZERO)==0){
                            rateave=new BigDecimal(0);
                        }else {
                            BigDecimal temp = benqiAve.divide(tongqiAve,6,BigDecimal.ROUND_HALF_UP).subtract(BigDecimal.ONE);
                            BigDecimal hundred = new BigDecimal(100);
                            rateave = temp.multiply(hundred).setScale(2,BigDecimal.ROUND_HALF_UP);
                        }
                        list.get(i).setTongqiAverage(tongqiAve);
                        list.get(i).setBenqiAverage(benqiAve);
                        list.get(i).setRateAverage(rateave);
                    }}
                result.put("result", list);
            }else if("3".equals(query.getId2())){ //企业
                if("51".equals(query.getId())) {
                    List<Map<String, Object>> maps = baseMapper.queryCustomRank51_3(query,split);
                    result.put("result", maps);
                }else if("52".equals(query.getId())){
                    List<Map<String, Object>> maps = baseMapper.queryCustomRank52_3(query,split);
                    result.put("result", maps);
                }
            }
            //企业节能技改项目 71完成个数 72投资金额 73预期节能量
        }else if("71".equals(query.getId()) || "72".equals(query.getId()) || "73".equals(query.getId())){
        if (energyCodes!=null && energyCodes.size()>0) {
            if("1".equals(query.getId2())){ //地区
                ArrayList maps =new ArrayList<>();
                for (int i = 0; i < energyProjectTypeList.size(); i++) {
                    String projectType = energyProjectTypeList.get(i).getProjectType();
                    List<Map<String, Object>> list = baseMapper.queryCustomRank71_1(query, split,projectType);
                    Map totalMap=baseMapper.queryCustomRank71_4( query, split,projectType);
                    if (totalMap.containsKey("type")) {
                        list.add(totalMap);
                        maps.add(list);
                    }
                }
                result.put("result", maps);
            }else if("2".equals(query.getId2())){ //行业
                ArrayList maps =new ArrayList<>();
                for (int i = 0; i < energyProjectTypeList.size(); i++) {
                    String projectType = energyProjectTypeList.get(i).getProjectType();
                    List<Map<String, Object>> list = baseMapper.queryCustomRank71_2(query, split, projectType);
                    Map totalMap=baseMapper.queryCustomRank71_4( query, split,projectType);
                    if (totalMap.containsKey("type")) {
                        list.add(totalMap);
                        maps.add(list);
                    }
                }
                result.put("result", maps);
            }else if("3".equals(query.getId2())){ //企业
                result.put("result",baseMapper.queryCustomRank71_3(page, query, split));
            }
        }
    } else{
            return null;
        }

        return result;
    }

    private float energyConsumptionByCode(Query query, float number) {
        List<TReportEnergysTructure> tructureList = baseMapper.energyConsumptionByEnergy(query);
        for (TReportEnergysTructure tructure : tructureList) {
            //折标系数异常的，采用参考折标计算
            String modulus = tructure.getModulus() != null ? tructure.getModulus() : tructure.getRefModulus();
            String modulusRef = tructure.getRefModulus();
            String[] split;
            String[] splitRef;
            float value = 0, valueRef = 0;
            if (modulus != null && !"".equals(modulus)) {
                split = modulus.split("-");
                value = split.length > 0 ? Float.parseFloat(split[0]) : 0;
            }
            if (modulusRef != null && !"".equals(modulusRef)) {
                splitRef = modulusRef.split("-");
                valueRef = splitRef.length > 0 ? Float.parseFloat(splitRef[0]) : 0;
            }
            //折标系数异常的，采用参考折标计算 当量值
            float temp = value!=0 && value < 20 ? value : valueRef;
            if (tructure.getConsumeIndustry() != null && tructure.getConsumeIndustry() != 0) {
                number += tructure.getConsumeIndustry() * temp;
            }
        }
        return number;
    }

    //获取截取后的地区编码
    public String extractAreaTmp(String area){
        if(StringUtils.isNotEmpty(area)){
            return area.replaceAll("0000","".replaceAll("00",""));
        }
        return area;
    }
}
