package com.ruoyi.aspect;

import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import lombok.RequiredArgsConstructor;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;

@Aspect
@Component
@RequiredArgsConstructor
public class InsertAspect {

    @Around("execution(* com.ruoyi.business.controller.*.*insert*(..))")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        // 获取目标方法的参数
        Object[] args = joinPoint.getArgs();

        // 遍历参数，查找包含 areaAuthCode 字段的对象
        for (Object arg : args) {
            if (hasAreaAuthCodeField(arg)) {

                LoginUser userinfo = SecurityUtils.getLoginUser();
                String authCode = userinfo.getUser().getAreaAuthCode();
                // 对包含 areaAuthCode 字段的对象进行处理
                setAreaAuthCode(arg, authCode);
            }
        }

        // 执行目标方法
        return joinPoint.proceed();
    }

    // 判断对象是否包含 areaAuthCode 字段
    private boolean hasAreaAuthCodeField(Object obj) {
        Class<?> clazz = obj.getClass();
        try {
            // 使用反射获取对象的字段
            Field areaAuthCodeField = clazz.getDeclaredField("areaAuthCode");
            return areaAuthCodeField != null;
        } catch (NoSuchFieldException e) {
            return false;
        }
    }

    // 设置对象的 areaAuthCode 字段的值
    private void setAreaAuthCode(Object obj, String value) {
        Class<?> clazz = obj.getClass();
        try {
            // 使用反射获取对象的字段
            Field areaAuthCodeField = clazz.getDeclaredField("areaAuthCode");
            // 设置字段为可访问
            areaAuthCodeField.setAccessible(true);
            // 设置字段的值
            areaAuthCodeField.set(obj, value);
        } catch (NoSuchFieldException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}