/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package com.mx.cneeds.server.user.common;



import com.mx.cneeds.common.annotation.DataFilter;
import com.mx.cneeds.common.dto.DataFilterDto;
import com.mx.cneeds.common.exception.RRException;
import com.mx.cneeds.common.pager.Constant;
import com.mx.cneeds.server.entity.SysUserEntity;
import com.mx.cneeds.server.user.service.*;
import org.apache.commons.lang.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.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 数据过滤，切面处理类
 *
 * @author Mark sunlightcs@gmail.com
 */
@Aspect
@Component
public class DataFilterAspect {

    @Autowired
    private SysUserService sysUserService;

    @Pointcut("@annotation(com.mx.cneeds.common.annotation.DataFilter)")
    public void dataFilterCut() {

    }

    @Before("dataFilterCut()")
    public void dataFilter(JoinPoint point){
        Object params = point.getArgs()[0];
        if(params != null && params instanceof Map){
            String username = (String) ((Map) params).get("login_username");
            //如果不是超级管理员，则进行数据过滤
            if(!Constant.STRING_SUPER_ADMIN.equals(username)){
                Map map = (Map)params;
                map.put(Constant.SQL_FILTER, getSQLFilter(username, point));
            }
            return ;
        }

        throw new RRException("数据权限接口，只能是Map类型参数，且不能为NULL");
    }

    /**
     * 获取数据过滤的SQL
     */
    private String getSQLFilter(String  username, JoinPoint point){
        MethodSignature signature = (MethodSignature) point.getSignature();
        DataFilter dataFilter = signature.getMethod().getAnnotation(DataFilter.class);

        DataFilterDto dataFilterDto = new DataFilterDto();

        dataFilterDto.setDeptId(dataFilter.deptId());
        dataFilterDto.setUserId(dataFilter.userId());
        dataFilterDto.setUser(dataFilter.user());
        dataFilterDto.setSubDept(dataFilter.subDept());
        dataFilterDto.setTableAlias(dataFilter.tableAlias());
        dataFilterDto.setUsername(username);

        String sqlFilter = sysUserService.genDataFilter(dataFilterDto);

        return sqlFilter;
    }



}
