package org.ts.ddcs.Service.Impl;

import com.alibaba.fastjson.JSONObject;
import org.ts.ddcs.Entity.RelayDatagramRecordEntity;
import org.ts.ddcs.Entity.RtuBaseInfo;
import org.ts.ddcs.log.LogHelper;
import org.ts.ddcs.Service.RtuService;
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.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

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


@Service("RtuService")
@Transactional
@SuppressWarnings("all")
public class RtuServiceImpl implements RtuService {

    @Autowired
    public JdbcTemplate jdbcTemplate;

    @Override
    public void saveOrUpdateRtu(RtuBaseInfo rtuBaseInfo) {
        try {
            String sql = "select  * from  t_base_rtu_info where RTU_CD='" + rtuBaseInfo.getRtuCode() + "' ";
            List<Map<String, Object>> records = jdbcTemplate.queryForList(sql);
            if (records != null && records.size() > 0) {
                sql = "UPDATE  t_base_rtu_info  SET UPDATE_TIME=?,RTU_CD_2=? ";
                sql += " WHERE RTU_CD =?";
                LogHelper.info("save or update rtu :" + sql);
                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, rtuBaseInfo.getRtuCode2());
                        preparedStatement.setString(++index, rtuBaseInfo.getRtuCode());

                    }
                });
            } else {
                sql = "INSERT INTO t_base_rtu_info (RTU_CD,RTU_CD_2,UPDATE_TIME) VALUES(?,?,?)";
                LogHelper.info("save or update rtu :" + sql);
                jdbcTemplate.update(sql, new PreparedStatementSetter() {
                    @Override
                    public void setValues(PreparedStatement preparedStatement) throws SQLException {
                        int index = 0;
                        preparedStatement.setString(++index, rtuBaseInfo.getRtuCode());
                        preparedStatement.setString(++index, rtuBaseInfo.getRtuCode2());
                        preparedStatement.setTimestamp(++index, new Timestamp(new Date().getTime()));
                    }
                });

            }

            //更新测站类型关联表
            String rtuKind = rtuBaseInfo.getRtuKind();
            if (null != rtuKind && rtuKind.length() > 0) {
                sql = "select * from t_base_rtu_kind where RTU_CODE='" + rtuBaseInfo.getRtuCode() + "'";
                List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
                if (null == list || list.size() <= 0) {
                    sql = "insert  into  t_base_rtu_kind (RTU_CODE,RTU_KIND) values (?,?)";
                    jdbcTemplate.update(sql, new PreparedStatementSetter() {
                        @Override
                        public void setValues(PreparedStatement preparedStatement) throws SQLException {
                            int index = 0;
                            preparedStatement.setString(++index, rtuBaseInfo.getRtuCode());
                            preparedStatement.setString(++index, rtuBaseInfo.getRtuKind());
                        }
                    });
                }
            }


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


    @Override
    @Transactional(rollbackFor = {Exception.class}, propagation = Propagation.REQUIRED)
    public void SaveRelayDatagramInfo(RelayDatagramRecordEntity recordEntity) {
        try {
            SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            String sql = "INSERT INTO t_b_datagram_relay (`RTU_CODE`, `DATAGRAM`, `DATAGRAM_PROCESS`, `DATAGRAM_BACK`, `COLLECT_TIME`, `PICK_TIME`, `RELAY_TIME`, `BACK_TIME`, `RELAY_RESULT`, `RELAY_IP`, `RELAY_ERROR`) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ";
            jdbcTemplate.update(sql, new PreparedStatementSetter() {
                @Override
                public void setValues(PreparedStatement preparedStatement) throws SQLException {
                    try {
                        int index = 0;
                        preparedStatement.setString(++index, recordEntity.getRtuCode());
                        preparedStatement.setString(++index, recordEntity.getDatagram());
                        preparedStatement.setString(++index, recordEntity.getDatagramProcess());
                        preparedStatement.setString(++index, recordEntity.getDatagramBack());
                        Date collectTime = null;
                        String collectTime_str = recordEntity.getCollectTime();
                        if (null != collectTime_str) {
                            collectTime = timeFormat.parse(collectTime_str);
                        }

                        if (null != collectTime) {
                            preparedStatement.setTimestamp(++index, new Timestamp(collectTime.getTime()));
                        } else {
                            preparedStatement.setTimestamp(++index, null);
                        }
                        Date pickTime = null;
                        String pickTime_str = recordEntity.getPickTime();
                        if (null != pickTime_str) {
                            pickTime = timeFormat.parse(pickTime_str);
                        }
                        if (null != pickTime) {
                            preparedStatement.setTimestamp(++index, new Timestamp(pickTime.getTime()));
                        } else {
                            preparedStatement.setTimestamp(++index, null);
                        }
                        Date relayTime = null;
                        String relayTime_str = recordEntity.getRelayTime();
                        if (null != relayTime_str) {
                            relayTime = timeFormat.parse(relayTime_str);
                        }
                        if (null != relayTime) {
                            preparedStatement.setTimestamp(++index, new Timestamp(relayTime.getTime()));
                        } else {
                            preparedStatement.setTimestamp(++index, null);
                        }

                        Date backTime = null;
                        String backTime_str = recordEntity.getBackTime();
                        if (null != backTime_str) {
                            backTime = timeFormat.parse(backTime_str);
                        }
                        if (null != backTime) {
                            preparedStatement.setTimestamp(++index, new Timestamp(backTime.getTime()));
                        } else {
                            preparedStatement.setTimestamp(++index, null);
                        }

                        preparedStatement.setString(++index, recordEntity.getRelayResult());
                        preparedStatement.setString(++index, recordEntity.getRelayIp());
                        preparedStatement.setString(++index, recordEntity.getRelayError());
                    } catch (Exception e) {

                    }
                }
            });

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

    @Override
    public List<RtuBaseInfo> rtuDataListByProjectId(String projectId) {
        try {
            String sql = "SELECT b.RTU_CD as rtuCode,b.RTU_NAME as rtuName,b.RTU_UUID as uuid,b.SIM_CD as phone,b.NT as remark ,b.PROJECT_ID as projectId ,b.ORG_CD as orgId ,p.project_name as projectName, o.ORG_NAME as orgName  FROM t_base_rtu_info b LEFT JOIN t_au_org o on o.ID = b.ORG_CD  LEFT JOIN t_base_project p on p.id = b.PROJECT_ID WHERE b.DEL='0' ";
            if (null != projectId && projectId.length() > 0) {
                sql += " AND b.PROJECT_ID ='" + projectId + "'";
            }
            sql += " ORDER BY  b.RTU_CD  ";
            List<RtuBaseInfo> list = jdbcTemplate.query(sql, new RowMapper<RtuBaseInfo>() {
                @Override
                public RtuBaseInfo mapRow(ResultSet resultSet, int i) throws SQLException {
                    RtuBaseInfo rtuBaseInfo = new RtuBaseInfo();

                    rtuBaseInfo.setRtuCode(resultSet.getString(1));
                    rtuBaseInfo.setRtuName(resultSet.getString(2));
                    rtuBaseInfo.setUuid(resultSet.getString(3));
                    rtuBaseInfo.setPhone(resultSet.getString(4));
                    rtuBaseInfo.setRemark(resultSet.getString(5));
                    rtuBaseInfo.setProjectId(resultSet.getString(6));
                    rtuBaseInfo.setOrgId(resultSet.getString(7));
                    rtuBaseInfo.setProjectName(resultSet.getString(8));
                    rtuBaseInfo.setOrgName(resultSet.getString(9));
                    return rtuBaseInfo;
                }
            });
            return list;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void updateRtuVersion(RtuBaseInfo rtuBaseInfo) {
        String sql = "UPDATE  t_base_rtu_info  SET UPDATE_TIME=?,SYS_VER=? ";
        sql += " WHERE RTU_CD =?";
        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, rtuBaseInfo.getRtuVersion());
                preparedStatement.setString(++index, rtuBaseInfo.getRtuCode());
            }
        });
    }

    @Override
    public RtuBaseInfo rtuInfo(String rtuCode) {
        try {
            String sql = "SELECT b.RTU_CD  ,b.RTU_NAME  ,b.RTU_UUID  ,b.SIM_CD  ,b.NT   ,b.PROJECT_ID   ,b.ORG_CD   ,p.project_name  , o.ORG_NAME,b.LOCATION_LAT,b.LOCATION_LON    FROM t_base_rtu_info b LEFT JOIN t_au_org o on o.ID = b.ORG_CD  LEFT JOIN t_base_project p on p.id = b.PROJECT_ID WHERE b.DEL='0' ";
            if (null != rtuCode && rtuCode.length() > 0) {
                sql += " AND b.RTU_CD ='" + rtuCode + "'";
            }
            sql += " ORDER BY  b.RTU_CD  ";
            List<RtuBaseInfo> list = jdbcTemplate.query(sql, new RowMapper<RtuBaseInfo>() {
                @Override
                public RtuBaseInfo mapRow(ResultSet resultSet, int i) throws SQLException {
                    RtuBaseInfo rtuBaseInfo = new RtuBaseInfo();
                    rtuBaseInfo.setRtuCode(resultSet.getString(1));
                    rtuBaseInfo.setRtuName(resultSet.getString(2));
                    rtuBaseInfo.setUuid(resultSet.getString(3));
                    rtuBaseInfo.setPhone(resultSet.getString(4));
                    rtuBaseInfo.setRemark(resultSet.getString(5));
                    rtuBaseInfo.setProjectId(resultSet.getString(6));
                    rtuBaseInfo.setOrgId(resultSet.getString(7));
                    rtuBaseInfo.setProjectName(resultSet.getString(8));
                    rtuBaseInfo.setOrgName(resultSet.getString(9));
                    rtuBaseInfo.setLat(resultSet.getString(10));
                    rtuBaseInfo.setLng(resultSet.getString(11));
                    return rtuBaseInfo;
                }
            });
            if (null != list && list.size() > 0) {
                return list.get(0);
            }

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

    @Override
    public List<RtuBaseInfo> cameraStation() {
        String sql = "SELECT r.RTU_CD FROM t_base_rtu_info r";
        sql += " LEFT JOIN t_base_rtu_run_setting s  on s.RTU_CODE = r.RTU_CD";
        sql += " WHERE s.CAMERA_ACTIVE is not null AND s.CAMERA_ACTIVE='1'";
        List<RtuBaseInfo> list = jdbcTemplate.query(sql, new RowMapper<RtuBaseInfo>() {
            @Override
            public RtuBaseInfo mapRow(ResultSet resultSet, int i) throws SQLException {
                RtuBaseInfo info = new RtuBaseInfo();
                info.setRtuCode(resultSet.getString("RTU_CD"));
                return info;
            }
        });
        return list;
    }
}
