package com.izouma.jiashanxia.web;

import cn.hutool.core.util.ObjectUtil;
import com.izouma.jiashanxia.domain.User;
import com.izouma.jiashanxia.dto.PageQuery;
import com.izouma.jiashanxia.dto.UserRegister;
import com.izouma.jiashanxia.enums.AuthorityName;
import com.izouma.jiashanxia.exception.BusinessException;
import com.izouma.jiashanxia.repo.UserRepo;
import com.izouma.jiashanxia.security.Authority;
import com.izouma.jiashanxia.security.JwtTokenUtil;
import com.izouma.jiashanxia.security.JwtUserFactory;
import com.izouma.jiashanxia.service.UserService;
import com.izouma.jiashanxia.utils.ObjUtils;
import com.izouma.jiashanxia.utils.SecurityUtils;
import com.izouma.jiashanxia.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.Collections;
import java.util.List;
import java.util.Map;

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

    @PostMapping("/register")
    public User register(@RequestParam String username,
                         @RequestParam String password) {
        UserRegister user = UserRegister.builder()
                .username(username)
                .nickname(username)
                .password(new BCryptPasswordEncoder().encode(password))
                .authorities(Collections.singleton(Authority.get(AuthorityName.ROLE_USER)))
                .build();
        return userService.create(user);
    }

    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/create")
    public User create(@RequestBody UserRegister userRegister) {
        return userService.create(userRegister);
    }

    @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("用户不存在"));
    }

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

    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/all")
    public Page<User> all(@RequestBody PageQuery pageQuery) {
        return userService.all(pageQuery);
    }

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

    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/del/{id}")
    public void del(@PathVariable Long id) {
        userService.del(id);
    }

    @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);
    }

    @PostMapping("/changePassword")
    public String changePassword(@RequestParam String password, @RequestParam String key, @RequestParam String code) {
        return userService.setPassword(SecurityUtils.getAuthenticatedUser().getId(), key, code, password);
    }

    @PreAuthorize("hasRole('ADMIN')")
    @GetMapping("/getToken/{userId}")
    public String getToken(@PathVariable Long userId) {
        return jwtTokenUtil.generateToken(JwtUserFactory.create(userRepo.findById(userId)
                .orElseThrow(new BusinessException("用户不存在"))));
    }

    @PostMapping("/employee")
    @ApiOperation("根据团队id员工列表")
    public List<User> employee(Long companyId) {
        return userRepo.findAllByCompanyIdAndDelFalse(companyId);
    }

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

    @PostMapping("/updateUserInfo")
    public void updateUserInfo(@RequestBody Map<String, Object> map) {
        userService.updateUserInfo(map);
    }

    @GetMapping("/myPromotion")
    @ApiOperation("我的推广列表")
    public List<User> myPromotion() {
        return userService.myPromotion(SecurityUtils.getAuthenticatedUser().getId());
    }

    @PostMapping("/promotion")
    @ApiOperation("企业端推广列表")
    public Page<User> promotion(@RequestBody PageQuery pageQuery) {
        Map<String, Object> query = pageQuery.getQuery();
        String userId = String.valueOf(query.get("userId"));
        query.remove("userId");
        return userService.myPromotion(pageQuery, Long.parseLong(userId));
    }

    @PreAuthorize("hasAnyRole('ADMIN','CREATOR')")
    @PostMapping("/myEmployee")
    @ApiOperation("员工列表")
    public Page<User> myEmployee(@RequestBody PageQuery pageQuery) {
        return userService.myEmployee(pageQuery, SecurityUtils.getAuthenticatedUser());
    }

    @GetMapping("/overview")
    public Map<String, Object> overview() {
        return userService.overview(SecurityUtils.getAuthenticatedUser().getId());
    }

    @PostMapping("/user")
    @ApiOperation("无公司的用户")
    public List<User> user(Long companyId) {
        List<User> users = userRepo.findAllByCompanyIdIsNullAndDelFalse();
        if (ObjectUtil.isNotEmpty(companyId)) {
            users.addAll(userRepo.findAllByCompanyIdAndDelFalse(companyId));
        }
        return users;
    }
}
