package com.xjrsoft.common.handler;

import oracle.sql.TIMESTAMP;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.LocalDateTimeTypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.time.LocalDateTime;

public class MyLocalDateTimeTypeHandler extends LocalDateTimeTypeHandler {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, LocalDateTime parameter, JdbcType jdbcType)
            throws SQLException {
        ps.setObject(i, Timestamp.valueOf(parameter));
    }

    @Override
    public LocalDateTime getNullableResult(ResultSet rs, String columnName) throws SQLException {
        Object object = rs.getObject(columnName);
        return getLocalDateTime(object);
    }

    @Override
    public LocalDateTime getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        Object object = rs.getObject(columnIndex);
        return getLocalDateTime(object);
    }

    @Override
    public LocalDateTime getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        Object object = cs.getObject(columnIndex);
        return getLocalDateTime(object);
    }

    private static LocalDateTime getLocalDateTime(Object object) throws SQLException {
        if (object instanceof LocalDateTime) {
            return (LocalDateTime) object;
        } else if(object instanceof Timestamp){//在这里强行转换，将sql的时间转换为LocalDateTime
            return ((Timestamp)object).toLocalDateTime();
        } else  if (object instanceof TIMESTAMP) {
            return ((TIMESTAMP) object).timestampValue().toLocalDateTime();
        }
        return null;
    }
}
