package cn.quantgroup.xyqb.service.session.aspect;

import cn.quantgroup.xyqb.entity.UserBtRegister;
import cn.quantgroup.xyqb.model.session.SessionValue;
import cn.quantgroup.xyqb.service.user.IUserBtRegisterService;
import lombok.extern.slf4j.Slf4j;
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.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * Created by Administrator on 2017/5/16.
 */
@Slf4j
@Aspect
@Component
@Order(value = Ordered.HIGHEST_PRECEDENCE)
public class UserBtRegisterFillAspect {

    @Autowired
    private IUserBtRegisterService userBtRegisterService;

    /** 生成还款计划的时候，去生成趸交服务费 */
    @Pointcut("@annotation(cn.quantgroup.xyqb.service.session.aspect.UserBtRegisterFill)")
    public void userBtRegisterFillCut() {
    }

    @Around("userBtRegisterFillCut()")
    public Object handleSingleServiceFeeRule(ProceedingJoinPoint pjp) throws Throwable {
        Object[] args = pjp.getArgs();
        try {
            args = fillUserBtRegister(args);
        } catch (Exception e) {
            log.error("补充用户白条登录渠道信息失败", e);
        }
        return pjp.proceed(args);
    }

    private Object[] fillUserBtRegister(Object[] args) {
        for (int i = 0; i < args.length; i++) {
            Object obj = args[i];
            if (obj instanceof SessionValue) {
                SessionValue value = (SessionValue) obj;
                UserBtRegister userBtRegister = userBtRegisterService.findByUserId(value.getUser().getId());
                if (null != userBtRegister && null != value.getLoginProperties()) {
                    value.getLoginProperties().setMerchantId(userBtRegister.getRegisterBtMerchantId());
                }
            }
        }
        return args;
    }
}
