package com.hrs.controller.user;

import com.hrs.dao.HouseDao;
import com.hrs.dao.impl.HouseDaoImpl;
import com.hrs.model.entity.House;
import com.hrs.model.entity.User;
import com.hrs.service.ReservationService;
import com.hrs.service.impl.ReservationServiceImpl;

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;
import java.text.SimpleDateFormat;
import java.util.Date;

/**   
* Copyright: Copyright (c) 2026 chinasofti
* 
* @ClassName: ReservationAddController.java
* @Description: 添加预约控制器
*
* @version: v1.0.0
* @author: 李鑫
* @date: 2026年4月13日 上午9:11:10 
*
* Modification History:
* Date         Author          Version            Description
*---------------------------------------------------------*
* 2026年4月13日     李鑫           v1.0.0               新建文件
*/
@WebServlet("/user/reservation/add")
public class ReservationAddController extends HttpServlet {
    
    private HouseDao houseDao = new HouseDaoImpl();
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        
        String houseIdStr = request.getParameter("houseId");
        if (houseIdStr == null || houseIdStr.trim().isEmpty()) {
            response.sendRedirect(request.getContextPath() + "/user/house/list");
            return;  // ← 必须加return
        }
        
        Long houseId = Long.parseLong(houseIdStr);
        House house = houseDao.findById(houseId);
        
        if (house == null) {
            response.sendRedirect(request.getContextPath() + "/user/house/list");
            return;  // ← 必须加return
        }
        
        HttpSession session = request.getSession(false);
        User loginUser = (User) session.getAttribute("loginUser");
        
        request.setAttribute("house", house);
        request.setAttribute("loginUser", loginUser);
        request.getRequestDispatcher("/jsp/user/reservation_add.jsp").forward(request, response);
        // forward后不需要return，因为这是最后一行
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        
        request.setCharacterEncoding("UTF-8");
        
        HttpSession session = request.getSession(false);
        if (session == null) {
            response.sendRedirect(request.getContextPath() + "/user/login");
            return;  // ← 必须加return
        }
        
        User loginUser = (User) session.getAttribute("loginUser");
        if (loginUser == null || !"0".equals(loginUser.getRoleType())) {
            response.sendRedirect(request.getContextPath() + "/user/login");
            return;  // ← 必须加return
        }
        
        String houseIdStr = request.getParameter("houseId");
        String reserveDate = request.getParameter("reserveDate");
        String reserveTime = request.getParameter("reserveTime");
        String remark = request.getParameter("remark");
        
        // 验证参数
        if (houseIdStr == null || reserveDate == null || reserveTime == null) {
            // 错误时回到预约表单页
            request.setAttribute("error", "请填写完整信息");
            doGet(request, response);
            return;  // ← 必须加return
        }
        
        Long houseId = Long.parseLong(houseIdStr);
        House house = houseDao.findById(houseId);
        
        if (house == null) {
            request.setAttribute("error", "房源不存在");
            doGet(request, response);
            return;  // ← 必须加return
        }
        
        // 组合时间
        String datetimeStr = reserveDate + " " + reserveTime + ":00";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date reserveDateTime;
        try {
            reserveDateTime = sdf.parse(datetimeStr);
        } catch (Exception e) {
            request.setAttribute("error", "时间格式错误");
            doGet(request, response);
            return;  // ← 必须加return
        }
        
        if (reserveDateTime.before(new Date())) {
            request.setAttribute("error", "预约时间不能早于当前时间");
            doGet(request, response);
            return;  // ← 必须加return
        }
        
        // 原来的代码
        // Reservation reservation = new Reservation();
        // reservation.setTenantId(loginUser.getId());
        // reservation.setHouseId(houseId);
        // reservation.setLandlordId(house.getLandlordId());
        // reservation.setReserveTime(reserveDateTime);
        // reservation.setRemark(remark);
        // boolean success = reservationDao.add(reservation);
        
        // 修改为
        ReservationService reservationService = new ReservationServiceImpl();
        ReservationService.ReservationResult result = reservationService.createReservation(
            loginUser.getId(), houseId, reserveDateTime, remark
        );
        
        if (result.isSuccess()) {
            // 对中文消息进行 URL 编码
            String encodedMsg = URLEncoder.encode(result.getMessage(), "UTF-8");
            response.sendRedirect(request.getContextPath() + "/user/reservation/list?msg=" + encodedMsg);
        } else {
            request.setAttribute("error", result.getMessage());
            doGet(request, response);
        }
    }
}