/* (C) 2022 YiRing, Inc. */
package com.yiring.auth.web.sys.user;

import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import com.yiring.auth.domain.role.Role;
import com.yiring.auth.domain.role.RoleRepository;
import com.yiring.auth.domain.user.User;
import com.yiring.auth.domain.user.UserRepository;
import com.yiring.auth.vo.user.UserVo;
import com.yiring.common.core.Result;
import com.yiring.common.param.IdParam;
import com.yiring.common.param.IdsParam;
import com.yiring.common.param.PageParam;
import com.yiring.common.util.Commons;
import com.yiring.common.utils.RepositoryUtil;
import com.yiring.common.utils.Specifications;
import com.yiring.common.vo.PageVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.data.domain.Page;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 系统用户控制器
 *
 * @author Jim
 * @version 0.1
 * 2022/1/24 14:13
 */

@Slf4j
@Validated
@ApiSupport(order = -97)
@Tag(name = "用户管理", description = "User")
@RestController
@RequestMapping("/sys/user/")
@RequiredArgsConstructor
public class UserController {

    final UserRepository userRepository;
    final RoleRepository roleRepository;

    @Operation(summary = "分配角色")
    @PostMapping("assign")
    public Result<String> assign(
        @ParameterObject @Validated IdParam idParam,
        @ParameterObject @Validated IdsParam idsParam
    ) {
        User entity = RepositoryUtil.find(userRepository, idParam.getId());

        // 查询角色集合
        Set<Role> roles = new HashSet<>(roleRepository.findAllById(idsParam.toIds()));
        entity.setRoles(roles);
        userRepository.saveAndFlush(entity);
        return Result.ok();
    }

    @Operation(summary = "分页查询")
    @GetMapping("page")
    public Result<PageVo<UserVo>> page(@ParameterObject @Validated PageParam param) {
        Page<User> page = userRepository.findAll(Specifications.exist(), PageParam.toPageable(param));

        List<UserVo> data = page.get().map(user -> Commons.transform(user, UserVo.class)).collect(Collectors.toList());
        PageVo<UserVo> vo = PageVo.build(data, page.getTotalElements(), page.getTotalPages());
        return Result.ok(vo);
    }
}
