package cn.reghao.devops.web.admin.account.controller.page;

import cn.reghao.devops.web.admin.account.model.po.User;
import cn.reghao.devops.web.admin.account.model.vo.RoleVO;
import cn.reghao.devops.web.admin.account.model.vo.UserVO;
import cn.reghao.devops.web.admin.account.service.AccountService;
import cn.reghao.devops.web.admin.account.service.AccountSessionService;
import cn.reghao.devops.web.admin.account.service.RoleService;
import cn.reghao.devops.web.admin.account.service.UserContext;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author reghao
 * @date 2021-04-04 21:24:18
 */
@Api(tags = "用户页面")
@RequestMapping("/rbac/user")
@Controller
public class UserPageController {
    private final AccountService accountService;
    private final RoleService roleService;
    private final AccountSessionService accountSessionService;

    public UserPageController(AccountService accountService, RoleService roleService, AccountSessionService accountSessionService) {
        this.accountService = accountService;
        this.roleService = roleService;
        this.accountSessionService = accountSessionService;
    }

    @ApiOperation(value = "个人信息页面")
    @GetMapping("/profile")
    public String userInfoPage(Model model) {
        User user = UserContext.getUser();
        model.addAttribute("user", user);
        return "/admin/user/userinfo";
    }

    @ApiOperation(value = "修改个人密码页面")
    @GetMapping("/passwd/edit")
    public String editPasswdPage(Model model) {
        return "/admin/user/userpasswd";
    }

    @ApiOperation(value = "用户列表页面")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    @GetMapping
    public String userPage(@RequestParam(value = "screenName", required = false) String screenName, Model model) {
        Page<UserVO> page;
        if (screenName != null) {
            List<UserVO> list = accountService.getByMatchScreenName(screenName);
            page = new PageImpl<>(list);
        } else {
            PageRequest pageRequest = PageRequest.of(0, 100);
            page = accountService.getUserVOByPage(pageRequest);
        }

        Map<Integer, String> map = accountSessionService.getLastAccess();
        page.getContent().forEach(userVO -> {
            int userId = userVO.getUserId();
            String lastAccessStr = map.get(userId);
            if (lastAccessStr != null) {
                userVO.setLastAccess(lastAccessStr);
            }
        });

        model.addAttribute("page", page);
        model.addAttribute("list", page.getContent());
        return "/admin/user/index";
    }

    @ApiOperation(value = "新增用户页面")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    @GetMapping("/add")
    public String addUserPage(Model model) {
        Set<RoleVO> allRoles = roleService.getAllRoles();
        model.addAttribute("allRoles", allRoles);
        model.addAttribute("userRoles", Collections.emptySet());
        return "/admin/user/add";
    }

    @ApiOperation(value = "用户详细信息页面")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    @GetMapping("/detail/{id}")
    public String userDetailPage(@PathVariable("id") int id, Model model) {
        User user = accountService.getById(id);
        Set<RoleVO> roles = roleService.getUserRoles(user.getId());
        List<String> names = roles.stream().map(RoleVO::getName).collect(Collectors.toList());

        model.addAttribute("roles", names.toString());
        model.addAttribute("user", user);
        return "/admin/user/detail";
    }

    @ApiOperation(value = "重置用户密码页面")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    @GetMapping("/passwd/{id}")
    public String modifyPasswordPage(@PathVariable("id") Integer id, Model model) {
        model.addAttribute("id", id);
        return "/admin/user/passwd";
    }

    @ApiOperation(value = "用户角色分配页面")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    @GetMapping("/role/{id}")
    public String assignRolePage(@PathVariable("id") User user, Model model) {
        Set<RoleVO> allRoles = roleService.getAllRoles();
        int userId = user.getId();
        Set<RoleVO> userRoles = roleService.getUserRoles(userId);

        model.addAttribute("id", userId);
        model.addAttribute("list", allRoles);
        model.addAttribute("authRoles", userRoles);
        return "/admin/user/role";
    }
}
