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

import cn.hutool.core.util.StrUtil;
import com.njzscloud.common.core.fastjson.Fastjson;
import com.njzscloud.common.core.ienum.DictItem;
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({DictItem.class})
@MappedJdbcTypes({JdbcType.VARCHAR})
public class DictItemTypeHandler implements TypeHandler<DictItem> {

    private static DictItem getResult(String result) {
        if (StrUtil.isBlank(result)) return null;
        try {
            return Fastjson.toBean(result, DictItem.class);
        } catch (Exception e) {
            log.error("JSON 格式数据映射失败", e);
            return null;
        }
    }

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

    }

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

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

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