/**
 * Copyright 2019 DH
 * All right reserved.
 * 项目名称: 大恒泰山系统
 * 创建日期:2022/1/4
 */
package org.ts.ddcs.controller.simulator.service.impl;


import org.springframework.beans.factory.annotation.Autowired;
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.ts.ddcs.controller.simulator.entity.SimulatorInfo;
import org.ts.ddcs.controller.simulator.service.RtuSimulatorService;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/***
 * Date:2022/1/4
 * Title:文件所属模块（必须填写）
 * Description：对本文件的详细描述，原则上不能少于30字
 * @author dylan
 * @mender：（文件的修改者，文件创建者之外的人）
 * @version 1.0
 * Remark：认为有必要的其他信息
 */
@Service("RtuSimulatorService")
public class RtuSimulatorServiceImpl implements RtuSimulatorService {

    @Autowired
    private JdbcTemplate jdbcTemplate;


    @Override
    public List<SimulatorInfo> simulatorList() {
        try {
            SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String sql = "SELECT s.ID,s.RTU_CODE,s.REMOTE_IP,s.REMOTE_PORT,s.DELAY_TIME,s.START_TIME,s.END_TIME ";
            sql += " FROM";
            sql += " t_d_rtu_simulator s";
            sql += " WHERE s.RUN_STATUS='1'";

            List<SimulatorInfo> list = jdbcTemplate.query(sql, new RowMapper<SimulatorInfo>() {
                @Override
                public SimulatorInfo mapRow(ResultSet resultSet, int i) throws SQLException {
                    SimulatorInfo simulatorInfo = new SimulatorInfo();
                    simulatorInfo.setId(resultSet.getString("ID"));
                    simulatorInfo.setRtuCode(resultSet.getString("RTU_CODE"));
                    Timestamp st = resultSet.getTimestamp("START_TIME");
                    if (null != st) {
                        simulatorInfo.setStartTime(timeFormat.format(new Date(st.getTime())));
                    }
                    Timestamp et = resultSet.getTimestamp("END_TIME");
                    if (null != et) {
                        simulatorInfo.setEndTime(timeFormat.format(new Date(et.getTime())));
                    }
                    simulatorInfo.setDelayTime(resultSet.getString("DELAY_TIME"));
                    simulatorInfo.setRemoteIp(resultSet.getString("REMOTE_IP"));
                    simulatorInfo.setRemotePort(resultSet.getString("REMOTE_PORT"));

                    return simulatorInfo;
                }
            });
            return list;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void updateSimulatorStatus(String id, String status) {
        try {
            String sql = "select  ID from  t_d_rtu_simulator where  ID='" + id + "'";
            List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
            if (null != list && list.size() > 0) {
                SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                sql = "UPDATE  t_d_rtu_simulator  SET RUN_STATUS=?  WHERE ID =?";
                jdbcTemplate.update(sql, new PreparedStatementSetter() {
                    @Override
                    public void setValues(PreparedStatement preparedStatement) throws SQLException {
                        int index = 0;
                        preparedStatement.setString(++index, status);
                        preparedStatement.setString(++index, id);
                    }
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public SimulatorInfo getSimulatorInfo(String id) {
        try {
            SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String sql = "SELECT s.ID,s.RTU_CODE,r.RTU_NAME,p.project_name,o.ORG_NAME,s.REMOTE_IP,s.REMOTE_PORT,s.DELAY_TIME,s.START_TIME,s.END_TIME,s.RUN_STATUS ";
            sql += " FROM";
            sql += " t_d_rtu_simulator s";
            sql += " LEFT JOIN t_base_rtu_info r ON r.RTU_CD = s.RTU_CODE";
            sql += " LEFT JOIN t_base_project p ON p.id = r.PROJECT_ID";
            sql += " LEFT JOIN t_au_org o ON o.ID = p.org_id";
            sql += " WHERE s.DEL_FLAG =0";
            if (null != id && id.length() > 0) {
                sql += " AND s.ID ='" + id + "'";
            }
            List<SimulatorInfo> list = jdbcTemplate.query(sql, new RowMapper<SimulatorInfo>() {
                @Override
                public SimulatorInfo mapRow(ResultSet resultSet, int i) throws SQLException {
                    SimulatorInfo simulatorInfo = new SimulatorInfo();
                    simulatorInfo.setId(resultSet.getString("ID"));
                    simulatorInfo.setRtuCode(resultSet.getString("RTU_CODE"));
                    simulatorInfo.setRtuName(resultSet.getString("RTU_NAME"));
                    simulatorInfo.setProjectName(resultSet.getString("project_name"));
                    simulatorInfo.setOrgName(resultSet.getString("ORG_NAME"));
                    Timestamp st = resultSet.getTimestamp("START_TIME");
                    if (null != st) {
                        simulatorInfo.setStartTime(timeFormat.format(new Date(st.getTime())));
                    }
                    Timestamp et = resultSet.getTimestamp("END_TIME");
                    if (null != et) {
                        simulatorInfo.setEndTime(timeFormat.format(new Date(et.getTime())));
                    }
                    simulatorInfo.setDelayTime(resultSet.getString("DELAY_TIME"));
                    simulatorInfo.setRemoteIp(resultSet.getString("REMOTE_IP"));
                    simulatorInfo.setRemotePort(resultSet.getString("REMOTE_PORT"));
                    simulatorInfo.setRunStatus(resultSet.getString("RUN_STATUS"));

                    return simulatorInfo;
                }
            });
            if (null != list && list.size() > 0) {
                return list.get(0);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void savePostDatagramInfo(String mainId, Date sendDt, String sendDatagram, Date backDt, String backDatagram) {
        try {
            String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase();
            String sql = "INSERT INTO t_d_rtu_simulator_detail (ID,MAIN_ID,SEND_TIME,SEND_DATAGRAM,BACK_TIME,BACK_DATAGRAM,RUN_STATUS) VALUES(?,?,?,?,?,?,?)";
            jdbcTemplate.update(sql, new PreparedStatementSetter() {
                @Override
                public void setValues(PreparedStatement preparedStatement) throws SQLException {
                    int index = 0;
                    preparedStatement.setString(++index, uuid);
                    preparedStatement.setString(++index, mainId);
                    preparedStatement.setTimestamp(++index, new Timestamp(sendDt.getTime()));
                    preparedStatement.setString(++index, sendDatagram);
                    if (backDatagram != null) {
                        preparedStatement.setTimestamp(++index, new Timestamp(backDt.getTime()));
                        preparedStatement.setString(++index, backDatagram);
                        preparedStatement.setInt(++index, 1);
                    } else {
                        preparedStatement.setTimestamp(++index, null);
                        preparedStatement.setString(++index, null);
                        preparedStatement.setInt(++index, 0);
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public List<SimulatorInfo> querySendDatagramDetail(String mainId, Date sendTime) {
        String sql = "SELECT * FROM t_d_rtu_simulator_detail WHERE MAIN_ID=? AND SEND_TIME=? AND BACK_TIME is not NULL";
        List<SimulatorInfo> list = jdbcTemplate.query(sql, new PreparedStatementSetter() {
            @Override
            public void setValues(PreparedStatement preparedStatement) throws SQLException {
                int index = 0;
                preparedStatement.setString(++index, mainId);
                preparedStatement.setTimestamp(++index, new Timestamp(sendTime.getTime()));
            }
        }, new RowMapper<SimulatorInfo>() {

            @Override
            public SimulatorInfo mapRow(ResultSet resultSet, int i) throws SQLException {
                SimulatorInfo simulatorInfo = new SimulatorInfo();
                simulatorInfo.setId(resultSet.getString("ID"));
                return simulatorInfo;
            }
        });
        return list;
    }


}
