package com.ruoyi.common.typehandler;


import com.ruoyi.common.utils.JsonUtils;
import jodd.util.StringUtil;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

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

/**
 * Created By Mack on 2021/3/17
 */
@MappedJdbcTypes(JdbcType.VARCHAR) // 数据库中该字段存储的类型
@MappedTypes(List.class) // 需要转换的对象
public class ListToStringTypeHandler extends BaseTypeHandler<List<String>> {

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, List<String> objList, JdbcType jdbcType) throws SQLException {
        String json = JsonUtils.toJsonString(objList);
        preparedStatement.setObject(i, json);
    }

    @Override
    public List<String> getNullableResult(ResultSet resultSet, String columnName) throws SQLException {
        String value = resultSet.getString(columnName);
        return getObjs(value);
    }


    @Override
    public List<String> getNullableResult(ResultSet resultSet, int i) throws SQLException {
        String value = resultSet.getString(i);

        return getObjs(value);
    }

    @Override
    public List<String> getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        String value = callableStatement.getString(i);

        return getObjs(value);
    }

    private List<String> getObjs(String value) {
        if (StringUtil.isNotBlank(value)) {
            return JsonUtils.parseArray(value, String.class);
        }

        return null;
    }
}

