package com.ruoyi.web.controller.client;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.OrderInfo;
import com.ruoyi.common.core.domain.dto.OrderCreateRequest;
import com.ruoyi.common.core.domain.dto.PaymentRequest;
import com.ruoyi.common.core.domain.dto.RefundRequest;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.service.IOrderInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 客户端订单Controller
 * 
 * @author ruoyi
 * @date 2025-01-27
 */
@RestController
@RequestMapping("/client/order")
public class ClientOrderInfoController extends BaseController
{
    @Autowired
    private IOrderInfoService orderInfoService;

    /**
     * 创建订单
     */
    @Log(title = "创建订单", businessType = BusinessType.INSERT)
    @PostMapping("/create")
    public AjaxResult createOrder(@RequestBody OrderCreateRequest request, HttpServletRequest httpRequest) {
        try {
            // 获取客户端IP
            String clientIp = getClientIp(httpRequest);
            request.setClientIp(clientIp);
            
            return orderInfoService.createOrder(request);
        } catch (Exception e) {
            return AjaxResult.error("创建订单失败: " + e.getMessage());
        }
    }

    /**
     * 支付订单
     */
    @Log(title = "支付订单", businessType = BusinessType.UPDATE)
    @PostMapping("/pay")
    public AjaxResult payOrder(@RequestBody PaymentRequest request) {
        try {
            return orderInfoService.payOrder(request);
        } catch (Exception e) {
            return AjaxResult.error("支付失败: " + e.getMessage());
        }
    }

    /**
     * 支付回调
     */
    @PostMapping("/callback")
    public AjaxResult paymentCallback(@RequestParam("orderId") String orderId,
                                     @RequestParam("tradeNo") String tradeNo,
                                     @RequestParam("payType") String payType) {
        try {
            return orderInfoService.completePayment(orderId, tradeNo, payType);
        } catch (Exception e) {
            return AjaxResult.error("支付回调处理失败: " + e.getMessage());
        }
    }

    /**
     * 确认出货
     */
    @Log(title = "确认出货", businessType = BusinessType.UPDATE)
    @PostMapping("/confirmShipment")
    public AjaxResult confirmShipment(@RequestParam("orderId") String orderId) {
        try {
            return orderInfoService.confirmShipment(orderId);
        } catch (Exception e) {
            return AjaxResult.error("确认出货失败: " + e.getMessage());
        }
    }

    /**
     * 申请退款
     */
    @Log(title = "申请退款", businessType = BusinessType.UPDATE)
    @PostMapping("/refund")
    public AjaxResult refundOrder(@RequestBody RefundRequest request) {
        try {
            return orderInfoService.refundOrder(request);
        } catch (Exception e) {
            return AjaxResult.error("退款申请失败: " + e.getMessage());
        }
    }

    /**
     * 查询用户订单列表
     */
    @GetMapping("/list")
    public AjaxResult getUserOrders() {
        try {
            LoginUser loginUser = SecurityUtils.getLoginUser();
            if (loginUser == null) {
                return AjaxResult.error("用户未登录");
            }
            
            List<OrderInfo> orders = orderInfoService.selectUserOrders(loginUser.getUserId());
            return AjaxResult.success("查询成功", orders);
        } catch (Exception e) {
            return AjaxResult.error("查询订单失败: " + e.getMessage());
        }
    }

    /**
     * 查询订单详情
     */
    @GetMapping("/detail/{orderId}")
    public AjaxResult getOrderDetail(@PathVariable String orderId) {
        try {
            OrderInfo orderInfo = orderInfoService.selectOrderByOrderId(orderId);
            if (orderInfo == null) {
                return AjaxResult.error("订单不存在");
            }
            
            // 检查用户权限
            LoginUser loginUser = SecurityUtils.getLoginUser();
            if (loginUser == null || !loginUser.getUserId().equals(orderInfo.getUserId())) {
                return AjaxResult.error("无权限查看此订单");
            }
            
            return AjaxResult.success("查询成功", orderInfo);
        } catch (Exception e) {
            return AjaxResult.error("查询订单详情失败: " + e.getMessage());
        }
    }

    /**
     * 获取客户端IP地址
     */
    private String getClientIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}
