package com.nantian.cloud.jljc.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nantian.cloud.jljc.entity.*;
import com.nantian.cloud.jljc.service.*;
import com.nantian.cloud.jljc.vo.Query;
import com.nantian.cloud.jljc.vo.comAnalysis.AEnergyInfoVo;
import com.nantian.cloud.jljc.vo.comAnalysis.AProductInfoVo;
import com.nantian.cloud.jljc.vo.comAnalysis.AUnitenergyInfoVo;
import com.nantian.sc.cloud.common.core.util.R;
import com.nantian.sc.cloud.common.log.annotation.SysLog;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@CrossOrigin
@RestController
@AllArgsConstructor
@RequestMapping("/statisticalAnalysis")
@Api(value = "statisticalAnalysis", tags = "统计分析")
public class StatisticalAnalysisController {
    @Autowired
    private TReportService tReportService;
    @Autowired
    private TReportEnergysTructureService tReportEnergysTructureService;
    @Autowired
    private TReportEnterpriseService tReportEnterpriseService;
    @Autowired
    private TReportFinancialService tReportFinancialService;
    @Autowired
    private TReportEnergysTructureeController tReportEnergysTructureeController;
    @Autowired
    private TReportProductService tReportProductService;
    @Autowired
    private TReportUnitenergyService tReportUnitenergyService;
    @Autowired
    private TReportRateprogressService tReportRateprogressService;
    @Autowired
    private ProductInfoService productInfoService;
    @Autowired
    private EnergyIndexService energyIndexService;


    @GetMapping("/energyConsumption")
    @SysLog("综合能耗分析（节能）")
    @ApiOperation(value = "综合能耗分析", notes = "综合能耗分析")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "分页对象", required = false, dataType = "json", paramType = "path"),
            @ApiImplicitParam(name = "Query", value = "查询条件（年份year、企业名称name、行政区编码area、行业industry）", required = false, dataType = "json", paramType = "path")
    })
    public R getPageCom(Page page, Query query) {
        Map<String, Object> map = new HashMap();

        //按企业维度获取综合能耗(带权限)
        String area = query.getArea();
        if (StringUtils.isNotEmpty(area)) {
            query.setArea(area.replaceAll("0000","".replaceAll("00","")));
        }
        IPage<Map<String, Object>> consumptionByCom = tReportService.getEnergyConsumptionByCom(page, query);

        //行业、地区的数据 用户属于区县级，显示所属州市的数据
        String areaStr = query.getArea();
        if (StringUtils.isNotEmpty(areaStr) && areaStr.length()==6) {
            query.setArea(StrUtil.subWithLength(areaStr, 0, 4)); //截取前4位
        }
        //按地区维度获取综合能耗
        List<Map<String, Object>> consumptionByArea = tReportService.getEnergyConsumptionByArea(query);
        //按行业维度获取综合能耗
        List<Map<String, Object>> consumptionByTrade = tReportService.getEnergyConsumptionByTrade(query);

        map.put("consumptionByCom", consumptionByCom);
        map.put("consumptionByArea", consumptionByArea);
        map.put("consumptionByTrade", consumptionByTrade);
        return R.ok(map);
    }

    @GetMapping("/comList")
    @SysLog("企业专题分析(企业列表)（节能）")
    @ApiOperation(value = "企业专题分析(企业列表)", notes = "企业专题分析(企业列表)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "分页对象", required = false, dataType = "json", paramType = "path"),
            @ApiImplicitParam(name = "query", value = "报表对象（year年份,name企业名称,area地区,industry行业,item产品名称）", required = false, dataType = "json", paramType = "path")
    })
    public R comList(Page page, Query query) {
        return R.ok(tReportService.comAnalysisList(page, query));
    }


    /**
     * 企业专题分析(能源情况)
     */
    @GetMapping("/comAnalysisEnergyInfo")
    @SysLog("企业专题分析(能源情况)（节能）")
    @ApiOperation(value = "企业专题分析(能源情况)", notes = "企业专题分析(能源情况)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "year", value = "年份", required = false, dataType = "json", paramType = "path"),
            @ApiImplicitParam(name = "enterpriseCode", value = "企业编码", required = false, dataType = "json", paramType = "path")
    })
    public R comAnalysisEnergyInfo(String year, String enterpriseCode) {

        if (year == null || "".equals(year)) {
            return R.failed("获取企业专题分析(能源情况)失败，年度不能为空");
        }
        if (enterpriseCode == null || "".equals(enterpriseCode)) {
            return R.failed("获取企业专题分析(能源情况)失败，企业社会信用编码不能为空");
        }

        DecimalFormat df = new DecimalFormat(".00"); //保留2位小数
        Map<String, Object> map = new HashMap<>();
        map.put("year", year);

        String energyInfoStr = tReportEnterpriseService.getEnergyInfo(enterpriseCode, year);
        List<String> energyConsume = new ArrayList<>(); //能源消费种类
        List<String> energyOut = new ArrayList<>();     //产出能源
        if (energyInfoStr != null) {
            //报表设置有数据，获取能源消费种类和产出能源
            List<EnergyInfo> energyInfoList = (List<EnergyInfo>) JSONArray.parseArray(energyInfoStr, EnergyInfo.class);
            for (EnergyInfo energyInfo : energyInfoList) {
                if ("true".equals(energyInfo.getCompBuyEnergy())) {
                    energyConsume.add(energyInfo.getEnergyName());
                }
                if ("true".equals(energyInfo.getProcessEnergy()) || "true".equals(energyInfo.getCraftEnergy())) {
                    energyOut.add(energyInfo.getEnergyName());
                }
            }
        }
        if (energyConsume.size() <= 0) {
            TReport tructureReport = tReportService.getInfoByType(enterpriseCode, year, "2");
            List<String> energyName = tReportEnergysTructureService.getEnergyName(tructureReport != null ? tructureReport.getId() : 0);
            energyConsume.addAll(energyName);
        }
        map.put("energyConsume", StringUtils.join(energyConsume, ","));
        map.put("energyOut", StringUtils.join(energyOut, ","));

        //获取能源结构（以从大到小排序）
        map.put("energyMix", getEnergyMix(year, enterpriseCode, df));
        //获取能源消费情况表
        map.put("energyConsumeInfo", getEnergyConsumeInfo(year, enterpriseCode, df));
        //获取能耗走势数据
        map.put("energytTrend", getEnergytTrend(year, enterpriseCode, df));

        //获取能耗走势的动态表头
        StringBuilder sb = new StringBuilder();
        sb.append("指标名称,");
        for (int i = 4; i >= 0; i--) {
            sb.append((Integer.parseInt(year) - i) + "年,");
        }
        sb.deleteCharAt(sb.length() - 1);
        String[] tableHead = sb.toString().split(",");
        map.put("tableHead", tableHead);

        return R.ok(map);

    }


    /**
     * 企业专题分析(能源情况2)
     */
    @GetMapping("/comAnalysisEnergyTrend")
    @SysLog("企业专题分析(能源情况2)（节能）")
    @ApiOperation(value = "企业专题分析(能源情况2)", notes = "企业专题分析(能源情况2)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "year", value = "年份", required = false, dataType = "json", paramType = "path"),
            @ApiImplicitParam(name = "enterpriseCode", value = "企业编码", required = false, dataType = "json", paramType = "path")
    })
    public R getAnalysisEnergyTrend(String year, String enterpriseCode) {

        if (year == null || "".equals(year)) {
            return R.failed("获取企业专题分析(能源情况)失败，年度不能为空");
        }
        if (enterpriseCode == null || "".equals(enterpriseCode)) {
            return R.failed("获取企业专题分析(能源情况)失败，企业社会信用编码不能为空");
        }

        DecimalFormat df = new DecimalFormat(".00"); //保留2位小数
        Map<String, Object> map = new HashMap<>();
        map.put("year", year);
        //获取单位产值综合能耗走势数据
        map.put("unitEnergyTrend", getunitEnergyTrend(year, enterpriseCode, df));
        //获取能源结构走势数据
        map.put("energyMixTrend", getEnergyMixTrend(year, enterpriseCode, df));
        return R.ok(map);
    }

    /**
     * 获取能源结构走势
     */
    private List<AEnergyInfoVo> getEnergyMixTrend(String year, String enterpriseCode, DecimalFormat df) {
        List<AEnergyInfoVo> energyMixTrend = new ArrayList<>();

        //获取本年能源结构（以从大到小排序）
        List<AEnergyInfoVo> energyMix = getEnergyMix(year, enterpriseCode, df);

        //取出能源结构中数值最大的3条，拼接能源结构走势
       /* int count = 3;
        if (energyMix.size() < 3) { //结果集数据小于3条
            count = energyMix.size();
        }
        for (int j = 0; j < count; j++) {
            AEnergyInfoVo mix = energyMix.get(j);
       */
        for (AEnergyInfoVo mix : energyMix) {
            if( mix != null && !mix.getName().contains("合计")){
                AEnergyInfoVo aEnergyInfoVo = new AEnergyInfoVo();
                aEnergyInfoVo.setName(mix.getName());
                aEnergyInfoVo.setUnit(mix.getUnit());
                aEnergyInfoVo.setNum5(mix.getNumber()); //本年值

                for (int i = 1; i <= 4; i++) { //获取前4年数据
                    String yearStr = (Integer.parseInt(year) - i) + ""; //yearStr=2020-i
                    TReport report = tReportService.getInfoByType(enterpriseCode, yearStr, "2"); //获取报表主表的数据

                    if(report != null){
                        TReportEnergysTructure q = new TReportEnergysTructure();
                        q.setDelFlag("1");
                        q.setReportId(report.getId());
                        q.setEnergyCode(StringUtils.isNotBlank(mix.getCode()) ? Integer.parseInt(mix.getCode()) : 0);
                        TReportEnergysTructure tructure = tReportEnergysTructureService.getOne(Wrappers.query(q));
                        if (tructure != null) {
                            //采用折标系数不存在，就使用参考折标系数
                            String modulus = tructure.getModulus() != null ? tructure.getModulus() : tructure.getRefModulus();
                            double number = 0;
                            if (modulus != null && !"".equals(modulus)) {
                                String[] split = modulus.split("-");
                                //当量值
                                float value = split.length > 0 ? Float.parseFloat(split[0]) : 0;
                                if (tructure.getConsumeIndustry() != null && tructure.getConsumeIndustry() != 0) {
                                    number = tructure.getConsumeIndustry() * value;
                                }
                            }
                            double num = Double.parseDouble(df.format(number));
                            //根据i，设置前几年数据
                            setEnergyNum(aEnergyInfoVo, i, num);
                        }
                    }
                }

                energyMixTrend.add(aEnergyInfoVo);
            }
        }

        /*if (energyMixTrend.size() > 0) { //结果集大于0，进行排序
            energyMixTrend.sort(new Comparator<AEnergyInfoVo>() {
                @Override
                public int compare(AEnergyInfoVo o1, AEnergyInfoVo o2) {
                    return (int)(o2.getNum5()-o1.getNum5()); //从大到小
                }
            });
        }*/

        return energyMixTrend;
    }

    /**
     * 获取单位产值综合能耗走势数据
     */
    private AEnergyInfoVo getunitEnergyTrend(String year, String enterpriseCode, DecimalFormat df) {
        AEnergyInfoVo energytTrend = new AEnergyInfoVo();
        for (int i = 0; i <= 4; i++) { //i=0 取得是本年数据
            String yearStr = (Integer.parseInt(year) - i) + "";
            TReport report = tReportService.getInfoByType(enterpriseCode, yearStr, "1");
            TReportFinancial q = new TReportFinancial();
            q.setDelFlag("1");
            q.setReportId(report != null ? report.getId() : 0);
            TReportFinancial financial = tReportFinancialService.getOne(Wrappers.query(q));
            energytTrend.setName("单位产值综合能耗");
            energytTrend.setUnit("吨标准煤/万元");
            if (financial != null) {
                double num = financial.getUnitEnergyConsumption() != null ? financial.getUnitEnergyConsumption() : 0;
                //根据i，设置前几年数据
                setEnergyNum(energytTrend, i, num);
            }
        }
        return energytTrend;
    }

    /**
     * 获取能耗走势数据
     */
    private AEnergyInfoVo getEnergytTrend(String year, String enterpriseCode, DecimalFormat df) {
        AEnergyInfoVo energytTrend = new AEnergyInfoVo();
        for (int i = 0; i <= 4; i++) { //i=0取得是本年数据
            String yearStr = (Integer.parseInt(year) - i) + "";
            TReport report = tReportService.getInfoByType(enterpriseCode, yearStr, "1");
            TReportFinancial q = new TReportFinancial();
            q.setDelFlag("1");
            q.setReportId(report != null ? report.getId() : 0);
            TReportFinancial financial = tReportFinancialService.getOne(Wrappers.query(q));
            //energytTrend.setName("综合能源消费量(万吨标准煤)");
            energytTrend.setName("综合能源消费量");
            energytTrend.setUnit("万吨标准煤");
            if (financial != null) {
                double num = financial.getEnergyConsumption() != null ? financial.getEnergyConsumption() : 0;
                //根据i，设置前几年数据
                setEnergyNum(energytTrend, i, num);
            }
        }
        return energytTrend;
    }

    /**
     * 根据i，设置前几年数据
     */
    private void setEnergyNum(AEnergyInfoVo energytTrend, int i, double num) {
        switch (i) {
            case 0:
                energytTrend.setNum5(num);
                break;
            case 1:
                energytTrend.setNum4(num);
                break;
            case 2:
                energytTrend.setNum3(num);
                break;
            case 3:
                energytTrend.setNum2(num);
                break;
            case 4:
                energytTrend.setNum1(num);
                break;
            default:
                break;
        }
    }

    /**
     * 获取能源结构（从大到小排序）
     */
    private List<AEnergyInfoVo> getEnergyMix(String year, String enterpriseCode, DecimalFormat df) {
        TReport energyReport = tReportService.getInfoByType(enterpriseCode, year, "2");
        List<TReportEnergysTructure> tructureList = tReportEnergysTructureService.getTructureByReportId(energyReport != null ? energyReport.getId() : 0);
        List<AEnergyInfoVo> energyMix = new ArrayList<>();
        for (TReportEnergysTructure tructure : tructureList) {
            AEnergyInfoVo aEnergyInfoVo = new AEnergyInfoVo();
            if (!"原煤".equals(tructure.getEnergyCodeName()) && !"合计当量值".equals(tructure.getEnergyCodeName()) && !"合计等价值".equals(tructure.getEnergyCodeName())) {
                //采用折标系数不存在，就使用参考折标系数
                String modulus = tructure.getModulus() != null ? tructure.getModulus() : tructure.getRefModulus();
                double number = 0;
                if (modulus != null && !"".equals(modulus)) {
                    String[] split = modulus.split("-");
                    //当量值
                    float value = split.length > 0 ? Float.parseFloat(split[0]) : 0;
                    /*if (tructure.getConsumeSum() != null && tructure.getConsumeSum() != 0) {
                        number = tructure.getConsumeSum() * value;
                    } */
                    if (tructure.getConsumeIndustry() != null && tructure.getConsumeIndustry() != 0) {
                        number = tructure.getConsumeIndustry() * value;
                    }
                }
                aEnergyInfoVo.setUnit("吨标准煤");
                aEnergyInfoVo.setCode(tructure.getEnergyCode()+"");
                aEnergyInfoVo.setName(tructure.getEnergyCodeName());
                aEnergyInfoVo.setNumber(Float.parseFloat(df.format(number)));
                energyMix.add(aEnergyInfoVo);
            }
        }

        if (energyMix.size() > 0) { //结果集大于0，进行排序
            energyMix.sort(new Comparator<AEnergyInfoVo>() {
                @Override
                public int compare(AEnergyInfoVo o1, AEnergyInfoVo o2) {
                    return (int) (o2.getNumber() - o1.getNumber()); //从大到小
                }
            });
        }

        return energyMix;
    }

    /**
     * 获取能源消费情况表
     */
    private List<AEnergyInfoVo> getEnergyConsumeInfo(String year, String enterpriseCode, DecimalFormat df) {
        TReportEnergysTructure tructure = getTReportEnergysTructure(year, enterpriseCode);

        Integer frontYear = Integer.parseInt(year) - 1;
        TReportEnergysTructure prevTructure = getTReportEnergysTructure(frontYear.toString(), enterpriseCode);

        TReportFinancial financial = getTReportFinancial(year, enterpriseCode);

        TReportFinancial prevFinancial = getTReportFinancial(frontYear.toString(), enterpriseCode);

        List<AEnergyInfoVo> energyConsumeInfo = new ArrayList<>();
        AEnergyInfoVo vo1 = new AEnergyInfoVo();
        AEnergyInfoVo vo2 = new AEnergyInfoVo();
        AEnergyInfoVo vo3 = new AEnergyInfoVo();
        AEnergyInfoVo vo4 = new AEnergyInfoVo();
        AEnergyInfoVo vo5 = new AEnergyInfoVo();
        vo1.setName("综合能源消费量");
        vo1.setUnit("吨标准煤");
        vo2.setName("工业生产消费");
        vo2.setUnit("吨标准煤");
        vo3.setName("非工业生产消费");
        vo3.setUnit("吨标准煤");
        vo4.setName("工业总产值");
        vo4.setUnit("万元");
        vo5.setName("单位产值综合能耗");
        vo5.setUnit("吨标准煤/万元");
        if (tructure != null) {
            vo2.setNumber(tructure.getConsumeIndustry() != null ? tructure.getConsumeIndustry() : 0);
            vo3.setNumber(tructure.getConsumeNoindustry() != null ? tructure.getConsumeNoindustry() : 0);
        }
        if (financial != null) {
            vo1.setNumber(financial.getEnergyConsumption() != null ? financial.getEnergyConsumption() * 10000 : 0);
            vo4.setNumber(financial.getIndustrialYield() != null ? financial.getIndustrialYield() : 0);
            vo5.setNumber(financial.getUnitEnergyConsumption() != null ? financial.getUnitEnergyConsumption() : 0);
        }
        if (prevTructure != null) {
            vo2.setPrevNumber(prevTructure.getConsumeIndustry() != null ? prevTructure.getConsumeIndustry() : 0);
            vo3.setPrevNumber(prevTructure.getConsumeNoindustry() != null ? prevTructure.getConsumeNoindustry() : 0);
        }
        if (prevFinancial != null) {
            vo1.setPrevNumber(prevFinancial.getEnergyConsumption() != null ? prevFinancial.getEnergyConsumption() * 10000 : 0);
            vo4.setPrevNumber(prevFinancial.getIndustrialYield() != null ? prevFinancial.getIndustrialYield() : 0);
            vo5.setPrevNumber(prevFinancial.getUnitEnergyConsumption() != null ? prevFinancial.getUnitEnergyConsumption() : 0);
        }
        energyConsumeInfo.add(vo1);
        energyConsumeInfo.add(vo2);
        energyConsumeInfo.add(vo3);
        energyConsumeInfo.add(vo4);
        energyConsumeInfo.add(vo5);
        List<AEnergyInfoVo> newEnergyConsumeInfo = new ArrayList<>();
        for (AEnergyInfoVo aEnergyInfoVo : energyConsumeInfo) {
            if (aEnergyInfoVo.getNumber() != 0 && aEnergyInfoVo.getPrevNumber() != 0) {
                double changeRatio = (aEnergyInfoVo.getNumber() / aEnergyInfoVo.getPrevNumber() - 1) * 100;
                aEnergyInfoVo.setChangeRatio(Float.parseFloat(df.format(changeRatio)));
                double average = (aEnergyInfoVo.getNumber() + aEnergyInfoVo.getPrevNumber()) / 2;
                aEnergyInfoVo.setAverage(Float.parseFloat(df.format(average)));
            }
            newEnergyConsumeInfo.add(aEnergyInfoVo);
        }
        //map.put("energyConsumeInfo", newEnergyConsumeInfo);

        return newEnergyConsumeInfo;
    }

    /**
     * 获取财务信息
     */
    private TReportFinancial getTReportFinancial(String year, String enterpriseCode) {
        TReport infoReport = tReportService.getInfoByType(enterpriseCode, year, "1");
        TReportFinancial q3 = new TReportFinancial();
        q3.setDelFlag("1");
        q3.setReportId(infoReport != null ? infoReport.getId() : 0);
        return tReportFinancialService.getOne(Wrappers.query(q3));
    }

    /**
     * 获取能源消费表合计信息
     */
    private TReportEnergysTructure getTReportEnergysTructure(String year, String enterpriseCode) {
        TReport energyReport = tReportService.getInfoByType(enterpriseCode, year, "2");
        Long reportId = energyReport != null ? energyReport.getId() : 0;
        //获取能源消费表合计信息
        List<TReportEnergysTructure> tructureListSum = tReportEnergysTructureService.getTructureByReportIdAndName(reportId, "合计当量值");
        TReportEnergysTructure tructure = tructureListSum.size() > 0 ? tructureListSum.get(0) : null;
        if (tructure == null) {
            //计算本年能源消费信息的能源合计值
            List<TReportEnergysTructure> tructureList = tReportEnergysTructureService.getTructureByReportId(reportId);
            //返回集合，下标  0：sumInfo合计当量值  1：sumEquInfo合计等价值
            List<TReportEnergysTructure> sumList = tReportEnergysTructureeController.getSum(tructureList, reportId, 0d);
            tructure = (sumList.size() > 0 ? sumList.get(0) : new TReportEnergysTructure());
        }
        return tructure;
    }


    /**
     * 企业专题分析(企业产品及产量情况)
     */
    @GetMapping("/comAnalysisProductInfo")
    @SysLog("企业专题分析(企业产品及产量情况)（节能）")
    @ApiOperation(value = "企业专题分析(企业产品及产量情况)", notes = "企业专题分析(企业产品及产量情况)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "year", value = "年份", required = false, dataType = "json", paramType = "path"),
            @ApiImplicitParam(name = "enterpriseCode", value = "企业编码", required = false, dataType = "json", paramType = "path")
    })
    public R comAnalysisProductInfo(String year, String enterpriseCode) {

        if (year == null || "".equals(year)) {
            return R.failed("获取企业专题分析(企业产品及产量情况)失败，年度不能为空");
        }
        if (enterpriseCode == null || "".equals(enterpriseCode)) {
            return R.failed("获取企业专题分析(企业产品及产量情况)失败，企业社会信用编码不能为空");
        }

        TReport report = tReportService.getInfoByType(enterpriseCode, year, "1");
        List<TReportProduct> productList = tReportProductService.getProductsByReportId(report != null ? report.getId() : 0);

        Integer prevYear = Integer.parseInt(year) - 1;
        TReport prevReport = tReportService.getInfoByType(enterpriseCode, prevYear.toString(), "1");
        List<TReportProduct> prevProductList = tReportProductService.getProductsByReportId(prevReport != null ? prevReport.getId() : 0);

        List<AProductInfoVo> productInfo = new ArrayList<AProductInfoVo>();
        DecimalFormat df = new DecimalFormat(".00"); //保留2位小数
        for (TReportProduct product : productList) {
            AProductInfoVo aProductInfoVo = new AProductInfoVo();
            aProductInfoVo.setProductName(product.getProductName());
            aProductInfoVo.setCapacity(product.getCapacityNum());
            aProductInfoVo.setYield(product.getYieldNum());
            aProductInfoVo.setProductNum(product.getProductNum());
            aProductInfoVo.setUnit(product.getCapacityUnit());

            for (TReportProduct prevProduct : prevProductList) {
                if (product.getProductName().equals(prevProduct.getProductName())) {
                    aProductInfoVo.setPrevYield(prevProduct.getYieldNum());
                    if (product.getYieldNum() != null && product.getYieldNum() != 0 && prevProduct.getYieldNum() != null && prevProduct.getYieldNum() != 0) {
                        double changeRatio = (product.getYieldNum() / prevProduct.getYieldNum() - 1) * 100;
                        aProductInfoVo.setChangeRatio(Double.parseDouble(df.format(changeRatio)));
                        double average = (product.getYieldNum() + prevProduct.getYieldNum()) / 2;
                        aProductInfoVo.setAverage(Double.parseDouble(df.format(average)));
                    }
                }
            }
            productInfo.add(aProductInfoVo);
        }

        return R.ok(productInfo);
    }

    /**
     * 企业专题分析(企业产品及产量情况2)
     */
    @GetMapping("/comAnalysisProductTrend")
    @SysLog("企业专题分析(企业产品及产量情况2)（节能）")
    @ApiOperation(value = "企业专题分析(企业产品及产量情况2)", notes = "企业专题分析(企业产品及产量情况2)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "year", value = "年份", required = true, dataType = "json", paramType = "path"),
            @ApiImplicitParam(name = "enterpriseCode", value = "企业编码", required = true, dataType = "json", paramType = "path"),
            @ApiImplicitParam(name = "productNum", value = "产品编码", required = true, dataType = "json", paramType = "path")
    })
    public R comAnalysisProductTrend(String year, String enterpriseCode, String productNum) {
        Map<String, Object> map = new HashMap<>();
        map.put("year", year);
        //获取产品走势图
        getProductTrend(year, enterpriseCode, productNum, map);
        return R.ok(map);
    }

    /**
     * 获取产品走势图
     */
    private void getProductTrend(String year, String enterpriseCode, String productNum, Map<String, Object> map) {
        DecimalFormat df = new DecimalFormat(".00"); //保留2位小数
        AEnergyInfoVo yieldTrend = new AEnergyInfoVo(); //年产量走势
        AEnergyInfoVo capacityTrend = new AEnergyInfoVo(); //年产能走势
        AEnergyInfoVo unitEnergyTrend = new AEnergyInfoVo(); //单位产品能耗走势

        for (int i = 0; i <= 4; i++) { //i=0取得是本年数据
            String yearStr = (Integer.parseInt(year) - i) + "";
            TReport report = tReportService.getInfoByType(enterpriseCode, yearStr, "1");
            TReportProduct q = new TReportProduct();
            q.setProductNum(productNum);
            q.setDelFlag("1");
            q.setReportId(report != null ? report.getId() : 0);
            TReportProduct product = tReportProductService.getOne(Wrappers.query(q));

            if (product != null) {
                if (i == 0) {
                    yieldTrend.setName("年产量");
                    capacityTrend.setName("年产能");
                    unitEnergyTrend.setName("单位产品能耗");
                    yieldTrend.setUnit(product.getYieldUnit());
                    capacityTrend.setUnit(product.getCapacityUnit());
                    unitEnergyTrend.setUnit("千克标准煤/" + product.getYieldUnit());
                }

                double unitEnergyConsumption = product.getUnitEnergyConsumptionUnit().contains("吨标准煤") && product.getUnitEnergyConsumption() != null
                        ? product.getUnitEnergyConsumption() * 1000 : product.getUnitEnergyConsumption();

                switch (i) {
                    case 0:
                        yieldTrend.setNum5(product.getYieldNum());
                        capacityTrend.setNum5(product.getCapacityNum());
                        unitEnergyTrend.setNum5(unitEnergyConsumption);
                        break;
                    case 1:
                        yieldTrend.setNum4(product.getYieldNum());
                        capacityTrend.setNum4(product.getCapacityNum());
                        unitEnergyTrend.setNum4(unitEnergyConsumption);
                        break;
                    case 2:
                        yieldTrend.setNum3(product.getYieldNum());
                        capacityTrend.setNum3(product.getCapacityNum());
                        unitEnergyTrend.setNum3(unitEnergyConsumption);
                        break;
                    case 3:
                        yieldTrend.setNum2(product.getYieldNum());
                        capacityTrend.setNum2(product.getCapacityNum());
                        unitEnergyTrend.setNum2(unitEnergyConsumption);
                        break;
                    case 4:
                        yieldTrend.setNum1(product.getYieldNum());
                        capacityTrend.setNum1(product.getCapacityNum());
                        unitEnergyTrend.setNum1(unitEnergyConsumption);
                        break;
                    default:
                        break;
                }

            }
        }

        map.put("yieldTrend", yieldTrend);
        map.put("capacityTrend", capacityTrend);
        map.put("unitEnergyTrend", unitEnergyTrend);
    }


    /**
     * 企业专题分析(能耗指标情况)
     */
    @GetMapping("/comAnalysisUnitenergyInfo")
    @SysLog("企业专题分析(能耗指标情况)（节能）")
    @ApiOperation(value = "企业专题分析(能耗指标情况)", notes = "企业专题分析(能耗指标情况)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "year", value = "年份", required = false, dataType = "json", paramType = "path"),
            @ApiImplicitParam(name = "enterpriseCode", value = "企业编码", required = false, dataType = "json", paramType = "path")
    })
    public R comAnalysisUnitenergyInfo(String year, String enterpriseCode) {

        if (year == null || "".equals(year)) {
            return R.failed("获取企业专题分析(能耗指标情况)失败，年度不能为空");
        }
        if (enterpriseCode == null || "".equals(enterpriseCode)) {
            return R.failed("获取企业专题分析(能耗指标情况)失败，企业社会信用编码不能为空");
        }

        TReport report = tReportService.getInfoByType(enterpriseCode, year, "3");
        //查询上年报表id
        String prevYear = (Integer.parseInt(year) - 1) + "";
        TReport prevReport = tReportService.getInfoByType(enterpriseCode, prevYear, "3");

        long id1 = report != null ? report.getId() : 0;
        long id2 = prevReport != null ? prevReport.getId() : 0;
        List<TReportUnitenergy> unitenergyList = tReportUnitenergyService.getByIdAndPrevId(id1, id2);

        List<AUnitenergyInfoVo> aUnitenergyInfoVoList = new ArrayList<>();
        DecimalFormat df = new DecimalFormat(".00"); //保留2位小数
        for (TReportUnitenergy unitenergy : unitenergyList) {
            AUnitenergyInfoVo aUnitenergyInfoVo = new AUnitenergyInfoVo();
            aUnitenergyInfoVo.setQuotaName(unitenergy.getQuotaName());
            aUnitenergyInfoVo.setQuotaUnit(unitenergy.getQuotaUnit());
            aUnitenergyInfoVo.setQuotaLimit(unitenergy.getQuotaLimit());
            aUnitenergyInfoVo.setGuidelineVal(unitenergy.getGuidelineVal());
            aUnitenergyInfoVo.setPrevGuidelineVal(unitenergy.getPrevGuidelineVal());
            if (unitenergy.getGuidelineVal() != null && unitenergy.getGuidelineVal() != 0 &&
                    unitenergy.getPrevGuidelineVal() != null && unitenergy.getPrevGuidelineVal() != 0) {
                double changeRatio = (unitenergy.getGuidelineVal() / unitenergy.getPrevGuidelineVal() - 1) * 100;
                aUnitenergyInfoVo.setChangeRatio(Double.parseDouble(df.format(changeRatio)));
            }
            aUnitenergyInfoVoList.add(aUnitenergyInfoVo);
        }

        return R.ok(aUnitenergyInfoVoList);
    }


    /**
     * 企业专题分析(节能量完成情况)
     */
    @GetMapping("/comAnalysisRateprogressInfo")
    @SysLog("企业专题分析(节能量完成情况)（节能）")
    @ApiOperation(value = "企业专题分析(节能量完成情况)", notes = "企业专题分析(节能量完成情况)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "year", value = "年份", required = false, dataType = "json", paramType = "path"),
            @ApiImplicitParam(name = "enterpriseCode", value = "企业编码", required = false, dataType = "json", paramType = "path")
    })
    public R comAnalysisRateprogressInfo(String year, String enterpriseCode) {

        if (year == null || "".equals(year)) {
            return R.failed("获取企业专题分析(节能量完成情况)失败，年度不能为空");
        }
        if (enterpriseCode == null || "".equals(enterpriseCode)) {
            return R.failed("获取企业专题分析(节能量完成情况)失败，企业社会信用编码不能为空");
        }

        Map<String, Object> map = new HashMap<>();
        //获取节能量完成情况的动态表头
        StringBuilder sb = new StringBuilder();
        sb.append("项目,");
        for (int i = 4; i >= 0; i--) {
            sb.append((Integer.parseInt(year) - i) + "年,");
        }
        sb.append("合计");
        String[] tableHead = sb.toString().split(",");
        map.put("tableHead", tableHead);

        //节能量完成情况5年数据
        StringBuilder stringBuilder = new StringBuilder();
        double target = 0, unitEnergyProgress = 0, energyProgress = 0, unitEnergyProgressEqual = 0, energyProgressEqual = 0;
        //float unitEnergyCompletion = 0, energyCompletion = 0, unitEnergyCompletionEqual = 0, energyCompletionEqual = 0;

        for (int i = 4; i >= 0; i--) {
            //获取能源报表信息
            Integer yearTemp = (Integer.parseInt(year) - i);
            TReport report = tReportService.getInfoByType(enterpriseCode, yearTemp.toString(), "4");
            TReportRateprogress q = new TReportRateprogress();
            q.setReportId(report != null ? report.getId() : 0);
            q.setDelFlag("1");
            //获取能耗指标表信息
            TReportRateprogress rateprogress = tReportRateprogressService.getOne(Wrappers.query(q));
            if (rateprogress != null) {
                target += rateprogress.getTarget() != null ? rateprogress.getTarget() : 0;
                unitEnergyProgress += rateprogress.getUnitEnergyProgress() != null ? rateprogress.getUnitEnergyProgress() : 0;
                energyProgress += rateprogress.getEnergyProgress() != null ? rateprogress.getEnergyProgress() : 0;
                unitEnergyProgressEqual += rateprogress.getUnitEnergyProgressEqual() != null ? rateprogress.getUnitEnergyProgressEqual() : 0;
                energyProgressEqual += rateprogress.getEnergyProgressEqual() != null ? rateprogress.getEnergyProgressEqual() : 0;
                //unitEnergyCompletion += rateprogress.getUnitEnergyCompletion() != null ? rateprogress.getUnitEnergyCompletion() : 0;
                //energyCompletion += rateprogress.getEnergyCompletion() != null ? rateprogress.getEnergyCompletion() : 0;
                //unitEnergyCompletionEqual += rateprogress.getUnitEnergyCompletionEqual() != null ? rateprogress.getUnitEnergyCompletionEqual() : 0;
                //energyCompletionEqual += rateprogress.getEnergyCompletionEqual() != null ? rateprogress.getEnergyCompletionEqual() : 0;
                if (rateprogress.getRemarks() != null) {
                    stringBuilder.append(rateprogress.getRemarks() + ",");
                }
                map.put("num" + (5 - i), rateprogress);
            } else {
                map.put("num" + (5 - i), new TReportRateprogress());
            }
        }

        //节能量完成情况合计值
        TReportRateprogress sum = new TReportRateprogress();
        sum.setTarget(target);
        sum.setUnitEnergyProgress(unitEnergyProgress);
        sum.setEnergyProgress(energyProgress);
        sum.setUnitEnergyProgressEqual(unitEnergyProgressEqual);
        sum.setEnergyProgressEqual(energyProgressEqual);
        //sum.setUnitEnergyCompletion(unitEnergyCompletion);
        //sum.setEnergyCompletion(energyCompletion);
        //sum.setUnitEnergyCompletionEqual(unitEnergyCompletionEqual);
        //sum.setEnergyCompletionEqual(energyCompletionEqual);
        map.put("sum", sum);

        //进度节能量目标完成情况说明
        if(StringUtils.endsWith(stringBuilder.toString(),",")){
            stringBuilder.deleteCharAt(stringBuilder.length() - 1);
        }
        map.put("remarks", stringBuilder.toString());

        return R.ok(map);
    }

    /**
     * 单位产品能耗排名（能效领跑者）
     */
    @GetMapping("/unitConsumptionRanking")
    @SysLog("单位产品能耗排名（能效领跑者）（节能）")
    @ApiOperation(value = "单位产品能耗排名（能效领跑者）", notes = "单位产品能耗排名（能效领跑者）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "year", value = "年份", required = false, dataType = "json", paramType = "path"),
            @ApiImplicitParam(name = "productCode", value = "产品编码", required = false, dataType = "json", paramType = "path")
    })
    public R unitConsumptionRanking(Page page, String year, String productCode) {

        if (year == null || "".equals(year)) {
            //年份为空，默认取系统上年年份
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
            Date date = new Date();
            year = (Integer.parseInt(sdf.format(date)) - 1) + "";
        }

        if (productCode == null || "".equals(productCode)) {
            //产品编码为空，默认取产品信息的第一条数据的产品编码
            IPage<ProductInfo> productInfoIPage = productInfoService.page(new Page<>(), Wrappers.query());
            productCode = productInfoIPage.getRecords().get(0).getProductNum();
        }

        Map<String, Object> map = new HashMap<>();
        IPage<Map<String, Object>> consumptionPage = tReportService.unitConsumptionRanking(page, year, productCode);
        map.put("consumptionPage", consumptionPage);

        List<Map<String, Object>> consumptionRank = tReportService.unitConsumptionTop3(year, productCode);
        map.put("consumptionRank", consumptionRank);

        return R.ok(map);
    }


    /**
     * 能效对标管理
     */
    @GetMapping("/energyBenchmarking")
    @SysLog("能效对标管理（节能）")
    @ApiOperation(value = "能效对标管理", notes = "能效对标管理")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "分页对象", required = false, dataType = "json", paramType = "path"),
            @ApiImplicitParam(name = "year", value = "年份", required = false, dataType = "json", paramType = "path"),
            @ApiImplicitParam(name = "energyId", value = "指标id", required = false, dataType = "json", paramType = "path")
    })
    public R energyBenchmarking(Page page, String year, String energyId) {
        return R.ok(tReportService.energyBenchmarking(page, year, energyId));
    }
}
