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;
using System.Linq;
using Hncore.Wx.Open;
using Hncore.Infrastructure.SMS;
using Hncore.Pass.BaseInfo.Models;
using System.Collections.Generic;
using Hncore.Pass.Vpn.Domain;
using Hncore.Infrastructure.WebApi;

namespace Hncore.Pass.Vpn.Job
{
    /// <summary>
    /// 删除不存在的账号
    /// </summary>
    public class RemoveAccountJob
    {
        public static void Start(IServiceProvider serviceProvider)
        {
            Task.Run(async () => { await Execute(serviceProvider); });
        }

        private static async Task Execute(IServiceProvider serviceProvider)
        {
            var doing = false;
            while (true)
            {
                while (true)
                {                 
                    if (doing||!(DateTime.Now.Hour == 23 && DateTime.Now.Minute < 5))
                    {
                        break;
                    }
                    LogHelper.Trace("开始删除过期账号");
                    doing = true;
                    try
                    {
                        using (var scope = serviceProvider.CreateScope())
                        {
                            var accountService = scope.ServiceProvider.GetService<ProductAccountService>();
                            var agentService = scope.ServiceProvider.GetService<AgentService>();
                            var removeAccounts = new List<ProductAccountEntity>();
                            var accounts = await accountService.Query(true).ToListAsync();
                            foreach (var item in accounts)
                            {
                                var ret = await agentService.GetOriginAccountInfo(item.ProductId.Value, item.Account, item.Pwd);
                                if (ret.Code != ResultCode.C_SUCCESS && ret.Code != ResultCode.C_NOT_EXISTS_ERROR)
                                {
                                    removeAccounts.Add(item);
                                }
                            }
                            await accountService.Deletes(removeAccounts);
                        }
                    }
                    catch (Exception e)
                    {
                        LogHelper.Error("账号删除失败", e);
                        break;
                    }
                    finally
                    {
                        doing = false;
                    }
                    await Task.Delay(6*60 * 1000);
                }
                await Task.Delay(60 * 1000);
            }               
        }
    }

}