package com.qxgmat.controller.api;

import com.nuliji.tools.MessageHelp;
import com.nuliji.tools.Response;
import com.nuliji.tools.ResponseHelp;
import com.nuliji.tools.Transform;
import com.nuliji.tools.exception.AuthException;
import com.nuliji.tools.exception.ParameterException;
import com.nuliji.tools.exception.SystemException;
import com.qxgmat.data.dao.entity.User;
import com.qxgmat.dto.request.*;
import com.qxgmat.dto.response.MyDto;
import com.qxgmat.help.CaptchaHelp;
import com.qxgmat.help.ShiroHelp;
import com.qxgmat.help.SmsHelp;
import com.qxgmat.service.UsersService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Validator;

/**
 * Created by GaoJie on 2017/10/31.
 */
@RestController
@RequestMapping("/api/auth")
@Api(tags = "用户验证", description = "登录注册找回密码", produces = MediaType.APPLICATION_JSON_VALUE)
public class AuthController {

    @Autowired
    private Validator validator;

    @Autowired
    private CaptchaHelp captchaHelp;

    @Autowired
    private SmsHelp smsHelp;

    @Autowired
    private ShiroHelp shiroHelp;

    @Autowired
    private UsersService usersService;


    @RequestMapping(value = "/token", method = RequestMethod.POST)
    @ApiOperation(value = "验证token", httpMethod = "POST")
    public Response<MyDto> token(@RequestHeader("token") String token, HttpSession session, HttpServletRequest request) {
        User user;
        if (token == null || token.isEmpty()){
            user = shiroHelp.getLoginUser();
            if (user == null) {
                throw new AuthException("未登录");
            }
        }else{
            user = usersService.getUserByToken(token);
            // 用该token登录
            shiroHelp.getSession().login(shiroHelp.user(user.getMobile(), ""));
        }

        User entity = usersService.get(user.getId());
        MyDto dto = Transform.convert(entity, MyDto.class);
        if (!entity.getMobile().isEmpty()){
            dto.setBindMobile(true);
        }
        if (!entity.getWechatUnionid().isEmpty()){
            dto.setBindWechat(true);
        }
        if (entity.getRealStatus() > 0){
            dto.setBindReal(true);
        }
        if(!entity.getPrepareStatus().isEmpty()){
            dto.setBindPrepare(true);
        }
        return ResponseHelp.success(dto);
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ApiOperation(value = "登录/注册", httpMethod = "POST")
    public Response<MyDto> login(@RequestBody @Validated UserLoginDto userLoginDto, HttpSession session, HttpServletRequest request) {
        if (!smsHelp.verifyCode(userLoginDto.getMobile(), userLoginDto.getMobileVerifyCode(), session)) {
            throw new ParameterException("手机验证码错误！");
        }
        try {
            User user = usersService.register(userLoginDto.getMobile(), userLoginDto.getInviteCode(), null);
        }catch (ParameterException e){
            // 忽略已注册信息
        }
        shiroHelp.getSession().login(shiroHelp.user(userLoginDto.getMobile(), ""));

        User entity = shiroHelp.getLoginUser();
        MyDto dto = Transform.convert(entity, MyDto.class);
        if (!entity.getMobile().isEmpty()){
            dto.setBindMobile(true);
        }
        if (!entity.getWechatUnionid().isEmpty()){
            dto.setBindWechat(true);
        }
        if (entity.getRealStatus() > 0){
            dto.setBindReal(true);
        }
        if(!entity.getPrepareStatus().isEmpty()){
            dto.setBindPrepare(true);
        }
        return ResponseHelp.success(dto);
    }


    @RequestMapping(value = "/wechat_pc", method = RequestMethod.GET)
    @ApiOperation(value = "直接微信二维码登录", httpMethod = "GET")
    public Response<Boolean> directWechatPc(
            @RequestParam(required = false, defaultValue = "") String code,
            HttpSession session, HttpServletResponse response) {
        User user = (User) shiroHelp.getLoginUser();
        if (user!=null){
            // 已登录用户，绑定
            usersService.Oauth(user, code, "wechat_pc");
        }else{
            shiroHelp.getSession().login(shiroHelp.oauth(code, "wechat_pc"));
        }
        return MessageHelp.success(true);
    }

    @RequestMapping(value = "/wechat", method = RequestMethod.GET)
    @ApiOperation(value = "直接微信二维码登录", httpMethod = "GET")
    public Response<Boolean> directWechat(
            @RequestParam(required = false, defaultValue = "") String code,
            HttpSession session, HttpServletResponse response) {
        User user = (User) shiroHelp.getLoginUser();
        if (user!=null){
            // 已登录用户，绑定
            usersService.Oauth(user, code, "wechat_native");
        }else{
            shiroHelp.getSession().login(shiroHelp.oauth(code, "wechat_native"));
        }
        return MessageHelp.success(true);
    }

    @RequestMapping(value = "/logout", method = RequestMethod.POST)
    @ApiOperation(value = "登出", httpMethod = "POST")
    public Response<Boolean> logout(HttpSession session, HttpServletRequest request) {
        shiroHelp.logout();
        return ResponseHelp.success(true);
    }

    @RequestMapping(value = "/bind", method = RequestMethod.POST)
    @ApiOperation(value = "绑定手机号", notes="第三方登录后可执行", httpMethod = "POST")
    public Response<Boolean> bind(@RequestBody @Validated UserValidMobileDto userValidMobileDto, HttpSession session) {
        if (!smsHelp.verifyCode(userValidMobileDto.getMobile(), userValidMobileDto.getMobileVerifyCode(), session)) {
            throw new ParameterException("手机验证码错误！");
        }
        User openUser = (User) shiroHelp.getLoginUser();
        if(openUser == null)
            throw new SystemException("第三方登录错误");
        if(openUser.getMobile().length() > 0)
            throw new SystemException("手机号已绑定");

        try{
            // 创建新的账号，设定手机号，绑定第三方登录
            User user = usersService.register(userValidMobileDto.getMobile(), userValidMobileDto.getInviteCode(), openUser);
        }catch (ParameterException e){
            throw new ParameterException("该手机号已注册，请通过手机号进行登录！");
        }
        return ResponseHelp.success(true);
    }

    @RequestMapping(value = "/valid/invite_code", method = RequestMethod.GET)
    @ApiOperation(value = "验证邀请码", notes="查询邀请码对应账号", httpMethod = "GET")
    public Response<String> validInviteCode(
            @RequestParam(required = true) String inviteCode
    ){
        User user = usersService.getByInviteCode(inviteCode);
        if(user == null){
            return ResponseHelp.success(null);
        }else{
            return ResponseHelp.success(user.getNickname());
        }
    }

    @RequestMapping(value = "/valid/mobile", method = RequestMethod.GET)
    @ApiOperation(value = "验证手机号", notes="查询手机对应账号", httpMethod = "GET")
    public Response<Boolean> validMobile(
            @RequestParam(required = true) String mobile
    ){
        User user = usersService.getByMobile(mobile);
        if(user == null){
            return ResponseHelp.success(false);
        }else{
            return ResponseHelp.success(true);
        }
    }
}
