using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;
using Dapper;
using DigitalSchoolApi.App_Data;
using DigitalSchoolApi.Models;
using Learun.Application.Organization;
using Learun.Util;
using Newtonsoft.Json;
using Convert = System.Convert;

namespace DigitalSchoolApi.Controllers
{
    /// <summary>
    /// 授权到期提醒
    /// </summary>
    public class EmailSendController
    {
        private readonly static string _admsConnection = ConfigurationManager.ConnectionStrings["CoreDBString"].ConnectionString;
        private readonly static string _misConnection = ConfigurationManager.ConnectionStrings["ConnectionPfcMisDBString"].ConnectionString;

        public static void Send()
        {
            try
            {
                //获取授权到期时间
                var lc = LicenseChecker.CheckLicense();
                //授权到期前发送邮件提醒
                if (!string.IsNullOrEmpty(lc.ExpirationDate) && !lc.ExpirationDate.Contains("永久有效"))
                {
                    using (IDbConnection admscon = new SqlConnection(_admsConnection))
                    {
                        admscon.Execute(
                            "insert into LR_Base_Log(F_LogId,F_CategoryId,F_SourceObjectId,F_SourceContentJson,F_OperateTime) values(newid(),997,'授权到期提醒','开始推送',getdate())");
                        //获取授权查看规则
                        var showAuthorize = admscon.QueryFirstOrDefault<ShowAuthorizeEntity>("select top 1 * from ShowAuthorize ");
                        if (showAuthorize != null && showAuthorize.IsRemind == 1 && !string.IsNullOrEmpty(showAuthorize.EmailAddr))
                        {
                            //授权到期时间
                            DateTime expirationDate = Convert.ToDateTime(lc.ExpirationDate);
                            DateTime now = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd"));
                            //计算授权到期时间与当前时间相差的天数
                            var ts = (expirationDate - now).Days;
                            //到期前{ExpirationTime}天，每天发送一封邮件
                            if (ts >= 0 && ts <= showAuthorize.ExpirationTime)
                            {
                                admscon.Execute(
                                    "insert into LR_Base_Log(F_LogId,F_CategoryId,F_SourceObjectId,F_SourceContentJson,F_OperateTime) values(newid(),997,'授权到期提醒','即将到期，发送提醒',getdate())");

                                //发送邮件
                                if (MailHelper.Send(showAuthorize.EmailAddr, showAuthorize.EmailTitle,
                                    showAuthorize.EmailContent))
                                {
                                    //发送邮件成功，记录数据
                                    var F_Sender = ConfigurationManager.AppSettings["MailUserName"];
                                    string addSendSql = $@"INSERT INTO [dbo].[LR_EmailSend]
           ([F_Id]
           ,[F_Sender]
           ,[F_SenderName]
           ,[F_To]
           ,[F_Subject]
           ,[F_BodyText]
           ,[F_Description]
           ,[F_EnabledMark]
           ,[F_DeleteMark]
,F_CreatorTime
           ,[F_Date])
     VALUES
           (NEWID()
           ,'{F_Sender}'
           ,null
           ,'{showAuthorize.EmailAddr}'
           ,'{showAuthorize.EmailTitle}'
           ,'{showAuthorize.EmailContent}'
           ,'授权到期提醒'
           ,0
           ,0
,getdate()
           ,getdate()) ";
                                    admscon.Execute(addSendSql);

                                }
                                admscon.Execute(
                                    "insert into LR_Base_Log(F_LogId,F_CategoryId,F_SourceObjectId,F_SourceContentJson,F_OperateTime) values(newid(),997,'授权到期提醒','发送成功',getdate())");

                            }
                            else
                            {
                                admscon.Execute(
                                    "insert into LR_Base_Log(F_LogId,F_CategoryId,F_SourceObjectId,F_SourceContentJson,F_OperateTime) values(newid(),997,'授权到期提醒','暂未到期',getdate())");
                            }
                        }

                    }
                }
            }
            catch (Exception ex)
            {
                using (IDbConnection conn = new SqlConnection(_admsConnection))
                {
                    conn.Execute(
                        $"insert into LR_Base_Log(F_LogId,F_CategoryId,F_SourceObjectId,F_SourceContentJson,F_OperateTime) values(newid(),997,'授权到期提醒异常','{ex.Message}',getdate())");
                }

            }
        }

    }
}
