package com.ruoyi.demo.typehander;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.springframework.stereotype.Component;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;

/*java LocalDataTime 和 mysql dataTime 类型对接*/
/*1.LocalDateTime 转换成 String*/
@Component
public class LocalDateTimeToDataTime extends BaseTypeHandler<LocalDateTime> {
    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, LocalDateTime localDateTime, JdbcType jdbcType) throws SQLException {
        //"yyyy-mm-dd hh:mm:ss"
        LocalDateTime localDateTime1 = localDateTime.atZone(ZoneId.of("Asia/Shanghai")).toLocalDateTime();
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        preparedStatement.setString(i,dateTimeFormatter.format(localDateTime1));
    }

    @Override
    public LocalDateTime getNullableResult(ResultSet resultSet, String s) throws SQLException {
        String dateAndTime = resultSet.getString(s);
        if(dateAndTime == null){
            return null;
        }
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(ZoneId.of("Asia/Shanghai"));  //注意：HH是24小时制 hh是12小时制
        LocalDateTime parse = LocalDateTime.parse(dateAndTime, dateTimeFormatter);
        return parse;
    }

    @Override
    public LocalDateTime getNullableResult(ResultSet resultSet, int i) throws SQLException {
        String dateAndTime = resultSet.getString(i);
        if(dateAndTime == null){
            return null;
        }
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(ZoneId.of("Asia/Shanghai"));  //注意：HH是24小时制 hh是12小时制
        LocalDateTime parse = LocalDateTime.parse(dateAndTime, dateTimeFormatter);
        return parse;
    }

    @Override
    public LocalDateTime getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        String dateAndTime = callableStatement.getString(i);
        if(dateAndTime == null){
            return null;
        }
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(ZoneId.of("Asia/Shanghai"));  //注意：HH是24小时制 hh是12小时制
        LocalDateTime parse = LocalDateTime.parse(dateAndTime, dateTimeFormatter);
        return parse;
    }
}
