using HoneyBox.Admin.Business.Attributes;
using HoneyBox.Admin.Business.Models;
using HoneyBox.Admin.Business.Models.Order;
using HoneyBox.Admin.Business.Services.Interfaces;
using Microsoft.AspNetCore.Mvc;

namespace HoneyBox.Admin.Business.Controllers;

/// <summary>
/// 订单管理控制器
/// </summary>
[Route("api/admin/business/orders")]
public class OrderController : BusinessControllerBase
{
    private readonly IOrderService _orderService;

    public OrderController(IOrderService orderService)
    {
        _orderService = orderService;
    }

    #region 订单查询

    /// <summary>
    /// 获取订单列表
    /// </summary>
    /// <param name="request">查询请求</param>
    /// <returns>分页订单列表</returns>
    [HttpGet]
    [BusinessPermission("order:list")]
    public async Task<IActionResult> GetOrderList([FromQuery] OrderListRequest request)
    {
        var result = await _orderService.GetOrderListAsync(request);
        return Ok(result);
    }

    /// <summary>
    /// 获取订单详情
    /// </summary>
    /// <param name="id">订单ID</param>
    /// <returns>订单详情</returns>
    [HttpGet("{id}")]
    [BusinessPermission("order:view")]
    public async Task<IActionResult> GetOrderDetail(int id)
    {
        var result = await _orderService.GetOrderDetailAsync(id);
        if (result == null)
        {
            return NotFoundError("订单不存在");
        }
        return Ok(result);
    }

    /// <summary>
    /// 获取卡单列表
    /// </summary>
    /// <param name="request">查询请求</param>
    /// <returns>分页卡单列表</returns>
    [HttpGet("stuck")]
    [BusinessPermission("order:list")]
    public async Task<IActionResult> GetStuckOrders([FromQuery] OrderListRequest request)
    {
        var result = await _orderService.GetStuckOrdersAsync(request);
        return Ok(result);
    }

    /// <summary>
    /// 获取兑换订单列表
    /// </summary>
    /// <param name="request">查询请求</param>
    /// <returns>分页兑换订单列表</returns>
    [HttpGet("recovery")]
    [BusinessPermission("order:list")]
    public async Task<IActionResult> GetRecoveryOrders([FromQuery] OrderListRequest request)
    {
        var result = await _orderService.GetRecoveryOrdersAsync(request);
        return Ok(result);
    }

    /// <summary>
    /// 获取综合订单列表（支持按账号类型和状态过滤）
    /// </summary>
    /// <param name="request">查询请求</param>
    /// <returns>分页订单列表</returns>
    [HttpGet("list")]
    [BusinessPermission("order:list")]
    public async Task<IActionResult> GetComprehensiveOrders([FromQuery] ComprehensiveOrderListRequest request)
    {
        var result = await _orderService.GetComprehensiveOrdersAsync(request);
        return Ok(result);
    }

    #endregion

    #region 发货管理

    /// <summary>
    /// 获取发货订单列表
    /// </summary>
    /// <param name="request">查询请求</param>
    /// <returns>分页发货订单列表</returns>
    [HttpGet("shipping")]
    [BusinessPermission("order:ship")]
    public async Task<IActionResult> GetShippingOrders([FromQuery] ShippingOrderListRequest request)
    {
        var result = await _orderService.GetShippingOrdersAsync(request);
        return Ok(result);
    }

    /// <summary>
    /// 获取发货订单详情
    /// </summary>
    /// <param name="id">发货记录ID</param>
    /// <returns>发货订单详情</returns>
    [HttpGet("shipping/{id}")]
    [BusinessPermission("order:ship")]
    public async Task<IActionResult> GetShippingOrderDetail(int id)
    {
        var result = await _orderService.GetShippingOrderDetailAsync(id);
        if (result == null)
        {
            return NotFoundError("发货订单不存在");
        }
        return Ok(result);
    }

    /// <summary>
    /// 发货处理
    /// </summary>
    /// <param name="id">发货记录ID</param>
    /// <param name="request">发货请求</param>
    /// <returns>操作结果</returns>
    [HttpPut("{id}/ship")]
    [BusinessPermission("order:ship")]
    public async Task<IActionResult> ShipOrder(int id, [FromBody] ShipOrderRequest request)
    {
        if (string.IsNullOrWhiteSpace(request.CourierName))
        {
            return ValidationError("快递公司名称不能为空");
        }

        if (string.IsNullOrWhiteSpace(request.CourierNumber))
        {
            return ValidationError("快递单号不能为空");
        }

        var operatorId = (int)(GetCurrentUserId() ?? 0);

        try
        {
            var result = await _orderService.ShipOrderAsync(id, request, operatorId);
            return result ? Ok("发货成功") : Error(BusinessErrorCodes.InternalError, "发货失败");
        }
        catch (BusinessException ex)
        {
            return Error(ex.Code, ex.Message);
        }
    }

    /// <summary>
    /// 取消发货订单
    /// </summary>
    /// <param name="id">发货记录ID</param>
    /// <returns>操作结果</returns>
    [HttpDelete("{id}/ship")]
    [BusinessPermission("order:ship")]
    public async Task<IActionResult> CancelShippingOrder(int id)
    {
        var operatorId = (int)(GetCurrentUserId() ?? 0);

        try
        {
            var result = await _orderService.CancelShippingOrderAsync(id, operatorId);
            return result ? Ok("取消发货成功") : Error(BusinessErrorCodes.InternalError, "取消发货失败");
        }
        catch (BusinessException ex)
        {
            return Error(ex.Code, ex.Message);
        }
    }

    #endregion

    #region 订单导出

    /// <summary>
    /// 导出订单
    /// </summary>
    /// <param name="request">导出请求</param>
    /// <returns>CSV文件</returns>
    [HttpGet("export")]
    [BusinessPermission("order:export")]
    public async Task<IActionResult> ExportOrders([FromQuery] OrderExportRequest request)
    {
        var bytes = await _orderService.ExportOrdersAsync(request);
        var fileName = $"orders_{DateTime.Now:yyyyMMddHHmmss}.csv";
        return File(bytes, "text/csv", fileName);
    }

    /// <summary>
    /// 导出发货订单
    /// </summary>
    /// <param name="request">导出请求</param>
    /// <returns>CSV文件</returns>
    [HttpGet("shipping/export")]
    [BusinessPermission("order:export")]
    public async Task<IActionResult> ExportShippingOrders([FromQuery] ShippingExportRequest request)
    {
        var bytes = await _orderService.ExportShippingOrdersAsync(request);
        var fileName = $"shipping_orders_{DateTime.Now:yyyyMMddHHmmss}.csv";
        return File(bytes, "text/csv", fileName);
    }

    /// <summary>
    /// 导出回收订单
    /// </summary>
    /// <param name="request">导出请求</param>
    /// <returns>CSV文件</returns>
    [HttpGet("recovery/export")]
    [BusinessPermission("order:export")]
    public async Task<IActionResult> ExportRecoveryOrders([FromQuery] RecoveryExportRequest request)
    {
        var bytes = await _orderService.ExportRecoveryOrdersAsync(request);
        var fileName = $"recovery_orders_{DateTime.Now:yyyyMMddHHmmss}.csv";
        return File(bytes, "text/csv", fileName);
    }

    /// <summary>
    /// 获取发货订单统计信息
    /// </summary>
    /// <param name="request">查询请求</param>
    /// <returns>统计信息</returns>
    [HttpGet("shipping/stats")]
    [BusinessPermission("order:ship")]
    public async Task<IActionResult> GetShippingStats([FromQuery] ShippingOrderListRequest request)
    {
        var result = await _orderService.GetShippingStatsAsync(request);
        return Ok(result);
    }

    /// <summary>
    /// 导出综合订单
    /// </summary>
    /// <param name="request">导出请求</param>
    /// <returns>CSV文件</returns>
    [HttpGet("list/export")]
    [BusinessPermission("order:export")]
    public async Task<IActionResult> ExportComprehensiveOrders([FromQuery] ComprehensiveOrderExportRequest request)
    {
        var bytes = await _orderService.ExportComprehensiveOrdersAsync(request);
        var fileName = $"comprehensive_orders_{DateTime.Now:yyyyMMddHHmmss}.csv";
        return File(bytes, "text/csv", fileName);
    }

    #endregion
}
