package cn.reghao.oss.console.account.controller.page;

import cn.reghao.oss.console.account.db.query.RoleQuery;
import cn.reghao.oss.console.account.db.query.UserQuery;
import cn.reghao.oss.console.account.model.po.Role;
import cn.reghao.oss.console.account.model.po.User;
import cn.reghao.oss.console.account.model.vo.UserVO;
import cn.reghao.oss.console.account.service.AccountSessionService;
import cn.reghao.oss.console.account.service.UserContext;
import cn.reghao.oss.console.util.db.PageSort;
import cn.reghao.jutil.jdk.converter.DateTimeConverter;
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.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
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 UserQuery userQuery;
    private final RoleQuery roleQuery;
    private final AccountSessionService accountSessionService;

    public UserPageController(UserQuery userQuery, RoleQuery roleQuery, AccountSessionService accountSessionService) {
        this.userQuery = userQuery;
        this.roleQuery = roleQuery;
        this.accountSessionService = accountSessionService;
    }

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

        Map<Integer, LocalDateTime> map = accountSessionService.getLastRequest();
        page.getContent().forEach(userVO -> {
            int userId = userVO.getUserId();
            LocalDateTime lastAccess = map.get(userId);
            if (lastAccess != null) {
                userVO.setLastAccess(DateTimeConverter.format(lastAccess));
            }
        });

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

    @ApiOperation(value = "新增用户页面")
    @GetMapping("/add")
    public String addUserPage(Model model) {
        Set<Role> allRoles = new HashSet<>(new HashSet<>(roleQuery.findAll()));
        Set<Role> userRoles = Collections.emptySet();

        model.addAttribute("allRoles", allRoles);
        model.addAttribute("userRoles", userRoles);
        return "/rbac/user/add";
    }

    @ApiOperation(value = "用户信息编辑页面")
    @GetMapping("/edit/{id}")
    @Deprecated
    public String editUserPage(@PathVariable("id") User user, Model model) {
        Set<Role> allRoles = new HashSet<>(roleQuery.findAll());
        Set<Role> userRoles = userQuery.getUserRoles(user);

        model.addAttribute("allRoles", allRoles);
        model.addAttribute("userRoles", userRoles);
        model.addAttribute("user", user);
        return "/rbac/user/edit";
    }

    @ApiOperation(value = "用户详细信息页面")
    @GetMapping("/detail/{id}")
    public String userDetailPage(@PathVariable("id") int id, Model model) {
        User user = userQuery.findById(id);
        Set<Role> roles = userQuery.getUserRoles(user);
        List<String> names = roles.stream().map(Role::getName).collect(Collectors.toList());

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

    @GetMapping("/profile")
    public String userInfoPage(Model model) {
        User user = UserContext.getUser();
        model.addAttribute("user", user);
        return "/rbac/user/userinfo";
    }

    @ApiOperation(value = "用户修改密码页面")
    @GetMapping("/passwd/{id}")
    public String modifyPasswordPage(@PathVariable("id") Integer id, Model model) {
        model.addAttribute("id", id);
        return "/rbac/user/passwd";
    }

    @GetMapping("/passwd/edit")
    public String editPasswdPage(Model model) {
        return "/rbac/user/editpasswd";
    }

    @ApiOperation(value = "用户角色分配页面")
    @GetMapping("/role/{id}")
    public String assignRolePage(@PathVariable("id") Integer userId, Model model) {
        Set<Role> roles = new HashSet<>(roleQuery.findAll());
        Set<Role> authRoles = userQuery.getUserRoles(userId);

        model.addAttribute("id", userId);
        model.addAttribute("list", roles);
        model.addAttribute("authRoles", authRoles);
        return "/rbac/user/role";
    }
}
