package com.nantian.cloud.dbcapp.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nantian.cloud.dbcapp.bean.EnterpriseDataInfo;
import com.nantian.cloud.dbcapp.entity.EnterpriseInfo;
import com.nantian.cloud.dbcapp.mapper.collectmaster.CollectMasterDataMapper;
import com.nantian.cloud.dbcapp.mapper.jly.EnergyInfoMapper;
import com.nantian.cloud.dbcapp.mapper.jly.EnterpriseHaltMapper;
import com.nantian.cloud.dbcapp.mapper.record.EnergyMapper;
import com.nantian.cloud.dbcapp.mapper.record.EnterpriseDataInfoMapper;
import com.nantian.cloud.dbcapp.mapper.record.EnterpriseEnergyDataMapper;
import com.nantian.cloud.dbcapp.pojo.*;
import com.nantian.cloud.dbcapp.service.EnterpriseEnergyDataService;
import com.nantian.cloud.dbcapp.tool.ExcleTool;
import com.nantian.cloud.dbcapp.unit.Pages;
import com.nantian.cloud.dbcapp.unit.SnowflakeIDWorker;
import com.nantian.cloud.dbcapp.vo.*;
import com.nantian.sc.cloud.common.core.util.R;
import com.nantian.sc.cloud.common.security.service.ScUser;
import com.nantian.sc.cloud.common.security.util.SecurityUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicLong;

@Service("energyDataService")
@Transactional
public class EnterpriseEnergyDataImpl implements EnterpriseEnergyDataService {

    @Autowired
    EnterpriseEnergyDataMapper enterpriseEnergyDataMapper;
    @Autowired
    CollectMasterDataMapper collectMasterDataMapper;
    @Autowired
    EnterpriseHaltMapper enterpriseHaltMapper;
    @Autowired
    EnterpriseDataInfoMapper enterpriseDataInfoMapper;
    @Autowired
    SnowflakeIDWorker snowflakeIDWorker;
    @Autowired
    EnergyInfoMapper energyInfoMapper;
    @Autowired
    EnergyMapper energyMapper;

    private static final AtomicLong LAST_TIME_MS = new AtomicLong();

    @Override
    public R getRealTime() {
        Integer count = 0, fail = 0;
        //获取采集实时数据（主从库都需要获取）
        //List<String> tableNameList = collectDataMapper.getTableNameList();
        //String[] tableNames = tableNameList.toArray(new String[tableNameList.size()]);
        List<String> tableNameList1 = collectMasterDataMapper.getTableNameList();
        String[] tableNames1 = tableNameList1.toArray(new String[tableNameList1.size()]);
        List<EnterpriseEnergyDataVo> dataMaster = collectMasterDataMapper.getDataByTable(tableNames1);
        //List<EnterpriseEnergyDataVo> data = collectDataMapper.getDataByTable(tableNames);
        //清除采集实时表所有数据
        enterpriseEnergyDataMapper.deleteRealTime(null);
        //将采集实时数据放入采集实时表
        try {
            //count += enterpriseEnergyDataMapper.insertAllRealTime(data);
            count += enterpriseEnergyDataMapper.insertAllRealTime(dataMaster);
        } catch (Exception e) {
            fail += 1;
            e.printStackTrace();
        }
        return R.ok("成功："+count+" 条，失败"+fail+" 条");
    }

    @Override
    public R noEnergyDataExcel(HttpServletResponse response, String epcStr, String type, String statDate, String sendDate) throws IOException {
        //实时库数据导入energy_record库
//        R realTime = getRealTime();
        //查询停产企业
        //List<EnterpriseHaltVo> haltCompany = enterpriseHaltMapper.getHaltCompany(statDate +"-01", epcStr);
        List<EnterpriseHaltVo> haltCompany = enterpriseHaltMapper.getHaltCompany(statDate , epcStr);
        //查询未送数据名单 type为1、2，去掉停产企业
        int days = getDaysOfMonth(statDate);
        //查询停用采集点，停用采集点不用报送数据
        List<EnterpriseDataInfo> enable = enterpriseDataInfoMapper.selectEnableDataCodeByMonth(null,statDate);
        //List<EnterpriseEnergyDataInfoPOJO> noEnergyDataExcel = enterpriseEnergyDataMapper.noEnergyDataExcel(epcStr, haltCompany, type, statDate, sendDate, days, enable);
        //for (int i=0; i<noEnergyDataExcel.size(); i++) {
        //    noEnergyDataExcel.get(i).setId((i+1)+"");
        //}
        //WriteExcel(response,statDate+"应送未送企业名单","总（"+noEnergyDataExcel.size()+"）",EnterpriseEnergyDataInfoPOJO.class,noEnergyDataExcel);
        List<EnterpriseEnergyDetailPOJO> noEnergyDataExcel = enterpriseEnergyDataMapper.noEnergyDataExcel(epcStr, haltCompany, type, statDate, sendDate, days, enable);
        //导出excel
        WriteExcel(response,statDate+"应送未送企业名单","总（"+noEnergyDataExcel.size()+"）",EnterpriseEnergyDetailPOJO.class,noEnergyDataExcel);
        return R.ok("导出系统列表EXCEL成功");
    }

    @Override
    public R noEnergyDataInfoExcel(HttpServletResponse response, String epcStr,  String type, String statDate)  throws IOException{
        //实时库数据导入energy_record库
//        R realTime = getRealTime();
        //查询停产企业
        List<EnterpriseHaltVo> haltCompany = enterpriseHaltMapper.getHaltCompany(statDate , epcStr);
        int num = getDaysOfMonth(statDate);
        /*if("1".equals(type) || "3".equals(type)){ //按数据质量查询
           num = getDaysOfMonth(statDate);
        }*/
        //查询停用采集点，停用采集点不用报送数据
        List<EnterpriseDataInfo> enable = enterpriseDataInfoMapper.selectEnableDataCodeByMonth(null,statDate);
        List<EnterpriseEnergyDetailPOJO> noEnergyDataExcel = enterpriseEnergyDataMapper.noEnergyDataInfoExcel(epcStr,haltCompany,num,statDate,type, enable);
        WriteExcel(response,statDate+"应送未送企业名单(详情)",null,EnterpriseEnergyDetailPOJO.class,noEnergyDataExcel);
        return R.ok("导出系统列表EXCEL成功");
    }

    @Override
    public R energyDataByEpc(String epc, String statDate, String sendDate, String type) {
        //获取企业实时库数据
        getRealTimeByEpc(epc);
        //查询企业数据传输情况
        return R.ok(enterpriseEnergyDataMapper.energyDataByEpc(epc, statDate, sendDate, type));
    }

    //获取企业实时库数据，放入采集实时表
    private void getRealTimeByEpc(String epc) {
        char ch = getTableName(epc);
        //获取采集实时数据（主从库都需要获取）
        String[] tableNames = {"enterprise_energy_data_"+ch};
        //List<EnterpriseEnergyDataVo> data = collectDataMapper.getDataByTable(tableNames);
        List<EnterpriseEnergyDataVo> dataMaster = collectMasterDataMapper.getDataByTable(tableNames);
        //清除该企业的采集实时表
        enterpriseEnergyDataMapper.deleteRealTime(epc);
        //将采集实时数据放入采集实时表
        Integer sum = 0, fail = 0;
        try {
            //sum += enterpriseEnergyDataMapper.insertAllRealTime(data);
            sum += enterpriseEnergyDataMapper.insertAllRealTime(dataMaster);
        } catch (Exception e) {
            fail += 1;
            e.printStackTrace();
        }
    }

    @Override
    public R energyPage(Page page, String type, EnterpriseEnergyDataVo energyDataVo, String start, String end) {
        if (!"1".equals(type) && !"2".equals(type)) {
            return R.failed("类型错误，取值1历史，2实时");
        }
        if ("2".equals(type)) { //查询实时库
            //获取企业实时库数据
            getRealTimeByEpc(energyDataVo.getEnterpriseCode());
        }
//        Integer total = enterpriseEnergyDataMapper.energyTotal(type, energyDataVo, start, end);
//        Pages pages = new Pages(page.getSize(), page.getCurrent());
        IPage<EnterpriseEnergyDataVo> dataVoList = enterpriseEnergyDataMapper.energyPage(page, type, energyDataVo, start, end);
        Map<String,Double> marks = new HashMap<>();
        for (EnterpriseEnergyDataVo dataVo : dataVoList.getRecords()) {
            String datacodes=dataVo.getDataCode().substring(10,14);
            marks=enterpriseEnergyDataMapper.getMarks(datacodes);
            dataVo.setMarkingRange(marks);
            dataVo.setColumnName();
        }
//        Pages dataVoPage = new Pages(total, page.getSize(), page.getCurrent(), dataVoList);
        return R.ok(dataVoList);
    }

    @Override
    public R noDataCollectByEpc(String epc, String statDate) {
        //获取天数
        int num = getDaysOfMonth(statDate);
        //在线采集采集点未送数据查询 与 传输异常一致
        List<ConfigureCollectVo> configureCollectVos = enterpriseEnergyDataMapper.noDataCollectByException(epc, statDate, num);
        return R.ok(configureCollectVos);
        /*String cancelState = enterpriseEnergyDataMapper.getCompanyCancelState(epc);
        if("1".equals(cancelState)){//企业已注销
            return R.ok();
        }
        //获取企业实时库数据
        getRealTimeByEpc(epc);
        //查询停用采集点，停用采集点不用报送数据
        List<EnterpriseDataInfo> enable = enterpriseDataInfoMapper.selectEnableDataCodeByMonth(epc,statDate);
        List<ConfigureCollectVo> configureCollectVos = enterpriseEnergyDataMapper.noDataCollectByEpc(epc, statDate, num, enable);*/
    }

    @Override
    public R enterpriseTceExcel(HttpServletResponse response, String year, String epcStr, String type) throws IOException {

        //更新企业综合能耗
        enterpriseEnergyDataMapper.deleteEnergyTce(year);
        //获取统计时间
        String[] statDateList = getStatDateList(year);
        if("1".equals(type)){ //取系统结算数据
            enterpriseEnergyDataMapper.insertEnergyTce(year,epcStr,statDateList);
        }else{
            //todo 取原始数据结算的结果
        }
        enterpriseEnergyDataMapper.updateEnergyTce();
        List<EnterpriseTcePOJO> enterpriseTceList =  enterpriseEnergyDataMapper.enterpriseTceExcel(epcStr,statDateList,year);
        for (int i = 0; i < enterpriseTceList.size(); i++) {
            enterpriseTceList.get(i).setId((i + 1) + "");
            enterpriseTceList.get(i).setZsOverstepLevel();
        }
        //导出excel
        WriteExcel(response,"企业综合能耗",year+"年企业综合能耗",EnterpriseTcePOJO.class,enterpriseTceList);
        return R.ok("企业综合能耗导出成功");
    }

    @Override
    public R enterpriseQuotaDetailExcel(HttpServletResponse response, String year, String epcStr, String type) throws IOException {
        //获取统计时间
        String[] statDateList = getStatDateList(year);

        List<EnterpriseQuotaDetailPOJO> quotaDetailList = new ArrayList<>();
        if("1".equals(type)){ //取系统结算数据
            quotaDetailList =  enterpriseEnergyDataMapper.enterpriseQuotaDetailExcel(epcStr,statDateList);
        }else{
            //todo 取原始数据结算的结果
        }
        for (int i = 0; i < quotaDetailList.size(); i++) {
            quotaDetailList.get(i).setId((i + 1) + "");
            quotaDetailList.get(i).setOverstepLevel();
        }
        //导出excel
        WriteExcel(response,"企业指标明细表",year+"年企业指标明细",EnterpriseQuotaDetailPOJO.class,quotaDetailList);
        return R.ok("企业指标明细导出成功");
    }

    @Override
    public R enterpriseElectricExcel(HttpServletResponse response, String year, String epcStr) throws IOException {
        //获取统计时间
        String[] statDateList = getStatDateList(year);
        List<EnterpriseElectricPOJO> electricPOJOS = enterpriseEnergyDataMapper.getEnterpriseElectricExcel(epcStr,statDateList);
        for (int i = 0; i < electricPOJOS.size(); i++) {
            electricPOJOS.get(i).setId((i + 1) + "");
            electricPOJOS.get(i).setOverstepLevel();
            electricPOJOS.get(i).setSumOverstepLevel();
        }
        //导出excel
        WriteExcel(response,"企业电力消耗明细",year+"年电力消耗",EnterpriseElectricPOJO.class,electricPOJOS);
        return R.ok("企业电力消耗明细导出成功");
    }

    @Override
    public R enterpriseEnergyExcel(HttpServletResponse response, String year, String epcStr, String energyCode) throws IOException {
        //获取统计时间
        String[] statDateList = getStatDateList(year);
        //获取能源编码、能源名称
        String tmpEnergyCode = energyCode;
        String name = enterpriseEnergyDataMapper.getEnergyName(energyCode);
        if ("0100".equals(energyCode)) { //煤
            name = "煤";
            tmpEnergyCode = "0100,0102,0103,0104,0105,0600,0700,0800";
        }

        String[] energyCodeList = tmpEnergyCode.split(",");
        List<EnterpriseEnergyPOJO> energyPOJOS  = enterpriseEnergyDataMapper.getEnterpriseEnergyExcel(epcStr,statDateList,energyCodeList);
        for (int i = 0; i < energyPOJOS.size(); i++) {
            energyPOJOS.get(i).setId((i + 1) + "");
            energyPOJOS.get(i).setMonthCode();
        }

        WriteExcel(response,"企业用"+name+"数据上传情况",year+"年企业用"+name+"数据上传情况",EnterpriseEnergyPOJO.class,energyPOJOS);
        return R.ok("企业用能数据传送明细导出成功");
    }

    /*@Override
    public R updateWaveException(ExceptionInfoVo data) {
        //总表数据isIgnore状态记为1，表示已处理异常忽略不计
        boolean b1 = enterpriseEnergyDataMapper.updateInfoByEpc(data);
        return b1 ? R.ok("修改数据成功") : R.failed("修改数据失败！");
    }*/

    /*@Override
    public R updateTransException(ExceptionInfoVo data) {
        return insertData(data);
    }*/

    /*@Override
    public R insertDataMaster(ExceptionInfoVo data) {
        if(StringUtils.isBlank(data.getEnterpriseCode()) || StringUtils.isBlank(data.getDataCode()) || StringUtils.isBlank(data.getDataValue()) || StringUtils.isBlank(data.getStatDate())){
            return R.failed("信息不全，无法补录数据！");
        }
        return insertData(data);
    }*/

    @Override
    public R modifyData(List<ApplyRecord> applyRecordList) {
        ScUser user = SecurityUtils.getUser();
        for (ApplyRecord applyRecord : applyRecordList) {

            if( StringUtils.isBlank(applyRecord.getAuditType()) || "2".equals(applyRecord.getAuditType())){
                return R.failed("政府审核转态为空，审核失败！");
            }else if("0".equals(applyRecord.getAuditType())){ //政府审核通过
                //String dataId = applyRecord.getDataId();
                String operaType = applyRecord.getOperaType();
                String dataId = enterpriseEnergyDataMapper.getDataId(applyRecord);
                if (StringUtils.isBlank(dataId)) {
                    //return R.failed("企业删改数据处理失败，原因原始数据dataId为空！");
                    String auditText = StringUtils.isNotBlank(applyRecord.getAuditText()) ? "政府审核说明，"+applyRecord.getAuditText() : "";
                    applyRecord.setOperaType("4"); //无效记录
                    applyRecord.setAuditText(auditText+"(原始数据为空，审核无效)");
                } else {
                    applyRecord.setDataId(dataId);
                    String remark = operaType.equals("3") ? "企业处理波动异常" : (operaType.equals("2") ? "企业自行删除数据" : "企业自行修改数据");
                    remark = StringUtils.isNotBlank(applyRecord.getRemark()) ? remark + "（说明："+applyRecord.getRemark()+")" : remark;
                    applyRecord.setRemark(remark); //设置备注信息
                    if(operaType.equals("3")){
                        applyRecord.setOperaType("2"); //处理波动异常，修改企业原始数据
                        //enterpriseEnergyDataMapper.updateExceptionState(applyRecord); //修改异常表记录为已处理
                        enterpriseEnergyDataMapper.deleteException(applyRecord); //删除已经处理的异常信息
                        energyMapper.saveExceptionalLogByApply(applyRecord, SecurityUtils.getUser(), "2"); //保存异常处理日志
                    }

                    //数据备份至回收站（同一条数据的历史操作记录需保留）
                    //enterpriseEnergyDataMapper.deleteDataBack(dataId);
                    enterpriseEnergyDataMapper.insertDataBack(applyRecord);

                    if (operaType.equals("1") || operaType.equals("3")) {
                        //修改数据,将isAdditional字段更新为修改数据的状态，用于前台展示，2为修改状态，1为补传状态
                        enterpriseEnergyDataMapper.updateDataInfo(applyRecord);
                    } else if (operaType.equals("2")) {
                        //删除数据
                        enterpriseEnergyDataMapper.deleteDataInfo(applyRecord);
                    }

                    //处理异常信息，波动异常处理，0企业已解决，1企业提交修改申请，2政府审核退回，4企业未处理
                    enterpriseEnergyDataMapper.updateExceptionHandlerReson(applyRecord,"0");

                }
            }else{ //政府审核退回
                if("3".equals(applyRecord.getOperaType())){ //处理波动异常
                    //修改异常表记录为政府审核不通过（0企业已解决，1企业提交修改申请，2政府审核退回，4企业未处理）
                    enterpriseEnergyDataMapper.updateExceptionHandlerReson(applyRecord, "2");
                }
            }

            //申请修改数据记录表审核内容更新
            applyRecord.setAuditUser(user.getUserRealName());
            enterpriseEnergyDataMapper.updateApplyRecord(applyRecord);
        }
        return R.ok();
    }

    /*@Override
    public R updateException(List<ExceptionInfoVo> datas) {
        //处理异常 1.波动异常需多数据源修改数据 2.传输异常需要补录数据
        Integer state = 0, staus = 0;
        String msg = "";
        for (int i = 0; i < datas.size(); i++) {
            ExceptionInfoVo data = datas.get(i);
            String id = data.getId();
            // 若非传输异常，同步修改采集表.否则补传数据
            if (data.getExceptionType() != null && !"0101".equals(data.getExceptionType())) {
                //波动异常，需修改数据
                R r = updateWaveException(data);
                staus = r.getCode();
                msg = r.getMsg();
            } else {
                //传输异常，需补传数据
                if(data.getDataValue()==null){
                    data.setDataValue("0");
                }
                if(data.getConvertRation()==null){
                    data.setConvertRation("0");
                }
                R r = insertData(data);
                staus = r.getCode();
                msg = r.getMsg();
            }
            if(staus == 0){ //成功，修改异常表处理状态为已处理
                state = enterpriseEnergyDataMapper.updateExceptionInfo(data);
            }
        }
        if (state == 0) {
            return R.ok("no", msg);
        } else {
            return R.ok("yes", msg);
        }
    }*/

    @Override
    public R enterpriseElectricDetail(String year) {
        String month = "", date = "";
        int days = 0, num = 0;
        for (int i = 1; i <= 12; i++) {
            month = year + (i < 10 ? "-0" : "-") + i;
            days = getDaysOfMonth(month);
            for (int j = 1; j <= days; j++) {
                num++;
                date = month + (j < 10 ? "-0" : "-") + j;
                //设置企业一级电力数据
                enterpriseEnergyDataMapper.updateElectricDetailData(num, date);
                //设置表头
                enterpriseEnergyDataMapper.updateElectricDetailTable(num, date);
            }
        }
        return R.ok();
    }

    @Override
    public R etlGaugesManage(String planId, String epc, String type) {
        if(com.mysql.cj.util.StringUtils.isNullOrEmpty(planId) || com.mysql.cj.util.StringUtils.isNullOrEmpty(epc) || com.mysql.cj.util.StringUtils.isNullOrEmpty(type)){
            return R.failed("审查计划id或企业编码或数据传输类型不能为空");
        }
        //type类型 1计量器具，2计量人员
        if(type.contains("1")){
            energyInfoMapper.etlGauges(planId,epc);
            List<ConfigureGaugeVo> gauges = energyInfoMapper.getGaugesByEtl(planId, epc);
            if(gauges!=null && gauges.size()>0){
                //计量器具信息至应用分析系统首页
                enterpriseDataInfoMapper.etlGauges(gauges,epc);
            }
        }
        if(type.contains("2")){
            energyInfoMapper.etlCompanyCalculater(planId,epc);
        }
        return R.ok();
    }

    @Override
    public R confirmException(List<ExceptionInfoVo> data) {
        if(data != null && data.size() > 0){
            //int i = enterpriseEnergyDataMapper.updateExceptionList(data); //异常确认无误
            int i = enterpriseEnergyDataMapper.deleteExceptionList(data); //删除已经处理的异常
            int j = energyMapper.saveBatchExceptionalLog( data, SecurityUtils.getUser(), "1"); //保存异常处理日志
            return i>0 ? R.ok("异常数据确认成功！") : R.failed("异常数据确认失败，请联系运维人员！");
        }else{
            return R.failed("异常数据确认失败，参数不能为空！");
        }
    }

    @Override
    public R updateWaveExceptionList(List<ExceptionInfoVo> data) {
        if(data != null && data.size() > 0){
            for (ExceptionInfoVo vo : data) {
                if(StringUtils.isBlank(vo.getId()) || StringUtils.isBlank(vo.getCollectItemName()) || StringUtils.isBlank(vo.getDataValue()) || StringUtils.isBlank(vo.getConvertRation())){
                    return R.failed("波动异常数据处理失败，原异常记录id、采集点名称、原始数据、不能为空！");
                }
                if(StringUtils.isBlank(vo.getEditDataValue()) || StringUtils.isBlank(vo.getEditConvertRation())){
                    return R.failed("波动异常数据处理失败，修改的数值、修改的折标系数不能为空！");
                }
                if(vo.getEditDataValue().equals(vo.getDataValue()) && vo.getEditConvertRation().equals(vo.getConvertRation())){
                    return R.failed("波动异常数据处理失败，修改的数值、折标系数与原始数据一致，请使用【确认无误】功能处理异常！");
                }
            }
            int i = enterpriseEnergyDataMapper.inestApplyRecord(data); //批量提交数据修改申请
            int j = enterpriseEnergyDataMapper.updateExceptionHandlerType(data, "1"); //批量修改异常数据企业受理状态，为企业提交修改申请
            return i>0 ? R.ok("波动异常数据处理，已提交政府审批，待审核通过异常处理成功！") : R.failed("波动异常数据处理失败，请联系运维人员！");
        }else{
            return R.failed("波动异常数据处理失败，参数不能为空！");
        }
    }

    @Override
    public void insertEnterpriseTmp() {
        enterpriseDataInfoMapper.insertEnterpriseTmp();
    }

    //补录数据至实时库主库
    private R insertData(ExceptionInfoVo data) {
        //获取采集配置项信息
        EnterpriseEnergyDataVo energyDataVo = enterpriseEnergyDataMapper.getEnergyCollectInfo(data);
        if (energyDataVo == null) {
            return R.failed("采集点不存在，无法补录数据！");
        }
        //获取实时库表名
        char ch = getTableName(energyDataVo.getEnterpriseCode());
        String tableName = "enterprise_energy_data_"+ch;
        //根据采集频率截取统计时间
        String statDate = "";
        if(energyDataVo.getStatType().equals("1")){
            statDate = data.getStatDate().substring(0,10);
        }else if(energyDataVo.getStatType().equals("2")){
            statDate = data.getStatDate().substring(0,7);
        }
        data.setStatDate(statDate);
        //判断重复数据
        List<String> recordIds = enterpriseEnergyDataMapper.getDataBySataDate(data);
        List<String> masterIds = collectMasterDataMapper.getDataBySataDate(data,tableName);
        //List<String> collectIds = collectDataMapper.getDataBySataDate(data,tableName);
        //if((recordIds!=null && recordIds.size()>0) || (masterIds!=null && masterIds.size()>0) || (collectIds!=null && collectIds.size()>0)){
        if((recordIds!=null && recordIds.size()>0) || (masterIds!=null && masterIds.size()>0)){
            return R.ok("数据已存在，不用补录！");
        }
        //将数据插入实时库
        energyDataVo.setValid("1");
        energyDataVo.setDigest(uniqueCurrentTimeMS()+"");
        energyDataVo.setId(snowflakeIDWorker.getID());
        boolean b = collectMasterDataMapper.insertData(energyDataVo,tableName);
        return b ? R.ok("数据补录成功。") : R.failed("数据补录失败！");
    }

    //根据查询内容写入excel
    private void WriteExcel(HttpServletResponse response,String excelName, String sheetName, Class headClass, List data) throws IOException {
        ServletOutputStream out = null;
        ExcelWriter excelWriter = null;
        try {
            //写入excel
            SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");//设置日期格式
            String fileName = new String(excelName.getBytes("UTF-8"), "ISO-8859-1") + df.format(new Date()) + ".xls";
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.flushBuffer();
            out = response.getOutputStream();
            excelWriter = EasyExcel.write(out, headClass).registerWriteHandler(ExcleTool.myHorizontalCellStyleStrategy()).build();
            WriteSheet writeSheet = EasyExcel.writerSheet(sheetName).build();
            excelWriter.write(data, writeSheet);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            out.flush();
            excelWriter.finish();
            out.close();
        }
    }

    //获取统计时间，如2021-01至2021-12
    private String[] getStatDateList(String year) {
        String[] statDateList = new String[12];
        for (int i = 1; i <= 12; i++) {
            statDateList[i - 1] = year + (i <= 9 ? "-0" : "-") + i;
        }
        return statDateList;
    }

    //根据月份获取天数
    public static int getDaysOfMonth(String date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        Calendar calendar = Calendar.getInstance();
        try {
            calendar.setTime(sdf.parse(date));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
    }

    //获取字符串的最后一位小写
    private char getTableName(String epc) {
        //取出企业编码最后一位，若为大写，转为小写
        char[] chars = epc.toCharArray();
        char ch = chars[epc.length() - 1];
        if (Character.isUpperCase(ch)) {
            ch = Character.toLowerCase(ch);
        }
        return ch;
    }

    //获取时间戳
    public static long uniqueCurrentTimeMS() {
        long now = System.currentTimeMillis();
        while(true) {
            long lastTime = LAST_TIME_MS.get();
            if (lastTime >= now){
                now = lastTime+1;
            }
            if (LAST_TIME_MS.compareAndSet(lastTime,now)){
                return now;
            }
        }
    }
}
