package com.hdkj.lt.bf.service.aspect;

import cn.hutool.core.util.StrUtil;
import com.hdkj.lt.base.exception.BusinessException;
import com.hdkj.lt.bf.service.StruService;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.model.LoginUser;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;

/**
 * @author luorui
 * @date 2025/7/17 17:08
 * 创建切面
 *
 */
@Aspect
@Component
public class UserCountyCodeAutoAspect {

    @Autowired
    StruService struService;

    @Before("@annotation(com.hdkj.lt.bf.service.aspect.UserCountyCodeAuto)")
    public void before(JoinPoint joinPoint) throws Throwable {
        //获取方案参数
        Object[] args = joinPoint.getArgs();
        if (args == null || args.length == 0) return;
        //获取方案签名
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        //获取方法上的注解
        UserCountyCodeAuto annotation = method.getAnnotation(UserCountyCodeAuto.class);
        String sourceFiled = annotation.sourceFiled();
        String targetFiled = annotation.targetFiled();

        //遍历所有参数对象
        for (Object arg : args) {
            if (arg == null) continue;
            Class<?> clazz = arg.getClass();
            //获取源字段
            Field source = getField(clazz, sourceFiled);
            if (source == null) continue;
            source.setAccessible(true);
            Object sourceValue = source.get(arg);
            //如果源字段为空, 或字符串处理掉
            if (sourceValue == null || (sourceValue instanceof String && StrUtil.isBlank((String) sourceValue))) {
                Field target = getField(clazz, targetFiled);
                List<Long> countyList = getCountyList();
                target.setAccessible(true);
                target.set(arg, countyList);
            }
        }
    }

    //查询登录人的所有机构区县信息
    private List<Long> getCountyList() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (loginUser == null) {
            throw new BusinessException("请先登录");
        }
        Long struId = loginUser.getSysUser().getDeptId();
        List<Long> countyList = struService.getCountyCodeListByStruId(struId);
        return countyList;
    }

    //递归查询字段（支持父类）
    private Field getField(Class<?> clazz, String fieldName) {
        try {
            return clazz.getDeclaredField(fieldName);
        } catch (NoSuchFieldException e) {
            Class<?> supperClass = clazz.getSuperclass();
            if (supperClass != null && supperClass != Object.class) {
                return getField(supperClass, fieldName);
            }
            return null;
        }
    }

}
