package com.ktg.framework.aspectj;

import cn.hutool.core.lang.Assert;
import com.ktg.common.annotation.MarsDataScope;
import com.ktg.common.core.domain.BaseEntity;
import com.ktg.common.core.domain.entity.SysRole;
import com.ktg.common.core.domain.entity.SysUser;
import com.ktg.common.core.domain.model.LoginUser;
import com.ktg.common.utils.SecurityUtils;
import com.ktg.common.utils.StringUtils;
import com.ktg.system.service.ISysUserService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

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

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

    /**
     * 岗位数据权限
     */
    public static final String MARS_DATA_SCOPE_WORKSTATION = "3";

    /**
     * 岗位及以下数据权限
     */
    public static final String MARS_DATA_SCOPE_WORKSTATION_AND_CHILD = "4";

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

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


    @Autowired
    private ISysUserService iSysUserService;

    @Before("@annotation(controllerDataScope)")
    public void doBefore(JoinPoint point, MarsDataScope controllerDataScope) {
        clearDataScope(point);
        handleDataScope(point, controllerDataScope);
    }

    protected void handleDataScope(final JoinPoint joinPoint, MarsDataScope controllerDataScope) {
        // 获取当前的用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
        List<Long> allChildWorkstationByUserIds = iSysUserService.getAllChildWorkstationByUserId(loginUser.getUser().getUserId());
        if (StringUtils.isNotNull(loginUser)) {
            SysUser currentUser = loginUser.getUser();
            // 如果是超级管理员，则不过滤数据
            if (StringUtils.isNotNull(currentUser) && !currentUser.isAdmin()) {
                dataScopeFilter(joinPoint, currentUser, controllerDataScope.workstationAlias(), controllerDataScope.userAlias(), allChildWorkstationByUserIds);
            }
        }
    }

    /**
     * 数据范围过滤
     *
     * @param joinPoint 切点
     * @param user      用户
     * @param workstationAlias 别名
     */
    public static void dataScopeFilter(JoinPoint joinPoint, SysUser user, String workstationAlias, String userAlias, List<Long> allChildWorkstationByUserIds) {
        StringBuilder sqlString = new StringBuilder();

        for (SysRole role : user.getRoles()) {
            String marsDataScope = role.getMarsDataScope();
            if (MARS_DATA_SCOPE_ALL.equals(marsDataScope)) {
                // 1.全部数据权限
                sqlString = new StringBuilder();
                break;
            } else if (MARS_DATA_SCOPE_CUSTOM.equals(marsDataScope)) {
                // 2.自定义数据权限
                sqlString.append(StringUtils.format(
                        " OR {}.workstation_id IN ( SELECT workstation_id FROM sys_role_workstation WHERE role_id = {} ) ", workstationAlias,
                        role.getRoleId()));
            } else if (MARS_DATA_SCOPE_WORKSTATION.equals(marsDataScope)) {
                // 3.自身岗位权限
                sqlString.append(StringUtils.format(" OR {}.workstation_id IN ( SELECT workstation_id FROM is_user_workstation WHERE user_id = {} )", workstationAlias, user.getUserId()));
            } else if (MARS_DATA_SCOPE_WORKSTATION_AND_CHILD.equals(marsDataScope)) {
               // 4.自身部门及以下数据权限
                Assert.isFalse(allChildWorkstationByUserIds.isEmpty(), "请先给该人员配置岗位信息！");
                String result = allChildWorkstationByUserIds.stream()
                        .map(String::valueOf)
                        .collect(Collectors.joining(","));
                sqlString.append(StringUtils.format(" OR {}.workstation_id IN ({})",
                        workstationAlias, result));
            } else if (MARS_DATA_SCOPE_SELF.equals(marsDataScope)) {
                // 5.自身权限
                if (StringUtils.isNotBlank(userAlias)) {
                    sqlString.append(StringUtils.format(" OR {}.user_id = {} ", userAlias, user.getUserId()));
                } else {
                    // 数据权限为仅本人且没有userAlias别名不查询任何数据
                    sqlString.append(" OR 1=0 ");
                }
            }
        }

        if (StringUtils.isNotBlank(sqlString.toString())) {
            Object params = joinPoint.getArgs()[0];
            if (StringUtils.isNotNull(params) && params instanceof BaseEntity) {
                BaseEntity baseBean = (BaseEntity) params;
                baseBean.getParamMap().put(MARS_DATA_SCOPE, " AND (" + sqlString.substring(4) + ")");
            }
        }
    }

    /**
     * 拼接权限sql前先清空params.dataScope参数防止注入
     */
    private void clearDataScope(final JoinPoint joinPoint) {
        Object paramMap = joinPoint.getArgs()[0];
        // if (StringUtils.isNotNull(paramMap) && paramMap instanceof BaseBean) {
        // 为了兼容BaseEntity
            if (StringUtils.isNotNull(paramMap) && paramMap instanceof BaseEntity) {
                BaseEntity baseBean = (BaseEntity) paramMap;
            baseBean.getParamMap().put(MARS_DATA_SCOPE, "");
        }
    }
}
