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

import java.lang.reflect.Field;
import java.sql.Statement;
import java.util.List;
import java.util.stream.Collectors;

import org.apache.ibatis.executor.resultset.ResultSetHandler;
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.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
import org.springframework.util.ReflectionUtils;

import com.huashe.park.common.animations.mybatis.Converter;
import com.huashe.park.common.animations.mybatis.ConverterCache;
import com.huashe.park.common.animations.mybatis.emuns.FieldConvert;
import com.huashe.park.common.animations.mybatis.FieldMetadataCache;

@Intercepts(@Signature(type = ResultSetHandler.class, method = "handleResultSets", args = {
    Statement.class
}))
public class ResultTypeConvertInterceptor implements Interceptor {
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object result = invocation.proceed();

        // 获取MappedStatement
        ResultSetHandler handler = (ResultSetHandler) invocation.getTarget();
        MetaObject metaObject = SystemMetaObject.forObject(handler);
        MappedStatement mappedStatement = (MappedStatement) metaObject.getValue("mappedStatement");

        // 判断是否为resultType映射
        if (mappedStatement.getResultMaps().size() == 1
            && mappedStatement.getResultMaps().get(0).getResultMappings().isEmpty()) {
            return filterResultType(result); // 仅处理resultType
        }
        return result; // 不处理resultMap
    }

    private Object filterResultType(Object result) {
        // 自定义过滤逻辑（如字段脱敏、数据转换等）
        if (result instanceof List) {
            return ((List<?>) result).stream().map(this::processBean).collect(Collectors.toList());
        }
        return processBean(result);
    }

    private Object processBean(Object bean) {
        if (bean == null) {
            return null;
        }
        Class<?> clazz = bean.getClass();
        List<Field> annotatedFields = FieldMetadataCache.getAnnotatedFields(clazz, FieldConvert.class);
        // 遍历类及父类的所有字段

        annotatedFields.forEach(field -> {
            FieldConvert annotation = field.getAnnotation(FieldConvert.class);
            if (annotation != null) {
                // 获取转换器实例（带缓存）
                Converter converter = ConverterCache.getConverter(annotation.converter());
                // 获取原始值
                Object originalValue = ReflectionUtils.getField(field, bean);
                // 执行类型转换
                Object convertedValue = converter.convert(originalValue);
                // 设置转换后的值
                ReflectionUtils.setField(field, bean, convertedValue);
            }
        }); // 包含私有字段

        return bean;
    }

}
