using CrazyStudio.Core.Common.Eitities.Page;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;
using XPrint.Image.Tools;
using XPrintServer.Api.Dto;
using XPrintServer.Api.Hubs;
using XPrintServer.Business.Enums;
using XPrintServer.Business.Services;
using XPrintServer.DataModel.Models;

namespace XPrintServer.Api.Controllers.Common
{

    [Route("api/[controller]/[action]")]
    [ApiController]
    public class OrderController : ControllerBase
    {

        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly OrderService _orderService;
        private readonly OrderInfoService _orderInfoService;
        private readonly ActionLogService _actionLogService;
        private readonly IHubContext<MsgHub> _hubContext;

        public OrderController(IHttpContextAccessor httpContextAccessor, OrderService orderService, OrderInfoService orderInfoService, ActionLogService actionLogService, IHubContext<MsgHub> hubContext)
        {
            _httpContextAccessor = httpContextAccessor;
            _orderService = orderService;
            _orderInfoService = orderInfoService;
            _actionLogService = actionLogService;
            _hubContext = hubContext;
        }

        /// <summary>
        /// 游客下单
        /// </summary>
        /// <param name="orderName">订单信息</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ActionResult<string>> GuestPlaceOrder([FromBody] SubmitOrder submitOrder)
        {
            try
            {
                //开始事务
                await _orderService.Context.Ado.BeginTranAsync();

                var now = DateTime.Now;
                Order order = new Order
                {
                    CreateTime = now,
                    OrderName = submitOrder.OrderName!,
                    OrderStatus = (int)OrderStatus.Paid,//未支付
                    PayType = 5,//展会订单，不需要支付
                    OrderTime = now,
                    OrderUserId = null//游客用户Id为Null
                };
                //提交订单信
                order = await _orderService.AddOrder(order);

                List<OrderInfo> orderInfos = new List<OrderInfo>();
                for (int i = 0; i < submitOrder.ImageInfos.Count; i++)
                {
                    var imageInfo = submitOrder.ImageInfos[i];
                    orderInfos.Add(new OrderInfo
                    {
                        OrderId = order.Id,
                        ResourceStatus = (int)ResourceStatus.WaitProduction,
                        PacketObjectName = imageInfo.PacketObjectName,
                        PacketUrl = imageInfo.PacketUrl,
                        ProductType = imageInfo.ProductType,
                        SceneImageObjectName = imageInfo.SceneImageObjectName,
                        SceneImageUrl = imageInfo.SceneImageUrl,
                        SubmitTime = now,
                    });
                }
                //提交订单关联资源信息
                await _orderInfoService.AddOrderInfos(orderInfos);

                //提交事务
                await _orderService.Context.Ado.CommitTranAsync();
                //返回订单Id
                return Ok(order.Id);
            }
            catch (Exception ex)
            {
                //异常事务回滚
                await _orderService.Context.Ado.RollbackTranAsync();
                //记录异常日志
                await _actionLogService.AddActionLog(new ActionLog { Title = "GuestPlaceOrder Error", Content = ex.Message + " " + ex.StackTrace, DateTime = DateTime.Now });
                //返回错误信息
                return StatusCode(500, ex.Message);
            }
        }


        //[HttpPost]
        //public async Task<ActionResult<List<Order>>> OrderList([FromBody] PageOrderStatusData pageData)
        //{
        //    try
        //    {
        //    }
        //    catch (Exception ex)
        //    {
        //        await _actionLogService.AddActionLog(new ActionLog { Title = "OrderList Error", Content = ex.Message + " " + ex.StackTrace, DateTime = DateTime.Now });
        //        return StatusCode(500, ex.Message);
        //    }
        //}


        /// <summary>
        /// 更改订单状态为已生产
        /// </summary>
        /// <param name="pageData"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ActionResult<bool>> ProductionFinish([FromBody] Guid orderId)
        {
            try
            {
                //查询12个月的已支付订单
                var isOK = await _orderService.ChangeOrderStatusToProductionFinish(orderId);
                return Ok(isOK);
            }
            catch (Exception ex)
            {
                await _actionLogService.AddActionLog(new ActionLog { Title = "ChangeOrderStatusToProducture Error", Content = ex.Message + " " + ex.StackTrace, DateTime = DateTime.Now });
                return StatusCode(500, ex.Message);
            }
        }


        /// <summary>
        /// 批量更改订单状态为已生产
        /// </summary>
        /// <param name="pageData"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ActionResult<bool>> ProductionBatchFinish([FromBody] HashSet<Guid> orderIds)
        {
            try
            {
                //查询12个月的已支付订单
                var isOK = await _orderService.BatchChangeOrderStatusToProductionStatus(orderIds, OrderStatus.ProductionFinish);
                return Ok(isOK);
            }
            catch (Exception ex)
            {
                //异常事务回滚
                await _actionLogService.AddActionLog(new ActionLog { Title = "ProductionBatchFinish Error", Content = ex.Message + " " + ex.StackTrace, DateTime = DateTime.Now });
                return StatusCode(500, ex.Message);
            }
        }
    }
}
