package com.ruoyi.framework.config.handler;


import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONWriter;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

/**
 * @author fuwu314
 * @describe：mysqlJson类型处理类
 * @date 2024/9/18
 */
@MappedTypes(value = {JSONObject.class, JSONArray.class})
public class MySqlJsonHandler<T extends Object> extends BaseTypeHandler<T> {
    private final static Logger log = LoggerFactory.getLogger(MySqlJsonHandler.class);
    private Class<T> clazz;

    public MySqlJsonHandler(Class<T> clazz) {
        if (clazz == null) throw new IllegalArgumentException("Type argument cannot be null");
        this.clazz = clazz;
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, this.toJson(parameter));
    }

    @Override
    public T getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return this.toObject(rs.getString(columnName), clazz);
    }

    @Override
    public T getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return this.toObject(rs.getString(columnIndex), clazz);
    }

    @Override
    public T getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return this.toObject(cs.getString(columnIndex), clazz);
    }

    /**
     * 将字符串内容转换为指定类型的对象
     *
     * @param content 字符串内容
     * @param clazz   目标类型
     * @return 目标类型的对象
     */
    private T toObject(String content, Class<T> clazz) {
        if (content != null && !content.isEmpty()) {
            try {
                return JSON.parseObject(content, clazz);
            } catch (Exception e) {
                log.error("解析JSON字符串出错", e);
                return null;
            }
        } else {
            return null;
        }
    }

    /**
     * 将对象转换为JSON字符串
     *
     * @param object 要转换的对象
     * @return JSON字符串
     * @throws RuntimeException 如果转换过程中发生异常
     */
    private String toJson(T object) {
        try {
            return JSON.toJSONString(object, JSONWriter.Feature.WriteMapNullValue);
        } catch (Exception e) {
            log.error("解析JSON字符串出错", e);
            return "[]";
        }
    }


}
