package org.ts.ddcs.Service.Impl;


import org.ts.ddcs.Entity.PptnEntity;
import org.ts.ddcs.Entity.RelayDatagramRecordEntity;
import org.ts.ddcs.Entity.RiverEntity;
import org.ts.ddcs.Entity.RsvrEntity;
import org.ts.ddcs.Log.LogHelper;
import org.ts.ddcs.Service.RelayService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementSetter;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
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.SQLException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service("RelayService")
@Transactional
@SuppressWarnings("all")
public class RelayServiceImpl implements RelayService {

    @Value("${run-config.server.relay_db_url}")
    public String  url;

    @Value("${run-config.server.relay_db_username}")
    public String  username;

    @Value("${run-config.server.relay_db_password}")
    public String  password;


    @Value("${run-config.server.relay_db_dbtype}")
    public String  dbtype;

    @Override
    @Transactional(rollbackFor = {Exception.class}, propagation = Propagation.REQUIRED)
    public void RelaySwPPTNData(PptnEntity entity) {
        try {
            DriverManagerDataSource dataSource = new DriverManagerDataSource();
            if(dbtype.equals("sqlserver")){
                dataSource.setDriverClassName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            }else if(dbtype.equals("mysql")){
                dataSource.setDriverClassName("com.mysql.jdbc.Driver");
            }else{
                return;
            }
            dataSource.setUrl(url);
            dataSource.setUsername(username);
            dataSource.setPassword(password);
            JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
            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()))+"'";
            List<Map<String ,Object>> records= jdbcTemplate.queryForList(sql);
            if(records != null && records.size()>0){
                sql = "UPDATE  st_pptn_r  set DRP=?,INTV=? 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.setString(++index, entity.getSTCD());
                        preparedStatement.setTimestamp(++index, entity.getTM());
                    }
                });
            }else{
                sql = "INSERT INTO st_pptn_r  (STCD,TM,DRP,INTV) 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());
                    }
                });
            }
        }catch (Exception e){
            LogHelper.error(e);
        }
    }

    @Override
    @Transactional(rollbackFor = {Exception.class}, propagation = Propagation.REQUIRED)
    public void RelaySwPPTN_5MinData(PptnEntity entity) {
        try {
            DriverManagerDataSource dataSource = new DriverManagerDataSource();
            if(dbtype.equals("sqlserver")){
                dataSource.setDriverClassName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            }else if(dbtype.equals("mysql")){
                dataSource.setDriverClassName("com.mysql.jdbc.Driver");
            }else{
                return;
            }
            dataSource.setUrl(url);
            dataSource.setUsername(username);
            dataSource.setPassword(password);
            JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
            String sql = "INSERT INTO st_pptn_r_5_min  (STCD,TM,DRP,INTV) 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());
                }
            });
        }catch (Exception e){
            LogHelper.error(e);
        }
    }

    @Override
    @Transactional(rollbackFor = {Exception.class}, propagation = Propagation.REQUIRED)
    public void RelaySwPPTN_5Min_to_hour_Data(PptnEntity entity) {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        if(dbtype.equals("sqlserver")){
            dataSource.setDriverClassName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
        }else if(dbtype.equals("mysql")){
            dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        }else{
            return;
        }
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
        //由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 > '"+tm_p1+"' AND tm <=  '"+tm_p2+"' )";

        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.RelaySwPPTNData(entity);
        }
    }

    @Override
    @Transactional(rollbackFor = {Exception.class}, propagation = Propagation.REQUIRED)
    public void RelaySwRSVRData(RsvrEntity entity) {
        try {
            DriverManagerDataSource dataSource = new DriverManagerDataSource();
            if(dbtype.equals("sqlserver")){
                dataSource.setDriverClassName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            }else if(dbtype.equals("mysql")){
                dataSource.setDriverClassName("com.mysql.jdbc.Driver");
            }else{
                return;
            }
            dataSource.setUrl(url);
            dataSource.setUsername(username);
            dataSource.setPassword(password);

            JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);

            String sql = "INSERT INTO st_rsvr_r (STCD,TM,RZ) 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());
                }
            });

//            String 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());
//                }
//            });

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

    @Override
    @Transactional(rollbackFor = {Exception.class}, propagation = Propagation.REQUIRED)
    public void RelaySwRIVERData(RiverEntity entity) {
        try {
            DriverManagerDataSource dataSource = new DriverManagerDataSource();
            if(dbtype.equals("sqlserver")){
                dataSource.setDriverClassName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            }else if(dbtype.equals("mysql")){
                dataSource.setDriverClassName("com.mysql.jdbc.Driver");
            }else{
                return;
            }
            dataSource.setUrl(url);
            dataSource.setUsername(username);
            dataSource.setPassword(password);

            JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);


            String sql = "INSERT INTO st_river_r  (STCD,TM,Z) 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());
                }
            });


//            String 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());
//                }
//            });

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


}
