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

using IRaCIS.Core.Domain.Models;
using Microsoft.AspNetCore.Mvc;
using IRaCIS.Core.Application.Interfaces;
using IRaCIS.Core.Application.ViewModel;
namespace IRaCIS.Core.Application.Service
{
    /// <summary>
    /// SystemNoticeService
    /// </summary>	
    [ApiExplorerSettings(GroupName = "Management")]
    public class SystemNoticeService : BaseService, ISystemNoticeService
    {

        private readonly IRepository<SystemNotice> _systemNoticeRepository;

        public SystemNoticeService(IRepository<SystemNotice> systemNoticeRepository)
        {
            _systemNoticeRepository = systemNoticeRepository;
        }

        [HttpPost]
        public async Task<PageOutput<SystemNoticeView>> GetSystemNoticeList(SystemNoticeQuery querySystemNotice)
        {


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

            return await systemNoticeQueryable.ToPagedListAsync(querySystemNotice.PageIndex, querySystemNotice.PageSize, querySystemNotice.SortField, querySystemNotice.Asc);
        }


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

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

                if (entity.NoticeStateEnum == Domain.Share.Management.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.Management.SystemNotice_NoticeStateEnum.HavePublished && systemNotice.NoticeStateEnum == Domain.Share.Management.SystemNotice_NoticeStateEnum.NotPublish)
                {
                    systemNotice.PublishedUserId = _userInfo.Id;
                    systemNotice.PublishedTime = DateTime.Now;
                }
                else if (addOrEditSystemNotice.NoticeStateEnum == Domain.Share.Management.SystemNotice_NoticeStateEnum.NotPublish && systemNotice.NoticeStateEnum == Domain.Share.Management.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 querySystemNotice)
        {
            var systemNoticeQueryable = _systemNoticeRepository
                .Where(t => t.NoticeUserTypeList.Any(t => t.UserTypeId == _userInfo.UserTypeId) && t.NoticeStateEnum==Domain.Share.Management.SystemNotice_NoticeStateEnum.HavePublished)
                .WhereIf(querySystemNotice.ApplicableProjectEnum != null, t => t.ApplicableProjectEnum == querySystemNotice.ApplicableProjectEnum)
                .WhereIf(querySystemNotice.NoticeLevelEnum != null, t => t.NoticeLevelEnum == querySystemNotice.NoticeLevelEnum)
                .WhereIf(querySystemNotice.NoticeModeEnum != null, t => t.NoticeModeEnum == querySystemNotice.NoticeModeEnum)
                .WhereIf(querySystemNotice.NoticeStateEnum != null && querySystemNotice.NoticeStateEnum != Domain.Share.Management.SystemNotice_NoticeStateEnum.HaveExpired, t => t.NoticeStateEnum == querySystemNotice.NoticeStateEnum)
                .WhereIf(querySystemNotice.NoticeModeEnum != null && querySystemNotice.NoticeStateEnum == Domain.Share.Management.SystemNotice_NoticeStateEnum.HaveExpired, t => t.NoticeStateEnum == Domain.Share.Management.SystemNotice_NoticeStateEnum.HavePublished && t.EndDate != null && t.EndDate < DateTime.Now)
                .WhereIf(querySystemNotice.NoticeTypeEnum != null, t => t.NoticeTypeEnum == querySystemNotice.NoticeTypeEnum)
                .WhereIf(!string.IsNullOrWhiteSpace(querySystemNotice.FileName), t => t.FileName.Contains(querySystemNotice.FileName))
                .WhereIf(!string.IsNullOrWhiteSpace(querySystemNotice.NoticeContent), t => t.NoticeContent.Contains(querySystemNotice.NoticeContent))
                .ProjectTo<SystemNoticeReadDTO>(_mapper.ConfigurationProvider, new { token = _userInfo.UserToken, userId = _userInfo.Id });

            return await systemNoticeQueryable.ToPagedListAsync(querySystemNotice.PageIndex, querySystemNotice.PageSize, querySystemNotice.SortField, querySystemNotice.Asc);
        }


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

            return await query.ToListAsync();
        }

    }
}