package com.hrs.controller.user;

import com.hrs.dao.UserDao;
import com.hrs.dao.impl.UserDaoImpl;
import com.hrs.service.UserService;
import com.hrs.service.impl.UserServiceImpl;
import com.hrs.model.entity.User;
import com.hrs.util.MD5Util;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**   
* Copyright: Copyright (c) 2026 chinasofti
* 
* @ClassName: LoginController.java
* @Description: 登录控制器
*
* @version: v1.0.0
* @author: 李鑫
* @date: 2026年4月13日 上午9:05:32 
*
* Modification History:
* Date         Author          Version            Description
*---------------------------------------------------------*
* 2026年4月13日     李鑫           v1.0.0               新建文件
*/
@WebServlet("/user/login")
public class LoginController extends HttpServlet {
    
    private UserDao userDao = new UserDaoImpl();
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        // GET请求：显示登录页面
        // 如果有消息（如注册成功），传递给页面
        String message = request.getParameter("message");
        if (message != null) {
            request.setAttribute("message", message);
        }
        request.getRequestDispatcher("/jsp/user/login.jsp").forward(request, response);
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        // POST请求：处理登录表单提交
        request.setCharacterEncoding("UTF-8");
        
        // 1. 获取表单参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String roleType = request.getParameter("roleType"); // 前端传：0-租客 1-房东 2-管理员
        
        // 2. 基础验证
        if (username == null || username.trim().isEmpty() ||
            password == null || password.trim().isEmpty()) {
            request.setAttribute("error", "用户名和密码不能为空");
            request.getRequestDispatcher("/jsp/user/login.jsp").forward(request, response);
            return;
        }
        
        // 3. 密码MD5加密（因为数据库里存的是MD5）
        String encryptedPassword = MD5Util.md5(password);
        
        // 4. 调用Service查询用户
        UserService userService = new UserServiceImpl();
        User user = userService.login(username, password, roleType);
        
        // 5. 验证结果
        if (user == null) {
            // 登录失败
            request.setAttribute("error", "用户名或密码错误");
            request.getRequestDispatcher("/jsp/user/login.jsp").forward(request, response);
            return;
        }
        
        // 6. 验证角色是否匹配
        if (!user.getRoleType().equals(roleType)) {
            request.setAttribute("error", "角色类型不匹配");
            request.getRequestDispatcher("/jsp/user/login.jsp").forward(request, response);
            return;
        }
        
        // 7. 验证账号状态
        if ("2".equals(user.getStatus())) {
            request.setAttribute("error", "账号已被禁用，请联系管理员");
            request.getRequestDispatcher("/jsp/user/login.jsp").forward(request, response);
            return;
        }
        
        // 8. 登录成功，保存用户信息到Session
        HttpSession session = request.getSession();
        session.setAttribute("loginUser", user);
        session.setAttribute("userRole", user.getRoleType());
        session.setMaxInactiveInterval(30 * 60); // 30分钟超时
        
        // 9. 根据角色跳转到不同首页
        String redirectUrl = "/HRS/";
        switch (user.getRoleType()) {
            case "0": // 租客
                redirectUrl = "/HRS/jsp/user/index.jsp";
                break;
            case "1": // 房东
                redirectUrl = "/HRS/jsp/landlord/index.jsp";
                break;
            case "2": // 管理员
                redirectUrl = "/HRS/jsp/admin/index.jsp";
                break;
        }
        
        response.sendRedirect(redirectUrl);
    }
}