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.OrderService;
import com.hrs.service.impl.OrderServiceImpl;

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

/**   
* Copyright: Copyright (c) 2026 chinasofti
* 
* @ClassName: OrderCreateController.java
* @Description: 创建订单控制器
*
* @version: v1.0.0
* @author: 李鑫
* @date: 2026年4月13日 上午9:06:38 
*
* Modification History:
* Date         Author          Version            Description
*---------------------------------------------------------*
* 2026年4月13日     李鑫           v1.0.0               新建文件
*/
@WebServlet("/user/order/create")
public class OrderCreateController extends HttpServlet {
    
    private HouseDao houseDao = new HouseDaoImpl();
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        
        // 获取房源ID
        String houseIdStr = request.getParameter("houseId");
        if (houseIdStr == null || houseIdStr.trim().isEmpty()) {
            response.sendRedirect(request.getContextPath() + "/user/house/list");
            return;
        }
        
        Long houseId = Long.parseLong(houseIdStr);
        House house = houseDao.findById(houseId);
        
        if (house == null || !"1".equals(house.getStatus())) {
            response.sendRedirect(request.getContextPath() + "/user/house/list");
            return;
        }
        
        HttpSession session = request.getSession(false);
        if (session == null) {
            response.sendRedirect(request.getContextPath() + "/user/login");
            return;
        }
        
        User loginUser = (User) session.getAttribute("loginUser");
        if (loginUser == null || !"0".equals(loginUser.getRoleType())) {
            response.sendRedirect(request.getContextPath() + "/user/login");
            return;
        }
        
        request.setAttribute("house", house);
        request.setAttribute("loginUser", loginUser);
        request.getRequestDispatcher("/jsp/user/order_create.jsp").forward(request, response);
    }
    
    @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;
        }
        
        User loginUser = (User) session.getAttribute("loginUser");
        if (loginUser == null || !"0".equals(loginUser.getRoleType())) {
            response.sendRedirect(request.getContextPath() + "/user/login");
            return;
        }
        
        String houseIdStr = request.getParameter("houseId");
        String startDateStr = request.getParameter("startDate");
        String endDateStr = request.getParameter("endDate");
        
        if (houseIdStr == null || startDateStr == null || endDateStr == null) {
            response.sendRedirect(request.getContextPath() + "/user/house/list");
            return;
        }
        
        Long houseId = Long.parseLong(houseIdStr);
        House house = houseDao.findById(houseId);
        
        if (house == null || !"1".equals(house.getStatus())) {
            response.sendRedirect(request.getContextPath() + "/user/house/list");
            return;
        }
        
        // 解析日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date startDate, endDate;
        try {
            startDate = sdf.parse(startDateStr);
            endDate = sdf.parse(endDateStr);
        } catch (ParseException e) {
            request.setAttribute("error", "日期格式错误");
            request.setAttribute("house", house);
            request.getRequestDispatcher("/jsp/user/order_create.jsp").forward(request, response);
            return;
        }
        
        // 验证日期
        if (startDate.before(new Date())) {
            request.setAttribute("error", "租赁开始日期不能早于今天");
            request.setAttribute("house", house);
            request.getRequestDispatcher("/jsp/user/order_create.jsp").forward(request, response);
            return;
        }
        
        if (endDate.before(startDate)) {
            request.setAttribute("error", "结束日期不能早于开始日期");
            request.setAttribute("house", house);
            request.getRequestDispatcher("/jsp/user/order_create.jsp").forward(request, response);
            return;
        }
        
        // 修改为
        OrderService orderService = new OrderServiceImpl();
        OrderService.CreateOrderResult result = orderService.createOrder(
            loginUser.getId(), houseId, startDate, endDate
        );
        
        if (result.isSuccess()) {
            // 对中文消息进行 URL 编码
            String encodedMsg = URLEncoder.encode(result.getMessage(), "UTF-8");
            response.sendRedirect(request.getContextPath() + "/user/order/list?msg=" + encodedMsg);
        } else {
            request.setAttribute("error", result.getMessage());
            request.setAttribute("house", house);
            request.getRequestDispatcher("/jsp/user/order_create.jsp").forward(request, response);
        }
    }
    
    /**
     * 生成订单编号
     */
    private String generateOrderNo() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        return "ORD" + sdf.format(new Date());
    }
}