package com.ruoyi.web.modules.industryservice.support;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.web.modules.industryservice.mapper.BreedingIndustryStatsMapper;

/**
 * 解析看板统计可见牧场 ID 集合。
 */
@Component
public class BreedingIndustryPastureScope
{
    @Autowired
    private BreedingIndustryStatsMapper breedingIndustryStatsMapper;

    public List<Long> resolveAllowedPastureIds()
    {
        List<Long> allActive = breedingIndustryStatsMapper.selectActivePastureIds();
        if (allActive == null)
        {
            allActive = Collections.emptyList();
        }
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (loginUser == null)
        {
            return Collections.emptyList();
        }
        if (loginUser.getPermissions() != null && loginUser.getPermissions().contains(Constants.ALL_PERMISSION))
        {
            return new ArrayList<>(allActive);
        }
        if (hasAllDataScope(loginUser))
        {
            return new ArrayList<>(allActive);
        }
        if (onlySelfDataScope(loginUser))
        {
            return Collections.emptyList();
        }
        return new ArrayList<>(allActive);
    }

    private static boolean hasAllDataScope(LoginUser loginUser)
    {
        if (loginUser.getUser() == null || loginUser.getUser().getRoles() == null)
        {
            return false;
        }
        for (SysRole role : loginUser.getUser().getRoles())
        {
            if (Constants.Dept.DATA_SCOPE_ALL.equals(role.getDataScope()))
            {
                return true;
            }
        }
        return false;
    }

    private static boolean onlySelfDataScope(LoginUser loginUser)
    {
        if (loginUser.getUser() == null || loginUser.getUser().getRoles() == null
                || loginUser.getUser().getRoles().isEmpty())
        {
            return false;
        }
        for (SysRole role : loginUser.getUser().getRoles())
        {
            if (!Constants.Dept.DATA_SCOPE_SELF.equals(role.getDataScope()))
            {
                return false;
            }
        }
        return true;
    }
}
