package com.ylx.common.aspect;

import com.ylx.common.annotation.EnumTranslate;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collection;

@Aspect
@Component
@Order(Ordered.HIGHEST_PRECEDENCE + 1)
public class EnumTranslateAspect {

    // 【改成你自己的 controller 包路径】
    @Pointcut("execution(public * com.ylx.web.controller..*.*(..))")
    public void pointcut() {}

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        Object result = point.proceed();
        if (result == null) return null;

        // 全局翻译：支持 单个对象 / List / 分页对象
        translate(result);
        return result;
    }

    // ==========================================
    // 核心方法：递归翻译所有类型
    // ==========================================
    private void translate(Object obj) {
        if (obj == null) return;

        // 1. 集合 List Set
        if (obj instanceof Collection) {
            ((Collection<?>) obj).forEach(this::translate);
            return;
        }

        // 2. 分页对象（这里是关键！自动提取分页里的 rows）
        Class<?> clazz = obj.getClass();
        try {
            // 通用分页字段：rows / list / data 三个都兼容
            for (String fieldName : Arrays.asList("rows", "list", "data")) {
                Field listField = clazz.getDeclaredField(fieldName);
                listField.setAccessible(true);
                Object listObj = listField.get(obj);
                if (listObj instanceof Collection) {
                    translate(listObj);
                }
            }
        } catch (NoSuchFieldException ignored) {
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 3. 翻译当前对象自身的字段
        translateFields(obj);
    }

    // ==========================================
    // 翻译单个对象的枚举字段
    // ==========================================
    private void translateFields(Object obj) {
        Field[] fields = obj.getClass().getDeclaredFields();
        for (Field field : fields) {
            EnumTranslate anno = field.getAnnotation(EnumTranslate.class);
            if (anno == null) continue;

            try {
                field.setAccessible(true);
                Object code = field.get(obj);
                if (code == null) continue;

                // 拿到枚举描述
                String desc = getEnumDesc(
                        anno.enumClass(),
                        code,
                        anno.codeMethod(),
                        anno.descMethod()
                );

                // 自动赋值给 statusDesc
                Field descField = obj.getClass().getDeclaredField(field.getName() + "Desc");
                descField.setAccessible(true);
                descField.set(obj, desc);
            } catch (NoSuchFieldException ignored) {
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    // ==========================================
    // 根据code获取枚举描述
    // ==========================================
    private String getEnumDesc(Class<? extends Enum<?>> enumClass, Object code, String codeMethod, String descMethod) {
        try {
            Method getCode = enumClass.getMethod(codeMethod);
            Method getDesc = enumClass.getMethod(descMethod);

            for (Enum<?> e : enumClass.getEnumConstants()) {
                Object enumCode = getCode.invoke(e);
                if (enumCode.equals(code)) {
                    return String.valueOf(getDesc.invoke(e));
                }
            }
        } catch (Exception ignored) {}
        return "";
    }
}
