package com.app.admin.framework.system.permission.authorization.service.impl;

import com.app.admin.framework.system.permission.authorization.dao.SysAdministratorRoleDao;
import com.app.admin.framework.system.permission.authorization.model.SysAdministratorRole;
import com.app.admin.framework.system.permission.authorization.service.SysAdministratorRoleService;
import com.app.admin.framework.system.permission.authorization.view.SysAdministratorRoleView;
import com.app.framework.core.support.enums.common.StateEnum;
import com.app.framework.core.support.service.impl.CrudBaseServiceSupport;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户角色关联管理
 */
@Service
public class SysAdministratorRoleServiceImpl extends CrudBaseServiceSupport<SysAdministratorRoleDao, SysAdministratorRole> implements SysAdministratorRoleService {

    /**
     * 查询用户所有角色
     *
     * @param userId    用户Id
     * @param stateEnum 角色状态
     */
    public List<SysAdministratorRoleView> selectByUserId(Long userId, StateEnum stateEnum) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("userId", userId);
        if (stateEnum != null)
            map.put("state", stateEnum.getValue());
        return getBaseMapper().selectByUserId(map);
    }

    /**
     * 根据角色Id删除权限
     *
     * @param roleId 角色Id
     */
    @Override
    public boolean deleteByRoleId(Long roleId) {
        LambdaQueryWrapper<SysAdministratorRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysAdministratorRole::getRoleId, roleId);
        return this.remove(wrapper);
    }

    /**
     * 根据用户Id删除权限
     *
     * @param userId 用户Id
     */
    public boolean deleteByUserId(Long userId) {
        LambdaQueryWrapper<SysAdministratorRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysAdministratorRole::getUserId, userId);
        return this.remove(wrapper);
    }

    /**
     * 根据角色ID获取对应的用户
     *
     * @param roleId 角色Id
     * @return List<用户名>
     */
    public List<String> getUsernameByRoleId(Long roleId) {
        return getBaseMapper().getUsernameByRoleId(roleId);
    }

    /**
     * 创建用户角色对应关系，不存在才创建
     *
     * @param userId 用户ID
     * @param roleId 角色ID
     */
    public SysAdministratorRole createIfAbsent(Long userId, Long roleId) {
        LambdaQueryWrapper<SysAdministratorRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysAdministratorRole::getUserId, userId);
        wrapper.eq(SysAdministratorRole::getRoleId, roleId);
        SysAdministratorRole one = this.getOne(wrapper);
        if (one == null) {
            one = new SysAdministratorRole();
            one.setUserId(userId);
            one.setRoleId(roleId);
            this.save(one);
        }
        return one;
    }
}