package com.izouma.nineth.web;

import com.izouma.nineth.domain.User;
import com.izouma.nineth.dto.PageQuery;
import com.izouma.nineth.dto.UserDTO;
import com.izouma.nineth.dto.UserRegister;
import com.izouma.nineth.enums.AuthorityName;
import com.izouma.nineth.exception.BusinessException;
import com.izouma.nineth.repo.UserRepo;
import com.izouma.nineth.security.Authority;
import com.izouma.nineth.security.JwtTokenUtil;
import com.izouma.nineth.security.JwtUserFactory;
import com.izouma.nineth.service.FollowService;
import com.izouma.nineth.service.UserService;
import com.izouma.nineth.utils.SecurityUtils;
import com.izouma.nineth.utils.excel.ExcelUtils;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang3.StringUtils;
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.HashMap;
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;
    private FollowService followService;

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


    @PostMapping("/save")
    public User save(@RequestBody User user) {
        if (user.getId() != null) {
            return userService.update(user);
        }
        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<UserDTO> all(@RequestBody PageQuery pageQuery) {
        if (!(SecurityUtils.getAuthenticatedUser() != null && SecurityUtils.getAuthenticatedUser().isAdmin())) {
            pageQuery.getQuery().put("hasRole", "ROLE_MINTER");
        }
        return userService.toDTO(userService.all(pageQuery));
    }

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

    @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 = userService.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("获取用户信息失败");
    }

    @PostMapping("/code2openId")
    @ApiOperation(value = "获取OpenId")
    public String code2openId(@RequestParam String code) throws WxErrorException {
        return userService.code2openId(code);
    }

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

    @PostMapping("/changePassword")
    @ApiOperation("修改密码")
    public String changePassword(@RequestParam String password, @RequestParam String code) {
        return userService.setPassword(SecurityUtils.getAuthenticatedUser().getId(), code, password);
    }

    @PostMapping("/forgotPassword")
    @ApiOperation("忘记密码")
    public String forgotPassword(@RequestParam String phone, @RequestParam String password, @RequestParam String code) {
        return userService.forgotPassword(phone, password, code);
    }

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

    @PostMapping("/bindPhone")
    public void bindPhone(@RequestParam String phone) {
        userService.bindPhone(SecurityUtils.getAuthenticatedUser().getId(), phone);
    }

    @GetMapping("/{id}/follow")
    public void follow(@PathVariable Long id) {
        followService.follow(SecurityUtils.getAuthenticatedUser().getId(), id);
    }

    @GetMapping("/{id}/unfollow")
    public void unfollow(@PathVariable Long id) {
        followService.unfollow(SecurityUtils.getAuthenticatedUser().getId(), id);
    }

    @GetMapping("/myFollows")
    @ApiOperation("我的关注")
    public List<UserDTO> myFollows() {
        return userService.toDTO(userRepo.userFollows(SecurityUtils.getAuthenticatedUser().getId()));
    }

    @GetMapping("/myFollowers")
    @ApiOperation("关注我的")
    public List<UserDTO> myFollowers() {
        return userService.toDTO(userRepo.userFollowers(SecurityUtils.getAuthenticatedUser().getId()));
    }

    @PostMapping("/setTradeCode")
    @ApiOperation("修改交易密码")
    public void setTradeCode(@RequestParam String token, @RequestParam String tradeCode) {
        userService.setTradeCode(SecurityUtils.getAuthenticatedUser().getId(), token, tradeCode);
    }

    @PostMapping("/verifyTradeCode")
    @ApiOperation("验证交易密码")
    public void verifyTradeCode(@RequestParam String tradeCode) {
        userService.verifyTradeCode(SecurityUtils.getAuthenticatedUser().getId(), tradeCode);
    }

    @PostMapping("/searchByPhone")
    public Map<String, Object> searchByPhone(@RequestParam String phone) {
        return userService.searchByPhone(phone);
    }

    @PreAuthorize("hasAnyRole('ADMIN', 'OPERATOR')")
    @PostMapping("/searchByPhoneAdmin")
    public Map<String, Object> searchByPhoneAdmin(@RequestParam String phone) {
        return userService.searchByPhoneAdmin(phone);
    }

    @GetMapping("/tradeCodeStatus")
    public Object tradeCodeStatus() {
        return new HashMap<String, Object>() {{
            put("set", StringUtils.isNotBlank(
                    userRepo.findById(SecurityUtils.getAuthenticatedUser().getId()).map(User::getTradeCode).orElse(null)
            ));
        }};
    }
}


