package com.steerinfo.ems.emswaterrealtime.service.impl;

import com.steerinfo.auth.utils.JwtUtil;
import com.steerinfo.ems.Utils.DateUtils;
import com.steerinfo.ems.Utils.MosaicUtils;
import com.steerinfo.ems.emswaihoursumtab1.mapper.EmsWAiHourSumTab1Mapper;
import com.steerinfo.ems.emswaihoursumtab1.model.EmsWAiHourSumTab1;
import com.steerinfo.ems.emswaihoursumtab1org.mapper.EmsWAiHourSumTab1OrgMapper;
import com.steerinfo.ems.emswaihoursumtab1org.model.EmsWAiHourSumTab1Org;
import com.steerinfo.ems.emswaterrealtime.mapper.EmsWaterRealtimeMapper;
import com.steerinfo.ems.emswaterrealtime.model.EmsWaterRealtime;
import com.steerinfo.ems.emswaterrealtime.service.IEmsWaterRealtimeService;
import com.steerinfo.ems.formula.model.Formula;
import com.steerinfo.ems.formula.service.IFormulaService;
import com.steerinfo.ems.ifmesemsswapfile.service.impl.IfMesEmsSwapfileServiceImpl;
import com.steerinfo.ems.trmcalpoint.model.TRmCalpoint;
import com.steerinfo.ems.trmcalpointexvalue.model.TRmCalpointExValue;
import com.steerinfo.ems.trmcalpointexvalue.service.ITRmCalpointExValueService;
import com.steerinfo.framework.datasource.DataSourceKey;
import com.steerinfo.framework.datasource.TargetDataSource;
import com.steerinfo.framework.mapper.IBaseMapper;
import com.steerinfo.framework.service.impl.BaseServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * EmsWaterRealtime服务实现：
 * @author generator
 * @version 1.0-SNAPSHORT 2021-08-24 07:52
 * 类描述
 * 修订历史：
 * 日期：2021-08-24
 * 作者：generator
 * 参考：
 * 描述：EmsWaterRealtime服务实现
 * @see null
 * @Copyright 湖南视拓信息技术股份有限公司. All rights reserved.
 */
@Service(value = "emsWaterRealtimeService")
public class EmsWaterRealtimeServiceImpl extends BaseServiceImpl<EmsWaterRealtime, String> implements IEmsWaterRealtimeService {

    private static final Logger logger = LoggerFactory.getLogger(IfMesEmsSwapfileServiceImpl.class);

    @Autowired
    private EmsWaterRealtimeMapper emsWaterRealtimeMapper;
    @Autowired
    private EmsWAiHourSumTab1Mapper emsWAiHourSumTab1Mapper;
    @Autowired
    private EmsWAiHourSumTab1OrgMapper emsWAiHourSumTab1OrgMapper;
    @Autowired
    ITRmCalpointExValueService tRmCalpointExValueService;
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    protected IBaseMapper<EmsWaterRealtime, String> getMapper() {
        return emsWaterRealtimeMapper;
    }

    //更换数据源使用
    static List<EmsWaterRealtime> emsWaterRealtimeList = new ArrayList<>();
    static List<EmsWAiHourSumTab1> emsWAiHourSumTab1s = new ArrayList<>();
    static List<EmsWAiHourSumTab1Org> emsWAiHourSumTab1Orgs = new ArrayList<>();
    static List<EmsWaterRealtime>  emsWaterToMeterRelation = new ArrayList<>();
    static List<TRmCalpointExValue> tRmCalpointExValues = new ArrayList<>();


    @Override
    @TargetDataSource(dataSourceKey = DataSourceKey.DB_OTHER)
    public List<EmsWaterRealtime> getWaterListByArmMeter() {
           // emsWaterRealtimeMapper.selectByPrimaryKey("1");//.getWaterListByArmMeter();
        //List<EmsWaterRealtime>
        String clock = DateUtils.dateStr(new Date(),"yyyy-MM-dd");
                emsWaterRealtimeList = emsWaterRealtimeMapper.getWaterListByArmMeter(clock);
        return emsWaterRealtimeList;
    }

    @Override
    public int dataGeneration() {

        int addSize = 0;
        int updateSize = 0;
        try {
            EmsWaterRealtime model;
            // emsWaterRealtimeMapper.selectByPrimaryKey("1");//.getWaterListByArmMeter();
            //List<EmsWaterRealtime> emsWaterRealtimeList = getWaterListByArmMeter();
            //updateSize = emsWaterRealtimeMapper.batchUpdate(emsWaterRealtimeList);
            for (EmsWaterRealtime emsWaterRealtime : emsWaterRealtimeList){
                emsWaterRealtime.setReadtime(new Date());
                //根据地址编码addresscode去进行更新（大用户出现先新增后修改的情况，导致我们出现同一个code出现两条数据）
                if(emsWaterRealtimeMapper.updateByAddresscodeSelective(emsWaterRealtime) == 0){
                    addSize+= emsWaterRealtimeMapper.insertSelective(emsWaterRealtime);
                }else {
                    updateSize+= 1;
                }
            }
            String clock = DateUtils.dateStr(new Date(),"yyyy-MM-dd HH:mm:ss");
            HashMap<String,Object> hashMap = new HashMap<String,Object>();
            hashMap.put("clock",clock);
            List<EmsWaterRealtime> emsWaterRealtimeList = emsWaterRealtimeMapper.getWaterTenMinutes();
            StringBuffer sub = new StringBuffer();
            String table="EMS_WATER";
            for (EmsWaterRealtime emsWaterRealtime : emsWaterRealtimeList){
                String[] tens = emsWaterRealtime.getmMaterial().split("\\.");
                String tag = tens[1];
                //多个表生成数据就填加table;
                table = tens[0];
                String sql = ","+tag + " = " + "'" + emsWaterRealtime.getSumvalue() + "'";
                sub.append(sql);
            }
            hashMap.put("table",table);
            hashMap.put("sql",sub.toString());
            updateSize += emsWaterRealtimeMapper.updateWaterMinutes(hashMap);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        }
        logger.info("本次总共新增水数据条数：" + addSize);
        logger.info("本次总共更新水数据条数：" + updateSize);
        return addSize+updateSize;
    }


    @Override
    public void getWaterTenMinutes() {
        int addSize = 0;
        int updateSize = 0;
        int i = 0;
        try {
            EmsWaterRealtime model;
            // emsWaterRealtimeMapper.selectByPrimaryKey("1");//.getWaterListByArmMeter();
            String clock1 = DateUtils.dateStr(new Date(),"yyyy-MM-dd HH:mm:ss");
            String clock2 = DateUtils.dateStr(new Date(),"yyyy-MM-dd HH:mm:ss");
            HashMap<String,Object> hashMap = new HashMap<String,Object>();
            hashMap.put("clock1",clock1);
            hashMap.put("clock2",clock2);
            try {
                addSize += emsWaterRealtimeMapper.insertWaterTenMinutes(hashMap);
            } catch (Exception e) {
                logger.error("主键已存在");
            } finally {
        emsWaterToMeterRelation = emsWaterRealtimeMapper.getWaterTenMinutes();
                StringBuffer sub = new StringBuffer();
                String table="EMS_WATER_TIMING";
                String[] tens;
                String tag;
                String sql;
                for (EmsWaterRealtime emsWaterRealtime : emsWaterToMeterRelation){
                    i++;
                    tens = emsWaterRealtime.getmType().split("\\.");
                    tag = tens[1];
                    //多个表生成数据就填加table;
                    table = tens[0];
                    sql = ","+tag + " = " + "'" + emsWaterRealtime.getSumvalue() + "'";
                    sub.append(sql);
                }
                clock2 = DateUtils.dateStr(new Date(),"yyyy-MM-dd HH:mm:ss");
                hashMap.put("table",table);
                hashMap.put("clock2",clock2);
                hashMap.put("sql",sub.toString());
                updateSize += emsWaterRealtimeMapper.updateWaterTenMinutes(hashMap);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        }
        logger.info("本次总共新增水数据条数：" + addSize);
        logger.info("本次总共更新水数据条数：" + updateSize+"；总共更新数据项"+i);
    }

    /***
     * 从大用户水系统获取数据到Mosaic
     */
    @Override
    public void getWaterListToMosaic() {
        List<EmsWaterRealtime> emsWaterRealtimeList = emsWaterRealtimeMapper.getWaterListToMosaic();
        //0x0069:032e:0 瞬时流量
        //0x020b:483d:0 累计流量
        //0x006b:41df:0 压力
        //final String SS="0x0069:032e:0";
        //final String LJ="0x020b:483d:0";
        //final String YL="0x006b:41df:0";
        //open
        MosaicUtils.SetOpenConnSample();
        StringBuilder sql = new StringBuilder("update Ana set Eng='");
        emsWaterRealtimeList.stream().forEach(s->{
            //sql = "update Param set ValueText='"+model.getEng().trim()+"' where Rid='"+model.getAltId()+"'";
          if(s.getMosaicid()==null||"".equals(s.getMosaicid())) {return;}
            //sql.append("update Ana set Eng='");
            sql.append(s.getSumvalue());
            sql.append("' where Equip=");
            sql.append(s.getMosaicid());
            //MosaicUtils.SetUpdateValue(sql.toString());
            //sql.delete(0,sql.length());
            switch (s.getmType()){
                case "SS":
                    sql.append(" AND Quantity=0x0069:032e:0");
                    break;
                case "YL":
                    sql.append(" AND Quantity=0x006b:41df:0");
                    break;
                default:
                    sql.append(" AND Quantity=0x020b:483d:0");
                    break;
            }
            MosaicUtils.SetUpdateValue(sql.toString());
            sql.delete(20,sql.length());
        });
        // Close
        MosaicUtils.SetCloseConnSample();
    }

    /**
     * 四个小时读取一次大用户水系统数据
     */
    @Override
    @TargetDataSource(dataSourceKey = DataSourceKey.DB_OTHER)
    public void getWaterHour() {
        if(!emsWaterToMeterRelation.equals(null) && emsWaterToMeterRelation.size()>0){
            int addSize = 0;
            int updateSize = 0;
            int i = 0;
            int size =emsWaterToMeterRelation.size();
            Calendar cal = Calendar.getInstance();
            //整点5个小时前
            cal.add(Calendar.HOUR_OF_DAY, -5);
            String clock5 = new SimpleDateFormat("yyyy-MM-dd HH").format(cal.getTime());
            // 整点4小时前
            cal.add(Calendar.HOUR_OF_DAY, 1);
            String clock4 = new SimpleDateFormat("yyyy-MM-dd HH").format(cal.getTime());
            //// 2小时前
            cal.add(Calendar.HOUR_OF_DAY, 2);
            String clock2 = new SimpleDateFormat("yyyy-MM-dd HH").format(cal.getTime());
            // 1小时前
            cal.add(Calendar.HOUR_OF_DAY, 1);
            String clock1 = new SimpleDateFormat("yyyy-MM-dd HH").format(cal.getTime());
            // 当前小时保留10分钟
            cal.add(Calendar.HOUR_OF_DAY, 1);
            String clock = new SimpleDateFormat("yyyy-MM-dd HH:mm").format(cal.getTime());
            // 24小时前
            cal.add(Calendar.DAY_OF_YEAR, -1);
            String clock24 = new SimpleDateFormat("yyyy-MM-dd HH").format(cal.getTime());
            HashMap<String,Object> historyMap = new HashMap<>(8);
            String[] tens;
            StringBuffer codes = new StringBuffer();
            String tags;
            StringBuffer whens = new StringBuffer();
            List<String> tagList = new ArrayList<>(size-1);
            List<String> codeList = new ArrayList<>(size-1);
            // tag存储字段
            String tag;
            // 存储表
            String table;
            // 十分钟表字段
            String tenvs;
            TRmCalpointExValue tRmCalpointExValue;
            String exTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
            for (EmsWaterRealtime emsWaterRealtime : emsWaterToMeterRelation){
                // 获取配置
                tag = emsWaterRealtime.getmName();
                table = emsWaterRealtime.getmUsertype();
                tenvs = emsWaterRealtime.getmType();
                if (tag == null || table == null || tenvs == null || tag.trim().isEmpty() || table.trim().isEmpty() || tenvs.trim().isEmpty()) {
                    tRmCalpointExValue=new TRmCalpointExValue();
                    tRmCalpointExValue.setItemid(emsWaterRealtime.getMeterid());
                    // 配置错误
                    tRmCalpointExValue.setExtype("2");
                    tRmCalpointExValue.setClock(clock);
                    tRmCalpointExValue.setCreatetime(exTime);
                    tRmCalpointExValue.setBz("配置不能为空");
                    tRmCalpointExValues.add(tRmCalpointExValue);
                    continue;
                }
                tens = emsWaterRealtime.getmType().split("\\.");
                if (tens.length != 2) {
                    tRmCalpointExValue = new TRmCalpointExValue();
                    tRmCalpointExValue.setItemid(emsWaterRealtime.getMeterid());
                    // 配置错误
                    tRmCalpointExValue.setExtype("2");
                    tRmCalpointExValue.setClock(clock);
                    tRmCalpointExValue.setCreatetime(exTime);
                    tRmCalpointExValue.setBz("十分钟表字段配置错误");
                    tRmCalpointExValues.add(tRmCalpointExValue);
                    continue;
                }
                whens.append(" when '");
                whens.append(emsWaterRealtime.getAddresscode());
                whens.append("' then '");
                whens.append(tens[1]);
                whens.append("'");
                tagList.add(tens[1]);
                codeList.add(emsWaterRealtime.getAddresscode());
            }
            codes.append("'");
            codes.append(codeList.toString().replaceAll("(?:\\[|null|\\]| +)", "")
                    .replaceAll(",","','"));
            codes.append("'");
            tags = tagList.toString().replaceAll("(?:\\[|null|\\]| +)", "");
            historyMap.put("whens",whens.toString());
            historyMap.put("clock4",clock4);
            historyMap.put("clock",clock);
            historyMap.put("codes", codes.toString());
            historyMap.put("tags", tags);
            emsWAiHourSumTab1s = emsWAiHourSumTab1Mapper.getHistoryData(historyMap);
            emsWAiHourSumTab1Orgs = emsWAiHourSumTab1OrgMapper.getHistoryDataOrg(historyMap);
        }
    }

    @Override
    @TargetDataSource(dataSourceKey = DataSourceKey.DB_OTHER)
    public void getWaterHour(String clock, String clock2) {
        if(!emsWaterToMeterRelation.equals(null) && emsWaterToMeterRelation.size()>0){
            int i = 0;
            int size =emsWaterToMeterRelation.size();
            HashMap<String,Object> historyMap = new HashMap<String,Object>(8);
            String[] tens;
            StringBuffer codes = new StringBuffer();
            String tags;
            StringBuffer whens = new StringBuffer();
            List<String> tagList = new ArrayList<>(size-1);
            List<String> codeList = new ArrayList<>(size-1);
            // tag存储字段
            String tag;
            // 存储表
            String table;
            // 十分钟表字段
            String tenvs;
            TRmCalpointExValue tRmCalpointExValue;
            String exTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
            for (EmsWaterRealtime emsWaterRealtime : emsWaterToMeterRelation){
                // 获取配置
                tag = emsWaterRealtime.getmName();
                table = emsWaterRealtime.getmUsertype();
                tenvs = emsWaterRealtime.getmType();
                if (tag == null || table == null || tenvs == null || tag.trim().isEmpty() || table.trim().isEmpty() || tenvs.trim().isEmpty()) {
                    tRmCalpointExValue=new TRmCalpointExValue();
                    tRmCalpointExValue.setItemid(emsWaterRealtime.getMeterid());
                    // 配置错误
                    tRmCalpointExValue.setExtype("2");
                    tRmCalpointExValue.setClock(clock);
                    tRmCalpointExValue.setCreatetime(exTime);
                    tRmCalpointExValue.setBz("配置不能为空");
                    tRmCalpointExValues.add(tRmCalpointExValue);
                    continue;
                }
                tens = emsWaterRealtime.getmType().split("\\.");
                if (tens.length != 2) {
                    tRmCalpointExValue = new TRmCalpointExValue();
                    tRmCalpointExValue.setItemid(emsWaterRealtime.getMeterid());
                    // 配置错误
                    tRmCalpointExValue.setExtype("2");
                    tRmCalpointExValue.setClock(clock);
                    tRmCalpointExValue.setCreatetime(exTime);
                    tRmCalpointExValue.setBz("十分钟表字段配置错误");
                    tRmCalpointExValues.add(tRmCalpointExValue);
                    continue;
                }
                tens = emsWaterRealtime.getmType().split("\\.");
                whens.append(" when '");
                whens.append(emsWaterRealtime.getAddresscode());
                whens.append("' then '");
                whens.append(tens[1]);
                whens.append("'");
                tagList.add(tens[1]);
                codeList.add(emsWaterRealtime.getAddresscode());
            }
            codes.append("'");
            codes.append(codeList.toString().replaceAll("(?:\\[|null|\\]| +)", "")
                    .replaceAll(",","','"));
            codes.append("'");
            tags = tagList.toString().replaceAll("(?:\\[|null|\\]| +)", "");
            historyMap.put("whens",whens.toString());
            historyMap.put("clock4",clock);
            historyMap.put("clock",clock2);
            historyMap.put("codes", codes.toString());
            historyMap.put("tags", tags);
            //emsWAiHourSumTab1s = emsWAiHourSumTab1Mapper.getHistoryData(historyMap);
            emsWAiHourSumTab1Orgs = emsWAiHourSumTab1OrgMapper.getHistoryDataOrg(historyMap);
        }
    }

    /**
     * 四个小时读取一次大用户水系统数据到小时表
     */
    @Override
    public void getHistoryWaterToHour() {
        //反射使用
        Object o;
        String varName;
        boolean accessFlag=false;
        Field[] fields;
        //赋值使用
        String sql;
        Double val = 0d;
        BigDecimal tab_val5 = BigDecimal.ZERO;
        BigDecimal org_val5 = BigDecimal.ZERO;
        //存储5小时前的值，禁止循环读取数据
        Integer j =0;
        Double [] val5s = new Double[0];
        String [] clock5s = new String[0];
        Calendar cal = Calendar.getInstance();
        Calendar cal5 = Calendar.getInstance();
        //当前小时
        String clock = new SimpleDateFormat("yyyy-MM-dd HH").format(cal.getTime());
        //当前整点5个小时前
        cal.add(Calendar.HOUR_OF_DAY, -5);
        String clock5 = new SimpleDateFormat("yyyy-MM-dd HH").format(cal.getTime());
        //异常处理使用
        TRmCalpointExValue tce;
        try{
            //获取用量值数据
        if(!emsWAiHourSumTab1s.equals(null)&&emsWAiHourSumTab1s.size()>0){
            clock5s=new String[emsWAiHourSumTab1s.size()];
        for(EmsWAiHourSumTab1 model : emsWAiHourSumTab1s) {
            fields = model.getClass().getDeclaredFields();
            for(int i = 0, len = fields.length; i < len; i++) {
                if(val5s.length==0){
                    val5s=new Double[fields.length];
                    Arrays.fill(val5s,0.0d);
                }
                // 对于每个属性，获取属性名
                varName = fields[i].getName().trim();
                String finalI = varName;
                try {
                    // 获取原来的访问控制权限
                    accessFlag = fields[i].isAccessible();
                    // 修改访问控制权限
                    fields[i].setAccessible(true);
                    try {
                        // 获取在对象f中属性fields[i]对应的对象中的变量
                        o = fields[i].get(model);
                        if(i==0){
                            clock5s[j]=o.toString();
                        }
                        if("class java.lang.Double".equals(fields[i].getGenericType().toString())){
                            //Method m = model.getClass().getMethod("get"+name);
                            //Double value = (Double) m.invoke(model);
                            if(o != null){
                                // 大于等于0
                                //if ((Double) o >= 0) {
                                //    //暂时不做判断，水数据四小时一次，等时间间距变小，再做处理
                                //    // 数据增加500以上，异常记录
                                //    if ((Double) o >= 500) {
                                //        // 记录异常数据
                                //        tce = gettRmCalpointExValue(clock5s[j],finalI,"8")
                                //        // 水数据增大超过最大值
                                //        tce.setBefvalue(val2);
                                //        tce.setCurvalue(val1);
                                //        tce.setClock(ma.get("TIM").toString());
                                //        tce.setCreatetime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                                //        //tce.setBz("十分钟水数据增大超过500，clock：" + clock1 + ",col:" + tenCol + ",table:" + tenTab);
                                //        tce.setBz("四小时水数据增大超过500，clock：" + clock1 + ",col:" + tenCol + ",table:" + tenTab);
                                //        tRmCalpointExValueService.add(tce);
                                //    }//else{
                                //    hval = hval.add(tenval);
                                //    //}
                                //} else {
                                //    // 清零处理
                                //    if (tenval.doubleValue() < -20d && val2.doubleValue() < 500d) {
                                //        hval = hval.add(val2);
                                //    }
                                //    // 记录异常数据
                                //    TRmCalpointExValue tce = new TRmCalpointExValue();
                                //    tce.setItemid(itemid);
                                //    tce.setExtype("1"); // 十分钟数据变小
                                //    tce.setBefvalue(val1);
                                //    tce.setCurvalue(val2);
                                //    tce.setClock(ma.get("TIM").toString());
                                //    tce.setCreatetime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                                //    tce.setBz("十分钟数据变小，clock：" + clock1 + ",col:" + tenCol + ",table:" + tenTab);
                                //    tRmCalpointExValueService.add(tce);
                                //}
                                //val=new BigDecimal(String.valueOf((Double) o));
                                //fields[i].set(model,val.setScale(1, RoundingMode.HALF_UP).doubleValue());
                            } else {
                                // 历史用量值更新失败
                                //tce = gettRmCalpointExValue(clock5s[j], finalI,"6");
                                //tce.setBz("准点用量值读取失败，clock：" + clock5s[j] + ",col:" + varName + ",table:"
                                //        + model.getClass().getName());
                                //tRmCalpointExValues.add(tce);
                                //用量直接赋值0
                                val=0d;
                                fields[i].set(model,val);
                            }
                        }
                    } catch (IllegalAccessException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } finally {
                        // 恢复访问控制权限
                        fields[i].setAccessible(accessFlag);
                    }
                } catch (IllegalArgumentException ex) {
                    ex.printStackTrace();
                }
            }
            if(emsWAiHourSumTab1Mapper.updateByPrimaryKeySelective(model)==0){
                emsWAiHourSumTab1Mapper.insertSelective(model);
            }
            j++;
        }
            val5s = new Double[0];
        }
        //获取仪表值数据
        if(!emsWAiHourSumTab1Orgs.equals(null)&&emsWAiHourSumTab1Orgs.size()>0){
            clock5s=new String[emsWAiHourSumTab1Orgs.size()];
            j = 0;
            for(EmsWAiHourSumTab1Org model : emsWAiHourSumTab1Orgs) {
                fields = model.getClass().getDeclaredFields();
                for(int i = 0;  i <  emsWaterToMeterRelation.size(); i++) {
                    if(val5s.length==0){
                        val5s=new Double[fields.length];
                        Arrays.fill(val5s,0.0d);
                    }
                    // 对于每个属性，获取属性名
                    varName = fields[i].getName().trim();
                    String finalI = varName;
                    try {
                        // 获取原来的访问控制权限
                        accessFlag = fields[i].isAccessible();
                        // 修改访问控制权限
                        fields[i].setAccessible(true);
                        try {
                            // 获取在对象f中属性fields[i]对应的对象中的变量
                            o = fields[i].get(model);
                            if(i==0){
                                clock5s[j]=o.toString();
                            }
                            if("class java.lang.Double".equals(fields[i].getGenericType().toString().trim())){
                                //Method m = model.getClass().getMethod("get"+name);
                                //Double value = (Double) m.invoke(model);
                                if(o != null){
                                    //val=new BigDecimal(String.valueOf(o));
                                    //fields[i].set(model,val.setScale(1, RoundingMode.HALF_UP).doubleValue());
                                } else {
                                    // 准点值错误
                                    tce = gettRmCalpointExValue(clock, finalI,"3");
                                    tce.setBz("准点仪表值读取失败，获取5小时前数据clock：" + clock + ",col:" + varName
                                            + ",table:" + model.getClass().getName());
                                    tRmCalpointExValues.add(tce);
                                    //if(val5s[i]==(0.0d)) {
                                        // 5小时前准点值,当前小时
                                        clock5s[j]+=":00:00";
                                        Date d = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(clock5s[j]);
                                        cal5.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(clock5s[j]));
                                        //上个小时
                                        cal5.add(Calendar.HOUR_OF_DAY, -4);
                                        clock5 = new SimpleDateFormat("yyyy-MM-dd HH").format(cal5.getTime());
                                        sql = "select " + varName + " from  EMS_W_AI_HOUR_SUM_TAB1_ORG where CLOCK = '" + clock5 + "'";
                                        try {
                                            val5s[i] = jdbcTemplate.queryForObject(sql, Double.class);
                                            val = val5s[i];
                                        } catch (Exception e) {
                                            val = 0d;
                                            //tce = gettRmCalpointExValue(clock5, finalI,"3");
                                            //tce.setCreatetime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                                            //        .format(new Date()));
                                            //tce.setBz("5小时前准点仪表值读取失败，clock：" + clock + ",col:" + varName + ",table:"
                                            //        + model.getClass().getName());
                                            //tRmCalpointExValues.add(tce);
                                        }
                                    //} else {
                                    //   val=val5s[i];
                                    //}
                                    fields[i].set(model,val);
                                }
                            }
                            //System.err.println("传入的对象中包含一个如下的变量：" + varName + " = " + o);
                        } catch (IllegalAccessException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } finally {
                            // 恢复访问控制权限
                            fields[i].setAccessible(accessFlag);
                        }
                    } catch (IllegalArgumentException ex) {
                        ex.printStackTrace();
                    }
                }
                if(emsWAiHourSumTab1OrgMapper.updateByPrimaryKeySelective(model)==0){
                    emsWAiHourSumTab1OrgMapper.insertSelective(model);
                }
                j++;
            }
        }
        if(emsWAiHourSumTab1Orgs.size()==0||emsWAiHourSumTab1s.size()==0){
            tce = new TRmCalpointExValue();
            tce.setItemid("数据传输错误");
            // 准点值错误
            tce.setExtype("12");
            tce.setClock(clock);
            tce.setCreatetime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                    .format(new Date()));
            tce.setBz("数据传输错误，无数据；请联系管理员");
            tRmCalpointExValues.add(tce);
        }
        } catch (Exception e) {
            tce = new TRmCalpointExValue();
            tce.setItemid("数据传输错误");
            // 准点值错误
            tce.setExtype("12");
            tce.setClock(clock);
            tce.setCreatetime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                    .format(new Date()));
            tce.setBz("数据传输错误，无数据；请联系管理员");
            tRmCalpointExValues.add(tce);
        }finally {
            //tRmCalpointExValueService.batchAdd(tRmCalpointExValues);
        }
    }

    private TRmCalpointExValue gettRmCalpointExValue(String clock, String finalI,String type) {
        String itemId;
        TRmCalpointExValue tce;
        itemId = emsWaterToMeterRelation.stream()
                .filter(emsWaterToMeter -> finalI.toUpperCase()
                        .equals(emsWaterToMeter.getmName().toUpperCase().trim()))
                .findFirst()
                .orElse(null).getMeterid();
        tce = new TRmCalpointExValue();
        tce.setItemid(itemId);
        tce.setExtype(type);
        tce.setClock(clock);
        tce.setCreatetime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                .format(new Date()));
        return tce;
    }

    @Override
    public void getAbnormalToExitValue() {

    }


    @Autowired
    IFormulaService formulaService;

    @Override
    public void getcalpoint() {
        List<TRmCalpoint> tRmCalpoints = emsWaterRealtimeMapper.getcalpoint();
        for(TRmCalpoint model : tRmCalpoints){
            Formula formula = new Formula();
            formula.setCode(model.getItemid());
            String itemdesc = model.getItemdesc(); // 项目描述
            formula.setDescription(itemdesc!=null && !itemdesc.trim().isEmpty() ? itemdesc : model.getTagAlias());
            // formula.setClock(DateUtils.getCurrentTime("yyyyMM"));
            formula.setClock("202001");
            formula.setIsavailable("1");
            formula.setRevisetime(DateUtils.getCurrentTime("yyyy-MM-dd HH:mm:ss"));
            formula.setTablename("T_RM_CALPOINT_VALUE");
            formula.setSourcecode("R(T_RM_CALPOINT_VALUE," + model.getItemid() + ")");
            formula.setRevisor(JwtUtil.getUseridByToken());

            formulaService.add(formula);
        }

    }
}
