package com.kcim.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kcim.dao.mapper.UserRoleMapper;
import com.kcim.dao.model.UserRole;
import com.kcim.dao.model.dto.RoleUserDTO;
import com.kcim.vo.CommonVO;
import com.kcim.service.UserRoleService;
import com.kcim.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

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


@Service("userRoleService")
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRole> implements UserRoleService {

    private final UserService userService;

    public UserRoleServiceImpl(UserService userService) {
        this.userService = userService;
    }

    /**
     * 通过roleId获取对应的关联人员
     *
     * @param roleId 角色id
     * @param hospId 医院id
     * @return {"id":1,"username":"tom"}
     */
    @Override
    public List<CommonVO> getUsersByRoleId(Long roleId, Long hospId) {
        return baseMapper.getUsersByRoleId(roleId, hospId);
    }

    /**
     * 绑定角色和人员关系时选择列表（可回显）
     *
     * @param roleId 角色id
     * @param hospId 医院id
     * @return {"id":1,"username":"tom","isSelect": true}
     */
    @Override
    public List<CommonVO> roleUserList(Long roleId, Long hospId) {
        // 得到这个角色下所有人员
        return baseMapper.getUsersByRoleId(roleId, hospId);
    }

    /**
     * 编辑角色和人员关系
     *
     * @param roleUserDTO {@link RoleUserDTO}
     * @param hospId      医院id
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Throwable.class)
    public void saveRoleUser(RoleUserDTO roleUserDTO, Long hospId) {
        Long roleId = roleUserDTO.getRoleId();
//        this.removeById(roleId);
        List<Long> userIds = roleUserDTO.getUserIds();
        this.remove(
                new LambdaQueryWrapper<UserRole>().eq(UserRole::getRoleId, roleId));
        if (CollUtil.isNotEmpty(userIds)) {
            List<UserRole> userRoles = userIds.stream().map(i -> {
                UserRole userRole = new UserRole();
                userRole.setRoleId(roleId).setUserId(i).setHospId(hospId);
                return userRole;
            }).collect(Collectors.toList());
            this.saveBatch(userRoles);
        }
    }

}