using SqlSugar;
using XPrintServer.Business.Enums;
using XPrintServer.Business.Services.Interface;
using XPrintServer.DataModel;
using XPrintServer.DataModel.Models;

namespace XPrintServer.Business.Services
{
    public class OrderService : SqlSugarRepository<Order>, IBusinessService
    {
        public OrderService(ConnectionConfig config) : base(config)
        {
        }

        public async Task<Order> AddOrder(Order order)
        {
            order.CreateTime = DateTime.Now;
            await Context.Insertable(order).SplitTable().ExecuteCommandAsync().ConfigureAwait(false);
            return order;
        }

        /// <summary>
        /// 更改支付订单状态为已生产完成
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        public async Task<bool> ChangeOrderStatusToProductionFinish(Guid orderId)
        {
            var order = await Context.Queryable<Order>().Where(o => o.Id == orderId).SplitTable().FirstAsync().ConfigureAwait(false);
            if (order.OrderStatus == (int)OrderStatus.Paid)
            {
                order.OrderStatus = (int)OrderStatus.ProductionFinish;
                await Context.Updateable(order).SplitTable().ExecuteCommandAsync().ConfigureAwait(false);
                return true;
            }
            return false;
        }

        /// <summary>
        /// 批量更改支付订单状态为已生产完成
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        public async Task<bool> BatchChangeOrderStatusToProductionStatus(HashSet<Guid> orderIds, OrderStatus orderStatus)
        {
            var orders = await Context.Queryable<Order>().Where(o => orderIds.Contains(o.Id)).SplitTable().ToListAsync().ConfigureAwait(false);
            bool isOK = false;
            if (orders.Any())
            {
                for (int i = 0; i < orders.Count; i++)
                {
                    var order = orders[i];
                    if (order.OrderStatus == (int)OrderStatus.Paid || order.OrderStatus == (int)OrderStatus.Unpaid)//order.OrderStatus == (int)OrderStatus.Unpaid Debug
                    {
                        order.OrderStatus = (int)orderStatus;
                        isOK = true;
                    }
                }
                await Context.Updateable(orders).SplitTable().ExecuteCommandAsync().ConfigureAwait(false);
            }
            else
            {
                isOK = true;
            }
            return isOK;
        }
    }
}
