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

using IRaCIS.Core.Application.Contracts;
using IRaCIS.Core.Application.MassTransit.Consumer;
using MassTransit.Mediator;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using System.Linq.Dynamic.Core;

namespace IRaCIS.Core.Application.Services
{
    /// <summary>
    /// TrialDocumentService
    /// </summary>	
    [ApiExplorerSettings(GroupName = "Trial")]
    public class TrialDocumentService(IRepository<TrialDocument> _trialDocumentRepository,
        IRepository<Trial> _trialRepository,
         IScopedMediator _mediatorScoped,
        IRepository<AuditRecord> _auditRecordRepository,
        IRepository<TrialDocumentAttachment> _trialDocumentAttachmentRepository,
        ISystemDocumentService _systemDocumentService,
        IRepository<SystemDocConfirmedIdentityUser> _systemDocConfirmedUserRepository,
        IRepository<SystemDocNeedConfirmedUserType> _systemDocNeedConfirmedUserTypeRepository,
         IRepository<TrialDocNeedConfirmedUserType> _trialDocNeedConfirmedUserTypeRepository,
        IRepository<SystemDocument> _systemDocumentRepository,
           IServiceScopeFactory serviceScopeFactory,
        IRepository<TrialIdentityUser> _trialIdentityUserRepository,
         IRepository<TrialUserRole> _trialUserRoleRepository,
          IRepository<IdentityUser> _identityUserRepository,
        IRepository<TrialDocConfirmedIdentityUser> _trialDocConfirmedUserRepository,
        IRepository<ReadingQuestionCriterionTrial> _readingQuestionCriterionTrialRepository, IMapper _mapper, IUserInfo _userInfo, IStringLocalizer _localizer) : BaseService, ITrialDocumentService
    {


        /// <summary>
        /// 获取项目文档附件列表
        /// </summary>
        /// <param name="inQuery"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<PageOutput<TrialDocumentAttachmentView>> GetTrialDocumentAttachmentList(TrialDocumentAttachmentQuery inQuery)
        {

            var trialDocumentAttachmentQueryable = _trialDocumentAttachmentRepository
                .WhereIf(inQuery.TrialDocumentId != null, x => x.TrialDocumentId == inQuery.TrialDocumentId)
                .WhereIf(inQuery.Name != null, x => x.Name.Contains(inQuery.Name))
                .WhereIf(inQuery.FileFormat != null, x => x.FileFormat == inQuery.FileFormat)
                .ProjectTo<TrialDocumentAttachmentView>(_mapper.ConfigurationProvider);

            var pageList = await trialDocumentAttachmentQueryable.ToPagedListAsync(inQuery);

            return pageList;
        }


        /// <summary>
        /// 添加或更新项目文档附件
        /// </summary>
        /// <param name="addOrEditTrialDocumentAttachment"></param>
        /// <returns></returns>
        public async Task<IResponseOutput> AddOrUpdateTrialDocumentAttachment(TrialDocumentAttachmentAddOrEdit addOrEditTrialDocumentAttachment)
        {
            //  在此处拷贝automapper 映射

            var entity = await _trialDocumentAttachmentRepository.InsertOrUpdateAsync(addOrEditTrialDocumentAttachment, true);

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

        }

        /// <summary>
        /// 删除项目文档附件
        /// </summary>
        /// <param name="trialDocumentAttachmentId"></param>
        /// <returns></returns>
        [HttpDelete("{trialDocumentAttachmentId:guid}")]
        public async Task<IResponseOutput> DeleteTrialDocumentAttachment(Guid trialDocumentAttachmentId)
        {
            var success = await _trialDocumentAttachmentRepository.DeleteFromQueryAsync(t => t.Id == trialDocumentAttachmentId, true);
            return ResponseOutput.Ok();
        }

        /// <summary>
        /// 发布项目文档
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<IResponseOutput> PublishTrialDocument(PublishTrialDocumentInDto inDto)
        {
            await _trialDocumentRepository.UpdatePartialFromQueryAsync(x => inDto.Ids.Contains(x.Id), x => new TrialDocument()
            {
                IsPublish = true,
                PublishDate = DateTime.Now,
                IsDeleted = false,
            }, false, true);
            await _trialDocumentRepository.SaveChangesAsync();
            Serilog.Log.Logger.Warning("开始 发布项目文档");

            await _mediatorScoped.Publish(new TrialDocumentPublishEvent { Ids = inDto.Ids });

           


            return ResponseOutput.Result(true);
        }

        /// <summary>
        /// 测试邮件定时发送
        /// </summary>
        /// <returns></returns>
        public async Task<IResponseOutput> TestPush()
        {


            await _mediatorScoped.Publish(new TrialDocumentErverDayEvent {  });
           
            return ResponseOutput.Result(true);
        }


        public async Task<IResponseOutput> TestSendEmail()
        {

            await _mediatorScoped.Publish(new ImageQCRecurringEvent { TrialId = Guid.Parse("08de2254-5d7d-581a-0242-0a0001000000") });


            return ResponseOutput.Result(true);
        }

        /// <summary>
        /// Setting 界面的  项目所有文档列表
        /// </summary>
        /// <param name="inQuery"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<PageOutput<TrialDocumentView>> GetTrialDocumentList(TrialDocumentQuery inQuery)
        {

            var trialDocumentQueryable = _trialDocumentRepository.AsQueryable(true).Where(t => t.TrialId == inQuery.TrialId)
            .WhereIf(!string.IsNullOrEmpty(inQuery.Name), t => t.Name.Contains(inQuery.Name))
            .WhereIf(inQuery.FileTypeId != null, t => t.FileTypeId == inQuery.FileTypeId)
            .WhereIf(inQuery.UserTypeId != null, t => t.NeedConfirmedUserTypeList.Any(t => t.NeedConfirmUserTypeId == inQuery.UserTypeId))
            .WhereIf(inQuery.IsDeleted != null, t => t.IsDeleted == inQuery.IsDeleted)
            .WhereIf(inQuery.IsPublish != null, t => t.IsPublish == inQuery.IsPublish)
            .WhereIf(!string.IsNullOrEmpty(inQuery.FileTypeCode), t => t.FileType.Code == inQuery.FileTypeCode)
            .ProjectTo<TrialDocumentView>(_mapper.ConfigurationProvider, new { token = _userInfo.UserToken, isEn_Us = _userInfo.IsEn_Us });

            return await trialDocumentQueryable.ToPagedListAsync(inQuery);
        }

        [HttpPost]
        public async Task<PageOutput<TriaAndSystemlSignDocView>> GetTrialSignDocumentList(TrialDocQuery inQuery)
        {
            var trialDocQueryable = from trialDoc in _trialDocumentRepository.Where(t => t.IsPublish)
                                    .WhereIf(inQuery.TrialId != null, t => t.TrialId == inQuery.TrialId)
                                    .Where(t => t.NeedConfirmedUserTypeList.Any(t => t.NeedConfirmUserTypeId == _userInfo.UserTypeId))

                                    join trialUser in _trialIdentityUserRepository.Where(t => t.IdentityUserId == _userInfo.IdentityUserId) on trialDoc.TrialId equals trialUser.TrialId
                                    join confirm in _trialDocConfirmedUserRepository.Where() on
                                    new { trialUser.IdentityUserId, TrialDocumentId = trialDoc.Id } equals new { IdentityUserId = confirm.ConfirmUserId, confirm.TrialDocumentId } into cc

                                    from confirm in cc.DefaultIfEmpty()
                                    select new TriaAndSystemlSignDocView()
                                    {
                                        TrialCode = trialDoc.Trial.TrialCode,
                                        ResearchProgramNo = trialDoc.Trial.ResearchProgramNo,
                                        ExperimentName = trialDoc.Trial.ExperimentName,
                                        CurrentStaffTrainDays = trialDoc.CurrentStaffTrainDays,
                                        NewStaffTrainDays = trialDoc.NewStaffTrainDays,
                                        Id = trialDoc.Id,
                                        IsSystemDoc = false,
                                        CreateTime = trialDoc.CreateTime,
                                        FullFilePath = trialDoc.Path,
                                        IsDeleted = trialDoc.IsDeleted,
                                        Name = trialDoc.Name,
                                        Path = trialDoc.Path,
                                        FileTypeId = trialDoc.FileTypeId,
                                        FileType = _userInfo.IsEn_Us ? trialDoc.FileType.Value : trialDoc.FileType.ValueCN,
                                        UpdateTime = trialDoc.UpdateTime,
                                        SignViewMinimumMinutes = trialDoc.SignViewMinimumMinutes,

                                        //IsConfirmed = confirm.ConfirmTime != null,
                                        ConfirmUserId = confirm.ConfirmUserId,
                                        ConfirmTime = confirm.ConfirmTime,
                                        RealName = trialUser.IdentityUser.FullName,
                                        UserName = trialUser.IdentityUser.UserName,

                                        IdentityUserTypeList = trialUser.TrialUserRoleList.Select(t => t.UserRole.UserTypeRole.UserTypeShortName).ToList(),

                                        DocNeedSignUserTypeList = trialDoc.NeedConfirmedUserTypeList.Select(t => t.UserTypeRole.UserTypeShortName).ToList(),
                                    };

            trialDocQueryable = trialDocQueryable.WhereIf(!string.IsNullOrEmpty(inQuery.Name), t => t.Name.Contains(inQuery.Name))
                .WhereIf(inQuery.FileTypeId != null, t => t.FileTypeId == inQuery.FileTypeId)
               .WhereIf(inQuery.IsSigned == true, t => t.ConfirmTime != null)
               .WhereIf(inQuery.IsSigned == false, t => t.ConfirmTime == null);


            return await trialDocQueryable.ToPagedListAsync(inQuery);

        }

        /// <summary>
        /// 获取下一个未签名的文件
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<UnionDocumentWithConfirmInfoView?> GetNextUnSignDocument(GetNextUnSignDocumentInDto inDto)
        {
            var result = new PageOutput<UnionDocumentWithConfirmInfoView>() { };

            if (inDto.TrialId != null)
            {
                result = (await this.GetUserDocumentList(new TrialUserDocUnionQuery()
                {
                    Asc = inDto.Asc,
                    IsSign = false,
                    SortField = inDto.SortField,
                    TrialId = inDto.TrialId.Value,
                    PageIndex = 1,
                    PageSize = 1,
                })).Data;
            }
            else
            {
                result = await _systemDocumentService.getWaitSignSysDocList(new SystemDocumentQuery()
                {
                    PageIndex = 1,
                    IsSigned = false,
                    PageSize = 1,
                    Asc = false,
                    SortField = "UpdateTime",
                });

            }


            if (result.CurrentPageData.Count > 0)
            {
                return result.CurrentPageData.First();
            }
            else
            {
                return null;
            }

        }

        /// <summary>
        ///  具体用户看到的 系统文件列表 + 项目类型文档
        /// </summary>
        /// <param name="inQuery"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IResponseOutput<PageOutput<UnionDocumentWithConfirmInfoView>>> GetUserDocumentList(TrialUserDocUnionQuery inQuery)
        {
            #region https://github.com/dotnet/efcore/issues/16243  操作不行
            ////系统文档查询
            //var systemDocumentQueryable = _systemDocumentRepository
            // .WhereIf(!_userInfo.IsAdmin, t => t.NeedConfirmedUserTypeList.Any(t => t.NeedConfirmUserTypeId == _userInfo.UserTypeId))
            // .WhereIf(!_userInfo.IsAdmin, t => t.IsAbandon == false || (t.IsAbandon == true && t.SystemDocConfirmedUserList.Any(t => t.ConfirmUserId == _userInfo.Id)))
            //.ProjectTo<UnionDocumentView>(_mapper.ConfigurationProvider, new { userId = _userInfo.Id, token = _userInfo.UserToken });

            ////项目文档查询
            //var trialDocQueryable = _trialDocumentRepository.Where(t => t.TrialId == querySystemDocument.TrialId)
            //   .WhereIf(!_userInfo.IsAdmin, t => t.NeedConfirmedUserTypeList.Any(t => t.NeedConfirmUserTypeId == _userInfo.UserTypeId))
            //   .WhereIf(!_userInfo.IsAdmin, t => t.IsAbandon == false || (t.IsAbandon == true && t.TrialDocConfirmedUserList.Any(t => t.ConfirmUserId == _userInfo.Id)))
            //   .ProjectTo<UnionDocumentView>(_mapper.ConfigurationProvider, new { userId = _userInfo.Id, token = _userInfo.UserToken });

            //var unionQuery = systemDocumentQueryable.Union(trialDocQueryable);
            //     .WhereIf(!string.IsNullOrEmpty(querySystemDocument.Name), t => t.Name.Contains(querySystemDocument.Name))
            //     .WhereIf(!string.IsNullOrEmpty(querySystemDocument.Type), t => t.Type.Contains(querySystemDocument.Type));
            #endregion

            #region 仅仅文档信息

            ////系统文档查询
            //var systemDocumentQueryable = _systemDocumentRepository
            // .WhereIf(!_userInfo.IsAdmin, t => t.NeedConfirmedUserTypeList.Any(t => t.NeedConfirmUserTypeId == _userInfo.UserTypeId))
            // .WhereIf(!_userInfo.IsAdmin, t => t.IsAbandon == false || (t.IsAbandon == true && t.SystemDocConfirmedUserList.Any(t => t.ConfirmUserId == _userInfo.Id)))
            // .Select(t => new UnionDocumentView()
            // {
            //     Id = t.Id,
            //     IsSystemDoc = true,
            //     CreateTime = t.CreateTime,
            //     FullFilePath = t.Path + "?access_token=" + _userInfo.UserToken,
            //     IsAbandon = t.IsAbandon,
            //     Name = t.Name,
            //     Path = t.Path,
            //     Type = t.Type,
            //     UpdateTime = t.UpdateTime,
            //     SignViewMinimumMinutes = t.SignViewMinimumMinutes,

            // });

            ////项目文档查询
            //var trialDocQueryable = _trialDocumentRepository.Where(t => t.TrialId == querySystemDocument.TrialId)
            //   .WhereIf(!_userInfo.IsAdmin, t => t.NeedConfirmedUserTypeList.Any(t => t.NeedConfirmUserTypeId == _userInfo.UserTypeId))
            //   .WhereIf(!_userInfo.IsAdmin, t => t.IsAbandon == false || (t.IsAbandon == true && t.TrialDocConfirmedUserList.Any(t => t.ConfirmUserId == _userInfo.Id)))
            //    .Select(t => new UnionDocumentView()
            //    {
            //        Id = t.Id,
            //        IsSystemDoc = false,
            //        CreateTime = t.CreateTime,
            //        FullFilePath = t.Path + "?access_token=" + _userInfo.UserToken,
            //        IsAbandon = t.IsAbandon,
            //        Name = t.Name,
            //        Path = t.Path,
            //        Type = t.Type,
            //        UpdateTime = t.UpdateTime,
            //        SignViewMinimumMinutes = t.SignViewMinimumMinutes,

            //    });

            #endregion

            var trialId = inQuery.TrialId;

            var trialInfo = await (_trialRepository.Where(t => t.Id == inQuery.TrialId, ignoreQueryFilters: true).Select(t => new { t.TrialFinishedTime, t.TrialStatusStr }).FirstNotNullAsync());

            var isInternal = _userInfo.IsZhiZhun;

            var workLanguage = _userInfo.UserWorkLanguage;

            #region 统一用户修改 

            var systemDocQuery =
                 from sysDoc in _systemDocumentRepository.Where(t => t.IsPublish).Where(t => t.NeedConfirmedUserTypeList.Any(c => c.NeedConfirmUserTypeId == _userInfo.UserTypeId))
                    //外部人员 只签署 外部需要签署的
                    .WhereIf(isInternal == false, t => t.DocUserSignType == DocUserSignType.InnerAndOuter)
                    .WhereIf(workLanguage == UserWorkLanguage.CN, t => t.DocLanguageType == DocLanguageType.CN || t.DocLanguageType == DocLanguageType.CN_US)
                    .WhereIf(workLanguage == UserWorkLanguage.US, t => t.DocLanguageType == DocLanguageType.US || t.DocLanguageType == DocLanguageType.CN_US)
                 from trialUser in _trialIdentityUserRepository.AsQueryable(false)
                  .Where(t => t.TrialId == inQuery.TrialId && t.IdentityUserId == _userInfo.IdentityUserId
                  && t.TrialUserRoleList.Any(t => sysDoc.NeedConfirmedUserTypeList.Any(c => c.NeedConfirmUserTypeId == t.UserRole.UserTypeId)))

                 join confirm in _systemDocConfirmedUserRepository.Where() on new { ConfirmUserId = trialUser.IdentityUserId, SystemDocumentId = sysDoc.Id } equals new { confirm.ConfirmUserId, confirm.SystemDocumentId } into cc
                 from confirm in cc.DefaultIfEmpty()
                 select new UnionDocumentWithConfirmInfoView()
                 {
                     IsSystemDoc = true,
                     Id = sysDoc.Id,
                     CreateTime = sysDoc.CreateTime,
                     IsDeleted = sysDoc.IsDeleted,
                     SignViewMinimumMinutes = sysDoc.SignViewMinimumMinutes,
                     Name = sysDoc.Name,
                     Path = sysDoc.Path,
                     FileType = _userInfo.IsEn_Us ? sysDoc.FileType.Value : sysDoc.FileType.ValueCN,
                     FileTypeId = sysDoc.FileTypeId,
                     UpdateTime = sysDoc.UpdateTime,
                     //IsConfirmed = confirm.ConfirmTime != null,

                     ConfirmUserId = confirm.ConfirmUserId,
                     ConfirmTime = confirm.ConfirmTime,

                     RealName = trialUser.IdentityUser.FullName,
                     UserName = trialUser.IdentityUser.UserName,

                     //UserTypeId = trialUser.UserRole.UserTypeId,
                     //UserTypeShortName = trialUser.UserRole.UserTypeRole.UserTypeShortName,
                     //DocNeedSignUserTypeList = sysDoc.NeedConfirmedUserTypeList.Select(t => t.UserTypeRole.UserTypeName),

                     FullFilePath = sysDoc.Path
                 };


            //项目文档查询
            var trialDocQuery =
                  from trialDoc in _trialDocumentRepository.Where(t => t.IsPublish).Where(t => t.TrialId == inQuery.TrialId).Where(t => t.NeedConfirmedUserTypeList.Any(c => c.NeedConfirmUserTypeId == _userInfo.UserTypeId))
                  from trialUser in _trialIdentityUserRepository.AsQueryable(false).Where(t => t.TrialId == inQuery.TrialId && t.IdentityUserId == _userInfo.IdentityUserId
                                && t.TrialUserRoleList.Any(t => trialDoc.NeedConfirmedUserTypeList.Any(c => c.NeedConfirmUserTypeId == t.UserRole.UserTypeId)))

                  join confirm in _trialDocConfirmedUserRepository.Where(t => t.TrialDocument.TrialId == inQuery.TrialId) on
                   new { trialUser.IdentityUserId, TrialDocumentId = trialDoc.Id } equals new { IdentityUserId = confirm.ConfirmUserId, confirm.TrialDocumentId } into cc
                  from confirm in cc.DefaultIfEmpty()
                  select new UnionDocumentWithConfirmInfoView()
                  {
                      IsSystemDoc = false,

                      Id = trialDoc.Id,
                      CreateTime = trialDoc.CreateTime,
                      IsDeleted = trialDoc.IsDeleted,
                      SignViewMinimumMinutes = trialDoc.SignViewMinimumMinutes,
                      Name = trialDoc.Name,
                      Path = trialDoc.Path,
                      FileTypeId = trialDoc.FileTypeId,
                      FileType = _userInfo.IsEn_Us ? trialDoc.FileType.Value : trialDoc.FileType.ValueCN,
                      UpdateTime = trialDoc.UpdateTime,
                      //IsConfirmed= confirm.ConfirmTime!=null,



                      ConfirmUserId = confirm.ConfirmUserId,
                      ConfirmTime = confirm.ConfirmTime,
                      RealName = trialUser.IdentityUser.FullName,
                      UserName = trialUser.IdentityUser.UserName,

                      //DocNeedSignUserTypeList = trialDoc.NeedConfirmedUserTypeList.Select(t => t.UserTypeRole.UserTypeName),

                      //UserTypeId = trialUser.UserRole.UserTypeId,
                      //UserTypeShortName = trialUser.UserRole.UserTypeRole.UserTypeShortName,

                      FullFilePath = trialDoc.Path
                  };



            #endregion



            #region 废弃

            ////系统文档查询
            //var systemDocQuery = from needConfirmedUserType in _systemDocNeedConfirmedUserTypeRepository.Where(t => t.NeedConfirmUserTypeId == _userInfo.UserTypeId, ignoreQueryFilters: true)
            //                                   .WhereIf(trialInfo.TrialFinishedTime != null, u => u.SystemDocument.CreateTime < trialInfo.TrialFinishedTime)
            //                                   .WhereIf(!_userInfo.IsAdmin, t => t.SystemDocument.IsDeleted == false || (t.SystemDocument.IsDeleted == true && t.SystemDocument.SystemDocConfirmedUserList.Any(t => t.ConfirmUserId == _userInfo.IdentityUserId)))

            //                              join trialUser in _trialUserRoleRepository.Where(t => t.TrialId == inQuery.TrialId && t.UserRole.IdentityUserId == _userInfo.IdentityUserId)
            //                                                              on needConfirmedUserType.NeedConfirmUserTypeId equals trialUser.UserRole.UserTypeId
            //                              join confirm in _systemDocConfirmedUserRepository.Where() on new { ConfirmUserId = trialUser.UserId, SystemDocumentId = needConfirmedUserType.SystemDocumentId } equals new { confirm.ConfirmUserId, confirm.SystemDocumentId } into cc
            //                              from confirm in cc.DefaultIfEmpty()
            //                              select new UnionDocumentWithConfirmInfoView()
            //                              {
            //                                  IsSystemDoc = true,

            //                                  Id = needConfirmedUserType.SystemDocument.Id,
            //                                  CreateTime = needConfirmedUserType.SystemDocument.CreateTime,
            //                                  IsDeleted = needConfirmedUserType.SystemDocument.IsDeleted,
            //                                  SignViewMinimumMinutes = needConfirmedUserType.SystemDocument.SignViewMinimumMinutes,
            //                                  Name = needConfirmedUserType.SystemDocument.Name,
            //                                  Path = needConfirmedUserType.SystemDocument.Path,
            //                                  FileTypeId = needConfirmedUserType.SystemDocument.FileTypeId,
            //                                  FileType = _userInfo.IsEn_Us ? needConfirmedUserType.SystemDocument.FileType.Value : needConfirmedUserType.SystemDocument.FileType.ValueCN,
            //                                  UpdateTime = needConfirmedUserType.SystemDocument.UpdateTime,

            //                                  FullFilePath = needConfirmedUserType.SystemDocument.Path,

            //                                  //IsConfirmed = confirm.ConfirmTime != null,
            //                                  ConfirmUserId = confirm.ConfirmUserId,
            //                                  ConfirmTime = confirm.ConfirmTime,
            //                                  RealName = trialUser.UserRole.FullName,
            //                                  UserName = trialUser.UserRole.IdentityUser.UserName,



            //                                  //IdentityUserTypeList = trialUser.TrialUser.TrialUserRoleList.Select(t => t.UserRole.UserTypeRole.UserTypeShortName),

            //                                  //DocNeedSignUserTypeList = needConfirmedUserType.SystemDocument.NeedConfirmedUserTypeList.Select(t => t.UserTypeRole.UserTypeShortName).ToList(),

            //                                  //UserTypeId = trialUser.UserRole.UserTypeId,
            //                                  //UserTypeShortName = trialUser.UserRole.UserTypeRole.UserTypeShortName
            //                              };

            ////项目文档查询
            //var trialDocQuery = from trialDoc in _trialDocumentRepository.AsQueryable(true).Where(t => t.TrialId == inQuery.TrialId)
            //   .WhereIf(!_userInfo.IsAdmin, t => t.NeedConfirmedUserTypeList.Any(t => t.NeedConfirmUserTypeId == _userInfo.UserTypeId))
            //   .WhereIf(!_userInfo.IsAdmin, t => t.IsDeleted == false || (t.IsDeleted == true && t.TrialDocConfirmedUserList.Any(t => t.ConfirmUserId == _userInfo.IdentityUserId)))

            //                        join trialUser in _trialUserRoleRepository.Where(t => t.TrialId == inQuery.TrialId && t.UserRole.IdentityUserId == _userInfo.IdentityUserId) on trialDoc.TrialId equals trialUser.TrialId
            //                        join confirm in _trialDocConfirmedUserRepository.Where(t => t.TrialDocument.TrialId == inQuery.TrialId) on
            //                        new { trialUser.UserId, TrialDocumentId = trialDoc.Id } equals new { UserId = confirm.ConfirmUserId, confirm.TrialDocumentId } into cc
            //                        from confirm in cc.DefaultIfEmpty()
            //                        select new UnionDocumentWithConfirmInfoView()
            //                        {
            //                            Id = trialDoc.Id,
            //                            IsSystemDoc = false,
            //                            CreateTime = trialDoc.CreateTime,
            //                            FullFilePath = trialDoc.Path,
            //                            IsDeleted = trialDoc.IsDeleted,
            //                            Name = trialDoc.Name,
            //                            Path = trialDoc.Path,
            //                            FileTypeId = trialDoc.FileTypeId,
            //                            FileType = _userInfo.IsEn_Us ? trialDoc.FileType.Value : trialDoc.FileType.ValueCN,
            //                            UpdateTime = trialDoc.UpdateTime,
            //                            SignViewMinimumMinutes = trialDoc.SignViewMinimumMinutes,

            //                            //IsConfirmed = confirm.ConfirmTime != null,
            //                            ConfirmUserId = confirm.ConfirmUserId,
            //                            ConfirmTime = confirm.ConfirmTime,
            //                            RealName = trialUser.UserRole.FullName,
            //                            UserName = trialUser.UserRole.IdentityUser.UserName,

            //                            //UserTypeId = trialUser.UserRole.UserTypeId,
            //                            //UserTypeShortName = trialUser.UserRole.UserTypeRole.UserTypeShortName


            //                            //IdentityUserTypeList = trialUser.TrialUser.TrialUserRoleList.Select(t => t.UserRole.UserTypeRole.UserTypeShortName).ToList(),

            //                            //DocNeedSignUserTypeList = trialDoc.NeedConfirmedUserTypeList.Select(t => t.UserTypeRole.UserTypeShortName).ToList(),
            //                        };

            #endregion

            #region 报错  奇怪的bug


            var unionQuery = systemDocQuery.Concat(trialDocQuery)
                //过滤掉删除的，并且没有签名的
                .Where(t => !(t.IsDeleted == true && t.ConfirmTime == null))
                .WhereIf(!string.IsNullOrEmpty(inQuery.Name), t => t.Name.Contains(inQuery.Name))
                .WhereIf(inQuery.FileTypeId != null, t => t.FileTypeId == inQuery.FileTypeId)
                .WhereIf(inQuery.IsSign == true, t => t.ConfirmTime != null)
                .WhereIf(inQuery.IsSign == false, t => t.ConfirmTime == null);

            var defalutSortArray = new string[] { nameof(UnionDocumentWithConfirmInfoView.IsDeleted), nameof(UnionDocumentWithConfirmInfoView.CreateTime) + " desc", nameof(UnionDocumentWithConfirmInfoView.ConfirmTime) };

            var result = await unionQuery.ToPagedListAsync(inQuery, defalutSortArray);

            //Concat 不能用导航属性
            var sysids = result.CurrentPageData.Where(t => t.IsSystemDoc == true).Select(t => t.Id).ToList();

            var sysDataList = await _systemDocumentRepository.Where(x => sysids.Contains(x.Id)).Include(x => x.SystemDocumentAttachmentList).ToListAsync();



            result.CurrentPageData.ForEach(x =>
            {
                if (sysDataList.Any(y => y.Id == x.Id))
                {
                    x.AttachmentCount = sysDataList.Where(y => y.Id == x.Id).Select(x => x.SystemDocumentAttachmentList.Where(z => !z.OffLine).Count()).FirstOrDefault();
                }
            });

            var trialids = result.CurrentPageData.Where(t => t.IsSystemDoc == false).Select(t => t.Id).ToList();

            var trialDataList = await _trialDocumentRepository.Where(x => trialids.Contains(x.Id)).Include(x => x.TrialDocumentAttachmentList).ToListAsync();

            result.CurrentPageData.ForEach(x =>
            {
                if (trialDataList.Any(y => y.Id == x.Id))
                {
                    x.AttachmentCount = trialDataList.Where(y => y.Id == x.Id).Select(x => x.TrialDocumentAttachmentList.Where(z => !z.OffLine).Count()).FirstOrDefault();
                }
            });
            #endregion

            #region 临时方案

            //var list1 = systemDocumentQueryable
            //   .WhereIf(!string.IsNullOrEmpty(querySystemDocument.Name), t => t.Name.Contains(querySystemDocument.Name))
            //  .WhereIf(querySystemDocument.FileTypeId != null, t => t.FileTypeId == querySystemDocument.FileTypeId)
            //  .WhereIf(querySystemDocument.IsSign == true, t => t.ConfirmTime != null)
            //  .WhereIf(querySystemDocument.IsSign == false, t => t.ConfirmTime == null).ToList();

            //var list2 = trialDocQueryable
            // .WhereIf(!string.IsNullOrEmpty(querySystemDocument.Name), t => t.Name.Contains(querySystemDocument.Name))
            //.WhereIf(querySystemDocument.FileTypeId != null, t => t.FileTypeId == querySystemDocument.FileTypeId)
            //.WhereIf(querySystemDocument.IsSign == true, t => t.ConfirmTime != null)
            //.WhereIf(querySystemDocument.IsSign == false, t => t.ConfirmTime == null).ToList();

            //var list3 = list1.Union(list2).ToList();

            //var result=list3.ToPagedList(querySystemDocument.PageIndex, querySystemDocument.PageSize, querySystemDocument.SortField, querySystemDocument.Asc);

            #endregion


            var needSignTrialDocCount = await _trialDocumentRepository.AsQueryable(true).Where(t => t.IsPublish)

                       .Where(t => t.TrialId == inQuery.TrialId && t.Trial.TrialStatusStr != StaticData.TrialState.TrialStopped)
                       .Where(t => t.Trial.TrialIdentityUserList.Any(t => t.IdentityUserId == _userInfo.IdentityUserId && t.TrialUserRoleList.Any(t => t.UserRole.UserTypeId == _userInfo.UserTypeId)))
                       .Where(t => t.IsDeleted == false && !t.TrialDocConfirmedUserList.Any(t => t.ConfirmUserId == _userInfo.IdentityUserId && t.ConfirmTime != null) && t.NeedConfirmedUserTypeList.Any(u => u.NeedConfirmUserTypeId == _userInfo.UserTypeId))
                       .CountAsync();


            var needSignSystemDocCount = await _systemDocumentRepository.AsQueryable(true).Where(t => t.IsPublish)
                      .WhereIf(workLanguage == UserWorkLanguage.CN, t => t.DocLanguageType == DocLanguageType.CN || t.DocLanguageType == DocLanguageType.CN_US)
                      .WhereIf(workLanguage == UserWorkLanguage.US, t => t.DocLanguageType == DocLanguageType.US || t.DocLanguageType == DocLanguageType.CN_US)
                      .WhereIf(isInternal == false, t => t.DocUserSignType == DocUserSignType.InnerAndOuter)
                      .Where(t => t.IsDeleted == false && !t.SystemDocConfirmedUserList.Any(t => t.ConfirmUserId == _userInfo.IdentityUserId && t.ConfirmTime != null) && t.NeedConfirmedUserTypeList.Any(u => u.NeedConfirmUserTypeId == _userInfo.UserTypeId))
                      .CountAsync();

            var trialTaskConfig = _trialRepository.Where(t => t.Id == inQuery.TrialId).ProjectTo<TrialProcessConfigDTO>(_mapper.ConfigurationProvider).FirstOrDefault();



            var isManualGenerateTask = _readingQuestionCriterionTrialRepository.Where(t => t.TrialId == trialId && t.IsSigned && t.IsAutoCreate == false).Any();
            var isAdditionalAssessment = _readingQuestionCriterionTrialRepository.Where(t => t.TrialId == trialId && t.IsSigned && t.IsAdditionalAssessment == true
            && t.TrialCriterionAdditionalAssessmentTypeList.Any(c =>/*c.AdditionalAssessmentType==Domain.Share.Reading.AdditionalAssessmentType.BrainMetastasis &&*/ c.IsSelected == true)).Any();

            return ResponseOutput.Ok(result, new { NeedSignCount = needSignTrialDocCount + needSignSystemDocCount, NeedSignTrialDocCount = needSignTrialDocCount, NeedSignSystemDocCount = needSignSystemDocCount, IsAdditionalAssessment = isAdditionalAssessment && isManualGenerateTask, TrialStatusStr = trialInfo.TrialStatusStr, TrialConfig = trialTaskConfig });
        }




        /// <summary>
        /// 获取确认列表情况  项目文档+系统文档+具体的人
        /// </summary>
        /// <param name="inQuery"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IResponseOutput<PageOutput<UnionDocumentWithConfirmInfoView>>> GetDocumentConfirmList(DocumentTrialUnionQuery inQuery)
        {

            #region 测试

            var trialInfo = (await _trialRepository.Where(t => t.Id == inQuery.TrialId, ignoreQueryFilters: true).Select(t => new { t.TrialFinishedTime, t.TrialStatusStr }).FirstNotNullAsync());

            var trialDocQuery =
                  from trialDoc in _trialDocumentRepository.Where(t => t.TrialId == inQuery.TrialId && t.IsPublish)
                                  .Where(t => inQuery.UserTypeId != null ? t.NeedConfirmedUserTypeList.Any(t => t.NeedConfirmUserTypeId == inQuery.UserTypeId) : true)
                  from trialUser in _trialIdentityUserRepository.AsQueryable(false).Where(t => t.TrialId == inQuery.TrialId
            && t.TrialUserRoleList.AsQueryable().Any(t => trialDoc.NeedConfirmedUserTypeList.Any(c => c.NeedConfirmUserTypeId == t.UserRole.UserTypeId))
            )
             .Where(t => inQuery.UserId != null ? t.IdentityUserId == inQuery.UserId : true)
             .Where(t => inQuery.UserTypeId != null ? t.TrialUserRoleList.Any(t => t.UserRole.UserTypeId == inQuery.UserTypeId) : true)


                  join confirm in _trialDocConfirmedUserRepository.Where(t => t.TrialDocument.TrialId == inQuery.TrialId) on
                   new { trialUser.IdentityUserId, TrialDocumentId = trialDoc.Id } equals new { IdentityUserId = confirm.ConfirmUserId, confirm.TrialDocumentId } into cc
                  from confirm in cc.DefaultIfEmpty()
                  select new UnionDocumentWithConfirmInfoView()
                  {
                      IsSystemDoc = false,

                      Id = trialDoc.Id,
                      CreateTime = trialDoc.CreateTime,
                      IsDeleted = trialDoc.IsDeleted,
                      SignViewMinimumMinutes = trialDoc.SignViewMinimumMinutes,
                      Name = trialDoc.Name,
                      Path = trialDoc.Path,
                      FileTypeId = trialDoc.FileTypeId,
                      FileType = _userInfo.IsEn_Us ? trialDoc.FileType.Value : trialDoc.FileType.ValueCN,
                      UpdateTime = trialDoc.UpdateTime,
                      //IsConfirmed= confirm.ConfirmTime!=null,



                      ConfirmUserId = trialUser.IdentityUserId,
                      ConfirmTime = confirm.ConfirmTime,
                      RealName = trialUser.IdentityUser.FullName,
                      UserName = trialUser.IdentityUser.UserName,

                      //UserTypeId = trialUser.UserRole.UserTypeId,
                      //UserTypeShortName = trialUser.UserRole.UserTypeRole.UserTypeShortName,
                      //DocNeedSignUserTypeList = trialDoc.NeedConfirmedUserTypeList.Select(t => t.UserTypeRole.UserTypeName),

                      FullFilePath = trialDoc.Path
                  };



            var systemDocQuery =
                 from sysDoc in _systemDocumentRepository.AsQueryable(false).Where(u => trialInfo.TrialFinishedTime != null ? u.CreateTime < trialInfo.TrialFinishedTime : true)
                                                .Where(t => inQuery.UserTypeId != null ? t.NeedConfirmedUserTypeList.Any(t => t.NeedConfirmUserTypeId == inQuery.UserTypeId) : true)
                 from trialUser in _trialIdentityUserRepository.AsQueryable(false).Where(t => t.TrialId == inQuery.TrialId
                       && t.TrialUserRoleList.Any(t => sysDoc.NeedConfirmedUserTypeList.AsQueryable().Any(c => c.NeedConfirmUserTypeId == t.UserRole.UserTypeId)))
                    .Where(t => inQuery.UserId != null ? t.IdentityUserId == inQuery.UserId : true)
                    .Where(t => inQuery.UserTypeId != null ? t.TrialUserRoleList.Any(t => t.UserRole.UserTypeId == inQuery.UserTypeId) : true)
                 join confirm in _systemDocConfirmedUserRepository.Where() on new { ConfirmUserId = trialUser.IdentityUserId, SystemDocumentId = sysDoc.Id } equals new { confirm.ConfirmUserId, confirm.SystemDocumentId } into cc
                 from confirm in cc.DefaultIfEmpty()
                 select new UnionDocumentWithConfirmInfoView()
                 {
                     IsSystemDoc = true,

                     Id = sysDoc.Id,
                     CreateTime = sysDoc.CreateTime,
                     IsDeleted = sysDoc.IsDeleted,
                     SignViewMinimumMinutes = sysDoc.SignViewMinimumMinutes,
                     Name = sysDoc.Name,
                     Path = sysDoc.Path,
                     FileType = _userInfo.IsEn_Us ? sysDoc.FileType.Value : sysDoc.FileType.ValueCN,
                     FileTypeId = sysDoc.FileTypeId,
                     UpdateTime = sysDoc.UpdateTime,
                     //IsConfirmed = confirm.ConfirmTime != null,

                     ConfirmUserId = trialUser.IdentityUserId,
                     ConfirmTime = confirm.ConfirmTime,

                     RealName = trialUser.IdentityUser.FullName,
                     UserName = trialUser.IdentityUser.UserName,

                     //UserTypeId = trialUser.UserRole.UserTypeId,
                     //UserTypeShortName = trialUser.UserRole.UserTypeRole.UserTypeShortName,

                     FullFilePath = sysDoc.Path
                 };

            //var tt = await trialDocQuery.ToPagedListAsync(inQuery);

            var unionQuery = trialDocQuery.Union(systemDocQuery).IgnoreQueryFilters().Where(t => !(t.IsDeleted == true && t.ConfirmTime == null))
                .WhereIf(!string.IsNullOrEmpty(inQuery.Name), t => t.Name.Contains(inQuery.Name))
                .WhereIf(inQuery.FileTypeId != null, t => t.FileTypeId == inQuery.FileTypeId)
                .WhereIf(inQuery.IsConfirmed == true, t => t.ConfirmTime != null)
                .WhereIf(inQuery.IsConfirmed == false, t => t.ConfirmTime == null)
                .WhereIf(inQuery.StartConfirmTime != null, t => t.ConfirmTime >= inQuery.StartConfirmTime.Value)
                .WhereIf(inQuery.EndConfirmTime != null, t => t.ConfirmTime <= inQuery.EndConfirmTime.Value)
                .WhereIf(inQuery.BeginCreateTime != null, t => t.CreateTime >= inQuery.BeginCreateTime)
               .WhereIf(inQuery.EndCreateTime != null, t => t.CreateTime <= inQuery.EndCreateTime)
                .WhereIf(!string.IsNullOrEmpty(inQuery.UserName), t => t.UserName.Contains(inQuery.UserName))
                .WhereIf(inQuery.IsDeleted != null, t => t.IsDeleted == inQuery.IsDeleted)
                .WhereIf(_userInfo.UserTypeEnumInt == (int)UserTypeEnum.EA, t => t.ConfirmTime != null);

            var result = await unionQuery.ToPagedListAsync(inQuery);

            //Concat 不能用导航属性
            var sysids = result.CurrentPageData.Where(t => t.IsSystemDoc == true).Select(t => t.Id).ToList();

            var sysDataList = await _systemDocumentRepository.Where(x => sysids.Contains(x.Id)).Include(x => x.SystemDocumentAttachmentList).ToListAsync();
            result.CurrentPageData.ForEach(x =>
            {
                if (sysDataList.Any(y => y.Id == x.Id))
                {
                    x.AttachmentCount = sysDataList.Where(y => y.Id == x.Id).Select(x => x.SystemDocumentAttachmentList.Where(z => !z.OffLine).Count()).FirstOrDefault();
                }
            });

            #region 处理文档 需要签署的角色类型  和每个人的角色信息

            var trialDocIdList = result.CurrentPageData.Where(t => t.IsSystemDoc == false).Select(t => t.Id).ToList();

            var sysDocIdList = result.CurrentPageData.Where(t => t.IsSystemDoc == true).Select(t => t.Id).ToList();

            var trialIdentityUserIdList = result.CurrentPageData.Select(t => t.ConfirmUserId).Distinct().ToList();

            var trialDocUserTypeList = _trialDocNeedConfirmedUserTypeRepository.Where(t => trialDocIdList.Contains(t.TrialDocumentId)).Select(t => new { t.TrialDocumentId, t.UserTypeRole.UserTypeShortName }).ToList();

            var sysDocUserTypeList = _systemDocNeedConfirmedUserTypeRepository.Where(t => sysDocIdList.Contains(t.SystemDocumentId)).Select(t => new { t.SystemDocumentId, t.UserTypeRole.UserTypeShortName }).ToList();

            var trialUserUserTypeList = _trialIdentityUserRepository.Where(t => t.TrialId == inQuery.TrialId && trialIdentityUserIdList.Contains(t.IdentityUserId)).IgnoreQueryFilters().Select(t => new { t.IdentityUserId, UserTypeList = t.TrialUserRoleList.Select(c => c.UserRole.UserTypeRole.UserTypeShortName).ToList() });


            foreach (var item in result.CurrentPageData)
            {
                if (item.IsSystemDoc)
                {
                    item.DocNeedSignUserTypeList = sysDocUserTypeList.Where(t => t.SystemDocumentId == item.Id).Select(t => t.UserTypeShortName).ToList();
                }
                else
                {
                    item.DocNeedSignUserTypeList = trialDocUserTypeList.Where(t => t.TrialDocumentId == item.Id).Select(t => t.UserTypeShortName).ToList();
                }

                item.IdentityUserTypeList = trialUserUserTypeList.Where(t => t.IdentityUserId == item.ConfirmUserId).SelectMany(c => c.UserTypeList).ToList();
            }


            #endregion

            var needSignTrialDocCount = await _trialDocumentRepository.AsQueryable(true)
                    .Where(t => t.Trial.TrialIdentityUserList.Any(t => t.IdentityUserId == _userInfo.IdentityUserId && t.TrialUserRoleList.Any(t => t.UserRole.UserTypeId == _userInfo.UserTypeId)))
                    .Where(t => t.IsDeleted == false && !t.TrialDocConfirmedUserList.Any(t => t.ConfirmUserId == _userInfo.IdentityUserId) && t.NeedConfirmedUserTypeList.Any(u => u.NeedConfirmUserTypeId == _userInfo.UserTypeId))
                    .CountAsync();


            var needSignSystemDocCount = await _systemDocumentRepository
                      .Where(t => t.IsDeleted == false && !t.SystemDocConfirmedUserList.Any(t => t.ConfirmUserId == _userInfo.IdentityUserId) && t.NeedConfirmedUserTypeList.Any(u => u.NeedConfirmUserTypeId == _userInfo.UserTypeId))
                      .CountAsync();


            return ResponseOutput.Ok(result, new { NeedSignCount = needSignTrialDocCount + needSignSystemDocCount, NeedSignTrialDocCount = needSignTrialDocCount, NeedSignSystemDocCount = needSignSystemDocCount, TrialStatusStr = trialInfo.TrialStatusStr });




            #endregion

            #region linq join 方式
            //var trialDocQuery = from trialDocumentNeedConfirmedUserType in _trialDocumentNeedConfirmedUserTypeRepository.Where(t => t.TrialDocument.TrialId == querySystemDocument.TrialId)
            //                    join trialUser in _trialUserRoleRepository.Where(t => t.TrialId == querySystemDocument.TrialId)
            //                                                  .WhereIf(querySystemDocument.UserId != null, t => t.UserId == querySystemDocument.UserId)
            //                    on trialDocumentNeedConfirmedUserType.NeedConfirmUserTypeId equals trialUser.User.UserTypeId

            //                    join confirm in _trialDocuserConfrimedRepository.AsQueryable() on trialUser.UserId equals confirm.ConfirmUserId into cc
            //                    from confirm in cc.DefaultIfEmpty()
            //                    select new UnionDocumentConfirmListView()
            //                    {
            //                        Id = trialDocumentNeedConfirmedUserType.TrialDocument.Id,
            //                        CreateTime = trialDocumentNeedConfirmedUserType.TrialDocument.CreateTime,
            //                        IsAbandon = trialDocumentNeedConfirmedUserType.TrialDocument.IsAbandon,
            //                        SignViewMinimumMinutes = trialDocumentNeedConfirmedUserType.TrialDocument.SignViewMinimumMinutes,
            //                        Name = trialDocumentNeedConfirmedUserType.TrialDocument.Name,
            //                        Path = trialDocumentNeedConfirmedUserType.TrialDocument.Path,
            //                        Type = trialDocumentNeedConfirmedUserType.TrialDocument.Type,
            //                        UpdateTime = trialDocumentNeedConfirmedUserType.TrialDocument.UpdateTime,

            //                        UserConfirmInfo = /*confirm == null ? null : */new UnionDocumentUserConfirmView()
            //                        {

            //                            ConfirmUserId = confirm.ConfirmUserId,
            //                            ConfirmTime = confirm.ConfirmTime,
            //                            RealName = trialUser.User.LastName + " / " + trialUser.User.LastName,
            //                            UserName = trialUser.User.UserName,
            //                        },

            //                        FullFilePath = trialDocumentNeedConfirmedUserType.TrialDocument.Path + "?access_token=" + _userInfo.UserToken
            //                    };

            #endregion

            #region 废弃
            //var trialInfo = (await _trialRepository.Where(t => t.Id == inQuery.TrialId, ignoreQueryFilters: true).Select(t => new { t.TrialFinishedTime, t.TrialStatusStr }).FirstNotNullAsync());

            //var trialDocQuery = from trialDocumentNeedConfirmedUserType in _trialDocNeedConfirmedUserTypeRepository.Where(t => t.TrialDocument.TrialId == inQuery.TrialId)
            //                    join trialUser in _trialUserRoleRepository.Where(t => t.TrialId == inQuery.TrialId)
            //                                                                  .WhereIf(inQuery.UserId != null, t => t.UserRole.IdentityUserId == inQuery.UserId)
            //                                                                  .WhereIf(inQuery.UserTypeId != null, t => t.UserRole.UserTypeId == inQuery.UserTypeId)
            //                                    on trialDocumentNeedConfirmedUserType.NeedConfirmUserTypeId equals trialUser.UserRole.UserTypeId

            //                    join confirm in _trialDocConfirmedUserRepository.Where(t => t.TrialDocument.TrialId == inQuery.TrialId) on
            //                     new { trialUser.UserRole.IdentityUserId, TrialDocumentId = trialDocumentNeedConfirmedUserType.TrialDocumentId } equals new { IdentityUserId = confirm.ConfirmUserId, confirm.TrialDocumentId } into cc
            //                    from confirm in cc.DefaultIfEmpty()
            //                    select new UnionDocumentWithConfirmInfoView()
            //                    {
            //                        IsSystemDoc = false,

            //                        Id = trialDocumentNeedConfirmedUserType.TrialDocument.Id,
            //                        CreateTime = trialDocumentNeedConfirmedUserType.TrialDocument.CreateTime,
            //                        IsDeleted = trialDocumentNeedConfirmedUserType.TrialDocument.IsDeleted,
            //                        SignViewMinimumMinutes = trialDocumentNeedConfirmedUserType.TrialDocument.SignViewMinimumMinutes,
            //                        Name = trialDocumentNeedConfirmedUserType.TrialDocument.Name,
            //                        Path = trialDocumentNeedConfirmedUserType.TrialDocument.Path,
            //                        FileTypeId = trialDocumentNeedConfirmedUserType.TrialDocument.FileTypeId,
            //                        FileType = _userInfo.IsEn_Us ? trialDocumentNeedConfirmedUserType.TrialDocument.FileType.Value : trialDocumentNeedConfirmedUserType.TrialDocument.FileType.ValueCN,
            //                        UpdateTime = trialDocumentNeedConfirmedUserType.TrialDocument.UpdateTime,
            //                        //IsConfirmed= confirm.ConfirmTime!=null,



            //                        ConfirmUserId = confirm.ConfirmUserId,
            //                        ConfirmTime = confirm.ConfirmTime,
            //                        RealName = trialUser.UserRole.FullName,
            //                        UserName = trialUser.UserRole.IdentityUser.UserName,

            //                        //UserTypeId = trialUser.UserRole.UserTypeId,
            //                        //UserTypeShortName = trialUser.UserRole.UserTypeRole.UserTypeShortName,

            //                        FullFilePath = trialDocumentNeedConfirmedUserType.TrialDocument.Path
            //                    };



            //var systemDocQuery = from needConfirmEdUserType in _systemDocNeedConfirmedUserTypeRepository.WhereIf(trialInfo.TrialFinishedTime != null, u => u.SystemDocument.CreateTime < trialInfo.TrialFinishedTime)

            //                     join trialUser in _trialUserRoleRepository.Where(t => t.TrialId == inQuery.TrialId)
            //                                                           .WhereIf(inQuery.UserId != null, t => t.UserRole.IdentityUserId == inQuery.UserId)
            //                           on needConfirmEdUserType.NeedConfirmUserTypeId equals trialUser.UserRole.UserTypeId
            //                     join confirm in _systemDocConfirmedUserRepository.Where() on new { ConfirmUserId = trialUser.UserId, SystemDocumentId = needConfirmEdUserType.SystemDocumentId } equals new { confirm.ConfirmUserId, confirm.SystemDocumentId } into cc
            //                     from confirm in cc.DefaultIfEmpty()
            //                     select new UnionDocumentWithConfirmInfoView()
            //                     {
            //                         IsSystemDoc = true,

            //                         Id = needConfirmEdUserType.SystemDocument.Id,
            //                         CreateTime = needConfirmEdUserType.SystemDocument.CreateTime,
            //                         IsDeleted = needConfirmEdUserType.SystemDocument.IsDeleted,
            //                         SignViewMinimumMinutes = needConfirmEdUserType.SystemDocument.SignViewMinimumMinutes,
            //                         Name = needConfirmEdUserType.SystemDocument.Name,
            //                         Path = needConfirmEdUserType.SystemDocument.Path,
            //                         FileType = _userInfo.IsEn_Us ? needConfirmEdUserType.SystemDocument.FileType.Value : needConfirmEdUserType.SystemDocument.FileType.ValueCN,
            //                         FileTypeId = needConfirmEdUserType.SystemDocument.FileTypeId,
            //                         UpdateTime = needConfirmEdUserType.SystemDocument.UpdateTime,
            //                         //IsConfirmed = confirm.ConfirmTime != null,

            //                         ConfirmUserId = confirm.ConfirmUserId,
            //                         ConfirmTime = confirm.ConfirmTime,
            //                         RealName = trialUser.UserRole.FullName,
            //                         UserName = trialUser.UserRole.IdentityUser.UserName,

            //                         //UserTypeId = trialUser.UserRole.UserTypeId,
            //                         //UserTypeShortName = trialUser.UserRole.UserTypeRole.UserTypeShortName,

            //                         FullFilePath = needConfirmEdUserType.SystemDocument.Path
            //                     };

            //var unionQuery = trialDocQuery.Union(systemDocQuery).IgnoreQueryFilters().Where(t => !(t.IsDeleted == true && t.ConfirmUserId == null))
            //    .WhereIf(!string.IsNullOrEmpty(inQuery.Name), t => t.Name.Contains(inQuery.Name))
            //    .WhereIf(inQuery.FileTypeId != null, t => t.FileTypeId == inQuery.FileTypeId)
            //    .WhereIf(inQuery.IsConfirmed == true, t => t.ConfirmTime != null)
            //    .WhereIf(inQuery.IsConfirmed == false, t => t.ConfirmTime == null)
            //    .WhereIf(inQuery.IsDeleted != null, t => t.IsDeleted == inQuery.IsDeleted)
            //    /*.Distinct()*/;

            //var result = await unionQuery.ToPagedListAsync(inQuery);

            //var needSignTrialDocCount = await _trialDocumentRepository.AsQueryable(true)
            //        .Where(t => t.Trial.TrialIdentityUserList.Any(t => t.IdentityUserId == _userInfo.IdentityUserId))
            //        .Where(t => t.IsDeleted == false && !t.TrialDocConfirmedUserList.Any(t => t.ConfirmUserId == _userInfo.IdentityUserId) && t.NeedConfirmedUserTypeList.Any(u => u.NeedConfirmUserTypeId == _userInfo.UserTypeId))
            //        .CountAsync();


            //var needSignSystemDocCount = await _systemDocumentRepository
            //          .Where(t => t.IsDeleted == false && !t.SystemDocConfirmedUserList.Any(t => t.ConfirmUserId == _userInfo.IdentityUserId) && t.NeedConfirmedUserTypeList.Any(u => u.NeedConfirmUserTypeId == _userInfo.UserTypeId))
            //          .CountAsync();


            //return ResponseOutput.Ok(result, new { NeedSignCount = needSignTrialDocCount + needSignSystemDocCount, NeedSignTrialDocCount = needSignTrialDocCount, NeedSignSystemDocCount = needSignSystemDocCount, TrialStatusStr = trialInfo.TrialStatusStr });

            #endregion

        }

        /// <summary>
        /// 获取系统签署文档签署人下拉框
        /// </summary>
        /// <returns></returns>
        public async Task<IResponseOutput> GetSysDocSignUserList()
        {
            //EA 只能查看内部人员文档
            var isEA = _userInfo.UserTypeEnumInt == (int)UserTypeEnum.EA;

            //EA 但是没有在进行的培训记录查看权限，那么返回空数据
            if (isEA && !_auditRecordRepository.Any(t => t.IsViewTrainingRecord && t.AuditState == AuditState.Ongoing && t.AuditRecordIdentityUserList.Any(c => c.IdentityUserId == _userInfo.IdentityUserId)))
            {
                return ResponseOutput.Ok();
            }

            var list = _systemDocConfirmedUserRepository.Where(t => t.ConfirmTime != null)
                .WhereIf(isEA, t => t.ConfirmUser.IsZhiZhun == true)
                .Select(t => new { t.ConfirmUserId, t.ConfirmUser.UserName, t.ConfirmUser.FullName }).Distinct().ToList();

            return ResponseOutput.Ok(list);
        }

        [HttpPost]
        public async Task<IResponseOutput<PageOutput<UnionDocumentWithConfirmInfoView>>> GetSysDocumentConfirmList(SystemDocQuery inQuery)
        {

            var isInternal = _userInfo.IsZhiZhun;

            var isEA = _userInfo.UserTypeEnumInt == (int)UserTypeEnum.EA;

            //EA 但是没有在进行的培训记录查看权限，那么返回空数据
            if (isEA && !_auditRecordRepository.Any(t => t.IsViewTrainingRecord && t.AuditState == AuditState.Ongoing && t.AuditRecordIdentityUserList.Any(c => c.IdentityUserId == _userInfo.IdentityUserId)))
            {
                return ResponseOutput.Ok(new PageOutput<UnionDocumentWithConfirmInfoView>());
            }


            var systemDocQuery =
               from sysDoc in _systemDocumentRepository.Where(t => t.IsPublish)
                                              .Where(t => inQuery.UserTypeId != null ? t.NeedConfirmedUserTypeList.Any(t => t.NeedConfirmUserTypeId == inQuery.UserTypeId) : true)
               from identityUser in _identityUserRepository.AsQueryable(false)

                  .Where(t => t.Status == UserStateEnum.Enable && t.UserRoleList.Where(t => t.IsUserRoleDisabled == false).Any(t => sysDoc.NeedConfirmedUserTypeList.AsQueryable().Any(c => c.NeedConfirmUserTypeId == t.UserTypeId)))
                  .Where(t => inQuery.UserId != null ? t.Id == inQuery.UserId : true)
                  .Where(t => inQuery.UserTypeId != null ? t.UserRoleList.Any(t => t.UserTypeId == inQuery.UserTypeId && t.IsUserRoleDisabled == false) : true)
                  .Where(t => isEA ? t.IsZhiZhun == true : true) //EA 只能查看内部人员文档
               join confirm in _systemDocConfirmedUserRepository.Where() on new { ConfirmUserId = identityUser.Id, SystemDocumentId = sysDoc.Id } equals new { confirm.ConfirmUserId, confirm.SystemDocumentId } into cc
               from confirm in cc.DefaultIfEmpty()
               select new UnionDocumentWithConfirmInfoView()
               {
                   IsSystemDoc = true,
                   SysDocUserSignType = sysDoc.DocUserSignType,
                   IsConfirmIdentityUserInner = identityUser.IsZhiZhun,
                   IsPublish = sysDoc.IsPublish,
                   Id = sysDoc.Id,
                   CreateTime = sysDoc.CreateTime,
                   IsDeleted = sysDoc.IsDeleted,
                   SignViewMinimumMinutes = sysDoc.SignViewMinimumMinutes,
                   Name = sysDoc.Name,
                   Path = sysDoc.Path,
                   FileType = _userInfo.IsEn_Us ? sysDoc.FileType.Value : sysDoc.FileType.ValueCN,
                   FileTypeId = sysDoc.FileTypeId,
                   UpdateTime = sysDoc.UpdateTime,
                   //IsConfirmed = confirm.ConfirmTime != null,

                   ConfirmUserId = identityUser.Id,
                   ConfirmTime = confirm.ConfirmTime,

                   RealName = identityUser.FullName,
                   UserName = identityUser.UserName,

                   //UserTypeId = trialUser.UserRole.UserTypeId,
                   //UserTypeShortName = trialUser.UserRole.UserTypeRole.UserTypeShortName,

                   FullFilePath = sysDoc.Path,

                   AttachmentCount = sysDoc.SystemDocumentAttachmentList.Where(t => t.OffLine == false).Count(),

                   DocNeedSignUserTypeList = sysDoc.NeedConfirmedUserTypeList.Select(t => t.UserTypeRole.UserTypeShortName).ToList(),

                   IdentityUserTypeList = identityUser.UserRoleList.Where(t => t.IsUserRoleDisabled == false).Select(c => c.UserTypeRole.UserTypeShortName).ToList()

               };

            var unionQuery = systemDocQuery.IgnoreQueryFilters().Where(t => !(t.IsDeleted == true && t.ConfirmTime == null))
                            //外部人员 只签署 外部需要签署的    
                            .Where(t => t.IsConfirmIdentityUserInner == false ? t.SysDocUserSignType == DocUserSignType.InnerAndOuter : true)
                            .WhereIf(!string.IsNullOrEmpty(inQuery.Name), t => t.Name.Contains(inQuery.Name))
                            .WhereIf(inQuery.FileTypeId != null, t => t.FileTypeId == inQuery.FileTypeId)
                            .WhereIf(inQuery.IsConfirmed == true, t => t.ConfirmTime != null)
                            .WhereIf(inQuery.IsConfirmed == false, t => t.ConfirmTime == null)
                            .WhereIf(inQuery.StartConfirmTime != null, t => t.ConfirmTime >= inQuery.StartConfirmTime.Value)
                            .WhereIf(inQuery.EndConfirmTime != null, t => t.ConfirmTime <= inQuery.EndConfirmTime.Value)
                            .WhereIf(inQuery.BeginCreateTime != null, t => t.CreateTime >= inQuery.BeginCreateTime)
                            .WhereIf(inQuery.EndCreateTime != null, t => t.CreateTime <= inQuery.EndCreateTime)
                            .WhereIf(!string.IsNullOrEmpty(inQuery.UserName), t => t.UserName.Contains(inQuery.UserName))
                            .WhereIf(inQuery.IsDeleted != null, t => t.IsDeleted == inQuery.IsDeleted)
                            .WhereIf(isInternal == false, t => t.ConfirmTime != null); //不是内部的人，看有签名时间的

            var result = await unionQuery.ToPagedListAsync(inQuery);

            #region 处理文档 需要签署的角色类型  和每个人的角色信息

            //var trialDocIdList = result.CurrentPageData.Where(t => t.IsSystemDoc == false).Select(t => t.Id).ToList();

            //var sysDocIdList = result.CurrentPageData.Where(t => t.IsSystemDoc == true).Select(t => t.Id).ToList();

            //var identityUserIdList = result.CurrentPageData.Select(t => t.ConfirmUserId).Distinct().ToList();


            //var sysDocUserTypeList = _systemDocNeedConfirmedUserTypeRepository.Where(t => sysDocIdList.Contains(t.SystemDocumentId)).Select(t => new { t.SystemDocumentId, t.UserTypeRole.UserTypeShortName }).ToList();

            //var identityUserUserTypeList = _identityUserRepository.Where(t => identityUserIdList.Contains(t.Id)).IgnoreQueryFilters().Select(t => new { IdentityUserId = t.Id, UserTypeList = t.UserRoleList.Where(t => t.IsUserRoleDisabled == false).Select(c => c.UserTypeRole.UserTypeShortName).ToList() });

            ////Concat 不能用导航属性
            //var sysids = result.CurrentPageData.Where(t => t.IsSystemDoc == true).Select(t => t.Id).ToList();

            //var sysDataList = await _systemDocumentRepository.Where(x => sysids.Contains(x.Id)).Include(x => x.SystemDocumentAttachmentList).ToListAsync();

            //foreach (var item in result.CurrentPageData)
            //{

            //    if (sysDataList.Any(y => y.Id == item.Id))
            //    {
            //        item.AttachmentCount = sysDataList.Where(y => y.Id == item.Id).Select(x => x.SystemDocumentAttachmentList.Where(z => !z.OffLine).Count()).FirstOrDefault();
            //    }

            //    if (item.IsSystemDoc)
            //    {
            //        item.DocNeedSignUserTypeList = sysDocUserTypeList.Where(t => t.SystemDocumentId == item.Id).Select(t => t.UserTypeShortName).ToList();
            //    }


            //    item.IdentityUserTypeList = identityUserUserTypeList.Where(t => t.IdentityUserId == item.ConfirmUserId).SelectMany(c => c.UserTypeList).ToList();
            //}


            #endregion

            return ResponseOutput.Ok(result);
        }

        /// <summary>
        /// 项目下面的参与用户下拉
        /// </summary>
        /// <param name="trialId"></param>
        /// <returns></returns>
        [HttpGet("{trialId:guid}")]
        public async Task<List<TrialUserDto>> GetTrialUserSelect(Guid trialId)
        {
            return await _trialIdentityUserRepository.Where(t => t.TrialId == trialId)
                .Select(t => new TrialUserDto() { UserId = t.IdentityUserId, RealName = t.IdentityUser.FullName, UserName = t.IdentityUser.UserName })
                   .ToListAsync();
        }


        /// <summary>
        /// 项目+系统的文档类型 下拉
        /// </summary>
        /// <param name="trialId"></param>
        /// <returns></returns>
        [HttpGet("{trialId:guid}")]
        public async Task<IResponseOutput> GetTrialDocAndSystemDocType(Guid trialId)
        {
            var result = await _trialDocumentRepository.Where(t => t.TrialId == trialId).Select(t => new { FileType = _userInfo.IsEn_Us ? t.FileType.Value : t.FileType.ValueCN, t.FileTypeId })
                   .Union(_systemDocumentRepository.Select(t => new { FileType = _userInfo.IsEn_Us ? t.FileType.Value : t.FileType.ValueCN, t.FileTypeId }))
                   .ToListAsync();

            return ResponseOutput.Ok(result);
        }

        [TrialGlobalLimit("BeforeOngoingCantOpt", "AfterStopCannNotOpt")]
        //[Authorize(Policy = IRaCISPolicy.PM)]
        public async Task<IResponseOutput> AddOrUpdateTrialDocument(AddOrEditTrialDocument addOrEditTrialDocument)
        {
            if (addOrEditTrialDocument.Id == null)
            {
                var entity = _mapper.Map<TrialDocument>(addOrEditTrialDocument);


                if (await _trialDocumentRepository.AnyAsync(t => t.FileTypeId == addOrEditTrialDocument.FileTypeId && t.Name == addOrEditTrialDocument.Name && t.TrialId == addOrEditTrialDocument.TrialId, true))
                {
                    //---该项目中已经存在同类型的同名文件。
                    return ResponseOutput.NotOk(_localizer["TrialD_DuplicateFileInProject"]);
                }

                entity.IsDeleted = true;
                //entity.Id = NewId.NextGuid();
                await _trialDocumentRepository.AddAsync(entity, true);
                return ResponseOutput.Ok(entity.Id.ToString());
            }
            else
            {
                if (await _trialDocumentRepository.AnyAsync(t => t.FileTypeId == addOrEditTrialDocument.FileTypeId && t.Name == addOrEditTrialDocument.Name && t.Id != addOrEditTrialDocument.Id && t.TrialId == addOrEditTrialDocument.TrialId, true))
                {
                    //---该项目中已经存在同类型的同名文件。
                    return ResponseOutput.NotOk(_localizer["TrialD_DuplicateFileInProject"]);
                }

                var document = (await _trialDocumentRepository.Where(t => t.Id == addOrEditTrialDocument.Id, true, true).Include(t => t.NeedConfirmedUserTypeList).FirstOrDefaultAsync()).IfNullThrowException();

                bool beforeIsPublish = document.IsPublish;
                bool beforeIsDeleted = document.IsDeleted;
                var beforeUserTypeIds = document.NeedConfirmedUserTypeList.Select(x => x.NeedConfirmUserTypeId).ToList();

                _mapper.Map(addOrEditTrialDocument, document);
                document.UpdateTime = DateTime.Now;

                #region 不区分路径了

                //if (document.FileTypeId != addOrEditTrialDocument.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(), addOrEditTrialDocument.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 _trialDocumentRepository.SaveChangesAsync();
                // 检查是否需要发送邮件给新增的角色
                if (beforeIsPublish && document.IsPublish && !beforeIsDeleted && !document.IsDeleted)
                {
                    // 找出新增的用户角色ID
                    var newUserTypeIds = addOrEditTrialDocument.NeedConfirmedUserTypeIdList
                        .Where(id => !beforeUserTypeIds.Contains(id))
                        .ToList();

                    if (newUserTypeIds.Any() && newUserTypeIds.Count() > 0)
                    {
                        // 发送邮件给新增的角色
                        Console.WriteLine("开始 发送项目文档更新邮件给新增角色");
                        Console.WriteLine(string.Join(",", newUserTypeIds));

                        await _mediatorScoped.Publish(new TrialDocumentPublishEvent
                        {
                            Ids = new List<Guid> { document.Id },
                            NewUserTypeIds = newUserTypeIds
                        });

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


        /// <summary>
        /// 已签名的文档 不允许删除
        /// </summary>
        /// <param name="trialDocumentId"></param>
        /// <param name="trialId"></param>
        /// <returns></returns>
        [HttpDelete("{trialId:guid}/{trialDocumentId:guid}")]
        //[Authorize(Policy = IRaCISPolicy.PM)]
        [TrialGlobalLimit("BeforeOngoingCantOpt", "AfterStopCannNotOpt")]
        public async Task<IResponseOutput> DeleteTrialDocument(Guid trialDocumentId, Guid trialId)
        {
            if (await _trialDocumentRepository.AsQueryable(true).Where(t => t.Id == trialDocumentId).AnyAsync(t => t.TrialDocConfirmedUserList.Any()))
            {
                //---已有用户阅读该文档，并签名，不允许删除。
                return ResponseOutput.NotOk(_localizer["TrialD_DocumentHasAlready"]);
            }

            var success = await _trialDocumentRepository.BatchDeleteNoTrackingAsync(t => t.Id == trialDocumentId);

            return ResponseOutput.Result(success);
        }


        /// <summary>
        /// 浏览文档说明时调用，记录第一次看的时间
        /// </summary>
        /// <param name="documentId"></param>
        /// <param name="isSystemDoc"></param>
        /// <returns></returns>
        [HttpPut("{trialId:guid}/{documentId:guid}/{isSystemDoc:bool}")]
        [UnitOfWork]
        public async Task<IResponseOutput> SetFirstViewDocumentTime(Guid documentId, bool isSystemDoc)
        {

            var success = false;
            if (isSystemDoc)
            {
                if (!await _systemDocConfirmedUserRepository.AnyAsync(t => t.SystemDocumentId == documentId && t.ConfirmUserId == _userInfo.IdentityUserId))
                {
                    await _systemDocConfirmedUserRepository.AddAsync(new SystemDocConfirmedIdentityUser() { SystemDocumentId = documentId, ConfirmUserId = _userInfo.IdentityUserId, SignFirstViewTime = DateTime.Now });

                }

            }
            else
            {

                if (!await _trialDocConfirmedUserRepository.AnyAsync(t => t.TrialDocumentId == documentId && t.ConfirmUserId == _userInfo.IdentityUserId))
                {

                    await _trialDocConfirmedUserRepository.AddAsync(new TrialDocConfirmedIdentityUser() { TrialDocumentId = documentId, ConfirmUserId = _userInfo.IdentityUserId, SignFirstViewTime = DateTime.Now });

                }


            }

            success = await _systemDocConfirmedUserRepository.SaveChangesAsync();

            return ResponseOutput.Ok(success);
        }

        [HttpPut("{documentId:guid}")]
        public async Task<IResponseOutput> SetSystemDocFirstViewTime(Guid documentId)
        {
            if (!await _systemDocConfirmedUserRepository.AnyAsync(t => t.SystemDocumentId == documentId && t.ConfirmUserId == _userInfo.IdentityUserId))
            {
                await _systemDocConfirmedUserRepository.AddAsync(new SystemDocConfirmedIdentityUser() { SystemDocumentId = documentId, ConfirmUserId = _userInfo.IdentityUserId, SignFirstViewTime = DateTime.Now });

            }

            var success = await _systemDocConfirmedUserRepository.SaveChangesAsync();

            return ResponseOutput.Ok(success);
        }

        [HttpPut("{trialId:guid}/{documentId:guid}")]
        public async Task<IResponseOutput> SetTrialDocFirstViewTime(Guid documentId)
        {
            if (!await _trialDocConfirmedUserRepository.AnyAsync(t => t.TrialDocumentId == documentId && t.ConfirmUserId == _userInfo.IdentityUserId))
            {

                await _trialDocConfirmedUserRepository.AddAsync(new TrialDocConfirmedIdentityUser() { TrialDocumentId = documentId, ConfirmUserId = _userInfo.IdentityUserId, SignFirstViewTime = DateTime.Now });

            }
            var success = await _trialDocConfirmedUserRepository.SaveChangesAsync();

            return ResponseOutput.Ok(success);
        }

        /// <summary>
        /// 用户 签名某个文档   可能是系统的，也可能是项目的
        /// </summary>
        /// <returns></returns>
        [TrialGlobalLimit("BeforeOngoingCantOpt", "AfterStopCannNotOpt")]
        public async Task<IResponseOutput> UserConfirm(UserConfirmCommand userConfirmCommand)
        {

            if (userConfirmCommand.isSystemDoc)
            {

                var sysDocConfirm = await _systemDocConfirmedUserRepository.FirstOrDefaultAsync(t => t.SystemDocumentId == userConfirmCommand.DocumentId && t.ConfirmUserId == _userInfo.IdentityUserId, true);

                if (sysDocConfirm.ConfirmTime != null)
                {
                    //---该文件已经签名
                    return ResponseOutput.NotOk(_localizer["TrialD_FileAlreadySigned"]);
                }

                if (sysDocConfirm.IsDeleted)
                {
                    //---文件已废除,签署失败！
                    return ResponseOutput.NotOk(_localizer["TrialD_ObsoleteFile"]);
                }


                sysDocConfirm.ConfirmTime = DateTime.Now;
                sysDocConfirm.SignText = userConfirmCommand.SignText;



                await _systemDocConfirmedUserRepository.SaveChangesAsync();


            }
            else
            {

                var trialDocConfirm = await _trialDocConfirmedUserRepository.FirstOrDefaultAsync(t => t.TrialDocumentId == userConfirmCommand.DocumentId && t.ConfirmUserId == _userInfo.IdentityUserId, true);

                if (trialDocConfirm.ConfirmTime != null)
                {
                    //---该文件已经签名
                    return ResponseOutput.NotOk(_localizer["TrialD_FileAlreadySigned"]);
                }

                if (trialDocConfirm.IsDeleted)
                {
                    //---文件已废除,签署失败！
                    return ResponseOutput.NotOk(_localizer["TrialD_ObsoleteFile"]);
                }

                trialDocConfirm.ConfirmTime = DateTime.Now;
                trialDocConfirm.SignText = userConfirmCommand.SignText;

                await _trialDocConfirmedUserRepository.SaveChangesAsync();

            }


            return ResponseOutput.Ok();
        }


        /// <summary>
        /// 用户 废除某个文档
        /// </summary>
        /// <param name="documentId"></param>
        /// <param name="isSystemDoc"></param>
        /// <returns></returns>
        [HttpPut("{documentId:guid}/{isSystemDoc:bool}")]
        [TrialGlobalLimit("BeforeOngoingCantOpt", "AfterStopCannNotOpt", "SignSystemDocNoTrialId")]
        public async Task<IResponseOutput> UserAbandonDoc(Guid documentId, bool isSystemDoc)
        {
            if (isSystemDoc)
            {
                await _systemDocumentRepository.UpdatePartialFromQueryAsync(documentId, u => new SystemDocument() { IsDeleted = true });
                await _systemDocConfirmedUserRepository.UpdatePartialFromQueryAsync(x => x.SystemDocumentId == documentId, x => new SystemDocConfirmedIdentityUser()
                {
                    IsDeleted = true
                });
            }
            else
            {
                await _trialDocumentRepository.UpdatePartialFromQueryAsync(documentId, u => new TrialDocument() { IsDeleted = true });
                await _trialDocConfirmedUserRepository.UpdatePartialFromQueryAsync(x => x.TrialDocumentId == documentId, x => new TrialDocConfirmedIdentityUser()
                {
                    IsDeleted = true
                });
            }
            await _systemDocumentRepository.SaveChangesAsync();
            return ResponseOutput.Ok();
        }






    }
}
