using Hncore.Infrastructure.Common;
using Hncore.Pass.Vpn.Service;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Threading.Tasks;
using Hncore.Infrastructure.Extension;
namespace Hncore.Pass.Vpn.Job
{
    /// <summary>
    /// 支付成功后开通账号的job
    /// </summary>
    public class OrderAccountJob
    {

        public static void Start(IServiceProvider serviceProvider)
        {
            Task.Run(async () => { await Execute(serviceProvider); });
        }

        private static async Task Execute(IServiceProvider serviceProvider)
        {           
            while (true) // 每轮间隔10分钟
            {
                LogHelper.Trace("开始处理订单");
                try
                {
                    using (var scope = serviceProvider.CreateScope())
                    {
                        var orderService = scope.ServiceProvider.GetService<ProductOrderService>();
                        var orders = await orderService.GetOrders(Domain.OrderStatus.PayOk);

                        await orders.ForEachAsync(async m =>
                        {
                            await orderService.ProcessOrderAccount(m);
                        });
                    }
                }
                catch (Exception e)
                {
                    LogHelper.Error("处理订单失败", e);                   
                }
                await Task.Delay(10 * 1000);
            }
        }
    }
}