package com.hrs.controller.landlord;

import com.hrs.dao.OrderDao;
import com.hrs.dao.impl.OrderDaoImpl;
import com.hrs.model.entity.Order;
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: OrderConfirmController.java
* @Description: 房东确认签约控制器
*
* @version: v1.0.0
* @author: 李鑫
* @date: 2026年4月13日 上午8:56:51 
*
* Modification History:
* Date         Author          Version            Description
*---------------------------------------------------------*
* 2026年4月13日     李鑫           v1.0.0               新建文件
*/
@WebServlet("/landlord/order/confirm")
public class OrderConfirmController extends HttpServlet {
    
    private OrderDao orderDao = new OrderDaoImpl();
    
    @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 || !"1".equals(loginUser.getRoleType())) {
            response.sendRedirect(request.getContextPath() + "/user/login");
            return;
        }
        
        String orderIdStr = request.getParameter("id");
        if (orderIdStr == null) {
            response.sendRedirect(request.getContextPath() + "/landlord/order/list");
            return;
        }
        
        Long orderId = Long.parseLong(orderIdStr);
        Order order = orderDao.findById(orderId);
        
        // 验证订单是否属于该房东的房源
        if (order == null) {
            String encodedError = URLEncoder.encode("订单不存在", "UTF-8");
            response.sendRedirect(request.getContextPath() + "/landlord/order/list?error=" + encodedError);
            return;
        }
        
        boolean success = orderDao.updateStatus(orderId, "1"); // 1-已签约
        
        if (success) {
            String encodedMsg = URLEncoder.encode("已确认签约", "UTF-8");
            response.sendRedirect(request.getContextPath() + "/landlord/order/list?msg=" + encodedMsg);
        } else {
            String encodedError = URLEncoder.encode("操作失败", "UTF-8");
            response.sendRedirect(request.getContextPath() + "/landlord/order/list?error=" + encodedError);
        }
    }
}