//--------------------------------------------------------------------
//     此代码由T4模板自动生成  byzhouhang 20210918
//	   生成时间 2022-02-15 13:11:20 
//     对此文件的更改可能会导致不正确的行为，并且如果重新生成代码，这些更改将会丢失。
//--------------------------------------------------------------------

using IRaCIS.Core.Application.Helper;
using MailKit;
using MailKit.Net.Imap;
using MailKit.Search;
using MailKit.Security;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using System.Text.RegularExpressions;

namespace IRaCIS.Core.Application.Contracts
{
    /// <summary>
    /// 系统邮件配置表
    /// </summary>	
    [ApiExplorerSettings(GroupName = "Common")]
    public class EmailNoticeConfigService(IRepository<EmailNoticeConfig> _emailNoticeConfigrepository,
        IRepository<EmailNoticeUserType> _emailNoticeUserTypeRepository,
            IOptionsMonitor<SystemEmailSendConfig> systemEmailConfig,
        IMapper _mapper, IUserInfo _userInfo, IStringLocalizer _localizer) : BaseService, IEmailNoticeConfigService
    {
        private readonly SystemEmailSendConfig _systemEmailConfig = systemEmailConfig.CurrentValue;

        /// <summary>
        /// 获取邮件列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<object> GetEmailList()
        {

            List<IMessageSummary> emailList = new List<IMessageSummary>();






            using (var client = new ImapClient())
            {
               

                try
                {
                    // 连接阿里邮箱 IMAP 服务器（使用 SSL）
                    client.Connect(_systemEmailConfig.Imap, 993, SecureSocketOptions.SslOnConnect);

                    // 登录
                    client.Authenticate(_systemEmailConfig.FromEmail, _systemEmailConfig.AuthorizationCode);

                    // 3. 获取发件箱文件夹 - 使用你找到的“已发送”
                    var sentFolder = client.GetFolder("已发送");
                    sentFolder.Open(FolderAccess.ReadOnly);

                    // 4. 搜索所有邮件（你可以在这里添加更精确的搜索条件）
                    var uids = sentFolder.Search(SearchQuery.All);
                    Console.WriteLine($"找到 {uids.Count} 封已发送邮件");

                    // 5. 遍历并处理邮件（示例中处理前10封）
                    foreach (var uid in uids.Take(10))
                    {
                        var message = sentFolder.GetMessage(uid);
                     
                        // 输出邮件基本信息
                        Console.WriteLine($"主题: {message.Subject}");
                        Console.WriteLine($"收件人: {string.Join(", ", message.To.Mailboxes.Select(m => m.Address))}");
                        Console.WriteLine($"日期: {message.Date.LocalDateTime:yyyy-MM-dd HH:mm:ss}");
                        Console.WriteLine($"发件人: {message.From}");
                        Console.WriteLine("----------------------------------");
                    }

                    sentFolder.Close();
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"操作失败: {ex.Message}");
                }
                finally
                {
                    client.Disconnect(true);
                }
            }
            return true;

         
        }

        [HttpPost]
        public async Task<PageOutput<EmailNoticeConfigView>> GetEmailNoticeConfigList(EmailNoticeConfigQuery inQuery)
        {
            var emailNoticeConfigQueryable = _emailNoticeConfigrepository
            .WhereIf(inQuery.SystemLevel == null, t => t.SystemLevel == SysEmailLevel.not_sys)
            .WhereIf(inQuery.SystemLevel != null, t => t.SystemLevel == inQuery.SystemLevel)
            .WhereIf(inQuery.IsDistinguishCriteria != null, t => t.IsDistinguishCriteria == inQuery.IsDistinguishCriteria)
             .WhereIf(inQuery.BusinessLevelEnum != null, t => t.BusinessLevelEnum == inQuery.BusinessLevelEnum)
            .WhereIf(inQuery.CriterionTypeEnum != null, t => t.CriterionTypeList.Any(t=>t==inQuery.CriterionTypeEnum))
             .WhereIf(inQuery.BusinessModuleEnum != null, t => t.BusinessModuleEnum == inQuery.BusinessModuleEnum)
            .WhereIf(inQuery.BusinessScenarioEnum != null, t => t.BusinessScenarioEnum == inQuery.BusinessScenarioEnum)
            .WhereIf(inQuery.IsReturnRequired != null, t => t.IsReturnRequired == inQuery.IsReturnRequired)
            .WhereIf(inQuery.IsEnable != null, t => t.IsEnable == inQuery.IsEnable)
             .WhereIf(inQuery.EmailUrgentEnum != null, t => t.EmailUrgentEnum == inQuery.EmailUrgentEnum)
            .WhereIf(inQuery.ToUserType != null, t => t.EmailNoticeUserTypeList.Any(t => t.UserType == inQuery.ToUserType && t.EmailUserType == EmailUserType.To))
            .WhereIf(inQuery.CopyUserType != null, t => t.EmailNoticeUserTypeList.Any(t => t.UserType == inQuery.CopyUserType && t.EmailUserType == EmailUserType.Copy))
            .ProjectTo<EmailNoticeConfigView>(_mapper.ConfigurationProvider);

            return await emailNoticeConfigQueryable.ToPagedListAsync(inQuery);
        }

        /// <summary>
        /// 批量更新邮件主题中英文
        /// </summary>
        /// <param name="inCommandList"></param>
        /// <returns></returns>
        public async Task<IResponseOutput> BatchUpdateEmail(List<BatchUpdateEmailTopicCommand> inCommandList)
        {
            var findIdList = inCommandList.Select(x => x.Id).ToList();

            var regex = new Regex(@"\{\s*\d+\s*\}");

            foreach (var inCommand in inCommandList)
            {
                if (regex.Matches($"{inCommand.EmailTopic}{inCommand.EmailTopicCN}")
                              .Any(t => t.Value.Contains(" ")))
                {
                    //邮件模板占位符不允许有空格,请核查占位符的地方
                    return ResponseOutput.NotOk(I18n.T("EmailNoticeConfig_ContainEmpty"));
                }
            }

            var list = _emailNoticeConfigrepository.Where(t => findIdList.Contains(t.Id), true).ToList();

            foreach (var item in list)
            {
                var exist = inCommandList.FirstOrDefault(t => t.Id == item.Id);
                if (exist != null)
                {
                    item.EmailTopic = exist.EmailTopic;
                    item.EmailTopicCN = exist.EmailTopicCN;
                }
            }

            await _emailNoticeConfigrepository.SaveChangesAsync();


            return ResponseOutput.Ok();
        }

        public async Task<IResponseOutput> AddOrUpdateEmailNoticeConfig(EmailNoticeConfigAddOrEdit addOrEditEmailNoticeConfig)
        {
            //var verifyExp1 = new EntityVerifyExp<EmailNoticeConfig>()
            //{
            //    VerifyExp = t => t.BusinessScenarioEnum == addOrEditEmailNoticeConfig.BusinessScenarioEnum && t.CriterionTypeEnum == addOrEditEmailNoticeConfig.CriterionTypeEnum,

            //    VerifyMsg = _localizer["EmailNoticeConfig_RepeatEmailScenario"]

            //};

            var criterionList = _emailNoticeConfigrepository.Where(t => t.BusinessScenarioEnum == addOrEditEmailNoticeConfig.BusinessScenarioEnum && t.IsEnable == true)
                .Where(t => t.CriterionTypeList != null)
                .WhereIf(addOrEditEmailNoticeConfig.Id != null, t => t.Id != addOrEditEmailNoticeConfig.Id)
                .Select(t => t.CriterionTypeList).ToList();//不能使用selectMany  会当成关联对象，不能当成字符串


            if (addOrEditEmailNoticeConfig.CriterionTypeList != null)
            {
                foreach (var item in addOrEditEmailNoticeConfig.CriterionTypeList)
                {
                    foreach (var itemList in criterionList)
                    {
                        if (itemList.Any(t => t == item))
                        {
                            return ResponseOutput.NotOk(_localizer["EmailNoticeConfig_RepeatEmailScenario"]);
                        }
                    }

                }
            }



            var verifyExp2 = new EntityVerifyExp<EmailNoticeConfig>()
            {
                VerifyExp = t => t.Code == addOrEditEmailNoticeConfig.Code && t.IsDistinguishCriteria == addOrEditEmailNoticeConfig.IsDistinguishCriteria && t.SystemLevel == addOrEditEmailNoticeConfig.SystemLevel,

                VerifyMsg = _localizer["EmailNoticeConfig_RepeatCode"]

            };

            // 匹配所有占位符的正则表达式，允许包含空格的占位符
            var regex = new Regex(@"\{\s*\d+\s*\}");

            if (regex.Matches($"{addOrEditEmailNoticeConfig.EmailTopic}{addOrEditEmailNoticeConfig.EmailTopicCN}{addOrEditEmailNoticeConfig.EmailHtmlContent}{addOrEditEmailNoticeConfig.EmailHtmlContentCN}")
                .Any(t => t.Value.Contains(" ")))
            {
                //邮件模板占位符不允许有空格,请核查占位符的地方
                return ResponseOutput.NotOk(I18n.T("EmailNoticeConfig_ContainEmpty"));
            }




            var entity = new EmailNoticeConfig() { };

            if (addOrEditEmailNoticeConfig.Id == null)
            {

                entity = _mapper.Map<EmailNoticeConfig>(addOrEditEmailNoticeConfig);


                foreach (var item in addOrEditEmailNoticeConfig.ToUserTypeList)
                {
                    entity.EmailNoticeUserTypeList.Add(new EmailNoticeUserType() { EmailUserType = EmailUserType.To, UserType = item });

                }

                foreach (var item in addOrEditEmailNoticeConfig.CopyUserTypeList)
                {
                    entity.EmailNoticeUserTypeList.Add(new EmailNoticeUserType() { EmailUserType = EmailUserType.Copy, UserType = item });

                }


                await _emailNoticeConfigrepository.AddAsync(entity, true, verifyExp2);


            }
            else
            {
                var emailNoticeConfigId = addOrEditEmailNoticeConfig.Id;
                await _emailNoticeUserTypeRepository.BatchDeleteNoTrackingAsync(t => t.EmailNoticeConfigId == emailNoticeConfigId);


                foreach (var item in addOrEditEmailNoticeConfig.ToUserTypeList)
                {
                    await _emailNoticeUserTypeRepository.AddAsync(new EmailNoticeUserType() { EmailUserType = EmailUserType.To, UserType = item, EmailNoticeConfigId = (Guid)emailNoticeConfigId });

                }

                foreach (var item in addOrEditEmailNoticeConfig.CopyUserTypeList)
                {
                    await _emailNoticeUserTypeRepository.AddAsync(new EmailNoticeUserType() { EmailUserType = EmailUserType.Copy, UserType = item, EmailNoticeConfigId = (Guid)emailNoticeConfigId });

                }


                entity = await _emailNoticeConfigrepository.UpdateFromDTOAsync(addOrEditEmailNoticeConfig, true, false, verifyExp2);




            }


            if (addOrEditEmailNoticeConfig.EmailCron != string.Empty)
            {
                var jobId = $"{entity.Id}_({addOrEditEmailNoticeConfig.BusinessScenarioEnum})";

                HangfireJobHelper.RemoveCronJob(jobId);

                //有的job 可能编辑控制直接不发，需要移除已存在的
                if (entity.IsAutoSend && entity.IsEnable)
                {
                    HangfireJobHelper.AddOrUpdateTimingCronJob(jobId, addOrEditEmailNoticeConfig.BusinessScenarioEnum, addOrEditEmailNoticeConfig.EmailCron);
                }

            }


            return ResponseOutput.Ok(entity.Id.ToString());


        }


        [HttpDelete("{emailNoticeConfigId:guid}")]
        public async Task<IResponseOutput> DeleteEmailNoticeConfig(Guid emailNoticeConfigId)
        {
            var success = await _emailNoticeConfigrepository.BatchDeleteNoTrackingAsync(t => t.Id == emailNoticeConfigId);

            return ResponseOutput.Result(success);
        }



        public async Task<Dictionary<object, string>> GetEmailScenarioEnumSelect()
        {
            return await Task.FromResult(EnumToSelectExtension.ToSelect<EmailScenarioEnum>());
        }
    }
}
