package com.nantian.cloud.jljc.controller;

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.cloud.jljc.vo.TableHeadVo;
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 org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

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


/**
 * 报表1-4进度节能量目标完成情况表
 *
 * @date 2020-09-16
 */
@CrossOrigin
@RestController
@AllArgsConstructor
@RequestMapping("/tReportRateprogress")
@Api(value = "tReportRateprogress", tags = "报表1-4进度节能量目标完成情况表")
public class TReportRateprogressController {
    final private TReportService tReportService;
    final private TReportRateprogressService tReportRateprogressService;
    final private EnterpriseInfoService enterpriseInfoService;
    final private TReportParaService tReportParaService;
    private final EcAbnormalVolatilityService ecAbnormalVolatilityService;
    private final EcAbnormalVolatilityInfoService ecAbnormalVolatilityInfoService;
    private final EcAbnormalVolatilityInfoController volatilityInfoController;
    private final EpcEnergyAccuracyAnalysisService epcEnergyAccuracyAnalysisService;
    private final EpcEnergyAccuracyAnalysisInfoService epcEnergyAccuracyAnalysisInfoService;

    /**
     * 分页查询
     *
     * @param page                分页对象
     * @param tReportRateprogress 报表1-4进度节能量目标完成情况表
     * @return
     */
    @SysLog("查询报表1-4进度节能量目标完成情况表")
    @ApiOperation(value = "查询报表1-4进度节能量目标完成情况表", notes = "条件查询报表1-4进度节能量目标完成情况表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "tReportRateprogress", value = "报表1-4进度节能量目标完成情况表", required = false, dataType = "json", paramType = "path"),
            @ApiImplicitParam(name = "Page", value = "分页对象", required = false, dataType = "json", paramType = "path")
    })
    @GetMapping("/page")
    public R getcheckGaugesPage(Page page, TReportRateprogress tReportRateprogress) {
        tReportRateprogress.setDelFlag("1"); //查询未删除数据
        //return R.ok(tReportEnergyProjectService.getPageScope(page,tReportEnergyProject));
        return R.ok(tReportRateprogressService.page(page, Wrappers.query(tReportRateprogress)));
    }

    /**
     * 通过年份查询报表1-4进度节能量目标完成情况表
     */
    @GetMapping("/getByYear")
    @SysLog("通过年份查询报表1-4进度节能量目标完成情况表")
    @ApiOperation(value = "通过年份查询报表1-4进度节能量目标完成情况表", notes = "通过年份查询报表1-4进度节能量目标完成情况表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "year", value = "年份", required = true, dataType = "string", paramType = "path"),
            @ApiImplicitParam(name = "enterpriseCode", value = "企业社会信用编码", required = true, dataType = "string", 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("查询失败，企业信用编码不能为空");
        }
        Map<String,Object> map = getRateprogress(year, enterpriseCode);
        return R.ok(map);
    }

    //获取表4信息
    public Map<String,Object> getRateprogress(String year, String enterpriseCode) {
        Map<String,Object> map = new HashMap<>();
        boolean unitEnergyFlag = false;
        boolean energyFlag = false;
        TReportRateprogress rateprogress = new TReportRateprogress();
        //获取能源报表信息
        TReport report = tReportService.getInfoByType(enterpriseCode, year, "4");
        if(report!=null){
            TReportRateprogress tReportRateprogress = new TReportRateprogress();
            tReportRateprogress.setReportId(report.getId());
            tReportRateprogress.setDelFlag("1");
            //获取进度节能量目标完成情况表
            rateprogress = tReportRateprogressService.getOne(Wrappers.query(tReportRateprogress));
        }
        if(rateprogress == null){
            rateprogress = new TReportRateprogress();
        }
        TReport q = new TReport();
        q.setEnterpriseCode(enterpriseCode);
        q.setYear(Integer.parseInt(year)-1);
        q.setDelFlag("1");
        List<TReport> list1 = tReportService.list(Wrappers.query(q).in("report_status", "2","3").in("type", "1","2"));
        if(list1!=null && list1.size()>=2){ //企业上年度表1、表2 数据已填写
            energyFlag = true;
            if(rateprogress.getEnergyProgress()==null || rateprogress.getEnergyProgress()==0d){
                Double energyProgress = tReportRateprogressService.getEnergyProgress(enterpriseCode,year,Integer.parseInt(year)-1);
                if(energyProgress!=0d){ //设置产值综合能耗 实际完成进度节能量
                    rateprogress.setEnergyProgress(energyProgress);
                }
            }
        }
        List<TReport> list2 = tReportService.list(Wrappers.query(q).in("report_status", "2","3").in("type", "3"));
        if(list2!=null && list2.size()>=1){ //企业上年度表3 数据已填写
            unitEnergyFlag = true;
            if(rateprogress.getUnitEnergyProgress()==null || rateprogress.getUnitEnergyProgress()==0d){
                Double unitEnergyProgress = tReportRateprogressService.getUnitEnergyProgress(enterpriseCode,year,Integer.parseInt(year)-1);
                if(unitEnergyProgress!=0d){ //设置单位产品综合能耗 实际完成进度节能量
                    rateprogress.setUnitEnergyProgress(unitEnergyProgress);
                }
            }
        }
        map.put("rateprogress",rateprogress);
        map.put("energyFlag",energyFlag);
        map.put("unitEnergyFlag",unitEnergyFlag);
        return map;
    }

    /**
     * 获取报表1-4字段名集合
     */
    @GetMapping("/entityList")
    @SysLog("查询报表1-4进度节能量目标完成情况表")
    @ApiOperation(value = "查询报表1-4进度节能量目标完成情况表", notes = "条件查询报表1-4进度节能量目标完成情况表")
    public R entityList() {
        List eList = new ArrayList();
        /*eList.add("id");
        eList.add("reportId");*/
        eList.add("remarks");
        eList.add("target");
        eList.add("unitEnergyProgress");
        eList.add("energyProgress");
        eList.add("unitEnergyCompletion");
        eList.add("energyCompletion");
        eList.add("unitEnergyProgressEqual");
        eList.add("energyProgressEqual");
        eList.add("unitEnergyCompletionEqual");
        eList.add("energyCompletionEqual");
       /* eList.add("userid");
        eList.add("updateTime");
        eList.add("delFlag");
        eList.add("deptId");*/
        eList.add("f1");
        eList.add("f2");
        eList.add("f3");
        eList.add("d1");
        eList.add("d2");
        eList.add("d3");
        eList.add("t1");
        eList.add("t1");
        eList.add("t1");
        return R.ok(eList);
    }


    /**
     * 获取报表1-4动态表头
     */
    @GetMapping("/tableHead")
    @SysLog("获取报表1-4动态表头")
    @ApiOperation(value = "获取报表1-4动态表头", notes = "获取报表1-4动态表头")
    @ApiImplicitParam(name = "year", value = "年份", required = true, dataType = "string", paramType = "path")
    public R tableHead(String year) {
        int tempYear = Integer.parseInt(year); //year=2020
        int i = tempYear % 5 == 0 ? 5 : tempYear % 5; //tempYear%5结果0，表示为当前五年计划的最后一年, i=5

        List<TableHeadVo> voList = new ArrayList<TableHeadVo>();
        voList.add(TableHeadVo.builder().title("项目").key("name").width("300").align("center").build());
        voList.add(TableHeadVo.builder().title("计量单位").key("unit").width("100").align("center").build());
        voList.add(TableHeadVo.builder().title("代码").key("code").width("70").align("center").build());
        voList.add(TableHeadVo.builder().title((tempYear - i + 1) + "年").key("one").width("120").align("center").build());
        voList.add(TableHeadVo.builder().title((tempYear - i + 1) + "至" + (tempYear - i + 2) + "年").key("two").width("120").align("center").build());
        voList.add(TableHeadVo.builder().title((tempYear - i + 1) + "至" + (tempYear - i + 3) + "年").key("three").width("120").align("center").build());
        voList.add(TableHeadVo.builder().title((tempYear - i + 1) + "至" + (tempYear - i + 4) + "年").key("four").width("120").align("center").build());
        voList.add(TableHeadVo.builder().title((tempYear - i + 1) + "至" + (tempYear - i + 5) + "年").key("five").width("120").align("center").build());

        return R.ok(voList);
    }

    /**
     * 信息
     *
     * @param tReportRateprogressId
     * @return R
     */
    @SysLog("通过ID查询报表1-4进度节能量目标完成情况表")
    @ApiOperation(value = "通过ID查询报表1-4进度节能量目标完成情况表", notes = "通过ID查询报表1-4进度节能量目标完成情况表")
    @ApiImplicitParam(name = "tReportRateprogressId", value = "报表1-4进度节能量目标完成情况表id", required = true, paramType = "path", dataType = "int")
    @GetMapping("/{tReportRateprogressId}")
    public R getById(@PathVariable("tReportRateprogressId") Integer tReportRateprogressId) {
        return R.ok(tReportRateprogressService.getById(tReportRateprogressId));
    }


    /**
     * 企业端预览报表1-4进度节能量目标完成情况表
     */
    @GetMapping("/previewRateprogress")
    @SysLog("企业端预览报表1-4进度节能量目标完成情况表")
    @ApiOperation(value = "企业端预览报表1-4进度节能量目标完成情况表", notes = "企业端预览报表1-4进度节能量目标完成情况表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "year", value = "年份", required = false, dataType = "json", paramType = "path"),
            @ApiImplicitParam(name = "enterpriseCode", value = "企业编码", required = false, dataType = "json", paramType = "path")
    })
    public R previewRateprogress(String year, String enterpriseCode) {

        if (year == null || "".equals(year)) {
            return R.failed("预览失败，年度不能为空");
        }
        if (StringUtils.isEmpty(enterpriseCode)) {
            enterpriseCode = SecurityUtils.getUser().getEnterpriseCode();
        }
        //企业端 flag为false
        return previewReport(year, enterpriseCode, false);
    }


    /**
     * 政府端预览报表1-4进度节能量目标完成情况表
     */
    @GetMapping("/previewRateprogressGov")
    @SysLog("政府端预览报表1-4进度节能量目标完成情况表")
    @ApiOperation(value = "政府端预览报表1-4进度节能量目标完成情况表", notes = "政府端预览报表1-4进度节能量目标完成情况表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "year", value = "年份", required = false, dataType = "json", paramType = "path"),
            @ApiImplicitParam(name = "enterpriseCode", value = "企业编码", required = false, dataType = "json", paramType = "path")
    })
    public R previewRateprogressGov(String year, String enterpriseCode) {

        if (year == null || "".equals(year)) {
            return R.failed("预览失败，年度不能为空");
        }
        if (enterpriseCode == null || "".equals(enterpriseCode)) {
            return R.failed("预览失败，企业编码不能为空");
        }
        //政府端 flag为true
        return previewReport(year, enterpriseCode, true);
    }

    /**
     * 预览报表1-4
     */
    private R previewReport(String year, String enterpriseCode, boolean flag) {
        Map<String, Object> map = new HashMap<>();
        //企业信息
        EnterpriseInfo enterpriseInfo = enterpriseInfoService.getInfoByCode(enterpriseCode);
        map.put("enterpriseInfo", enterpriseInfo);
        //获取报表本年的能源报表信息
        TReport tReport = tReportService.getInfoByType(enterpriseCode, year, "4");
        map.put("tReport", tReport);

        //查询本年度 进度节能量目标完成情况表
        TReportRateprogress num = new TReportRateprogress();
        num.setReportId(tReport != null ? tReport.getId() : 0);
        num.setDelFlag("1");
        TReportRateprogress one = tReportRateprogressService.getOne(Wrappers.query(num));
        //取出本年的进度节能量目标完成情况说明
        map.put("remark", (one != null ? one.getRemarks() : ""));

        //判断year是五年计划的第几年
        Integer tempYear = Integer.parseInt(year); //year=2020
        int i = tempYear % 5 == 0 ? 5 : tempYear % 5; //tempYear%5结果0，表示为当前五年计划的最后一年, i=5

        double target = 0, energyProgress = 0, unitEnergyProgress = 0, energyCompletion = 0, unitEnergyCompletion = 0;
        double energyProgressEqu = 0, unitEnergyProgressEqu = 0, energyCompletionEqu = 0, unitEnergyCompletionEqu = 0; //等价值
        DecimalFormat df = new DecimalFormat(".00"); //保留两位小数
        for (int j = i; j >= 1; j--) { //j=i取得是本年数据
            //获取能源报表信息
            String yearStr = (tempYear - j + 1) + ""; //j=5, yearStr=2020-5+1
            TReport report = tReportService.getInfoByType(enterpriseCode, yearStr, "4");
            TReportRateprogress rateprogress2 = new TReportRateprogress();
            if (report != null) {
                TReportRateprogress rateprogress = new TReportRateprogress();
                rateprogress.setReportId(report.getId());
                rateprogress.setDelFlag("1");
                //获取能耗指标表信息
                rateprogress2 = tReportRateprogressService.getOne(Wrappers.query(rateprogress));
                /*if(tempYear.toString().equals(yearStr)){
                    //取出本年的进度节能量目标完成情况说明
                    map.put("remark", rateprogress2.getRemarks());
                }*/
                if (null != rateprogress2) {
                    target += (rateprogress2.getTarget() != null ? rateprogress2.getTarget() : 0);
                    energyProgress += (rateprogress2.getEnergyProgress() != null ? rateprogress2.getEnergyProgress() : 0);
                    unitEnergyProgress += (rateprogress2.getUnitEnergyProgress() != null ? rateprogress2.getUnitEnergyProgress() : 0);
                    energyProgressEqu += (rateprogress2.getEnergyProgressEqual() != null ? rateprogress2.getEnergyProgressEqual() : 0);
                    unitEnergyProgressEqu += (rateprogress2.getUnitEnergyProgressEqual() != null ? rateprogress2.getUnitEnergyProgressEqual() : 0);
                    if (energyProgress != 0 && target != 0) {
                        energyCompletion = (energyProgress / target) * 100;
                    }
                    if (unitEnergyProgress != 0 && target != 0) {
                        unitEnergyCompletion = (unitEnergyProgress / target) * 100;
                    }
                    if (energyProgressEqu != 0 && target != 0) {
                        energyCompletionEqu = (energyProgressEqu / target) * 100;
                    }
                    if (unitEnergyProgressEqu != 0 && target != 0) {
                        unitEnergyCompletionEqu = (unitEnergyProgressEqu / target) * 100;
                    }
                    rateprogress2.setTarget(Double.parseDouble(df.format(target)));
                    rateprogress2.setEnergyProgress(Double.parseDouble(df.format(energyProgress)));
                    rateprogress2.setUnitEnergyProgress(Double.parseDouble(df.format(unitEnergyProgress)));
                    rateprogress2.setEnergyCompletion(Double.parseDouble(df.format(energyCompletion)));
                    rateprogress2.setUnitEnergyCompletion(Double.parseDouble(df.format(unitEnergyCompletion)));
                    rateprogress2.setEnergyProgressEqual(Double.parseDouble(df.format(energyProgressEqu)));
                    rateprogress2.setUnitEnergyProgressEqual(Double.parseDouble(df.format(unitEnergyProgressEqu)));
                    rateprogress2.setEnergyCompletionEqual(Double.parseDouble(df.format(energyCompletionEqu)));
                    rateprogress2.setUnitEnergyCompletionEqual(Double.parseDouble(df.format(unitEnergyCompletionEqu)));
                }
            }
            map.put("num" + (i - j + 1), rateprogress2);
        }

        if (i != 5) { //若year为2018年，则2019、2020报表为空数据
            for (int k = i + 1; k <= 5; k++) {
                map.put("num" + k, null);
            }
        }

        if(flag){ //政府端，要追加异常波动分析、精确性分析
            R<List<EcAbnormalVolatilityInfo>> volatilityInfo = volatilityInfoController.listByReport(year, enterpriseCode, "表4");
            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, "表4");
            map.put("analysis", analysisInfos);
        }

        Integer number = Integer.parseInt(year)%5 == 0?5:Integer.parseInt(year)%5;
        map.put("number", number);

        return R.ok(map);
    }

    /**
     * 保存
     *
     * @param s
     * @return R
     */
    @SysLog("保存报表1-4进度节能量目标完成情况表")
    @ApiOperation(value = "保存报表1-4进度节能量目标完成情况表", notes = "新增报表1-4进度节能量目标完成情况表")
    @ApiImplicitParam(name = "s", value = "报表1-4进度节能量目标完成情况表", required = true, dataType = "json", paramType = "path")
    @PostMapping("/save")
    @Transactional
    public R save(@RequestBody String s) {
        JSONObject json = JSONObject.parseObject(s);
        TReport tReport = JSONObject.parseObject(json.getString("report"), TReport.class);
        TReportRateprogress tReportRateprogress = JSONObject.parseObject(json.getString("rateprogress"), TReportRateprogress.class);
        if (tReport.getYear() == null) {
            return R.failed("报表年度不能为空，请检查！");
        }
        /*if(StringUtils.isBlank(tReport.getEnterpriseCode())){
            return R.failed("报表企业代码不能为空，请检查！");
        }*/

        ScUser u = SecurityUtils.getUser();
        //进行异常波动分析
        //R map = getEcAbnormalVolatility(tReport, tReportRateprogress, u);
        //if (map != null) return map;

        //进行精确性分析
        R map = epcEnergyAccuracyAnalysisService.getEpcEnergyAccuracyAnalysis4(tReport, tReportRateprogress, u);
        if (map != null) return map;

        //保存报表4的数据
        tReportRateprogress.setUserid(u.getId());
        //tReportRateprogress.setDeptId(u.getDeptId());
        String enterpriseCode = StringUtils.isNotEmpty(tReport.getEnterpriseCode()) ? tReport.getEnterpriseCode() : u.getEnterpriseCode();
        EnterpriseInfo info = enterpriseInfoService.getInfoByCode(enterpriseCode);
        tReport.setDeptId(info != null && info.getRegionCode()!=null ? Integer.parseInt(info.getRegionCode()) : u.getDeptId());
        tReportRateprogress.setDelFlag("1");
        tReportRateprogress.setUpdateTime(new Date());
        TReport q = new TReport();
        q.setEnterpriseCode(enterpriseCode);
        q.setYear(tReport.getYear());
        q.setType("4");
        q.setDelFlag("1");
        TReport o = tReportService.getOne(Wrappers.query(q));
        if (o != null) {
            tReport.setId(o.getId());
            //tReportRateprogress.setReportId(o.getId());
        } else {
            tReport.setType("4");
            tReport.setEnterpriseCode(enterpriseCode);
        }
        tReport.setUpdateTime(new Date());
        Integer deptId = info != null && info.getRegionCode()!=null? Integer.parseInt(info.getRegionCode()) : u.getDeptId();
        tReport.setDeptId(deptId);
        if("530000".equals(deptId.toString())){ //企业区域直属省级
            tReport.setProvStatus("1"); //企业所填报表，省级可直接查看、审核
        }
        tReport.setReportStatus("2");
        tReportService.saveOrUpdate(tReport);

        if (o == null) {
            //tReportService.getTReportIdByType(tReport.getEnterpriseCode(),tReport.getYear().toString(),tReport.getType(),u);
            //TReport n = tReportService.getOne(Wrappers.query(tReport));
            //tReportRateprogress.setReportId(tReportService.getTReportIdByType(tReport.getEnterpriseCode(),tReport.getYear().toString(),tReport.getType(),u));
            tReportRateprogress.setReportId(tReport.getId());
        }else{
            tReportRateprogress.setReportId(o.getId());
        }
        TReportRateprogress r = new TReportRateprogress();
        r.setReportId(tReportRateprogress.getReportId());
        TReportRateprogress ro = tReportRateprogressService.getOne(Wrappers.query(r));
        if (ro != null) {
            tReportRateprogress.setId(ro.getId());
        }

        //return R.ok(tReportRateprogressService.saveOrUpdate(tReportRateprogress));
//        boolean update = tReportRateprogressService.saveOrUpdate(tReportRateprogress);
        boolean update=false;
        if(tReportRateprogress.getId()!=null){
            update = tReportRateprogressService.updateById(tReportRateprogress);
        }else{
            update = tReportRateprogressService.save(tReportRateprogress);
        }
        if (update) {
            //报表4信息更新成功，报表信息才更新
            //return R.ok(tReportService.saveOrUpdate(tReport));
            return R.ok();
        } else {
            return R.failed();
        }
    }


    /**
     * 进行异常波动分析
     */
    private R getEcAbnormalVolatility(TReport tReport, TReportRateprogress tReportRateprogress, ScUser u) {
        //获取上年的报表信息
        String frontYear = (tReport.getYear() - 1) + "";
        String enterpriseCode = StringUtils.isNotEmpty(tReport.getEnterpriseCode()) ? tReport.getEnterpriseCode() : u.getEnterpriseCode();
        TReport frontReport = tReportService.getInfoByType(enterpriseCode, frontYear, "4");
        if (frontReport != null) {
            //获取上一年能进度节能量目标完成情况信息
            TReportRateprogress front = new TReportRateprogress();
            front.setReportId(frontReport.getId());
            front.setDelFlag("1");
            TReportRateprogress frontRateprogress = tReportRateprogressService.getOne(Wrappers.query(front));
            if (frontRateprogress != null) { //上年数据存在，进行异常波动分析
                boolean flage = false; //波动标志默认为，false，不波动
                //取出异常波动 预警区间
                TReportPara tReportPara = new TReportPara();
                tReportPara.setType("1");
                List<TReportPara> paras = tReportParaService.list(Wrappers.query(tReportPara));
                for (TReportPara para : paras) {
                    if (para.getUplimt() != null || para.getDownlimt() != null) {
                        //取出本年的异常波动表
                        EcAbnormalVolatility ecAbnormalVolatility = new EcAbnormalVolatility();
                        ecAbnormalVolatility.setYear(tReport.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("表4");*/
                        //进行异常波动分析
                        DecimalFormat df = new DecimalFormat(".00"); //保留两位小数
                        Map<String, Object> map = new HashMap();
                        map.put("dataTable", "表4");

                        VolatilityTmpController.VolatilityTmp volatilityTmp = new VolatilityTmpController.VolatilityTmp(
                                ecAbnormalVolatilityInfoService,
                                u, flage, para, volatility, df, map,
                                null,
                                "表4",
                                (double)(tReportRateprogress.getTarget()!=null?tReportRateprogress.getTarget():0),
                                (double)(frontRateprogress.getTarget()!=null?frontRateprogress.getTarget():0),
                                //(tReportRateprogress.getTarget() / frontRateprogress.getTarget() - 1) * 100,
                                "进度节能量目标，超出波动范围。若确定数值，请填写变化情况说明！",
                                "进度节能量目标",
                                "吨标准煤").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,
                                "表4",
                                (double)(tReportRateprogress.getUnitEnergyProgress()!=null?tReportRateprogress.getUnitEnergyProgress():0),
                                (double)(frontRateprogress.getUnitEnergyProgress()!=null?frontRateprogress.getUnitEnergyProgress():0),
                                //(tReportRateprogress.getUnitEnergyProgress() / frontRateprogress.getUnitEnergyProgress() - 1) * 100,
                                "单位产品综合能耗实际完成进度节能量-当量值，超出波动范围。若确定数值，请填写变化情况说明！",
                                "单位产品综合能耗实际完成进度节能量-当量值",
                                "吨标准煤").invoke();
                        if (volatilityTmp2.is()) { //超出波动范围，且未填写波动说明，返回错误信息
                            return R.failed(map);
                        }
                        flage = volatilityTmp2.isFlage(); //更新超期标志

                        VolatilityTmpController.VolatilityTmp volatilityTmp3 = new VolatilityTmpController.VolatilityTmp(
                                ecAbnormalVolatilityInfoService,
                                u, flage, para, volatility, df, map,
                                null,
                                "表4",
                                (double)(tReportRateprogress.getEnergyProgress()!=null?tReportRateprogress.getEnergyProgress():0),
                                (double)(frontRateprogress.getEnergyProgress()!=null?frontRateprogress.getEnergyProgress():0),
                                //(tReportRateprogress.getEnergyProgress() / frontRateprogress.getEnergyProgress() - 1) * 100,
                                "产值综合能耗实际完成进度节能量-当量值，超出波动范围。若确定数值，请填写变化情况说明！",
                                "产值综合能耗实际完成进度节能量-当量值",
                                "吨标准煤").invoke();
                        if (volatilityTmp3.is()) { //超出波动范围，且未填写波动说明，返回错误信息
                            return R.failed(map);
                        }
                        flage = volatilityTmp3.isFlage(); //更新超期标志

                        VolatilityTmpController.VolatilityTmp volatilityTmp4 = new VolatilityTmpController.VolatilityTmp(
                                ecAbnormalVolatilityInfoService,
                                u, flage, para, volatility, df, map,
                                null,
                                "表4",
                                (double)(tReportRateprogress.getUnitEnergyProgressEqual()!=null?tReportRateprogress.getUnitEnergyProgressEqual():0),
                                (double)(frontRateprogress.getUnitEnergyProgressEqual()!=null?frontRateprogress.getUnitEnergyProgressEqual():0),
                                //(tReportRateprogress.getUnitEnergyProgressEqual() / frontRateprogress.getUnitEnergyProgressEqual() - 1) * 100,
                                "单位产品综合能耗实际完成进度节能量-等价值，超出波动范围。若确定数值，请填写变化情况说明！",
                                "单位产品综合能耗实际完成进度节能量-等价值",
                                "吨标准煤").invoke();
                        if (volatilityTmp4.is()) { //超出波动范围，且未填写波动说明，返回错误信息
                            return R.failed(map);
                        }
                        flage = volatilityTmp4.isFlage(); //更新超期标志

                        VolatilityTmpController.VolatilityTmp volatilityTmp5 = new VolatilityTmpController.VolatilityTmp(
                                ecAbnormalVolatilityInfoService,
                                u, flage, para, volatility, df, map,
                                null,
                                "表4",
                                (double)(tReportRateprogress.getEnergyProgressEqual()!=null?tReportRateprogress.getEnergyProgressEqual():0),
                                (double)(frontRateprogress.getEnergyProgressEqual()!=null?frontRateprogress.getEnergyProgressEqual():0),
                                //(tReportRateprogress.getEnergyProgressEqual() / frontRateprogress.getEnergyProgressEqual() - 1) * 100,
                                "产值综合能耗实际完成进度节能量-等价值，超出波动范围。若确定数值，请填写变化情况说明！",
                                "产值综合能耗实际完成进度节能量-等价值",
                                "吨标准煤").invoke();
                        if (volatilityTmp5.is()) { //超出波动范围，且未填写波动说明，返回错误信息
                            return R.failed(map);
                        }
                        flage = volatilityTmp5.isFlage(); //更新超期标志

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

    /**
     * 上传
     *
     * @param tReport
     * @return R
     */
    @SysLog("保存报表1-4项目表")
    @ApiOperation(value = "保存报表1-4项目表", notes = "新增报表1-4项目表")
    @ApiImplicitParam(name = "TReport", value = "报表1-4项目表", required = true, dataType = "json", paramType = "path")
    @PostMapping("/submit")
    public R submit(@RequestBody TReport tReport) {
        if (tReport.getYear() == null) {
            return R.failed("报表年度不能为空，请检查！");
        }
        ScUser u = SecurityUtils.getUser();
        String enterpriseCode = StringUtils.isEmpty(tReport.getEnterpriseCode()) ? u.getEnterpriseCode() : tReport.getEnterpriseCode();

        TReport q = new TReport();
        q.setEnterpriseCode(enterpriseCode);
        q.setYear(tReport.getYear());
        q.setType("4");
        q.setDelFlag("1");
        TReport o = tReportService.getOne(Wrappers.query(q));
        if (o == null) {
            return R.failed("请先保存报表1-4 进度节能量目标完成情况表，再上报！");
        }

        //获取能源报表信息
        TReportRateprogress rateprogress = new TReportRateprogress();
        rateprogress.setReportId(o.getId());
        rateprogress.setDelFlag("1");
        TReportRateprogress reportRateprogress = tReportRateprogressService.getOne(Wrappers.query(rateprogress));
        if (reportRateprogress == null) {
            return R.failed("请先保存报表1-4 进度节能量目标完成情况表，再上报！");
        }

        tReport.setId(o.getId());
        tReport.setReportStatus("3");
        tReport.setAuditStatus("1");
        tReport.setAuditStatus2("1");
        tReport.setAuditStatus3("1");
        return R.ok(tReportService.updateById(tReport));
    }

    /**
     * 修改
     *
     * @param tReportRateprogress
     * @return R
     */
    @SysLog("修改报表1-4进度节能量目标完成情况表信息")
    @ApiOperation(value = "修改报表1-4进度节能量目标完成情况表信息", notes = "修改报表1-4进度节能量目标完成情况表信息")
    @ApiImplicitParam(name = "tReportRateprogress", value = "报表1-4进度节能量目标完成情况表", required = true, dataType = "json", paramType = "path")
    @PutMapping
    public R updateById(@RequestBody TReportRateprogress tReportRateprogress) {
        ScUser u = SecurityUtils.getUser();
        if (u.getId() != null) {
            tReportRateprogress.setUserid(u.getId());
        }
        tReportRateprogress.setUpdateTime(new Date());
        return R.ok(tReportRateprogressService.updateById(tReportRateprogress));
    }

    /**
     * 删除
     *
     * @param tReportRateprogressId
     * @return R
     */
    @SysLog("删除报表1-4进度节能量目标完成情况表")
    @ApiOperation(value = "删除报表1-4进度节能量目标完成情况表", notes = "删除报表1-4进度节能量目标完成情况表信息")
    @ApiImplicitParam(name = "tReportRateprogressId", value = "报表1-4进度节能量目标完成情况表信息ID", required = true, dataType = "int", paramType = "path")
    @DeleteMapping("/{tReportRateprogressId}")
    public R removeById(@PathVariable("tReportRateprogressId") Long tReportRateprogressId) {
        TReportRateprogress tReportRateprogress = tReportRateprogressService.getById(tReportRateprogressId);
        ScUser u = SecurityUtils.getUser();
        if (u.getId() != null) {
            tReportRateprogress.setUserid(u.getId());
        }
        tReportRateprogress.setDelFlag("4");
        tReportRateprogress.setUpdateTime(new Date());
        return R.ok(tReportRateprogressService.updateById(tReportRateprogress));
    }


}
