package com.backendsys.config.Mybatis.handler.timezone;

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

import java.sql.*;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;

@MappedTypes(LocalDateTime.class)
@MappedJdbcTypes(JdbcType.VARCHAR)   // 关键：对应数据库 VARCHAR
@Component
public class LocalDateTimeHandler extends BaseTypeHandler<LocalDateTime> {

    private static final DateTimeFormatter FMT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    /* ====== 写入：LocalDateTime -> VARCHAR ====== */
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i,
                                    LocalDateTime parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, parameter.format(FMT));
    }

    /* 允许 null */
    @Override
    public void setParameter(PreparedStatement ps, int i,
                             LocalDateTime parameter, JdbcType jdbcType) throws SQLException {
        if (parameter == null) {
            ps.setNull(i, Types.VARCHAR);
        } else {
            super.setParameter(ps, i, parameter, jdbcType);
        }
    }

    /* ====== 读取：VARCHAR -> LocalDateTime ====== */
    @Override
    public LocalDateTime getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return strToLocalDateTime(rs.getString(columnName));
    }

    @Override
    public LocalDateTime getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return strToLocalDateTime(rs.getString(columnIndex));
    }

    @Override
    public LocalDateTime getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return strToLocalDateTime(cs.getString(columnIndex));
    }

    private LocalDateTime strToLocalDateTime(String val) {
        if (val == null || val.trim().isEmpty()) {
            return null;
        }
        // 按自己的格式解析
        return LocalDateTime.parse(val.trim(), FMT)
                .atZone(ZoneId.of("UTC"))
                .withZoneSameInstant(ZoneId.of(TimezoneContextHolder.getTimeZone()))
                .toLocalDateTime();
    }
}