package org.dromara.common.sensitive.service.impl;

import com.ruoyi.common.core.domain.StringConstant;
import com.ruoyi.common.core.utils.ServletUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import com.ruoyi.common.core.core.SensitiveService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * 脱敏服务
 * 默认管理员不过滤
 * 需自行根据业务重写实现
 *
 * @author Lion Li
 */
@ConditionalOnMissingBean(SensitiveService.class)
@Service
public class SensitiveServiceImpl implements SensitiveService {

    @Value("${Sensitive.uris:null}")
    private String uris;

    /**
     * 是否脱敏
     */
    @Override
    public boolean isSensitive(String roleKey, String perms) {
        String uri = Objects.requireNonNull(ServletUtils.getRequest()).getRequestURI();

        String[] urisArr = StringUtils.splitByWholeSeparatorPreserveAllTokens(uris, StringConstant.COMMA);
        if (ArrayUtils.isEmpty(urisArr)) {
            urisArr = new String[]{};
        }

        if (!ArrayUtils.contains(urisArr, uri)) {
            return false;
        }

        if (!SecurityUtils.isLogin()) {
            return true;
        }
        boolean roleExist = StringUtils.isNotBlank(roleKey);
        boolean permsExist = StringUtils.isNotBlank(perms);
        if (roleExist && permsExist) {
            if (SecurityUtils.hasRole(roleKey) && SecurityUtils.hasPermission(perms)) {
                return false;
            }
        } else if (roleExist && SecurityUtils.hasRole(roleKey)) {
            return false;
        } else if (permsExist && SecurityUtils.hasPermission(perms)) {
            return false;
        }
        return !SecurityUtils.isAdmin();
    }

}
