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

using IRaCIS.Core.Domain.Share;
using Microsoft.AspNetCore.Mvc;
using System.Text.RegularExpressions;

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

        [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.CriterionTypeEnum != null, t => t.CriterionTypeEnum == inQuery.CriterionTypeEnum)
            .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)
            .ProjectTo<EmailNoticeConfigView>(_mapper.ConfigurationProvider);

            return await emailNoticeConfigQueryable.ToPagedListAsync(inQuery);
        }


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

                VerifyMsg = _localizer["EmailNoticeConfig_RepeatEmailScenario"]
            };

            // 匹配所有占位符的正则表达式，允许包含空格的占位符
            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("EmailNoticeConfig_ContainEmpty");
            }


            if (addOrEditEmailNoticeConfig.Id == null)
            {

                var 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, verifyExp1);

                return ResponseOutput.Ok(entity.Id.ToString());
            }
            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 });

                }


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

                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>());
        }
    }
}
