package com.quinn.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.quinn.common.QuinnException;
import com.quinn.common.RoleType;
import com.quinn.intergration.AttrIcon;
import com.quinn.pojo.Invite;
import com.quinn.pojo.User;
import com.quinn.pojo.UserInfo;
import com.quinn.service.InviteService;
import com.quinn.service.UserInfoService;
import com.quinn.service.UserService;
import com.quinn.task.SendAsyncEmail;
import com.quinn.utils.AsyncTaskUtil;
import com.quinn.utils.QuinnUtils;
import com.quinn.vo.CheckLoginForm;
import com.quinn.vo.RegisterForm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Controller
public class LoginController {

    @Autowired
    InviteService inviteService;
    @Autowired
    UserService userService;
    @Autowired
    UserInfoService userInfoService;

    @GetMapping({"/","/index","/source/view/index",
            "/blog/read/index"
    })
    public String index(){
        return "index";
    }

    @PostMapping("/checkLogin")
    public void checkLogin(HttpServletResponse response,CheckLoginForm loginForm) throws IOException {
        PrintWriter writer = response.getWriter();
        User user = userService.getOne(new QueryWrapper<User>().eq("username", loginForm.getUsername()));
        String isOk = "no";
        if (user != null){
            // checkPassword
            String password = user.getPassword();
            boolean check = new BCryptPasswordEncoder().matches(loginForm.getPassword(),password);
            if (check){
                isOk = "ok";
            }
        }
        writer.write(isOk);
        writer.flush();
        writer.close();
    }

    @GetMapping("/toLogin")
    public String toLogin(){
        return "login";
    }

    @GetMapping("/register")
    public String toRegister(){
        return "register";
    }

    // 注册业务
    @PostMapping("/checkRegister")
    public void checkRegister(HttpServletResponse response,RegisterForm registerForm) throws IOException {
        response.setCharacterEncoding("UTF-8");
        PrintWriter writer = response.getWriter();
        // 表单密码重复判断
        if (!registerForm.getPassword().equals(registerForm.getRepassword())){
            toResult(writer,"两次输入密码不一致！");
            return;
        }
        // 用户名已存在
        User hasUser = userService.getOne(new QueryWrapper<User>().eq("username", registerForm.getUsername()));
        if (hasUser!=null){
            toResult(writer,"用户名太热门了，请更换用户名");
            return;
        }
        // 验证邀请码
        Invite invite = inviteService.getOne(new QueryWrapper<Invite>()
                .eq("code", registerForm.getCode())
                .eq("status",'0'));
        if (invite==null){
            toResult(writer,"注册码不存在!");
            return;
        }
        if (!invite.getApplyEmail().equals(registerForm.getEmail())){
            toResult(writer,"请使用申请注册码邮箱注册用户!");
            return;
        }
        toResult(writer,"ok");
    }

    // 注册业务
    @PostMapping("/register")
    public String register(RegisterForm registerForm, Model model) throws IOException {
        // 表单密码重复判断
        if (!registerForm.getPassword().equals(registerForm.getRepassword())){
            throw new QuinnException("防爬虫,两次输入密码不一致！");
        }
        // 用户名已存在
        User hasUser = userService.getOne(new QueryWrapper<User>().eq("username", registerForm.getUsername()));
        if (hasUser!=null){
            throw new QuinnException("防爬虫,用户名太热门了，请更换用户名");
        }

        // 验证邀请码
        Invite invite = inviteService.getOne(new QueryWrapper<Invite>().eq("code", registerForm.getCode()));
        if (invite==null){
            throw new QuinnException("防爬虫,注册码不存在!");
        }
        if (!invite.getApplyEmail().equals(registerForm.getEmail())){
            throw new QuinnException("防爬虫,请使用申请注册码邮箱注册用户!");
        }
        // 构建用户对象
        User user = new User();
        user.setUid(QuinnUtils.getUuid()); // 用户唯一id
        user.setRole(RoleType.NORMAL.name());
        user.setUsername(registerForm.getUsername());
        // 密码加密
        String bCryptPassword = new BCryptPasswordEncoder().encode(registerForm.getPassword());
        user.setAvatar(AttrIcon.INSTANCE.generateImgUrl(registerForm.getUsername()));
        user.setPassword(bCryptPassword);
        user.setGmtCreate(QuinnUtils.getTime());
        user.setLoginDate(QuinnUtils.getTime());
        // 保存对象！
        userService.save(user);
        // 激活邀请码
        invite.setActiveTime(QuinnUtils.getTime());
        invite.setStatus(1);
        invite.setUid(user.getUid());
        inviteService.updateById(invite);
        userInfoService.save(new UserInfo().setUid(user.getUid()).setEmail(registerForm.getEmail()));
        // 发送注册成功通知邮件
        AsyncTaskUtil.INSTANCE.submit(new SendAsyncEmail(registerForm.getUsername(),registerForm.getEmail()));
        // 注册成功，重定向到登录页面
        return "redirect:/toLogin";
    }

    private void toResult(PrintWriter writer, String msg) {
        writer.write(msg);
        writer.flush();
        writer.close();
    }

}
