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;

namespace Hncore.Pass.Vpn.Job
{
    /// <summary>
    /// 过期提醒job
    /// </summary>
    public class ExpireTipJob
    {
        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 == 8 && DateTime.Now.Minute < 5))
                    {
                        break;
                    }
                    doing = true;
                    try
                    {
                        using (var scope = serviceProvider.CreateScope())
                        {
                            var accountService = scope.ServiceProvider.GetService<ProductAccountService>();
                            var wxUserService = scope.ServiceProvider.GetService<WxAppUserService>();
                            var userService = scope.ServiceProvider.GetService<UserService>();

                            var expireAccounts1 = await accountService.GetExpireingAccountsTime(1);
                            var expireAccounts0 = await accountService.GetExpireingAccountsTime(0);
                            var expireAccounts_1 = await accountService.GetExpireingAccountsTime(-1);

                            await Tip(expireAccounts1, wxUserService, userService, "还有一天过期");
                            await Tip(expireAccounts0, wxUserService, userService, "今天过期");
                            await Tip(expireAccounts_1, wxUserService, userService, "已经过期一天");

                        }
                    }
                    catch (Exception e)
                    {
                        LogHelper.Error("处理过期提醒失败", e);
                        break;
                    }
                    finally
                    {
                        doing = false;
                    }
                    await Task.Delay(6*60 * 1000);
                }
                await Task.Delay(60 * 1000);
            }               
        }

        public static async Task Tip(List<ProductAccountEntity> accounts, WxAppUserService wxUserService, UserService userService,string tip="")
        {           
            var userIds = accounts.Select(m => m.UserId.Value).Distinct().ToList();
            var wxUsers = await wxUserService.GetWxUsers(userIds);
            var userInfos = await userService.GetByIds(userIds);

            var tipUsers = new Dictionary<int, bool>();
            foreach (var account in accounts)
            {
                if (tipUsers.ContainsKey(account.UserId.Value)||account.PackageName.IndexOf("测试")!=-1 || account.PackageName.IndexOf("天卡") != -1)
                {
                    continue;
                }
                var userInfo = userInfos.FirstOrDefault(m => m.Id == account.UserId);
                if (wxUsers != null && wxUsers.Count > 0)
                {
                    var remark = "请及时续费，以免影响您使用。";
                    if(tip=="已经过期一天"){
                        remark = "续费价更优，请登录官网juip.com，联系客服咨询更低价格，现有十几款IP产品，总有一款适合您。";
                    }
                    var title_remark = "请登录juip.com查看具体的到期账号！";
                    if(tip=="今天过期"){
                        title_remark = "您有IP账号将于今天到期，请点击查看详情";
                    } else if(tip=="还有一天过期"){
                        title_remark = "您有IP账号将于明天到期，请点击查看详情";
                    } else {
                        title_remark = "您有IP账号已到期1天，请点击查看详情";
                    }
                    var wxUser = wxUsers.FirstOrDefault(m => m.UserId == account.UserId);
                    if (wxUser != null && wxUser.Openid.Has())
                    {
                        var msg = new TemplateMPModel();
                        msg.first = new TemplateDataItem($"尊敬的用户您好，你的账户{tip}！");
                        msg.Url = "http://www.juip.com/user/myaccounts";
                        msg.template_id = "ltm4OfRDoxgdRG4EC8NMzX-NrkfHUz8aGz33TXSbP44";
                        msg.Items.Add(new TemplateDataItem(title_remark));
                        msg.Items.Add(new TemplateDataItem(userInfo.Phone));
                        msg.Items.Add(new TemplateDataItem("IP账号服务"));
                        msg.Items.Add(new TemplateDataItem(account.EndTime.Value.ToString("yyyy-MM-dd hh:mm:ss")));
                        msg.remark = new TemplateDataItem(remark);
                        await TemplateApi.SendTemplateMessageAsync(wxUser.Appid, wxUser.Openid, Wx.Open.Enums.ChannelType.MP, msg);
                    }
                }

                var ret = false;
                if (userInfo != null && RegexPattern.IsMobile(userInfo.Phone))
                {
                    if(tip=="今天过期"){
                        ret = AliSmsService.Send("SMS_199202299", new { date = account.EndTime.Value.ToString("yyyy-MM-dd hh:mm:ss") }, "聚IP商城", userInfo.Phone);
                    } else if(tip=="还有一天过期"){
                        ret = AliSmsService.Send("SMS_199222107", new { date = account.EndTime.Value.ToString("yyyy-MM-dd hh:mm:ss") }, "聚IP商城", userInfo.Phone);
                    } else {
                        ret = AliSmsService.Send("SMS_461965526", new { date = account.EndTime.Value.ToString("yyyy-MM-dd hh:mm:ss") }, "聚IP", userInfo.Phone);
                    }
                    // var ret = AliSmsService.Send("SMS_193505090", new { date = account.EndTime.Value.ToString("yyyy-MM-dd hh:mm:ss") }, "聚IP商城", userInfo.Phone);
                }
                tipUsers[account.UserId.Value] = true;
            }
        }


    }

}