package com.seer.teach.common.advice;

import com.github.houbb.opencc4j.util.ZhConverterUtil;
import com.seer.teach.common.ResultBean;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: Captain
 * @Description: 繁体转简体
 * @Date: 2025-06-09 14:12
 */
@RestControllerAdvice(basePackages = "com.seer.teach.controller") // 改成你的 controller 包路径
public class SimplifiedChineseAdviceConfig implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        // 所有响应都处理
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body,
                                  MethodParameter returnType,
                                  MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                  org.springframework.http.server.ServerHttpRequest request,
                                  org.springframework.http.server.ServerHttpResponse response) {

        if (body instanceof ResultBean) {
            ResultBean<?> result = (ResultBean<?>) body;
            Object data = result.getData();
            if (data != null) {
                Object simplified = convertToSimplifiedChinese(data);
                return new ResultBean<>(result.getCode(), result.getMsg(), simplified);
            }
        }

        return body;
    }

    private Object convertToSimplifiedChinese(Object obj) {
        if (obj instanceof String) {
            return ZhConverterUtil.toSimple((String) obj);
        }

        if (obj instanceof List) {
            List<?> list = (List<?>) obj;
            List<Object> newList = new ArrayList<>();
            for (Object item : list) {
                newList.add(convertToSimplifiedChinese(item));
            }
            return newList;
        }

        if (obj instanceof Map) {
            Map<?, ?> map = (Map<?, ?>) obj;
            Map<Object, Object> newMap = new HashMap<>();
            for (Map.Entry<?, ?> entry : map.entrySet()) {
                newMap.put(entry.getKey(), convertToSimplifiedChinese(entry.getValue()));
            }
            return newMap;
        }

        // 处理数组
        if (obj.getClass().isArray()) {
            Object[] array = (Object[]) obj;
            Object[] newArray = new Object[array.length];
            for (int i = 0; i < array.length; i++) {
                newArray[i] = convertToSimplifiedChinese(array[i]);
            }
            return newArray;
        }

        // 处理自定义对象字段（只处理非 JDK 类）
        if (!obj.getClass().getName().startsWith("java")) {
            Field[] fields = obj.getClass().getDeclaredFields();
            for (Field field : fields) {
                field.setAccessible(true);
                try {
                    Object value = field.get(obj);
                    if (value != null) {
                        Object newValue = convertToSimplifiedChinese(value);
                        field.set(obj, newValue);
                    }
                } catch (Exception ignored) {
                }
            }
        }

        return obj;
    }
}