package com.izouma.awesomeAdmin.web;

import com.izouma.awesomeAdmin.domain.User;
import com.izouma.awesomeAdmin.dto.PageQuery;
import com.izouma.awesomeAdmin.exception.BusinessException;
import com.izouma.awesomeAdmin.repo.UserRepo;
import com.izouma.awesomeAdmin.security.Authority;
import com.izouma.awesomeAdmin.service.UserService;
import com.izouma.awesomeAdmin.utils.ObjUtils;
import com.izouma.awesomeAdmin.utils.SecurityUtils;
import com.izouma.awesomeAdmin.utils.excel.ExcelUtils;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@AllArgsConstructor
@RestController
@RequestMapping("/user")
public class UserController extends BaseController {
    private UserRepo    userRepo;
    private UserService userService;

    @PostMapping("/register")
    public User register(@RequestParam String username,
                         @RequestParam String password) {
        User user = User.builder()
                        .username(username)
                        .nickname(username)
                        .password(new BCryptPasswordEncoder().encode(password))
                        .enabled(true)
                        .authorities(Collections.singleton(new Authority(Authority.NAMES.ROLE_USER.name())))
                        .build();
        return userRepo.save(user);
    }

    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/save")
    public User save(@RequestBody User user) {
        if (user.getId() != null) {
            User orig = userRepo.findById(user.getId()).orElseThrow(new BusinessException("无记录"));
            ObjUtils.merge(orig, user);
            return userRepo.save(orig);
        }
        return userRepo.save(user);
    }

    @GetMapping("/my")
    public User my() {
        return userRepo.findById(SecurityUtils.getAuthenticatedUser().getId()).orElseThrow(new BusinessException("用户不存在"));
    }

    @PreAuthorize("hasRole('ADMIN')")
    @GetMapping("/all")
    public Page<User> all(PageQuery pageQuery) {
        return userRepo.findAll(toSpecification(pageQuery, User.class), toPageRequest(pageQuery));
    }

    @PreAuthorize("hasRole('ADMIN')")
    @GetMapping("/get/{id}")
    public User get(@PathVariable Long id) {
        return userRepo.findById(id).orElseThrow(new BusinessException("无记录"));
    }

    @GetMapping("/excel")
    @ResponseBody
    public void excel(HttpServletResponse response, PageQuery pageQuery) throws IOException {
        List<User> data = all(pageQuery).getContent();
        ExcelUtils.export(response, data);
    }

    @PostMapping("/getMaUserInfo")
    @ApiOperation(value = "获取小程序用户信息")
    public User getMaUserInfo(String sessionKey, String rawData, String signature, String encryptedData, String iv) {
        User user = userService.getMaUserInfo(sessionKey, rawData, signature, encryptedData, iv);
        if (user != null) {
            return user;
        }
        throw new BusinessException("获取用户信息失败");
    }

}
