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

using Microsoft.AspNetCore.Mvc;
using IRaCIS.Core.Application.Contracts;
using User = IRaCIS.Core.Domain.Models.User;
using DocumentFormat.OpenXml.Office2010.Word;

namespace IRaCIS.Core.Application.Services
{
    /// <summary>
    /// SystemDocumentService
    /// </summary>	
    [ApiExplorerSettings(GroupName = "Trial")]
    public class SystemDocumentService : BaseService, ISystemDocumentService
    {

        private readonly IRepository<SystemDocument> _systemDocumentRepository;
        private readonly IRepository<SystemDocNeedConfirmedUserType> _systemDocNeedConfirmedUserTypeRepository;
        private readonly IRepository<SystemDocConfirmedUser> _systemDocConfirmedUserRepository;

        public SystemDocumentService( IRepository<SystemDocument> systemDocumentRepository,
            IRepository<SystemDocNeedConfirmedUserType> systemDocNeedConfirmedUserTypeRepository,
            IRepository<SystemDocConfirmedUser> systemDocConfirmedUserRepository)
        {
            _systemDocumentRepository = systemDocumentRepository;
            this._systemDocNeedConfirmedUserTypeRepository = systemDocNeedConfirmedUserTypeRepository;
            _systemDocConfirmedUserRepository = systemDocConfirmedUserRepository;
            }



        /// <summary>
        /// 管理端列表
        /// </summary>
        /// <param name="querySystemDocument"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<PageOutput<SystemDocumentView>> GetSystemDocumentListAsync(SystemDocumentQuery querySystemDocument)
        {
            var systemDocumentQueryable = _systemDocumentRepository.AsQueryable(true)
               .WhereIf(!string.IsNullOrEmpty(querySystemDocument.Name), t => t.Name.Contains(querySystemDocument.Name))
               .WhereIf(querySystemDocument.FileTypeId != null, t => t.FileTypeId == querySystemDocument.FileTypeId)
               .ProjectTo<SystemDocumentView>(_mapper.ConfigurationProvider, new { token = _userInfo.UserToken, userId = _userInfo.Id });

            return await systemDocumentQueryable.ToPagedListAsync(querySystemDocument.PageIndex, querySystemDocument.PageSize, querySystemDocument.SortField, querySystemDocument.Asc);
        }

        public async Task<IResponseOutput> AddOrUpdateSystemDocumentAsync(AddOrEditSystemDocument addOrEditSystemDocument)
        {
            if (addOrEditSystemDocument.Id == null)
            {
                var entity = _mapper.Map<SystemDocument>(addOrEditSystemDocument);


                if (await _systemDocumentRepository.AnyAsync(t => t.FileTypeId == addOrEditSystemDocument.FileTypeId && t.Name == addOrEditSystemDocument.Name,true))
                {
                //---系统中已存在同类型的同名文件。
                    return ResponseOutput.NotOk(_localizer["SystemD_DuplicateFile"]);
                }

                await _systemDocumentRepository.AddAsync(entity, true);

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

            }
            else
            {
                var document = (await _systemDocumentRepository.Where(t => t.Id == addOrEditSystemDocument.Id, true, true).Include(t => t.NeedConfirmedUserTypeList).FirstOrDefaultAsync()).IfNullThrowException();


                if (await _systemDocumentRepository.AnyAsync(t => t.FileTypeId == addOrEditSystemDocument.FileTypeId && t.Name == addOrEditSystemDocument.Name && t.Id != addOrEditSystemDocument.Id, true))
                {
                //---系统中已存在同类型的同名文件。
                    return ResponseOutput.NotOk(_localizer["SystemD_DuplicateFile"]);
                }
              

                _mapper.Map(addOrEditSystemDocument, document);

                #region 之前区分路径文件夹 现在不区分废弃

                //if (document.FileTypeId != addOrEditSystemDocument.FileTypeId)
                //{
                //    var rootPath = Directory.GetParent(_hostEnvironment.ContentRootPath.TrimEnd('\\')).IfNullThrowException().FullName;
                //    var beforeFilePath = Path.Combine(rootPath, document.Path);

                //    document.Path = document.Path.Replace(document.FileTypeId.ToString(), addOrEditSystemDocument.FileTypeId.ToString());

                //    var nowPath = Path.Combine(rootPath, document.Path);

                //    if (File.Exists(beforeFilePath))
                //    {
                //        File.Move(beforeFilePath, nowPath, true);
                //        File.Delete(beforeFilePath);
                //    }

                //}

                #endregion


                var success = await _systemDocumentRepository.SaveChangesAsync();

                return ResponseOutput.Ok(document.Id.ToString());
            }



        }

        [HttpDelete("{systemDocumentId:guid}")]
        public async Task<IResponseOutput> AbandonSystemDocumentAsync(Guid systemDocumentId)
        {

            await _systemDocumentRepository.UpdatePartialFromQueryAsync(systemDocumentId, u => new SystemDocument() { IsDeleted = true });

            await _systemDocConfirmedUserRepository.UpdatePartialFromQueryAsync(x => x.SystemDocumentId == systemDocumentId, x => new SystemDocConfirmedUser()
            {
                IsDeleted = true
            });

            await _systemDocConfirmedUserRepository.SaveChangesAsync();
            return ResponseOutput.Result(true);
        }



        [HttpDelete("{systemDocumentId:guid}")]
        public async Task<IResponseOutput> DeleteSystemDocumentAsync(Guid systemDocumentId)
        {

            if (await _repository.Where<SystemDocument>(t => t.Id == systemDocumentId).AnyAsync(u => u.SystemDocConfirmedUserList.Any()))
            {
                //---已有用户阅读该文档，并签名，不允许删除。
                return ResponseOutput.NotOk(_localizer["SystemD_CannotDeleteSignedFile"]);
            }

            var success = await _systemDocumentRepository.DeleteFromQueryAsync(t => t.Id == systemDocumentId,true,true);

            return ResponseOutput.Result(true);
        }


        /// <summary>
        /// 获取需要签署的系统文档列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<PageOutput<UnionDocumentWithConfirmInfoView>> getWaitSignSysDocList(SystemDocumentQuery querySystemDocument)
        {
            var query = from sysDoc in _systemDocumentRepository.Where(t => t.NeedConfirmedUserTypeList.Any(t => t.NeedConfirmUserTypeId == _userInfo.UserTypeId))
                    .WhereIf(!string.IsNullOrEmpty(querySystemDocument.Name), t => t.Name.Contains(querySystemDocument.Name))
                    .WhereIf(querySystemDocument.FileTypeId != null, t => t.FileTypeId == querySystemDocument.FileTypeId)
                        join confirm in _repository.GetQueryable<SystemDocConfirmedUser>() on new { ConfirmUserId = _userInfo.Id, SystemDocumentId = sysDoc.Id } equals new { confirm.ConfirmUserId, confirm.SystemDocumentId } into cc
                        from confirm in cc.DefaultIfEmpty()

                        join user in _repository.GetQueryable<User>() on _userInfo.Id equals user.Id

                        select new UnionDocumentWithConfirmInfoView()
                        {
                            IsSystemDoc = true,

                            Id = sysDoc.Id,
                            CreateTime = sysDoc.CreateTime,
                            IsDeleted = sysDoc.IsDeleted,
                            SignViewMinimumMinutes = sysDoc.SignViewMinimumMinutes,
                            Name = sysDoc.Name,
                            Path = sysDoc.Path,
                            FileType = sysDoc.FileType.MappedValue,
                            UpdateTime = sysDoc.UpdateTime,

                            FullFilePath = sysDoc.Path ,

                            ConfirmUserId = confirm.ConfirmUserId,
                            ConfirmTime = confirm.ConfirmTime,
                            RealName = user.LastName + " / " + user.FirstName,
                            UserName = user.UserName,
                            UserTypeId = user.UserTypeId,
                            UserTypeShortName = user.UserTypeRole.UserTypeShortName
                        };

            return await query.Where(t=>t.ConfirmTime==null).ToPagedListAsync(querySystemDocument.PageIndex, querySystemDocument.PageSize, querySystemDocument.SortField, querySystemDocument.Asc); 



        }

    }
}
