package com.hrs.controller.admin;

import com.hrs.dao.UserDao;
import com.hrs.dao.impl.UserDaoImpl;
import com.hrs.model.entity.User;

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;
import java.net.URLEncoder;

/**   
* Copyright: Copyright (c) 2026 chinasofti
* 
* @ClassName: AdminUserStatusController.java
* @Description: 管理员操作用户状态控制器（启用/禁用)
*
* @version: v1.0.0
* @author: 李鑫
* @date: 2026年4月13日 上午8:54:49 
*
* Modification History:
* Date         Author          Version            Description
*---------------------------------------------------------*
* 2026年4月13日     李鑫           v1.0.0               新建文件
*/
@WebServlet("/admin/user/status")
public class AdminUserStatusController extends HttpServlet {
    
    private UserDao userDao = new UserDaoImpl();
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        
        HttpSession session = request.getSession(false);
        if (session == null) {
            response.sendRedirect(request.getContextPath() + "/user/login");
            return;
        }
        
        User loginUser = (User) session.getAttribute("loginUser");
        if (loginUser == null || !"2".equals(loginUser.getRoleType())) {
            response.sendRedirect(request.getContextPath() + "/user/login");
            return;
        }
        
        String userIdStr = request.getParameter("id");
        String action = request.getParameter("action"); // enable 或 disable
        
        if (userIdStr == null || action == null) {
            response.sendRedirect(request.getContextPath() + "/admin/user/list");
            return;
        }
        
        Long userId = Long.parseLong(userIdStr);
        String status = "enable".equals(action) ? "1" : "2";
        
        boolean success = userDao.updateStatus(userId, status);
        
        if (success) {
            String msg = "enable".equals(action) ? "用户已启用" : "用户已禁用";
            String encodedMsg = URLEncoder.encode(msg, "UTF-8");
            response.sendRedirect(request.getContextPath() + "/admin/user/list?msg=" + encodedMsg);
        } else {
            String encodedError = URLEncoder.encode("操作失败", "UTF-8");
            response.sendRedirect(request.getContextPath() + "/admin/user/list?error=" + encodedError);
        }
    }
}