using Hncore.Infrastructure.Common;
using Hncore.Pass.BaseInfo.Models;
using Hncore.Pass.BaseInfo.Request.User;
using Hncore.Pass.Vpn.Domain;
using Hncore.Pass.Vpn.Request.Product;
using Hncore.Pass.Vpn.Service;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Threading.Tasks;

namespace Hncore.Pass.Vpn.Job
{
    /// <summary>
    /// 超时支付的job
    /// </summary>
    public class OrderOutTimePayJob
    {

        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 userService = scope.ServiceProvider.GetService<Hncore.Pass.BaseInfo.Service.UserService>();
                        var orders = await orderService.GetLimitTimeOrders(Domain.OrderStatus.NoPay, 30);
                        orders.ForEach(async order =>
                        {                           
                            order.OrderState = Domain.OrderStatus.TimeOutClose;
                            await orderService.Update(order);
                            //返还用户余额支付部分
                            if (order.AccountPayAmount > 0)
                            {
                                var amountInfo = new UpdateAmountRequest()
                                {
                                    Amount = order.AccountPayAmount.Value,
                                    OpAmountType = ScoreType.AccountRefund,
                                    UserId = order.UserId,
                                    AttchInfo = order.OrderNo,
                                    OperateUserName = order.UserName,
                                };
                                await userService.UpdateAmount(amountInfo);

                            }                          
                        });
                    }
                }
                catch (Exception e)
                {
                    LogHelper.Error("处理超时支付失败", e);
                    break;
                }
                await Task.Delay(60 * 1000);
            }
        }
    }
}