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: AdminUserDeleteController.java
* @Description: 管理员删除用户控制器
*
* @version: v1.0.0
* @author: 李鑫
* @date: 2026年4月13日 上午8:54:34 
*
* Modification History:
* Date         Author          Version            Description
*---------------------------------------------------------*
* 2026年4月13日     李鑫           v1.0.0               新建文件
*/
@WebServlet("/admin/user/delete")
public class AdminUserDeleteController 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");
        if (userIdStr == null) {
            response.sendRedirect(request.getContextPath() + "/admin/user/list");
            return;
        }
        
        Long userId = Long.parseLong(userIdStr);
        
        // 不能删除自己
        if (userId.equals(loginUser.getId())) {
            String encodedError = URLEncoder.encode("不能删除自己", "UTF-8");
            response.sendRedirect(request.getContextPath() + "/admin/user/list?error=" + encodedError);
            return;
        }
        
        boolean success = userDao.delete(userId);
        
        if (success) {
            String encodedMsg = URLEncoder.encode("删除成功", "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);
        }
    }
}