package com.xjrsoft.common.handler;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.extension.toolkit.JdbcUtils;
import com.xjrsoft.common.utils.LocalDateTimeUtil;
import oracle.sql.INTERVALDS;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalTime;

public class XjrLocalTimeTypeHandler extends BaseTypeHandler<LocalTime> {
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, LocalTime localTime, JdbcType jdbcType)
            throws SQLException {
        DbType dbType = JdbcUtils.getDbType(ps.getConnection().getMetaData().getURL());
        if (dbType == DbType.ORACLE || dbType == DbType.ORACLE_12C) {
            // oracle时间类型处理
            ps.setObject(i, new INTERVALDS(StringPool.ZERO + StringPool.SPACE + LocalDateTimeUtil.format(localTime) + StringPool.DOT + StringPool.ZERO));
        } else {
            ps.setObject(i, localTime);
        }
    }

    @Override
    public LocalTime getNullableResult(ResultSet rs, String columnName) throws SQLException {
        Object object = rs.getObject(columnName);
        if (object == null) {
            return null;
        }
        if (object instanceof INTERVALDS) {
            return LocalDateTimeUtil.convertIntervalToLocalTime((INTERVALDS) object);
        }
        return rs.getObject(columnName, LocalTime.class);
    }

    @Override
    public LocalTime getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        Object object = rs.getObject(columnIndex);
        if (object == null) {
            return null;
        }
        if (object instanceof INTERVALDS) {
            return LocalDateTimeUtil.convertIntervalToLocalTime((INTERVALDS) object);
        }
        return rs.getObject(columnIndex, LocalTime.class);
    }

    @Override
    public LocalTime getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        Object object = cs.getObject(columnIndex);
        if (object == null) {
            return null;
        }
        if (object instanceof INTERVALDS) {
            return LocalDateTimeUtil.convertIntervalToLocalTime((INTERVALDS) object);
        }
        return cs.getObject(columnIndex, LocalTime.class);
    }
}
