package com.persagy.dmp.mybatis.typehandler;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.util.StrUtil;
import com.persagy.dmp.common.lang.PsDateTime;
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 java.sql.*;
import java.time.format.DateTimeParseException;

/**
 * Mybatis日期时间全局处理
 * @author Charlie Yu
 * @version 1.0 2021-04-08
 */
@MappedJdbcTypes({JdbcType.CHAR, JdbcType.TIMESTAMP})
@MappedTypes(PsDateTime.class)
public class PsDateTimeTypeHandler extends BaseTypeHandler<PsDateTime> {

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, PsDateTime psDateTime, JdbcType jdbcType) throws SQLException {
        preparedStatement.setString(i, psDateTime.toString());
    }

    @Override
    public PsDateTime getNullableResult(ResultSet resultSet, String s) throws SQLException {
        String date = resultSet.getString(s);
        return formatDateTime(date);
    }

    @Override
    public PsDateTime getNullableResult(ResultSet resultSet, int i) throws SQLException {
        String date = resultSet.getString(i);
        return formatDateTime(date);
    }

    @Override
    public PsDateTime getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        String date = callableStatement.getString(i);
        return formatDateTime(date);
    }

    /**
     * 转换日期
     * @param date
     * @return
     */
    private PsDateTime formatDateTime(String date) {
        if(StrUtil.isBlank(date)) {
            return null;
        }
        try {
            return PsDateTime.parsePsDateTime(date);
        } catch (DateTimeParseException e) {
            return new PsDateTime(date, DatePattern.NORM_DATETIME_PATTERN);
        }
    }
}
