package com.persagy.server.datacenter.utils

import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.serializer.SerializerFeature
import org.apache.ibatis.type.BaseTypeHandler
import org.apache.ibatis.type.JdbcType
import org.slf4j.LoggerFactory
import java.sql.CallableStatement
import java.sql.PreparedStatement
import java.sql.ResultSet
import java.sql.SQLException

/**
 * @author 蔡云飞
 * @date 2020/6/21 11:06
 */ // 继承自BaseTypeHandler<Object> 使用Object是为了让JsonUtil可以处理任意类型
class JsonTypeHandler<T>(type: Class<T>?) : BaseTypeHandler<T>() {
    private val type: Class<T>

    @Throws(SQLException::class)
    override fun setNonNullParameter(preparedStatement: PreparedStatement, i: Int, o: T, jdbcType: JdbcType) {
        preparedStatement.setString(i, JSON.toJSONString(o, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullListAsEmpty, SerializerFeature.WriteNullStringAsEmpty))
    }

    @Throws(SQLException::class)
    override fun getNullableResult(resultSet: ResultSet, s: String): T {
        return JSON.parseObject(resultSet.getString(s), type)
    }

    @Throws(SQLException::class)
    override fun getNullableResult(resultSet: ResultSet, i: Int): T {
        return JSON.parseObject(resultSet.getString(i), type)
    }

    @Throws(SQLException::class)
    override fun getNullableResult(callableStatement: CallableStatement, i: Int): T {
        return JSON.parseObject(callableStatement.getString(i), type)
    }

    companion object {
        private val LOG = LoggerFactory.getLogger(JsonTypeHandler::class.java)
    }

    init {
        LOG.info("JsonTypeHandler($type)")
        requireNotNull(type) { "Type argument cannot be null" }
        this.type = type
    }
}