package com.forum.controller;

import com.forum.entity.User;
import com.forum.service.UserService;
import com.forum.utils.MD5;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/user")
public class LoginController {

    @Autowired
    private UserService userService;

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

    @PostMapping("/toLogin")
    public String frontLogin(@RequestParam String getUserName,
                        @RequestParam String getPassWord,
                        HttpSession session,
                        RedirectAttributes attributes){
        User user = userService.checkUser(getUserName, getPassWord);
        if(user != null && user.getType().equals(0)){
            user.setPassword(null);
            session.setAttribute("user", user);

            return "redirect:/";
        }else {
            attributes.addFlashAttribute("msg", "用户名或密码错误");
            return "redirect:/user";
        }
    }

    @GetMapping("/logout")
    public String logout(HttpSession session){
        session.removeAttribute("user");
        return "redirect:/";
    }

        //注册
    @GetMapping("/register")
    public String frontRegister(Model model){

        return "register";
    }
    @PostMapping("/toRegister")
    public String register(User user, RedirectAttributes attributes){

        System.out.println(user.getUsername());
        if (user!=null){
            user.setPassword(MD5.code(user.getPassword()));
            userService.addUser(user);

            attributes.addFlashAttribute("msg", "恭喜注册成功，快去登录吧！");
            return "redirect:/user";
        }else {
            return "/register";
        }

    }

    @GetMapping("/toUpdatePage")
    public String toUpdatePage(){
        return "update";
    }
    @PostMapping ("/toUpdate")
    public String updatePass(@RequestParam String newPassword,
                             @RequestParam String oldPassword,
                             @RequestParam String username,
                             User user,
                             RedirectAttributes attributes){
        if (oldPassword!=null&&newPassword!=null){
            userService.update(MD5.code(newPassword),username);
            attributes.addFlashAttribute("msg","密码修改成功！");
            return "redirect:/user";
        }else {
            attributes.addFlashAttribute("msg","密码修改失败！");
            return "update";
        }


    }
}
