package com.ruoyi.framework.util;

import java.util.ArrayList;
import java.util.List;

import com.aliyun.core.utils.StringUtils;
import com.ruoyi.common.core.domain.vo.UserVO;
import com.ruoyi.common.utils.collection.CollectionUtils;

import lombok.Data;

@Data
public class DataScopeBuilder {
    private boolean needScope;
    private UserVO user;
    private String deptAlias;
    private String userAlias;
    private String deptSetAlias;
    private String userSetAlias;
    private String permission;
    private List<AreaJoinScope> areaJoinScopes;

    // 私有构造函数，通过静态方法创建实例
    private DataScopeBuilder() {}

    // 静态工厂方法
    public static DataScopeBuilder create() {
        return new DataScopeBuilder();
    }

    // 设置是否需要数据权限
    public DataScopeBuilder needScope(boolean needScope) {
        this.needScope = needScope;
        return this;
    }

    // 设置用户
    public DataScopeBuilder user(UserVO user) {
        this.user = user;
        return this;
    }

    // 部门字段别名
    public DataScopeBuilder deptAlias(String deptAlias) {
        this.deptAlias = deptAlias;
        return this;
    }

    // 用户字段别名
    public DataScopeBuilder userAlias(String userAlias) {
        this.userAlias = userAlias;
        return this;
    }

    // 部门集合字段别名
    public DataScopeBuilder deptSetAlias(String deptSetAlias) {
        this.deptSetAlias = deptSetAlias;
        return this;
    }

    // 用户集合字段别名
    public DataScopeBuilder userSetAlias(String userSetAlias) {
        this.userSetAlias = userSetAlias;
        return this;
    }

    // 权限
    public DataScopeBuilder permission(String permission) {
        this.permission = permission;
        return this;
    }

    // 运营区字段别名
    public DataScopeBuilder areaAlias(String areaAlias, String permission) {
        if (StringUtils.isBlank(permission) || StringUtils.isBlank(areaAlias)) {
            return this;
        }
        if (this.areaJoinScopes == null) {
            this.areaJoinScopes = new ArrayList<>();
        }
        this.areaJoinScopes.add(new AreaJoinScope(areaAlias, permission));
        return this;
    }

    public DataScopeBuilder areaAlias(String areaAlias, List<String> permissions) {
        if (CollectionUtils.isNotEmpty(permissions)) {
            for (String permission : permissions) {
                this.areaAlias(areaAlias, permission);
            }
        }
        return this;
    }

    // 构建最终的SQL
    public String build() {
        if (this.needScope) {
            // 如果是超级管理员，则不过滤数据
            if (user != null && !user.isAdmin()){
                return DataScopeUtil.getJoinSqlString(DataScopeUtil.getSqlString(this), "");
            }
        }
        return "";
    }

}
