package com.zd.common.core.enums;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;

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

/**
 * code 作为值的转换器
 *
 * @Author: zhoupan
 * @Date: 2021/09/10/10:29
 * @Description:
 */
@MappedTypes({BaseEnum.class})
public class CodeToValueEnumTypeHandler<E extends Enum<?> & BaseEnum> extends BaseTypeHandler<BaseEnum> {

    private Class<E> type;

    public CodeToValueEnumTypeHandler(Class<E> type) {
        if (type == null) {
            throw new IllegalArgumentException("要转换的枚举类不能为空");
        }
        this.type = type;
    }


    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, BaseEnum baseEnum, JdbcType jdbcType) throws SQLException {
        if (baseEnum == null) {
            preparedStatement.setObject(i, null, jdbcType.TYPE_CODE);
            return;
        }
        if (jdbcType == null) {
            preparedStatement.setObject(i, baseEnum.getDictKey());
            return;
        }

        preparedStatement.setObject(i, baseEnum.getDictKey(), jdbcType.TYPE_CODE);
    }

    @Override
    public BaseEnum getNullableResult(ResultSet resultSet, String s) throws SQLException {
        Object code = resultSet.getObject(s);
        if (resultSet.wasNull()) {
            return null;
        }
        return BaseEnum.valueOfEnum(type, code);

    }

    @Override
    public BaseEnum getNullableResult(ResultSet resultSet, int i) throws SQLException {
        Object code = resultSet.getObject(i);
        if (resultSet.wasNull()) {
            return null;
        }

        return BaseEnum.valueOfEnum(type, code);
    }

    @Override
    public BaseEnum getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        Object code = callableStatement.getObject(i);
        if (callableStatement.wasNull()) {
            return null;
        }

        return BaseEnum.valueOfEnum(type, code);
    }
}
