package com.weavi.controller;

import com.weavi.entity.Userinfo;
import com.weavi.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


@Controller
@RequestMapping("/weavi")
@Slf4j
public class UserController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private UserService userService;

    @RequestMapping("/loginpage")
    public String loginpage(){
        return "login";
    }

    @RequestMapping("/hello")
    public String hello(){
        return "hello";
    }

    @RequestMapping(value = "/index")
    public String index(){
        return "index";
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST, consumes = "application/json")
//    @ResponseBody
    public String login(@RequestBody Userinfo user, HttpServletRequest request) {
        logger.warn("操作：{}", "登录");

        Map<String, Object> map = new HashMap<String, Object>();
        if (user == null || user.getUserAccount() == null || "".equals(user.getUserAccount())) {
            map.put("resCode", 1);
          //  return map;
        }
        Userinfo userinfo = userService.findUserByAccount(user.getUserAccount());
        if (userinfo == null) {
            map.put("resCode", 2);
          //  return map;
        } else if (!(userinfo.getUserPassword().equals(user.getUserPassword()))) {
            map.put("resCode", 3);
          //  return map;
        }
        System.out.println("user:" + request.getSession().getId());
        request.getSession().setAttribute("user", userinfo);
        logger.warn("用户登录成功：{},{}", new Object[] { userinfo.getUserAccount(), userinfo.getUserName() });
        map.put("resCode", 0);
       // return map;
        return "redirect:/hello";
    }

    @RequestMapping(value = "registpage")
    public String registpage() {
        return "regist";
    }

    @RequestMapping(value = "regist", method = RequestMethod.POST, consumes = "application/json")
    @ResponseBody
    public Object regist(@RequestBody Userinfo user, HttpServletRequest request) {
        logger.warn("操作：{}", "用户注册");
        Map<String, Object> map = userService.addUser(user, request);
        return map;

    }

    @RequestMapping(value = "logout")
    public void logout(HttpServletRequest request, HttpServletResponse response) {
        request.getSession().removeAttribute("user");
        try {
            response.sendRedirect("/weavi");
        } catch (IOException e) {
            e.printStackTrace();
            logger.error("用户退出异常：{},{}", e);
        }
    }

}