package com.gitee.sop.admin.service.sys;

import com.gitee.sop.admin.common.support.ServiceSupport;
import com.gitee.sop.admin.common.user.User;
import com.gitee.sop.admin.common.util.CopyUtil;
import com.gitee.sop.admin.dao.entity.SysRole;
import com.gitee.sop.admin.dao.entity.SysUserRole;
import com.gitee.sop.admin.dao.mapper.SysRoleMapper;
import com.gitee.sop.admin.dao.mapper.SysUserRoleMapper;
import com.gitee.sop.admin.service.sys.dto.SysRoleDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @author 六如
 */
@Service
public class SysUserRoleService implements ServiceSupport<SysUserRole, SysUserRoleMapper> {

    @Autowired
    private SysRoleMapper sysRoleMapper;

    /**
     * 设置用户角色
     *
     * @param userId   用户id
     * @param roleIds  角色id
     * @param operator 操作人
     */
    public void setUserRole(Long userId, List<Long> roleIds, User operator) {
        this.query()
                .eq(SysUserRole::getUserId, userId)
                .delete();

        if (CollectionUtils.isEmpty(roleIds)) {
            return;
        }
        List<SysUserRole> saveList = new LinkedHashSet<>(roleIds).stream()
                .map(roleId -> {
                    SysUserRole sysUserRole = new SysUserRole();
                    sysUserRole.setRoleId(roleId);
                    sysUserRole.setUserId(userId);
                    sysUserRole.setAddBy(operator.getUserId());
                    return sysUserRole;
                })
                .collect(Collectors.toList());

        this.saveBatch(saveList);
    }

    public List<Long> listUserRoleIds(Long userId) {
        return this.query()
                .eq(SysUserRole::getUserId, userId)
                .listUniqueValue(SysUserRole::getRoleId);
    }

    public List<SysRoleDTO> listUserRoles(Long userId) {
        List<Long> roleIds = this.listUserRoleIds(userId);
        if (roleIds.isEmpty()) {
            return new ArrayList<>(0);
        }
        return sysRoleMapper.query()
                .in(SysRole::getId, roleIds)
                .list(sysRole -> CopyUtil.copyBean(sysRole, SysRoleDTO::new));
    }

}
