package com.izouma.dingdong.web;

import com.izouma.dingdong.domain.User;
import com.izouma.dingdong.dto.PageQuery;
import com.izouma.dingdong.enums.Identity;
import com.izouma.dingdong.exception.BusinessException;
import com.izouma.dingdong.repo.UserRepo;
import com.izouma.dingdong.security.Authority;
import com.izouma.dingdong.service.UserService;
import com.izouma.dingdong.utils.ObjUtils;
import com.izouma.dingdong.utils.SecurityUtils;
import com.izouma.dingdong.utils.excel.ExcelUtils;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
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.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@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(Authority.getInstance(Authority.NAMES.ROLE_USER)))
                .identity(Identity.USER)
                .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);
        }
//        if (user.getAuthorities() == null) {
//            user.setAuthorities(Collections.singleton(Authority.getInstance(Authority.NAMES.ROLE_USER)));
//            user.setIdentity(Identity.USER);
//        }
        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("获取用户信息失败");
    }

    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/setPasswordAdmin")
    public String setPasswordAdmin(@RequestParam Long userId, @RequestParam String password) {
        return userService.setPassword(userId, password);
    }

    @GetMapping("/allUser")
    public Page<User> allUser(PageQuery pageQuery) {
        Map<String, Object> query = pageQuery.getQuery();
        //只查找身份为user的
        query.put("identity","USER");
        //拉入黑名单的不显示
        query.put("blacklist","false");
        pageQuery.setQuery(query);
        return userRepo.findAll(toSpecification(pageQuery, User.class), toPageRequest(pageQuery));
    }

    @GetMapping("/allAdmin")
    public Page<User> allAdmin(PageQuery pageQuery) {
        //List<User> users = userRepo.findAllByAuthoritiesNotContains(Authority.getInstance(Authority.NAMES.ROLE_USER));
        List<User> users = userRepo.findAllByIdentity(Identity.ADMIN);
        return new PageImpl<>(users, toPageRequest(pageQuery), pageQuery.getPage());
    }

}
