package org.ts.ddcs.business.lkszy.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.business.lkszy.entity.FlowRateEntity;
import org.ts.ddcs.business.lkszy.service.LkszyService;

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


/**
 * 数据入库实现类
 */
@Service("SzyService")
public class LkszyServiceImpl implements LkszyService {

    @Autowired
    private JdbcTemplate jdbcTemplate;


    @Override
    public List<FlowRateEntity> lastDetail(String rtuCode, Date tm) {
        String sql = "SELECT r.MP_CD ,r.MP_Q,r.ACC_W,r.MP_Q_2,r.ACC_W_2,r.TM,r.TS ,b.RTU_NAME,p.id,p.project_name FROM wr_mp_q_r  r LEFT JOIN t_base_rtu_info b ON b.RTU_CD = r.MP_CD LEFT JOIN t_base_project p ON p.ID = b.PROJECT_ID WHERE 1=1 ";
        sql += " AND  r.MP_CD = ? ";
        sql += " AND  r.TM > ? ";
        sql += " ORDER BY  r.TM";
        List<FlowRateEntity> list = jdbcTemplate.query(sql, new PreparedStatementSetter() {
            @Override
            public void setValues(PreparedStatement preparedStatement) throws SQLException {
                int index = 1;
                preparedStatement.setString(index++, rtuCode);
                preparedStatement.setTimestamp(index++, new Timestamp(tm.getTime()));
            }
        }, new RowMapper<FlowRateEntity>() {
            @Override
            public FlowRateEntity mapRow(ResultSet resultSet, int i) throws SQLException {
                FlowRateEntity flowRateEntity = new FlowRateEntity();
                flowRateEntity.setMpCode(resultSet.getString("MP_CD"));
                flowRateEntity.setInstantFlowrateFirst(resultSet.getString("MP_Q"));
                flowRateEntity.setAccFlowrateFirst(resultSet.getString("ACC_W"));
                flowRateEntity.setInstantFlowrateSecond(resultSet.getString("MP_Q_2"));
                flowRateEntity.setAccFlowrateSecond(resultSet.getString("ACC_W_2"));
                flowRateEntity.setTm(resultSet.getTimestamp("TM"));
                flowRateEntity.setTs(resultSet.getTimestamp("TS"));
                return flowRateEntity;
            }
        });

        return list;
    }
}
