package com.zd.common.datascope.aspect;

import java.lang.reflect.Method;
import java.util.List;
import java.util.function.Predicate;
import java.util.logging.Logger;

import com.zd.common.core.constant.UserConstants;
import com.zd.common.core.domain.per.PerFun;
import com.zd.common.core.exception.CheckedException;
import com.zd.common.core.exception.PreAuthorizeException;
import com.zd.common.core.exception.ServiceException;
import com.zd.system.api.domain.SysPermitInfo;
import org.apache.commons.collections4.CollectionUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
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 com.zd.common.core.utils.StringUtils;
import com.zd.common.core.web.domain.BaseEntity;
import com.zd.common.datascope.annotation.DataScope;
import com.zd.common.security.service.TokenService;
import com.zd.system.api.domain.SysRole;
import com.zd.system.api.domain.SysUser;
import com.zd.system.api.model.LoginUser;

/**
 * 数据过滤处理
 *
 * @author zd
 */
@Aspect
@Component
public class DataScopeAspect {
    /**
     * 全部数据权限
     */
    public static final String DATA_SCOPE_ALL = "1";

    /**
     * 自定数据权限
     */
    public static final String DATA_SCOPE_CUSTOM = "2";

    /**
     * 部门数据权限
     */
    public static final String DATA_SCOPE_DEPT = "3";

    /**
     * 部门及以下数据权限
     */
    public static final String DATA_SCOPE_DEPT_AND_CHILD = "4";

    /**
     * 仅本人数据权限
     */
    public static final String DATA_SCOPE_SELF = "5";

    /**
     * 数据权限过滤关键字
     */
    public static final String DATA_SCOPE = "dataScope";

    @Autowired
    private TokenService tokenService;

    // 配置织入点
    @Pointcut("@annotation(com.zd.common.datascope.annotation.DataScope)")
    public void dataScopePointCut() {
    }

    @Before("dataScopePointCut()")
    public void doBefore(JoinPoint point) throws Throwable {
        clearDataScope(point);
        handleDataScope(point);
    }

    protected void handleDataScope(final JoinPoint joinPoint) {
        // 获得注解
        DataScope controllerDataScope = getAnnotationLog(joinPoint);
        if (controllerDataScope == null) {
            return;
        }
        // 获取当前的用户
        LoginUser loginUser = tokenService.getLoginUser();
        if (StringUtils.isNotNull(loginUser)) {
            SysUser currentUser = loginUser.getSysUser();
            // 如果是超级管理员，则不过滤数据
            if (StringUtils.isNotNull(currentUser) && !currentUser.isAdmin() && UserConstants.USER_LOGIN_PC == loginUser.getLoginType()) {
                dataScopeNewFilter(joinPoint, currentUser, controllerDataScope);
            }
        }
    }

    @Deprecated
    public static void dataScopeFilter(JoinPoint joinPoint, SysUser user, String deptAlias, String userAlias, boolean isSubAdmin) {
        StringBuilder sqlString = new StringBuilder();
        Boolean f = true;
        for (SysRole role : user.getRoles()) {
            String dataScope = role.getDataScope();
            if (DATA_SCOPE_ALL.equals(dataScope)) {
                sqlString = new StringBuilder();
                f = false;
                break;
            } else if (DATA_SCOPE_CUSTOM.equals(dataScope)) {
                sqlString.append(StringUtils.format(
                        " OR {}.dept_id IN ( SELECT dept_id FROM sys_role_dept WHERE role_id = {} ) ", deptAlias,
                        role.getRoleId()));
            } else if (DATA_SCOPE_DEPT.equals(dataScope)) {
                sqlString.append(StringUtils.format(" OR {}.dept_id = {} ", deptAlias, user.getDeptId()));
            } else if (DATA_SCOPE_DEPT_AND_CHILD.equals(dataScope)) {
                sqlString.append(StringUtils.format(
                        " OR {}.dept_id IN ( SELECT dept_id FROM sys_dept WHERE dept_id = {} or find_in_set( {} , ancestors ) )",
                        deptAlias, user.getDeptId(), user.getDeptId()));
            } else if (DATA_SCOPE_SELF.equals(dataScope)) {
                if (StringUtils.isNotBlank(userAlias)) {
                    sqlString.append(StringUtils.format(" OR {}.user_id = {} ", userAlias, user.getUserId()));
                } else {
                    // 数据权限为仅本人且没有userAlias别名不查询任何数据
                    sqlString.append(" OR 1=0 ");
                }
            }
        }
        if (f && isSubAdmin) {
            sqlString.append(StringUtils.format(" OR {}.admin_id = {} ", userAlias, user.getUserId()));
        }
        if (StringUtils.isNotBlank(sqlString.toString())) {
            Object params = joinPoint.getArgs()[0];
            if (StringUtils.isNotNull(params) && params instanceof BaseEntity) {
                BaseEntity baseEntity = (BaseEntity) params;
                baseEntity.getParams().put(DATA_SCOPE, " AND (" + sqlString.substring(4) + ")");
            }
        }
    }

    /**
     * 2.6需求变动数据范围过滤
     *
     * @param joinPoint  切点
     * @param user       用户
     * @param controllerDataScope  权限注解
     */
    public static void dataScopeNewFilter(JoinPoint joinPoint, SysUser user, DataScope controllerDataScope) {
        StringBuilder sqlString = new StringBuilder();
        Boolean f = true;

        String deptAlias = controllerDataScope.deptAlias();
        String userAlias = controllerDataScope.userAlias();
        if(org.apache.commons.lang3.StringUtils.isBlank(controllerDataScope.permi())){
            System.err.println("\r\n" + joinPoint.getSignature().getName() + "()方法： 未添加模块注解，请尽快补充！！！" + "\r\n");
            return;
        }

        List<SysPermitInfo> permits = user.getPermits();
        if(CollectionUtils.isEmpty(permits)){
            throw new PreAuthorizeException();
        }

        String finalPermi = controllerDataScope.permi() + PerFun.LIST;
        SysPermitInfo permitInfo = permits.stream().filter(a -> finalPermi.equals(a.getMenuPerms())).findFirst().orElse(null);
        if(permitInfo == null){
            return;
        }

        // 1：全部数据权限
        String dataScope = permitInfo.getDataScope() + "";
        if (DATA_SCOPE_ALL.equals(dataScope)) {
            sqlString = new StringBuilder();
            f = false;
        } else if (DATA_SCOPE_CUSTOM.equals(dataScope)) {
            // 2：本部门以及下级部门
            sqlString.append(StringUtils.format(
                    " OR {}.dept_id IN ( SELECT dept_id FROM sys_dept WHERE dept_id = {} or find_in_set( {} , ancestors ) )",
                    deptAlias, user.getDeptId(), user.getDeptId()));
        } else if (DATA_SCOPE_DEPT.equals(dataScope)) {
            // 3：本部门以及指定部门（指定部门关联表中查询）
            List<Long> deptIds = permitInfo.getDeptIds();
            if(CollectionUtils.isEmpty(deptIds)){
                // TODO 数据问题暂这样处理
                throw new PreAuthorizeException();
            }else {

                StringBuffer sb = new StringBuffer();
                for (Long deptId : deptIds) {
                    sb.append("\'").append(deptId).append("\'").append(",");
                }
                sqlString.append(StringUtils.format(
                        " OR {}.dept_id IN ( {} ) ", deptAlias, sb.substring(0, sb.length()-1)));
            }

        } else if (DATA_SCOPE_DEPT_AND_CHILD.equals(dataScope)) {
            // 4：仅本人
            if (StringUtils.isNotBlank(userAlias)) {
                sqlString.append(StringUtils.format(" OR {}.user_id = {} ", userAlias, user.getUserId()));
            } else {
                // 数据权限为仅本人且没有userAlias别名不查询任何数据
                sqlString.append(" OR 1=0 ");
            }
        }

        /*if (f && controllerDataScope.subAdmin()) {
            sqlString.append(StringUtils.format(" OR {}.admin_id = {} ", userAlias, user.getUserId()));
        }*/

        if (StringUtils.isNotBlank(sqlString.toString())) {
            Predicate<JoinPoint> predicate = x-> x.getArgs().length>0;
            if(predicate.test(joinPoint)) {
                Object params = joinPoint.getArgs()[0];
                if (StringUtils.isNotNull(params) && params instanceof BaseEntity) {
                    BaseEntity baseEntity = (BaseEntity) params;
                    baseEntity.getParams().put(DATA_SCOPE, " AND (" + sqlString.substring(4) + ")");
                }
            }
        }
    }

    /**
     * 是否存在注解，如果存在就获取
     */
    private DataScope getAnnotationLog(JoinPoint joinPoint) {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();

        if (method != null) {
            return method.getAnnotation(DataScope.class);
        }
        return null;
    }

    /**
     * 拼接权限sql前先清空params.dataScope参数防止注入
     */
    private void clearDataScope(final JoinPoint joinPoint) {
        Predicate<JoinPoint> predicate = x-> x.getArgs().length>0;
        if(predicate.test(joinPoint)){
            Object params = joinPoint.getArgs()[0];
            if (StringUtils.isNotNull(params) && params instanceof BaseEntity) {
                BaseEntity baseEntity = (BaseEntity) params;
                baseEntity.getParams().put(DATA_SCOPE, "");
            }
        }

    }
}
