using System.Security.Claims;
using HoneyBox.Core.Interfaces;
using HoneyBox.Model.Base;
using HoneyBox.Model.Models;
using HoneyBox.Model.Models.Lottery;
using HoneyBox.Model.Models.Order;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

using OrderPrizeOrderLogRequest = HoneyBox.Model.Models.Order.PrizeOrderLogRequest;

namespace HoneyBox.Api.Controllers;

/// <summary>
/// 订单控制器 - 处理订单创建、查询和抽奖结果
/// </summary>
/// <remarks>
/// 提供一番赏、无限赏、商城等订单的创建、金额计算、查询和抽奖结果查询功能
/// </remarks>
[ApiController]
[Route("api")]
public class OrderController : ControllerBase
{
    private readonly IOrderService _orderService;
    private readonly ILotteryService _lotteryService;
    private readonly ILogger<OrderController> _logger;

    public OrderController(
        IOrderService orderService,
        ILotteryService lotteryService,
        ILogger<OrderController> logger)
    {
        _orderService = orderService;
        _lotteryService = lotteryService;
        _logger = logger;
    }

    #region 一番赏订单

    /// <summary>
    /// 一番赏订单金额计算
    /// </summary>
    /// <remarks>
    /// POST /api/ordermoney
    /// 
    /// 计算一番赏订单金额，包含优惠券抵扣、余额抵扣等
    /// Requirements: 1.1-1.6
    /// </remarks>
    /// <param name="request">订单金额计算请求参数</param>
    /// <returns>订单金额计算结果</returns>
    [HttpPost("ordermoney")]
    [Authorize]
    [ProducesResponseType(typeof(ApiResponse<OrderCalculationDto>), StatusCodes.Status200OK)]
    [ProducesResponseType(typeof(ApiResponse<OrderCalculationDto>), StatusCodes.Status401Unauthorized)]
    public async Task<ApiResponse<OrderCalculationDto>> CalculateOrderMoney([FromBody] OrderMoneyRequest? request)
    {
        var userId = GetCurrentUserId();
        if (userId == null)
        {
            return ApiResponse<OrderCalculationDto>.Unauthorized();
        }

        try
        {
            if (request == null)
            {
                return ApiResponse<OrderCalculationDto>.Fail("请求参数不能为空");
            }

            if (request.GoodsId <= 0)
            {
                return ApiResponse<OrderCalculationDto>.Fail("商品ID不能为空");
            }

            if (request.PrizeNum <= 0)
            {
                return ApiResponse<OrderCalculationDto>.Fail("抽奖次数不能为空");
            }

            var result = await _orderService.CalculateOrderMoneyAsync(userId.Value, request);
            return ApiResponse<OrderCalculationDto>.Success(result);
        }
        catch (InvalidOperationException ex)
        {
            _logger.LogWarning("Calculate order money failed: UserId={UserId}, GoodsId={GoodsId}, Error={Error}",
                userId, request?.GoodsId, ex.Message);
            return ApiResponse<OrderCalculationDto>.Fail(ex.Message);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to calculate order money: UserId={UserId}, GoodsId={GoodsId}",
                userId, request?.GoodsId);
            return ApiResponse<OrderCalculationDto>.Fail("计算订单金额失败");
        }
    }

    /// <summary>
    /// 一番赏订单创建
    /// </summary>
    /// <remarks>
    /// POST /api/orderbuy
    /// 
    /// 创建一番赏订单并执行抽奖，返回订单信息和抽奖结果
    /// Requirements: 2.1-2.6
    /// </remarks>
    /// <param name="request">订单创建请求参数</param>
    /// <returns>订单创建结果，包含订单号和支付信息</returns>
    [HttpPost("orderbuy")]
    [Authorize]
    [ProducesResponseType(typeof(ApiResponse<OrderBuyResponseDto>), StatusCodes.Status200OK)]
    [ProducesResponseType(typeof(ApiResponse<OrderBuyResponseDto>), StatusCodes.Status401Unauthorized)]
    public async Task<ApiResponse<OrderBuyResponseDto>> CreateOrder([FromBody] OrderBuyRequest? request)
    {
        var userId = GetCurrentUserId();
        if (userId == null)
        {
            return ApiResponse<OrderBuyResponseDto>.Unauthorized();
        }

        try
        {
            if (request == null)
            {
                return ApiResponse<OrderBuyResponseDto>.Fail("请求参数不能为空");
            }

            if (request.GoodsId <= 0)
            {
                return ApiResponse<OrderBuyResponseDto>.Fail("商品ID不能为空");
            }

            if (request.PrizeNum <= 0)
            {
                return ApiResponse<OrderBuyResponseDto>.Fail("抽奖次数不能为空");
            }

            var result = await _orderService.CreateOrderAsync(userId.Value, request);
            return ApiResponse<OrderBuyResponseDto>.Success(result, "支付成功");
        }
        catch (InvalidOperationException ex)
        {
            _logger.LogWarning("Create order failed: UserId={UserId}, GoodsId={GoodsId}, Error={Error}",
                userId, request?.GoodsId, ex.Message);
            
            // 未绑定手机号返回特殊状态码 -9，前端根据此状态码跳转绑定页面
            if (ex.Message.Contains("绑定手机号"))
            {
                return ApiResponse<OrderBuyResponseDto>.Fail(ex.Message, -9);
            }
            
            return ApiResponse<OrderBuyResponseDto>.Fail(ex.Message);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to create order: UserId={UserId}, GoodsId={GoodsId}, Message={Message}, StackTrace={StackTrace}",
                userId, request?.GoodsId, ex.Message, ex.StackTrace);
            return ApiResponse<OrderBuyResponseDto>.Fail($"创建订单失败: {ex.Message}");
        }
    }

    #endregion

    #region 无限赏订单

    /// <summary>
    /// 无限赏订单金额计算
    /// POST /api/infinite_ordermoney
    /// Requirements: 3.1-3.3
    /// </summary>
    [HttpPost("infinite_ordermoney")]
    [Authorize]
    public async Task<ApiResponse<OrderCalculationDto>> CalculateInfiniteOrderMoney([FromBody] InfiniteOrderMoneyRequest? request)
    {
        var userId = GetCurrentUserId();
        if (userId == null)
        {
            return ApiResponse<OrderCalculationDto>.Unauthorized();
        }

        try
        {
            if (request == null)
            {
                return ApiResponse<OrderCalculationDto>.Fail("请求参数不能为空");
            }

            if (request.GoodsId <= 0)
            {
                return ApiResponse<OrderCalculationDto>.Fail("商品ID不能为空");
            }

            if (request.PrizeNum <= 0)
            {
                return ApiResponse<OrderCalculationDto>.Fail("抽奖次数不能为空");
            }

            var result = await _orderService.CalculateInfiniteOrderMoneyAsync(userId.Value, request);
            return ApiResponse<OrderCalculationDto>.Success(result);
        }
        catch (InvalidOperationException ex)
        {
            _logger.LogWarning("Calculate infinite order money failed: UserId={UserId}, GoodsId={GoodsId}, Error={Error}",
                userId, request?.GoodsId, ex.Message);
            return ApiResponse<OrderCalculationDto>.Fail(ex.Message);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to calculate infinite order money: UserId={UserId}, GoodsId={GoodsId}",
                userId, request?.GoodsId);
            return ApiResponse<OrderCalculationDto>.Fail("计算订单金额失败");
        }
    }

    /// <summary>
    /// 无限赏订单创建
    /// POST /api/infinite_orderbuy
    /// Requirements: 4.1-4.3
    /// </summary>
    [HttpPost("infinite_orderbuy")]
    [Authorize]
    public async Task<ApiResponse<OrderBuyResponseDto>> CreateInfiniteOrder([FromBody] InfiniteOrderBuyRequest? request)
    {
        var userId = GetCurrentUserId();
        if (userId == null)
        {
            return ApiResponse<OrderBuyResponseDto>.Unauthorized();
        }

        try
        {
            if (request == null)
            {
                return ApiResponse<OrderBuyResponseDto>.Fail("请求参数不能为空");
            }

            if (request.GoodsId <= 0)
            {
                return ApiResponse<OrderBuyResponseDto>.Fail("商品ID不能为空");
            }

            if (request.PrizeNum <= 0)
            {
                return ApiResponse<OrderBuyResponseDto>.Fail("抽奖次数不能为空");
            }

            var result = await _orderService.CreateInfiniteOrderAsync(userId.Value, request);
            return ApiResponse<OrderBuyResponseDto>.Success(result, "支付成功");
        }
        catch (InvalidOperationException ex)
        {
            _logger.LogWarning("Create infinite order failed: UserId={UserId}, GoodsId={GoodsId}, Error={Error}",
                userId, request?.GoodsId, ex.Message);
            
            // 未绑定手机号返回特殊状态码 -9，前端根据此状态码跳转绑定页面
            if (ex.Message.Contains("绑定手机号"))
            {
                return ApiResponse<OrderBuyResponseDto>.Fail(ex.Message, -9);
            }
            
            return ApiResponse<OrderBuyResponseDto>.Fail(ex.Message);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to create infinite order: UserId={UserId}, GoodsId={GoodsId}",
                userId, request?.GoodsId);
            return ApiResponse<OrderBuyResponseDto>.Fail("创建订单失败");
        }
    }

    #endregion

    #region 商城订单

    /// <summary>
    /// 商城订单金额计算
    /// POST /api/mall_ordermoney
    /// Requirements: 5.1-5.3
    /// </summary>
    [HttpPost("mall_ordermoney")]
    [Authorize]
    public async Task<ApiResponse<OrderCalculationDto>> CalculateMallOrderMoney([FromBody] MallOrderMoneyRequest? request)
    {
        var userId = GetCurrentUserId();
        if (userId == null)
        {
            return ApiResponse<OrderCalculationDto>.Unauthorized();
        }

        try
        {
            if (request == null)
            {
                return ApiResponse<OrderCalculationDto>.Fail("请求参数不能为空");
            }

            if (request.GoodsId <= 0)
            {
                return ApiResponse<OrderCalculationDto>.Fail("商品ID不能为空");
            }

            var result = await _orderService.CalculateMallOrderMoneyAsync(userId.Value, request);
            return ApiResponse<OrderCalculationDto>.Success(result);
        }
        catch (InvalidOperationException ex)
        {
            _logger.LogWarning("Calculate mall order money failed: UserId={UserId}, GoodsId={GoodsId}, Error={Error}",
                userId, request?.GoodsId, ex.Message);
            return ApiResponse<OrderCalculationDto>.Fail(ex.Message);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to calculate mall order money: UserId={UserId}, GoodsId={GoodsId}",
                userId, request?.GoodsId);
            return ApiResponse<OrderCalculationDto>.Fail("计算订单金额失败");
        }
    }

    #endregion

    #region 订单查询

    /// <summary>
    /// 订单列表查询
    /// </summary>
    /// <remarks>
    /// POST /api/order_list
    /// 
    /// 获取当前用户的订单列表，支持按状态筛选和分页
    /// Requirements: 6.1-6.4
    /// </remarks>
    /// <param name="request">订单列表请求参数</param>
    /// <returns>订单列表分页数据</returns>
    [HttpPost("order_list")]
    [Authorize]
    [ProducesResponseType(typeof(ApiResponse<PageResponse<OrderListDto>>), StatusCodes.Status200OK)]
    [ProducesResponseType(typeof(ApiResponse<PageResponse<OrderListDto>>), StatusCodes.Status401Unauthorized)]
    public async Task<ApiResponse<PageResponse<OrderListDto>>> GetOrderList([FromBody] OrderListRequest? request)
    {
        var userId = GetCurrentUserId();
        if (userId == null)
        {
            return ApiResponse<PageResponse<OrderListDto>>.Unauthorized();
        }

        try
        {
            request ??= new OrderListRequest();
            if (request.Page < 1) request.Page = 1;
            if (request.PageSize < 1) request.PageSize = 10;

            var result = await _orderService.GetOrderListAsync(userId.Value, request);
            return ApiResponse<PageResponse<OrderListDto>>.Success(result);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to get order list: UserId={UserId}", userId);
            return ApiResponse<PageResponse<OrderListDto>>.Fail("获取订单列表失败");
        }
    }

    /// <summary>
    /// 订单详情查询
    /// POST /api/order_detail
    /// Requirements: 7.1-7.3
    /// </summary>
    [HttpPost("order_detail")]
    [Authorize]
    public async Task<ApiResponse<OrderInfoDto>> GetOrderDetail([FromBody] OrderDetailRequest? request)
    {
        var userId = GetCurrentUserId();
        if (userId == null)
        {
            return ApiResponse<OrderInfoDto>.Unauthorized();
        }

        try
        {
            if (request == null || string.IsNullOrWhiteSpace(request.OrderNum))
            {
                return ApiResponse<OrderInfoDto>.Fail("订单号不能为空");
            }

            var result = await _orderService.GetOrderDetailAsync(userId.Value, request.OrderNum);
            return ApiResponse<OrderInfoDto>.Success(result);
        }
        catch (InvalidOperationException ex)
        {
            _logger.LogWarning("Get order detail failed: UserId={UserId}, OrderNum={OrderNum}, Error={Error}",
                userId, request?.OrderNum, ex.Message);
            return ApiResponse<OrderInfoDto>.Fail(ex.Message);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to get order detail: UserId={UserId}, OrderNum={OrderNum}",
                userId, request?.OrderNum);
            return ApiResponse<OrderInfoDto>.Fail("获取订单详情失败");
        }
    }

    #endregion

    #region 抽奖结果查询

    /// <summary>
    /// 一番赏抽奖结果查询
    /// POST /api/prizeorderlog
    /// Requirements: 8.1-8.3
    /// </summary>
    [HttpPost("prizeorderlog")]
    [Authorize]
    public async Task<ApiResponse<PrizeOrderLogResponseDto>> GetPrizeOrderLog([FromBody] OrderPrizeOrderLogRequest? request)
    {
        var userId = GetCurrentUserId();
        if (userId == null)
        {
            return ApiResponse<PrizeOrderLogResponseDto>.Unauthorized();
        }

        try
        {
            if (request == null || string.IsNullOrWhiteSpace(request.OrderNum))
            {
                return ApiResponse<PrizeOrderLogResponseDto>.Fail("订单号不能为空");
            }

            var result = await _orderService.GetPrizeOrderLogAsync(userId.Value, request.OrderNum);
            return ApiResponse<PrizeOrderLogResponseDto>.Success(result);
        }
        catch (InvalidOperationException ex)
        {
            _logger.LogWarning("Get prize order log failed: UserId={UserId}, OrderNum={OrderNum}, Error={Error}",
                userId, request?.OrderNum, ex.Message);
            return ApiResponse<PrizeOrderLogResponseDto>.Fail(ex.Message);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to get prize order log: UserId={UserId}, OrderNum={OrderNum}",
                userId, request?.OrderNum);
            return ApiResponse<PrizeOrderLogResponseDto>.Fail("获取抽奖结果失败");
        }
    }

    /// <summary>
    /// 无限赏抽奖结果查询
    /// POST /api/infinite_prizeorderlog
    /// Requirements: 9.1-9.2
    /// </summary>
    [HttpPost("infinite_prizeorderlog")]
    [Authorize]
    public async Task<ApiResponse<InfinitePrizeOrderLogResponseDto>> GetInfinitePrizeOrderLog([FromBody] OrderPrizeOrderLogRequest? request)
    {
        var userId = GetCurrentUserId();
        if (userId == null)
        {
            return ApiResponse<InfinitePrizeOrderLogResponseDto>.Unauthorized();
        }

        try
        {
            if (request == null || string.IsNullOrWhiteSpace(request.OrderNum))
            {
                return ApiResponse<InfinitePrizeOrderLogResponseDto>.Fail("订单号不能为空");
            }

            var result = await _orderService.GetInfinitePrizeOrderLogAsync(userId.Value, request.OrderNum);
            return ApiResponse<InfinitePrizeOrderLogResponseDto>.Success(result);
        }
        catch (InvalidOperationException ex)
        {
            _logger.LogWarning("Get infinite prize order log failed: UserId={UserId}, OrderNum={OrderNum}, Error={Error}",
                userId, request?.OrderNum, ex.Message);
            return ApiResponse<InfinitePrizeOrderLogResponseDto>.Fail(ex.Message);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to get infinite prize order log: UserId={UserId}, OrderNum={OrderNum}",
                userId, request?.OrderNum);
            return ApiResponse<InfinitePrizeOrderLogResponseDto>.Fail("获取抽奖结果失败");
        }
    }

    /// <summary>
    /// 无限赏中奖记录查询
    /// GET /api/infinite_shang_log
    /// Requirements: 4.1-4.3
    /// </summary>
    [HttpGet("infinite_shang_log")]
    public async Task<ApiResponse<InfiniteShangLogResponseDto>> GetInfiniteShangLog([FromQuery] InfiniteShangLogRequest? request)
    {
        try
        {
            if (request == null || request.GoodsId <= 0)
            {
                return ApiResponse<InfiniteShangLogResponseDto>.Fail("商品ID不能为空");
            }

            // 设置默认分页参数
            var page = request.Page > 0 ? request.Page : 1;
            var pageSize = request.PageSize > 0 ? request.PageSize : 100;

            var result = await _lotteryService.GetInfiniteShangLogAsync(
                request.GoodsId, 
                request.ShangId ?? 0, 
                request.IsMibao ?? 0, 
                page, 
                pageSize);
            return ApiResponse<InfiniteShangLogResponseDto>.Success(result);
        }
        catch (InvalidOperationException ex)
        {
            _logger.LogWarning("Get infinite shang log failed: GoodsId={GoodsId}, Error={Error}",
                request?.GoodsId, ex.Message);
            return ApiResponse<InfiniteShangLogResponseDto>.Fail(ex.Message);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to get infinite shang log: GoodsId={GoodsId}",
                request?.GoodsId);
            return ApiResponse<InfiniteShangLogResponseDto>.Fail("获取中奖记录失败");
        }
    }

    /// <summary>
    /// 无限赏用户抽奖记录查询（盒子抽奖记录）
    /// POST /api/infinite_prizerecords
    /// Requirements: 5.1-5.3
    /// </summary>
    [HttpPost("infinite_prizerecords")]
    [Authorize]
    public async Task<ApiResponse<InfinitePrizeRecordsResponseDto>> GetInfinitePrizeRecords([FromBody] InfinitePrizeRecordsRequest? request)
    {
        var userId = GetCurrentUserId();
        if (userId == null)
        {
            return ApiResponse<InfinitePrizeRecordsResponseDto>.Unauthorized();
        }

        try
        {
            if (request == null || request.GoodsId <= 0)
            {
                return ApiResponse<InfinitePrizeRecordsResponseDto>.Fail("商品ID不能为空");
            }

            // 设置默认分页参数
            var page = request.Page > 0 ? request.Page : 1;
            var pageSize = request.PageSize > 0 ? request.PageSize : 100;

            var result = await _lotteryService.GetInfinitePrizeRecordsAsync(
                userId.Value,
                request.GoodsId, 
                page, 
                pageSize);
            return ApiResponse<InfinitePrizeRecordsResponseDto>.Success(result);
        }
        catch (InvalidOperationException ex)
        {
            _logger.LogWarning("Get infinite prize records failed: UserId={UserId}, GoodsId={GoodsId}, Error={Error}",
                userId, request?.GoodsId, ex.Message);
            return ApiResponse<InfinitePrizeRecordsResponseDto>.Fail(ex.Message);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to get infinite prize records: UserId={UserId}, GoodsId={GoodsId}",
                userId, request?.GoodsId);
            return ApiResponse<InfinitePrizeRecordsResponseDto>.Fail("获取抽奖记录失败");
        }
    }

    /// <summary>
    /// 道具卡抽奖（重抽）
    /// POST /api/item_card_chou
    /// Requirements: 6.1-6.4
    /// </summary>
    [HttpPost("item_card_chou")]
    [Authorize]
    public async Task<ApiResponse<ItemCardDrawResponseDto>> DrawWithItemCard([FromBody] ItemCardDrawRequest? request)
    {
        var userId = GetCurrentUserId();
        if (userId == null)
        {
            return ApiResponse<ItemCardDrawResponseDto>.Unauthorized();
        }

        try
        {
            if (request == null)
            {
                return ApiResponse<ItemCardDrawResponseDto>.Fail("请求参数不能为空");
            }

            if (request.GoodsId <= 0)
            {
                return ApiResponse<ItemCardDrawResponseDto>.Fail("商品ID不能为空");
            }

            if (string.IsNullOrWhiteSpace(request.OrderListIds))
            {
                return ApiResponse<ItemCardDrawResponseDto>.Fail("参数错误");
            }

            // 解析订单项ID列表
            var orderListIds = request.OrderListIds
                .Split(',', StringSplitOptions.RemoveEmptyEntries)
                .Select(s => int.TryParse(s.Trim(), out var id) ? id : 0)
                .Where(id => id > 0)
                .ToList();

            if (!orderListIds.Any())
            {
                return ApiResponse<ItemCardDrawResponseDto>.Fail("参数错误");
            }

            var result = await _lotteryService.DrawWithItemCardAsync(userId.Value, request.GoodsId, orderListIds);
            return ApiResponse<ItemCardDrawResponseDto>.Success(result, "重抽成功");
        }
        catch (InvalidOperationException ex)
        {
            _logger.LogWarning("Item card draw failed: UserId={UserId}, GoodsId={GoodsId}, Error={Error}",
                userId, request?.GoodsId, ex.Message);
            return ApiResponse<ItemCardDrawResponseDto>.Fail(ex.Message);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to draw with item card: UserId={UserId}, GoodsId={GoodsId}",
                userId, request?.GoodsId);
            return ApiResponse<ItemCardDrawResponseDto>.Fail("重抽失败,请刷新重试");
        }
    }

    #endregion

    #region 订单模块扩展 (9个接口)

    /// <summary>
    /// 获取订单支付状态
    /// GET /api/get_order_status
    /// Requirements: 6.1
    /// </summary>
    [HttpGet("get_order_status")]
    [Authorize]
    public async Task<ApiResponse<OrderStatusResponseDto>> GetOrderStatus([FromQuery] string order_num)
    {
        var userId = GetCurrentUserId();
        if (userId == null)
        {
            return ApiResponse<OrderStatusResponseDto>.Unauthorized();
        }

        try
        {
            if (string.IsNullOrWhiteSpace(order_num))
            {
                return ApiResponse<OrderStatusResponseDto>.Fail("订单编号不能为空");
            }

            var result = await _orderService.GetOrderStatusAsync(userId.Value, order_num);
            return ApiResponse<OrderStatusResponseDto>.Success(result, result.Message);
        }
        catch (InvalidOperationException ex)
        {
            _logger.LogWarning("Get order status failed: UserId={UserId}, OrderNum={OrderNum}, Error={Error}",
                userId, order_num, ex.Message);
            return ApiResponse<OrderStatusResponseDto>.Fail(ex.Message);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to get order status: UserId={UserId}, OrderNum={OrderNum}",
                userId, order_num);
            return ApiResponse<OrderStatusResponseDto>.Fail("获取订单状态失败");
        }
    }

    /// <summary>
    /// 获取订单列表（GET方式）
    /// GET /api/get_order_list
    /// Requirements: 6.2
    /// </summary>
    [HttpGet("get_order_list")]
    [Authorize]
    public async Task<ApiResponse<GetOrderListResponseDto>> GetOrderListByGet([FromQuery] int page = 1, [FromQuery] int page_size = 10)
    {
        var userId = GetCurrentUserId();
        if (userId == null)
        {
            return ApiResponse<GetOrderListResponseDto>.Unauthorized();
        }

        try
        {
            var result = await _orderService.GetOrderListByGetAsync(userId.Value, page, page_size);
            return ApiResponse<GetOrderListResponseDto>.Success(result, "获取成功");
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to get order list: UserId={UserId}", userId);
            return ApiResponse<GetOrderListResponseDto>.Fail("获取订单列表失败");
        }
    }

    /// <summary>
    /// 创建网页支付订单
    /// POST /api/create_web_pay_order
    /// Requirements: 6.3
    /// </summary>
    [HttpPost("create_web_pay_order")]
    [Authorize]
    public async Task<ApiResponse<WebPayOrderResponseDto>> CreateWebPayOrder([FromBody] CreateWebPayOrderRequest? request)
    {
        var userId = GetCurrentUserId();
        if (userId == null)
        {
            return ApiResponse<WebPayOrderResponseDto>.Unauthorized();
        }

        try
        {
            if (request == null || string.IsNullOrWhiteSpace(request.OrderNum))
            {
                return ApiResponse<WebPayOrderResponseDto>.Fail("订单编号不能为空");
            }

            var result = await _orderService.CreateWebPayOrderAsync(userId.Value, request.OrderNum);
            return ApiResponse<WebPayOrderResponseDto>.Success(result, "创建成功");
        }
        catch (InvalidOperationException ex)
        {
            _logger.LogWarning("Create web pay order failed: UserId={UserId}, OrderNum={OrderNum}, Error={Error}",
                userId, request?.OrderNum, ex.Message);
            return ApiResponse<WebPayOrderResponseDto>.Fail(ex.Message);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to create web pay order: UserId={UserId}, OrderNum={OrderNum}",
                userId, request?.OrderNum);
            return ApiResponse<WebPayOrderResponseDto>.Fail("创建支付订单失败");
        }
    }

    /// <summary>
    /// 获取订单URL链接
    /// GET /api/get_order_url_link
    /// Requirements: 6.4
    /// </summary>
    [HttpGet("get_order_url_link")]
    public async Task<ApiResponse<OrderUrlLinkResponseDto>> GetOrderUrlLink([FromQuery] string order_num)
    {
        try
        {
            if (string.IsNullOrWhiteSpace(order_num))
            {
                return ApiResponse<OrderUrlLinkResponseDto>.Fail("订单编号不能为空");
            }

            var result = await _orderService.GetOrderUrlLinkAsync(order_num);
            return ApiResponse<OrderUrlLinkResponseDto>.Success(result, "获取成功");
        }
        catch (InvalidOperationException ex)
        {
            _logger.LogWarning("Get order url link failed: OrderNum={OrderNum}, Error={Error}",
                order_num, ex.Message);
            return ApiResponse<OrderUrlLinkResponseDto>.Fail(ex.Message);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to get order url link: OrderNum={OrderNum}", order_num);
            return ApiResponse<OrderUrlLinkResponseDto>.Fail("获取失败");
        }
    }

    /// <summary>
    /// 商城下单
    /// POST /api/mall_orderbuy
    /// Requirements: 6.5
    /// </summary>
    [HttpPost("mall_orderbuy")]
    [Authorize]
    public async Task<ApiResponse<OrderBuyResponseDto>> CreateMallOrder([FromBody] MallOrderBuyRequest? request)
    {
        var userId = GetCurrentUserId();
        if (userId == null)
        {
            return ApiResponse<OrderBuyResponseDto>.Unauthorized();
        }

        try
        {
            if (request == null)
            {
                return ApiResponse<OrderBuyResponseDto>.Fail("请求参数不能为空");
            }

            if (request.GoodsId <= 0)
            {
                return ApiResponse<OrderBuyResponseDto>.Fail("商品ID不能为空");
            }

            if (request.PrizeNum <= 0)
            {
                return ApiResponse<OrderBuyResponseDto>.Fail("抽奖次数不能为空");
            }

            var result = await _orderService.CreateMallOrderAsync(userId.Value, request);
            return ApiResponse<OrderBuyResponseDto>.Success(result, "下单成功");
        }
        catch (InvalidOperationException ex)
        {
            _logger.LogWarning("Create mall order failed: UserId={UserId}, GoodsId={GoodsId}, Error={Error}",
                userId, request?.GoodsId, ex.Message);
            
            // 未绑定手机号返回特殊状态码 -9，前端根据此状态码跳转绑定页面
            if (ex.Message.Contains("绑定手机号"))
            {
                return ApiResponse<OrderBuyResponseDto>.Fail(ex.Message, -9);
            }
            
            return ApiResponse<OrderBuyResponseDto>.Fail(ex.Message);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to create mall order: UserId={UserId}, GoodsId={GoodsId}",
                userId, request?.GoodsId);
            return ApiResponse<OrderBuyResponseDto>.Fail("购买失败,请刷新重试");
        }
    }

    /// <summary>
    /// 获取抽奖结果（别名）
    /// POST /api/prize_order_log
    /// Requirements: 6.6
    /// </summary>
    [HttpPost("prize_order_log")]
    [Authorize]
    public async Task<ApiResponse<PrizeOrderLogResponseDto>> GetPrizeOrderLogAlias([FromBody] OrderPrizeOrderLogRequest? request)
    {
        // 复用已有的 prizeorderlog 接口逻辑
        return await GetPrizeOrderLog(request);
    }

    /// <summary>
    /// 获取道具卡列表
    /// GET /api/item_card_list
    /// Requirements: 6.7
    /// </summary>
    [HttpGet("item_card_list")]
    [Authorize]
    public async Task<ApiResponse<ItemCardListResponseDto>> GetItemCardList([FromQuery] int page = 1, [FromQuery] int page_size = 20)
    {
        var userId = GetCurrentUserId();
        if (userId == null)
        {
            return ApiResponse<ItemCardListResponseDto>.Unauthorized();
        }

        try
        {
            var result = await _orderService.GetItemCardListAsync(userId.Value, page, page_size);
            return ApiResponse<ItemCardListResponseDto>.Success(result, "请求成功");
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to get item card list: UserId={UserId}", userId);
            return ApiResponse<ItemCardListResponseDto>.Fail("获取道具卡列表失败");
        }
    }

    /// <summary>
    /// 连击赏秘宝下单
    /// POST /api/infinite_mibao_orderbuy
    /// Requirements: 6.8
    /// </summary>
    [HttpPost("infinite_mibao_orderbuy")]
    [Authorize]
    public async Task<ApiResponse<OrderBuyResponseDto>> CreateInfiniteMibaoOrder([FromBody] InfiniteMibaoOrderBuyRequest? request)
    {
        var userId = GetCurrentUserId();
        if (userId == null)
        {
            return ApiResponse<OrderBuyResponseDto>.Unauthorized();
        }

        try
        {
            if (request == null)
            {
                return ApiResponse<OrderBuyResponseDto>.Fail("请求参数不能为空");
            }

            if (request.GoodsId <= 0)
            {
                return ApiResponse<OrderBuyResponseDto>.Fail("商品ID不能为空");
            }

            if (request.PrizeNum <= 0)
            {
                return ApiResponse<OrderBuyResponseDto>.Fail("抽奖次数不能为空");
            }

            var result = await _orderService.CreateInfiniteMibaoOrderAsync(userId.Value, request);
            return ApiResponse<OrderBuyResponseDto>.Success(result, "下单成功");
        }
        catch (InvalidOperationException ex)
        {
            _logger.LogWarning("Create infinite mibao order failed: UserId={UserId}, GoodsId={GoodsId}, Error={Error}",
                userId, request?.GoodsId, ex.Message);
            
            // 未绑定手机号返回特殊状态码 -9，前端根据此状态码跳转绑定页面
            if (ex.Message.Contains("绑定手机号"))
            {
                return ApiResponse<OrderBuyResponseDto>.Fail(ex.Message, -9);
            }
            
            return ApiResponse<OrderBuyResponseDto>.Fail(ex.Message);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to create infinite mibao order: UserId={UserId}, GoodsId={GoodsId}",
                userId, request?.GoodsId);
            return ApiResponse<OrderBuyResponseDto>.Fail("购买失败,请刷新重试");
        }
    }

    /// <summary>
    /// 获取测试用户Token（仅测试环境）
    /// GET /api/get_user_test
    /// Requirements: 6.9
    /// </summary>
    [HttpGet("get_user_test")]
    [Authorize]
    public async Task<ApiResponse<string>> GetUserTest([FromQuery] int user_id)
    {
        var userId = GetCurrentUserId();
        if (userId == null)
        {
            return ApiResponse<string>.Unauthorized();
        }

        try
        {
            var result = await _orderService.GetUserTestTokenAsync(userId.Value, user_id);
            if (string.IsNullOrEmpty(result))
            {
                return ApiResponse<string>.Success(string.Empty, "获取失败");
            }
            return ApiResponse<string>.Success(result, "获取成功");
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to get user test token: UserId={UserId}, TargetUserId={TargetUserId}",
                userId, user_id);
            return ApiResponse<string>.Success(string.Empty, "获取失败");
        }
    }

    #endregion

    #region Private Helper Methods

    /// <summary>
    /// 获取当前登录用户ID
    /// </summary>
    private int? GetCurrentUserId()
    {
        var userIdClaim = User.FindFirst(ClaimTypes.NameIdentifier);
        if (userIdClaim == null || !int.TryParse(userIdClaim.Value, out var userId))
        {
            return null;
        }
        return userId;
    }

    #endregion
}
