package com.nantian.cloud.jljc.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
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.sc.cloud.common.core.util.R;
import com.nantian.sc.cloud.common.log.annotation.SysLog;
import com.nantian.sc.cloud.common.security.service.ScUser;
import com.nantian.sc.cloud.common.security.util.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

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


/**
 * 报表1-1财务信息表
 *
 * @author stz
 * @date 2020-09-17
 */
@Slf4j
@CrossOrigin
@RestController
@AllArgsConstructor
@RequestMapping("/tReportFinancial")
@Api(value = "tReportFinancial", tags = "报表1-1财务信息表")
public class TReportFinancialController {

    final private TReportFinancialService tReportFinancialService;
    final private TReportService tReportService;
    final private TReportParaService tReportParaService;
    private final EcAbnormalVolatilityService ecAbnormalVolatilityService;
    private final EcAbnormalVolatilityInfoService ecAbnormalVolatilityInfoService;
    private final EnterpriseInfoService enterpriseInfoService;
    final private TReportEnergysTructureeController tReportEnergysTructureeController;
    final private TReportEnergysTructureService tReportEnergysTructureService;
    final private TReportEnergyOutService tReportEnergyOutService;
    final private TReportEnergyOutController tReportEnergyOutController;


    /**
     * 分页查询
     */
    @GetMapping("/page")
    @SysLog("查询报表1-1财务信息表")
    @ApiOperation(value = "查询报表1-1财务信息表", notes = "条件查询报表1-1财务信息表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "tReportFinancial", value = "报表1-1财务信息表", required = false, dataType = "json", paramType = "path"),
            @ApiImplicitParam(name = "page", value = "分页对象", required = false, dataType = "json", paramType = "path")
    })
    public R getcheckGaugesPage(Page page, TReportFinancial tReportFinancial) {
        tReportFinancial.setDelFlag("1"); //查询未删除数据
        //return R.ok(tReportFinancialService.getPageScope(page,tReportFinancial));
        return R.ok(tReportFinancialService.page(page, Wrappers.query(tReportFinancial)));
    }

    /**
     * 通过id查询报表1-1财务信息表
     */
    @GetMapping("/getById/{tReportFinancialId}")
    @SysLog("通过id查询报表1-1财务信息表")
    @ApiOperation(value = "通过id查询报表1-1财务信息表", notes = "通过id查询报表1-1财务信息表")
    @ApiImplicitParam(name = "tReportFinancialId", value = "报表1-1财务信息表id", required = true, paramType = "path", dataType = "int")
    public R getById(@PathVariable("tReportFinancialId") Integer tReportFinancialId) {
        return R.ok(tReportFinancialService.getById(tReportFinancialId));
    }

    /**
     * 通过年份查询报表1-1财务信息表
     */
    @GetMapping("/getByYear")
    @SysLog("通过年份查询报表1-1财务信息表")
    @ApiOperation(value = "通过年份查询报表1-1财务信息表", notes = "通过年份查询报表1-1财务信息表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "year", value = "年份", required = true, dataType = "json", paramType = "path"),
            @ApiImplicitParam(name = "enterpriseCode", value = "企业社会信用编码", required = true, dataType = "json", paramType = "path")
    })
    public R getByYear(String year, String enterpriseCode) {
        if (year == null || "".equals(year)) {
            return R.failed("查询报表1-1财务信息表失败，年度不能为空");
        }
        if (enterpriseCode == null || "".equals(enterpriseCode)) {
            return R.failed("查询报表1-1财务信息表失败，企业社会信用编码不能为空");
        }
        ScUser u = SecurityUtils.getUser();

        //获取报表信息id
        //long reportId = tReportService.getTReportIdByType(enterpriseCode, year, "1", u);
        TReport report = tReportService.getInfoByType(enterpriseCode, year, "1");
        TReportFinancial financial = tReportFinancialService.getFinancialsByReportId(report != null ? report.getId() : 0);

        if(financial==null){
            financial = new TReportFinancial();
        }
        if(financial.getEnergyConsumption()==null || financial.getEnergyConsumption().equals(0d)){ //更新综合能源消费量
            financial = getEnergyConsumptionInfo(year,enterpriseCode,financial);
        }
        //获取财务信息-上年记录
        /* String frontYear = (Integer.valueOf(year) - 1) + "";
        TReport frontReport = tReportService.getInfoByType(enterpriseCode, frontYear, "1");
        TReportFinancial frontFinancial = tReportFinancialService.getFinancialsByReportId(frontReport != null ? frontReport.getId() : 0);
        if (frontFinancial != null) {
            //设置财务信息上年值
            financial.setIndustrialYield2(frontFinancial.getIndustrialYield());
            financial.setSalesRevenue2(frontFinancial.getSalesRevenue());
            financial.setTaxesPayment2(frontFinancial.getTaxesPayment());
            financial.setEmployeesNum2(frontFinancial.getEmployeesNum());
            financial.setIcsemNum2(frontFinancial.getIcsemNum());
            financial.setEnergyConsumption2(frontFinancial.getEnergyConsumption());
            financial.setProductionCost2(frontFinancial.getProductionCost());
            financial.setEnergyConsumptionCost2(frontFinancial.getEnergyConsumptionCost());
            financial.setEnergyConsumptionCostRatio2(frontFinancial.getEnergyConsumptionCostRatio());
            financial.setUnitEnergyConsumption2(frontFinancial.getUnitEnergyConsumption());
        }*/
        return R.ok(financial);
    }


    /**
     * 更新报表1-1财务信息表
     */
    @Transactional
    @PostMapping("/upFinancial")
    @SysLog("更新报表1-1财务信息表")
    @ApiOperation(value = "更新报表1-1财务信息表（参数说明是键值对说明，参数s除外）", notes = "更新报表1-1财务信息表（参数说明是键值对说明），参数s除外")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "report", value = "能源报表信息", required = true, dataType = "String"),
            @ApiImplicitParam(name = "data", value = "报表1-1财务信息表信息", required = true, dataType = "String")
    })
    public R upFinancial(@RequestBody String s) {

        log.error("更新报表1-1财务信息表：" + s);

        JSONObject json = JSONObject.parseObject(s);
        //获取能源报表信息
        TReport report = JSONObject.parseObject(json.getString("report"), TReport.class);
        if (report.getYear() == null || "".equals(report.getYear())) {
            return R.failed("更新报表1-1财务信息表失败，年度不能为空");
        }

        ScUser u = SecurityUtils.getUser();
        String enterpriseCode = StringUtils.isNotEmpty(report.getEnterpriseCode()) ? report.getEnterpriseCode() : u.getEnterpriseCode();

        //获取主要产品列表
        TReportFinancial financial = JSONObject.parseObject(json.getString("data"), TReportFinancial.class);


        //进行异常波动分析
        R map = getEcAbnormalVolatility(report, u, financial);
        if (map != null) return map;


        //更新报表1-1财务信息
        //获取报表信息id （有数据就返回id，无数据就新增记录后返回id）
        long reportId = tReportService.getTReportIdByType(enterpriseCode, report.getYear() + "", "1", u);
        //更新报表信息
        report.setId(reportId);
        report.setUserid(u.getId());
        report.setUpdateTime(new Date());
        report.setReportStatus("2");
        //boolean b = tReportService.updateById(report);

        //根据报表信息id取值，有值为修改，否则新增
        TReportFinancial oldFinancial = tReportFinancialService.getFinancialsByReportId(reportId);
        if (oldFinancial != null) {
            financial.setId(oldFinancial.getId()); //修改
        }

        //获取上年的财务信息
        TReport r = tReportService.getInfoByType(enterpriseCode, (report.getYear() - 1) + "", "1");
        TReportFinancial frontFinancial = new TReportFinancial();
        if (r != null) {
            //获取上一年能源消费信息
            TReportFinancial front = new TReportFinancial();
            front.setReportId(r.getId());
            front.setDelFlag("1");
            frontFinancial = tReportFinancialService.getOne(Wrappers.query(front));
        }

        //计算财务信息的 能源消费占生产成本比例、 单位产值综合能耗（可比价） 以及上年值的变化率
        double energyConsumptionCostRatio = 0, energyConsumptionCostRatio2 = 0, unitEnergyConsumption = 0, unitEnergyConsumption2 = 0,
                energyConsumptionCostRatioRate = 0, unitEnergyConsumptionRate = 0;
        //能源消费占生产成本比例 = 能源消费成本 / 生产总成本 * 100
        if (financial.getEnergyConsumptionCost() != null && financial.getProductionCost() != null
                && financial.getEnergyConsumptionCost() != 0 && financial.getProductionCost() != 0) {
            energyConsumptionCostRatio = (financial.getEnergyConsumptionCost() / financial.getProductionCost()) * 100;
        }
        //单位产值综合能耗(吨标准煤/万元) = 综合能源消费量(万吨标准煤) * 10000 / 工业总产值(万元)
        if (financial.getEnergyConsumption() != 0 && financial.getIndustrialYield() != 0) { //综合能源消费量的值来源于报表2
            unitEnergyConsumption = (financial.getEnergyConsumption() * 10000) / financial.getIndustrialYield();
        }
        if (frontFinancial != null) {
            if (frontFinancial.getEnergyConsumptionCost() != null && frontFinancial.getProductionCost() != null
                    && frontFinancial.getEnergyConsumptionCost() != 0 && frontFinancial.getProductionCost() != 0) {
                energyConsumptionCostRatio2 = frontFinancial.getEnergyConsumptionCost() / frontFinancial.getProductionCost() * 100;
            }
            if (energyConsumptionCostRatio != 0 && energyConsumptionCostRatio2 != 0) {
                energyConsumptionCostRatioRate = (energyConsumptionCostRatio / energyConsumptionCostRatio2 - 1) * 100;
            }
            if (frontFinancial.getEnergyConsumption() != null && frontFinancial.getIndustrialYield() != null
                    && frontFinancial.getEnergyConsumption() != 0 && frontFinancial.getIndustrialYield() != 0) { //综合能源消费量的值来源于报表2
                unitEnergyConsumption2 = (frontFinancial.getEnergyConsumption() * 10000) / frontFinancial.getIndustrialYield();
            }
            if (unitEnergyConsumption != 0 && unitEnergyConsumption2 != 0) {
                unitEnergyConsumptionRate = (unitEnergyConsumption / unitEnergyConsumption2 - 1) * 100;
            }
        }

        DecimalFormat df = new DecimalFormat(".00"); //保留两位小数
        financial.setEnergyConsumptionCostRatio(Double.parseDouble(df.format(energyConsumptionCostRatio)));
        financial.setEnergyConsumptionCostRatioRate(Double.parseDouble(df.format(energyConsumptionCostRatioRate)));
        financial.setUnitEnergyConsumption(Double.parseDouble(df.format(unitEnergyConsumption)));
        financial.setUnitEnergyConsumptionRate(Double.parseDouble(df.format(unitEnergyConsumptionRate)));

        //financial.setDeptId(u.getId());
        EnterpriseInfo info = enterpriseInfoService.getInfoByCode(u.getEnterpriseCode());
        financial.setDeptId(info != null && info.getRegionCode()!=null ? Integer.parseInt(info.getRegionCode()) : u.getDeptId());
        financial.setDelFlag("1");
        financial.setReportId(reportId);
        financial.setUserid(u.getId());
        financial.setUpdateTime(new Date());

        //return R.ok(tReportFinancialService.saveOrUpdate(financial));
        boolean update = tReportFinancialService.saveOrUpdate(financial);
        if (update) {
            //财务信息更新成功，才更新报表信息
            return R.ok(tReportService.updateById(report));
        } else {
            return R.failed();
        }

    }


    /**
     * 进行异常波动分析
     */
    private R getEcAbnormalVolatility(TReport report, ScUser u, TReportFinancial financial) {
        //获取上年的报表信息
        String frontYear = (report.getYear() - 1) + "";
        String enterpriseCode = StringUtils.isNotEmpty(report.getEnterpriseCode()) ? report.getEnterpriseCode() : u.getEnterpriseCode();
        TReport frontReport = tReportService.getInfoByType(enterpriseCode, frontYear, "1");
        if (frontReport != null) {
            //获取上一年能源消费信息
            TReportFinancial front = new TReportFinancial();
            front.setReportId(frontReport.getId());
            front.setDelFlag("1");
            TReportFinancial frontFinancial = tReportFinancialService.getOne(Wrappers.query(front));
            if (frontFinancial != null) { //上年数据存在，进行异常波动分析
                boolean flage = false; //波动标志默认为，false，不波动
                //取出异常波动 预警区间
                TReportPara tReportPara = new TReportPara();
                tReportPara.setType("1");
                /*List<TReportPara> paras = tReportParaService.list(Wrappers.query(tReportPara));
                for (TReportPara para : paras) {*/
                TReportPara para = tReportParaService.list(Wrappers.query(tReportPara)).get(1);
                if (para != null && (para.getUplimt() != null || para.getDownlimt() != null)) {
                    //取出本年的异常波动表
                    EcAbnormalVolatility ecAbnormalVolatility = new EcAbnormalVolatility();
                    ecAbnormalVolatility.setYear(report.getYear() + "");
                    ecAbnormalVolatility.setDelFlag("1");
                    ecAbnormalVolatility.setEpc(u.getEnterpriseCode());
                    EcAbnormalVolatility volatility = ecAbnormalVolatilityService.getOne(Wrappers.query(ecAbnormalVolatility));
                    /*//取出本年的异常波动详情表
                    EcAbnormalVolatilityInfo ecAbnormalVolatilityInfo = new EcAbnormalVolatilityInfo();
                    ecAbnormalVolatilityInfo.setAbnormalVolatilityId(volatility != null ? volatility.getId() : 0);
                    ecAbnormalVolatilityInfo.setDelFlag("1");
                    ecAbnormalVolatilityInfo.setType("财务信息"); //仅表1用到这个字段
                    ecAbnormalVolatilityInfo.setDataTable("表1");*/
                    //进行异常波动分析
                    DecimalFormat df = new DecimalFormat(".00"); //保留两位小数
                    Map<String, Object> map = new HashMap();
                    map.put("dataTable", "表1");
                    map.put("type", "财务信息");

                    VolatilityTmpController.VolatilityTmp volatilityTmp = new VolatilityTmpController.VolatilityTmp(
                            ecAbnormalVolatilityInfoService,
                            u, flage, para, volatility, df, map,
                            "财务信息",
                            "表1",
                            financial.getIndustrialYield(),
                            frontFinancial.getIndustrialYield(),
                            //financial.getIndustrialYieldRate() == null ? 0 : financial.getIndustrialYieldRate(),
                            "【财务信息】工业总产值（可比价），超出波动范围。若确定数值，请填写变化情况说明！",
                            "工业总产值（可比价）",
                            "万元").invoke();
                    if (volatilityTmp.is()) { //超出波动范围，且未填写波动说明，返回错误信息
                        return R.failed(map);
                    }
                    flage = volatilityTmp.isFlage(); //更新超期标志

                    VolatilityTmpController.VolatilityTmp volatilityTmp2 = new VolatilityTmpController.VolatilityTmp(
                            ecAbnormalVolatilityInfoService,
                            u, flage, para, volatility, df, map,
                            "财务信息",
                            "表1",
                            financial.getSalesRevenue(),
                            frontFinancial.getSalesRevenue(),
                            //financial.getSalesRevenueRate() == null ? 0 : financial.getSalesRevenueRate(),
                            "【财务信息】销售收入，超出波动范围。若确定数值，请填写变化情况说明！",
                            "销售收入",
                            "万元").invoke();
                    if (volatilityTmp2.is()) { //超出波动范围，且未填写波动说明，返回错误信息
                        return R.failed(map);
                    }
                    flage = volatilityTmp2.isFlage(); //更新超期标志

                    VolatilityTmpController.VolatilityTmp volatilityTmp3 = new VolatilityTmpController.VolatilityTmp(
                            ecAbnormalVolatilityInfoService,
                            u, flage, para, volatility, df, map,
                            "财务信息",
                            "表1",
                            financial.getTaxesPayment(),
                            frontFinancial.getTaxesPayment(),
                            //financial.getTaxesPaymentRate() == null ? 0 : financial.getTaxesPaymentRate(),
                            "【财务信息】上缴利税，超出波动范围。若确定数值，请填写变化情况说明！",
                            "上缴利税",
                            "万元").invoke();
                    if (volatilityTmp3.is()) { //超出波动范围，且未填写波动说明，返回错误信息
                        return R.failed(map);
                    }
                    flage = volatilityTmp3.isFlage(); //更新超期标志

                    VolatilityTmpController.VolatilityTmp volatilityTmp4 = new VolatilityTmpController.VolatilityTmp(
                            ecAbnormalVolatilityInfoService,
                            u, flage, para, volatility, df, map,
                            "财务信息",
                            "表1",
                            (double)(financial.getEmployeesNum() == null ? 0 : financial.getEmployeesNum()),
                            (double)(frontFinancial.getEmployeesNum() == null ? 0 : frontFinancial.getEmployeesNum()),
                            //financial.getEmployeesNumRate() == null ? 0 : financial.getEmployeesNumRate(),
                            "【财务信息】从业人员，超出波动范围。若确定数值，请填写变化情况说明！",
                            "从业人员",
                            "人").invoke();
                    if (volatilityTmp4.is()) { //超出波动范围，且未填写波动说明，返回错误信息
                        return R.failed(map);
                    }
                    flage = volatilityTmp4.isFlage(); //更新超期标志

                    VolatilityTmpController.VolatilityTmp volatilityTmp5 = new VolatilityTmpController.VolatilityTmp(
                            ecAbnormalVolatilityInfoService,
                            u, flage, para, volatility, df, map,
                            "财务信息",
                            "表1",
                            (double)(financial.getIcsemNum() == null ? 0 : financial.getIcsemNum()),
                            (double)(frontFinancial.getIcsemNum() == null ? 0 : frontFinancial.getIcsemNum()),
                            //financial.getIcsemNumRate() == null ? 0 : financial.getIcsemNumRate(),
                            "【财务信息】能源管理师，超出波动范围。若确定数值，请填写变化情况说明！",
                            "能源管理师",
                            "人").invoke();
                    if (volatilityTmp5.is()) { //超出波动范围，且未填写波动说明，返回错误信息
                        return R.failed(map);
                    }
                    flage = volatilityTmp5.isFlage(); //更新超期标志

                    // 综合能源消费量（当量值）   数据从能报2的工业生产消费合计中获取
                       /* VolatilityTmpController.VolatilityTmp volatilityTmp6 = new VolatilityTmpController.VolatilityTmp(
                                ecAbnormalVolatilityInfoService,
                                u, flage, para, volatility, df, map,
                                "财务信息",
                                "表1",
                                financial.getEnergyConsumption(),
                                frontFinancial.getEnergyConsumption(),
                                financial.getEnergyConsumptionRate() == null ? 0 : financial.getEnergyConsumptionRate(),
                                "【财务信息】综合能源消费量（当量值），超出波动范围。若确定数值，请填写变化情况说明！",
                                "综合能源消费量（当量值）",
                                "万吨标准煤").invoke();
                        if (volatilityTmp6.is()) { //超出波动范围，且未填写波动说明，返回错误信息
                            return R.failed(map);
                        }
                        flage = volatilityTmp6.isFlage(); //更新超期标志*/

                    VolatilityTmpController.VolatilityTmp volatilityTmp7 = new VolatilityTmpController.VolatilityTmp(
                            ecAbnormalVolatilityInfoService,
                            u, flage, para, volatility, df, map,
                            "财务信息",
                            "表1",
                            financial.getProductionCost(),
                            frontFinancial.getProductionCost(),
                            //financial.getProductionCostRate() == null ? 0 : financial.getProductionCostRate(),
                            "【财务信息】生产总成本，超出波动范围。若确定数值，请填写变化情况说明！",
                            "生产总成本",
                            "万元").invoke();
                    if (volatilityTmp7.is()) { //超出波动范围，且未填写波动说明，返回错误信息
                        return R.failed(map);
                    }
                    flage = volatilityTmp7.isFlage(); //更新超期标志

                    VolatilityTmpController.VolatilityTmp volatilityTmp8 = new VolatilityTmpController.VolatilityTmp(
                            ecAbnormalVolatilityInfoService,
                            u, flage, para, volatility, df, map,
                            "财务信息",
                            "表1",
                            financial.getEnergyConsumptionCost(),
                            frontFinancial.getEnergyConsumptionCost(),
                            //financial.getEnergyConsumptionCostRate() == null ? 0 : financial.getEnergyConsumptionCostRate(),
                            "【财务信息】能源消费成本，超出波动范围。若确定数值，请填写变化情况说明！",
                            "能源消费成本",
                            "万元").invoke();
                    if (volatilityTmp8.is()) { //超出波动范围，且未填写波动说明，返回错误信息
                        return R.failed(map);
                    }
                    flage = volatilityTmp8.isFlage(); //更新超期标志

                    //表1财务信息数据没有数据超出异常范围，判断是否记录了其他异常波动信息，若无主表信息需要删除
                    if (!flage && volatility != null) {
                        upVolatility(u, volatility);
                    }
                }
            }

        }
        return null;
    }

    /**
     * 没有超出波动范围，却有波动记录，需要删除波动记录
     */
    private void deleteVolatilityInfo(ScUser u, EcAbnormalVolatilityInfo volatilityInfo) {
        volatilityInfo.setDelFlag("4");
        volatilityInfo.setUserid(u.getId());
        volatilityInfo.setUpdateTime(new Date());
        boolean delete = ecAbnormalVolatilityInfoService.updateById(volatilityInfo);
    }

    /**
     * 判断是否记录了其他异常波动信息，若无主表信息需要删除
     */
    private void upVolatility(ScUser u, EcAbnormalVolatility volatility) {
        /*List<EcAbnormalVolatilityInfo> volatilityInfoList = ecAbnormalVolatilityInfoService.list(Wrappers.query(ecAbnormalVolatilityInfo));
        if (volatilityInfoList.size() > 0) {
            //删除异常波动详情表  内容为表1的信息
            List<EcAbnormalVolatilityInfo> newList = new ArrayList<>();
            for (EcAbnormalVolatilityInfo volatilityInfo : volatilityInfoList) {
                volatilityInfo.setDelFlag("4");
                volatilityInfo.setUpdateTime(new Date());
                volatilityInfo.setUserid(u.getId());
                newList.add(volatilityInfo);
            }
            ecAbnormalVolatilityInfoService.updateBatchById(newList);
        }*/

        //其他报表的异常波动详情表信息
        EcAbnormalVolatilityInfo volatilityInfoOther = new EcAbnormalVolatilityInfo();
        volatilityInfoOther.setAbnormalVolatilityId(volatility != null ? volatility.getId() : 0);
        volatilityInfoOther.setDelFlag("1");
        List<EcAbnormalVolatilityInfo> volatilityInfoOtherList = ecAbnormalVolatilityInfoService.list(Wrappers.query(volatilityInfoOther));
        if (!(volatilityInfoOtherList.size() > 0)) {
            //其他报表的异常波动详情信息不存在，删除主表
            volatility.setDelFlag("4");
            volatility.setUpdateTime(new Date());
            volatility.setUserid(u.getId());
            ecAbnormalVolatilityService.updateById(volatility);
        }
    }


    /**
     * 保存报表1-1财务信息表
     */
    @PostMapping("/save")
    @SysLog("保存报表1-1财务信息表")
    @ApiOperation(value = "保存报表1-1财务信息表", notes = "新增报表1-1财务信息表")
    @ApiImplicitParam(name = "TReportFinancial", value = "报表1-1财务信息表", required = true, dataType = "json", paramType = "path")
    public R save(@RequestBody TReportFinancial tReportFinancial) {
        ScUser u = SecurityUtils.getUser();
        tReportFinancial.setUserid(u.getId());
        //tReportFinancial.setDeptId(u.getDeptId());
        EnterpriseInfo info = enterpriseInfoService.getInfoByCode(u.getEnterpriseCode());
        tReportFinancial.setDeptId(info != null && info.getRegionCode()!=null ? Integer.parseInt(info.getRegionCode()) : u.getDeptId());
        tReportFinancial.setDelFlag("1");
        tReportFinancial.setUpdateTime(new Date());
        return R.ok(tReportFinancialService.save(tReportFinancial));
    }

    /**
     * 修改报表1-1财务信息表信息
     */
    @PutMapping
    @SysLog("修改报表1-1财务信息表信息")
    @ApiOperation(value = "修改报表1-1财务信息表信息", notes = "修改报表1-1财务信息表信息")
    @ApiImplicitParam(name = "TReportFinancial", value = "报表1-1财务信息表", required = true, dataType = "json", paramType = "path")
    public R updateById(@RequestBody TReportFinancial tReportFinancial) {
        ScUser u = SecurityUtils.getUser();
        tReportFinancial.setUserid(u.getId());
        tReportFinancial.setUpdateTime(new Date());
        return R.ok(tReportFinancialService.updateById(tReportFinancial));
    }

    /**
     * 删除报表1-1财务信息表
     */
    @DeleteMapping("/{tReportFinancialId}")
    @SysLog("删除报表1-1财务信息表")
    @ApiOperation(value = "删除报表1-1财务信息表", notes = "删除报表1-1财务信息表信息")
    @ApiImplicitParam(name = "tReportFinancialId", value = "报表1-1财务信息表信息ID", required = true, dataType = "int", paramType = "path")
    public R removeById(@PathVariable("tReportFinancialId") Long tReportFinancialId) {
        TReportFinancial tReportFinancial = tReportFinancialService.getById(tReportFinancialId);
        if (tReportFinancial == null) {
            return R.failed("报表1-1财务信息表信息不存在，删除失败！");
        }
        ScUser u = SecurityUtils.getUser();
        tReportFinancial.setUserid(u.getId());
        tReportFinancial.setDelFlag("4");
        tReportFinancial.setUpdateTime(new Date());
        return R.ok(tReportFinancialService.updateById(tReportFinancial));
    }


    /**
     * 更新所有财务信息的综合能源消费量、单位产值综合能耗
     */
    //@GetMapping("/upFinancialByRpt2")
    public R upFinancial() {
        QueryWrapper<TReport> q = Wrappers.query();
        q.ge("id","14378");
        q.eq("type","1");
        q.eq("del_flag","1");
        List<TReport> tReport1s = tReportService.list(q);
        tReport1s.stream().sorted(Comparator.comparingInt(TReport::getYear));



        for (TReport tReport1 : tReport1s) {
            /*if("10080".equals(tReport1.getId().toString())){
                System.err.println(10080);
            }*/

            //报表1-2
            TReport t2 = new TReport();
            t2.setType("2");
            t2.setDelFlag("1");
            t2.setYear(tReport1.getYear());
            t2.setEnterpriseCode(tReport1.getEnterpriseCode());
            List<TReport> tReport2 = tReportService.list(Wrappers.query(t2));
            if(tReport2.size()>0){
                tReport2.stream().sorted(Comparator.comparing(TReport::getDate));
            }
            long reportid2 = tReport2.size()>0 ? tReport2.get(0).getId() : 0;
            List<TReportEnergysTructure> tructureList = tReportEnergysTructureService.getTructureByReportId(reportid2);

            TReportEnergysTructure tructureSum;
            if(tructureList.size()>0){
                List<TReportEnergysTructure> sumList2 = tReportEnergysTructureeController.getSum(tructureList, reportid2, 0d);
                tructureSum = (sumList2.size() > 0 ? sumList2.get(0) : null);
            }else{
                tructureSum = null;
            }



            //报表1-2-1
            TReport t2_1 = new TReport();
            t2_1.setType("2-1");
            t2_1.setDelFlag("1");
            t2_1.setYear(tReport1.getYear());
            t2_1.setEnterpriseCode(tReport1.getEnterpriseCode());
            List<TReport> tReports2_1 = tReportService.list(Wrappers.query(t2_1));
            if(tReports2_1.size()>0){
                tReports2_1.stream().sorted(Comparator.comparing(TReport::getDate));
            }
            long reportid2_1 = tReports2_1.size()>0?tReports2_1.get(0).getId():0;
            TReportEnergyOut o = new TReportEnergyOut();
            o.setReportId(reportid2_1);
            o.setDelFlag("1");
            List<TReportEnergyOut> outList = tReportEnergyOutService.list(Wrappers.query(o));

            TReportEnergyOut outSum;
            if(outList.size()>0){
                List<TReportEnergyOut> sumList2_1 = tReportEnergyOutController.getSum(outList, reportid2_1);
                outSum = (sumList2_1.size() > 0 ? sumList2_1.get(0) : null);
            }else{
                outSum = null;
            }



            //报表1
            //获取上年的财务信息
            /*TReport t = new TReport();
            t.setEnterpriseCode(tReport1.getEnterpriseCode());
            t.setYear(tReport1.getYear() - 1);
            t.setType("1");
            t.setDelFlag("1");
            List<TReport> reports = tReportService.list(Wrappers.query(t));
            TReport r = reports.size() > 0 ? reports.get(0) : null;
            TReportFinancial frontFinancial = new TReportFinancial();
            if (r != null) {
                TReportFinancial f = new TReportFinancial();
                f.setReportId(r.getId());
                f.setDelFlag("1");
                List<TReportFinancial> financials = tReportFinancialService.list(Wrappers.query(f));
                frontFinancial = financials.size() > 0 ? financials.get(0) : null;
            }*/

            //获取本年财务信息
            TReportFinancial f = new TReportFinancial();
            f.setReportId(tReport1.getId());
            f.setDelFlag("1");
            List<TReportFinancial> financials = tReportFinancialService.list(Wrappers.query(f));
            TReportFinancial financial = financials.size() > 0 ? financials.get(0) : null;
            //财务信息，综合能源消费量、单位产值综合能耗数值更新
            if(financial!=null){
                double energyConsumption=0, energyConsumptionRate = 0, unitEnergyConsumption = 0, unitEnergyConsumption2 = 0, unitEnergyConsumptionRate = 0;

                EnterpriseInfo enterpriseInfo = enterpriseInfoService.getInfoByCode(tReport1.getEnterpriseCode());
                if(outSum!=null && outSum.getProductionConsumption()!=null){//填写了报表2-1
                    /*if(enterpriseInfo!=null && "1".equals(enterpriseInfo.getJgzh())){ //加工转换企业
                        //综合能源消费量=工业生产消费的能源折标量合计-能源加工转换产出折标量合计-回收利用折标量合计
                        energyConsumption = (outSum.getProductionConsumption() != null ? outSum.getProductionConsumption() : 0)
                                - (outSum.getConversionOutputRef() != null ? outSum.getConversionOutputRef() : 0)
                                - (outSum.getRecycling() != null ? outSum.getRecycling() : 0); //吨标准煤
                    }else{ //不是加工转换企业
                        //综合能源消费量=工业生产消费的能源折标量合计-回收利用折标量合计
                        energyConsumption = (outSum.getProductionConsumption() != null ? outSum.getProductionConsumption() : 0)
                                - (outSum.getRecycling() != null ? outSum.getRecycling() : 0); //吨标准煤
                    }*/
                    //综合能源消费量=工业生产消费的能源折标量合计-能源加工转换产出折标量合计-回收利用折标量合计
                    energyConsumption = (outSum.getProductionConsumption() != null ? outSum.getProductionConsumption() : 0)
                            - (outSum.getConversionOutputRef() != null ? outSum.getConversionOutputRef() : 0)
                            - (outSum.getRecycling() != null ? outSum.getRecycling() : 0); //吨标准煤
                } else if (tructureSum != null) {
                    //只填写了表2
                    energyConsumption = (tructureSum.getConsumeIndustry() != 0 && tructureSum.getConsumeIndustry() != null) ? tructureSum.getConsumeIndustry() : 0; //吨标准煤
                }

                //单位产值综合能耗(吨标准煤/万元) = 综合能源消费量(万吨标准煤) * 10000 / 工业总产值(万元)
                if (financial.getIndustrialYield() != null && energyConsumption != 0 && financial.getIndustrialYield() != 0) {
                    unitEnergyConsumption = energyConsumption / financial.getIndustrialYield();
                }

                //有上年数据，计算变化率
                /*if (frontFinancial != null) {
                    if (frontFinancial.getEnergyConsumption() != null && frontFinancial.getEnergyConsumption() != 0 && energyConsumption != 0) {
                        energyConsumptionRate = (energyConsumption / frontFinancial.getEnergyConsumption() - 1) * 100;
                    }
                    if (frontFinancial.getEnergyConsumption() != null && frontFinancial.getIndustrialYield() != null
                            && frontFinancial.getEnergyConsumption() != 0 && frontFinancial.getIndustrialYield() != 0) { //综合能源消费量的值来源于报表2
                        unitEnergyConsumption2 = (frontFinancial.getEnergyConsumption() * 10000) / frontFinancial.getIndustrialYield();
                    }
                    if (unitEnergyConsumption != 0 && unitEnergyConsumption2 != 0) {
                        unitEnergyConsumptionRate = (unitEnergyConsumption / unitEnergyConsumption2 - 1) * 100;
                    }
                }*/

                DecimalFormat df = new DecimalFormat(".00"); //保留2位小数
                DecimalFormat df2 = new DecimalFormat(".0000"); //保留4位小数
                financial.setEnergyConsumption(Double.parseDouble(df2.format(energyConsumption != 0 ? energyConsumption / 10000 : 0)));
                //financial.setEnergyConsumptionRate(Double.parseDouble(df2.format(energyConsumptionRate)));
                financial.setUnitEnergyConsumption(Double.parseDouble(df.format(unitEnergyConsumption)));
                //financial.setUnitEnergyConsumptionRate(Double.parseDouble(df.format(unitEnergyConsumptionRate)));

                tReportFinancialService.updateById(financial);
            }

        }
        return R.ok();
    }


    /**
     * 更新所有财务信息的综合能源消费量、单位产值综合能耗（折标系数异常的，采用参考折标计算）
     */
    //@GetMapping("/upFinancialRefByRpt2")
    public R upFinancialEqu() {
        QueryWrapper<TReport> q = Wrappers.query();
        q.ge("id","14378");
        q.eq("type","1");
        q.eq("del_flag","1");
        List<TReport> tReport1s = tReportService.list(q);
        tReport1s.stream().sorted(Comparator.comparingInt(TReport::getYear));


        for (TReport tReport1 : tReport1s) {

            //报表1-2
            TReport t2 = new TReport();
            t2.setType("2");
            t2.setDelFlag("1");
            t2.setYear(tReport1.getYear());
            t2.setEnterpriseCode(tReport1.getEnterpriseCode());
            List<TReport> tReport2 = tReportService.list(Wrappers.query(t2));
            if(tReport2.size()>0){
                tReport2.stream().sorted(Comparator.comparing(TReport::getDate));
            }
            long reportid2 = tReport2.size()>0 ? tReport2.get(0).getId() : 0;
            List<TReportEnergysTructure> tructureList = tReportEnergysTructureService.getTructureByReportId(reportid2);

            TReportEnergysTructure tructureSum;
            if(tructureList.size()>0){
                List<TReportEnergysTructure> sumList2 = tReportEnergysTructureeController.getSum(tructureList, reportid2, 0d);
                //tructureSum = (sumList2.size() >=2 ? sumList2.get(2) : null); //采用参考折标系数的计算值
                tructureSum = (sumList2.size() >=2 ? sumList2.get(1) : null); //采用等价值
            }else{
                tructureSum = null;
            }


            //报表1-2-1
            TReport t2_1 = new TReport();
            t2_1.setType("2-1");
            t2_1.setDelFlag("1");
            t2_1.setYear(tReport1.getYear());
            t2_1.setEnterpriseCode(tReport1.getEnterpriseCode());
            List<TReport> tReports2_1 = tReportService.list(Wrappers.query(t2_1));
            if(tReports2_1.size()>0){
                tReports2_1.stream().sorted(Comparator.comparing(TReport::getDate));
            }
            long reportid2_1 = tReports2_1.size()>0?tReports2_1.get(0).getId():0;
            TReportEnergyOut o = new TReportEnergyOut();
            o.setReportId(reportid2_1);
            o.setDelFlag("1");
            List<TReportEnergyOut> outList = tReportEnergyOutService.list(Wrappers.query(o));

            TReportEnergyOut outSum;
            if(outList.size()>0){
                List<TReportEnergyOut> sumList2_1 = tReportEnergyOutController.getSum(outList, reportid2_1);
                //outSum = (sumList2_1.size() >= 2 ? sumList2_1.get(2) : null); //采用参考折标系数的计算值
                outSum = (sumList2_1.size() >= 2 ? sumList2_1.get(1) : null); //采用等价值
            }else{
                outSum = null;
            }


            //获取本年财务信息
            TReportFinancial f = new TReportFinancial();
            f.setReportId(tReport1.getId());
            f.setDelFlag("1");
            List<TReportFinancial> financials = tReportFinancialService.list(Wrappers.query(f));
            TReportFinancial financial = financials.size() > 0 ? financials.get(0) : null;
            //财务信息，综合能源消费量、单位产值综合能耗数值更新
            if(financial!=null){
                double energyConsumption=0, energyConsumptionRate = 0, unitEnergyConsumption = 0, unitEnergyConsumption2 = 0, unitEnergyConsumptionRate = 0;

                EnterpriseInfo enterpriseInfo = enterpriseInfoService.getInfoByCode(tReport1.getEnterpriseCode());
                if(outSum!=null && outSum.getProductionConsumption()!=null){//填写了报表2-1
                    //综合能源消费量=工业生产消费的能源折标量合计-能源加工转换产出折标量合计-回收利用折标量合计
                    energyConsumption = (outSum.getProductionConsumption() != null ? outSum.getProductionConsumption() : 0)
                            - (outSum.getConversionOutputRef() != null ? outSum.getConversionOutputRef() : 0)
                            - (outSum.getRecycling() != null ? outSum.getRecycling() : 0); //吨标准煤
                } else if (tructureSum != null) {
                    //只填写了表2
                    energyConsumption = (tructureSum.getConsumeIndustry() != 0 && tructureSum.getConsumeIndustry() != null) ? tructureSum.getConsumeIndustry() : 0; //吨标准煤
                }

                //单位产值综合能耗(吨标准煤/万元) = 综合能源消费量(万吨标准煤) * 10000 / 工业总产值(万元)
                if (financial.getIndustrialYield() != null && energyConsumption != 0 && financial.getIndustrialYield() != 0) {
                    unitEnergyConsumption = energyConsumption / financial.getIndustrialYield();
                }

                DecimalFormat df = new DecimalFormat(".00"); //保留2位小数
                DecimalFormat df2 = new DecimalFormat(".0000"); //保留4位小数
                financial.setEnergyConsumptionRef(Double.parseDouble(df2.format(energyConsumption != 0 ? energyConsumption / 10000 : 0))); //万吨标准煤
                financial.setUnitEnergyConsumptionRef(Double.parseDouble(df.format(unitEnergyConsumption)));

                tReportFinancialService.updateById(financial);
            }

        }
        return R.ok();
    }

    /**
     * 更新所有财务信息的综合能源消费量同比变化率、单位产值综合能耗同比变化率等 同比变化率
     */
    //@GetMapping("/upFinancialRate")
    public R upFinancial2() {
        /*TReportFinancial t1 = new TReportFinancial();
        t1.setDelFlag("1");*/
        QueryWrapper<TReportFinancial> t1 = Wrappers.query();
        t1.ge("report_id","14378");
        t1.eq("del_flag","1");
        List<TReportFinancial> financials = tReportFinancialService.list(t1);

        for (TReportFinancial financial : financials) {
            //本年报表信息
            TReport r = tReportService.getById(financial.getReportId());

            if (r != null) {
                //上年报表信息
                TReport t2 = new TReport();
                t2.setType("1");
                t2.setDelFlag("1");
                t2.setEnterpriseCode(r.getEnterpriseCode());
                t2.setYear(r.getYear() - 1);
                List<TReport> list = tReportService.list(Wrappers.query(t2));
                TReport r2 = list.size() > 0 ? list.get(0) : null;
                //上年财务信息
                TReportFinancial financial2 = tReportFinancialService.getFinancialsByReportId(r2 != null ? r2.getId() : 0);

                if (financial2 != null) {
                    //有上年数据，计算变化率
                    Double energyConsumption = financial.getEnergyConsumption();
                    double energyConsumptionRate = 0, unitEnergyConsumption = 0, unitEnergyConsumption2 = 0, unitEnergyConsumptionRate = 0;
                    if (financial2.getEnergyConsumption() != null && financial2.getEnergyConsumption() != 0 && energyConsumption != 0) {
                        energyConsumptionRate = (energyConsumption / financial2.getEnergyConsumption() - 1) * 100;
                    }
                    if (financial.getEnergyConsumption() != null && financial.getIndustrialYield() != null
                            && financial.getEnergyConsumption() != 0 && financial.getIndustrialYield() != 0) { //综合能源消费量的值来源于报表2
                        unitEnergyConsumption = (financial.getEnergyConsumption() * 10000) / financial.getIndustrialYield();
                    }
                    if (financial2.getEnergyConsumption() != null && financial2.getIndustrialYield() != null
                            && financial2.getEnergyConsumption() != 0 && financial2.getIndustrialYield() != 0) { //综合能源消费量的值来源于报表2
                        unitEnergyConsumption2 = (financial2.getEnergyConsumption() * 10000) / financial2.getIndustrialYield();
                    }
                    if (unitEnergyConsumption != 0 && unitEnergyConsumption2 != 0) {
                        unitEnergyConsumptionRate = (unitEnergyConsumption / unitEnergyConsumption2 - 1) * 100;
                    }

                    DecimalFormat df = new DecimalFormat(".00"); //保留2位小数
                    DecimalFormat df2 = new DecimalFormat(".0000"); //保留4位小数
                    financial.setEnergyConsumptionRate(Double.parseDouble(df2.format(energyConsumptionRate)));
                    financial.setUnitEnergyConsumptionRate(Double.parseDouble(df.format(unitEnergyConsumptionRate)));

                    if (financial2.getIndustrialYield() != null && financial2.getIndustrialYield() != 0
                            && financial.getIndustrialYield() != null && financial.getIndustrialYield() != 0) { //工业总产值同比变化率
                        financial.setIndustrialYieldRate(Double.parseDouble(df2.format((financial.getIndustrialYield() / financial2.getIndustrialYield() - 1) * 100)));
                    }
                    if (financial2.getSalesRevenue() != null && financial2.getSalesRevenue() != 0
                            && financial.getSalesRevenue() != null && financial.getSalesRevenue() != 0) { //销售收入同比变化率
                        financial.setSalesRevenueRate(Double.parseDouble(df2.format((financial.getSalesRevenue() / financial2.getSalesRevenue() - 1) * 100)));
                    }
                    if (financial2.getTaxesPayment() != null && financial2.getTaxesPayment() != 0
                            && financial.getTaxesPayment() != null && financial.getTaxesPayment() != 0) { //上缴利税同比变化率
                        financial.setTaxesPaymentRate(Double.parseDouble(df2.format((financial.getTaxesPayment() / financial2.getTaxesPayment() - 1) * 100)));
                    }
                    if (financial2.getEmployeesNum() != null && financial2.getEmployeesNum() != 0
                            && financial.getEmployeesNum() != null && financial.getEmployeesNum() != 0) { //从业人员同比变化比率
                        financial.setEmployeesNumRate(Double.parseDouble(df2.format((financial.getEmployeesNum() / financial2.getEmployeesNum() - 1) * 100)));
                    }
                    if (financial2.getIcsemNum() != null && financial2.getIcsemNum() != 0
                            && financial.getIcsemNum() != null && financial.getIcsemNum() != 0) { //能源管理师同比变化率
                        financial.setIcsemNumRate(Double.parseDouble(df2.format((financial.getIcsemNum() / financial2.getIcsemNum() - 1) * 100)));
                    }
                    if (financial2.getProductionCost() != null && financial2.getProductionCost() != 0
                            && financial.getProductionCost() != null && financial.getProductionCost() != 0) { //生产总成本同比变化率
                        financial.setProductionCostRate(Double.parseDouble(df2.format((financial.getProductionCost() / financial2.getProductionCost() - 1) * 100)));
                    }
                    if (financial2.getEnergyConsumptionCost() != null && financial2.getEnergyConsumptionCost() != 0
                            && financial.getEnergyConsumptionCost() != null && financial.getEnergyConsumptionCost() != 0) { //能源消费成本同比变化率
                        financial.setEnergyConsumptionCostRate(Double.parseDouble(df2.format((financial.getEnergyConsumptionCost() / financial2.getEnergyConsumptionCost() - 1) * 100)));
                    }
                    if (financial2.getEnergyConsumptionCostRatio() != null && financial2.getEnergyConsumptionCostRatio() != 0
                            && financial.getEnergyConsumptionCostRatio() != null && financial.getEnergyConsumptionCostRatio() != 0) { //能源消费占总成本同比变化率
                        financial.setEnergyConsumptionCostRatioRate(Double.parseDouble(df2.format((financial.getEnergyConsumptionCostRatio() / financial2.getEnergyConsumptionCostRatio() - 1) * 100)));
                    }

                    tReportFinancialService.updateById(financial);

                }
            }

        }
        return R.ok();
    }


    private TReportFinancial getEnergyConsumptionInfo(String year, String enterpriseCode,TReportFinancial financial) {
        //报表1-2
        TReport tReport2 = tReportService.getInfoByType(enterpriseCode, year, "2");
        long reportid2 = tReport2!=null ? tReport2.getId() : 0;
        List<TReportEnergysTructure> tructureList = tReportEnergysTructureService.getTructureByReportId(reportid2);
        TReportEnergysTructure tructureSum;
        if (tructureList.size() > 0) {
            List<TReportEnergysTructure> sumList2 = tReportEnergysTructureeController.getSum(tructureList, reportid2, 0d);
            tructureSum = (sumList2.size() > 0 ? sumList2.get(0) : null);
        } else {
            tructureSum = null;
        }

        //报表1-2-1
        TReport tReport2_1 = tReportService.getInfoByType(enterpriseCode, year, "2-1");
        long reportid2_1 = tReport2_1!=null ? tReport2_1.getId() : 0;
        TReportEnergyOut o = new TReportEnergyOut();
        o.setReportId(reportid2_1);
        o.setDelFlag("1");
        List<TReportEnergyOut> outList = tReportEnergyOutService.list(Wrappers.query(o));
        TReportEnergyOut outSum;
        if (outList.size() > 0) {
            List<TReportEnergyOut> sumList2_1 = tReportEnergyOutController.getSum(outList, reportid2_1);
            outSum = (sumList2_1.size() > 0 ? sumList2_1.get(0) : null);
        } else {
            outSum = null;
        }

        //财务信息，综合能源消费量、单位产值综合能耗数值更新
        if (financial != null) {
            double energyConsumption = 0, energyConsumptionRate = 0, unitEnergyConsumption = 0, unitEnergyConsumption2 = 0, unitEnergyConsumptionRate = 0;
            if (outSum != null && outSum.getProductionConsumption() != null) {//填写了报表2-1
                //综合能源消费量=工业生产消费的能源折标量合计-能源加工转换产出折标量合计-回收利用折标量合计
                energyConsumption = (outSum.getProductionConsumption() != null ? outSum.getProductionConsumption() : 0)
                        - (outSum.getConversionOutputRef() != null ? outSum.getConversionOutputRef() : 0)
                        - (outSum.getRecycling() != null ? outSum.getRecycling() : 0); //吨标准煤
            } else if (tructureSum != null) {
                //只填写了表2
                energyConsumption = (tructureSum.getConsumeIndustry() != 0 && tructureSum.getConsumeIndustry() != null) ? tructureSum.getConsumeIndustry() : 0; //吨标准煤
            }

            //单位产值综合能耗(吨标准煤/万元) = 综合能源消费量(万吨标准煤) * 10000 / 工业总产值(万元)
            if (financial.getIndustrialYield() != null && energyConsumption != 0 && financial.getIndustrialYield() != 0) {
                unitEnergyConsumption = energyConsumption / financial.getIndustrialYield();
            }

            TReport report1 = tReportService.getInfoByType(enterpriseCode, (Integer.parseInt(year) - 1) + "", "1");
            TReportFinancial frontFinancial = tReportFinancialService.getFinancialsByReportId(report1 != null ? report1.getId() : 0);
            //有上年数据，计算变化率
            if (frontFinancial != null) {
                if (frontFinancial.getEnergyConsumption() != null && frontFinancial.getEnergyConsumption() != 0 && energyConsumption != 0) {
                    energyConsumptionRate = (energyConsumption / (frontFinancial.getEnergyConsumption()*10000) - 1) * 100;
                }
                if (frontFinancial.getEnergyConsumption() != null && frontFinancial.getIndustrialYield() != null
                        && frontFinancial.getEnergyConsumption() != 0 && frontFinancial.getIndustrialYield() != 0) { //综合能源消费量的值来源于报表2
                    unitEnergyConsumption2 = (frontFinancial.getEnergyConsumption() * 10000) / frontFinancial.getIndustrialYield();
                }
                if (unitEnergyConsumption != 0 && unitEnergyConsumption2 != 0) {
                    unitEnergyConsumptionRate = (unitEnergyConsumption / unitEnergyConsumption2 - 1) * 100;
                }
            }

            DecimalFormat df = new DecimalFormat(".00"); //保留2位小数
            DecimalFormat df2 = new DecimalFormat(".0000"); //保留4位小数
            financial.setEnergyConsumption(Double.parseDouble(df2.format(energyConsumption != 0 ? energyConsumption / 10000 : 0)));
            financial.setEnergyConsumptionRate(Double.parseDouble(df2.format(energyConsumptionRate)));
            financial.setUnitEnergyConsumption(Double.parseDouble(df.format(unitEnergyConsumption)));
            financial.setUnitEnergyConsumptionRate(Double.parseDouble(df.format(unitEnergyConsumptionRate)));
        }
        return financial;
    }
}
