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

using IRaCIS.Core.Application.Interfaces;
using IRaCIS.Core.Application.ViewModel;
using Microsoft.AspNetCore.Mvc;
namespace IRaCIS.Core.Application.Service
{
    /// <summary>
    /// SystemNoticeService
    /// </summary>	
    [ApiExplorerSettings(GroupName = "Management")]
    public class SystemNoticeService(IRepository<SystemNotice> _systemNoticeRepository, IMapper _mapper, IUserInfo _userInfo, IStringLocalizer _localizer) : BaseService, ISystemNoticeService
    {



        [HttpPost]
        public async Task<PageOutput<SystemNoticeView>> GetSystemNoticeList(SystemNoticeQuery inQuery)
        {
            //防止生成sql生成GETDATE() 时区导致的问题
            var appDateTimeNow = DateTime.Now;

            var systemNoticeQueryable = _systemNoticeRepository
                .WhereIf(inQuery.ApplicableProjectEnum != null, t => t.ApplicableProjectEnum == inQuery.ApplicableProjectEnum)
                .WhereIf(inQuery.NoticeLevelEnum != null, t => t.NoticeLevelEnum == inQuery.NoticeLevelEnum)
                .WhereIf(inQuery.NoticeModeEnum != null, t => t.NoticeModeEnum == inQuery.NoticeModeEnum)
                .WhereIf(inQuery.NoticeStateEnum != null && inQuery.NoticeStateEnum != Domain.Share.SystemNotice_NoticeStateEnum.HaveExpired, t => t.NoticeStateEnum == inQuery.NoticeStateEnum)
               .WhereIf(inQuery.NoticeModeEnum != null && inQuery.NoticeStateEnum == Domain.Share.SystemNotice_NoticeStateEnum.HaveExpired, t => t.NoticeStateEnum == Domain.Share.SystemNotice_NoticeStateEnum.HavePublished && t.EndDate != null && t.EndDate < appDateTimeNow)
               .WhereIf(inQuery.NoticeTypeEnum != null, t => t.NoticeTypeEnum == inQuery.NoticeTypeEnum)
                .WhereIf(!string.IsNullOrWhiteSpace(inQuery.FileName), t => t.FileName.Contains(inQuery.FileName))
                .WhereIf(!string.IsNullOrWhiteSpace(inQuery.NoticeContent), t => t.NoticeContent.Contains(inQuery.NoticeContent))
            .ProjectTo<SystemNoticeView>(_mapper.ConfigurationProvider, new { token = _userInfo.UserToken });

            return await systemNoticeQueryable.ToPagedListAsync(inQuery);
        }


        public async Task<IResponseOutput> AddOrUpdateSystemNotice(SystemNoticeAddOrEdit addOrEditSystemNotice)
        {

            if (addOrEditSystemNotice.Id == null)
            {
                var entity = await _systemNoticeRepository.InsertFromDTOAsync(addOrEditSystemNotice);

                if (entity.NoticeStateEnum == Domain.Share.SystemNotice_NoticeStateEnum.HavePublished)
                {
                    entity.PublishedUserId = _userInfo.Id;
                    entity.PublishedTime = DateTime.Now;
                }
                await _systemNoticeRepository.SaveChangesAsync();
                return ResponseOutput.Ok(entity.Id.ToString());

            }
            else
            {
                var systemNotice = (await _systemNoticeRepository.Where(t => t.Id == addOrEditSystemNotice.Id, true, true).Include(t => t.NoticeUserTypeList).FirstOrDefaultAsync()).IfNullThrowException();

                if (addOrEditSystemNotice.NoticeStateEnum == Domain.Share.SystemNotice_NoticeStateEnum.HavePublished && systemNotice.NoticeStateEnum == Domain.Share.SystemNotice_NoticeStateEnum.NotPublish)
                {
                    systemNotice.PublishedUserId = _userInfo.Id;
                    systemNotice.PublishedTime = DateTime.Now;
                }
                else if (addOrEditSystemNotice.NoticeStateEnum == Domain.Share.SystemNotice_NoticeStateEnum.NotPublish && systemNotice.NoticeStateEnum == Domain.Share.SystemNotice_NoticeStateEnum.HavePublished)
                {
                    systemNotice.PublishedUserId = null;
                    systemNotice.PublishedTime = null;
                }



                _mapper.Map(addOrEditSystemNotice, systemNotice);


                await _systemNoticeRepository.SaveChangesAsync();

                return ResponseOutput.Ok();

            }


        }


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

            return ResponseOutput.Result(success);
        }


        /// <summary>设置已读 </summary>
        [HttpPut("{systemNoticeId:guid}")]
        public async Task<IResponseOutput> SetSystemNoticeHaveRead(Guid systemNoticeId)
        {
            var systemNotice = (await _systemNoticeRepository.FirstOrDefaultAsync(t => t.Id == systemNoticeId)).IfNullThrowException();

            systemNotice.NoticeUserReadList.Add(new SystemNoticeUserRead() { SystemNoticeId = systemNoticeId });

            var success = await _systemNoticeRepository.SaveChangesAsync();


            return ResponseOutput.Result(success);
        }

        /// <summary>获取登陆用户的系统通知列表  只是过滤了用户类型 和已经发布的</summary>
        [HttpPost]
        public async Task<PageOutput<SystemNoticeReadDTO>> GetUserSystemNoticeList(SystemNoticeQuery inQuery)
        {
            //防止生成sql生成GETDATE() 时区导致的问题
            var appDateTimeNow = DateTime.Now;

            var systemNoticeQueryable = _systemNoticeRepository
                .Where(t => t.NoticeUserTypeList.Any(t => t.UserTypeId == _userInfo.UserTypeId) && t.NoticeStateEnum == Domain.Share.SystemNotice_NoticeStateEnum.HavePublished)
                .WhereIf(inQuery.ApplicableProjectEnum != null, t => t.ApplicableProjectEnum == inQuery.ApplicableProjectEnum)
                .WhereIf(inQuery.NoticeLevelEnum != null, t => t.NoticeLevelEnum == inQuery.NoticeLevelEnum)
                .WhereIf(inQuery.NoticeModeEnum != null, t => t.NoticeModeEnum == inQuery.NoticeModeEnum)
                .WhereIf(inQuery.NoticeStateEnum != null && inQuery.NoticeStateEnum != Domain.Share.SystemNotice_NoticeStateEnum.HaveExpired, t => t.NoticeStateEnum == inQuery.NoticeStateEnum)
                .WhereIf(inQuery.NoticeModeEnum != null && inQuery.NoticeStateEnum == Domain.Share.SystemNotice_NoticeStateEnum.HaveExpired, t => t.NoticeStateEnum == Domain.Share.SystemNotice_NoticeStateEnum.HavePublished && t.EndDate != null && t.EndDate < appDateTimeNow)
                .WhereIf(inQuery.NoticeTypeEnum != null, t => t.NoticeTypeEnum == inQuery.NoticeTypeEnum)
                .WhereIf(!string.IsNullOrWhiteSpace(inQuery.FileName), t => t.FileName.Contains(inQuery.FileName))
                .WhereIf(!string.IsNullOrWhiteSpace(inQuery.NoticeContent), t => t.NoticeContent.Contains(inQuery.NoticeContent))
                .ProjectTo<SystemNoticeReadDTO>(_mapper.ConfigurationProvider, new { token = _userInfo.UserToken, userId = _userInfo.Id });

            return await systemNoticeQueryable.ToPagedListAsync(inQuery);
        }


        public async Task<List<SystemNoticeView>> GetUserNoticeList()
        {
            //防止生成sql生成GETDATE() 时区导致的问题
            var appDateTimeNow = DateTime.Now;

            var query = _systemNoticeRepository
                  .Where(t => t.NoticeUserTypeList.Any(t => t.UserTypeId == _userInfo.UserTypeId) && t.NoticeStateEnum == Domain.Share.SystemNotice_NoticeStateEnum.HavePublished && !t.NoticeUserReadList.Any(t => t.CreateUserId == _userInfo.Id))
                  .Where(t => t.EndDate == null || t.EndDate != null && t.EndDate > appDateTimeNow)
                  .ProjectTo<SystemNoticeView>(_mapper.ConfigurationProvider, new { token = _userInfo.UserToken, userId = _userInfo.Id });

            return await query.ToListAsync();
        }

    }
}
