package com.ho.business.service.impl;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.ho.business.entity.*;
import com.ho.business.mapper.IncomeMeasurementMapper;
import com.ho.business.mapper.IncomeTotalMapper;
import com.ho.business.service.IncomeMeasurementService;
import com.ho.business.service.InverterService;
import com.ho.business.service.StationService;
import com.ho.common.tools.constant.CommonConstant;
import com.ho.common.tools.constant.EnvConstant;
import com.ho.common.tools.entity.SimpleUser;
import com.ho.td.api.entity.inverter.InverterTimingGenerate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionException;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class IncomeMeasurementServiceImpl implements IncomeMeasurementService {

    @Autowired
    private IncomeMeasurementMapper incomeMeasurementMapper;

    @Autowired
    IncomeTotalMapper incomeTotalMapper;

    @Autowired
    InverterService inverterService;


    //查询时间间隔
    @Value("${inverter.timeInterval}")
    Integer timeInterval;

    @Autowired
    private StationService stationService;

    @Value("${spring.profiles.active}")
    private String env;

    /**
     * 根据电站id查询费率模板下拉列表数据
     *
     * @param stationId
     * @return
     */
    @Override
    public List<RateTemplate> getRateTemplateList(Integer stationId) {
        return incomeMeasurementMapper.getRateTemplateList(stationId);
    }

    /**
     * 根据模板id查询费率下拉列表数据
     *
     * @param templateId
     * @return
     */
    @Override
    public List<IncomeRateMapping> getRateList(long templateId) {
        return incomeMeasurementMapper.getRateList(templateId);
    }

    /**
     * 根据模板id和费率id查询费率详情
     *
     * @param rateId
     * @param templateId
     * @return
     */
    @Override
    public IncomeRateMapping getRateDetails(int rateId, long templateId) {
        return incomeMeasurementMapper.getRateDetails(rateId, templateId);
    }

    /**
     * 企业用电费率查询
     *
     * @param incomeRate
     * @return
     */
    @Override
    public List<IncomeRate> selectIncomeRates(IncomeRate incomeRate) {


        // 判断是否有用户自填数据,如果有则查询用户填写的数据,如果没有则展示实时数据
        List<IncomeRate> incomeRates = incomeMeasurementMapper.selectIncomeRates(incomeRate);
        if (incomeRates != null && incomeRates.size() > 0) {
            return incomeRates;
        }
        String date = incomeRate.getDataDate();
        DateTime startTime = DateUtil.parse(date, CommonConstant.DATE_YM);
        startTime = DateUtil.beginOfMonth(startTime);
        DateTime endTime = DateUtil.endOfMonth(startTime);
        incomeRate.setStartTime(DateUtil.format(startTime, CommonConstant.DATE));
        incomeRate.setEndTime(DateUtil.format(endTime, CommonConstant.DATE));
        incomeRates = incomeMeasurementMapper.selectRealRates(incomeRate);
        return incomeRates;
    }

    /**
     * 新增或修改费率
     *
     * @param incomeRates
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public String insertOrUpdateIncomeRates(List<IncomeRate> incomeRates, SimpleUser simpleUser) {
        int line = 0;
        try {
            if (incomeRates.size() > 0) {

                String dataDate = incomeRates.get(0).getDataDate();
                long oldTemplateId = incomeRates.get(0).getOldTemplateId();
                long rateId = incomeRates.get(0).getOldRateId();
                Integer stationId = incomeRates.get(0).getStationId();
                // 查询累计收益数据是否存在.用于判断是修改还是新增
                IncomeTotal incomeTotalData = this.selectTotalFee(dataDate, stationId);
                if (incomeTotalData != null) { // 进入if为存在数据,执行修改操作
                    IncomeTotal incomeTotal = null;
                    for (IncomeRate incomeRate : incomeRates) {
                        long addTemplateId = incomeRate.getTemplateId();
                        long addRateId = incomeRate.getRateId();

                        // 这里进行一次判断,如果出现创建相同费率的数据则会报错,这里的判断为了防止报错,直接会到页面
                        int ischeck = incomeMeasurementMapper.ischeck(addTemplateId, dataDate, addRateId, incomeRate.getStationId(), incomeRate.getId());
                        if (ischeck > 0) {
                            throw new RuntimeException("费率选择不可相同!");
                        }
                        int checkTemplate = incomeMeasurementMapper.checkTemplate(addTemplateId, dataDate, incomeRate.getStationId(), incomeRate.getId());
                        if (checkTemplate > 0) {
                            throw new RuntimeException("模板选择不可不同!");
                        }

                        if (incomeRate.getActionType() == 0) {
                            line = incomeMeasurementMapper.batchIncomeRates(incomeRates, addTemplateId, dataDate);
                        } else {
                            // 修改企业用电数据
                            line = incomeMeasurementMapper.modifyIncomeRate(incomeRate, addTemplateId, dataDate);
                        }

                        incomeTotal = new IncomeTotal();
                        String q = incomeRate.getQ();
                        String price = incomeRate.getPrice();
                        String dis = incomeRate.getDiscount();
                        String discount = dis;
                        if (dis.indexOf("%") > 0) {
                            discount = dis.substring(0, dis.indexOf("%"));
                        }
                        BigDecimal total = new BigDecimal(q).multiply(new BigDecimal(price)).multiply(new BigDecimal(discount));
                        // 查询除了修改的费率以外的企业用电收益数据累加值,用于用户页面上修改了企业用电后更新企业用电收益字段内容
                        String totalData = null;
                        if (incomeRate.getActionType() == 0) {
                            totalData = incomeMeasurementMapper.queryRateTotal(addTemplateId, dataDate, incomeRate.getRateId());
                        } else {
                            totalData = incomeMeasurementMapper.queryRateTotal(oldTemplateId, dataDate, incomeRate.getRateId());
                        }
                        if (totalData == null) {
                            totalData = "0";
                        }
                        // total 用户页面上修改电量后重新计算该费率的企业用电收益 + 查询出来的除了该费率以外的企业用电收益 保存为累计收益里 企业用电收益字段
                        incomeTotal.setEleTotalFee(total.add(new BigDecimal(totalData)));
                        incomeTotal.setDataDate(incomeRate.getDataDate());
                        incomeTotal.setStationId(incomeRate.getStationId());
                        incomeTotal.setTemplateId(addTemplateId);
                        incomeTotal.setRateId(incomeRate.getRateId());
                        // 查询一次上网用电收益数据,如果不存在给0用于计算和保存数据库,如果存在的话需要放入参数,参与入库时计算
                        String incomeFee = incomeMeasurementMapper.getIncomeFee(incomeRate);
                        if (incomeFee != null) {
                            incomeTotal.setIncomeFee(new BigDecimal(incomeFee));
                        } else {
                            incomeTotal.setIncomeFee(new BigDecimal("0"));
                        }
                        line = incomeMeasurementMapper.modifyEleTotalFee(incomeTotal);
                    }
                } else { // 进入else则是进行新增操作
                    IncomeTotal incomeTotal = null;
                    for (IncomeRate incomeRate : incomeRates) {
                        // 这里进行一次判断,如果出现创建相同费率的数据则会报错,这里的判断为了防止报错,直接会到页面
                        int ischeck = incomeMeasurementMapper.ischeck(oldTemplateId, dataDate, rateId, incomeRate.getStationId(), incomeRate.getId());
                        if (ischeck > 0) {
                            // transactionManager.rollback(transactionStatus);
                            // return "费率选择不可相同!";
                            throw new RuntimeException("费率选择不可相同!");
                        }
                        int checkTemplate = incomeMeasurementMapper.checkTemplate(oldTemplateId, dataDate, incomeRate.getStationId(), incomeRate.getId());
                        if (checkTemplate > 0) {
                            // transactionManager.rollback(transactionStatus);
                            throw new RuntimeException("模板选择不可不同!");
                            // return "模板选择不可不同!";
                        }
                        incomeTotal = new IncomeTotal();
                        String q = incomeRate.getQ();
                        String price = incomeRate.getPrice();
                        String dis = incomeRate.getDiscount();
                        String discount = dis;
                        if (dis.indexOf("%") > 0) {
                            discount = dis.substring(0, dis.indexOf("%"));
                        }
                        // q:用电量  price:单价 discount:折扣 相乘得到当前数据的累计收益
                        BigDecimal total = new BigDecimal(q).multiply(new BigDecimal(price)).multiply(new BigDecimal(discount));
                        incomeTotal.setEleTotalFee(total);
                        incomeTotal.setIncomeFee(new BigDecimal("0"));
                        incomeTotal.setTotalFee(total);
                        incomeTotal.setTemplateId(incomeRate.getTemplateId());
                        incomeTotal.setRateId(incomeRate.getRateId());
                        incomeTotal.setStationId(incomeRate.getStationId());
                        incomeTotal.setDataDate(incomeRate.getDataDate());
                        incomeTotal.setGroupId(simpleUser.getGroupId());
                        incomeTotal.setRateName(incomeRate.getRateName());
                        line = incomeMeasurementMapper.insertTotalFee(incomeTotal);
                    }
                    // 这里执行批量入库,实际修改了页面后只会进行单条数据入库
                    line = incomeMeasurementMapper.batchIncomeRates(incomeRates, oldTemplateId, dataDate);
                }
            } else {
                return "操作失败!";
            }
        } catch (TransactionException e) {
            // transactionManager.rollback(transactionStatus);
            throw new RuntimeException("操作失败");
        }
        // transactionManager.commit(transactionStatus);
        return "操作成功";
    }

    /**
     * 查询上网用电数据
     *
     * @param surfQRate
     * @return
     */
    @Override
    public List<IncomeQRate> selectQRate(IncomeQRate surfQRate) {
        return incomeMeasurementMapper.selectQRate(surfQRate);
    }

    @Override
    public int insertSurfQRate(IncomeQRate surfQRate, SimpleUser simpleUser) {
        int line = 0;
        String dataDate = surfQRate.getDataDate();
        long templateId = surfQRate.getTemplateId();
        Integer stationId = surfQRate.getStationId();
        // 查询累计收益数据是否存在.用于判断是修改还是新增
        IncomeTotal incomeTotalData = this.selectTotalFee(dataDate, stationId);
        if (incomeTotalData != null) {
            IncomeTotal incomeTotal = null;
            incomeTotal = new IncomeTotal();
            String q = surfQRate.getSurfQ();
            String price = surfQRate.getPrice();
            // 上网用电不存在折扣,且一个电站只会有一条数据直接计算即可
            BigDecimal total = new BigDecimal(q).multiply(new BigDecimal(price));
            incomeTotal.setIncomeFee(total.add(incomeTotalData.getIncomeFee()));
            incomeTotal.setDataDate(surfQRate.getDataDate());
            incomeTotal.setStationId(surfQRate.getStationId());
            incomeTotal.setSurfTemplateId(templateId);
            incomeTotal.setRateId(surfQRate.getRateId());
            String eleTotalFee = incomeMeasurementMapper.getEleTotalFee(surfQRate);
            if (eleTotalFee != null) {
                incomeTotal.setEleTotalFee(new BigDecimal(eleTotalFee));
            } else {
                incomeTotal.setEleTotalFee(new BigDecimal("0"));
            }
            line = incomeMeasurementMapper.modifyEleTotalFee(incomeTotal);
        } else {
            IncomeTotal incomeTotal = null;
            incomeTotal = new IncomeTotal();
            String q = surfQRate.getSurfQ();
            String price = surfQRate.getPrice();
            BigDecimal total = new BigDecimal(q).multiply(new BigDecimal(price));
            incomeTotal.setIncomeFee(total);
            incomeTotal.setEleTotalFee(new BigDecimal("0"));
            incomeTotal.setTotalFee(total);
            incomeTotal.setSurfTemplateId(templateId);
            incomeTotal.setRateId(surfQRate.getRateId());
            incomeTotal.setStationId(surfQRate.getStationId());
            incomeTotal.setDataDate(surfQRate.getDataDate());
            incomeTotal.setGroupId(simpleUser.getGroupId());
            line = incomeMeasurementMapper.insertTotalFee(incomeTotal);
        }
        return incomeMeasurementMapper.insertSurfQRate(surfQRate);
    }

    /**
     * 修改上网用电数据
     *
     * @param surfQRate
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int modifySurfRate(IncomeQRate surfQRate, String operatorId) {
        int line = 0;
        IncomeTotal incomeTotal = new IncomeTotal();
        String q = surfQRate.getSurfQ();
        String price = surfQRate.getPrice();
        BigDecimal total = new BigDecimal(q).multiply(new BigDecimal(price));
        incomeTotal.setIncomeFee(total);
        incomeTotal.setDataDate(surfQRate.getDataDate());
        incomeTotal.setStationId(surfQRate.getStationId());
        incomeTotal.setSurfTemplateId(surfQRate.getTemplateId());
        incomeTotal.setRateId(surfQRate.getRateId());
        // 查询企业用电数据,进行累计总收益用
        String eleTotalFee = incomeMeasurementMapper.getEleTotalFee(surfQRate);
        if (eleTotalFee != null) {
            incomeTotal.setEleTotalFee(new BigDecimal(eleTotalFee));
        } else {
            incomeTotal.setEleTotalFee(new BigDecimal(0));
        }
        line = incomeMeasurementMapper.modifyEleTotalFee(incomeTotal);
        line = incomeMeasurementMapper.modifySurfRate(surfQRate);
        return line;
    }

    /**
     * 确认按钮
     *
     * @param incomeTotal
     * @return
     */
    @Override
    public int confirm(IncomeTotal incomeTotal) {
        //确认type = 2
        int typeTwo = incomeMeasurementMapper.confirmTwo(incomeTotal);
        //确认type = 1
        int typeOne = incomeMeasurementMapper.confirmOne(incomeTotal);

        return typeOne + typeTwo;
    }

    /**
     * 查询费率号(下拉框数据)
     *
     * @return
     */
    @Override
    public List<IncomeRateMapping> selectRates() {
        return incomeMeasurementMapper.selectRates();
    }

    /**
     * 查询累计收益
     *
     * @param incomeTotal
     * @return
     */
    @Override
    public IncomeTotal selectTotal(IncomeTotal incomeTotal) {
        IncomeTotal incomeTotal1 = incomeMeasurementMapper.selectTotal(incomeTotal);
        if (incomeTotal1 != null) {
            //手动添加添加上网用电数据需要再次查询实时的企业用电数据
            if (CommonConstant.ZERO == (incomeTotal1.getEleTotalFee().intValue())) {
                String date = incomeTotal.getDataDate();
                DateTime startTime = DateUtil.parse(date, CommonConstant.DATE_YM);
                startTime = DateUtil.beginOfMonth(startTime);
                DateTime endTime = DateUtil.endOfMonth(startTime);
                incomeTotal.setStartTime(DateUtil.format(startTime, CommonConstant.DATE));
                incomeTotal.setEndTime(DateUtil.format(endTime, CommonConstant.DATE));
                IncomeTotal eleIncomeTotal = incomeMeasurementMapper.selectTotalReal(incomeTotal);
                if (eleIncomeTotal != null) {
                    if (eleIncomeTotal.getEleTotalFee() != null) {
                        incomeTotal1.setEleTotalFee(eleIncomeTotal.getEleTotalFee());
                        incomeTotal1.setTotalFee(eleIncomeTotal.getEleTotalFee().add(incomeTotal1.getIncomeFee()));
                    }
                }
            }
            //手动添加企业用电数据需要再次查询实时的上网用电数据
            if (CommonConstant.ZERO == (incomeTotal1.getIncomeFee().intValue())) {
                String date = incomeTotal.getDataDate();
                DateTime startTime = DateUtil.parse(date, CommonConstant.DATE_YM);
                startTime = DateUtil.beginOfMonth(startTime);
                DateTime endTime = DateUtil.endOfMonth(startTime);
                incomeTotal.setStartTime(DateUtil.format(startTime, CommonConstant.DATE));
                incomeTotal.setEndTime(DateUtil.format(endTime, CommonConstant.DATE));
                IncomeTotal IncomeFeeIncomeTotal = incomeMeasurementMapper.selectTotalReal(incomeTotal);
                if (IncomeFeeIncomeTotal != null) {
                    if (IncomeFeeIncomeTotal.getIncomeFee() != null) {
                        incomeTotal1.setIncomeFee(IncomeFeeIncomeTotal.getIncomeFee());
                        incomeTotal1.setTotalFee(IncomeFeeIncomeTotal.getIncomeFee().add(incomeTotal1.getEleTotalFee()));
                    }
                }
            }
            return incomeTotal1;
        }
        String date = incomeTotal.getDataDate();
        DateTime startTime = DateUtil.parse(date, CommonConstant.DATE_YM);
        startTime = DateUtil.beginOfMonth(startTime);
        DateTime endTime = DateUtil.endOfMonth(startTime);
        incomeTotal.setStartTime(DateUtil.format(startTime, CommonConstant.DATE));
        incomeTotal.setEndTime(DateUtil.format(endTime, CommonConstant.DATE));
        IncomeTotal incomeTotal2 = incomeMeasurementMapper.selectTotalReal(incomeTotal);
        if (incomeTotal2 != null) {
            incomeTotal2.setDate(incomeTotal.getDataDate());
        }
        return incomeTotal2;
    }

    /**
     * 根据dataDate(数据时间)和templateId(模板id)查询是否已经有一条数据
     *
     * @param dataDate
     * @param stationId
     * @return
     */
    @Override
    public IncomeTotal selectTotalFee(String dataDate, Integer stationId) {
        return incomeMeasurementMapper.selectTotalFee(dataDate, stationId);
    }

    @Override
    public IncomeRate selectIncomeDetails(IncomeRate incomeRate) {
        return incomeMeasurementMapper.selectIncomeDetails(incomeRate);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Map<String, Object> excelInput(List<IncomeRate> incomeRates, SimpleUser simpleUser) {
        Map<String, Object> result = new HashMap<>(0);
        int i = 0;
        int line = 0;

        // 临时存放模板名称,用于比较用
        String templateName = "";

        // 临时存放费率名称,用于比较用
        String rateName = "";

        // 用于导入时计算合计
        BigDecimal totalStr = new BigDecimal("0");

        if (incomeRates.size() > 0) {

            IncomeTotal incomeTotal = null;
            try {
                for (IncomeRate incomeRate : incomeRates) {
                    // 由于excel导入时拿不到模板id和费率id所以根据模板名去查询一次模板信息,从而获取模板id
                    RateTemplate template = incomeMeasurementMapper.getTemplateByName(incomeRate.getStationId(), incomeRate.getTemplateName());
                    if (template == null) {
                        result.put("code", "400");
                        result.put("msg", "模板未找到,请确认模板名称是否正确!");
                        throw new RuntimeException("模板未找到,请确认模板名称是否正确!");
                    }
                    Long templateId = template.getId();
                    incomeRate.setTemplateId(templateId);
                    if (i == 0) {
                        // 先删除电站 设置时间下的所有数据重新插入
                        incomeMeasurementMapper.deleteIncomeRates(incomeRate);

                        // 给模板名称赋值
                        templateName = incomeRate.getTemplateName();
                    }
                    String dataDate = incomeRates.get(0).getDataDate();
                    IncomeTotal incomeTotalData = this.selectTotalFee(dataDate, incomeRate.getStationId());
                    if (incomeTotalData != null) {
                        incomeTotal = new IncomeTotal();
                        String q = incomeRate.getQ();

                        // 判断一次模板是否启用
                        int isOpen = incomeMeasurementMapper.checkTemplateOpen(templateId);
                        if (isOpen <= 0) {
                            result.put("code", "400");
                            result.put("msg", "模板未启用,请确认后重试!");
                            throw new RuntimeException("模板未启用,请确认后重试!");
                        }

                        // 这里根据模板id和费率名称查询费率信息
                        IncomeRateMapping rateMapping = incomeMeasurementMapper.getRateByName(templateId, incomeRate.getRateName());
                        if (rateMapping == null) {
                            // transactionManager.rollback(transactionStatus);
                            result.put("code", "400");
                            result.put("msg", "费率未找到,请确认费率名称是否正确!");
                            // return result;
                            throw new RuntimeException("费率未找到,请确认费率名称是否正确!");
                        }

                        // 判断模板名称是否有多个,如果不同则不允许添加
                        if (!templateName.equals(incomeRate.getTemplateName())) {
                            // transactionManager.rollback(transactionStatus);
                            result.put("code", "400");
                            result.put("msg", "模板选择不可不同!");
                            // return result;
                            throw new RuntimeException("模板选择不可不同!");
                        }

                        // 判断费率名称是否有多个,如果相同则不允许添加
                        rateName = incomeRate.getRateName();

                        for (int i1 = 0; i1 < incomeRates.size(); i1++) {
                            if (i1 != i && rateName.equals(incomeRates.get(i1).getRateName())) {
                                // transactionManager.rollback(transactionStatus);
                                result.put("code", "400");
                                result.put("msg", "费率选择不可相同!");
                                // return result;
                                throw new RuntimeException("费率选择不可相同!");
                            }
                        }

                        incomeRate.setRateId(Integer.valueOf(rateMapping.getRateId().toString()));
                        incomeRate.setRateName(rateMapping.getRateName());
                        incomeRate.setStartTime(rateMapping.getStartTime());
                        incomeRate.setEndTime(rateMapping.getEndTime());
                        incomeRate.setPrice(String.valueOf(rateMapping.getPrice()));
                        incomeRate.setDiscount(String.valueOf(rateMapping.getDiscount()));
                        line = incomeMeasurementMapper.excelInput(incomeRate, templateId, dataDate);
                        // 根据获取到的模板和费率信息对数据进行计算
                        BigDecimal total = new BigDecimal(q).multiply(new BigDecimal(rateMapping.getPrice())).multiply(new BigDecimal(rateMapping.getDiscount()));
                        String totalData = incomeMeasurementMapper.queryRateTotal(templateId, dataDate, rateMapping.getRateId());
                        if (null == totalData) {
                            totalData = "0";
                        }
                        incomeTotal.setEleTotalFee(total.add(new BigDecimal(totalData)));
                        incomeTotal.setDataDate(incomeRate.getDataDate());
                        incomeTotal.setStationId(incomeRate.getStationId());
                        incomeTotal.setTemplateId(templateId);
                        incomeTotal.setRateId(incomeRate.getRateId());
                        // 这里取imcome_total表里企业用电收益 进行累加
                        String incomeFee = incomeMeasurementMapper.getIncomeFee(incomeRate);
                        if (incomeFee != null) {
                            incomeTotal.setIncomeFee(new BigDecimal(incomeFee));
                        } else {
                            incomeTotal.setIncomeFee(new BigDecimal(0));
                        }
                        line = incomeMeasurementMapper.modifyEleTotalFee(incomeTotal);
                    } else {


                        // 判断一次模板是否启用
                        int isOpen = incomeMeasurementMapper.checkTemplateOpen(templateId);
                        if (isOpen <= 0) {
                            result.put("code", "400");
                            result.put("msg", "模板未启用,请确认后重试!");
                            throw new RuntimeException("模板未启用,请确认后重试!");
                        }

                        // 这里根据模板id和费率名称查询费率信息
                        IncomeRateMapping rateMapping = incomeMeasurementMapper.getRateByName(templateId, incomeRate.getRateName());
                        if (rateMapping == null) {
                            // transactionManager.rollback(transactionStatus);
                            result.put("code", "400");
                            result.put("msg", "费率未找到,请确认费率名称是否正确!");
                            // return result;
                            throw new RuntimeException("费率未找到,请确认费率名称是否正确!");
                        }

                        // 判断模板名称是否有多个,如果不同则不允许添加
                        if (!templateName.equals(incomeRate.getTemplateName())) {
                            // transactionManager.rollback(transactionStatus);
                            result.put("code", "400");
                            result.put("msg", "模板选择不可不同!");
                            // return result;
                            throw new RuntimeException("模板选择不可不同!");
                        }

                        // 判断费率名称是否有多个,如果相同则不允许添加
                        rateName = incomeRate.getRateName();

                        for (int i1 = 0; i1 < incomeRates.size(); i1++) {
                            if (i1 != i && rateName.equals(incomeRates.get(i1).getRateName())) {
                                // transactionManager.rollback(transactionStatus);
                                result.put("code", "400");
                                result.put("msg", "费率选择不可相同!");
                                // return result;
                                throw new RuntimeException("费率选择不可相同!");
                            }
                        }

                        // 进入else则是页面上没有手动输入过数据,income_total表里没有数据,走新增流程
                        incomeTotal = new IncomeTotal();
                        String q = incomeRate.getQ();
                        BigDecimal total = new BigDecimal(q).multiply(new BigDecimal(rateMapping.getPrice())).multiply(new BigDecimal(rateMapping.getDiscount()));
                        totalStr = totalStr.add(total);
                        incomeTotal.setEleTotalFee(totalStr);
                        incomeTotal.setIncomeFee(new BigDecimal("0"));
                        incomeTotal.setTotalFee(totalStr);
                        incomeTotal.setTemplateId(templateId);
                        incomeTotal.setRateId(incomeRate.getRateId());
                        incomeTotal.setStationId(incomeRate.getStationId());
                        incomeTotal.setDataDate(incomeRate.getDataDate());
                        incomeTotal.setGroupId(simpleUser.getGroupId());
                        if (i == incomeRates.size() - 1) {
                            line = incomeMeasurementMapper.insertTotalFee(incomeTotal);
                        }
                        incomeRate.setRateName(rateMapping.getRateName());
                        incomeRate.setStartTime(rateMapping.getStartTime());
                        incomeRate.setEndTime(rateMapping.getEndTime());
                        incomeRate.setPrice(String.valueOf(rateMapping.getPrice()));
                        incomeRate.setDiscount(String.valueOf(rateMapping.getDiscount()));
                        line = incomeMeasurementMapper.excelInput(incomeRate, templateId, dataDate);
                    }
                    i++;
                }
            } catch (NumberFormatException e) {
                // transactionManager.rollback(transactionStatus);
                throw new RuntimeException("操作失败!");
            }
            if (line > 0) {
                result.put("code", "200");
                result.put("msg", "操作成功");
                // transactionManager.commit(transactionStatus);
            } else {
                result.put("code", "400");
                result.put("msg", "操作失败");
                // transactionManager.rollback(transactionStatus);
                throw new RuntimeException("操作失败!");
            }
        } else {
            return result;
        }
        return result;
    }

    @Override
    //@Async //使用异步
    public int jobDataManage() {
        //因为dev开发环境垃圾数据太多,所以做个配置，dev环境只跑一个集团的数据
        //只有开发环境exp 写死一个groupId,通合环境使用真实表数据，其他环境不跑这个定时任务
        //查所有集团
        /**
         *查询电站是根据条件查询
         * */

        List<Station> stations = stationService.selectByInverterFlag(CommonConstant.ONE);
        List<Integer> groupIds = new ArrayList<>();
        Map<Integer, List<Station>> groupMap = new HashMap<>();
        groupIds = stations.stream().map(s -> {
            return s.getGroupId();
        }).distinct().collect(Collectors.toList());
       /* if (EnvConstant.EXP.equals(env) || EnvConstant.DEV.equals(env)) {
            //只增加集团为1的
            groupIds = new ArrayList<>();
            groupIds.add(1);
        }*/
        groupMap = stations.stream().collect(Collectors.groupingBy(Station::getGroupId));
        log.info("groupMap:" + groupMap);
        IncomeTotal incomeTotal = null;
        for (Integer groupId : groupIds) {
            //所有的发电量原始数据集
            List<InverterTimingGenerate> realDatas = inverterService.timingGenerationList(stations);
            if (realDatas != null) {
                log.info("realDatas:" + realDatas.toString());
            }
            //吧
            //过滤掉发电量为零的数据
            realDatas = realDatas.stream().filter(s -> {
                return s.getPowerGeneration().compareTo(BigDecimal.ZERO) != 0;
            }).collect(Collectors.toList());
            //查station的费率
            List<Station> stationByGroupIdList = groupMap.get(groupId);
            if (stationByGroupIdList.isEmpty()) {
                log.error("该集团电站为空 ,groupId: {}", groupId);
                continue;
            }
            //查集团下各个电站的费率
            List<IncomeQRate> stationRates = new ArrayList<>();
            for (Station station : stationByGroupIdList) {
                //查询时间当前时间 - 15 分钟
                DateTime timeBefore = DateUtil.offset(new Date(), DateField.MINUTE, -timeInterval);
                String day = DateUtil.format(timeBefore, CommonConstant.DATE_Hms);
                IncomeQRate incomeQRate = incomeMeasurementMapper.queryPriceBystationId(station.getId(), day);
                if (incomeQRate != null) {
                    stationRates.add(incomeQRate);
                }
            }
            //一个集团循环一次,一个集团入库一次,以便批量入库
            List<IncomeTotal> groupIncomeTotalList = new ArrayList<>(128);
            //将电站费率按staionId转为Map
            if (!stationRates.isEmpty()) {
                Map<Integer, List<IncomeQRate>> stationRateMap = stationRates.stream().collect(Collectors.groupingBy(IncomeQRate::getStationId));
                for (InverterTimingGenerate realData : realDatas) {
                    //这个电站有配置才做收益计算，否则不做
                    Integer stationIdKey = realData.getStationId();
                    //不包含这个电站的费率就跳过
                    if (!stationRateMap.containsKey(stationIdKey) && stationRateMap.get(stationIdKey) == null) {
                        log.error("这个电站没有配置费率, stationId: {} ", stationIdKey);
                        continue;
                    }
                    //这个电站的费率只存在一個費率
                    IncomeQRate incomeQRate = stationRateMap.get(stationIdKey).get(0);
                    incomeTotal = new IncomeTotal();
                    incomeTotal.setTemplateId(incomeQRate.getTemplateId());
                    incomeTotal.setRateId(incomeQRate.getRateId());
                    BigDecimal powerGeneration = realData.getPowerGeneration();
                    String price = incomeQRate.getPrice();
                    String discount = incomeQRate.getDiscount();
                    BigDecimal q = powerGeneration.multiply(new BigDecimal(price)).multiply(new BigDecimal(discount));
                    incomeTotal.setEle(powerGeneration.doubleValue());
                    incomeTotal.setEleTotalFee(q);
                    incomeTotal.setIncomeFee(BigDecimal.ZERO);
                    incomeTotal.setTotalFee(q);
                    incomeTotal.setSrcId(realData.getSrcId());
                    incomeTotal.setStationId(realData.getStationId());
                    incomeTotal.setRateName(incomeQRate.getRateName());
                    incomeTotal.setPrice(incomeQRate.getPrice());
                    incomeTotal.setStartTime(incomeQRate.getStartTime());
                    incomeTotal.setEndTime(incomeQRate.getEndTime());
                    incomeTotal.setDiscount(discount);
                    String datadateStr = DateUtil.format(realData.getProcessTime(), CommonConstant.DATE);
                    //如果datadate字段的时间是00:00:00，把日期改为前一天
                    Date processTime = realData.getProcessTime();
                    String processTimeStr = DateUtil.format(processTime, CommonConstant.DATE);
                    String strdate = null;
                    if (processTimeStr.endsWith(CommonConstant.START_SUFFIX_TIMESTAMP)) {
                        strdate = DateUtil.format(DateUtil.offsetDay(processTime, -1), CommonConstant.DATE_YMD);
                    } else {
                        strdate = DateUtil.format(processTime, CommonConstant.DATE_YMD);
                    }
                    incomeTotal.setDate(strdate);
                    incomeTotal.setDataDate(datadateStr);
                    incomeTotal.setGroupId(groupId);
                    groupIncomeTotalList.add(incomeTotal);
                    //改为批量batch add
                    //incomeMeasurementMapper.insertRealData(incomeTotal);
                }
            }
            //groupIncomeTotalList 不为空入库
            if (!groupIncomeTotalList.isEmpty()) {
                log.info("groupIncomeTotalList:" + groupIncomeTotalList.toString());
                incomeTotalMapper.insertRealDataBatch(groupIncomeTotalList);
            }
        }
        return 0;

    }

}
