package com.nantian.cloud.jljc.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
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-16
 */
@Slf4j
@CrossOrigin
@RestController
@AllArgsConstructor
@RequestMapping("/tReportProduct")
@Api(value = "tReportProduct", tags = "报表1-1主要产品表")
public class TReportProductController {

    final private TReportProductService tReportProductService;
    final private TReportEnterpriseService tReportEnterpriseService;
    final private TReportService tReportService;
    final private TReportParaService tReportParaService;
    private final EcAbnormalVolatilityService ecAbnormalVolatilityService;
    private final EcAbnormalVolatilityInfoService ecAbnormalVolatilityInfoService;
    private final EnterpriseInfoService enterpriseInfoService;

    /**
     * 分页查询
     */
    @GetMapping("/page")
    @SysLog("查询报表1-1主要产品表")
    @ApiOperation(value = "查询报表1-1主要产品表", notes = "条件查询报表1-1主要产品表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "tReportProduct", value = "报表1-1主要产品表", required = false, dataType = "json", paramType = "path"),
            @ApiImplicitParam(name = "page", value = "分页对象", required = false, dataType = "json", paramType = "path")
    })
    public R getcheckGaugesPage(Page page, TReportProduct tReportProduct) {
        tReportProduct.setDelFlag("1"); //查询未删除数据
        //return R.ok(tReportProductService.getPageScope(page,tReportProduct));
        return R.ok(tReportProductService.page(page, Wrappers.query(tReportProduct)));
    }

    /**
     * 通过id查询报表1-1主要产品表
     */
    @GetMapping("/{tReportProductId}")
    @SysLog("通过id查询报表1-1主要产品表")
    @ApiOperation(value = "通过id查询报表1-1主要产品表", notes = "通过id查询报表1-1主要产品表")
    @ApiImplicitParam(name = "tReportProductId", value = "报表1-1主要产品表id", required = true, paramType = "path", dataType = "int")
    public R getById(@PathVariable("tReportProductId") Integer tReportProductId) {
        return R.ok(tReportProductService.getById(tReportProductId));
    }

    /**
     * 通过年份、企业社会编码查询所有主要产品的名称
     */
    @GetMapping("/getProductName")
    @SysLog("通过年份、企业社会编码查询所有主要产品的名称")
    @ApiOperation(value = "通过年份、企业社会编码查询所有主要产品的名称", notes = "通过年份、企业社会编码查询所有主要产品的名称")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "year", value = "年份", required = true, paramType = "path"),
            @ApiImplicitParam(name = "enterpriseCode", value = "企业社会信用编码", required = true, paramType = "path")
    })
    public R getProductName(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");
        if (report == null) {
            return R.ok();
        }
        return R.ok(tReportProductService.getProductName(report.getId() != null ? report.getId() : 0));
    }

    /**
     * 通过年份查询报表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("查询主要产品表失败，年度不能为空");
        }
        if (enterpriseCode == null || "".equals(enterpriseCode)) {
            return R.failed("查询失败，企业社会信用编码不能为空");
        }
        //ScUser u = SecurityUtils.getUser();
        //获取能源报表信息
        TReport report = tReportService.getInfoByType(enterpriseCode, year, "1");
        if (report == null) {
            return R.ok();
        }
        //获取主要产品信息
        List<TReportProduct> products = tReportProductService.getProductsByReportId(report.getId());
        return R.ok(products);
    }


    /**
     * 通过年份查询报表1-1主要产品表近三年数据
     */
    @GetMapping("/getByYear2")
    @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 getByYear2(String year, String enterpriseCode) {
        if (year == null || "".equals(year)) {
            return R.failed("查询失败，年度不能为空");
        }
        if (enterpriseCode == null || "".equals(enterpriseCode)) {
            return R.failed("查询失败，企业社会信用编码不能为空");
        }

        //获取能源报表信息
        Integer yearTemp = Integer.parseInt(year);
        TReport report1 = tReportService.getInfoByType(enterpriseCode, year, "1");
        TReport report2 = tReportService.getInfoByType(enterpriseCode, (yearTemp - 1) + "", "1");
        TReport report3 = tReportService.getInfoByType(enterpriseCode, (yearTemp - 2) + "", "1");

        //获取主要产品信息
        List<TReportProduct> products = tReportProductService.getProductsByReportIds(
                report1 != null ? report1.getId() : 0, report2 != null ? report2.getId() : 0, report3 != null ? report3.getId() : 0);
        return R.ok(products);
    }

    /**
     * 通过年份查询初始化报表信息
     */
    @GetMapping("/initialize")
    @SysLog("通过年份查询初始化报表信息")
    @ApiOperation(value = "通过年份查询初始化报表信息", notes = "通过年份查询初始化报表信息")
    @ApiImplicitParam(name = "year", value = "年份", required = false, dataType = "json", paramType = "path")
    public R initialize(String year, String enterpriseCode) {
        if (year == null || "".equals(year)) {
            return R.failed("查询失败，年度不能为空");
        }
        //String productInfoStr = tReportEnterpriseService.getProductInfo(enterpriseCode, year);
        if(StringUtils.isEmpty(enterpriseCode)){
            enterpriseCode = SecurityUtils.getUser().getEnterpriseCode();
        }
        String productInfoStr = tReportEnterpriseService.getProductInfo(enterpriseCode, year);
        if (productInfoStr != null) {
            List<ProductInfo> productInfoList = (List<ProductInfo>) JSONArray.parseArray(productInfoStr, ProductInfo.class);
            List<TReportProduct> products = new ArrayList<>();
            for (ProductInfo productInfo : productInfoList) {
                TReportProduct product = new TReportProduct();
                product.setProductName(productInfo.getProductName());
                product.setProductNum(productInfo.getProductNum());
                product.setCapacityNum(productInfo.getCapacityNum());
                product.setCapacityUnit(productInfo.getUnit());
                product.setYieldUnit(productInfo.getUnit());
                product.setUnitEnergyConsumptionUnit("吨标准煤");
                products.add(product);
            }
            return R.ok(products);
        } else {
            return R.ok();
        }
    }


    /**
     * 批量更新报表1-1主要产品表
     */
    @Transactional
    @PostMapping("/upProducts")
    @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 upProducts(@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();
        String products = json.getString("data");
        //获取主要产品列表
        List<TReportProduct> productList = (List<TReportProduct>) JSONArray.parseArray(products, TReportProduct.class);


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


        //批量更新报表1-1主要产品表
        //获取报表信息id
        long reportId = tReportService.getTReportIdByType(enterpriseCode, report.getYear() + "", "1", u);
        //更新报表信息
        report.setId(reportId);
        report.setUserid(u.getId());
        report.setReportStatus("2");
        report.setUpdateTime(new Date());
        //boolean b = tReportService.updateById(report);

        List<TReportProduct> newProductList = new ArrayList<TReportProduct>();
        for (TReportProduct product : productList) {
            TReportProduct p = new TReportProduct();
            p.setReportId(reportId);
            p.setProductName(product.getProductName());
            //若报表信息id、产品名为条件有数据，该条记录为修改；否则为新增
            TReportProduct np = tReportProductService.getOne(Wrappers.query(p));
            if (np != null) { //修改
                product.setId(np.getId());
            } else { //新增
                //product.setDeptId(u.getId());
                EnterpriseInfo info = enterpriseInfoService.getInfoByCode(u.getEnterpriseCode());
                product.setDeptId(info != null && info.getRegionCode()!=null ? Integer.parseInt(info.getRegionCode()) : u.getDeptId());
                product.setDelFlag("1");
            }
            //product.setDeptId(u.getId());
            //product.setDelFlag("1");
            product.setReportId(reportId);
            product.setUserid(u.getId());
            product.setUpdateTime(new Date());
            //product.setYieldUnit(product.getCapacityUnit());
            DecimalFormat df = new DecimalFormat(".00"); //保留两位小数
            if (product.getEnergyConsumption() != null && product.getEnergyConsumption() != 0) {
                //设置单位产品能耗值    单位产品能耗值 = 产品能耗值/年产量
                double unitEnergyConsumption = product.getEnergyConsumption() / product.getYieldNum();
                if (unitEnergyConsumption < 1) {
                    product.setUnitEnergyConsumption(Double.parseDouble(df.format(unitEnergyConsumption * 1000)));
                    product.setUnitEnergyConsumptionUnit("千克标准煤/" + product.getYieldUnit());
                } else {
                    product.setUnitEnergyConsumption(Double.parseDouble(df.format(unitEnergyConsumption)));
                    product.setUnitEnergyConsumptionUnit("吨标准煤/" + product.getYieldUnit());
                }
            } else {
                //产品能耗为null或0时，单位产品能耗的单位
                product.setUnitEnergyConsumptionUnit("吨标准煤/" + product.getYieldUnit());
            }
            //产品能耗的单位
            product.setEnergyConsumptionUnit("吨标准煤");
            newProductList.add(product);
        }

        //return R.ok(tReportProductService.saveOrUpdateBatch(newProductList));
        boolean updateBatch = tReportProductService.saveOrUpdateBatch(newProductList);
        if (updateBatch) {
            //产品信息更新成功，报表信息才更新
            return R.ok(tReportService.updateById(report));
        } else {
            return R.failed();
        }
    }


    /**
     * 进行异常波动分析
     */
    private R getEcAbnormalVolatility(TReport report, ScUser u, List<TReportProduct> productList) {
        //获取上年的报表信息
        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) {
            //获取上一年主要产品信息
            TReportProduct front = new TReportProduct();
            front.setReportId(frontReport.getId());
            front.setDelFlag("1");
            List<TReportProduct> frontProductList = tReportProductService.list(Wrappers.query(front));
            if (frontProductList.size() > 0) { //上年数据存在，进行异常波动分析
                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.setDataTable("表1");
                    ecAbnormalVolatilityInfo.setType("主要产品"); //仅表1用到这个字段*/
                    //进行异常波动分析
                    DecimalFormat df = new DecimalFormat(".00"); //保留两位小数
                    Map<String, Object> map = new HashMap();
                    map.put("dataTable", "表1");
                    map.put("type", "主要产品");

                    //本年产品信息
                    for (TReportProduct product : productList) {
                        boolean addState = true; //新增标志默认为，true，是新增项
                        //上年产品信息
                        for (TReportProduct frontProduct : frontProductList) {
                            if (product.getProductName().equals(frontProduct.getProductName()) || product.getProductNum().equals(frontProduct.getProductNum())) {
                                addState = false;  //该条产品，不是新增项

                                VolatilityTmpController.VolatilityTmp volatilityTmp = new VolatilityTmpController.VolatilityTmp(
                                        ecAbnormalVolatilityInfoService,
                                        u, flage, para, volatility, df, map,
                                        "主要产品",
                                        "表1",
                                        product.getCapacityNum()!=null?product.getCapacityNum():0,
                                        frontProduct.getCapacityNum()!=null?frontProduct.getCapacityNum():0,
                                        //(product.getCapacityNum() / frontProduct.getCapacityNum() - 1) * 100,
                                        "【主要产品】" + product.getProductName() + "（年产能数量），超出波动范围。若确定数值，请填写变化情况说明！",
                                        product.getProductName() + "（年产能数量）",
                                        product.getCapacityUnit()).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",
                                        product.getYieldNum()!=null?product.getYieldNum():0,
                                        frontProduct.getYieldNum()!=null?frontProduct.getYieldNum():0,
                                        //(product.getYieldNum() / frontProduct.getYieldNum() - 1) * 100,
                                        "【主要产品】" + product.getProductName() + "（年产量数量），超出波动范围。若确定数值，请填写变化情况说明！",
                                        product.getProductName() + "（年产量数量）",
                                        product.getYieldUnit()).invoke();
                                if (volatilityTmp2.is()) { //超出波动范围，且未填写波动说明，返回错误信息
                                    return R.failed(map);
                                }
                                flage = volatilityTmp2.isFlage(); //更新超期标志

                            }
                        }

                        //遍历完上年数据，无相同名称的产品，属于新增
                        EcAbnormalVolatilityInfo ecAbnormalVolatilityInfo = new EcAbnormalVolatilityInfo();
                        ecAbnormalVolatilityInfo.setAbnormalVolatilityId(volatility != null ? volatility.getId() : 0);
                        ecAbnormalVolatilityInfo.setDelFlag("1");
                        ecAbnormalVolatilityInfo.setDataTable("表1");
                        ecAbnormalVolatilityInfo.setType("主要产品"); //仅表1用到这个字段
                        ecAbnormalVolatilityInfo.setDataContent(product.getProductName());
                        ecAbnormalVolatilityInfo.setAddState("T");
                        EcAbnormalVolatilityInfo addVolatilityInfo = ecAbnormalVolatilityInfoService.getOne(Wrappers.query(ecAbnormalVolatilityInfo));
                        if (addState) {
                            if (addVolatilityInfo == null) {
                                map.put("msg", "【主要产品】" + product.getProductName() + "，属于新增产品，请填写新增情况说明！");
                                map.put("dataContent", product.getProductName());
                                map.put("unitVal", product.getCapacityUnit());
                                map.put("addState", "T");
                                return R.failed(map);
                            }
                        } else {
                            if (addVolatilityInfo != null) {
                                //没有新增，却有新增记录，需要删除
                                deleteVolatilityInfo(u, addVolatilityInfo);
                            }
                        }


                    }

                    //表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 = "TReportProduct", value = "报表1-1主要产品表", required = true, dataType = "json", paramType = "path")
    public R save(@RequestBody TReportProduct tReportProduct) {
        ScUser u = SecurityUtils.getUser();
        tReportProduct.setUserid(u.getId());
        EnterpriseInfo info = enterpriseInfoService.getInfoByCode(u.getEnterpriseCode());
        tReportProduct.setDeptId(info != null && info.getRegionCode()!=null ? Integer.parseInt(info.getRegionCode()) : u.getDeptId());
        //tReportProduct.setDeptId(u.getDeptId());
        tReportProduct.setDelFlag("1");
        tReportProduct.setUpdateTime(new Date());
        return R.ok(tReportProductService.save(tReportProduct));
    }

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

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

    /**
     * 批量删除报表1-1主要产品表
     */
    @DeleteMapping("/delBatch")
    @SysLog("批量删除报表1-1主要产品表")
    @ApiOperation(value = "批量删除报表1-1主要产品表", notes = "批量删除报表1-1主要产品表")
    @ApiImplicitParam(name = "ids", value = "多个id 逗号隔开", required = true, dataType = "int", paramType = "path")
    public R delBatch(String ids) {

        String[] split = ids.split(",");
        List<TReportProduct> newProductList = new ArrayList<>();
        for (int i = 0; i < split.length; i++) {
            TReportProduct tReportProduct = tReportProductService.getById(Integer.parseInt(split[i]));
            ScUser u = SecurityUtils.getUser();
            tReportProduct.setUserid(u.getId());
            tReportProduct.setUpdateTime(new Date());
            tReportProduct.setDelFlag("4");
            newProductList.add(tReportProduct);
        }
        return R.ok(tReportProductService.updateBatchById(newProductList));
    }


    /**
     * 根据unitEnergyConsumptionOldOld 单位产品能耗历史数据，更新产品能耗、单位产品能耗数据和单位
     */
    //@GetMapping("/upByOld")
    public R upByOld() {
        List<TReportProduct> reportProducts = tReportProductService.list();
        List<TReportProduct> newList = new ArrayList<>();
        DecimalFormat df = new DecimalFormat(".0000"); //保留两位小数
        for (TReportProduct product : reportProducts) {
            if (product.getUnitEnergyConsumptionOldOld() != null) {
                if (product.getUnitEnergyConsumptionOldOld() >= 1000) {
                    product.setUnitEnergyConsumption(Double.parseDouble(df.format(product.getUnitEnergyConsumptionOldOld() / 1000)));
                    product.setUnitEnergyConsumptionUnit("吨标准煤/" + product.getYieldUnit());
                } else {
                    product.setUnitEnergyConsumption(Double.parseDouble(df.format(product.getUnitEnergyConsumptionOldOld())));
                    product.setUnitEnergyConsumptionUnit("千克标准煤/" + product.getYieldUnit());
                }
                if (product.getYieldNum() != null && product.getYieldNum()!=0) {
                    product.setEnergyConsumption(Double.parseDouble(df.format(product.getUnitEnergyConsumptionOldOld() / 1000 * product.getYieldNum())));
                }
            }else{
                //产品能耗为null时，单位产品能耗的单位
                product.setUnitEnergyConsumptionUnit("吨标准煤/" + product.getYieldUnit());
            }
            product.setEnergyConsumptionUnit("吨标准煤");
            tReportProductService.updateById(product);
        }
        return R.ok();
    }

}
