package com.izouma.nineth.web;

import com.izouma.nineth.aspect.CipherParam;
import com.izouma.nineth.aspect.RequestCipher;
import com.izouma.nineth.domain.User;
import com.izouma.nineth.enums.AuthorityName;
import com.izouma.nineth.exception.AuthenticationException;
import com.izouma.nineth.security.JwtTokenUtil;
import com.izouma.nineth.security.JwtUser;
import com.izouma.nineth.security.JwtUserFactory;
import com.izouma.nineth.service.UserRegisterService;
import com.izouma.nineth.service.UserService;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Objects;

@Slf4j
@AllArgsConstructor
@RestController
@RequestMapping("/auth")
public class AuthenticationController {
    private final AuthenticationManager authenticationManager;
    private final JwtTokenUtil          jwtTokenUtil;
    private final UserService           userService;
    private final UserRegisterService userRegisterService;

    @PostMapping("/login")
    public String loginByUserPwd(String username, String password, Integer expiration) {
        Authentication authentication = authenticate(username, password);
        JwtUser jwtUser = (JwtUser) authentication.getPrincipal();
        return jwtTokenUtil.generateToken(jwtUser);
    }

    @PostMapping("/loginAdmin")
    public String loginByUserPwdAdmin(String username, String password, Integer expiration) {
        Authentication authentication = authenticate(username, password);
        if (!authentication.getAuthorities().contains(new SimpleGrantedAuthority(AuthorityName.ROLE_ADMIN.name()))) {
            throw new AuthenticationException("禁止登录", null);
        }
        JwtUser jwtUser = (JwtUser) authentication.getPrincipal();
        return jwtTokenUtil.generateToken(jwtUser);
    }

    @PostMapping("/phoneLogin")
    @ApiOperation(value = "手机号验证码登录")
    public String phoneLogin(String phone, String code) {
        User user = userRegisterService.loginByPhone(phone, code);
        return jwtTokenUtil.generateToken(JwtUserFactory.create(user));
    }

    @PostMapping("/phonePwdLogin")
    @ApiOperation(value = "手机号密码登录")
    public String phonePwdLogin(String phone, String password) {
        User user = userService.loginByPhonePwd(phone, password);
        return jwtTokenUtil.generateToken(JwtUserFactory.create(user));
    }

    @PostMapping("/phoneRegister")
    @ApiOperation(value = "手机号密码注册")
    public String phonePwdLogin(String phone, String code, String password, String inviteCode, Long invitor,
                                String captcha, String captchaKey) {
//        boolean verify = captchaService.verify(captchaKey, captcha ,true);
//        if (!verify) {
//            throw new BusinessException("验证码错误");
//        }
        User user = userRegisterService.phoneRegister(phone, code, password, inviteCode, invitor);
        return jwtTokenUtil.generateToken(JwtUserFactory.create(user));
    }

    @PostMapping("/mpLogin")
    @ApiOperation(value = "公众号登录")
    public String mpLogin(String code) {
        try {
            User user = userService.loginMp(code);
            return jwtTokenUtil.generateToken(JwtUserFactory.create(user));
        } catch (Exception e) {
            log.error("loginByCode", e);
            throw new AuthenticationException("登陆错误", e);
        }
    }

    @PostMapping("/maLogin")
    @ApiOperation(value = "小程序登录")
    public String maLogin(String code) {
        try {
            User user = userService.loginMa(code);
            return jwtTokenUtil.generateToken(JwtUserFactory.create(user));
        } catch (Exception e) {
            log.error("loginByCode", e);
            throw new AuthenticationException("登陆错误", e);
        }
    }

    @PostMapping("/phonePwdLoginWithCipher")
    @ApiOperation(value = "手机号密码登录(带加密)")
    @RequestCipher
    public String phonePwdLoginWithCipher(String phone, @CipherParam String password) {
        User user = userService.loginByPhonePwd(phone, password);
        return jwtTokenUtil.generateToken(JwtUserFactory.create(user));
    }

    /**
     * Authenticates the user. If something is wrong, an {@link AuthenticationException} will be thrown
     *
     * @return Authentication
     */
    private Authentication authenticate(String username, String password) {
        Objects.requireNonNull(username);
        Objects.requireNonNull(password);
        try {
            //user实现类为jwtUserDetailsService 密码效验为WebSecurityConfigurerAdapter 的 matches方法
            return authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
        } catch (DisabledException e) {
            throw new AuthenticationException("禁止登录", e);
        } catch (BadCredentialsException e) {
            throw new AuthenticationException("用户名或密码错误", e);
        }
    }
}
