package com.bohuikeji.frame.module.admin.utils;

import com.bohuikeji.frame.module.admin.annotation.TableKeyField;
import com.bohuikeji.frame.module.admin.base.EntityBase;
import com.bohuikeji.frame.module.admin.entity.sys.SysRole;
import org.apache.http.HttpEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * 实体工具类
 * @author 10552
 */
public final class EntityUtils {
    protected static transient Logger log = LoggerFactory.getLogger(ReflectUtil.class);
    private static Map<String,String> tableKeys=new HashMap<>(5);
    private static final String SQL="SELECT column_name FROM INFORMATION_SCHEMA.`KEY_COLUMN_USAGE` WHERE table_schema={0} and table_name={1} AND constraint_name='PRIMARY'";


    /**
     * 获取实体外键字段的关联类
     * @param objClass
     * @param fieldName
     * @return
     */
    public static Class<? extends EntityBase> getKeyClass(Class<? extends EntityBase> objClass,String fieldName){
        try {
            Field field=objClass.getDeclaredField(fieldName);
            field.setAccessible(true);
            TableKeyField tableKeyField=field.getAnnotation(TableKeyField.class);
            if (tableKeyField==null){
                log.error("外键无法识别，请为[{},{}]字段配置TableKeyField注解",objClass.getName(),fieldName);
                return null;
            }

            if (tableKeyField.key()==EntityBase.class){
                log.error("字段[{},{}]外键配置错误,无法识别关联实体",objClass.getName(),fieldName);
                return null;
            }
            return tableKeyField.key();

        } catch (NoSuchFieldException e) {
            log.error("未找到字段[{}.{}]",objClass.getName(),fieldName);
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取注解
     * @param objClass
     * @param fieldName
     * @param tClass
     * @param <T>
     * @return
     */
    public static <T extends Annotation> T getAnnotation(Class<? extends EntityBase> objClass, String fieldName, Class<T> tClass){
        Field field= null;
        try {
            field = objClass.getDeclaredField(fieldName);
            field.setAccessible(true);
            return field.getAnnotation(tClass);
        } catch (NoSuchFieldException e) {
            log.error("字段[{},{}]外键配置错误,无法识别关联实体",objClass.getName(),fieldName);
            e.printStackTrace();
            return null;
        }

    }

    /**
     * 查询指定表的主键字段名称
     * @param tableName
     * @return
     */
    public static String getTableKey(String tableName){
        if (StringUtils.isBlank(tableKeys.get(tableName))){
            String id_column=(String)new SysRole().sql().selectObj(SQL,SpringUtil.getProperty("tools.dbName"),tableName);
            tableKeys.put(tableName,id_column);
        }
        return tableKeys.get(tableName);
    }


    public static String toString(HttpEntity entity, String s) {
        return entity+s;
    }
}
