package com.hrs.controller.user;

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: OrderPayController.java
* @Description: 订单支付控制器（模拟支付）
*
* @version: v1.0.0
* @author: 李鑫
* @date: 2026年4月13日 上午9:07:43 
*
* Modification History:
* Date         Author          Version            Description
*---------------------------------------------------------*
* 2026年4月13日     李鑫           v1.0.0               新建文件
*/
@WebServlet("/user/order/pay")
public class OrderPayController 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 || !"0".equals(loginUser.getRoleType())) {
            response.sendRedirect(request.getContextPath() + "/user/login");
            return;
        }
        
        String orderIdStr = request.getParameter("id");
        if (orderIdStr == null) {
            response.sendRedirect(request.getContextPath() + "/user/order/list");
            return;
        }
        
        Long orderId = Long.parseLong(orderIdStr);
        Order order = orderDao.findById(orderId);
        
        if (order == null || !order.getTenantId().equals(loginUser.getId())) {
            response.sendRedirect(request.getContextPath() + "/user/order/list");
            return;
        }
        
        // 模拟支付：更新支付状态为已支付
        boolean success = orderDao.updatePayStatus(orderId, "1");
        
        if (success) {
            String encodedMsg = URLEncoder.encode("支付成功", "UTF-8");
            response.sendRedirect(request.getContextPath() + "/user/order/list?msg=" + encodedMsg);
        } else {
            String encodedError = URLEncoder.encode("支付失败", "UTF-8");
            response.sendRedirect(request.getContextPath() + "/user/order/list?error=" + encodedError);
        }
    }
}