package org.ts.ddcs.Service.Impl;


import com.alibaba.fastjson.JSONObject;
import org.ts.ddcs.DataItemTemplate.DataItemTemplateInterface;
import org.ts.ddcs.Entity.*;
import org.ts.ddcs.log.LogHelper;
import org.ts.ddcs.Service.SwService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementSetter;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 数据入库实现类
 */
@Service("SwService")
@Transactional
@SuppressWarnings("all")
public class SwServiceImpl implements SwService {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    @Transactional(rollbackFor = {Exception.class}, propagation = Propagation.REQUIRED)
    public void SaveSwData(JSONObject entity) {
        try {
            SimpleDateFormat timeFormat2 = new SimpleDateFormat("yyyyMMddHHmmss");
            Date dt = timeFormat2.parse(entity.getString("DT"));
            Date tm = timeFormat2.parse(entity.getString("TM"));
            Date ts = timeFormat2.parse(entity.getString("TS"));
            String v = "";
            String sql = "INSERT INTO st_pptn_r";
            sql += " (STCD,TM";
            if (entity.containsKey("DRP")) {
                sql += ",DRP";
                v += ",?";
            }
            if (entity.containsKey("INTV")) {
                sql += ",INTV";
                v += ",?";
            }
            if (entity.containsKey("PDR")) {
                sql += ",PDR";
                v += ",?";
            }
            if (entity.containsKey("DYP")) {
                sql += ",DYP";
                v += ",?";
            }
            if (entity.containsKey("WTH")) {
                sql += ",WTH";
                v += ",?";
            }
            if (entity.containsKey("PT")) {
                sql += ",PT";
                v += ",?";
            }
            sql += ",DT,TS) VALUES (?,?";
            sql += v;
            sql += ",?,?)";

            jdbcTemplate.update(sql, new PreparedStatementSetter() {
                @Override
                public void setValues(PreparedStatement preparedStatement) throws SQLException {
                    int index = 0;
                    preparedStatement.setString(++index, entity.getString("RTUCODE"));
                    preparedStatement.setTimestamp(++index, new Timestamp(tm.getTime()));
                    if (entity.containsKey("DRP")) {
                        DataItemTemplateInterface dataItemTemplateInterface = (DataItemTemplateInterface) entity.get("DRP");
                        preparedStatement.setBigDecimal(++index, dataItemTemplateInterface.GetDecimal());
                    }
                    if (entity.containsKey("INTV")) {
                        DataItemTemplateInterface dataItemTemplateInterface = (DataItemTemplateInterface) entity.get("INTV");
                        preparedStatement.setBigDecimal(++index, dataItemTemplateInterface.GetDecimal());
                    }
                    if (entity.containsKey("PDR")) {
                        DataItemTemplateInterface dataItemTemplateInterface = (DataItemTemplateInterface) entity.get("PDR");
                        preparedStatement.setBigDecimal(++index, dataItemTemplateInterface.GetDecimal());
                    }
                    if (entity.containsKey("DYP")) {
                        DataItemTemplateInterface dataItemTemplateInterface = (DataItemTemplateInterface) entity.get("DYP");
                        preparedStatement.setBigDecimal(++index, dataItemTemplateInterface.GetDecimal());
                    }
                    if (entity.containsKey("WTH")) {
                        DataItemTemplateInterface dataItemTemplateInterface = (DataItemTemplateInterface) entity.get("WTH");
                        preparedStatement.setBigDecimal(++index, dataItemTemplateInterface.GetDecimal());
                    }
                    if (entity.containsKey("PT")) {
                        DataItemTemplateInterface dataItemTemplateInterface = (DataItemTemplateInterface) entity.get("PT");
                        preparedStatement.setBigDecimal(++index, dataItemTemplateInterface.GetDecimal());
                    }
                    preparedStatement.setTimestamp(++index, new Timestamp(dt.getTime()));
                    preparedStatement.setTimestamp(++index, new Timestamp(ts.getTime()));
                }
            });

        } catch (Exception e) {
            LogHelper.error(e);
        }
    }

    @Override
    @Transactional(rollbackFor = {Exception.class}, propagation = Propagation.REQUIRED)
    public void SaveSwPPTNData(PptnEntity entity) {
        try {
            SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            //写入业务表
            String sql = "select  * from  st_pptn_r where STCD='" + entity.getSTCD() + "' and TM='" + timeFormat.format(new Date(entity.getTM().getTime())) + "'  LIMIT 1";
            List<Map<String, Object>> records = jdbcTemplate.queryForList(sql);
            if (records != null && records.size() > 0) {
                sql = "UPDATE  st_pptn_r  set DRP=?,INTV=?,PDR=?,DYP=?,WTH=?,PT=?,DT=?,TS=? where STCD=? and TM=?";
                jdbcTemplate.update(sql, new PreparedStatementSetter() {
                    @Override
                    public void setValues(PreparedStatement preparedStatement) throws SQLException {
                        int index = 0;
                        preparedStatement.setBigDecimal(++index, entity.getDRP());
                        preparedStatement.setBigDecimal(++index, entity.getINTV());
                        preparedStatement.setBigDecimal(++index, entity.getPDR());
                        preparedStatement.setBigDecimal(++index, entity.getDYP());
                        preparedStatement.setString(++index, entity.getWTH());
                        preparedStatement.setBigDecimal(++index, entity.getPT());
                        preparedStatement.setTimestamp(++index, entity.getDT());
                        preparedStatement.setTimestamp(++index, entity.getTS());
                        preparedStatement.setString(++index, entity.getSTCD());
                        preparedStatement.setTimestamp(++index, entity.getTM());
                    }
                });
            } else {
                sql = "INSERT INTO st_pptn_r  (STCD,TM,DRP,INTV,PDR,DYP,WTH,PT,DT,TS) VALUES (?,?,?,?,?,?,?,?,?,?)";
                jdbcTemplate.update(sql, new PreparedStatementSetter() {
                    @Override
                    public void setValues(PreparedStatement preparedStatement) throws SQLException {
                        int index = 0;
                        preparedStatement.setString(++index, entity.getSTCD());
                        preparedStatement.setTimestamp(++index, entity.getTM());
                        preparedStatement.setBigDecimal(++index, entity.getDRP());
                        preparedStatement.setBigDecimal(++index, entity.getINTV());
                        preparedStatement.setBigDecimal(++index, entity.getPDR());
                        preparedStatement.setBigDecimal(++index, entity.getDYP());
                        preparedStatement.setString(++index, entity.getWTH());
                        preparedStatement.setBigDecimal(++index, entity.getPT());
                        preparedStatement.setTimestamp(++index, entity.getDT());
                        preparedStatement.setTimestamp(++index, entity.getTS());
                    }
                });
            }
            //更新缓存表
            sql = "select  * from  st_pptn_r_cache where STCD='" + entity.getSTCD() + "'  LIMIT 1";
            records = jdbcTemplate.queryForList(sql);
            if (records != null && records.size() > 0) {
                sql = "UPDATE  st_pptn_r_cache  set TM=?,DRP=?,INTV=?,PDR=?,DYP=?,WTH=?,PT=?,DT=?,TS=? where STCD=?";
                jdbcTemplate.update(sql, new PreparedStatementSetter() {
                    @Override
                    public void setValues(PreparedStatement preparedStatement) throws SQLException {
                        int index = 0;
                        preparedStatement.setTimestamp(++index, entity.getTM());
                        preparedStatement.setBigDecimal(++index, entity.getDRP());
                        preparedStatement.setBigDecimal(++index, entity.getINTV());
                        preparedStatement.setBigDecimal(++index, entity.getPDR());
                        preparedStatement.setBigDecimal(++index, entity.getDYP());
                        preparedStatement.setString(++index, entity.getWTH());
                        preparedStatement.setBigDecimal(++index, entity.getPT());
                        preparedStatement.setTimestamp(++index, entity.getDT());
                        preparedStatement.setTimestamp(++index, entity.getTS());
                        preparedStatement.setString(++index, entity.getSTCD());
                    }
                });
            } else {
                sql = "INSERT INTO st_pptn_r_cache  (STCD,TM,DRP,INTV,PDR,DYP,WTH,PT,DT,TS) VALUES (?,?,?,?,?,?,?,?,?,?)";
                jdbcTemplate.update(sql, new PreparedStatementSetter() {
                    @Override
                    public void setValues(PreparedStatement preparedStatement) throws SQLException {
                        int index = 0;
                        preparedStatement.setString(++index, entity.getSTCD());
                        preparedStatement.setTimestamp(++index, entity.getTM());
                        preparedStatement.setBigDecimal(++index, entity.getDRP());
                        preparedStatement.setBigDecimal(++index, entity.getINTV());
                        preparedStatement.setBigDecimal(++index, entity.getPDR());
                        preparedStatement.setBigDecimal(++index, entity.getDYP());
                        preparedStatement.setString(++index, entity.getWTH());
                        preparedStatement.setBigDecimal(++index, entity.getPT());
                        preparedStatement.setTimestamp(++index, entity.getDT());
                        preparedStatement.setTimestamp(++index, entity.getTS());
                    }
                });
            }

        } catch (Exception e) {
            LogHelper.error(e);
        }
    }

    @Override
    @Transactional(rollbackFor = {Exception.class}, propagation = Propagation.REQUIRED)
    public void SaveSwPPTN_5Min_Data(PptnEntity entity) {
        try {
            String sql = "INSERT INTO st_pptn_r_5_min  (STCD,TM,DRP,INTV,PDR,DYP,WTH,DT,TS) VALUES (?,?,?,?,?,?,?,?,?)";
            jdbcTemplate.update(sql, new PreparedStatementSetter() {
                @Override
                public void setValues(PreparedStatement preparedStatement) throws SQLException {
                    int index = 0;
                    preparedStatement.setString(++index, entity.getSTCD());
                    preparedStatement.setTimestamp(++index, entity.getTM());
                    preparedStatement.setBigDecimal(++index, entity.getDRP());
                    preparedStatement.setBigDecimal(++index, entity.getINTV());
                    preparedStatement.setBigDecimal(++index, entity.getPDR());
                    preparedStatement.setBigDecimal(++index, entity.getDYP());
                    preparedStatement.setString(++index, entity.getWTH());
                    preparedStatement.setTimestamp(++index, entity.getDT());
                    preparedStatement.setTimestamp(++index, entity.getTS());
                }
            });
        } catch (Exception e) {
            LogHelper.error(e);
        }
    }


    @Override
    @Transactional(rollbackFor = {Exception.class}, propagation = Propagation.REQUIRED)
    public void SaveSwPPTN_5Min_to_hour_Data(PptnEntity entity) {
        //由5分钟生成数据到时段降水
        Timestamp tm = entity.getTM();
        SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String tm_p2 = timeFormat.format(new Date(tm.getTime()));

        Calendar tmDate = Calendar.getInstance();
        tmDate.setTime(new Date(tm.getTime()));
        tmDate.add(Calendar.MINUTE, -5);
        tmDate.set(Calendar.MINUTE, 0);
        tmDate.set(Calendar.SECOND, 0);
        String tm_p1 = timeFormat.format(tmDate.getTime());
        String sql = " SELECT";
        sql += "        sum(DRP) as drp_sum";
        sql += "        FROM";
        sql += " st_pptn_r_5_min";
        sql += "        WHERE";
        sql += " STCD = '" + entity.getSTCD() + "'";
        sql += " AND ( TM > str_to_date( '" + tm_p1 + "', '%Y-%m-%d %H:%i:%s' ) AND tm <= str_to_date( '" + tm_p2 + "', '%Y-%m-%d %H:%i:%s' ) )";

        List<Map<String, Object>> drp_sum_list = jdbcTemplate.queryForList(sql);
        if (null != drp_sum_list && drp_sum_list.size() > 0) {
            BigDecimal drp_sum = (BigDecimal) drp_sum_list.get(0).get("drp_sum");
            tmDate.setTime(new Date(tm.getTime()));
            tmDate.add(Calendar.MINUTE, -5);
            tmDate.set(Calendar.MINUTE, 0);
            tmDate.set(Calendar.SECOND, 0);
            entity.setTM(new Timestamp(tmDate.getTime().getTime()));
            entity.setDRP(drp_sum);
            entity.setINTV(new BigDecimal(1.0));
            this.SaveSwPPTNData(entity);
        }
    }

    @Override
    @Transactional(rollbackFor = {Exception.class}, propagation = Propagation.REQUIRED)
    public void SaveSwRSVRData(RsvrEntity entity) {
        try {
            String sql = "SELECT r.STCD FROM st_rsvr_r  r WHERE r.STCD =? AND r.TM=? LIMIT 1";

            List<Map<String, Object>> list = jdbcTemplate.query(sql, new PreparedStatementSetter() {
                @Override
                public void setValues(PreparedStatement preparedStatement) throws SQLException {
                    int count = 0;
                    preparedStatement.setString(++count, entity.getSTCD());
                    preparedStatement.setTimestamp(++count, entity.getTM());
                }
            }, new RowMapper<Map<String, Object>>() {
                @Override
                public Map<String, Object> mapRow(ResultSet resultSet, int i) throws SQLException {
                    Map<String, Object> item = new HashMap<>();
                    item.put("rtuCode", resultSet.getString("STCD"));
                    return item;
                }
            });
            if (null != list && list.size() > 0) {
                sql = "UPDATE  st_rsvr_r  set RZ=?,INQ=?,W=?,BLRZ=?,OTQ=?,RWCHRCD=?,RWPTN=?,INQDR=?,MSQMT=?,DT=?,TS=? where STCD =? AND TM=?";
                jdbcTemplate.update(sql, new PreparedStatementSetter() {
                    @Override
                    public void setValues(PreparedStatement preparedStatement) throws SQLException {
                        int index = 0;
                        preparedStatement.setBigDecimal(++index, entity.getRZ());
                        preparedStatement.setBigDecimal(++index, entity.getINQ());
                        preparedStatement.setBigDecimal(++index, entity.getW());
                        preparedStatement.setBigDecimal(++index, entity.getBLRZ());
                        preparedStatement.setBigDecimal(++index, entity.getOTQ());
                        preparedStatement.setString(++index, entity.getRWCHRCD());
                        preparedStatement.setString(++index, entity.getRWPTN());
                        preparedStatement.setBigDecimal(++index, entity.getINQDR());
                        preparedStatement.setString(++index, entity.getMSQMT());
                        preparedStatement.setTimestamp(++index, entity.getDT());
                        preparedStatement.setTimestamp(++index, entity.getTS());
                        preparedStatement.setString(++index, entity.getSTCD());
                        preparedStatement.setTimestamp(++index, entity.getTM());
                    }
                });
            } else {
                sql = "INSERT INTO st_rsvr_r (STCD,TM,RZ,INQ,W,BLRZ,OTQ,RWCHRCD,RWPTN,INQDR,MSQMT,DT,TS) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)";
                jdbcTemplate.update(sql, new PreparedStatementSetter() {
                    @Override
                    public void setValues(PreparedStatement preparedStatement) throws SQLException {
                        int index = 0;
                        preparedStatement.setString(++index, entity.getSTCD());
                        preparedStatement.setTimestamp(++index, entity.getTM());
                        preparedStatement.setBigDecimal(++index, entity.getRZ());
                        preparedStatement.setBigDecimal(++index, entity.getINQ());
                        preparedStatement.setBigDecimal(++index, entity.getW());
                        preparedStatement.setBigDecimal(++index, entity.getBLRZ());
                        preparedStatement.setBigDecimal(++index, entity.getOTQ());
                        preparedStatement.setString(++index, entity.getRWCHRCD());
                        preparedStatement.setString(++index, entity.getRWPTN());
                        preparedStatement.setBigDecimal(++index, entity.getINQDR());
                        preparedStatement.setString(++index, entity.getMSQMT());
                        preparedStatement.setTimestamp(++index, entity.getDT());
                        preparedStatement.setTimestamp(++index, entity.getTS());
                    }
                });
            }
            //更新级存表
            sql = "SELECT r.STCD FROM st_rsvr_r_cache  r WHERE r.STCD =? LIMIT 1";
            list = jdbcTemplate.query(sql, new PreparedStatementSetter() {
                @Override
                public void setValues(PreparedStatement preparedStatement) throws SQLException {
                    int count = 0;
                    preparedStatement.setString(++count, entity.getSTCD());
                }
            }, new RowMapper<Map<String, Object>>() {
                @Override
                public Map<String, Object> mapRow(ResultSet resultSet, int i) throws SQLException {
                    Map<String, Object> item = new HashMap<>();
                    item.put("rtuCode", resultSet.getString("STCD"));
                    return item;
                }
            });
            if (null != list && list.size() > 0) {
                sql = "UPDATE  st_rsvr_r_cache  set TM=?,RZ=?,INQ=?,W=?,BLRZ=?,OTQ=?,RWCHRCD=?,RWPTN=?,INQDR=?,MSQMT=?,DT=?,TS=? where STCD =? ";
                jdbcTemplate.update(sql, new PreparedStatementSetter() {
                    @Override
                    public void setValues(PreparedStatement preparedStatement) throws SQLException {
                        int index = 0;
                        preparedStatement.setTimestamp(++index, entity.getTM());
                        preparedStatement.setBigDecimal(++index, entity.getRZ());
                        preparedStatement.setBigDecimal(++index, entity.getINQ());
                        preparedStatement.setBigDecimal(++index, entity.getW());
                        preparedStatement.setBigDecimal(++index, entity.getBLRZ());
                        preparedStatement.setBigDecimal(++index, entity.getOTQ());
                        preparedStatement.setString(++index, entity.getRWCHRCD());
                        preparedStatement.setString(++index, entity.getRWPTN());
                        preparedStatement.setBigDecimal(++index, entity.getINQDR());
                        preparedStatement.setString(++index, entity.getMSQMT());
                        preparedStatement.setTimestamp(++index, entity.getDT());
                        preparedStatement.setTimestamp(++index, entity.getTS());
                        preparedStatement.setString(++index, entity.getSTCD());

                    }
                });
            } else {
                sql = "INSERT INTO st_rsvr_r_cache (STCD,TM,RZ,INQ,W,BLRZ,OTQ,RWCHRCD,RWPTN,INQDR,MSQMT,DT,TS) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)";
                jdbcTemplate.update(sql, new PreparedStatementSetter() {
                    @Override
                    public void setValues(PreparedStatement preparedStatement) throws SQLException {
                        int index = 0;
                        preparedStatement.setString(++index, entity.getSTCD());
                        preparedStatement.setTimestamp(++index, entity.getTM());
                        preparedStatement.setBigDecimal(++index, entity.getRZ());
                        preparedStatement.setBigDecimal(++index, entity.getINQ());
                        preparedStatement.setBigDecimal(++index, entity.getW());
                        preparedStatement.setBigDecimal(++index, entity.getBLRZ());
                        preparedStatement.setBigDecimal(++index, entity.getOTQ());
                        preparedStatement.setString(++index, entity.getRWCHRCD());
                        preparedStatement.setString(++index, entity.getRWPTN());
                        preparedStatement.setBigDecimal(++index, entity.getINQDR());
                        preparedStatement.setString(++index, entity.getMSQMT());
                        preparedStatement.setTimestamp(++index, entity.getDT());
                        preparedStatement.setTimestamp(++index, entity.getTS());
                    }
                });
            }
        } catch (Exception e) {
            LogHelper.error(e);
        }
    }


    @Override
    @Transactional(rollbackFor = {Exception.class}, propagation = Propagation.REQUIRED)
    public void SaveSwRIVERData(RiverEntity entity) {
        try {
            String sql = "SELECT STCD FROM st_river_r WHERE STCD =? AND TM=? LIMIT 1";
            List<Map<String, Object>> list = jdbcTemplate.query(sql, new PreparedStatementSetter() {
                @Override
                public void setValues(PreparedStatement preparedStatement) throws SQLException {
                    int count = 0;
                    preparedStatement.setString(++count, entity.getSTCD());
                    preparedStatement.setTimestamp(++count, entity.getTM());
                }
            }, new RowMapper<Map<String, Object>>() {
                @Override
                public Map<String, Object> mapRow(ResultSet resultSet, int i) throws SQLException {
                    Map<String, Object> item = new HashMap<>();
                    item.put("rtuCode", resultSet.getString("STCD"));
                    return item;
                }
            });

            if (null != list && list.size() > 0) {
                sql = "UPDATE st_river_r  set Z=?,Q=?,XSA=?,XSAVV=?,XSMXV=?,FLWCHRCD=?,WPTN=?,MSQMT=?,MSAMT=?,MSVMT=?,DT=?,TS=? where STCD=? AND TM=?";
                jdbcTemplate.update(sql, new PreparedStatementSetter() {
                    @Override
                    public void setValues(PreparedStatement preparedStatement) throws SQLException {
                        int index = 0;
                        preparedStatement.setBigDecimal(++index, entity.getZ());
                        preparedStatement.setBigDecimal(++index, entity.getQ());
                        preparedStatement.setBigDecimal(++index, entity.getXSA());
                        preparedStatement.setBigDecimal(++index, entity.getXSAVV());
                        preparedStatement.setBigDecimal(++index, entity.getXSMXV());
                        preparedStatement.setString(++index, entity.getFLWCHRCD());
                        preparedStatement.setString(++index, entity.getWPTN());
                        preparedStatement.setString(++index, entity.getMSQMT());
                        preparedStatement.setString(++index, entity.getMSAMT());
                        preparedStatement.setString(++index, entity.getMSVMT());
                        preparedStatement.setTimestamp(++index, entity.getDT());
                        preparedStatement.setTimestamp(++index, entity.getTS());
                        preparedStatement.setString(++index, entity.getSTCD());
                        preparedStatement.setTimestamp(++index, entity.getTM());
                    }
                });
            } else {
                sql = "INSERT INTO st_river_r  (STCD,TM,Z,Q,XSA,XSAVV,XSMXV,FLWCHRCD,WPTN,MSQMT,MSAMT,MSVMT,DT,TS) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
                jdbcTemplate.update(sql, new PreparedStatementSetter() {
                    @Override
                    public void setValues(PreparedStatement preparedStatement) throws SQLException {
                        int index = 0;
                        preparedStatement.setString(++index, entity.getSTCD());
                        preparedStatement.setTimestamp(++index, entity.getTM());
                        preparedStatement.setBigDecimal(++index, entity.getZ());
                        preparedStatement.setBigDecimal(++index, entity.getQ());
                        preparedStatement.setBigDecimal(++index, entity.getXSA());
                        preparedStatement.setBigDecimal(++index, entity.getXSAVV());
                        preparedStatement.setBigDecimal(++index, entity.getXSMXV());
                        preparedStatement.setString(++index, entity.getFLWCHRCD());
                        preparedStatement.setString(++index, entity.getWPTN());
                        preparedStatement.setString(++index, entity.getMSQMT());
                        preparedStatement.setString(++index, entity.getMSAMT());
                        preparedStatement.setString(++index, entity.getMSVMT());
                        preparedStatement.setTimestamp(++index, entity.getDT());
                        preparedStatement.setTimestamp(++index, entity.getTS());
                    }
                });
            }
            //更新缓存表
            sql = "SELECT STCD FROM st_river_r_cache WHERE STCD ='" + entity.getSTCD() + "' LIMIT 1";
            list = jdbcTemplate.queryForList(sql);
            if (null != list && list.size() > 0) {
                sql = "UPDATE  st_river_r_cache set TM=?,Z=?,Q=?,XSA=?,XSAVV=?,XSMXV=?,FLWCHRCD=?,WPTN=?,MSQMT=?,MSAMT=?,MSVMT=?,DT=?,TS=? WHERE STCD=?";
                jdbcTemplate.update(sql, new PreparedStatementSetter() {
                    @Override
                    public void setValues(PreparedStatement preparedStatement) throws SQLException {
                        int index = 0;
                        preparedStatement.setTimestamp(++index, entity.getTM());
                        preparedStatement.setBigDecimal(++index, entity.getZ());
                        preparedStatement.setBigDecimal(++index, entity.getQ());
                        preparedStatement.setBigDecimal(++index, entity.getXSA());
                        preparedStatement.setBigDecimal(++index, entity.getXSAVV());
                        preparedStatement.setBigDecimal(++index, entity.getXSMXV());
                        preparedStatement.setString(++index, entity.getFLWCHRCD());
                        preparedStatement.setString(++index, entity.getWPTN());
                        preparedStatement.setString(++index, entity.getMSQMT());
                        preparedStatement.setString(++index, entity.getMSAMT());
                        preparedStatement.setString(++index, entity.getMSVMT());
                        preparedStatement.setTimestamp(++index, entity.getDT());
                        preparedStatement.setTimestamp(++index, entity.getTS());
                        preparedStatement.setString(++index, entity.getSTCD());
                    }
                });
            } else {
                sql = "INSERT INTO st_river_r_cache  (STCD,TM,Z,Q,XSA,XSAVV,XSMXV,FLWCHRCD,WPTN,MSQMT,MSAMT,MSVMT,DT,TS) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
                jdbcTemplate.update(sql, new PreparedStatementSetter() {
                    @Override
                    public void setValues(PreparedStatement preparedStatement) throws SQLException {
                        int index = 0;
                        preparedStatement.setString(++index, entity.getSTCD());
                        preparedStatement.setTimestamp(++index, entity.getTM());
                        preparedStatement.setBigDecimal(++index, entity.getZ());
                        preparedStatement.setBigDecimal(++index, entity.getQ());
                        preparedStatement.setBigDecimal(++index, entity.getXSA());
                        preparedStatement.setBigDecimal(++index, entity.getXSAVV());
                        preparedStatement.setBigDecimal(++index, entity.getXSMXV());
                        preparedStatement.setString(++index, entity.getFLWCHRCD());
                        preparedStatement.setString(++index, entity.getWPTN());
                        preparedStatement.setString(++index, entity.getMSQMT());
                        preparedStatement.setString(++index, entity.getMSAMT());
                        preparedStatement.setString(++index, entity.getMSVMT());
                        preparedStatement.setTimestamp(++index, entity.getDT());
                        preparedStatement.setTimestamp(++index, entity.getTS());
                    }
                });
            }

        } catch (Exception e) {
            LogHelper.error(e);
        }
    }

    @Override
    @Transactional(rollbackFor = {Exception.class}, propagation = Propagation.REQUIRED)
    public void SaveSwWaterGateData(WaterGateInfo waterGateInfo) {
        try {
            String sql = "SELECT STCD FROM st_watergate_r WHERE STCD =? AND TM=? LIMIT 1";
            List<Map<String, Object>> list = jdbcTemplate.query(sql, new PreparedStatementSetter() {
                @Override
                public void setValues(PreparedStatement preparedStatement) throws SQLException {
                    int count = 0;
                    preparedStatement.setString(++count, waterGateInfo.getSTCD());
                    preparedStatement.setTimestamp(++count, waterGateInfo.getTM());
                }
            }, new RowMapper<Map<String, Object>>() {
                @Override
                public Map<String, Object> mapRow(ResultSet resultSet, int i) throws SQLException {
                    Map<String, Object> item = new HashMap<>();
                    item.put("rtuCode", resultSet.getString("STCD"));
                    return item;
                }
            });

            if (null != list && list.size() > 0) {

                sql = "DELETE FROM st_watergate_r_attr WHERE STCD =? AND TM =?";
                jdbcTemplate.update(sql, new PreparedStatementSetter() {
                    @Override
                    public void setValues(PreparedStatement preparedStatement) throws SQLException {
                        int index = 0;
                        preparedStatement.setString(++index, waterGateInfo.getSTCD());
                        preparedStatement.setTimestamp(++index, waterGateInfo.getTM());
                    }
                });


                if (waterGateInfo.getGateSum() > 0) {
                    sql = "INSERT INTO st_watergate_r_attr  (STCD,TM,GATE_CD,GATE_OPEN_HIGHTEN) VALUES (?,?,?,?)";
                    jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
                        @Override
                        public void setValues(PreparedStatement preparedStatement, int i) throws SQLException {
                            WaterGateDetailInfo detailInfo = waterGateInfo.getDetailInfoList().get(i);
                            int index = 0;
                            preparedStatement.setString(++index, detailInfo.getSTCD());
                            preparedStatement.setTimestamp(++index, detailInfo.getTM());
                            preparedStatement.setString(++index, detailInfo.getGateCode());
                            preparedStatement.setBigDecimal(++index, detailInfo.getOpenHeight());
                        }

                        @Override
                        public int getBatchSize() {
                            return waterGateInfo.getGateSum();
                        }
                    });
                }

                sql = "UPDATE st_watergate_r  set GATE_SUM=?,DT=?,TS=? where STCD=? AND TM=?";
                jdbcTemplate.update(sql, new PreparedStatementSetter() {
                    @Override
                    public void setValues(PreparedStatement preparedStatement) throws SQLException {
                        int index = 0;
                        preparedStatement.setInt(++index, waterGateInfo.getGateSum());
                        preparedStatement.setTimestamp(++index, waterGateInfo.getDT());
                        preparedStatement.setTimestamp(++index, waterGateInfo.getTS());
                        preparedStatement.setString(++index, waterGateInfo.getSTCD());
                        preparedStatement.setTimestamp(++index, waterGateInfo.getTM());
                    }
                });

            } else {
                sql = "INSERT INTO st_watergate_r  (STCD,TM,GATE_SUM,DT,TS) VALUES (?,?,?,?,?)";
                jdbcTemplate.update(sql, new PreparedStatementSetter() {
                    @Override
                    public void setValues(PreparedStatement preparedStatement) throws SQLException {
                        int index = 0;
                        preparedStatement.setString(++index, waterGateInfo.getSTCD());
                        preparedStatement.setTimestamp(++index, waterGateInfo.getTM());
                        preparedStatement.setInt(++index, waterGateInfo.getGateSum());
                        preparedStatement.setTimestamp(++index, waterGateInfo.getDT());
                        preparedStatement.setTimestamp(++index, waterGateInfo.getTS());
                    }
                });

                if (waterGateInfo.getGateSum() > 0) {
                    sql = "INSERT INTO st_watergate_r_attr  (STCD,TM,GATE_CD,GATE_OPEN_HIGHTEN) VALUES (?,?,?,?)";
                    jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
                        @Override
                        public void setValues(PreparedStatement preparedStatement, int i) throws SQLException {
                            WaterGateDetailInfo detailInfo = waterGateInfo.getDetailInfoList().get(i);
                            int index = 0;
                            preparedStatement.setString(++index, detailInfo.getSTCD());
                            preparedStatement.setTimestamp(++index, detailInfo.getTM());
                            preparedStatement.setString(++index, detailInfo.getGateCode());
                            preparedStatement.setBigDecimal(++index, detailInfo.getOpenHeight());
                        }

                        @Override
                        public int getBatchSize() {
                            return waterGateInfo.getGateSum();
                        }
                    });
                }
            }
            //更新缓存表
            sql = "SELECT STCD FROM st_watergate_r_cache WHERE STCD =?  LIMIT 1";
            list = jdbcTemplate.query(sql, new PreparedStatementSetter() {
                @Override
                public void setValues(PreparedStatement preparedStatement) throws SQLException {
                    int count = 0;
                    preparedStatement.setString(++count, waterGateInfo.getSTCD());
                }
            }, new RowMapper<Map<String, Object>>() {
                @Override
                public Map<String, Object> mapRow(ResultSet resultSet, int i) throws SQLException {
                    Map<String, Object> item = new HashMap<>();
                    item.put("rtuCode", resultSet.getString("STCD"));
                    return item;
                }
            });
            if (null != list && list.size() > 0) {
                sql = "DELETE FROM st_watergate_r_attr_cache WHERE STCD =?";
                jdbcTemplate.update(sql, new PreparedStatementSetter() {
                    @Override
                    public void setValues(PreparedStatement preparedStatement) throws SQLException {
                        int index = 0;
                        preparedStatement.setString(++index, waterGateInfo.getSTCD());
                    }
                });

                if (waterGateInfo.getGateSum() > 0) {
                    sql = "INSERT INTO st_watergate_r_attr_cache  (STCD,TM,GATE_CD,GATE_OPEN_HIGHTEN) VALUES (?,?,?,?)";
                    jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
                        @Override
                        public void setValues(PreparedStatement preparedStatement, int i) throws SQLException {
                            WaterGateDetailInfo detailInfo = waterGateInfo.getDetailInfoList().get(i);
                            int index = 0;
                            preparedStatement.setString(++index, detailInfo.getSTCD());
                            preparedStatement.setTimestamp(++index, detailInfo.getTM());
                            preparedStatement.setString(++index, detailInfo.getGateCode());
                            preparedStatement.setBigDecimal(++index, detailInfo.getOpenHeight());
                        }

                        @Override
                        public int getBatchSize() {
                            return waterGateInfo.getGateSum();
                        }
                    });
                }

                sql = "UPDATE st_watergate_r_cache  set TM=?,GATE_SUM=?,DT=?,TS=? where STCD=?";
                jdbcTemplate.update(sql, new PreparedStatementSetter() {
                    @Override
                    public void setValues(PreparedStatement preparedStatement) throws SQLException {
                        int index = 0;
                        preparedStatement.setTimestamp(++index, waterGateInfo.getTM());
                        preparedStatement.setInt(++index, waterGateInfo.getGateSum());
                        preparedStatement.setTimestamp(++index, waterGateInfo.getDT());
                        preparedStatement.setTimestamp(++index, waterGateInfo.getTS());
                        preparedStatement.setString(++index, waterGateInfo.getSTCD());
                    }
                });
            } else {
                sql = "INSERT INTO st_watergate_r_cache  (STCD,TM,GATE_SUM,DT,TS) VALUES (?,?,?,?,?)";
                jdbcTemplate.update(sql, new PreparedStatementSetter() {
                    @Override
                    public void setValues(PreparedStatement preparedStatement) throws SQLException {
                        int index = 0;
                        preparedStatement.setString(++index, waterGateInfo.getSTCD());
                        preparedStatement.setTimestamp(++index, waterGateInfo.getTM());
                        preparedStatement.setInt(++index, waterGateInfo.getGateSum());
                        preparedStatement.setTimestamp(++index, waterGateInfo.getDT());
                        preparedStatement.setTimestamp(++index, waterGateInfo.getTS());
                    }
                });

                if (waterGateInfo.getGateSum() > 0) {
                    sql = "INSERT INTO st_watergate_r_attr_cache  (STCD,TM,GATE_CD,GATE_OPEN_HIGHTEN) VALUES (?,?,?,?)";
                    jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
                        @Override
                        public void setValues(PreparedStatement preparedStatement, int i) throws SQLException {
                            WaterGateDetailInfo detailInfo = waterGateInfo.getDetailInfoList().get(i);
                            int index = 0;
                            preparedStatement.setString(++index, detailInfo.getSTCD());
                            preparedStatement.setTimestamp(++index, detailInfo.getTM());
                            preparedStatement.setString(++index, detailInfo.getGateCode());
                            preparedStatement.setBigDecimal(++index, detailInfo.getOpenHeight());
                        }

                        @Override
                        public int getBatchSize() {
                            return waterGateInfo.getGateSum();
                        }
                    });
                }
            }

        } catch (Exception e) {
            LogHelper.error(e);
        }
    }

    @Override
    @Transactional(rollbackFor = {Exception.class}, propagation = Propagation.REQUIRED)
    public void SaveSwImage(String id, String savePath, RtuImageEntity imageEntity) {
        try {

            String sql = "INSERT INTO t_file (`ID`, `GROUP_ID`, `FILE_NAME`, `EXT_NAME`, `CONTENT_TYPE`, `FILE_SIZE`, `SAVED_PATH`, `STATUS`) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
            jdbcTemplate.update(sql, new PreparedStatementSetter() {
                @Override
                public void setValues(PreparedStatement preparedStatement) throws SQLException {
                    int index = 0;
                    preparedStatement.setString(++index, id);
                    preparedStatement.setString(++index, imageEntity.getGroupId());
                    preparedStatement.setString(++index, imageEntity.getFileName());
                    preparedStatement.setString(++index, "jpg");
                    preparedStatement.setString(++index, "image/jpeg");
                    preparedStatement.setBigDecimal(++index, new BigDecimal(0));
                    preparedStatement.setString(++index, savePath);
                    preparedStatement.setBigDecimal(++index, new BigDecimal(1));
                }
            });


            sql = "INSERT INTO  st_rtu_camera_image (STCD,TM,GROUP_ID) VALUES(?,?,?)";
            jdbcTemplate.update(sql, new PreparedStatementSetter() {
                @Override
                public void setValues(PreparedStatement preparedStatement) throws SQLException {
                    int index = 0;
                    preparedStatement.setString(++index, imageEntity.getRtuCode());
                    preparedStatement.setTimestamp(++index, imageEntity.getTm());
                    preparedStatement.setString(++index, imageEntity.getGroupId());
                }
            });

        } catch (Exception e) {
            LogHelper.error(e);
        }

    }

    @Override
    public void SaveSwRtuSE(RtuStatusEntity entity) {
        try {
            String sql = "SELECT b.RTU_CD FROM t_base_rtu_info b WHERE b.RTU_CD ='" + entity.getStcd() + "'";
            List<Map<String, Object>> records = jdbcTemplate.queryForList(sql);
            if (records != null && records.size() == 1) {
                LogHelper.info("rtu status: " + entity.getStcd() + " update ");
                sql = "UPDATE  t_base_rtu_info  set WATER_SE=?,VOLTAGE=?,AC_ZT_WARNING=?,BATTERY_VOLTAGE_WARNING=? where RTU_CD=? ";
                jdbcTemplate.update(sql, new PreparedStatementSetter() {
                    @Override
                    public void setValues(PreparedStatement preparedStatement) throws SQLException {
                        int index = 0;
                        preparedStatement.setString(++index, entity.getWaterSe());
                        preparedStatement.setBigDecimal(++index, entity.getVoltage());
                        preparedStatement.setString(++index, entity.getAcZt());
                        preparedStatement.setString(++index, entity.getBatteryVoltage());
                        preparedStatement.setString(++index, entity.getStcd());

                    }
                });
            }

//            else {
//                LogHelper.info("rtu status: " + entity.getStcd() + " new ");
//                sql = "INSERT INTO t_base_rtu_info  (RTU_CD,WATER_SE,VOLTAGE,AC_ZT_WARNING,BATTERY_VOLTAGE_WARNING) VALUES (?,?)";
//                jdbcTemplate.update(sql, new PreparedStatementSetter() {
//                    @Override
//                    public void setValues(PreparedStatement preparedStatement) throws SQLException {
//                        int index = 0;
//                        preparedStatement.setString(++index, entity.getStcd());
//                        preparedStatement.setString(++index, entity.getWaterSe());
//                        preparedStatement.setBigDecimal(++index, entity.getVoltage());
//                        preparedStatement.setString(++index, entity.getAcZt());
//                        preparedStatement.setString(++index, entity.getBatteryVoltage());
//                    }
//                });
//            }

            SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String ts = timeFormat.format(new Date(entity.getCollectTime().getTime()));
            sql = "SELECT RTU_CD FROM t_base_rtu_status WHERE RTU_CD ='" + entity.getStcd() + "' AND TS='" + ts + "'";
            records = jdbcTemplate.queryForList(sql);
            if (null != records && records.size() > 0) {
                sql = "UPDATE  t_base_rtu_status  SET VOLTAGE=? WHERE RTU_CD=? AND TS=?";
                jdbcTemplate.update(sql, new PreparedStatementSetter() {
                    @Override
                    public void setValues(PreparedStatement preparedStatement) throws SQLException {
                        int index = 0;
                        preparedStatement.setBigDecimal(++index, entity.getVoltage());
                        preparedStatement.setString(++index, entity.getStcd());
                        preparedStatement.setTimestamp(++index, entity.getCollectTime());
                    }
                });
            } else {
                sql = "INSERT INTO t_base_rtu_status  (RTU_CD,TS,VOLTAGE) VALUES (?,?,?)";
                jdbcTemplate.update(sql, new PreparedStatementSetter() {
                    @Override
                    public void setValues(PreparedStatement preparedStatement) throws SQLException {
                        int index = 0;
                        preparedStatement.setString(++index, entity.getStcd());
                        preparedStatement.setTimestamp(++index, entity.getCollectTime());
                        preparedStatement.setBigDecimal(++index, entity.getVoltage());
                    }
                });
            }


            //水位计
//            String se = entity.getWaterSe();
//            if (null != se && se.length() > 0) {
//                sql = "SELECT w.ID as id,w.HAPPEN_TIME as ht  FROM t_b_rtu_warning w WHERE w.WARNING_STATUS ='0' AND w.WARNING_INFO ='3' AND w.RTU_CODE ='" + entity.getStcd() + "'";
//                List<Map<String, Object>> warningList = jdbcTemplate.queryForList(sql);
//                if (null != warningList && warningList.size() > 0) {
//                    if (se.equals("0")) {
//                        //恢复
//                        sql = "UPDATE  t_b_rtu_warning  SET WARNING_STATUS='1' ,RECOVERY_TIME=?  WHERE ID =?";
//                        jdbcTemplate.update(sql, new PreparedStatementSetter() {
//                            @Override
//                            public void setValues(PreparedStatement preparedStatement) throws SQLException {
//                                int index = 0;
//                                preparedStatement.setTimestamp(++index, new Timestamp(new Date().getTime()));
//                                preparedStatement.setString(++index, (String) warningList.get(0).get("id"));
//                            }
//                        });
//                    } else {
//                        //维持报警
//                    }
//                } else {
//                    if (se.equals("1")) {
//                        String id = UUID.randomUUID().toString().replace("-", "").toLowerCase();
//                        sql = "INSERT INTO t_b_rtu_warning (ID,RTU_CODE,WARNING_INFO,HAPPEN_TIME,WARNING_STATUS) VALUES (?,?,'3',?,'0')";
//                        jdbcTemplate.update(sql, new PreparedStatementSetter() {
//                            @Override
//                            public void setValues(PreparedStatement preparedStatement) throws SQLException {
//                                int index = 0;
//                                preparedStatement.setString(++index, id);
//                                preparedStatement.setString(++index, entity.getStcd());
//                                preparedStatement.setTimestamp(++index, new Timestamp(new Date().getTime()));
//                            }
//                        });
//                    }
//                }
//            }
            //交流电
//            String ac = entity.getAcZt();
//            if (null != ac && ac.length() > 0) {
//                sql = "SELECT w.ID as id,w.HAPPEN_TIME as ht  FROM t_b_rtu_warning w WHERE w.WARNING_STATUS ='0' AND w.WARNING_INFO ='1' AND w.RTU_CODE ='" + entity.getStcd() + "'";
//                List<Map<String, Object>> warningList = jdbcTemplate.queryForList(sql);
//                if (null != warningList && warningList.size() > 0) {
//                    if (ac.equals("0")) {
//                        //恢复
//                        sql = "UPDATE  t_b_rtu_warning  SET WARNING_STATUS='1' ,RECOVERY_TIME=?  WHERE ID =?";
//                        jdbcTemplate.update(sql, new PreparedStatementSetter() {
//                            @Override
//                            public void setValues(PreparedStatement preparedStatement) throws SQLException {
//                                int index = 0;
//                                preparedStatement.setTimestamp(++index, new Timestamp(new Date().getTime()));
//                                preparedStatement.setString(++index, (String) warningList.get(0).get("id"));
//                            }
//                        });
//                    } else {
//                        //维持报警
//                    }
//                } else {
//                    if (ac.equals("1")) {
//                        String id = UUID.randomUUID().toString().replace("-", "").toLowerCase();
//                        sql = "INSERT INTO t_b_rtu_warning (ID,RTU_CODE,WARNING_INFO,HAPPEN_TIME,WARNING_STATUS) VALUES (?,?,'1',?,'0')";
//                        jdbcTemplate.update(sql, new PreparedStatementSetter() {
//                            @Override
//                            public void setValues(PreparedStatement preparedStatement) throws SQLException {
//                                int index = 0;
//                                preparedStatement.setString(++index, id);
//                                preparedStatement.setString(++index, entity.getStcd());
//                                preparedStatement.setTimestamp(++index, new Timestamp(new Date().getTime()));
//                            }
//                        });
//                    }
//                }
//            }
            //电池电压
//            String bt = entity.getBatteryVoltage();
//            if (null != bt && bt.length() > 0) {
//                sql = "SELECT w.ID as id,w.HAPPEN_TIME as ht  FROM t_b_rtu_warning w WHERE w.WARNING_STATUS ='0' AND w.WARNING_INFO ='2' AND w.RTU_CODE ='" + entity.getStcd() + "'";
//                List<Map<String, Object>> warningList = jdbcTemplate.queryForList(sql);
//                if (null != warningList && warningList.size() > 0) {
//                    if (bt.equals("0")) {
//                        //恢复
//                        sql = "UPDATE  t_b_rtu_warning  SET WARNING_STATUS='1' ,RECOVERY_TIME=?  WHERE ID =?";
//                        jdbcTemplate.update(sql, new PreparedStatementSetter() {
//                            @Override
//                            public void setValues(PreparedStatement preparedStatement) throws SQLException {
//                                int index = 0;
//                                preparedStatement.setTimestamp(++index, new Timestamp(new Date().getTime()));
//                                preparedStatement.setString(++index, (String) warningList.get(0).get("id"));
//                            }
//                        });
//                    } else {
//                        //维持报警
//                    }
//                } else {
//                    if (bt.equals("1")) {
//                        String id = UUID.randomUUID().toString().replace("-", "").toLowerCase();
//                        sql = "INSERT INTO t_b_rtu_warning (ID,RTU_CODE,WARNING_INFO,HAPPEN_TIME,WARNING_STATUS) VALUES (?,?,'2',?,'0')";
//                        jdbcTemplate.update(sql, new PreparedStatementSetter() {
//                            @Override
//                            public void setValues(PreparedStatement preparedStatement) throws SQLException {
//                                int index = 0;
//                                preparedStatement.setString(++index, id);
//                                preparedStatement.setString(++index, entity.getStcd());
//                                preparedStatement.setTimestamp(++index, new Timestamp(new Date().getTime()));
//                            }
//                        });
//                    }
//                }
//            }
        } catch (Exception e) {
            LogHelper.error(e);
        }
    }

    @Override
    public RsvrEntity lastRsvrData(String rtuCode) {
        String sql = "SELECT c.STCD,c.RZ,c.TM FROM  st_rsvr_r_cache c";
        sql += " WHERE c.STCD='" + rtuCode + "' AND  c.RZ is not null";
        sql += " ORDER BY c.TM DESC";
        sql += " LIMIT 1";
        List<RsvrEntity> list = jdbcTemplate.query(sql, new RowMapper<RsvrEntity>() {
            @Override
            public RsvrEntity mapRow(ResultSet resultSet, int i) throws SQLException {
                RsvrEntity entity = new RsvrEntity();
                entity.setSTCD(resultSet.getString("STCD"));
                entity.setRZ(resultSet.getBigDecimal("RZ"));
                entity.setTM(resultSet.getTimestamp("TM"));
                return entity;
            }
        });
        if (null != list && list.size() > 0) {
            return list.get(0);
        }
        return null;
    }

    @Override
    public RtuImageEntity imageInfo(String groupId, Date tm) {

        String sql = "SELECT *  FROM st_rtu_camera_image WHERE  GROUP_ID =? AND TM=?";
        List<RtuImageEntity> list = jdbcTemplate.query(sql, new PreparedStatementSetter() {
            @Override
            public void setValues(PreparedStatement preparedStatement) throws SQLException {
                preparedStatement.setString(1, groupId);
                preparedStatement.setTimestamp(2, new Timestamp(tm.getTime()));

            }
        }, new RowMapper<RtuImageEntity>() {
            @Override
            public RtuImageEntity mapRow(ResultSet resultSet, int i) throws SQLException {
                RtuImageEntity entity = new RtuImageEntity();
                entity.setRtuCode(resultSet.getString("STCD"));
                entity.setGroupId(resultSet.getString("GROUP_ID"));
                entity.setTm(resultSet.getTimestamp("TM"));
                return entity;
            }
        });
        if (null != list && list.size() > 0) {
            return list.get(0);
        }

        return null;
    }


    @Override
    @Transactional(rollbackFor = {Exception.class}, propagation = Propagation.REQUIRED)
    public void SaveSwRtuStatus(RtuStatusEntity entity) {
        try {
            //更新RTU唯一码、4G卡SIM卡号
            String sql = "UPDATE  t_base_rtu_info  set RTU_UUID=?,CCID=? where RTU_CD=? ";
            jdbcTemplate.update(sql, new PreparedStatementSetter() {
                @Override
                public void setValues(PreparedStatement preparedStatement) throws SQLException {
                    int index = 0;
                    preparedStatement.setString(++index, entity.getUuid());
                    preparedStatement.setString(++index, entity.getCcid());
                    preparedStatement.setString(++index, entity.getStcd());
                }
            });
            //更新实时状态表
            sql = "select rtu_code from  rtu_realtime_status where rtu_code = '" + entity.getStcd() + "' ";
            List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
            if (list.size() > 0) {
                sql = "UPDATE  rtu_realtime_status  ";
                sql += " SET last_up_time=?,dtu_signal=?,voltage=?,temperature=?,rtu_status=?,rtu_error=?,battery_status=?,battery_battery_in=?,battery_battery_out=?,battery_power=?,battery_temperature=?,sun_power_voltage=?,sun_power_electric=?,update_time=? ";
                sql += " WHERE rtu_code=? ";
                jdbcTemplate.update(sql, new PreparedStatementSetter() {
                    @Override
                    public void setValues(PreparedStatement preparedStatement) throws SQLException {
                        int index = 0;
                        preparedStatement.setTimestamp(++index, entity.getCollectTime());
                        preparedStatement.setBigDecimal(++index, entity.getSignal());
                        preparedStatement.setBigDecimal(++index, entity.getVoltage());
                        preparedStatement.setBigDecimal(++index, entity.getTemperature());
                        preparedStatement.setInt(++index, new Integer(entity.getStatus()));
                        preparedStatement.setInt(++index, new Integer(entity.getError()));
                        preparedStatement.setString(++index, entity.getBatteryStatus());
                        preparedStatement.setString(++index, entity.getBatteryIn());
                        preparedStatement.setString(++index, entity.getBatteryOut());
                        preparedStatement.setBigDecimal(++index, entity.getBatteryPower());
                        preparedStatement.setBigDecimal(++index, entity.getBatteryTemperature());
                        preparedStatement.setBigDecimal(++index, entity.getSunPowerVoltage());
                        preparedStatement.setBigDecimal(++index, entity.getSunPowerElectric());
                        preparedStatement.setTimestamp(++index, new Timestamp(System.currentTimeMillis()));
                        preparedStatement.setString(++index, entity.getStcd());
                    }
                });
            } else {
                sql = "INSERT INTO rtu_realtime_status  (rtu_code,last_up_time,dtu_signal,voltage,temperature,rtu_status,rtu_error,battery_status,battery_battery_in,battery_battery_out,battery_power,battery_temperature,sun_power_voltage,sun_power_electric) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
                jdbcTemplate.update(sql, new PreparedStatementSetter() {
                    @Override
                    public void setValues(PreparedStatement preparedStatement) throws SQLException {
                        int index = 0;
                        preparedStatement.setString(++index, entity.getStcd());
                        preparedStatement.setTimestamp(++index, entity.getCollectTime());
                        preparedStatement.setBigDecimal(++index, entity.getSignal());
                        preparedStatement.setBigDecimal(++index, entity.getVoltage());
                        preparedStatement.setBigDecimal(++index, entity.getTemperature());
                        preparedStatement.setInt(++index, new Integer(entity.getStatus()));
                        preparedStatement.setInt(++index, new Integer(entity.getError()));
                        preparedStatement.setString(++index, entity.getBatteryStatus());
                        preparedStatement.setString(++index, entity.getBatteryIn());
                        preparedStatement.setString(++index, entity.getBatteryOut());
                        preparedStatement.setBigDecimal(++index, entity.getBatteryPower());
                        preparedStatement.setBigDecimal(++index, entity.getBatteryTemperature());
                        preparedStatement.setBigDecimal(++index, entity.getSunPowerVoltage());
                        preparedStatement.setBigDecimal(++index, entity.getSunPowerElectric());
                    }
                });
            }
            //添加实时状态历史表
//            sql = "INSERT INTO rtu_realtime_status_history  (rtu_code,last_up_time,dtu_signal,voltage,temperature,rtu_status,rtu_error,battery_status,battery_battery_in,battery_battery_out,battery_power,battery_temperature,sun_power_voltage,sun_power_electric) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
//            jdbcTemplate.update(sql, new PreparedStatementSetter() {
//                @Override
//                public void setValues(PreparedStatement preparedStatement) throws SQLException {
//                    int index = 0;
//                    preparedStatement.setString(++index, entity.getStcd());
//                    preparedStatement.setTimestamp(++index, entity.getCollectTime());
//                    preparedStatement.setBigDecimal(++index, entity.getSignal());
//                    preparedStatement.setBigDecimal(++index, entity.getVoltage());
//                    preparedStatement.setBigDecimal(++index, entity.getTemperature());
//                    preparedStatement.setInt(++index, new Integer(entity.getStatus()));
//                    preparedStatement.setInt(++index, new Integer(entity.getError()));
//                    preparedStatement.setString(++index, entity.getBatteryStatus());
//                    preparedStatement.setString(++index, entity.getBatteryIn());
//                    preparedStatement.setString(++index, entity.getBatteryOut());
//                    preparedStatement.setBigDecimal(++index, entity.getBatteryPower());
//                    preparedStatement.setBigDecimal(++index, entity.getBatteryTemperature());
//                    preparedStatement.setBigDecimal(++index, entity.getSunPowerVoltage());
//                    preparedStatement.setBigDecimal(++index, entity.getSunPowerElectric());
//                }
//            });
            SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String ts = timeFormat.format(new Date(entity.getCollectTime().getTime()));
            sql = "SELECT RTU_CD FROM t_base_rtu_status WHERE RTU_CD ='" + entity.getStcd() + "' AND TS='" + ts + "'";
            List<Map<String ,Object>> records = jdbcTemplate.queryForList(sql);
//            sql ="select * from t_base_rtu_status where RTU_CD=? and TS=?";
//            List<Map<String ,Object>> list2 =jdbcTemplate.queryForList(sql, new PreparedStatementSetter() {
//                @Override
//                public void setValues(PreparedStatement preparedStatement) throws SQLException {
//                    int index = 0;
//                    preparedStatement.setString(++index, entity.getStcd());
//                    preparedStatement.setTimestamp(++index, new Timestamp(entity.getCollectTime().getTime()));
//                }
//            });
            if(null == records || records.size()==0) {
                sql = "INSERT INTO t_base_rtu_status  (RTU_CD,TS,RTU_SIGNAL,VOLTAGE,TEMPERATURE,RTU_STATUS,RTU_ERROR,BATTERY_STATUS,BATTERY_IN,BATTERY_OUT,BATTERY_POWER,BATTERY_TEMPERATURE,SUN_POWER_VOLTAGE,SUN_POWER_ELECTRIC) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
                jdbcTemplate.update(sql, new PreparedStatementSetter() {
                    @Override
                    public void setValues(PreparedStatement preparedStatement) throws SQLException {
                        int index = 0;
                        preparedStatement.setString(++index, entity.getStcd());
                        preparedStatement.setTimestamp(++index, entity.getCollectTime());
                        preparedStatement.setBigDecimal(++index, entity.getSignal());
                        preparedStatement.setBigDecimal(++index, entity.getVoltage());
                        preparedStatement.setBigDecimal(++index, entity.getTemperature());
                        preparedStatement.setInt(++index, new Integer(entity.getStatus()));
                        preparedStatement.setInt(++index, new Integer(entity.getError()));
                        preparedStatement.setString(++index, entity.getBatteryStatus());
                        preparedStatement.setString(++index, entity.getBatteryIn());
                        preparedStatement.setString(++index, entity.getBatteryOut());
                        preparedStatement.setBigDecimal(++index, entity.getBatteryPower());
                        preparedStatement.setBigDecimal(++index, entity.getBatteryTemperature());
                        preparedStatement.setBigDecimal(++index, entity.getSunPowerVoltage());
                        preparedStatement.setBigDecimal(++index, entity.getSunPowerElectric());
                    }
                });
            }
        } catch (Exception e) {
            LogHelper.error(e);
        }
    }

    @Override
    public RtuStatusEntity SwRtuStatus(String stcd) {
        String sql = "SELECT * FROM rtu_realtime_status WHERE rtu_code ='" + stcd + "'";
        List<RtuStatusEntity> list = jdbcTemplate.query(sql, new RowMapper<RtuStatusEntity>() {
            @Override
            public RtuStatusEntity mapRow(ResultSet resultSet, int i) throws SQLException {
                RtuStatusEntity entity = new RtuStatusEntity();
                entity.setStcd(resultSet.getString("rtu_code"));
                entity.setCollectTime(resultSet.getTimestamp("last_up_time"));
                entity.setSignal(resultSet.getBigDecimal("dtu_signal"));
                entity.setVoltage(resultSet.getBigDecimal("voltage"));
                entity.setTemperature(resultSet.getBigDecimal("temperature"));
                entity.setStatus(resultSet.getInt("rtu_status"));
                entity.setError(resultSet.getInt("rtu_error"));
                entity.setBatteryStatus(resultSet.getString("battery_status"));
                entity.setBatteryIn(resultSet.getString("battery_battery_in"));
                entity.setBatteryOut(resultSet.getString("battery_battery_out"));
                entity.setBatteryPower(resultSet.getBigDecimal("battery_power"));
                entity.setBatteryTemperature(resultSet.getBigDecimal("battery_temperature"));
                entity.setSunPowerVoltage(resultSet.getBigDecimal("sun_power_voltage"));
                entity.setSunPowerElectric(resultSet.getBigDecimal("sun_power_electric"));
                return entity;
            }
        });

        if (null != list && list.size() == 1) {
            return list.get(0);
        }
        return null;
    }
}
