package jnpf.attendance.handler;

import cn.hutool.core.collection.CollUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

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

public class JsonToListTypeHandler extends BaseTypeHandler<List<Object>> {
    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, List<Object> parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, toJson(parameter));
    }

    @Override
    public List<Object> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        List<Object> list = parseJson(rs.getString(columnName));
        if(CollUtil.isEmpty(list)){
            return null;
        }
        // 删除掉为空的数据
        list.removeIf(Objects::isNull);
        return list;
    }

    @Override
    public List<Object> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        List<Object> list = parseJson(rs.getString(columnIndex));
        if(CollUtil.isEmpty(list)){
            return null;
        }
        // 删除掉为空的数据
        list.removeIf(Objects::isNull);
        return list;
    }

    @Override
    public List<Object> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        List<Object> list = parseJson(cs.getString(columnIndex));
        if(CollUtil.isEmpty(list)){
            return null;
        }
        // 删除掉为空的数据
        list.removeIf(Objects::isNull);
        return list;
    }

    private String toJson(List<Object> list) {
        try {
            return OBJECT_MAPPER.writeValueAsString(list);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private List<Object> parseJson(String json) {
        try {
            if (json == null || json.isEmpty()) {
                return null;
            }
            List<Object> result = OBJECT_MAPPER.readValue(json,
                    OBJECT_MAPPER.getTypeFactory().constructCollectionType(List.class, Object.class)
            );
            return result.stream()
                    .filter(Objects::nonNull)
                    .flatMap(item -> {
                        if (item instanceof List) {
                            List<?> itemList = (List<?>) item;
                            return itemList.stream().filter(Objects::nonNull);
                        } else {
                            return java.util.stream.Stream.of(item);
                        }
                    }).collect(java.util.stream.Collectors.toList());
        } catch (Exception e) {
            throw new RuntimeException("JSON解析失败: " + json, e);
        }
    }
}