package com.njzscloud.common.mp.support.handler.j;

import cn.hutool.core.util.StrUtil;
import com.njzscloud.common.core.fastjson.Fastjson;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;

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

/**
 * Json 类型处理器
 */
@Slf4j
@MappedTypes({Object.class})
@MappedJdbcTypes({JdbcType.VARCHAR})
public class JsonTypeHandler implements TypeHandler<Object> {

    @Override
    public void setParameter(PreparedStatement ps, int i, Object parameter, JdbcType jdbcType) throws SQLException {
        if (parameter == null) ps.setNull(i, jdbcType.TYPE_CODE);
        else ps.setString(i, Fastjson.toJsonStr(parameter));

    }

    private static Object getResult(String result) {
        if (StrUtil.isBlank(result)) return null;
        try {
            return Fastjson.toBean(result, Object.class);
        } catch (Exception e) {
            return result;
        }
    }

    @Override
    public Object getResult(ResultSet rs, String columnName) throws SQLException {
        String result = rs.getString(columnName);
        return getResult(result);
    }

    @Override
    public Object getResult(ResultSet rs, int columnIndex) throws SQLException {
        String result = rs.getString(columnIndex);
        return getResult(result);
    }

    @Override
    public Object getResult(CallableStatement cs, int columnIndex) throws SQLException {
        String result = cs.getString(columnIndex);
        return getResult(result);
    }
}
