package com.nantian.cloud.jljc.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.apache.commons.lang3.StringUtils;
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.annotation.Inner;
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.web.bind.annotation.*;

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


/**
 * 报表1-1企业信息
 *
 * @author stz
 * @date 2020-09-16
 */
@Slf4j
@CrossOrigin
@RestController
@AllArgsConstructor
@RequestMapping("/tReportEnterprise")
@Api(value = "tReportEnterprise", tags = "报表1-1企业信息，四项报表设置信息，报表1信息")
public class TReportEnterpriseController {

    //报表1-1
    final private TReportEnterpriseService tReportEnterpriseService;
    final private TReportFinancialService tReportFinancialService;
    final private TReportProductService tReportProductService;
    //报表信息
    final private TReportService tReportService;
    //报表1-2
    final private TReportEnergysTructureService tReportEnergysTructureService;
    //报表1-2-1
    final private TReportEnergyOutService tReportEnergyOutService;
    //报表1-3
    final private TReportUnitenergyService tReportUnitenergyService;
    //报表1-3-1
    final private TReportUnitenergyCompService tReportUnitenergyCompService;
    //报表1-5
    final private TReportEnergyProjectService tReportEnergyProjectService;
    //产品信息
    final private ProductInfoService productInfoService;
    //能耗指标信息
    final private EnergyIndexService energyIndexService;
    final private EcAbnormalVolatilityInfoController volatilityInfoController;
    private final EpcEnergyAccuracyAnalysisService epcEnergyAccuracyAnalysisService;
    private final EnterpriseInfoService enterpriseInfoService;


    /**
     * 根据年份获取报表设置企业信息（企业端）
     */
    @GetMapping("/getEnterpriseInfo")
    @SysLog("根据年份获取报表设置企业信息（企业端）")
    @ApiOperation(value = "获取报表设置企业信息（企业端）", notes = "获取报表设置企业信息（企业端）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "year", value = "年份", required = true, dataType = "json", paramType = "path"),
            @ApiImplicitParam(name = "enterpriseCode", value = "企业社会信用编码", required = true, dataType = "json", paramType = "path")
    })
    public R getEnterpriseInfo(String year, String enterpriseCode) {
        if (year == null || "".equals(year)) {
            return R.failed("获取报表设置企业信息失败，年度不能为空");
        }
        if (StringUtils.isEmpty(enterpriseCode)) {
            enterpriseCode = SecurityUtils.getUser().getEnterpriseCode();
        }
        TReportEnterprise enterpriseInfo = tReportEnterpriseService.getEnterpriseInfo(enterpriseCode, year);
        if (enterpriseInfo == null) {
            //今年没有进行报表设置，读取往年数据
            for (int i = 1; i <= 5; i++) {
                Integer temp = Integer.parseInt(year) - i;
                TReportEnterprise info = tReportEnterpriseService.getEnterpriseInfo(enterpriseCode, temp.toString());
                if (info != null && info.getEpcType() != null) {
                    info.setId(null);    //获取的往年数据，id需要清空
                    info.setYear(year);  //获取的往年数据，默认给报表锁所设置的年度
                    //设置企业类型
                    EnterpriseInfo infoByCode = enterpriseInfoService.getInfoByCode(enterpriseCode);
                    if (infoByCode != null) {
                        if (infoByCode.getCompanyType() != null) {
                            info.setEpcType(tReportEnterpriseService.getTypeNameByStr(infoByCode.getCompanyType()));
                        }
                    }
                    String linkJson = info.getProcessingLinkJson();
                    if (null != linkJson && linkJson.contains(",")) { //加工装换环节
                        Set<String> setTmp = new HashSet<>(Arrays.asList(linkJson.replaceAll("\\[","").replaceAll("]","").split(","))); //字符去重
                        String linkStr = StringUtils.join(setTmp,",");
                        linkStr = linkStr.startsWith(",") ? linkStr.substring(1) : linkStr; //去除第一逗号字符
                        info.setProcessingLinkJson(linkStr);
                    }
                    return R.ok(info);
                }
            }
            return R.ok(); //前5年都没有数据
        } else {
            //return R.ok(tReportEnterpriseService.getNameByEnterprise(enterpriseInfo));
            /*if (null != enterpriseInfo.getEpcType()) {
                enterpriseInfo.setEpcType(tReportEnterpriseService.getTypeNameByStr(enterpriseInfo.getEpcType()));
            }*/
            if (null != enterpriseInfo.getEpcType()) {
                enterpriseInfo.setEpcType(tReportEnterpriseService.getTypeNameByStr(enterpriseInfo.getEpcType()));
            }
            String linkJson = enterpriseInfo.getProcessingLinkJson();
            if (null != linkJson && linkJson.contains(",")) { //加工装换环节
                Set<String> setTmp = new HashSet<>(Arrays.asList(linkJson.replaceAll("\\[","").replaceAll("]","").split(","))); //字符去重
                String linkStr = StringUtils.join(setTmp,",");
                linkStr = linkStr.startsWith(",") ? linkStr.substring(1) : linkStr; //去除第一逗号字符
                enterpriseInfo.setProcessingLinkJson(linkStr);
            }
            return R.ok(enterpriseInfo);
        }
    }



    /**
     * 不需要身份验证的接口 根据年份获取报表设置企业信息（postman）
     */
    @Inner(value = false) //取消身份验证
    @GetMapping("/getEnterpriseInfo_wu")
    @SysLog("获取报表设置企业信息（企业端 无身份验证）")
    @ApiOperation(value = "获取报表设置企业信息（企业端）", notes = "获取报表设置企业信息（企业端）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "year", value = "年份", required = true, dataType = "json", paramType = "path"),
            @ApiImplicitParam(name = "enterpriseCode", value = "企业社会信用编码", required = true, dataType = "json", paramType = "path")
    })
    public R getEnterpriseInfo_wu(String year, String enterpriseCode) {
        if (year == null || "".equals(year)) {
            return R.failed("获取报表设置企业信息失败，年度不能为空");
        }
        TReportEnterprise enterpriseInfo = tReportEnterpriseService.getEnterpriseInfo(enterpriseCode, year);
        if (enterpriseInfo == null) {
            //今年没有进行报表设置，读取往年数据
            for (int i = 1; i <= 5; i++) {
                Integer temp = Integer.parseInt(year) - i;
                TReportEnterprise info = tReportEnterpriseService.getEnterpriseInfo(enterpriseCode, temp.toString());
                if (info != null && info.getEpcType() != null) {
                    info.setId(null);    //获取的往年数据，id需要清空
                    info.setYear(year);  //获取的往年数据，默认给报表锁所设置的年度
                    //设置企业类型
                    EnterpriseInfo infoByCode = enterpriseInfoService.getInfoByCode(enterpriseCode);
                    if (infoByCode != null) {
                        if (infoByCode.getCompanyType() != null) {
                            info.setEpcType(tReportEnterpriseService.getTypeNameByStr(infoByCode.getCompanyType()));
                        }
                    }
                    return R.ok(info);
                }
            }
            return R.ok(); //前5年都没有数据
        } else {
            if (null != enterpriseInfo.getEpcType()) {
                enterpriseInfo.setEpcType(tReportEnterpriseService.getTypeNameByStr(enterpriseInfo.getEpcType()));
            }
            return R.ok(enterpriseInfo);
        }
    }

    /**
     * 根据年份获取报表设置主要产品（企业端）
     */
    @GetMapping("/getProductInfo")
    @SysLog("根据年份获取报表设置主要产品（企业端）")
    @ApiOperation(value = "获取报表设置主要产品（企业端）", notes = "获取报表设置主要产品（企业端）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "year", value = "年份", required = true, dataType = "json", paramType = "path"),
            @ApiImplicitParam(name = "enterpriseCode", value = "企业社会信用编码", required = true, dataType = "json", paramType = "path")
    })
    public R getProductInfo(String year, String enterpriseCode) {
        if (year == null || "".equals(year)) {
            return R.failed("获取报表设置主要产品失败，年度不能为空");
        }
        if (StringUtils.isEmpty(enterpriseCode)) {
            enterpriseCode = SecurityUtils.getUser().getEnterpriseCode();
        }
        String productInfoStr = tReportEnterpriseService.getProductInfo(enterpriseCode, year);
        /*if (productInfoStr == null) {
            return R.ok();
        } else { //json转换
            List<JsonProductInfoVo> productInfoList = (List<JsonProductInfoVo>) JSONArray.parseArray(productInfoStr, JsonProductInfoVo.class);
            return R.ok(productInfoList);
        }*/
        if (productInfoStr != null && !"".equals(productInfoStr)) {
            return R.ok(productInfoStr);
        } else {
            //今年没有进行报表设置，读取往年数据
            for (int i = 1; i <= 5; i++) {
                Integer temp = Integer.parseInt(year) - i;
                String productInfo = tReportEnterpriseService.getProductInfo(enterpriseCode, temp.toString());
                if (productInfo != null && !"".equals(productInfo)) {
                    return R.ok(productInfo);
                }
            }
            return R.ok(); //前5年都没有数据
        }
    }

    /**
     * 根据年份获取报表设置用能种类（企业端）
     */
    @GetMapping("/getEnergyInfo")
    @SysLog("根据年份获取报表设置用能种类（企业端）")
    @ApiOperation(value = "获取报表设置用能种类（企业端）", notes = "获取报表设置用能种类（企业端）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "year", value = "年份", required = true, dataType = "json", paramType = "path"),
            @ApiImplicitParam(name = "enterpriseCode", value = "企业社会信用编码", required = true, dataType = "json", paramType = "path")
    })
    public R getEnergyInfo(String year, String enterpriseCode) {
        if (year == null || "".equals(year)) {
            return R.failed("获取报表设置用能种类失败，年度不能为空");
        }
        if (StringUtils.isEmpty(enterpriseCode)) {
            enterpriseCode = SecurityUtils.getUser().getEnterpriseCode();
        }
        String energyInfoStr = tReportEnterpriseService.getEnergyInfo(enterpriseCode, year);
        /*if (energyInfoStr == null) {
            return R.ok();
        } else { //json转换
            List<JsonEnergyinfoVo> energyInfoList = (List<JsonEnergyinfoVo>) JSONArray.parseArray(energyInfoStr, JsonEnergyinfoVo.class);
            return R.ok(energyInfoList);
        }*/

        if (energyInfoStr != null && !"".equals(energyInfoStr)) {
            return R.ok(energyInfoStr);
        } else {
            //今年没有进行报表设置，读取往年数据
            for (int i = 1; i <= 5; i++) {
                Integer temp = Integer.parseInt(year) - i;
                String energyInfo = tReportEnterpriseService.getEnergyInfo(enterpriseCode, temp.toString());
                if (energyInfo != null && !"".equals(energyInfo)) {
                    return R.ok(energyInfo);
                }
            }
            return R.ok(); //前5年都没有数据
        }
    }

    /**
     * 根据年份获取报表设置指标设定（企业端）
     */
    @GetMapping("/getEnergyIndex")
    @SysLog("根据年份获取报表设置指标设定（企业端）")
    @ApiOperation(value = "获取报表设置指标设定（企业端）", notes = "获取报表设置指标设定（企业端）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "year", value = "年份", required = true, dataType = "json", paramType = "path"),
            @ApiImplicitParam(name = "enterpriseCode", value = "企业社会信用编码", required = true, dataType = "json", paramType = "path")
    })
    public R getEnergyIndex(String year, String enterpriseCode) {
        if (year == null || "".equals(year)) {
            return R.failed("获取报表设置指标设定失败，年度不能为空");
        }
        if (StringUtils.isEmpty(enterpriseCode)) {
            enterpriseCode = SecurityUtils.getUser().getEnterpriseCode();
        }
        String energyIndexStr = tReportEnterpriseService.getEnergyIndex(enterpriseCode, year);
        /*if (energyIndexStr == null) {
            return R.ok();
        } else { //json转换
            List<JsonEnergyindexVo> energyIndexList = (List<JsonEnergyindexVo>) JSONArray.parseArray(energyIndexStr, JsonEnergyindexVo.class);
            return R.ok(energyIndexList);
        }*/
        if (energyIndexStr != null && !"".equals(energyIndexStr)) {
            return R.ok(energyIndexStr);
        } else {
            //今年没有进行报表设置，读取往年数据
            for (int i = 1; i <= 5; i++) {
                Integer temp = Integer.parseInt(year) - i;
                String energyIndex = tReportEnterpriseService.getEnergyIndex(enterpriseCode, temp.toString());
                if (energyIndex != null && !"".equals(energyIndex)) {
                    return R.ok(energyIndex);
                }
            }
            return R.ok(); //前5年都没有数据
        }
    }

    /**
     * 更新报表设置企业信息（企业端）
     */
    @PostMapping("/upEnterpriseInfo")
    @SysLog("更新报表设置企业信息（企业端）")
    @ApiOperation(value = "更新报表设置企业信息（企业端）", notes = "更新报表设置企业信息（企业端）")
    @ApiImplicitParam(name = "TReportEnterprise", value = "企业信息", required = true, dataType = "json")
    public R upEnterpriseInfo(@RequestBody TReportEnterprise tReportEnterprise) {
        log.error("更新报表设置企业信息:{}", tReportEnterprise);

        ScUser u = SecurityUtils.getUser();
        String enterpriseCode = tReportEnterprise.getEnterpriseCode();
        if (StringUtils.isEmpty(enterpriseCode)) {
            enterpriseCode = u.getEnterpriseCode();
        }

        String year = tReportEnterprise.getYear();
        if (year == null || "".equals(year)) {
            return R.failed("更新报表设置企业信息失败，年度不能为空");
        }
        /*if (enterpriseCode == null || "".equals(enterpriseCode)) {
            return R.failed("更新报表设置企业信息失败，企业信用代码不能为空");
        }*/

        EnterpriseInfo info = enterpriseInfoService.getInfoByCode(enterpriseCode);
        if(info==null){ //企业基本信息表为空，需将报表设置企业信息同步到基本信息表
            EnterpriseInfo newInfo = new EnterpriseInfo();
            newInfo.setEnterpriseCode(enterpriseCode);
            newInfo.setCmpName(tReportEnterprise.getEnterpriseName());
            newInfo.setAddress(tReportEnterprise.getAddress());
            newInfo.setZipCode(tReportEnterprise.getZipCode());
            newInfo.setCorporationName(tReportEnterprise.getCorporationName());
            newInfo.setRegisterPrincipal(tReportEnterprise.getRegisterPrincipal());
            newInfo.setRegionCode(tReportEnterprise.getArea());
            newInfo.setIndustryCode(tReportEnterprise.getTrade());
            newInfo.setFieldCode(tReportEnterprise.getField());
            newInfo.setJgzh(tReportEnterprise.getProcessingLink());
            newInfo.setCenter(tReportEnterprise.getCenter());
            newInfo.setPhone(tReportEnterprise.getTelephone());
            newInfo.setFax(tReportEnterprise.getFax());
            newInfo.setEmail(tReportEnterprise.getEmail());
            newInfo.setUrl(tReportEnterprise.getWebsite());
            newInfo.setDelFlag("1");
            newInfo.setUpdateTime(new Date());
            newInfo.setUserid(u.getId());
            newInfo.setDeptId(Integer.parseInt(tReportEnterprise.getArea()));
            enterpriseInfoService.save(newInfo);
        }else{
            //更新企业基本信息表 的行业编码、地区码
            info.setUserid(u.getId());
            info.setUpdateTime(new Date());
            info.setRegionCode(tReportEnterprise.getArea());
            info.setIndustryCode(tReportEnterprise.getTrade());
            info.setDeptId(Integer.parseInt(tReportEnterprise.getArea()));
            info.setCmpName(tReportEnterprise.getEnterpriseName());
            enterpriseInfoService.updateById(info);
        }

        TReportEnterprise oldEnterpriseInfo = tReportEnterpriseService.getEnterpriseInfo(enterpriseCode, year);
        if (oldEnterpriseInfo != null) { //有数据，修改
            tReportEnterprise.setId(oldEnterpriseInfo.getId());
        } else { //无数据，新增
            //tReportEnterprise.setDeptId(u.getDeptId());
            //tReportEnterprise.setDeptId(info != null ? Integer.parseInt(info.getRegionCode()) : u.getDeptId());
            tReportEnterprise.setDeptId(tReportEnterprise.getArea()!=null?Integer.parseInt(tReportEnterprise.getArea()):u.getDeptId());
            tReportEnterprise.setDelFlag("1");
        }

        //无加工转换 或 没有设置加工转换环节
        if ("false".equals(tReportEnterprise.getProcessingLinkJson()) || "2".equals(tReportEnterprise.getProcessingLink())) {
            tReportEnterprise.setProcessingLinkJson("[]");
        }

        //获取报表信息id
        long reportId = tReportService.getTReportIdByType(enterpriseCode, year, "1", u);
        tReportEnterprise.setReportId(reportId);
        tReportEnterprise.setUserid(u.getId());
        tReportEnterprise.setUpdateTime(new Date());

        //设置企业类型
        EnterpriseInfo infoByCode = enterpriseInfoService.getInfoByCode(enterpriseCode);
        if (infoByCode != null) {
            if (infoByCode.getCompanyType() != null) {
                tReportEnterprise.setEpcType(infoByCode.getCompanyType());
            }
        }

        return R.ok(tReportEnterpriseService.saveOrUpdateByUniqueKey(tReportEnterprise));
    }

    /**
     * 更新报表设置主要产品（企业端）
     */
    @PostMapping("/upProductInfo")
    @SysLog("更新报表设置主要产品（企业端）")
    @ApiOperation(value = "更新报表设置主要产品（企业端）（参数说明是键值对说明）", notes = "更新报表设置主要产品（企业端）（参数说明是键值对说明）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "enterpriseCode", value = "企业社会信用编码", required = true, dataType = "String"),
            @ApiImplicitParam(name = "year", value = "年度", required = true, dataType = "String"),
            @ApiImplicitParam(name = "data", value = "主要产品信息", required = true, dataType = "String")
    })
    public R upProductInfo(@RequestBody String s) {

        log.error("更新报表设置主要产品：" + s);

        JSONObject json = JSONObject.parseObject(s);
        String enterpriseCode = json.getString("enterpriseCode");
        ScUser u = SecurityUtils.getUser();
        if (StringUtils.isEmpty(enterpriseCode)) {
            enterpriseCode = u.getEnterpriseCode();
        }
        String year = json.getString("year");
        String productInfo = json.getString("data");
        if (year == null || "".equals(year)) {
            return R.failed("更新报表设置主要产品失败，年度不能为空");
        }
        if (enterpriseCode == null || "".equals(enterpriseCode)) {
            return R.failed("更新报表设置主要产品失败，企业信用代码不能为空");
        }

        //判断是否可以设置主要产品信息
        //获取报表信息id
        long reportId = tReportService.getTReportIdByType(enterpriseCode, year, "1", u);
        List<TReportProduct> products = tReportProductService.getProductsByReportId(reportId);
        if (products.size() != 0) { //报表1产品信息已填
            return R.failed("报表1-1 基本信息表的产品信息已填写，不能设置主要产品信息！若需设置，需将涉及的相关信息删除！");
        }


        //TReportEnterprise oldEnterpriseInfo = tReportEnterpriseService.getEnterpriseInfo(enterpriseCode, year);
        //if (oldEnterpriseInfo != null) { //有数据，修改
        //    oldEnterpriseInfo.setProductinfos(productInfo); //productinfos主要产品
        //} else { //无数据，新增
        TReportEnterprise oldEnterpriseInfo = new TReportEnterprise();
        oldEnterpriseInfo.setYear(year);
        oldEnterpriseInfo.setEnterpriseCode(enterpriseCode);
        oldEnterpriseInfo.setProductinfos(productInfo); //productinfos主要产品
        oldEnterpriseInfo.setDelFlag("1");
        //oldEnterpriseInfo.setDeptId(u.getDeptId());
        EnterpriseInfo info = enterpriseInfoService.getInfoByCode(enterpriseCode);
        oldEnterpriseInfo.setDeptId(info != null && info.getRegionCode()!=null ? Integer.parseInt(info.getRegionCode()) : u.getDeptId());
        //}
        oldEnterpriseInfo.setUserid(u.getId());
        oldEnterpriseInfo.setUpdateTime(new Date());
        oldEnterpriseInfo.setReportId(reportId);

        return R.ok(tReportEnterpriseService.saveOrUpdateByUniqueKey(oldEnterpriseInfo));
    }

    /**
     * 更新报表设置用能种类（企业端）
     */
    @PostMapping("/upEnergyInfo")
    @SysLog("更新报表设置用能种类（企业端）")
    @ApiOperation(value = "更新报表设置用能种类（企业端）（参数说明是键值对说明）", notes = "更新报表设置用能种类（企业端）（参数说明是键值对说明）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "enterpriseCode", value = "企业社会信用编码", required = true, dataType = "String"),
            @ApiImplicitParam(name = "year", value = "年度", required = true, dataType = "String"),
            @ApiImplicitParam(name = "data", value = "用能种类信息", required = true, dataType = "String")
    })
    public R upEnergyInfo(@RequestBody String s) {
        log.error("更新报表设置用能种类：" + s);

        JSONObject json = JSONObject.parseObject(s);
        String year = json.getString("year");
        String energyInfo = json.getString("data");
        String enterpriseCode = json.getString("enterpriseCode");
        ScUser u = SecurityUtils.getUser();
        if (StringUtils.isEmpty(enterpriseCode)) {
            enterpriseCode = u.getEnterpriseCode();
        }
        if (year == null || "".equals(year)) {
            return R.failed("更新报表设置用能种类失败，年度不能为空");
        }
        if (enterpriseCode == null || "".equals(enterpriseCode)) {
            return R.failed("更新报表设置用能种类失败，企业信用代码不能为空");
        }

        //判断是否可以设置用能种类信息
        //获取报表信息id
        long reportId = tReportService.getTReportIdByType(enterpriseCode, year, "1", u);
        TReport report2 = tReportService.getInfoByType(enterpriseCode, year, "2");
        long reportId2 = report2!=null ? report2.getId() : 0;
        TReportEnergysTructure tructure = new TReportEnergysTructure();
        tructure.setDelFlag("1");
        tructure.setReportId(reportId2);
        List<TReportEnergysTructure> tructureList = tReportEnergysTructureService.list(Wrappers.query(tructure));
        if (tructureList.size() != 0) { //报表1-2已填
            return R.failed("报表1-2 能源消费结构表已填写，不能设置用能种类信息！若需设置，需将涉及的相关信息删除！");
        }
        TReport report2_1 = tReportService.getInfoByType(enterpriseCode, year, "2-1");
        long reportId2_1 = report2_1!=null ? report2_1.getId() : 0;
        TReportEnergyOut out = new TReportEnergyOut();
        out.setDelFlag("1");
        out.setReportId(reportId2_1);
        List<TReportEnergyOut> outList = tReportEnergyOutService.list(Wrappers.query(out));
        if (outList.size() != 0) { //报表1-2附表已填
            return R.failed("报表1-2附表 能源产出结构表已填写，不能设置用能种类信息！若需设置，需将涉及的相关信息删除！");
        }
        TReport report5 = tReportService.getInfoByType(enterpriseCode, year, "5");
        long reportId5 = report5!=null ? report5.getId() : 0;
        TReportEnergyProject project = new TReportEnergyProject();
        project.setDelFlag("1");
        project.setReportId(reportId5);
        List<TReportEnergyProject> projectList = tReportEnergyProjectService.list(Wrappers.query(project));
        if (projectList.size() != 0) { //报表1-5已填
            return R.failed("报表1-5 节能改造项目情况表已填写，不能设置用能种类信息！若需设置，需将涉及的相关信息删除！");
        }


        //TReportEnterprise oldEnterpriseInfo = tReportEnterpriseService.getEnterpriseInfo(enterpriseCode, year);
        //if (oldEnterpriseInfo != null) { //有数据，修改
        //    oldEnterpriseInfo.setEnergyTypes(energyInfo); //energyTypes用能种类
        //} else { //无数据，新增
        TReportEnterprise oldEnterpriseInfo = new TReportEnterprise();
        oldEnterpriseInfo.setYear(year);
        oldEnterpriseInfo.setEnterpriseCode(enterpriseCode);
        oldEnterpriseInfo.setEnergyTypes(energyInfo);  //energyTypes用能种类
        //oldEnterpriseInfo.setDeptId(u.getDeptId());
        EnterpriseInfo info = enterpriseInfoService.getInfoByCode(u.getEnterpriseCode());
        oldEnterpriseInfo.setDeptId(info != null && info.getRegionCode()!=null ? Integer.parseInt(info.getRegionCode()) : u.getDeptId());
        oldEnterpriseInfo.setDelFlag("1");
        //}
        oldEnterpriseInfo.setReportId(reportId);
        oldEnterpriseInfo.setUserid(u.getId());
        oldEnterpriseInfo.setUpdateTime(new Date());

        return R.ok(tReportEnterpriseService.saveOrUpdateByUniqueKey(oldEnterpriseInfo));
    }

    /**
     * 更新报表设置指标设定（企业端）
     */
    @PostMapping("/upEnergyIndex")
    @SysLog("更新报表设置指标设定（企业端）")
    @ApiOperation(value = "更新报表设置指标设定（企业端）（参数说明是键值对说明）", notes = "更新报表设置指标设定（企业端）（参数说明是键值对说明）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "enterpriseCode", value = "企业社会信用编码", required = true, dataType = "String"),
            @ApiImplicitParam(name = "year", value = "年度", required = true, dataType = "String"),
            @ApiImplicitParam(name = "data", value = "指标设定信息", required = true, dataType = "String")
    })
    public R upEnergyIndex(@RequestBody String s) {
        log.error("更新报表设置用能种类：" + s);

        JSONObject json = JSONObject.parseObject(s);
        String year = json.getString("year");
        String energyIndex = json.getString("data");
        String enterpriseCode = json.getString("enterpriseCode");
        ScUser u = SecurityUtils.getUser();
        if (StringUtils.isEmpty(enterpriseCode)) {
            enterpriseCode = u.getEnterpriseCode();
        }
        if (year == null || "".equals(year)) {
            return R.failed("更新报表设置指标设定失败，年度不能为空");
        }
        if (enterpriseCode == null || "".equals(enterpriseCode)) {
            return R.failed("更新报表设置指标设定失败，企业信用代码不能为空");
        }

        //判断是否可以设置指标设定信息
        //获取报表信息id
        long reportId = tReportService.getTReportIdByType(enterpriseCode, year, "1", u);
        TReport report3 = tReportService.getInfoByType(enterpriseCode, year, "3");
        long reportId3 = report3!=null ? report3.getId() : 0;
        TReportUnitenergy unitenergy = new TReportUnitenergy();
        unitenergy.setDelFlag("1");
        unitenergy.setReportId(reportId3);
        List<TReportUnitenergy> unitenergyList = tReportUnitenergyService.list(Wrappers.query(unitenergy));
        if (unitenergyList.size() != 0) { //报表1-3已填
            return R.failed("表1-3 单位产品综合能耗指标情况表已填写，不能设置指标设定信息！若需设置，需将涉及的相关信息删除！");
        }
        TReport report3_1 = tReportService.getInfoByType(enterpriseCode, year, "3-1");
        long reportId3_1 = report3_1!=null ? report3_1.getId() : 0;
        TReportUnitenergyComp comp = new TReportUnitenergyComp();
        comp.setDelFlag("1");
        comp.setReportId(reportId3_1);
        List<TReportUnitenergyComp> compList = tReportUnitenergyCompService.list(Wrappers.query(comp));
        if (compList.size() != 0) { //报表1-3附表已填
            return R.failed("表1-3附表 可比单位产品综合能耗指标情况表已填写，不能设置指标设定信息！若需设置，需将涉及的相关信息删除！");
        }


        //TReportEnterprise oldEnterpriseInfo = tReportEnterpriseService.getEnterpriseInfo(enterpriseCode, year);
        //if (oldEnterpriseInfo != null) { //有数据，修改
        //    oldEnterpriseInfo.setIndicators(energyIndex); //indicators指标信息
        //} else { //无数据，新增
        TReportEnterprise oldEnterpriseInfo = new TReportEnterprise();
        oldEnterpriseInfo.setYear(year);
        oldEnterpriseInfo.setEnterpriseCode(enterpriseCode);
        oldEnterpriseInfo.setIndicators(energyIndex);  //indicators指标信息
        //oldEnterpriseInfo.setDeptId(u.getDeptId());
        EnterpriseInfo info = enterpriseInfoService.getInfoByCode(u.getEnterpriseCode());
        oldEnterpriseInfo.setDeptId(info != null && info.getRegionCode()!=null ? Integer.parseInt(info.getRegionCode()) : u.getDeptId());
        oldEnterpriseInfo.setDelFlag("1");
        //}
        oldEnterpriseInfo.setReportId(reportId);
        oldEnterpriseInfo.setUserid(u.getId());
        oldEnterpriseInfo.setUpdateTime(new Date());

        return R.ok(tReportEnterpriseService.saveOrUpdateByUniqueKey(oldEnterpriseInfo));
    }


    /**
     * 企业端预览报表1-1基本信息
     */
    @GetMapping("/preview")
    @SysLog("企业端预览报表1-1基本信息")
    //@ApiOperation(value = "根据报表信息id获取报表1-1信息", notes = "根据报表信息id获取报表1-1信息")
    @ApiOperation(value = "企业端预览报表1-1基本信息", notes = "企业端预览报表1-1基本信息")
    @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-1基本信息失败，年度不能为空");
        }
        if (StringUtils.isEmpty(enterpriseCode)) {
            enterpriseCode = SecurityUtils.getUser().getEnterpriseCode();
        }
        //企业端 flag为false
        return previewReport(year, enterpriseCode, false);

    }

    /**
     * 政府端预览报表1-1基本信息
     */
    @GetMapping("/previewGov")
    @SysLog("政府端预览报表1-1基本信息")
    @ApiOperation(value = "政府端预览报表1-1基本信息", notes = "政府端预览报表1-1基本信息")
    @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-1基本信息失败，年度不能为空");
        }
        if (enterpriseCode == null || "".equals(enterpriseCode)) {
            return R.failed("预览报表1-1基本信息失败，企业社会信用编码不能为空");
        }
        //政府端 flag为true
        return previewReport(year, enterpriseCode, true);
    }

    /**
     * 预览报表1-1信息
     */
    private R previewReport(String year, String enterpriseCode, boolean flag) {
        Map<String, Object> map = new HashMap();

        //获取能源报表信息
        //TReport report = tReportService.getById(reportId);
        TReport report = tReportService.getInfoByType(enterpriseCode, year, "1");
        if (report == null) {
            return R.ok();
        }

        //获取企业信息
        //TReportEnterprise enterprise = tReportEnterpriseService.getEnterpriseByReportId(report.getId());
        TReportEnterprise enterprise = tReportEnterpriseService.getEnterpriseInfo(enterpriseCode, year);
        if (enterprise != null) {
            enterprise = tReportEnterpriseService.getNameByEnterprise(enterprise);
        }

        //获取主要产品信息
        //DecimalFormat df = new DecimalFormat(".00"); //保留两位小数
        List<TReportProduct> products = tReportProductService.getProductsByReportId(report.getId());
        /*List<TReportProduct> newProducts = new ArrayList<>();
        if (products.size() > 0) {
            for (TReportProduct product : products) {
                if (product.getEnergyConsumption() != 0 && product.getEnergyConsumption() != null) {
                    //设置单位产品能耗值
                    float unitEnergyConsumption = product.getUnitEnergyConsumption() / product.getYieldNum();
                    if (unitEnergyConsumption < 1) {
                        product.setUnitEnergyConsumption(Float.parseFloat(df.format(unitEnergyConsumption * 1000)));
                        product.setUnitEnergyConsumptionUnit("千克标准煤/" + product.getYieldUnit());
                    } else {
                        product.setUnitEnergyConsumption(Float.parseFloat(df.format(unitEnergyConsumption)));
                        product.setUnitEnergyConsumptionUnit("吨标准煤/" + product.getYieldUnit());
                    }
                }
                newProducts.add(product);
            }
        }*/

        //获取当前年度财务信息
        TReportFinancial financial = tReportFinancialService.getFinancialsByReportId(report.getId());

        //获取上年度财务信息
        Integer prevYear = Integer.parseInt(year) - 1;
        TReport prevReport = tReportService.getInfoByType(report.getEnterpriseCode(), prevYear + "", "1");
        if (prevReport != null) {
            TReportFinancial prevFinancial = tReportFinancialService.getFinancialsByReportId(prevReport.getId());
            if (prevFinancial!=null) {
                DecimalFormat df = new DecimalFormat(".00"); //保留两位小数
                if (financial!=null){
                    //财务信息的能源消费成本（变化率），若没值，就进行计算
                    if (financial.getEnergyConsumptionCostRate() == null) {
                        double energyConsumptionCostRate = 0;
                        if (financial.getEnergyConsumptionCost() != null && financial.getEnergyConsumptionCost() != 0
                                && prevFinancial.getEnergyConsumptionCost() != null && prevFinancial.getEnergyConsumptionCost() != 0) {
                            energyConsumptionCostRate = (financial.getEnergyConsumptionCost() / prevFinancial.getEnergyConsumptionCost() - 1) * 100;
                        }
                        financial.setEnergyConsumptionCostRate(Double.parseDouble(df.format(energyConsumptionCostRate)));
                    }
                    //财务信息的能源管理师（变化率），若没值，就进行计算
                    if (financial.getIcsemNumRate() == null) {
                        float icsemNumRate = 0;
                        if (financial.getIcsemNum() != null && financial.getIcsemNum() != 0
                                && prevFinancial.getIcsemNum() != null && prevFinancial.getIcsemNum() != 0) {
                            icsemNumRate = (financial.getIcsemNum() / prevFinancial.getIcsemNum() - 1) * 100;
                        }
                        financial.setIcsemNumRate(Double.parseDouble(df.format(icsemNumRate)));
                    }
                }
            }
             map.put("prevFinancial", prevFinancial);
        }else{
            map.put("prevFinancial", null);
        }

        map.put("enterprise", enterprise);
        map.put("products", products);
        map.put("financial", financial);
        map.put("report", report);

        if (flag) { //政府端，要追加异常波动分析，精确性分析
            R<List<EcAbnormalVolatilityInfo>> volatilityInfo = volatilityInfoController.listByReport(year, enterpriseCode, "表1");
            List<EcAbnormalVolatilityInfo> volatility = new ArrayList<>();
            if (volatilityInfo != null) {
                if (volatilityInfo.getCode() == 0 && volatilityInfo.getData().size() > 0) {
                    volatility.addAll(volatilityInfo.getData());
                }
            }
            map.put("volatility", volatility);
            EpcEnergyAccuracyAnalysis q = new EpcEnergyAccuracyAnalysis();
            q.setDelFlag("1");
            q.setYear(year);
            q.setEpc(enterpriseCode);
            EpcEnergyAccuracyAnalysis analysis = epcEnergyAccuracyAnalysisService.getOne(Wrappers.query(q));
            map.put("analysis", analysis);
        }

        return R.ok(map);
    }


    /**
     * 预览报表1-1企业信息
     */
    @GetMapping("/previewEnterprise")
    @SysLog("预览报表1-1企业信息")
    @ApiOperation(value = "预览报表1-1企业信息", notes = "预览报表1-1企业信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "year", value = "年份", required = false, dataType = "json", paramType = "path"),
            @ApiImplicitParam(name = "enterpriseCode", value = "企业编码", required = false, dataType = "json", paramType = "path")
    })
    public R previewEnterprise(String year, String enterpriseCode) {

        /*//获取能源报表信息
        TReport report = tReportService.getInfoByType(enterpriseCode, year, "1");
        //获取企业信息
        TReportEnterprise enterprise = tReportEnterpriseService.getEnterpriseByReportId(report.getId());
        */
        if (year == null || "".equals(year)) {
            return R.failed("查询失败，年度不能为空");
        }
        if (enterpriseCode == null || "".equals(enterpriseCode)) {
            return R.failed("查询失败，企业编码不能为空");
        }
        ScUser u = SecurityUtils.getUser();
        TReportEnterprise enterprise = tReportEnterpriseService.getEnterpriseInfo(enterpriseCode, year);
        if (enterprise == null) {
            return R.ok();
        }
        return R.ok(tReportEnterpriseService.getNameByEnterprise(enterprise));
    }


    /**
     * 获取耗能指标信息、产品信息涉及的行业
     */
    @GetMapping("/getTrade")
    @SysLog("获取耗能指标信息、产品信息涉及的行业")
    @ApiOperation(value = "获取耗能指标信息、产品信息涉及的行业", notes = "获取耗能指标信息、产品信息涉及的行业")
    public R getTrade() {
        List<String> productTrades = productInfoService.getTrade();
        List<String> energyIndexTrades = energyIndexService.getTrade();
        productTrades.remove(null);
        energyIndexTrades.remove(null);

        Map<String, Object> map = new HashMap();
        map.put("productTrade", productTrades);
        map.put("energyIndexTrade", energyIndexTrades);

        return R.ok(map);
    }


    /**
     * 提交报表1-1基本情况表
     */
    @PostMapping("/submit")
    @SysLog("提交报表1-1基本情况表")
    @ApiOperation(value = "提交报表1-1基本情况表", notes = "提交报表1-1基本情况表")
    @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-1基本情况表失败，年度不能为空");
        }
        ScUser u = SecurityUtils.getUser();
        //获取报表信息id
        //long reportId = tReportService.getTReportIdByType(u.getEnterpriseCode(), tReport.getYear() + "", "1", u);
        String enterpriseCode = StringUtils.isEmpty(tReport.getEnterpriseCode()) ? u.getEnterpriseCode() : tReport.getEnterpriseCode();
        TReport oldReport = tReportService.getInfoByType(enterpriseCode, tReport.getYear() + "", "1");
        if (oldReport == null) {
            return R.failed("请先保存报表1-1 基本情况表，再上报！");
        }

        //获取企业基本信息
        TReportEnterprise enterprise = tReportEnterpriseService.getEnterpriseByReportId(oldReport.getId());
        if (enterprise == null) {
            return R.failed("报表设置企业信息未完成！");
        }

        //获取财务信息
        TReportFinancial financial = tReportFinancialService.getFinancialsByReportId(oldReport.getId());
        if (financial == null) {
            return R.failed("请先保存财务信息，再上报！");
        }

        //获取主要产品信息
        List<TReportProduct> products = tReportProductService.getProductsByReportId(oldReport.getId());
        if (products.size() <= 0) {
            return R.failed("请先保存主要产品信息，再上报！");
        }

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

    /**
     * 审核报表1-1基本情况表
     */
    @PostMapping("/auditor")
    @SysLog("审核报表1-1基本情况表")
    @ApiOperation(value = "审核报表1-1基本情况表", notes = "审核报表1-1基本情况表")
    @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-1基本情况表失败！");
        }
        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("审核失败");
    }

}
