package com.ltgk.framework.aspectj;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.ltgk.common.annotation.DataAreaCodeSource;
import com.ltgk.common.constant.ReturnMsgConstants;
import com.ltgk.common.core.domain.BaseAreaCode;
import com.ltgk.common.core.domain.entity.SysUser;
import com.ltgk.common.core.domain.model.LoginUser;
import com.ltgk.common.utils.SecurityUtils;
import com.ltgk.common.utils.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @Author: wan kun
 * @Description: 自定义行政区域数据权限处理类
 * @Date: 2024/12/19 8:58
 * @Version: 1.0
 */
@Aspect
@Component
public class DataAreaCodeSourceAspect {
    /**
     * 全部数据权限
     */
    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 = "dataAreaCodeSource";

    @Before("@annotation(controllerDataAreaCodeSource)")
    public void doBefore(JoinPoint point, DataAreaCodeSource controllerDataAreaCodeSource) throws Throwable {
        clearDataScope(point);
        handleDataScope(point, controllerDataAreaCodeSource);
    }

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

    /**
     * 数据范围过滤
     *
     * @param joinPoint 切点
     * @param user      用户
     */
    public static void dataScopeFilter(JoinPoint joinPoint, SysUser user, String searchKey) {
        List<String> areaCodes = SecurityUtils.getAreaCodes();
        if (ObjectUtils.isEmpty(areaCodes)) {
            throw new RuntimeException(ReturnMsgConstants.USER_NOT_AREA_PERMISSION);
        }
        StringBuilder sqlString = new StringBuilder();
        sqlString.append(searchKey).append(" in (");
        StringBuilder finalSqlString = sqlString;
        areaCodes.forEach(areaCode -> finalSqlString.append("'").append(areaCode).append("',"));
        sqlString = new StringBuilder(sqlString.substring(0, sqlString.length() - 1));
        sqlString.append(")");
        Object params = joinPoint.getArgs()[0];
        if (StringUtils.isNotNull(params) && params instanceof BaseAreaCode) {
            BaseAreaCode entity = (BaseAreaCode) params;
            entity.setAreaCodeCondition(sqlString.toString());
        }
    }

    /**
     * 拼接权限sql前先清空
     */
    private void clearDataScope(final JoinPoint joinPoint) {
        Object params = joinPoint.getArgs()[0];
        if (StringUtils.isNotNull(params) && params instanceof BaseAreaCode) {
            BaseAreaCode entity = (BaseAreaCode) params;
            entity.setAreaCodeCondition(null);
        }
    }
}
