package com.landaiqing.servlet;

import com.landaiqing.entity.UserEntity;
import com.landaiqing.service.UserService;
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;
import java.util.Date;

@WebServlet("/reply")
public class ReplyServlet extends HttpServlet {
    private UserService userService;

    {
        try {
            userService = new UserService();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            String userId = req.getParameter("userId");
            if (StringUtils.isNullOrEmpty(userId)){
                req.setAttribute("errorMsg","userId 的值不能为空!!!");
                req.getRequestDispatcher("error.jsp").forward(req,resp);
                return;
            }
            String replyContent = req.getParameter("replyContent");
            if (StringUtils.isNullOrEmpty(replyContent)){
                req.setAttribute("errorMsg","content 的值不能为空!!!");
                req.getRequestDispatcher("error.jsp").forward(req,resp);
                return;
            }
            Date time = new java.sql.Date(new Date().getTime());

            UserEntity userEntity=new UserEntity();
            userEntity.setUserId(Integer.valueOf(userId));
            userEntity.setReplyContent(replyContent);
            userEntity.setReplyDateTime((java.sql.Date) time);

            int result = userService.reply(userEntity);
            if (result<=0){
                req.setAttribute("errorMsg","插入失败!!!");
                req.getRequestDispatcher("error.jsp").forward(req,resp);
                return;
            }

            resp.sendRedirect("index.jsp");
        } catch (Exception e) {
            req.setAttribute("errorMsg","系统异常!!!");
            req.getRequestDispatcher("error.jsp").forward(req,resp);
            throw new RuntimeException(e);
        }
    }
}
