package com.ningdatech.carapi.common.aop;

import cn.hutool.core.collection.CollUtil;
import com.google.common.collect.Lists;
import com.ningdatech.carapi.sys.contants.RegionContant;
import com.ningdatech.carapi.sys.entity.dto.RegionDTO;
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.Field;
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 BuildChildrenRegionEntityAspect {

    @Autowired
    private RegionsCacheHelper regionsCacheHelper;

    @Pointcut("@annotation(com.ningdatech.carapi.common.aop.BuildChildrenRegionEntity)")
    public void buildChildrenRegionEntityAspect() {

    }

    @Before("buildChildrenRegionEntityAspect() && @annotation(buildChildrenRegionEntity)")
    public void before(JoinPoint joinPoint, BuildChildrenRegionEntity buildChildrenRegionEntity) throws Throwable {

        Object entity = joinPoint.getArgs()[buildChildrenRegionEntity.entityIndex()];

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

        Class<?> clazz = entity.getClass();
        Method getRegionId = clazz.getMethod("getRegionId");
        Long regionId = (Long) getRegionId.invoke(entity);
        if (Objects.nonNull(regionId)) {
            RegionDTO currRegion = regionsCacheHelper.getByRegionId(regionId);
            List<Long> regionIds;
            if (currRegion.getRegionCode().equals(currRegion.getParentCode())
                    || currRegion.getRegionLevel().equals(RegionContant.THIRD_LEVEL)) {
                regionIds = Lists.newArrayList(regionId);
            } else {
                regionIds = regionsCacheHelper.listChildRegionId(regionId, false, true);
            }
            if (CollUtil.isNotEmpty(regionIds)) {
                Field field = clazz.getDeclaredField("regionIds");
                field.setAccessible(true);
                field.set(entity, regionIds);
            }
        }

    }


}