package com.brilliance.isc.common.aspect;


import com.brilliance.isc.bo.Bch;
import com.brilliance.isc.common.api.bch.service.BchService;
import com.brilliance.isc.common.context.SettleContext;
import com.brilliance.isc.constant.ErrorCode;
import com.brilliance.isc.exception.RestBizException;
import com.brilliance.isc.vo.manager.SessionUserVo;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Aspect
@Component
public class FilterBchAspect {

    private final Logger logger = LoggerFactory.getLogger(FilterBchAspect.class);

    @Autowired
    private BchService bchService;

    @Pointcut("@annotation(com.brilliance.isc.annotation.FilterBch)")
    public void pointcut(){}

    @Around("pointcut()")
    public Object handle(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        String className = proceedingJoinPoint.getTarget().getClass().getName();
        String methodName = proceedingJoinPoint.getSignature().getName();
        try {
            Object object = proceedingJoinPoint.proceed();
            logger.info("类名：{},方法名：{},执行切面:FilterBch，过滤机构列表",className,methodName);
            Bch orgBch = null;
            SessionUserVo sessionUser = SettleContext.getSessionUserVo();
            if (sessionUser != null) {
                orgBch = bchService.getByBranch(sessionUser.getOwnOrgDepartmentNumber());
            }
            if (orgBch == null) {
                logger.error("获取不到登录机构,不予处理直接返回!");
                return object;
            }
            if ("2".equalsIgnoreCase(orgBch.getLev()) && "7".equalsIgnoreCase(orgBch.getBchtyp())) {
                logger.info("当前登录机构branch:{},类型是经办非记账",orgBch.getBranch());
                List<Bch> bchList = (List<Bch>) object;
                if (bchList != null && bchList.size() >0) {
                    String orgbchinr = orgBch.getInr();
                    if (bchList.stream().anyMatch(item->item.getInr().equalsIgnoreCase(orgbchinr))) {
                        logger.info("切面过滤成功，返回当前登录机构");
                        List<Bch> rtnBchList = new ArrayList<>();
                        rtnBchList.add(orgBch);
                        return rtnBchList;
                    }
                }
            }
            return object;
        } catch (Throwable throwable) {
            logger.error("获取机构列表: an exception has been throwing in "+className+":"+methodName+"():{}",throwable);
            if(throwable instanceof RestBizException){
                throw (RestBizException) throwable;
            }else {
                throw new RestBizException(ErrorCode.BIZ_COMMON_ERROR, throwable.getMessage());
            }
        }
    }
}
