package com.ho.business.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import jodd.util.StringUtil;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

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

/**
 * @描述 JSON字段处理器
 * @创建人 fancl
 * @创建时间 2021/10/21
 * @修改人
 */

public class JsonHandler extends BaseTypeHandler<JSONObject> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, JSONObject detail, JdbcType jdbcType) throws SQLException {
        String jsonString = JSONObject.toJSONString(detail);
        Object parse = JSON.parse(jsonString);
        String targetStr = parse.toString();

        ps.setString(i, targetStr);
    }


    /**
     * 根据列明 获取可以为空的结果
     *
     * @param rs
     * @param columnName
     * @return
     * @throws SQLException
     */
    @Override
    public JSONObject getNullableResult(ResultSet rs, String columnName) throws SQLException {
        //原始的字符串
        JSONObject detail = null;
        String columnStr = rs.getString(columnName);
        String jsonString = JSONObject.toJSONString(columnStr);
        //不为空才转换
        if (!StringUtil.isBlank(columnStr)) {
            detail = JSONObject.parseObject(columnStr, JSONObject.class);
        }
        return detail;
    }

    /**
     * 根据列索引 查找列内容
     *
     * @param rs
     * @param columnIndex
     * @return
     * @throws SQLException
     */
    @Override
    public JSONObject getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        JSONObject detail = null;
        String columnStr = rs.getString(columnIndex);
        if (!StringUtil.isBlank(columnStr)) {
            detail = JSONObject.parseObject(columnStr, JSONObject.class);
        }
        return detail;
    }

    /**
     * 根据列索引 获取内容
     *
     * @param callableStatement
     * @param columnIndex
     * @return
     * @throws SQLException
     */
    @Override
    public JSONObject getNullableResult(CallableStatement callableStatement, int columnIndex) throws SQLException {
        JSONObject detail = null;
        String columnStr = callableStatement.getString(columnIndex);
        if (!StringUtil.isBlank(columnStr)) {
            detail = JSONObject.parseObject(columnStr, JSONObject.class);
        }
        return detail;
    }
}
