package vip.xiaonuo.coldchain.core.handler;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
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.ArrayList;
import java.util.List;

@Slf4j
@MappedJdbcTypes(JdbcType.VARCHAR)
@MappedTypes({List.class})
public class IntegerListTypeHandler extends BaseTypeHandler<List<Integer>> {

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, List<Integer> ts, JdbcType jdbcType) throws SQLException {
        String content = (ts == null || ts.isEmpty()) ? null : toJSONString(ts);  // 将 List 转换为 JSON 字符串
        preparedStatement.setString(i, content);  // 存储为 VARCHAR 类型
    }

    @Override
    public List<Integer> getNullableResult(ResultSet resultSet, String s) throws SQLException {
        try {
            String content = resultSet.getString(s);
            return this.getListByJsonArrayString(content);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<Integer> getNullableResult(ResultSet resultSet, int i) throws SQLException {
        try {
            String content = resultSet.getString(i);
            return this.getListByJsonArrayString(content);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<Integer> getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        try {
            String content = callableStatement.getString(i);
            return this.getListByJsonArrayString(content);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    public List<Integer> getListByJsonArrayString(String content) throws JsonProcessingException {
        if (StrUtil.isEmpty(content)) {
            return new ArrayList<>();
        } else {
            return new ObjectMapper().readValue(content, new TypeReference<List<Integer>>() {});  // 反序列化为 List<Integer>
        }
    }

    /**
     * 将对象转换为 JSON 字符串
     */
    public String toJSONString(Object obj) {
        try {
            return (obj == null) ? null : JSONUtil.toJsonStr(obj);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
