package com.iformall.log;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.iformall.annotation.UserDataRuleAnnotation;
import com.iformall.domain.po.base.BaseEntity;
import com.iformall.domain.po.MallUserInfo;
import com.iformall.domain.po.WxUserDataRule;
import com.iformall.mapper.WxRentContractMapper;
import com.iformall.service.WxUserDataRuleService;
import com.iformall.shiro.UserSession;
import org.apache.commons.lang3.StringUtils;
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.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.HashSet;

/**
 * @author gongbiao
 */
@Aspect
@Component
public class UserDataRuleAspect {
    private static final Logger logger = LoggerFactory.getLogger(UserDataRuleAspect.class);

    @Autowired
    private WxUserDataRuleService wxUserDataRuleService;

    @Autowired
    private WxRentContractMapper wxRentContractMapper;

    @Pointcut("@annotation(com.iformall.annotation.UserDataRuleAnnotation)")
    public void userDataRulePointcut() {
    }

    @Before("userDataRulePointcut()")
    public void doBefore(JoinPoint joinPoint) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        MallUserInfo user = (MallUserInfo) request.getSession().getAttribute(UserSession.userInfo);
        if (user == null) {
            logger.error("session 获取 user 失败");
            return;
        }

        //得到用户的数据权限
        WxUserDataRule byUserId = wxUserDataRuleService.findByUserId(user.getId());
        if (byUserId == null) {
            logger.info("用户的数据权限未配置");
            return;
        }
        String buildingFloor = byUserId.getBuildingFloor();
        if (StringUtils.isNotEmpty(buildingFloor)) {
            Object[] data = JSONArray.parseArray(buildingFloor).toArray();
            buildingFloor = StringUtils.join(data, ",");
        }

        String businessForRule = byUserId.getBusiness();
        if (StringUtils.isNotEmpty(businessForRule)) {
            Object[] data = JSONArray.parseArray(businessForRule).toArray();
            businessForRule = StringUtils.join(data, ",");
        }

        HashSet<String> targetSet = new HashSet();
        String target = byUserId.getTarget();
        if (StringUtils.isNotEmpty(target)) {
            JSONArray objects = JSONArray.parseArray(target);
            for (int i = 0; i < objects.size(); i++) {
                JSONObject jsonObject = objects.getJSONObject(i);
                targetSet.add(jsonObject.getString("tag"));
            }
        }

        //得到注释的名称
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        //判断tag是否在用户权限中 如果存在加入参数查询
        Method method = signature.getMethod();
        String value = method.getAnnotation(UserDataRuleAnnotation.class).value();
        if (targetSet.contains(value)) {
            //得到方法的参数
            Object[] args = joinPoint.getArgs();
            if (args[0] instanceof BaseEntity) {
                BaseEntity baseEntity = (BaseEntity) args[0];
                baseEntity.setFloorForRule(buildingFloor);
                baseEntity.setBusinessForRule(businessForRule);
                String contract = "contract";
                if (StringUtils.isNotEmpty(buildingFloor) && value.contains(contract)) {
                    int count = wxRentContractMapper.getShopCountMax();
                    String[] tempShop = new String[count];
                    baseEntity.setTempShop(tempShop);
                }
            }

        }
    }

}
