package com.pictc.utils;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;


@SuppressWarnings("rawtypes")
public class MybatisTools implements ApplicationContextAware {
	
	 /**
     * 	存储Mapper类与实体类的映射关系
     * key: Mapper接口的Class对象
     * value: 对应的实体类的Class对象
     */
    private static final Map<Class<?>,BaseMapper<?>> ENTITY_MAPPER_MAP = new HashMap<>();

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        // 获取所有继承自BaseMapper的接口（即MyBatis-Plus的Mapper接口）
        
		Map<String, BaseMapper> mapperBeans = applicationContext.getBeansOfType(BaseMapper.class);
        
        for (BaseMapper<?> mapper : mapperBeans.values()) {
            // 获取Mapper接口的Class对象（因为mapper是代理对象，需要获取原始接口）
            Class<?> mapperInterface = getMapperInterface(mapper.getClass());
            
            // 解析Mapper接口对应的实体类
            Class<?> entityClass = resolveEntityClass(mapperInterface);
            
            if (entityClass != null) {
                ENTITY_MAPPER_MAP.put(entityClass, mapper);
            }
        }
        System.out.println(ENTITY_MAPPER_MAP);
    }

    /**
     * 	获取Mapper代理对象对应的原始接口
     */
    private Class<?> getMapperInterface(Class<?> mapperProxyClass) {
        // MyBatis的Mapper代理类会实现对应的Mapper接口
        Class<?>[] interfaces = mapperProxyClass.getInterfaces();
        for (Class<?> iface : interfaces) {
            // 判断是否是BaseMapper的子类
            if (BaseMapper.class.isAssignableFrom(iface) && iface != BaseMapper.class) {
                return iface;
            }
        }
        return mapperProxyClass;
    }

    /**
     * 	解析Mapper接口对应的实体类（通过泛型参数）
     */
    private Class<?> resolveEntityClass(Class<?> mapperInterface) {
        // 获取Mapper接口的泛型父类（BaseMapper<T>）
        Type[] genericInterfaces = mapperInterface.getGenericInterfaces();
        for (Type genericInterface : genericInterfaces) {
            if (genericInterface instanceof ParameterizedType) {
                ParameterizedType parameterizedType = (ParameterizedType) genericInterface;
                // 检查是否是BaseMapper
                if (parameterizedType.getRawType() == BaseMapper.class) {
                    // 获取泛型参数T（即实体类）
                    Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
                    if (actualTypeArguments.length > 0 && actualTypeArguments[0] instanceof Class) {
                        return (Class<?>) actualTypeArguments[0];
                    }
                }
            }
        }
        return null;
    }



    /**
     * 	根据实体类获取对应的Mapper类
     */
    public static BaseMapper<?> getMapper(Class<?> entityClass) {
        return ENTITY_MAPPER_MAP.get(entityClass);
    }
    
    
    public static TableInfo getTableInfo(Class<?> entityClass) {
    	return TableInfoHelper.getTableInfo(entityClass);
    }
    
    public static TableInfo getTableInfo(String tablename) {
    	return TableInfoHelper.getTableInfo(tablename);
    }


}
