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.dto.AuditorDto;
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-3能耗指标表
 *
 * @author stz
 * @date 2020-09-16
 */
@Slf4j
@CrossOrigin
@RestController
@AllArgsConstructor
@RequestMapping("/tReportUnitenergy")
@Api(value = "tReportUnitenergy", tags = "报表1-3能耗指标表")
public class TReportUnitenergyController {

    final private TReportUnitenergyService tReportUnitenergyService;
    final private TReportEnterpriseService tReportEnterpriseService;
    final private TReportService tReportService;
    final private TReportParaService tReportParaService;
    private final EcAbnormalVolatilityService ecAbnormalVolatilityService;
    private final EcAbnormalVolatilityInfoService ecAbnormalVolatilityInfoService;
    private final EcAbnormalVolatilityInfoController volatilityInfoController;
    private final EpcEnergyAccuracyAnalysisService epcEnergyAccuracyAnalysisService;
    private final EpcEnergyAccuracyAnalysisInfoService epcEnergyAccuracyAnalysisInfoService;
    private final EnergyIndexService energyIndexService;
    private final EnterpriseInfoService enterpriseInfoService;


    public static final double NEGATIVE_INFINITY = -1.0 / 0.0;
    public static final double POSITIVE_INFINITY = 1.0 / 0.0;


    /**
     * 分页查询
     */
    @GetMapping("/page")
    @SysLog("查询报表1-3能耗指标表")
    @ApiOperation(value = "查询报表1-3能耗指标表", notes = "条件查询报表1-3能耗指标表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "tReportUnitenergy", value = "报表1-3能耗指标表", required = false, dataType = "json", paramType = "path"),
            @ApiImplicitParam(name = "page", value = "分页对象", required = false, dataType = "json", paramType = "path")
    })
    public R getcheckGaugesPage(Page page, TReportUnitenergy tReportUnitenergy) {
        tReportUnitenergy.setDelFlag("1"); //查询未删除数据
        //return R.ok(tReportUnitenergyService.getPageScope(page,tReportUnitenergy));
        return R.ok(tReportUnitenergyService.page(page, Wrappers.query(tReportUnitenergy)));
    }

    /**
     * 通过id查询报表1-3能耗指标表
     */
    @GetMapping("/{tReportUnitenergyId}")
    @SysLog("通过id查询报表1-3能耗指标表")
    @ApiOperation(value = "通过id查询报表1-3能耗指标表", notes = "通过id查询报表1-3能耗指标表")
    @ApiImplicitParam(name = "tReportUnitenergyId", value = "报表1-3能耗指标表id", required = true, paramType = "path", dataType = "int")
    public R getById(@PathVariable("tReportUnitenergyId") Integer tReportUnitenergyId) {
        return R.ok(tReportUnitenergyService.getById(tReportUnitenergyId));
    }

    /**
     * 通过年份查询报表1-3能耗指标表
     */
    @GetMapping("/getByYear")
    @SysLog("通过年份查询报表1-3能耗指标表")
    @ApiOperation(value = "通过年份查询报表1-3能耗指标表", notes = "通过年份查询报表1-3能耗指标表")
    @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, "3");
        if (report == null) {
            return R.ok();
        }
        //获取能耗指标表信息
        List<TReportUnitenergy> unitenergyList = tReportUnitenergyService.getUnitenergyByReportId(report.getId());
        return R.ok(unitenergyList);
    }

    /**
     * 通过年份查询初始化报表信息
     */
    @GetMapping("/initialize")
    @SysLog("通过年份查询初始化报表信息")
    @ApiOperation(value = "通过年份查询初始化报表信息", notes = "通过年份查询初始化报表信息")
    @ApiImplicitParam(name = "year", value = "年份", required = false, dataType = "json", paramType = "path")
    public R initialize(String year) {
        if (year == null || "".equals(year)) {
            return R.failed("查询失败，年度不能为空");
        }

        //查询当年报表设置信息
        ScUser u = SecurityUtils.getUser();
        String energyIndexStr = tReportEnterpriseService.getEnergyIndex(u.getEnterpriseCode(), year);
        List<Long> ids = new ArrayList<>();
        if (energyIndexStr != null && !"".equals(energyIndexStr)) {
            List<EnergyIndex> energyIndexList = (List<EnergyIndex>) JSONArray.parseArray(energyIndexStr, EnergyIndex.class);
            for (EnergyIndex energyIndex : energyIndexList) {
                ids.add(energyIndex.getId());
            }
        }

        //查询上年报表id
        String prevYear = (Integer.parseInt(year) - 1) + "";
        TReport report = tReportService.getInfoByType(u.getEnterpriseCode(), prevYear, "3");
        Long reportId = report == null ? 0 : report.getId();

        //根据报表设置信息、上年id初始化报表信息
        List<TReportUnitenergy> unitenergyList = tReportUnitenergyService.initialize(ids, reportId);
        return R.ok(unitenergyList);
    }

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


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

        log.error("批量更新报表1-3能耗指标表：" + 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-3能耗指标表失败，年度不能为空");
        }

        ScUser u = SecurityUtils.getUser();
        String enterpriseCode = StringUtils.isNotEmpty(report.getEnterpriseCode()) ? report.getEnterpriseCode() : u.getEnterpriseCode();
        String data = json.getString("data");
        //获取能源消费表列表
        List<TReportUnitenergy> unitenergyList = (List<TReportUnitenergy>) JSONArray.parseArray(data, TReportUnitenergy.class);


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

        //进行精确性分析
        boolean c = epcEnergyAccuracyAnalysisService.getEpcEnergyAccuracyAnalysis3(report, unitenergyList, u);


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

        List<TReportUnitenergy> newUnitenergyList = new ArrayList<TReportUnitenergy>();
        for (TReportUnitenergy unitenergy : unitenergyList) {
            hasOld(u, unitenergy, reportId);
            unitenergy.setReportId(reportId);
            unitenergy.setUserid(u.getId());
            unitenergy.setUpdateTime(new Date());
            //添加指标限额
            EnergyIndex energyIndex = new EnergyIndex();
            if(unitenergy.getQuotaId()!=null){
                energyIndex = energyIndexService.getById(unitenergy.getQuotaId());
            }else{
                EnergyIndex i = new EnergyIndex();
                i.setIndexName(unitenergy.getQuotaName());
                i.setDelFlag("1");
                energyIndex = energyIndexService.getOne(Wrappers.query(i));
            }
            if (energyIndex != null) {
                unitenergy.setQuotaLimit(energyIndex.getLocalLimit() != null ? energyIndex.getLocalLimit() : energyIndex.getGovLimit());
            }
            newUnitenergyList.add(unitenergy);
        }

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


    /**
     * 判断是否有历史数据
     */
    private void hasOld(ScUser u, TReportUnitenergy unitenergy, long reportId) {
        TReportUnitenergy old = new TReportUnitenergy();
        old.setReportId(reportId);
        old.setDelFlag("1");
        if(unitenergy.getQuotaId()!=null){
            old.setQuotaId(unitenergy.getQuotaId());
        }else{
            old.setQuotaName(unitenergy.getQuotaName());
        }
        TReportUnitenergy o = tReportUnitenergyService.getOne(Wrappers.query(old));
        if (o != null) { //有历史数据为修改
            unitenergy.setId(o.getId());
        } else {
            //unitenergy.setDeptId(u.getId());
            EnterpriseInfo info = enterpriseInfoService.getInfoByCode(u.getEnterpriseCode());
            unitenergy.setDeptId(info != null && info.getRegionCode()!=null ? Integer.parseInt(info.getRegionCode()) : u.getDeptId());
            unitenergy.setDelFlag("1");
        }
    }

    /**
     * 进行异常波动分析
     */
    private R getEcAbnormalVolatility(TReport report, ScUser u, List<TReportUnitenergy> unitenergyList) {
        //获取上年的报表信息
        String frontYear = (report.getYear() - 1) + "";
        String enterpriseCode = StringUtils.isNotEmpty(report.getEnterpriseCode()) ? report.getEnterpriseCode() : u.getEnterpriseCode();
        TReport frontReport = tReportService.getInfoByType(enterpriseCode, frontYear, "3");
        if (frontReport != null) {
            //获取上一年能耗指标信息
            TReportUnitenergy front = new TReportUnitenergy();
            front.setReportId(frontReport.getId());
            front.setDelFlag("1");
            List<TReportUnitenergy> frontUnitenergyList = tReportUnitenergyService.list(Wrappers.query(front));
            if (frontUnitenergyList.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("表3");*/
                    //进行异常波动分析
                    DecimalFormat df = new DecimalFormat(".00"); //保留两位小数
                    Map<String, Object> map = new HashMap();
                    map.put("dataTable", "表3");

                    //本年能耗指标信息
                    for (TReportUnitenergy unitenergy : unitenergyList) {
                        boolean addState = true; //新增标志默认为，true，是新增项
                        //上年能耗指标信息
                        for (TReportUnitenergy frontUnitenergy : frontUnitenergyList) {
                            //if (unitenergy.getQuotaName().equals(frontUnitenergy.getQuotaName())) {
                            if (unitenergy.getQuotaId() == frontUnitenergy.getQuotaId() || unitenergy.getQuotaId().equals(frontUnitenergy.getQuotaId())
                                    || unitenergy.getQuotaName().equals(frontUnitenergy.getQuotaName())) {
                                addState = false;  //该条指标信息，不是新增项

                                VolatilityTmpController.VolatilityTmp volatilityTmp = new VolatilityTmpController.VolatilityTmp(
                                        ecAbnormalVolatilityInfoService,
                                        u, flage, para, volatility, df, map,
                                        null,
                                        "表3",
                                        (double)(unitenergy.getChildVal()!=null?unitenergy.getChildVal():0),
                                        (double)(frontUnitenergy.getChildVal()!=null?frontUnitenergy.getChildVal():0),
                                        //(unitenergy.getChildVal() / frontUnitenergy.getChildVal() - 1) * 100,
                                        unitenergy.getQuotaName() + "（子项值），超出波动范围。若确定数值，请填写变化情况说明！",
                                        unitenergy.getQuotaName() + "（子项值）",
                                        unitenergy.getChildUnit()).invoke();
                                if (volatilityTmp.is()) { //超出波动范围，且未填写波动说明，返回错误信息
                                    return R.failed(map);
                                }
                                flage = volatilityTmp.isFlage(); //更新超期标志

                                VolatilityTmpController.VolatilityTmp volatilityTmp2 = new VolatilityTmpController.VolatilityTmp(
                                        ecAbnormalVolatilityInfoService,
                                        u, flage, para, volatility, df, map,
                                        null,
                                        "表3",
                                        (double)(unitenergy.getParentVal()!=null?unitenergy.getParentVal():0),
                                        (double)(frontUnitenergy.getParentVal()!=null?frontUnitenergy.getParentVal():0),
                                        //(unitenergy.getParentVal() / frontUnitenergy.getParentVal() - 1) * 100,
                                        unitenergy.getQuotaName() + "（母项值），超出波动范围。若确定数值，请填写变化情况说明！",
                                        unitenergy.getQuotaName() + "（母项值）",
                                        unitenergy.getParentUnit()).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("表3");
                        ecAbnormalVolatilityInfo.setDataContent(unitenergy.getQuotaName());
                        ecAbnormalVolatilityInfo.setAddState("T");
                        EcAbnormalVolatilityInfo addVolatilityInfo = ecAbnormalVolatilityInfoService.getOne(Wrappers.query(ecAbnormalVolatilityInfo));
                        if (addState) {
                            if (addVolatilityInfo == null) {
                                map.put("msg", unitenergy.getQuotaName() + "，属于新增能耗指标，请填写新增情况说明！");
                                map.put("dataContent", unitenergy.getQuotaName());
                                map.put("unitVal", unitenergy.getQuotaUnit());
                                map.put("addState", "T");
                                return R.failed(map);
                            }
                        } else {
                            if (addVolatilityInfo != null) {
                                //没有新增，却有新增记录，需要删除
                                deleteVolatilityInfo(u, addVolatilityInfo);
                            }
                        }

                    }

                    //表3没有数据超出异常范围，判断是否记录了其他异常波动信息，若无主表信息需要删除
                    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) {

        //其他报表的异常波动详情表信息
        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-3能耗指标表
     */
    @PostMapping("/submit")
    @SysLog("提交报表1-3能耗指标表")
    @ApiOperation(value = "提交报表1-3能耗指标表", notes = "提交报表1-3能耗指标表")
    @ApiImplicitParam(name = "TReport", value = "能源报表信息", required = true, dataType = "String")
    public R save(@RequestBody TReport tReport) {
        if (tReport.getYear() == null || "".equals(tReport.getYear())) {
            return R.failed("提交报表1-3能耗指标表失败，年度不能为空");
        }
        ScUser u = SecurityUtils.getUser();
        //获取报表信息id
        //long reportId = tReportService.getTReportIdByType(u.getEnterpriseCode(), tReport.getYear()+"", "3", u);
        String enterpriseCode = StringUtils.isEmpty(tReport.getEnterpriseCode()) ? u.getEnterpriseCode() : tReport.getEnterpriseCode();
        TReport oldReport = tReportService.getInfoByType(enterpriseCode, tReport.getYear() + "", "3");
        if (oldReport == null) {
            return R.failed("请先保存报表1-3 单位产品综合能耗指标情况表，再上报！");
        }

        //获取能耗指标表信息
        List<TReportUnitenergy> unitenergyList = tReportUnitenergyService.getUnitenergyByReportId(oldReport.getId());
        if (unitenergyList.size() <= 0) {
            return R.failed("请先保存报表1-3 单位产品综合能耗指标情况表，再上报！");
        }

        tReport.setId(oldReport.getId());
        tReport.setUpdateTime(new Date());
        tReport.setUserid(u.getId());
        tReport.setReportStatus("3");
        tReport.setAuditStatus("1");
        tReport.setAuditStatus2("1");
        tReport.setAuditStatus3("1");
        return R.ok(tReportService.updateById(tReport));
    }

    /**
     * 修改报表1-3能耗指标表信息
     */
    @PutMapping
    @SysLog("修改报表1-3能耗指标表信息")
    @ApiOperation(value = "修改报表1-3能耗指标表信息", notes = "修改报表1-3能耗指标表信息")
    @ApiImplicitParam(name = "TReportUnitenergy", value = "报表1-3能耗指标表", required = true, dataType = "json", paramType = "path")
    public R updateById(@RequestBody TReportUnitenergy tReportUnitenergy) {
        ScUser u = SecurityUtils.getUser();
        tReportUnitenergy.setUserid(u.getId());
        tReportUnitenergy.setUpdateTime(new Date());
        return R.ok(tReportUnitenergyService.updateById(tReportUnitenergy));
    }

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

    /**
     * 企业端预览报表1-3能耗指标表
     */
    @GetMapping("/preview")
    @SysLog("企业端预览报表1-3能耗指标表")
    @ApiOperation(value = "企业端预览报表1-3能耗指标表", notes = "企业端预览报表1-3能耗指标表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "year", value = "年份", required = false, dataType = "json", paramType = "path"),
            @ApiImplicitParam(name = "enterpriseCode", value = "企业编码", required = false, dataType = "json", paramType = "path")
    })
    public R getByReportId(String year, String enterpriseCode) {
        if (year == null || "".equals(year)) {
            return R.failed("预览报表1-3能耗指标表失败，年度不能为空");
        }
        if(StringUtils.isEmpty(enterpriseCode)){
            enterpriseCode = SecurityUtils.getUser().getEnterpriseCode();
        }
        //企业端 flag为false
        return previewReport(year, enterpriseCode, false);
    }

    /**
     * 政府端预览报表1-3能耗指标表
     */
    @GetMapping("/previewGov")
    @SysLog("政府端预览报表1-3能耗指标表")
    @ApiOperation(value = "政府端预览报表1-3能耗指标表", notes = "政府端预览报表1-3能耗指标表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "year", value = "年份", required = false, dataType = "json", paramType = "path"),
            @ApiImplicitParam(name = "enterpriseCode", value = "企业编码", required = false, dataType = "json", paramType = "path")
    })
    public R getByReportIdGov(String year, String enterpriseCode) {
        if (year == null || "".equals(year)) {
            return R.failed("预览报表1-3能耗指标表失败，年度不能为空");
        }
        if (enterpriseCode == null || "".equals(enterpriseCode)) {
            return R.failed("预览报表1-3能耗指标表失败，企业社会信用编码不能为空");
        }
        //政府端 flag为true
        return previewReport(year, enterpriseCode, true);
    }

    /**
     * 预览报表1-3能耗指标表
     */
    private R previewReport(String year, String enterpriseCode, boolean flag) {

        //获取能源报表信息
        //TReport report = tReportService.getById(reportId);
        TReport report = tReportService.getInfoByType(enterpriseCode, year, "3");
        //查询上年报表id
        String prevYear = (Integer.parseInt(year) - 1) + "";
        TReport prevReport = tReportService.getInfoByType(enterpriseCode, prevYear, "3");

        //获取企业信息
        //TReportEnterprise enterprise = tReportEnterpriseService.getEnterpriseInfo(report.getEnterpriseCode(), report.getYear() + "");
        TReportEnterprise enterprise = tReportEnterpriseService.getEnterpriseInfo(enterpriseCode, year);

        //获取能耗指标表信息
        //List<TReportUnitenergy> unitenergyList = tReportUnitenergyService.getUnitenergyByReportId(report.getId());
        //获取上年能耗指标表信息
        //List<TReportUnitenergy> prevUnitenergyList = tReportUnitenergyService.getUnitenergyByReportId(prevReport.getId());
        //根据本年、上年报表id获取 能耗指标表列表信息
        //List<TReportUnitenergy> unitenergyList = tReportUnitenergyService.getByIdAndPrevId(report.getId(), prevReport.getId());
        long id1 = report != null ? report.getId() : 0;
        long id2 = prevReport != null ? prevReport.getId() : 0;
        List<TReportUnitenergy> unitenergyList = tReportUnitenergyService.getByIdAndPrevId(id1, id2);

        Map<String, Object> map = new HashMap();
        map.put("enterprise", enterprise);
        map.put("report", report);
        map.put("unitenergy", unitenergyList);

        if (flag) { //政府端，要追加异常波动分析
            R<List<EcAbnormalVolatilityInfo>> volatilityInfo = volatilityInfoController.listByReport(year, enterpriseCode, "表3");
            List<EcAbnormalVolatilityInfo> volatility = new ArrayList<>();
            if (volatilityInfo != null) {
                if (volatilityInfo.getCode() == 0 && volatilityInfo.getData().size() > 0) {
                    volatility.addAll(volatilityInfo.getData());
                }
            }
            map.put("volatility", volatility);
            //精确性分析
            List<EpcEnergyAccuracyAnalysisInfo> analysisInfos = epcEnergyAccuracyAnalysisInfoService.getAnalysisInfoList(year, enterpriseCode, "表3");
            map.put("analysis", analysisInfos);
        }

        return R.ok(map);
    }


    /**
     * 审核报表1-3能耗指标表
     */
    @PostMapping("/auditor")
    @SysLog("审核报表1-3能耗指标表")
    @ApiOperation(value = "审核报表1-3能耗指标表", notes = "审核报表1-3能耗指标表")
    @ApiImplicitParam(name = "auditorDto", value = "报表审核对象", required = true, dataType = "json", paramType = "path")
    public R updateByAuditor(@RequestBody AuditorDto auditorDto) {
        ScUser u = SecurityUtils.getUser();
        if (auditorDto.getId() == null) {
            return R.failed("报表id为空，审核报表1-3能耗指标表失败！");
        }
        TReport tReport = new TReport();
        tReport.setId(auditorDto.getId());
        tReport.setUpdateTime(new Date());
        tReport.setUserid(u.getId());
        tReport.setAuditStatus(auditorDto.getAuditStatus());
        tReport.setAuditRemark(auditorDto.getAuditRemark());
        boolean b = tReportService.updateById(tReport);
        return b ? R.ok("2".equals(auditorDto.getAuditStatus()) ? "已审核" : "已退回") : R.failed("审核失败");
    }

}
