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

import java.util.Collections;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.mapper.SysRoleMapper;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import com.ruoyi.web.modules.account.constant.MemberConstants;
import com.ruoyi.web.modules.merchant.mapper.MerchantBindMapper;

/**
 * 会员与 sys_user 复用：角色 member、追加角色等
 */
@Component
public class MemberSysUserSupport
{
    public static final long DEFAULT_DEPT_ID = 100L;

    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Autowired
    private MerchantBindMapper merchantBindMapper;

    public Long resolveMemberRoleId()
    {
        return resolveRoleId(MemberConstants.MEMBER_ROLE_KEY, "会员");
    }

    public void grantRoleIfAbsent(Long userId, String roleKey)
    {
        if (userId == null || StringUtils.isEmpty(roleKey))
        {
            return;
        }
        if (merchantBindMapper.countUserHasRole(userId, roleKey) > 0)
        {
            return;
        }
        Long roleId = resolveRoleId(roleKey, roleKey);
        SysUserRole userRole = new SysUserRole();
        userRole.setUserId(userId);
        userRole.setRoleId(roleId);
        userRoleMapper.batchUserRole(Collections.singletonList(userRole));
    }

    private Long resolveRoleId(String roleKey, String label)
    {
        SysRole query = new SysRole();
        query.setRoleKey(roleKey);
        for (SysRole role : roleMapper.selectRoleList(query))
        {
            if (roleKey.equals(role.getRoleKey()))
            {
                return role.getRoleId();
            }
        }
        try
        {
            Long roleId = Long.valueOf(roleKey);
            if (roleMapper.selectRoleById(roleId) != null)
            {
                return roleId;
            }
        }
        catch (NumberFormatException ignored)
        {
            // not numeric role id
        }
        throw new ServiceException("未配置" + label + "角色（role_key=" + roleKey + "）");
    }
}
