package com.ningdatech.carapi.common.aop;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ningdatech.carapi.datascope.model.DataScopeEntity;
import com.ningdatech.carapi.sys.helper.RegionsCacheHelper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

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

/**
 * @program:
 * @description: 生成子区域
 * BuildChildrenRegionAspect
 * @author: PoffyZhang
 * @created: 2022/11/11 09:12
 */
@Aspect
@Component
@Slf4j
@AllArgsConstructor
@Order(10)
public class BuildChildrenRegionWrapperAspect {

    @Autowired
    private RegionsCacheHelper regionsCacheHelper;

    @Pointcut("@annotation(com.ningdatech.carapi.common.aop.BuildChildrenRegionWrapper)")
    public void buildChildrenRegionWrapperAspect() {

    }

    @Before("buildChildrenRegionWrapperAspect() && @annotation(buildChildrenRegionWrapper)")
    public void before(JoinPoint joinPoint, BuildChildrenRegionWrapper buildChildrenRegionWrapper) throws Throwable {

        LambdaQueryWrapper<DataScopeEntity> wrapper = (LambdaQueryWrapper) joinPoint.getArgs()[buildChildrenRegionWrapper.wrapperIndex()];
        Object entity = joinPoint.getArgs()[buildChildrenRegionWrapper.entityIndex()];

        if(Objects.isNull(wrapper)){
            return;
        }

        Class<?> clazz = entity.getClass();
        Method getRegionId = clazz.getMethod("getRegionId");
        Long regionId = (Long) getRegionId.invoke(entity);
        if(Objects.nonNull(regionId)){
            List<Long> regionIds = regionsCacheHelper.listChildRegionId(regionId);
            if (CollUtil.isNotEmpty(regionIds)){
                wrapper.in(CollUtil.isNotEmpty(regionIds), DataScopeEntity::getRegionId,regionIds);
            }
        }
    }
}