package com.huashe.park.infrastructure.cfg.mybatis;

import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;

@Intercepts(@Signature(
        type = Executor.class,
        method = "query",
        args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}
))
public class FieldConvertInterceptor implements Interceptor {
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        // 执行原始查询逻辑
        Object result = invocation.proceed();

        // 处理结果集中的JSON字段
//        if (result instanceof List) {
//            ((List<?>) result).forEach(this::processJsonFields);
//        } else if (result != null) {
//            processJsonFields(result);
//        }
        return result;
    }
//
//    private void processJsonFields(Object obj) {
//        // 反射遍历所有标记@JsonField的字段
//        Arrays.stream(obj.getClass().getDeclaredFields())
//                .filter(f -> f.isAnnotationPresent(FieldConvert.class))
//                .forEach(f -> {
//                    try {
//                        f.setAccessible(true);
//                        String jsonValue = (String) f.get(obj);
//                        if (jsonValue != null) {
//                            JsonData data = new ObjectMapper().readValue(jsonValue, JsonData.class);
//                            f.set(obj, data);
//                        }
//                    } catch (Exception e) {
//                        throw new RuntimeException("JSON字段处理失败", e);
//                    }
//                });
//    }

}
