package com.ruoyi.biemo.elasticsearch.util;

import com.ruoyi.biemo.elasticsearch.annotation.FieldInfo;
import com.ruoyi.biemo.elasticsearch.entity.FieldMapping;
import com.ruoyi.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class ElasticSearchUtils {

    public static List<FieldMapping>  getFieldInfo(Class clazz){
        return getFieldInfo(clazz,null);
    }

    private static List<FieldMapping> getFieldInfo(Class clazz, String fieldName){
        Field[] fields = clazz.getDeclaredFields();
        List<FieldMapping> fieldMappingList= new ArrayList<>();
        for(Field field:fields){
            FieldInfo fieldInfo = field.getAnnotation(FieldInfo.class);
            if(fieldInfo==null){
                continue;
            }
            if("object".equals(fieldInfo.type())){
                Class fc = field.getType();
                if(fc.isPrimitive()){ //如果是基本数据类型
                    String name = field.getName();
                    if(StringUtils.isNotBlank(fieldName)){
                        name = name+"."+fieldName;
                    }
                    fieldMappingList.add(new FieldMapping(name,fieldInfo.type(),fieldInfo.participle(), fieldInfo.ignoreAbove()));
                }else{
                    if(fc.isAssignableFrom(List.class)){ //判断是否为List
                        System.out.println("List类型：" + field.getName());
                        Type gt = field.getGenericType();    //得到泛型类型
                        ParameterizedType pt = (ParameterizedType)gt;
                        Class lll = (Class)pt.getActualTypeArguments()[0];
                        fieldMappingList.addAll(getFieldInfo(lll,field.getName()));
                    }else{
                        fieldMappingList.addAll(getFieldInfo(fc,field.getName()));
                    }
                }
            }else{
                String name = field.getName();
                if(StringUtils.isNotBlank(fieldName)){
                    name = fieldName+"."+name;
                }
                fieldMappingList.add(new FieldMapping(name,fieldInfo.type(),fieldInfo.participle(), fieldInfo.ignoreAbove()));
            }
        }
        return fieldMappingList;
    }
}
