package com.landaiqing.servlet.system;

import com.landaiqing.entity.AdminUserEntity;
import com.landaiqing.service.AdminUserService;
import com.mysql.cj.util.StringUtils;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

@WebServlet("/addAdmin")
public class AddAdmin extends HttpServlet {
    private AdminUserService adminUserService;

    {
        try {
            adminUserService = new AdminUserService();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {

            String adminUseName = req.getParameter("adminUserName");
            if (StringUtils.isNullOrEmpty(adminUseName)){
                req.setAttribute("errorMsg","adminUseName 的值不能为空!!!");
                req.getRequestDispatcher("error.jsp").forward(req,resp);
                return;
            }
            String adminPassword = req.getParameter("adminPassword");
            if (StringUtils.isNullOrEmpty(adminPassword)){
                req.setAttribute("errorMsg","adminPassword 的值不能为空!!!");
                req.getRequestDispatcher("error.jsp").forward(req,resp);
                return;
            }
            String isValid = req.getParameter("isValid");
            if (StringUtils.isNullOrEmpty(isValid)){
                req.setAttribute("errorMsg","isValid 的值不能为空!!!");
                req.getRequestDispatcher("error.jsp").forward(req,resp);
                return;
            }


            AdminUserEntity adminUserEntity=new AdminUserEntity();
            adminUserEntity.setAdminUserName(adminUseName);
            adminUserEntity.setAdminPassword(adminPassword);
            adminUserEntity.setIsValid(Integer.valueOf(isValid));

            int result = adminUserService.insertAdmin(adminUserEntity);
            if (result<=0){
                req.setAttribute("errorMsg","插入失败!!!");
                req.getRequestDispatcher("error.jsp").forward(req,resp);
                return;
            }
            resp.sendRedirect("./System/index.jsp");
        } catch (Exception e) {
            req.setAttribute("errorMsg","系统异常!!!");
            req.getRequestDispatcher("error.jsp").forward(req,resp);
            throw new RuntimeException(e);
        }
    }
}
