using IRaCIS.Application.Contracts;
using IRaCIS.Application.Interfaces;
using IRaCIS.Core.API._ServiceExtensions.NewtonsoftJson;
using IRaCIS.Core.Application.Contracts;
using IRaCIS.Core.Application.Contracts.DTO;
using IRaCIS.Core.Application.ViewModel;
using IRaCIS.Core.Domain.Models;
using IRaCIS.Core.Domain.Share;
using IRaCIS.Core.Infra.EFCore.Common;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using NPOI.XSSF.UserModel;
using System.Globalization;
using static IRaCIS.Core.Application.Service.ExcelExportHelper;

namespace IRaCIS.Core.Application.Service.Common
{

    [ApiExplorerSettings(GroupName = "Common")]
    public class ExcelExportService(IRepository<TrialUser> _trialUserRepository,
        IRepository<VisitTask> _visitTaskRepository,
        IRepository<ReadingQuestionCriterionTrial> _readingQuestionCriterionTrialRepository,
        IRepository<SystemDocNeedConfirmedUserType> _systemDocNeedConfirmedUserTypeRepository,
        IRepository<DicomStudy> _dicomStudyRepository,
        IRepository<QCChallenge> _qcChallengeRepository,
        IRepository<ReadModule> _readModuleRepository,
        IRepository<NoneDicomStudy> _noneDicomStudyRepository,
        IRepository<StudyMonitor> _studyMonitorRepository,
        IRepository<CommonDocument> _commonDocumentRepository,
        IRepository<SystemDocConfirmedUser> _systemDocConfirmedUserRepository,
        IRepository<TrialDocNeedConfirmedUserType> _trialDocNeedConfirmedUserTypeRepository,
        IRepository<TrialDocConfirmedUser> _trialDocConfirmedUserRepository,
        IRepository<Subject> _subjectRepository, 
        IMapper _mapper, IUserInfo _userInfo, IStringLocalizer _localizer, IWebHostEnvironment _hostEnvironment) : BaseService
    {


        #region 后续需要移动过来



        /// <summary>
        /// 项目参与人员导出
        /// </summary>
        /// <param name="param"></param>
        /// <param name="_commonDocumentRepository"></param>
        /// <param name="_dictionaryService"></param>
        /// <param name="_trialRepository"></param>
        /// <param name="_trialUseRepository"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> TrialUserListExport(TrialMaintenanceExportQuery param,
            [FromServices] IRepository<CommonDocument> _commonDocumentRepository,
            [FromServices] IDictionaryService _dictionaryService,
            [FromServices] IRepository<Trial> _trialRepository,
            [FromServices] IRepository<TrialUser> _trialUseRepository

            )
        {


            var exportInfo = (await _trialRepository.Where(t => t.Id == param.TrialId).IgnoreQueryFilters().ProjectTo<ExcelExportInfo>(_mapper.ConfigurationProvider).FirstOrDefaultAsync()).IfNullThrowException();

            var list = await _trialUseRepository.Where(t => t.TrialId == param.TrialId).IgnoreQueryFilters()
                .WhereIf(param.UserTypeId != null, t => t.User.UserTypeId == param.UserTypeId)
                .WhereIf(!string.IsNullOrWhiteSpace(param.UserName), t => t.User.UserName.Contains(param.UserName))

                .WhereIf(param.IsDeleted != null, t => t.IsDeleted == param.IsDeleted)
                .WhereIf(!string.IsNullOrWhiteSpace(param.OrganizationName),
                    t => t.User.OrganizationName.Contains(param.OrganizationName))
                .WhereIf(!string.IsNullOrWhiteSpace(param.UserRealName),
                    t => (t.User.FullName).Contains(param.UserRealName))
                .ProjectTo<TrialMaintenanceDTO>(_mapper.ConfigurationProvider).ToListAsync();

            exportInfo.List = ExportExcelConverterDate.ConvertToClientTimeInObject(list, _userInfo.TimeZoneId);
            exportInfo.CurrentTime = ExportExcelConverterDate.DateTimeInternationalToString(DateTime.Now, _userInfo.TimeZoneId);



            return await ExcelExportHelper.DataExportAsync(StaticData.Export.TrialUserList_Export, exportInfo, exportInfo.TrialCode, _commonDocumentRepository, _hostEnvironment, _dictionaryService, typeof(TrialMaintenanceDTO));

        }

        /// <summary>
        /// Site用户列表导出
        /// </summary>
        /// <param name="param"></param>
        /// <param name="_commonDocumentRepository"></param>
        /// <param name="_dictionaryService"></param>
        /// <param name="_trialRepository"></param>
        /// <param name="_trialSiteUserRepository"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> TrialSiteUserListExport(SiteCRCExportQueryDTO param,
            [FromServices] IRepository<CommonDocument> _commonDocumentRepository,
            [FromServices] IDictionaryService _dictionaryService,
            [FromServices] IRepository<Trial> _trialRepository,
            [FromServices] IRepository<TrialSiteUser> _trialSiteUserRepository
            )
        {


            var exportInfo = (await _trialRepository.Where(t => t.Id == param.TrialId).IgnoreQueryFilters().ProjectTo<ExcelExportInfo>(_mapper.ConfigurationProvider).FirstOrDefaultAsync()).IfNullThrowException();

            var list = await _trialSiteUserRepository.Where(t => t.TrialId == param.TrialId).IgnoreQueryFilters()
                 .WhereIf(param.IsDeleted != null, t => t.IsDeleted == param.IsDeleted)
                 .WhereIf(!string.IsNullOrWhiteSpace(param.SiteName), t => t.TrialSite.TrialSiteName.Contains(param.SiteName) || t.TrialSite.TrialSiteAliasName.Contains(param.SiteName))
                 .WhereIf(!string.IsNullOrWhiteSpace(param.TrialSiteAliasName),
                     t => t.TrialSite.TrialSiteAliasName.Contains(param.TrialSiteAliasName))
                 .WhereIf(!string.IsNullOrWhiteSpace(param.TrialSiteCode),
                     t => t.TrialSite.TrialSiteCode.Contains(param.TrialSiteCode))
                 .WhereIf(_userInfo.UserTypeEnumInt == (int)UserTypeEnum.ClinicalResearchCoordinator,
                     t => t.UserId == _userInfo.Id)
                 .WhereIf(!string.IsNullOrWhiteSpace(param.UserKeyInfo), t => (t.User.FullName).Contains(param.UserKeyInfo)
                     || t.User.UserName.Contains(param.UserKeyInfo) || t.User.EMail.Contains(param.UserKeyInfo))

                 .ProjectTo<SiteUserExportDTO>(_mapper.ConfigurationProvider).ToListAsync();

            exportInfo.List = ExportExcelConverterDate.ConvertToClientTimeInObject(list, _userInfo.TimeZoneId);
            exportInfo.CurrentTime = ExportExcelConverterDate.DateTimeInternationalToString(DateTime.Now, _userInfo.TimeZoneId);




            return await ExcelExportHelper.DataExportAsync(StaticData.Export.TrialSiteUserList_Export, exportInfo, exportInfo.TrialCode, _commonDocumentRepository, _hostEnvironment, _dictionaryService, typeof(SiteUserExportDTO));

        }

        /// <summary>
        /// Site用户汇总表导出
        /// </summary>
        /// <param name="queryParam"></param>
        /// <param name="_commonDocumentRepository"></param>
        /// <param name="_trialSiteSurveyRepository"></param>
        /// <param name="_trialSiteUserSurveyRepository"></param>
        /// <param name="_trialRepository"></param>
        /// <param name="_dictionaryService"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> TrialSiteUserSummaryListExport(TrialSiteUserSurveyExportQueryDto queryParam,
            [FromServices] IRepository<CommonDocument> _commonDocumentRepository,
            [FromServices] IRepository<TrialSiteSurvey> _trialSiteSurveyRepository,
            [FromServices] IRepository<TrialSiteUserSurvey> _trialSiteUserSurveyRepository,
            [FromServices] IRepository<Trial> _trialRepository,
            [FromServices] IDictionaryService _dictionaryService
        )
        {

            var data = (await _trialRepository.Where(t => t.Id == queryParam.TrialId).IgnoreQueryFilters().ProjectTo<ExcelExportInfo>(_mapper.ConfigurationProvider).FirstOrDefaultAsync()).IfNullThrowException();

            var groupSelectIdQuery =
                _trialSiteSurveyRepository.Where(t => t.TrialId == queryParam.TrialId)
                    .WhereIf(queryParam.TrialSiteId != null, t => t.TrialSiteId == queryParam.TrialSiteId)
                    .WhereIf(!string.IsNullOrEmpty(queryParam.FormWriterKeyInfo), t => (t.UserName).Contains(queryParam.FormWriterKeyInfo) || t.Email.Contains(queryParam.FormWriterKeyInfo) || t.Phone.Contains(queryParam.FormWriterKeyInfo))
                    .GroupBy(t => t.TrialSiteId)
                    .Select(g => g.OrderByDescending(u => u.CreateTime).Select(t => t.Id).First());


            var query = _trialSiteUserSurveyRepository
                .Where(t => groupSelectIdQuery.Contains(t.TrialSiteSurveyId))
                .WhereIf(queryParam.UserTypeId != null, t => t.UserTypeId == queryParam.UserTypeId)
                .WhereIf(queryParam.IsGenerateAccount != null, t => t.IsGenerateAccount == queryParam.IsGenerateAccount)
                .WhereIf(queryParam.State != null && queryParam.State != TrialSiteUserStateEnum.OverTime, t => t.InviteState == queryParam.State)
                .WhereIf(!string.IsNullOrEmpty(queryParam.UserName), t => (t.LastName + " / " + t.FirstName).Contains(queryParam.UserName))
                .WhereIf(!string.IsNullOrEmpty(queryParam.OrganizationName), t => t.OrganizationName.Contains(queryParam.OrganizationName))
                .ProjectTo<TrialSiteUserSummaryDto>(_mapper.ConfigurationProvider);

            var list = await query.ToListAsync();
            data.List = ExportExcelConverterDate.ConvertToClientTimeInObject(list, _userInfo.TimeZoneId);

            var exportInfo = data;

            exportInfo.CurrentTime = ExportExcelConverterDate.DateTimeInternationalToString(DateTime.Now, _userInfo.TimeZoneId);


            return await ExcelExportHelper.DataExportAsync(StaticData.Export.TrialSiteUserSummary_Export, exportInfo, exportInfo.TrialCode, _commonDocumentRepository, _hostEnvironment, _dictionaryService, typeof(TrialSiteUserSummaryDto));

        }


        /// <summary>
        /// 项目列表导出---new
        /// </summary>
        /// <param name="inQuery"></param>
        /// <param name="_commonDocumentRepository"></param>
        /// <param name="_dictionaryService"></param>
        /// <param name="_trialRepository"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> GetTrialList_Export(TrialToBeDoneQuery inQuery,
          [FromServices] IRepository<CommonDocument> _commonDocumentRepository,
          [FromServices] IDictionaryService _dictionaryService,
          [FromServices] IRepository<Trial> _trialRepository
          )
        {
            var isPM = _userInfo.UserTypeEnumInt == (int)UserTypeEnum.ProjectManager || _userInfo.UserTypeEnumInt == (int)UserTypeEnum.APM;
            var isCRC = _userInfo.UserTypeEnumInt == (int)UserTypeEnum.ClinicalResearchCoordinator;
            var isIQC = _userInfo.UserTypeEnumInt == (int)UserTypeEnum.IQC;
            var isMIM = _userInfo.UserTypeEnumInt == (int)UserTypeEnum.MIM;
            var isSPMOrCPM = _userInfo.UserTypeEnumInt == (int)UserTypeEnum.SPM || _userInfo.UserTypeEnumInt == (int)UserTypeEnum.CPM;
            var isIR = _userInfo.UserTypeEnumInt == (int)UserTypeEnum.IndependentReviewer;


            var query = _trialRepository.AsQueryable()
             .WhereIf(inQuery.TrialIdList.Count() > 0, o => inQuery.TrialIdList.Contains(o.Id))

             .WhereIf(inQuery.SponsorId != null, o => o.SponsorId == inQuery.SponsorId)
             .WhereIf(!string.IsNullOrEmpty(inQuery.Code), o => o.TrialCode.Contains(inQuery.Code))
             .WhereIf(!string.IsNullOrEmpty(inQuery.ResearchProgramNo), o => o.ResearchProgramNo.Contains(inQuery.ResearchProgramNo))
             .WhereIf(!string.IsNullOrWhiteSpace(inQuery.ExperimentName), o => o.ExperimentName.Contains(inQuery.ExperimentName))
             .WhereIf(_userInfo.UserTypeEnumInt != (int)UserTypeEnum.SuperAdmin && _userInfo.UserTypeEnumInt != (int)UserTypeEnum.Admin && _userInfo.UserTypeEnumInt != (int)UserTypeEnum.OP, t => t.TrialUserList.Any(t => t.UserId == _userInfo.Id && t.IsDeleted == false) && t.IsDeleted == false)
             .WhereIf(inQuery.CriterionType != null, o => o.TrialReadingCriterionList.Any(t => t.CriterionType == inQuery.CriterionType && t.IsSigned && t.IsConfirm))
             .WhereIf(!string.IsNullOrEmpty(inQuery.PM_EMail), o => o.TrialUserList.Any(t => t.User.EMail.Contains(inQuery.PM_EMail) && (t.User.UserTypeEnum == UserTypeEnum.ProjectManager || t.User.UserTypeEnum == UserTypeEnum.APM)))
             .Select(t => new TrialToBeDoneDto()
             {
                 TrialId = t.Id,
                 ResearchProgramNo = t.ResearchProgramNo,
                 ExperimentName = t.ExperimentName,
                 TrialCode = t.TrialCode,
                 CreateTime = t.CreateTime,
                 Sponsor = _userInfo.IsEn_Us ? t.Sponsor.SponsorName : t.Sponsor.SponsorNameCN,
                 TrialStatusStr = t.TrialStatusStr,

                 ExpetiedTaskCount = isPM ? t.VisitTaskList.Where(t => t.IsUrgent).Count() : 0,

                 ReReadingApprovalCount = isPM ? t.VisitTaskReReadingList.Where(t => t.OriginalReReadingTask.ReReadingApplyState == ReReadingApplyState.DocotorHaveApplyed).Count() : 0,

                 PendingReconciliationCount = isPM ? t.SubjectVisitList.Where(t => t.CheckState == CheckStateEnum.ToCheck).Count() : 0,

                 PendingResponseCount = isPM ? t.SubjectVisitList.Where(u => u.CheckState == CheckStateEnum.CVIng &&
                    u.CheckChallengeDialogList.OrderByDescending(t => t.CreateTime).First().UserTypeEnum == UserTypeEnum.ClinicalResearchCoordinator).Count() : 0,


                 SPM_ReReadingApprovalCount = isSPMOrCPM ? t.VisitTaskReReadingList.Where(t => t.OriginalReReadingTask.ReReadingApplyState == ReReadingApplyState.TrialGroupHaveApplyed).Count() : 0,

                 SPM_ReviewerSelectApprovalCount = isSPMOrCPM ? t.EnrollList.Where(u => u.EnrollStatus == EnrollStatus.HasCommittedToCRO).Count() : 0,

                 MIM_UrgentCount = isMIM ? t.TaskMedicalReviewList.Where(t => t.IsClosedDialog == false && t.VisitTask.TaskState == TaskState.Effect && t.IsInvalid == false && t.MedicalManagerUserId == _userInfo.Id)
                 .Where(u => u.VisitTask.IsUrgent &&
                    u.AuditState != MedicalReviewAuditState.HaveSigned).Count() : 0,

                 MIM_PendingResponseCount = isMIM ? t.TaskMedicalReviewList.Where(t => t.IsClosedDialog == false && t.VisitTask.TaskState == TaskState.Effect && t.IsInvalid == false && t.MedicalManagerUserId == _userInfo.Id)
                 .Where(u => u.LatestReplyUser.UserTypeEnum == UserTypeEnum.IndependentReviewer && u.AuditState == MedicalReviewAuditState.Auditing).Count() : 0,

                 MIM_PendingReviewCount = isMIM ? t.TaskMedicalReviewList.Where(t => t.IsClosedDialog == false && t.VisitTask.TaskState == TaskState.Effect && t.IsInvalid == false && t.MedicalManagerUserId == _userInfo.Id)
                 .Where(u => u.AuditState != MedicalReviewAuditState.HaveSigned && u.LatestReplyUser.UserTypeEnum != UserTypeEnum.IndependentReviewer).Count() : 0,

                 CRC_UrgentCount = isCRC ? t.SubjectVisitList.Where(c => c.TrialSite.CRCUserList.Any(u => u.UserId == _userInfo.Id) && t.IsUrgent).Count() : 0,

                 CRC_CheckQuestionCount = isCRC ? t.SubjectVisitList.Where(c => c.TrialSite.CRCUserList.Any(u => u.UserId == _userInfo.Id))
                .Where(u => u.CheckState == CheckStateEnum.CVIng && u.CheckChallengeState == CheckChanllengeTypeEnum.PMWaitCRCReply).Count() : 0,

                 CRC_QCQuestionCount = isCRC ? t.SubjectVisitList.Where(c => c.TrialSite.CRCUserList.Any(u => u.UserId == _userInfo.Id)).SelectMany(c => c.QCChallengeList)
                .Where(u => u.IsClosed == false && (u.LatestReplyUser.UserTypeEnum == UserTypeEnum.IQC || u.LatestReplyUserId == null)).Count() : 0,


                 //待审核 审核中  加急的数量
                 IQC_UrgentCount = isIQC ? t.SubjectVisitList.Where(u => u.CurrentActionUserId == _userInfo.Id && t.QCProcessEnum != TrialQCProcess.NotAudit && t.IsUrgent).Count() : 0,

                 //审核未完成
                 IQC_AuditToBeDealedCount = isIQC ? t.SubjectVisitList.Where(u => u.CurrentActionUserId == _userInfo.Id && t.QCProcessEnum != TrialQCProcess.NotAudit).Count() : 0,

                 //质疑待处理
                 IQC_QuestionToBeDealedCount = isIQC ? t.SubjectVisitList.SelectMany(c => c.QCChallengeList)
                .Where(u => u.CreateUserId == _userInfo.Id && u.IsClosed == false && u.LatestReplyUser.UserTypeEnum == UserTypeEnum.ClinicalResearchCoordinator).Count() : 0,

                 //待领取
                 IQC_ToBeClaimedCount = isIQC ? t.SubjectVisitList.Where(t => t.SubmitState == SubmitStateEnum.Submitted && t.AuditState != AuditStateEnum.QCPassed)
                    .Where(u => u.CurrentActionUserId == null && (u.PreliminaryAuditUserId == null || (u.PreliminaryAuditUserId != _userInfo.Id && u.ReviewAuditUserId == null))).Count() : 0,


                 IR_ReadingCriterionList = isIR ? t.TrialReadingCriterionList.Where(t => t.IsConfirm && t.IsSigned).OrderBy(t => t.CriterionName).Select(t => t.CriterionName).ToList() : null,

                 IR_PMEmailList = isIR ? t.TrialUserList.Where(t => t.User.UserTypeEnum == UserTypeEnum.ProjectManager || t.User.UserTypeEnum == UserTypeEnum.APM).OrderBy(t => t.User.EMail).Select(t => t.User.EMail).ToList() : null,

                 IR_TotalReadCount = isIR ? t.VisitTaskList.Where(t => t.DoctorUserId == _userInfo.Id && t.TaskState == TaskState.Effect && t.ReadingTaskState == ReadingTaskState.HaveSigned).Count() : 0,


                 IR_UnReadCount = isIR ? t.VisitTaskList
                   .Where(c => c.DoctorUserId == _userInfo.Id && c.ReadingTaskState != ReadingTaskState.HaveSigned && c.TaskState == TaskState.Effect && c.TrialReadingCriterion.IsSigned)
                   // 前序 不存在 未一致性核查未通过的
                   .Where(t => !t.Subject.SubjectVisitList.Any(sv => sv.CheckState != CheckStateEnum.CVPassed && t.VisitTaskNum > sv.VisitNum))
                   //前序 不存在  未生成任务的访视
                   .Where(t => t.TrialReadingCriterion.IsAutoCreate == false ? !t.Subject.SubjectCriteriaEvaluationVisitFilterList.Where(d => d.TrialReadingCriterionId == t.TrialReadingCriterionId).Any(f => f.IsGeneratedTask == false && t.VisitTaskNum > f.SubjectVisit.VisitNum) : true)

                   .Where(y => y.IsFrontTaskNeedSignButNotSign == false && (y.IsNeedClinicalDataSign == false || y.IsClinicalDataSign == true)).Count() : 0,

                 IR_UrgentCount = isIR ? t.VisitTaskList.Where(t => t.SourceSubjectVisit.IsUrgent).Count() : 0,

             });


            var list = query.ToList();

            var exportInfo = new ExcelExportInfo();

            exportInfo.List = ExportExcelConverterDate.ConvertToClientTimeInObject(list, _userInfo.TimeZoneId);
            exportInfo.CurrentTime = ExportExcelConverterDate.DateTimeInternationalToString(DateTime.Now, _userInfo.TimeZoneId);



            return await ExcelExportHelper.DataExportAsync(StaticData.Export.TrialList_Export, exportInfo, exportInfo.TrialCode, _commonDocumentRepository, _hostEnvironment, _dictionaryService, typeof(TrialToBeDoneDto));

        }


        #endregion





        #region 导表查询

        /// <summary>
        /// getDocumentConfirmList  培训记录导出--new
        /// </summary>
        /// <param name="inQuery"></param>
        /// <param name="_commonDocumentRepository"></param>
        /// <param name="_dictionaryService"></param>
        /// <param name="_subjectVisitRepository"></param>
        /// <param name="_trialRepository"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> PMTrainingRecordList_Export(DocumentTrialUnionQuery inQuery,
            [FromServices] IRepository<CommonDocument> _commonDocumentRepository,
            [FromServices] IDictionaryService _dictionaryService,
            [FromServices] IRepository<SubjectVisit> _subjectVisitRepository,
            [FromServices] IRepository<Trial> _trialRepository
            )
        {
            var trialInfo = (await _trialRepository.Where(t => t.Id == inQuery.TrialId).Select(t => new { t.TrialFinishedTime, t.TrialStatusStr }).FirstNotNullAsync());

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

                                join confirm in _trialDocConfirmedUserRepository.Where(t => t.TrialDocument.TrialId == inQuery.TrialId) on
                                 new { trialUser.UserId, TrialDocumentId = trialDocumentNeedConfirmedUserType.TrialDocumentId } equals new { UserId = confirm.ConfirmUserId, confirm.TrialDocumentId } into cc
                                from confirm in cc.DefaultIfEmpty()
                                select new TrainingRecordExportDTO()
                                {
                                    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.User.FullName,
                                    UserName = trialUser.User.UserName,
                                    UserTypeId = trialUser.User.UserTypeId,
                                    UserTypeShortName = trialUser.User.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 _trialUserRepository.Where(t => t.TrialId == inQuery.TrialId)
                                                                       .WhereIf(inQuery.UserId != null, t => t.UserId == inQuery.UserId)
                                       on needConfirmEdUserType.NeedConfirmUserTypeId equals trialUser.User.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 TrainingRecordExportDTO()
                                 {
                                     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.User.FullName,
                                     UserName = trialUser.User.UserName,
                                     UserTypeId = trialUser.User.UserTypeId,
                                     UserTypeShortName = trialUser.User.UserTypeRole.UserTypeShortName,

                                     //FullFilePath = needConfirmEdUserType.SystemDocument.Path
                                 };

            var unionQuery = trialDocQuery.Union(systemDocQuery)
                .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)
                .WhereIf(inQuery.UserTypeId != null, t => t.UserTypeId == inQuery.UserTypeId);

            var list = await unionQuery.ToListAsync();


            var exportInfo = (await _trialRepository.Where(t => t.Id == inQuery.TrialId).IgnoreQueryFilters().ProjectTo<ExcelExportInfo>(_mapper.ConfigurationProvider).FirstOrDefaultAsync()).IfNullThrowException();

            exportInfo.List = list;
            exportInfo.CurrentTime = ExportExcelConverterDate.DateTimeInternationalToString(DateTime.Now, _userInfo.TimeZoneId);
            exportInfo.List = ExportExcelConverterDate.ConvertToClientTimeInObject(list, _userInfo.TimeZoneId);



            return await ExcelExportHelper.DataExportAsync(StaticData.Export.TrialTrainingRecordList_Export, exportInfo, $"{exportInfo.ResearchProgramNo}", _commonDocumentRepository, _hostEnvironment, _dictionaryService, typeof(TrainingRecordExportDTO));

        }







        /// <summary>
        /// 影像上传列表    只导出已上传状态的访视记录
        /// </summary>
        /// <param name="inQuery"></param>
        /// <param name="_commonDocumentRepository"></param>
        /// <param name="_dictionaryService"></param>
        /// <param name="_subjectVisitRepository"></param>
        /// <param name="_trialRepository"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> CRCVisitList_Export(CRCVisitSearchDTO inQuery,
            [FromServices] IRepository<CommonDocument> _commonDocumentRepository,
            [FromServices] IDictionaryService _dictionaryService,
            [FromServices] IRepository<SubjectVisit> _subjectVisitRepository,
            [FromServices] IRepository<Trial> _trialRepository
            )
        {

            var svExpression = QCCommon.GetSubjectVisitFilter(inQuery.VisitPlanArray);

            var query = _subjectVisitRepository.Where(x => x.TrialId == inQuery.TrialId)
                       .Where(t => t.Subject.FinalSubjectVisitId != null ? t.VisitNum <= t.Subject.FinalSubjectVisit.VisitNum : true)
                       .WhereIf(inQuery.TrialSiteId != null, t => t.TrialSiteId == inQuery.TrialSiteId)
                       .WhereIf(inQuery.SubjectId != null, t => t.Subject.Id == inQuery.SubjectId)
                       .WhereIf(!string.IsNullOrEmpty(inQuery.SubjectInfo), t => t.Subject.Code.Contains(inQuery.SubjectInfo))

                       .WhereIf(inQuery.VisitPlanArray != null && inQuery.VisitPlanArray?.Length > 0, svExpression)
                       //.WhereIf(!string.IsNullOrEmpty(visitSearchDTO.VisitPlanInfo), visitSearchDTO.VisitPlanInfo.Contains('.') ? t => t.InPlan == false : t => t.VisitNum == decimal.Parse(visitSearchDTO.VisitPlanInfo))
                       .WhereIf(inQuery.AuditStateArray != null && inQuery.AuditStateArray?.Length > 0, t => inQuery.AuditStateArray!.Contains(t.AuditState))
                       .WhereIf(inQuery.SubmitState != null, t => t.SubmitState == inQuery.SubmitState)
                       .WhereIf(inQuery.ChallengeState != null, t => t.ChallengeState == inQuery.ChallengeState)
                       .WhereIf(inQuery.IsUrgent != null, t => t.IsUrgent == inQuery.IsUrgent)
                       .WhereIf(_userInfo.UserTypeEnumInt == (int)UserTypeEnum.ClinicalResearchCoordinator || _userInfo.UserTypeEnumInt == (int)UserTypeEnum.CRA, t => t.TrialSite.CRCUserList.Any(t => t.UserId == _userInfo.Id))
                       .ProjectTo<CRCVisitExportDTO>(_mapper.ConfigurationProvider);

            var list = query.OrderBy(t => t.TrialSiteCode).ThenBy(t => t.SubjectCode).ThenBy(t => t.BlindName).ToList();

            var exportInfo = (await _trialRepository.Where(t => t.Id == inQuery.TrialId).IgnoreQueryFilters().ProjectTo<ExcelExportInfo>(_mapper.ConfigurationProvider).FirstOrDefaultAsync()).IfNullThrowException();

            exportInfo.List = ExportExcelConverterDate.ConvertToClientTimeInObject(list, _userInfo.TimeZoneId);
            exportInfo.CurrentTime = ExportExcelConverterDate.DateTimeInternationalToString(DateTime.Now, _userInfo.TimeZoneId);



            return await ExcelExportHelper.DataExportAsync(StaticData.Export.TrialCRCUploadImageList_Export, exportInfo, $"{exportInfo.ResearchProgramNo}", _commonDocumentRepository, _hostEnvironment, _dictionaryService, typeof(CRCVisitExportDTO));

        }

        /// <summary>
        /// 影像质控导出---new
        /// </summary>
        /// <param name="inQuery"></param>
        /// <param name="_commonDocumentRepository"></param>
        /// <param name="_dictionaryService"></param>
        /// <param name="_subjectVisitRepository"></param>
        /// <param name="_trialRepository"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> QCVisitList_Export(QCVisitSearchDTO inQuery,
         [FromServices] IRepository<CommonDocument> _commonDocumentRepository,
         [FromServices] IDictionaryService _dictionaryService,
         [FromServices] IRepository<SubjectVisit> _subjectVisitRepository,
         [FromServices] IRepository<Trial> _trialRepository
         )
        {
            var svExpression = QCCommon.GetSubjectVisitFilter(inQuery.VisitPlanArray);
            var query = _subjectVisitRepository.Where(x => x.TrialId == inQuery.TrialId)
                         .WhereIf(inQuery.VisitId != null, t => t.Id == inQuery.VisitId)
                        .WhereIf(inQuery.CurrentActionUserId != null, t => t.CurrentActionUserId == inQuery.CurrentActionUserId)
                        .WhereIf(inQuery.ChallengeState != null, t => t.ChallengeState == inQuery.ChallengeState)
                        .WhereIf(inQuery.TrialSiteId != null, t => t.TrialSiteId == inQuery.TrialSiteId)
                        .WhereIf(inQuery.SubjectId != null, t => t.Subject.Id == inQuery.SubjectId)
                        .WhereIf(!string.IsNullOrEmpty(inQuery.SubjectInfo), t => /*t.Subject.FirstName.Contains(subjectInfo) || t.Subject.LastName.Contains(subjectInfo) ||*/ t.Subject.Code.Contains(inQuery.SubjectInfo))
                        .WhereIf(inQuery.VisitPlanArray != null && inQuery.VisitPlanArray?.Length > 0, svExpression)
                        //.WhereIf(!string.IsNullOrEmpty(visitSearchDTO.VisitPlanInfo), visitSearchDTO.VisitPlanInfo.Contains('.') ? t => t.VisitNum.ToString().Contains(".") : t => t.VisitNum == decimal.Parse(visitSearchDTO.VisitPlanInfo))
                        //.WhereIf(visitSearchDTO.AuditState != null, t => t.AuditState == visitSearchDTO.AuditState)
                        .WhereIf(inQuery.AuditStateArray != null && inQuery.AuditStateArray?.Length > 0, t => inQuery.AuditStateArray!.Contains(t.AuditState))

                        .WhereIf(inQuery.HandleUserId != null, t => t.PreliminaryAuditUserId == inQuery.HandleUserId || t.CurrentActionUserId == inQuery.HandleUserId
                        || t.ReviewAuditUserId == inQuery.HandleUserId
                        || t.QCChallengeList.Any(t => t.CreateUserId == inQuery.HandleUserId)
                        || t.QCChallengeDialogList.Any(t => t.CreateUserId == inQuery.HandleUserId))
                        .WhereIf(inQuery.IsUrgent != null, t => t.IsUrgent == inQuery.IsUrgent)
                        .Where(t => t.SubmitState != SubmitStateEnum.None)
                        .WhereIf(inQuery.BeginAuditTime != null, t => t.Trial.QCProcessEnum == TrialQCProcess.SingleAudit ? t.PreliminaryAuditTime >= inQuery.BeginAuditTime :
                        (t.Trial.QCProcessEnum == TrialQCProcess.DoubleAudit ? t.ReviewAuditTime >= inQuery.BeginAuditTime : true))

                         .WhereIf(inQuery.EndAuditTime != null, t => t.Trial.QCProcessEnum == TrialQCProcess.SingleAudit ? t.PreliminaryAuditTime <= inQuery.EndAuditTime :
                        (t.Trial.QCProcessEnum == TrialQCProcess.DoubleAudit ? t.ReviewAuditTime <= inQuery.EndAuditTime : true))

                        .ProjectTo<QCVisitExportDTO>(_mapper.ConfigurationProvider);


            var list = query.ToList();

            var exportInfo = (await _trialRepository.Where(t => t.Id == inQuery.TrialId).IgnoreQueryFilters().ProjectTo<ExcelExportInfo>(_mapper.ConfigurationProvider).FirstOrDefaultAsync()).IfNullThrowException();

            exportInfo.List = ExportExcelConverterDate.ConvertToClientTimeInObject(list, _userInfo.TimeZoneId);
            exportInfo.CurrentTime = ExportExcelConverterDate.DateTimeInternationalToString(DateTime.Now, _userInfo.TimeZoneId);



            return await ExcelExportHelper.DataExportAsync(StaticData.Export.TrialQCVisitImageList_Export, exportInfo, $"{exportInfo.ResearchProgramNo}", _commonDocumentRepository, _hostEnvironment, _dictionaryService, typeof(CRCVisitExportDTO));

        }


        /// <summary>
        ///  质疑列表   
        /// </summary>
        /// <param name="inQuery"></param>
        /// <param name="_commonDocumentRepository"></param>
        /// <param name="_dictionaryService"></param>
        /// <param name="_trialRepository"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> GetQCChallengeList_Export(ChallengeQuery inQuery,
             [FromServices] IRepository<CommonDocument> _commonDocumentRepository,
            [FromServices] IDictionaryService _dictionaryService,
            [FromServices] IRepository<Trial> _trialRepository
            )

        {
            var svExpression = QCCommon.GetQCChallengeFilter(inQuery.VisitPlanArray);

            var query = _qcChallengeRepository.Where(x => x.TrialId == inQuery.TrialId)
                //.WhereIf(challengeQuery.ChallengeState != null, t => t.SubjectVisit.ChallengeState == challengeQuery.ChallengeState)
                .WhereIf(inQuery.ReuploadEnum != null, t => t.ReuploadEnum == inQuery.ReuploadEnum)
                .WhereIf(inQuery.IsClosed != null, t => t.IsClosed == inQuery.IsClosed)
                .WhereIf(inQuery.TrialSiteId != null, t => t.SubjectVisit.TrialSiteId == inQuery.TrialSiteId)
                .WhereIf(inQuery.SubjectId != null, t => t.SubjectVisit.SubjectId == inQuery.SubjectId)
                .WhereIf(inQuery.CreateUserId != null, t => t.CreateUserId == inQuery.CreateUserId)
                .WhereIf(inQuery.SubjectCode != null, t => t.SubjectVisit.Subject.Code.Contains(inQuery.SubjectCode!))
                .WhereIf(inQuery.VisitPlanArray != null && inQuery.VisitPlanArray?.Length > 0, svExpression)
                 //.WhereIf(!string.IsNullOrEmpty(challengeQuery.VisitPlanInfo), challengeQuery.VisitPlanInfo.Contains('.') ? t => t.SubjectVisit.VisitNum.ToString().Contains(".") : t => t.SubjectVisit.VisitNum == decimal.Parse(challengeQuery.VisitPlanInfo))
                 .WhereIf(inQuery.IsOverTime != null && inQuery.IsOverTime == true, t => t.IsClosed ? t.ClosedTime > t.DeadlineTime : DateTime.Now > t.DeadlineTime)
                .WhereIf(inQuery.IsOverTime != null && inQuery.IsOverTime == false, t => t.IsClosed ? t.ClosedTime < t.DeadlineTime : DateTime.Now < t.DeadlineTime)
                .WhereIf(inQuery.IsUrgent != null, t => t.SubjectVisit.IsUrgent == inQuery.IsUrgent)
                .WhereIf(_userInfo.UserTypeEnumInt == (int)UserTypeEnum.ClinicalResearchCoordinator || _userInfo.UserTypeEnumInt == (int)UserTypeEnum.CRA, t => t.SubjectVisit.TrialSite.CRCUserList.Any(t => t.UserId == _userInfo.Id))

                .ProjectTo<QCChanllengeExportDto>(_mapper.ConfigurationProvider);

            var list = query.OrderBy(t => t.TrialSiteCode).ThenBy(t => t.SubjectCode).ThenBy(t => t.ChallengeCode).ToList();

            var exportInfo = (await _trialRepository.Where(t => t.Id == inQuery.TrialId).IgnoreQueryFilters().ProjectTo<ExcelExportInfo>(_mapper.ConfigurationProvider).FirstOrDefaultAsync()).IfNullThrowException();

            exportInfo.List = ExportExcelConverterDate.ConvertToClientTimeInObject(list, _userInfo.TimeZoneId);
            exportInfo.CurrentTime = ExportExcelConverterDate.DateTimeInternationalToString(DateTime.Now, _userInfo.TimeZoneId);


            return await ExcelExportHelper.DataExportAsync(StaticData.Export.TrialQCImageChanllengeList_Export, exportInfo, $"{exportInfo.ResearchProgramNo}", _commonDocumentRepository, _hostEnvironment, _dictionaryService, typeof(QCChanllengeExportDto));
        }


        /// <summary>
        /// 受试者信息导出表
        /// </summary>
        /// <param name="inQuery"></param>
        /// <param name="_commonDocumentRepository"></param>
        /// <param name="_subjectRepository"></param>
        /// <param name="_dictionaryService"></param>
        /// <param name="_trialRepository"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> GetSubjectList_Export(SubjectQueryParam inQuery,
                [FromServices] IRepository<CommonDocument> _commonDocumentRepository,
                [FromServices] IRepository<Subject> _subjectRepository,
                [FromServices] IDictionaryService _dictionaryService,
                 [FromServices] IRepository<Trial> _trialRepository)
        {

            var subjectQuery = _subjectRepository.Where(u => u.TrialId == inQuery.TrialId)
                  .WhereIf(!string.IsNullOrWhiteSpace(inQuery.Code), t => t.Code.Contains(inQuery.Code))
                  .WhereIf(!string.IsNullOrWhiteSpace(inQuery.Name), t => t.ShortName.Contains(inQuery.Name))
                  .WhereIf(!string.IsNullOrWhiteSpace(inQuery.Sex), t => t.Sex.Contains(inQuery.Sex))
                  .WhereIf(inQuery.Status != null, t => t.Status == inQuery.Status)

                  .WhereIf(inQuery.TrialSiteId != null, t => t.TrialSiteId == inQuery.TrialSiteId)
                  // CRC  只负责他管理site的受试者
                  .WhereIf(_userInfo.UserTypeEnumInt == (int)UserTypeEnum.ClinicalResearchCoordinator || _userInfo.UserTypeEnumInt == (int)UserTypeEnum.CRA, t => t.TrialSite.CRCUserList.Any(t => t.UserId == _userInfo.Id))
                 .ProjectTo<SubjectExportDTO>(_mapper.ConfigurationProvider)
                   .WhereIf(inQuery.IsMissingImages == true, t => t.MissingSubmmitCount > 0)
                  .WhereIf(inQuery.IsMissingImages == false, t => t.MissingSubmmitCount == 0)
                 ;


            var list = subjectQuery.OrderBy(t => t.TrialSiteCode).ThenBy(t => t.Code).ToList();

            var exportInfo = (await _trialRepository.Where(t => t.Id == inQuery.TrialId).IgnoreQueryFilters().ProjectTo<ExcelExportInfo>(_mapper.ConfigurationProvider).FirstOrDefaultAsync()).IfNullThrowException();

            exportInfo.List = ExportExcelConverterDate.ConvertToClientTimeInObject(list, _userInfo.TimeZoneId);
            exportInfo.CurrentTime = ExportExcelConverterDate.DateTimeInternationalToString(DateTime.Now, _userInfo.TimeZoneId);


            return await ExcelExportHelper.DataExportAsync(StaticData.Export.TrialSubjectList_Export, exportInfo, $"{exportInfo.ResearchProgramNo}", _commonDocumentRepository, _hostEnvironment, _dictionaryService, typeof(SubjectExportDTO));

        }





        /// <summary>
        /// Subject 进展表 --new
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="_commonDocumentRepository"></param>
        /// <param name="_dictionaryService"></param>
        /// <param name="_trialRepository"></param>
        /// <returns></returns>

        [HttpPost]
        public async Task<IActionResult> GetSubjectProgress_Export(SubjectProgressQuery dto,
        [FromServices] IRepository<CommonDocument> _commonDocumentRepository,
        [FromServices] IDictionaryService _dictionaryService,
         [FromServices] IRepository<Trial> _trialRepository)
        {


            var query = from subject in _subjectRepository.Where(u => u.TrialId == dto.TrialId)
                        join trialReadingCriterion in _readingQuestionCriterionTrialRepository.Where(u => u.TrialId == dto.TrialId && u.IsConfirm && u.Id == dto.TrialReadingCriterionId) on subject.TrialId equals trialReadingCriterion.TrialId

                        select new SubjectProgressDto()
                        {
                            TrialSiteCode = subject.TrialSite.TrialSiteCode,
                            SubjectCode = subject.Code,
                            SubjectStatus = subject.Status,


                            VisitList = subject.SubjectVisitList.Where(t => t.VisitExecuted != VisitExecutedEnum.Unavailable).Select(t => new SubjectProgressDto.MouduleProgress()
                            {
                                TaskName = t.VisitName,
                                VisitTaskNum = t.VisitNum,
                                Inplan = t.InPlan,
                                IsFinalVisit = t.IsFinalVisit,
                                IsLostVisit = t.IsLostVisit,
                                ReadingStatus =
                                t.VisitTaskList.Where(t => t.TaskState == TaskState.Effect && t.TrialReadingCriterionId == dto.TrialReadingCriterionId && t.TaskAllocationState == TaskAllocationState.Allocated && t.IsAnalysisCreate == false && t.ReadingCategory == ReadingCategory.Visit && t.ReadingTaskState == ReadingTaskState.HaveSigned).Count() == (int)trialReadingCriterion.ReadingType ?
                                ReadingStatusEnum.ReadCompleted : t.VisitTaskList.Where(t => t.TaskState == TaskState.Effect && t.TrialReadingCriterionId == dto.TrialReadingCriterionId && t.IsAnalysisCreate == false && t.ReadingCategory == ReadingCategory.Visit && t.TaskAllocationState == TaskAllocationState.Allocated).Count() == (int)trialReadingCriterion.ReadingType ? ReadingStatusEnum.ImageReading :
                                t.ReadingStatus
                            }).ToList(),

                            ModuleList = subject.ReadModuleList.Where(t => t.TrialReadingCriterionId == dto.TrialReadingCriterionId).Select(t => new SubjectProgressDto.MouduleProgress()
                            {
                                TaskName = t.ModuleName,
                                VisitTaskNum = (t.ReadingSetType == ReadingSetType.ImageReading ? ReadingCommon.TaskNumDic[ReadingCategory.Global] : ReadingCommon.TaskNumDic[ReadingCategory.Oncology]) + t.SubjectVisit.VisitNum,
                                ReadingSetType = t.ReadingSetType,
                                ReadingStatus = t.ModuleTaskList.Where(t => t.TaskState == TaskState.Effect && t.IsAnalysisCreate == false && (t.ReadingCategory == ReadingCategory.Oncology || t.ReadingCategory == ReadingCategory.Global) && t.ReadingTaskState == ReadingTaskState.HaveSigned).Count() == (int)trialReadingCriterion.ReadingType ?
                                 ReadingStatusEnum.ReadCompleted : t.ModuleTaskList.Where(t => t.TaskState == TaskState.Effect && t.IsAnalysisCreate == false && (t.ReadingCategory == ReadingCategory.Oncology || t.ReadingCategory == ReadingCategory.Global) && t.TaskAllocationState == TaskAllocationState.Allocated).Count() == (int)trialReadingCriterion.ReadingType ?
                                 ReadingStatusEnum.ImageReading : t.ReadingStatus
                            }).ToList()


                        }
               ;


            var list = query.ToList();
            //.ProjectTo<SubjectProgressDto>(_mapper.ConfigurationProvider).ToListAsync();



            var exportInfo = (await _trialRepository.Where(t => t.Id == dto.TrialId).IgnoreQueryFilters().ProjectTo<ExcelExportInfo>(_mapper.ConfigurationProvider).FirstOrDefaultAsync()).IfNullThrowException();

            exportInfo.CriterionName = await _readingQuestionCriterionTrialRepository.Where(u => u.TrialId == dto.TrialId && u.IsConfirm && u.Id == dto.TrialReadingCriterionId).Select(t => t.CriterionName).FirstOrDefaultAsync();

            exportInfo.List = ExportExcelConverterDate.ConvertToClientTimeInObject(list, _userInfo.TimeZoneId);
            exportInfo.CurrentTime = ExportExcelConverterDate.DateTimeInternationalToString(DateTime.Now, _userInfo.TimeZoneId);


            var (memoryStream, fileName) = await ExcelExportHelper.DataExport_NpoiTestAsync(StaticData.Export.TrialSubjectProgressList_Export, exportInfo, /*"", */_commonDocumentRepository, _hostEnvironment, _dictionaryService, typeof(SubjectProgressDto));


            // 使用NPOI  进行二次处理

            var wb = new XSSFWorkbook(memoryStream);

            var sheet = wb.GetSheetAt(0);

            foreach (var subject in list)
            {
                var index = list.IndexOf(subject);
                var row = sheet.GetRow(index + 4);


                foreach (var item in subject.TotalList)
                {
                    //从第五列开始动态写
                    var visitIndex = subject.TotalList.IndexOf(item) + 4;

                    var cell = row.CreateCell(visitIndex);

                    if (item.IsLostVisit == true)
                    {
                        cell.CellStyle = sheet.GetRow(1).GetCell(7).CellStyle;
                    }
                    else
                    {
                        switch (item.ReadingStatus)
                        {
                            case ReadingStatusEnum.ImageNotSubmit:

                                cell.CellStyle = sheet.GetRow(1).GetCell(1).CellStyle;

                                break;
                            case ReadingStatusEnum.ImageQuality:
                                cell.CellStyle = sheet.GetRow(1).GetCell(2).CellStyle;
                                break;
                            case ReadingStatusEnum.ConsistencyCheck:
                                cell.CellStyle = sheet.GetRow(1).GetCell(3).CellStyle;
                                break;
                            case ReadingStatusEnum.TaskAllocate:
                                cell.CellStyle = sheet.GetRow(1).GetCell(4).CellStyle;
                                break;
                            case ReadingStatusEnum.ImageReading:
                                cell.CellStyle = sheet.GetRow(1).GetCell(5).CellStyle;
                                break;
                            case ReadingStatusEnum.ReadCompleted:
                                cell.CellStyle = sheet.GetRow(1).GetCell(6).CellStyle;
                                break;

                            default:
                                break;
                        }
                    }



                    cell.SetCellValue(item.TaskName);
                }
            }

            var memoryStream2 = new MemoryStream();
            wb.Write(memoryStream2, true);
            memoryStream2.Seek(0, SeekOrigin.Begin);

            return new FileStreamResult(memoryStream2, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
            {
                FileDownloadName = $"{exportInfo.ResearchProgramNo}_{exportInfo.CriterionName}_{fileName}_{DateTime.Now.ToString("yyyyMMddHHmmss")}.xlsx"
            };

        }


        /// <summary>
        /// 影像上传监控表
        /// </summary>
        /// <param name="inQuery"></param>
        /// <param name="_commonDocumentRepository"></param>
        /// <param name="_dictionaryService"></param>
        /// <param name="_trialRepository"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> GetStudyUploadMonitor_Export(StudyQuery inQuery,
        [FromServices] IRepository<CommonDocument> _commonDocumentRepository,
        [FromServices] IDictionaryService _dictionaryService,
         [FromServices] IRepository<Trial> _trialRepository)
        {

            var svExpression = QCCommon.GetStudyMonitorSubjectVisitFilter(inQuery.VisitPlanArray);
            var StudyMonitorQuery = _studyMonitorRepository.Where(t => t.TrialId == inQuery.TrialId, ignoreQueryFilters: true)
                 .WhereIf(_userInfo.UserTypeEnumInt == (int)UserTypeEnum.ClinicalResearchCoordinator || _userInfo.UserTypeEnumInt == (int)UserTypeEnum.CRA, t => t.Subject.TrialSite.CRCUserList.Any(t => t.UserId == _userInfo.Id))
                  //.WhereIf(!string.IsNullOrEmpty(studyQuery.VisitPlanInfo), studyQuery.VisitPlanInfo.Contains('.') ? t => t.SubjectVisit.VisitNum.ToString().Contains(".") : t => t.SubjectVisit.VisitNum == decimal.Parse(studyQuery.VisitPlanInfo))
                  .WhereIf(inQuery.VisitPlanArray != null && inQuery.VisitPlanArray?.Length > 0, svExpression)
                 .WhereIf(!string.IsNullOrWhiteSpace(inQuery.SubjectInfo), t => t.Subject.Code.Contains(inQuery.SubjectInfo))
                 .WhereIf(inQuery.SubjectId != null, t => t.SubjectId == inQuery.SubjectId)
                 .WhereIf(inQuery.SubjectVisitId != null, t => t.SubjectId == inQuery.SubjectVisitId)
                 .WhereIf(inQuery.TrialSiteId != null, t => t.Subject.TrialSiteId == inQuery.TrialSiteId)
                 .WhereIf(inQuery.IsDicom != null, t => t.IsDicom == inQuery.IsDicom)
                 .WhereIf(!string.IsNullOrWhiteSpace(inQuery.Uploader), t => t.CreateUser.UserName.Contains(inQuery.Uploader))
                 .WhereIf(inQuery.IsSuccess != null, t => t.IsSuccess == inQuery.IsSuccess)
                 .WhereIf(!string.IsNullOrWhiteSpace(inQuery.StudyCode), t => t.StudyCode.Contains(inQuery.StudyCode))
                 .Select(t => new UnionStudyMonitorExportDto()
                 {
                     TrialSiteCode = t.Subject.TrialSite.TrialSiteCode,
                     TrialSiteAliasName = t.Subject.TrialSite.TrialSiteAliasName,

                     SubjectCode = t.Subject.Code,


                     VisitName = t.SubjectVisit.VisitName,

                     StudyCode = t.StudyCode,

                     IsDicom = t.IsDicom,

                     Uploader = t.CreateUser.UserName,

                     IP = t.IP,

                     UploadStartTime = t.UploadStartTime,

                     UploadFinishedTime = t.UploadFinishedTime,

                     ArchiveFinishedTime = t.ArchiveFinishedTime,


                     UploadTime = t.CreateTime,

                     FileCount = t.FileCount,
                     FileSize = t.FileSize,

                     IsDicomReUpload = t.IsDicomReUpload,

                     IsSuccess = t.IsSuccess,
                     Note = t.Note,
                 });

            var list = await StudyMonitorQuery.ToListAsync();

            var exportInfo = (await _trialRepository.Where(t => t.Id == inQuery.TrialId).IgnoreQueryFilters().ProjectTo<ExcelExportInfo>(_mapper.ConfigurationProvider).FirstOrDefaultAsync()).IfNullThrowException();

            exportInfo.List = ExportExcelConverterDate.ConvertToClientTimeInObject(list, _userInfo.TimeZoneId);
            exportInfo.CurrentTime = ExportExcelConverterDate.DateTimeInternationalToString(DateTime.Now, _userInfo.TimeZoneId);



            return await ExcelExportHelper.DataExportAsync(StaticData.Export.TrialStudyUploadMonitor_Export, exportInfo, $"{exportInfo.ResearchProgramNo}", _commonDocumentRepository, _hostEnvironment, _dictionaryService, typeof(UnionStudyMonitorExportDto));


        }





        /// <summary>
        /// 阅片期信息表
        /// </summary>
        /// <param name="param"></param>
        /// <param name="_commonDocumentRepository"></param>
        /// <param name="_dictionaryService"></param>
        /// <param name="_trialRepository"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> GetReadingPeriodList_Export(ReadPeriodQuery param,
                [FromServices] IRepository<CommonDocument> _commonDocumentRepository,
                [FromServices] IDictionaryService _dictionaryService,
                 [FromServices] IRepository<Trial> _trialRepository)
        {

            var list = await _readModuleRepository.Where(u => u.TrialId == param.TrialId)

                  .ProjectTo<ReadPeriodExportDto>(_mapper.ConfigurationProvider).ToListAsync();

            list = list.OrderBy(t => t.TrialSiteCode).ThenBy(t => t.SubjectCode).ToList();

            var exportInfo = (await _trialRepository.Where(t => t.Id == param.TrialId).IgnoreQueryFilters().ProjectTo<ExcelExportInfo>(_mapper.ConfigurationProvider).FirstOrDefaultAsync()).IfNullThrowException();

            exportInfo.List = ExportExcelConverterDate.ConvertToClientTimeInObject(list, _userInfo.TimeZoneId);
            exportInfo.CurrentTime = ExportExcelConverterDate.DateTimeInternationalToString(DateTime.Now, _userInfo.TimeZoneId);


            return await ExcelExportHelper.DataExportAsync(StaticData.Export.TrialSubjectReadingPeriodList_Export, exportInfo, $"{exportInfo.ResearchProgramNo}", _commonDocumentRepository, _hostEnvironment, _dictionaryService, typeof(ReadPeriodExportDto));

        }

        /// <summary>
        /// 一致性核查  检查信息表
        /// </summary>
        /// <param name="studyQuery"></param>
        /// <param name="_commonDocumentRepository"></param>
        /// <param name="_dictionaryService"></param>
        /// <param name="_trialRepository"></param>
        /// <returns></returns>

        [HttpPost]
        public async Task<IActionResult> GetDicomAndNoneDicomStudyList_Export(StudyQuery studyQuery,
                [FromServices] IRepository<CommonDocument> _commonDocumentRepository,
                [FromServices] IDictionaryService _dictionaryService,
                 [FromServices] IRepository<Trial> _trialRepository)
        {

            var svExpression = QCCommon.GetDicomStudySubjectVisitFilter(studyQuery.VisitPlanArray);

            var dicomStudyQuery = _dicomStudyRepository.Where(t => t.TrialId == studyQuery.TrialId)
                    .WhereIf(_userInfo.UserTypeEnumInt == (int)UserTypeEnum.ClinicalResearchCoordinator || _userInfo.UserTypeEnumInt == (int)UserTypeEnum.CRA, t => t.Subject.TrialSite.CRCUserList.Any(t => t.UserId == _userInfo.Id))
                    .WhereIf(studyQuery.VisitPlanArray != null && studyQuery.VisitPlanArray?.Length > 0, svExpression)
                    .WhereIf(!string.IsNullOrWhiteSpace(studyQuery.SubjectInfo), t => t.Subject.Code.Contains(studyQuery.SubjectInfo))
                    .Where(x => x.SubjectVisit.AuditState == AuditStateEnum.QCPassed)
                    .Select(t => new UnionStudyExportDTO()
                    {
                        VisitName = t.SubjectVisit.VisitName,
                        VisitNum = t.SubjectVisit.VisitNum,
                        IsDicom = true,
                        SubjectCode = t.Subject.Code,
                        Modality = t.Modalities,
                        StudyCode = t.StudyCode,
                        StudyTime = t.StudyTime,

                        TrialSiteAliasName = t.Subject.TrialSite.TrialSiteAliasName,

                        TrialSiteCode = t.Subject.TrialSite.TrialSiteCode,

                        CheckState = t.SubjectVisit.CheckState,
                        //Uploader = t.Uploader.UserName,
                        //UploadTime = t.CreateTime

                    });

            var svExpression2 = QCCommon.GetNoneDicomStudySubjectVisitFilter(studyQuery.VisitPlanArray);


            var nodeDicomStudyQuery = _noneDicomStudyRepository.Where(t => t.TrialId == studyQuery.TrialId)
                .WhereIf(_userInfo.UserTypeEnumInt == (int)UserTypeEnum.ClinicalResearchCoordinator || _userInfo.UserTypeEnumInt == (int)UserTypeEnum.CRA, t => t.Subject.TrialSite.CRCUserList.Any(t => t.UserId == _userInfo.Id))
                 .WhereIf(studyQuery.VisitPlanArray != null && studyQuery.VisitPlanArray?.Length > 0, svExpression2)
                 .WhereIf(!string.IsNullOrWhiteSpace(studyQuery.SubjectInfo), t => t.Subject.Code.Contains(studyQuery.SubjectInfo))
                 .Where(x => x.SubjectVisit.AuditState == AuditStateEnum.QCPassed)
                 .Select(t => new UnionStudyExportDTO()
                 {

                     VisitName = t.SubjectVisit.VisitName,
                     VisitNum = t.SubjectVisit.VisitNum,
                     IsDicom = false,
                     SubjectCode = t.Subject.Code,
                     Modality = t.Modality,
                     StudyCode = t.StudyCode,
                     StudyTime = t.ImageDate,

                     TrialSiteAliasName = t.Subject.TrialSite.TrialSiteAliasName,

                     TrialSiteCode = t.Subject.TrialSite.TrialSiteCode,

                     CheckState = t.SubjectVisit.CheckState,

                     //Uploader = t.CreateUser.UserName,
                     //UploadTime = t.CreateTime

                 });



            var list = await dicomStudyQuery.Union(nodeDicomStudyQuery)
              .ToListAsync();

            list = list.OrderBy(t => t.TrialSiteCode).ThenBy(t => t.SubjectCode).ThenBy(t => t.VisitNum).ToList();

            var exportInfo = (await _trialRepository.Where(t => t.Id == studyQuery.TrialId).IgnoreQueryFilters().ProjectTo<ExcelExportInfo>(_mapper.ConfigurationProvider).FirstOrDefaultAsync()).IfNullThrowException();

            exportInfo.List = ExportExcelConverterDate.ConvertToClientTimeInObject(list, _userInfo.TimeZoneId);
            exportInfo.CurrentTime = ExportExcelConverterDate.DateTimeInternationalToString(DateTime.Now, _userInfo.TimeZoneId);


            return await ExcelExportHelper.DataExportAsync(StaticData.Export.TrialStudyList_Export, exportInfo, $"{exportInfo.ResearchProgramNo}", _commonDocumentRepository, _hostEnvironment, _dictionaryService, typeof(UnionStudyExportDTO));
        }


        /// <summary>
        /// 一致性核查记录表  
        /// </summary>
        /// <param name="inQuery"></param>
        /// <param name="_commonDocumentRepository"></param>
        /// <param name="_dictionaryService"></param>
        /// <param name="_trialRepository"></param>
        /// <param name="_subjectVisitRepository"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> GetConsistencyVerificationList_Export(CheckQuery inQuery,
                [FromServices] IRepository<CommonDocument> _commonDocumentRepository,
                [FromServices] IDictionaryService _dictionaryService,
                [FromServices] IRepository<Trial> _trialRepository,
                 [FromServices] IRepository<SubjectVisit> _subjectVisitRepository)
        {

            var svExpression = QCCommon.GetSubjectVisitFilter(inQuery.VisitPlanArray);

            var query = _subjectVisitRepository.Where(x => x.TrialId == inQuery.TrialId)
                        .Where(x => x.AuditState == AuditStateEnum.QCPassed) //一致性核查中的，或者还没一致性核查的                                                                                                                 
                        .WhereIf(inQuery.CheckState != null, t => t.CheckState == inQuery.CheckState)
                        .WhereIf(inQuery.TrialSiteId != null, t => t.TrialSiteId == inQuery.TrialSiteId)
                        .WhereIf(!string.IsNullOrEmpty(inQuery.SubjectInfo), t => t.Subject.Code.Contains(inQuery.SubjectInfo))
                        .WhereIf(inQuery.VisitPlanArray != null && inQuery.VisitPlanArray?.Length > 0, svExpression)
                        //.WhereIf(!string.IsNullOrEmpty(checkQuery.VisitPlanInfo), checkQuery.VisitPlanInfo.Contains('.') ? t => t.InPlan == false : t => t.VisitNum == decimal.Parse(checkQuery.VisitPlanInfo))
                        .WhereIf(_userInfo.UserTypeEnumInt == (int)UserTypeEnum.ClinicalResearchCoordinator || _userInfo.UserTypeEnumInt == (int)UserTypeEnum.CRA, t => t.TrialSite.CRCUserList.Any(t => t.UserId == _userInfo.Id))//CRC 过滤负责的site
                        .ProjectTo<PMKCheckEXportDTO>(_mapper.ConfigurationProvider);

            var list = query.OrderBy(t => t.TrialSiteCode).ThenBy(t => t.SubjectCode).ThenBy(t => t.VisitNum).ToList();

            var exportInfo = (await _trialRepository.Where(t => t.Id == inQuery.TrialId).IgnoreQueryFilters().ProjectTo<ExcelExportInfo>(_mapper.ConfigurationProvider).FirstOrDefaultAsync()).IfNullThrowException();

            exportInfo.List = ExportExcelConverterDate.ConvertToClientTimeInObject(list, _userInfo.TimeZoneId);
            exportInfo.CurrentTime = ExportExcelConverterDate.DateTimeInternationalToString(DateTime.Now, _userInfo.TimeZoneId);


            return await ExcelExportHelper.DataExportAsync(StaticData.Export.TrialSubjectVisitCheckList_Export, exportInfo, $"{exportInfo.ResearchProgramNo}", _commonDocumentRepository, _hostEnvironment, _dictionaryService, typeof(PMKCheckEXportDTO));
        }




        /// <summary>
        /// PM阅片跟踪
        /// </summary>
        /// <param name="inQuery"></param>
        /// <param name="_commonDocumentRepository"></param>
        /// <param name="_dictionaryService"></param>
        /// <param name="_trialRepository"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> GetReadingTaskList_Export(VisitTaskQuery inQuery,
                [FromServices] IRepository<CommonDocument> _commonDocumentRepository,
                [FromServices] IDictionaryService _dictionaryService,
                [FromServices] IRepository<Trial> _trialRepository)
        {
            var list = await _visitTaskRepository.Where(t => t.TrialId == inQuery.TrialId && t.IsAnalysisCreate == false)
               //.Where(t => t.IsAnalysisCreate == false && t.DoctorUserId != null)

               .WhereIf(inQuery.TaskState != null, t => t.TaskState == inQuery.TaskState)
               .WhereIf(inQuery.ArmEnum != null, t => t.ArmEnum == inQuery.ArmEnum)
               .WhereIf(inQuery.TrialSiteId != null, t => t.Subject.TrialSiteId == inQuery.TrialSiteId)
               .WhereIf(inQuery.SubjectId != null, t => t.SubjectId == inQuery.SubjectId)
               .WhereIf(inQuery.IsUrgent != null, t => t.IsUrgent == inQuery.IsUrgent)
               .WhereIf(inQuery.DoctorUserId != null, t => t.DoctorUserId == inQuery.DoctorUserId)
               .WhereIf(inQuery.ReadingCategory != null, t => t.ReadingCategory == inQuery.ReadingCategory)
               .WhereIf(inQuery.ReadingTaskState != null, t => t.ReadingTaskState == inQuery.ReadingTaskState)
               .WhereIf(inQuery.TaskAllocationState != null, t => t.TaskAllocationState == inQuery.TaskAllocationState)
               .WhereIf(inQuery.TrialReadingCriterionId != null, t => t.TrialReadingCriterionId == inQuery.TrialReadingCriterionId)


               .WhereIf(!string.IsNullOrEmpty(inQuery.TrialSiteCode), t => (t.BlindTrialSiteCode.Contains(inQuery.TrialSiteCode!) && t.IsAnalysisCreate) || (t.Subject.TrialSite.TrialSiteCode.Contains(inQuery.TrialSiteCode!) && t.IsAnalysisCreate == false))
               .WhereIf(!string.IsNullOrEmpty(inQuery.TaskName), t => t.TaskName.Contains(inQuery.TaskName) || t.TaskBlindName.Contains(inQuery.TaskName))
               .WhereIf(!string.IsNullOrEmpty(inQuery.SubjectCode), t => t.Subject.Code.Contains(inQuery.SubjectCode) || t.BlindSubjectCode.Contains(inQuery.SubjectCode))
               .WhereIf(inQuery.BeginAllocateDate != null, t => t.AllocateTime > inQuery.BeginAllocateDate)
               .WhereIf(inQuery.EndAllocateDate != null, t => t.AllocateTime < inQuery.EndAllocateDate!.Value.AddDays(1))
               .ProjectTo<ReadingTaskExportDto>(_mapper.ConfigurationProvider).ToListAsync();

            //var defalutSortArray = new string[] { nameof(VisitTask.IsUrgent) + " desc", nameof(VisitTask.SubjectId), nameof(VisitTask.VisitTaskNum) };

            list = list.OrderBy(t => t.TrialSiteCode).ThenBy(t => t.SubjectCode).ThenBy(t => t.VisitTaskNum).ToList();


            var exportInfo = (await _trialRepository.Where(t => t.Id == inQuery.TrialId).IgnoreQueryFilters().ProjectTo<ExcelExportInfo>(_mapper.ConfigurationProvider).FirstOrDefaultAsync()).IfNullThrowException();

            exportInfo.List = ExportExcelConverterDate.ConvertToClientTimeInObject(list, _userInfo.TimeZoneId);
            exportInfo.CurrentTime = ExportExcelConverterDate.DateTimeInternationalToString(DateTime.Now, _userInfo.TimeZoneId);


            return await ExcelExportHelper.DataExportAsync(StaticData.Export.TrialReadingTaskList_Export, exportInfo, $"{exportInfo.ResearchProgramNo}", _commonDocumentRepository, _hostEnvironment, _dictionaryService, typeof(ReadingTaskExportDto));
        }




        /// <summary>
        /// PM 重阅追踪 
        /// </summary>
        /// <param name="inQuery"></param>
        /// <param name="_commonDocumentRepository"></param>
        /// <param name="_visitTaskReReadingRepository"></param>
        /// <param name="_dictionaryService"></param>
        /// <param name="_trialRepository"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> GetReReadingTaskList_Export(VisitTaskQuery inQuery,
                [FromServices] IRepository<CommonDocument> _commonDocumentRepository,
                 [FromServices] IRepository<VisitTaskReReading> _visitTaskReReadingRepository,
                [FromServices] IDictionaryService _dictionaryService,
                [FromServices] IRepository<Trial> _trialRepository)
        {


            var visitTaskQueryable = _visitTaskReReadingRepository
                  .Where(t => t.OriginalReReadingTask.TrialId == inQuery.TrialId /*&& t.OriginalReReadingTask.IsAnalysisCreate == false*/)
                  .WhereIf(inQuery.RootReReadingTaskId != null, t => t.RootReReadingTaskId == inQuery.RootReReadingTaskId || t.OriginalReReadingTaskId == inQuery.RootReReadingTaskId)
                  .WhereIf(!string.IsNullOrEmpty(inQuery.TaskCode), t => t.OriginalReReadingTask.TaskCode.Contains(inQuery.TaskCode!) || t.RootReReadingTask.TaskCode.Contains(inQuery.TaskCode!))
                  .WhereIf(inQuery.TrialSiteId != null, t => t.OriginalReReadingTask.Subject.TrialSiteId == inQuery.TrialSiteId)
                  .WhereIf(inQuery.TaskState != null, t => t.OriginalReReadingTask.TaskState == inQuery.TaskState)
                  .WhereIf(inQuery.ReReadingApplyState != null, t => t.OriginalReReadingTask.ReReadingApplyState == inQuery.ReReadingApplyState)
                   .WhereIf(inQuery.RequestReReadingType != null, t => t.RequestReReadingType == inQuery.RequestReReadingType)
                  .WhereIf(inQuery.SubjectId != null, t => t.OriginalReReadingTask.SubjectId == inQuery.SubjectId)
                  .WhereIf(inQuery.IsUrgent != null, t => t.OriginalReReadingTask.IsUrgent == inQuery.IsUrgent)
                  .WhereIf(inQuery.DoctorUserId != null, t => t.OriginalReReadingTask.DoctorUserId == inQuery.DoctorUserId)
                  .WhereIf(inQuery.ArmEnum != null, t => t.OriginalReReadingTask.ArmEnum == inQuery.ArmEnum)
                  .WhereIf(inQuery.ReadingTaskState != null, t => t.OriginalReReadingTask.ReadingTaskState == inQuery.ReadingTaskState)
                  .WhereIf(inQuery.TaskAllocationState != null, t => t.OriginalReReadingTask.TaskAllocationState == inQuery.TaskAllocationState)
                  .WhereIf(inQuery.TrialReadingCriterionId != null, t => t.OriginalReReadingTask.TrialReadingCriterionId == inQuery.TrialReadingCriterionId)
                  .WhereIf(inQuery.ReadingCategory != null, t => t.OriginalReReadingTask.ReadingCategory == inQuery.ReadingCategory)

                  .WhereIf(!string.IsNullOrEmpty(inQuery.RequestReReadingReason), t => t.RequestReReadingReason.Contains(inQuery.RequestReReadingReason))

                  .WhereIf(inQuery.RequestReReadingResultEnum != null, t => t.RequestReReadingResultEnum == inQuery.RequestReReadingResultEnum)


                   .WhereIf(!string.IsNullOrEmpty(inQuery.TrialSiteCode), t => (t.OriginalReReadingTask.BlindTrialSiteCode.Contains(inQuery.TrialSiteCode!) && t.OriginalReReadingTask.IsAnalysisCreate) || (t.OriginalReReadingTask.Subject.TrialSite.TrialSiteCode.Contains(inQuery.TrialSiteCode!) && t.OriginalReReadingTask.IsAnalysisCreate == false))
                  .WhereIf(!string.IsNullOrEmpty(inQuery.TaskName), t => t.OriginalReReadingTask.TaskName.Contains(inQuery.TaskName) || t.OriginalReReadingTask.TaskBlindName.Contains(inQuery.TaskName))
                  .WhereIf(!string.IsNullOrEmpty(inQuery.SubjectCode), t => ((t.OriginalReReadingTask.Subject.Code.Contains(inQuery.SubjectCode) || t.OriginalReReadingTask.Subject.MedicalNo.Contains(inQuery.SubjectCode)) && t.OriginalReReadingTask.IsAnalysisCreate == false) || (t.OriginalReReadingTask.BlindSubjectCode.Contains(inQuery.SubjectCode) && t.OriginalReReadingTask.IsAnalysisCreate))
                  .WhereIf(inQuery.BeginAllocateDate != null, t => t.OriginalReReadingTask.AllocateTime > inQuery.BeginAllocateDate)
                  .WhereIf(inQuery.EndAllocateDate != null, t => t.OriginalReReadingTask.AllocateTime < inQuery.EndAllocateDate!.Value.AddDays(1))

                   .WhereIf(inQuery.BeginRequestReReadingTime != null, t => t.RequestReReadingTime >= inQuery.BeginRequestReReadingTime)
                  .WhereIf(inQuery.EndRequestReReadingTime != null, t => t.RequestReReadingTime <= inQuery.EndRequestReReadingTime!.Value.AddDays(1))
                  .ProjectTo<ReReadingTaskExportDto>(_mapper.ConfigurationProvider);

            //var defalutSortArray = new string[] { nameof(ReReadingTaskView.OriginalReReadingTask) + "." + nameof(ReReadingTaskView.OriginalReReadingTask.IsUrgent) + " desc", nameof(ReReadingTaskView.OriginalReReadingTask) + "." + nameof(ReReadingTaskView.OriginalReReadingTask.SubjectId), nameof(ReReadingTaskView.OriginalReReadingTask) + "." + nameof(ReReadingTaskView.OriginalReReadingTask.VisitTaskNum) };

            var list = visitTaskQueryable.OrderBy(t => t.TrialSiteCode).ThenBy(t => t.SubjectCode).ThenBy(t => t.VisitTaskNum).ToList();

            var exportInfo = (await _trialRepository.Where(t => t.Id == inQuery.TrialId).IgnoreQueryFilters().ProjectTo<ExcelExportInfo>(_mapper.ConfigurationProvider).FirstOrDefaultAsync()).IfNullThrowException();

            exportInfo.List = ExportExcelConverterDate.ConvertToClientTimeInObject(list, _userInfo.TimeZoneId);
            exportInfo.CurrentTime = ExportExcelConverterDate.DateTimeInternationalToString(DateTime.Now, _userInfo.TimeZoneId);


            return await ExcelExportHelper.DataExportAsync(StaticData.Export.TrialReReadingTaskList_Export, exportInfo, $"{exportInfo.ResearchProgramNo}", _commonDocumentRepository, _hostEnvironment, _dictionaryService, typeof(ReReadingTaskExportDto));
        }



        /// <summary>
        /// PM  医学审核（挑选任务生成后的列表）
        /// </summary>
        /// <param name="inQuery"></param>
        /// <param name="_commonDocumentRepository"></param>
        /// <param name="_taskMedicalReviewRepository"></param>
        /// <param name="_dictionaryService"></param>
        /// <param name="_trialRepository"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> GetMedicalReviewTaskList_Export(TaskMedicalReviewQuery inQuery,
                [FromServices] IRepository<CommonDocument> _commonDocumentRepository,
                 [FromServices] IRepository<TaskMedicalReview> _taskMedicalReviewRepository,
                [FromServices] IDictionaryService _dictionaryService,
                [FromServices] IRepository<Trial> _trialRepository)
        {

            var taskMedicalReviewQueryable = _taskMedicalReviewRepository.Where(t => t.VisitTask.TrialId == inQuery.TrialId)

                             .WhereIf(inQuery.TrialSiteId != null, t => t.VisitTask.Subject.TrialSiteId == inQuery.TrialSiteId)
                             .WhereIf(inQuery.SubjectId != null, t => t.VisitTask.SubjectId == inQuery.SubjectId)
                             .WhereIf(!string.IsNullOrEmpty(inQuery.SubjectCode), t => t.VisitTask.Subject.Code.Contains(inQuery.SubjectCode) || t.VisitTask.Subject.MedicalNo.Contains(inQuery.SubjectCode))
                             .WhereIf(!string.IsNullOrEmpty(inQuery.TaskName), t => t.VisitTask.TaskName.Contains(inQuery.TaskName) || t.VisitTask.TaskBlindName.Contains(inQuery.TaskName))
                             .WhereIf(inQuery.IsUrgent != null, t => t.VisitTask.IsUrgent == inQuery.IsUrgent)
                             .WhereIf(inQuery.DoctorUserId != null, t => t.VisitTask.DoctorUserId == inQuery.DoctorUserId)
                             .WhereIf(!string.IsNullOrEmpty(inQuery.TrialSiteCode), t => (t.VisitTask.BlindTrialSiteCode.Contains(inQuery.TrialSiteCode) && t.VisitTask.IsAnalysisCreate) || (t.VisitTask.Subject.TrialSite.TrialSiteCode.Contains(inQuery.TrialSiteCode) && t.VisitTask.IsAnalysisCreate == false))
                             .WhereIf(inQuery.ReadingCategory != null, t => t.VisitTask.ReadingCategory == inQuery.ReadingCategory)
                             .WhereIf(inQuery.TaskState != null, t => t.VisitTask.TaskState == inQuery.TaskState)
                             .WhereIf(inQuery.ArmEnum != null, t => t.VisitTask.ArmEnum == inQuery.ArmEnum)
                             .WhereIf(inQuery.AuditState != null, t => t.AuditState == inQuery.AuditState)
                             .WhereIf(inQuery.MedicalManagerUserId != null, t => t.MedicalManagerUserId == inQuery.MedicalManagerUserId)
                             .WhereIf(inQuery.BeginSignTime != null, t => t.VisitTask.SignTime > inQuery.BeginSignTime)
                             .WhereIf(inQuery.EndSignTime != null, t => t.VisitTask.SignTime < inQuery.EndSignTime)
                             .WhereIf(inQuery.AuditAdviceEnum != null, t => t.AuditAdviceEnum == inQuery.AuditAdviceEnum)

                             .WhereIf(inQuery.DoctorUserIdeaEnum != null, t => t.DoctorUserIdeaEnum == inQuery.DoctorUserIdeaEnum)
                             .WhereIf(inQuery.TrialReadingCriterionId != null, t => t.VisitTask.TrialReadingCriterionId == inQuery.TrialReadingCriterionId)
                             .WhereIf(inQuery.IsInvalid != null, t => t.IsInvalid == inQuery.IsInvalid)
                             .WhereIf(inQuery.IsHaveQuestion != null, t => t.IsHaveQuestion == inQuery.IsHaveQuestion)

                             .WhereIf(inQuery.BeginAllocateDate != null, t => t.AllocateTime >= inQuery.BeginAllocateDate)
                             .WhereIf(inQuery.EndAllocateDate != null, t => t.AllocateTime <= inQuery.EndAllocateDate)
                             .WhereIf(inQuery.BeginAuditSignTime != null, t => t.AuditSignTime >= inQuery.BeginAuditSignTime)
                              .WhereIf(inQuery.EndAuditSignTime != null, t => t.AuditSignTime <= inQuery.EndAuditSignTime)
                             .ProjectTo<TaskMedicalReviewExportDto>(_mapper.ConfigurationProvider);

            var list = taskMedicalReviewQueryable.OrderBy(t => t.TrialSiteCode).ThenBy(t => t.SubjectCode).ThenBy(t => t.VisitTaskNum).ToList();


            var exportInfo = (await _trialRepository.Where(t => t.Id == inQuery.TrialId).IgnoreQueryFilters().ProjectTo<ExcelExportInfo>(_mapper.ConfigurationProvider).FirstOrDefaultAsync()).IfNullThrowException();

            exportInfo.List = ExportExcelConverterDate.ConvertToClientTimeInObject(list, _userInfo.TimeZoneId);
            exportInfo.CurrentTime = ExportExcelConverterDate.DateTimeInternationalToString(DateTime.Now, _userInfo.TimeZoneId);


            return await ExcelExportHelper.DataExportAsync(StaticData.Export.TrialMedicalReviewList_Export, exportInfo, $"{exportInfo.ResearchProgramNo}", _commonDocumentRepository, _hostEnvironment, _dictionaryService, typeof(TaskMedicalReviewExportDto));
        }


        /// <summary>
        /// 影像下载记录表
        /// </summary>
        /// <param name="inQuery"></param>
        /// <param name="_trialImageDownloadRepository"></param>
        /// <param name="_dictionaryService"></param>
        /// <param name="_trialRepository"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> GetTrialDownloadList_Export(TrialIamgeDownQuery inQuery,
            [FromServices] IRepository<TrialImageDownload> _trialImageDownloadRepository,
            [FromServices] IDictionaryService _dictionaryService,
            [FromServices] IRepository<Trial> _trialRepository)
        {
            var query = _trialImageDownloadRepository.Where(t => t.TrialId == inQuery.TrialId)
                  .WhereIf(inQuery.SubjectCode.IsNotNullOrEmpty(), t => t.SubjectCode.Contains(inQuery.SubjectCode))
                  .WhereIf(inQuery.IP.IsNotNullOrEmpty(), t => t.IP.Contains(inQuery.IP))
                   .WhereIf(inQuery.Name.IsNotNullOrEmpty(), t => t.CreateUser.UserName.Contains(inQuery.Name) || t.CreateUser.FullName.Contains(inQuery.Name))
                  .WhereIf(inQuery.ImageType != null, t => t.ImageType == inQuery.ImageType)
                  .WhereIf(inQuery.UserType != null, t => t.CreateUser.UserTypeEnum == inQuery.UserType)
                  .WhereIf(inQuery.IsSuccess != null, t => t.IsSuccess == inQuery.IsSuccess)
                  .WhereIf(inQuery.DownloadStartTime != null, t => t.DownloadStartTime >= inQuery.DownloadStartTime)
                  .WhereIf(inQuery.DownloadEndTime != null, t => t.DownloadEndTime <= inQuery.DownloadEndTime)

                  .ProjectTo<TrialImageDownloadExportDto>(_mapper.ConfigurationProvider);

            var list = await query.SortToListAsync(inQuery);


            var exportInfo = (await _trialRepository.Where(t => t.Id == inQuery.TrialId).IgnoreQueryFilters().ProjectTo<ExcelExportInfo>(_mapper.ConfigurationProvider).FirstOrDefaultAsync()).IfNullThrowException();

            exportInfo.List = ExportExcelConverterDate.ConvertToClientTimeInObject(list, _userInfo.TimeZoneId);
            exportInfo.CurrentTime = ExportExcelConverterDate.DateTimeInternationalToString(DateTime.Now, _userInfo.TimeZoneId);


            return await ExcelExportHelper.DataExportAsync(StaticData.Export.TrialImageDownloadList_Export, exportInfo, $"{exportInfo.ResearchProgramNo}", _commonDocumentRepository, _hostEnvironment, _dictionaryService, typeof(TrialImageDownloadExportDto));

        }

        /// <summary>
        /// 影像接收记录表
        /// </summary>
        /// <param name="inQuery"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> GetSCPImageUploadList_Export(SCPImageUploadQuery inQuery,
            [FromServices] IRepository<SCPImageUpload> _scpImageUploadRepository,
            [FromServices] IDictionaryService _dictionaryService,
            [FromServices] IRepository<Trial> _trialRepository)
        {
            var query = _scpImageUploadRepository.Where(t => t.TrialId == inQuery.TrialId)
              .WhereIf(!string.IsNullOrWhiteSpace(inQuery.CalledAE), t => t.CalledAE.Contains(inQuery.CalledAE))
              .WhereIf(!string.IsNullOrWhiteSpace(inQuery.CallingAEIP), t => t.CallingAEIP.Contains(inQuery.CallingAEIP))
              .WhereIf(!string.IsNullOrWhiteSpace(inQuery.CallingAE), t => t.CallingAE.Contains(inQuery.CallingAE))
             .WhereIf(inQuery.StartTime != null, t => t.StartTime >= inQuery.StartTime)
             .WhereIf(inQuery.EndTime != null, t => t.EndTime <= inQuery.EndTime)
              .WhereIf(!string.IsNullOrWhiteSpace(inQuery.TrialSiteKeyInfo), t => t.TrialSite.TrialSiteCode.Contains(inQuery.TrialSiteKeyInfo)
               || t.TrialSite.TrialSiteAliasName.Contains(inQuery.TrialSiteKeyInfo) || t.TrialSite.TrialSiteName.Contains(inQuery.TrialSiteKeyInfo))
              .ProjectTo<SCPImageUploadExportDTO>(_mapper.ConfigurationProvider);


            var list = await query.SortToListAsync(inQuery);

            var exportInfo = (await _trialRepository.Where(t => t.Id == inQuery.TrialId).IgnoreQueryFilters().ProjectTo<ExcelExportInfo>(_mapper.ConfigurationProvider).FirstOrDefaultAsync()).IfNullThrowException();

            exportInfo.List = ExportExcelConverterDate.ConvertToClientTimeInObject(list, _userInfo.TimeZoneId);
            exportInfo.CurrentTime = ExportExcelConverterDate.DateTimeInternationalToString(DateTime.Now, _userInfo.TimeZoneId);


            return await ExcelExportHelper.DataExportAsync(StaticData.Export.TrialSCPImageUploadList_Export, exportInfo, $"{exportInfo.ResearchProgramNo}", _commonDocumentRepository, _hostEnvironment, _dictionaryService, typeof(SCPImageUploadExportDTO));

        }

        /// <summary>
        /// 国际化导出
        /// </summary>
        /// <param name="inQuery"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> GetInternationalizationList_Export(InternationalizationQuery inQuery,
            [FromServices] IRepository<Internationalization> _internationalizationRepository,
            [FromServices] IDictionaryService _dictionaryService)
        {

            var internationalizationQueryable = _internationalizationRepository
                .WhereIf(inQuery.Description != null, t => t.Description.Contains(inQuery.Description))
                 .WhereIf(inQuery.Module != null, t => t.Module.Contains(inQuery.Module))
                 .WhereIf(inQuery.PublishLogId != null, t => t.PublishLogId == inQuery.PublishLogId)
                .WhereIf(inQuery.Code != null, t => t.Code.Contains(inQuery.Code))
                .WhereIf(inQuery.State != null, t => t.State == inQuery.State)
                .WhereIf(inQuery.InternationalizationType != null, t => t.InternationalizationType == inQuery.InternationalizationType)
                .WhereIf(inQuery.Value != null, t => t.Value.Contains(inQuery.Value))
                .WhereIf(inQuery.ValueCN != null, t => t.ValueCN.Contains(inQuery.ValueCN))
                .ProjectTo<InternationalizationView>(_mapper.ConfigurationProvider);

            var list = internationalizationQueryable.SortToListAsync(inQuery);

            var exportInfo = new ExcelExportInfo();
            exportInfo.List = ExportExcelConverterDate.ConvertToClientTimeInObject(list, _userInfo.TimeZoneId);
            exportInfo.CurrentTime = ExportExcelConverterDate.DateTimeInternationalToString(DateTime.Now, _userInfo.TimeZoneId);

            return await ExcelExportHelper.DataExportAsync(StaticData.Export.TrialSCPImageUploadList_Export, exportInfo, $"{exportInfo.ResearchProgramNo}", _commonDocumentRepository, _hostEnvironment, _dictionaryService, typeof(InternationalizationView));

        }

        /// <summary>
        ///影像检查列表-患者为维度组织
        /// </summary>
        /// <param name="inQuery"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> GetPatientList_Export(PatientTrialQuery inQuery,
             [FromServices] IRepository<SCPPatient> _patientRepository,
            [FromServices] IDictionaryService _dictionaryService,
            [FromServices] IRepository<Trial> _trialRepository)
        {


            var query = _patientRepository.Where(t => t.TrialId == inQuery.TrialId)
             .WhereIf(!string.IsNullOrWhiteSpace(inQuery.PatientIdStr), t => t.PatientIdStr.Contains(inQuery.PatientIdStr))
             .WhereIf(!string.IsNullOrWhiteSpace(inQuery.PatientName), t => t.PatientName.Contains(inQuery.PatientName))
             .WhereIf(!string.IsNullOrWhiteSpace(inQuery.SubejctCode), t => t.Subject.Code.Contains(inQuery.SubejctCode))
             .WhereIf(!string.IsNullOrWhiteSpace(inQuery.TrialSiteKeyInfo), t => t.TrialSite.TrialSiteCode.Contains(inQuery.TrialSiteKeyInfo)
               || t.TrialSite.TrialSiteAliasName.Contains(inQuery.TrialSiteKeyInfo) || t.TrialSite.TrialSiteName.Contains(inQuery.TrialSiteKeyInfo))
             .WhereIf(!string.IsNullOrWhiteSpace(inQuery.CallingAE), t => t.SCPStudyList.Any(t => t.CallingAE == inQuery.CallingAE))
             .WhereIf(!string.IsNullOrWhiteSpace(inQuery.CalledAE), t => t.SCPStudyList.Any(t => t.CalledAE == inQuery.CalledAE))
             .WhereIf(inQuery.BeginPushTime != null, t => t.LatestPushTime >= inQuery.BeginPushTime)
             .WhereIf(inQuery.EndPushTime != null, t => t.LatestPushTime <= inQuery.EndPushTime);


            var resultQuery = from patient in query

                              select new SCPPatientSubjectExportDTO()
                              {
                                  //CreateUserId = patient.CreateUserId,
                                  //UpdateTime = patient.UpdateTime,
                                  //UpdateUserId = patient.UpdateUserId,
                                  //TrialId = patient.TrialId,
                                  //SubejctId = patient.SubjectId,
                                  //CreateTime = patient.CreateTime,
                                  //PatientId = patient.Id,

                                  PatientBirthDate = patient.PatientBirthDate,
                                  CalledAEList = patient.SCPStudyList.Select(t => t.CalledAE).Distinct().ToList(),
                                  CallingAEList = patient.SCPStudyList.Select(t => t.CallingAE).Distinct().ToList(),
                                  EarliestStudyTime = patient.EarliestStudyTime,
                                  LatestStudyTime = patient.LatestStudyTime,
                                  LatestPushTime = patient.LatestPushTime,
                                  PatientAge = patient.PatientAge,
                                  PatientName = patient.PatientName,
                                  PatientIdStr = patient.PatientIdStr,
                                  PatientSex = patient.PatientSex,
                                  StudyCount = patient.SCPStudyList.Count(),
                                  SubjectCode = patient.Subject.Code,
                                  TrialSiteAliasName = patient.TrialSite.TrialSiteAliasName,
                                  TrialSiteCode = patient.TrialSite.TrialSiteCode,
                                  TrialSiteName = patient.TrialSite.TrialSiteName

                              };

            var list = await resultQuery.SortToListAsync(inQuery);

            var exportInfo = (await _trialRepository.Where(t => t.Id == inQuery.TrialId).IgnoreQueryFilters().ProjectTo<ExcelExportInfo>(_mapper.ConfigurationProvider).FirstOrDefaultAsync()).IfNullThrowException();

            exportInfo.List = ExportExcelConverterDate.ConvertToClientTimeInObject(list, _userInfo.TimeZoneId);
            exportInfo.CurrentTime = ExportExcelConverterDate.DateTimeInternationalToString(DateTime.Now, _userInfo.TimeZoneId);


            return await ExcelExportHelper.DataExportAsync(StaticData.Export.TrialSCPImageUploadPatientList_Export, exportInfo, $"{exportInfo.ResearchProgramNo}", _commonDocumentRepository, _hostEnvironment, _dictionaryService, typeof(SCPPatientSubjectExportDTO));

        }

        /// <summary>
        /// 自身一致性分析(仅做了resist1.1)
        /// </summary>
        /// <param name="inQuery"></param>
        /// <param name="_commonDocumentRepository"></param>
        /// <param name="_dictionaryService"></param>
        /// <param name="_trialRepository"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> GetSelfAnalysisTaskList_Export(VisitTaskQuery inQuery,
                [FromServices] IRepository<CommonDocument> _commonDocumentRepository,
                [FromServices] IDictionaryService _dictionaryService,
                [FromServices] IRepository<Trial> _trialRepository)
        {

            var criterion = await _readingQuestionCriterionTrialRepository.Where(t => t.Id == inQuery.TrialReadingCriterionId).Select(t => new { t.CriterionType, t.CriterionName }).FirstNotNullAsync();

            if (criterion.CriterionType != CriterionType.RECIST1Point1)
            {
                //---当前标准导出还未支持
                throw new Exception(_localizer["ExcelExport_UnsupportedExport"]);
            }
            //产生一致性分析的Subject

            var subjectQuerybal = _visitTaskRepository.Where(t => t.TrialId == inQuery.TrialId && t.TaskState == TaskState.Effect && t.IsSelfAnalysis == true).Select(t => t.SubjectId).Distinct();

            var allList = await _visitTaskRepository.Where(t => t.TrialId == inQuery.TrialId && t.TaskState == TaskState.Effect && subjectQuerybal.Contains(t.SubjectId) && t.ReadingCategory == ReadingCategory.Visit)
                .Where(t => (t.IsSelfAnalysis == true || t.IsSelfAnalysis == null) && t.VisitTaskNum > 0) //一致性分析的结果 + 正常任务的结果 + 仅仅访视的结果 +去除基线

               //.WhereIf(inQuery.SubjectId != null, t => t.SubjectId == inQuery.SubjectId)
               //.WhereIf(inQuery.TaskState != null, t => t.TaskState == inQuery.TaskState)
               //.WhereIf(inQuery.IsSelfAnalysis != null, t => t.IsSelfAnalysis == inQuery.IsSelfAnalysis)

               .WhereIf(inQuery.TrialReadingCriterionId != null, t => t.TrialReadingCriterionId == inQuery.TrialReadingCriterionId)
               .WhereIf(inQuery.TrialSiteId != null, t => t.Subject.TrialSiteId == inQuery.TrialSiteId)

               .WhereIf(inQuery.IsUrgent != null, t => t.IsUrgent == inQuery.IsUrgent)
               .WhereIf(inQuery.DoctorUserId != null, t => t.DoctorUserId == inQuery.DoctorUserId)
               .WhereIf(inQuery.ReadingCategory != null, t => t.ReadingCategory == inQuery.ReadingCategory)
               .WhereIf(inQuery.ReadingTaskState != null, t => t.ReadingTaskState == inQuery.ReadingTaskState)
               .WhereIf(inQuery.TaskAllocationState != null, t => t.TaskAllocationState == inQuery.TaskAllocationState)
               .WhereIf(inQuery.ArmEnum != null, t => t.ArmEnum == inQuery.ArmEnum)
               .WhereIf(!string.IsNullOrEmpty(inQuery.TrialSiteCode), t => (t.BlindTrialSiteCode.Contains(inQuery.TrialSiteCode!) && t.IsAnalysisCreate) || (t.Subject.TrialSite.TrialSiteCode.Contains(inQuery.TrialSiteCode!) && t.IsAnalysisCreate == false))
               .WhereIf(!string.IsNullOrEmpty(inQuery.TaskName), t => t.TaskName.Contains(inQuery.TaskName) || t.TaskBlindName.Contains(inQuery.TaskName))
               .WhereIf(!string.IsNullOrEmpty(inQuery.SubjectCode), t => t.Subject.Code.Contains(inQuery.SubjectCode))
               .WhereIf(inQuery.BeginAllocateDate != null, t => t.AllocateTime > inQuery.BeginAllocateDate)
               .WhereIf(inQuery.EndAllocateDate != null, t => t.AllocateTime < inQuery.EndAllocateDate!.Value.AddDays(1))
               .ProjectTo<SelftAnalysisExport>(_mapper.ConfigurationProvider).ToListAsync();



            var list = allList.Where(t => t.IsSelfAnalysis == null).OrderBy(t => t.TrialSiteCode).ThenBy(t => t.SubjectCode).ThenBy(t => t.VisitTaskNum).ToList();

            //To do 根据任务Id  找对评估结果，这里需要考虑标准  以及对应的翻译

            //基线和访视的评估结果翻译枚举 分别对应着

            foreach (var item in list)
            {
                //找到一致性分析的结果
                var selfAnalysisTask = allList.Where(t => t.IsSelfAnalysis == true && t.SubjectCode == item.SubjectCode && t.VisitTaskNum == item.VisitTaskNum && t.TaskName == t.TaskName && t.UserName == item.UserName).FirstOrDefault();


                //因为基线的评估结果是 是否存在疾病 而 其他访视的结果是 整体肿瘤评估结果 是用不同的枚举翻译的 所以这里手动翻译 不把翻译逻辑耦合到通用的翻译代码里面 在此特殊处理

                item.AgainEvaluateResult = selfAnalysisTask?.EvaluateResult ?? String.Empty;

                //将自身一致性分析的字段 赋值到访视任务这个字段
                item.IsAnalysisDiffToOriginalData = selfAnalysisTask?.IsAnalysisDiffToOriginalData;

            }


            var exportInfo = (await _trialRepository.Where(t => t.Id == inQuery.TrialId).IgnoreQueryFilters().ProjectTo<ExcelExportInfo>(_mapper.ConfigurationProvider).FirstOrDefaultAsync()).IfNullThrowException();

            exportInfo.CriterionName = await _readingQuestionCriterionTrialRepository.Where(u => u.TrialId == inQuery.TrialId && u.IsConfirm && u.Id == inQuery.TrialReadingCriterionId).Select(t => t.CriterionName).FirstOrDefaultAsync();
            exportInfo.List = ExportExcelConverterDate.ConvertToClientTimeInObject(list, _userInfo.TimeZoneId);
            exportInfo.CurrentTime = ExportExcelConverterDate.DateTimeInternationalToString(DateTime.Now, _userInfo.TimeZoneId);


            return await ExcelExportHelper.DataExportAsync(StaticData.Export.TrialSelfAnalysisList_Export, exportInfo, $"{exportInfo.ResearchProgramNo}_{exportInfo.CriterionName}", _commonDocumentRepository, _hostEnvironment, _dictionaryService, typeof(SelftAnalysisExport));
        }


        /// <summary>
        /// 组件一致性分析(仅做了resist1.1)
        /// </summary>
        /// <param name="inQuery"></param>
        /// <param name="_commonDocumentRepository"></param>
        /// <param name="_dictionaryService"></param>
        /// <param name="_trialRepository"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> GetGroupAnalysisTaskList_Export(VisitTaskQuery inQuery,
                [FromServices] IRepository<CommonDocument> _commonDocumentRepository,
                [FromServices] IDictionaryService _dictionaryService,
                [FromServices] IRepository<Trial> _trialRepository)
        {
            var criterion = await _readingQuestionCriterionTrialRepository.Where(t => t.Id == inQuery.TrialReadingCriterionId).Select(t => new { t.CriterionType, t.CriterionName }).FirstNotNullAsync();

            if (criterion.CriterionType != CriterionType.RECIST1Point1)
            {
                //---当前标准导出还未支持
                throw new Exception(_localizer["ExcelExport_UnsupportedExport"]);
            }

            //产生组间一致性分析的Subject

            var subjectQuerybal = _visitTaskRepository.Where(t => t.TrialId == inQuery.TrialId && t.TaskState == TaskState.Effect && t.IsSelfAnalysis == false).Select(t => t.SubjectId).Distinct();

            var allList = await _visitTaskRepository.Where(t => t.TrialId == inQuery.TrialId && t.TaskState == TaskState.Effect && subjectQuerybal.Contains(t.SubjectId) && t.ReadingCategory == ReadingCategory.Visit)
                .Where(t => (t.IsSelfAnalysis == false || t.IsSelfAnalysis == null) && t.VisitTaskNum > 0) //一致性分析的结果 + 正常任务的结果 +仅仅访视的结果

               //.WhereIf(inQuery.SubjectId != null, t => t.SubjectId == inQuery.SubjectId)
               //.WhereIf(inQuery.TaskState != null, t => t.TaskState == inQuery.TaskState)
               //.WhereIf(inQuery.IsSelfAnalysis != null, t => t.IsSelfAnalysis == inQuery.IsSelfAnalysis)

               .WhereIf(inQuery.TrialReadingCriterionId != null, t => t.TrialReadingCriterionId == inQuery.TrialReadingCriterionId)
               .WhereIf(inQuery.TrialSiteId != null, t => t.Subject.TrialSiteId == inQuery.TrialSiteId)

               .WhereIf(inQuery.IsUrgent != null, t => t.IsUrgent == inQuery.IsUrgent)
               .WhereIf(inQuery.DoctorUserId != null, t => t.DoctorUserId == inQuery.DoctorUserId)
               .WhereIf(inQuery.ReadingCategory != null, t => t.ReadingCategory == inQuery.ReadingCategory)
               .WhereIf(inQuery.ReadingTaskState != null, t => t.ReadingTaskState == inQuery.ReadingTaskState)
               .WhereIf(inQuery.TaskAllocationState != null, t => t.TaskAllocationState == inQuery.TaskAllocationState)
               .WhereIf(inQuery.ArmEnum != null, t => t.ArmEnum == inQuery.ArmEnum)
               .WhereIf(!string.IsNullOrEmpty(inQuery.TrialSiteCode), t => (t.BlindTrialSiteCode.Contains(inQuery.TrialSiteCode!) && t.IsAnalysisCreate) || (t.Subject.TrialSite.TrialSiteCode.Contains(inQuery.TrialSiteCode!) && t.IsAnalysisCreate == false))
               .WhereIf(!string.IsNullOrEmpty(inQuery.TaskName), t => t.TaskName.Contains(inQuery.TaskName) || t.TaskBlindName.Contains(inQuery.TaskName))
               .WhereIf(!string.IsNullOrEmpty(inQuery.SubjectCode), t => t.Subject.Code.Contains(inQuery.SubjectCode))
               .WhereIf(inQuery.BeginAllocateDate != null, t => t.AllocateTime > inQuery.BeginAllocateDate)
               .WhereIf(inQuery.EndAllocateDate != null, t => t.AllocateTime < inQuery.EndAllocateDate!.Value.AddDays(1))
               .ProjectTo<GroupAnalysisExport>(_mapper.ConfigurationProvider).ToListAsync();


            //找到原任务（非组间一致性分析的）
            var list = allList.Where(t => t.IsSelfAnalysis == null).OrderBy(t => t.TrialSiteCode).ThenBy(t => t.SubjectCode).ThenBy(t => t.VisitTaskNum).ToList();


            var newList = new List<GroupAnalysisExport>();

            // 每个subject访视进行分组

            foreach (var group in list.GroupBy(t => new { t.SubjectCode, t.VisitTaskNum, t.TaskName, t.ArmEnum })
                .OrderBy(g => g.Key.SubjectCode)
                .ThenBy(g => g.Key.VisitTaskNum)
                //.ThenBy(g => g.Key.ArmEnum)
                )
            {
                var subjectVisitGroupList = group.ToList();


                //找到当前访视组间一致性分析的任务结果

                var groupTaskList = allList.Where(t => t.IsSelfAnalysis == false && t.SubjectCode == group.Key.SubjectCode && t.VisitTaskNum == group.Key.VisitTaskNum && t.TaskName == group.Key.TaskName).ToList();

                foreach (var subjectVisitTaskArm in subjectVisitGroupList.OrderBy(t => t.ArmEnum))
                {

                    foreach (var item in groupTaskList)
                    {
                        var cloneObj = subjectVisitTaskArm.Clone();


                        cloneObj.AgainUserName = item.UserName;
                        cloneObj.AgainEvaluateResult = item.EvaluateResult;
                        cloneObj.AgainArmEnum = item.ArmEnum;

                        cloneObj.IsGroupAnalysisDiffToOriginalData = cloneObj.ArmEnum == Arm.DoubleReadingArm1 ? item.IsGroupDiffArm1 : item.IsGroupDiffArm2;

                        newList.Add(cloneObj);
                    }
                }

            }




            var exportInfo = (await _trialRepository.Where(t => t.Id == inQuery.TrialId).IgnoreQueryFilters().ProjectTo<ExcelExportInfo>(_mapper.ConfigurationProvider).FirstOrDefaultAsync()).IfNullThrowException();
            exportInfo.CriterionName = await _readingQuestionCriterionTrialRepository.Where(u => u.TrialId == inQuery.TrialId && u.IsConfirm && u.Id == inQuery.TrialReadingCriterionId).Select(t => t.CriterionName).FirstOrDefaultAsync();
            exportInfo.List = ExportExcelConverterDate.ConvertToClientTimeInObject(newList, _userInfo.TimeZoneId); ;
            exportInfo.CurrentTime = ExportExcelConverterDate.DateTimeInternationalToString(DateTime.Now, _userInfo.TimeZoneId);


            return await ExcelExportHelper.DataExportAsync(StaticData.Export.TrialGroupAnalysisList_Export, exportInfo, $"{exportInfo.ResearchProgramNo}_{exportInfo.CriterionName}", _commonDocumentRepository, _hostEnvironment, _dictionaryService, typeof(GroupAnalysisExport));
        }


        public class ExportDocumentDes
        {
            public string Code { get; set; }

            public string FileName { get; set; }

            public ExportCatogory ExportCatogory { get; set; }
        }


        public enum ExportCatogory
        {
            // 整体肿瘤评估
            OverallTumorEvaluation = 1,

            //肿瘤疗效评估
            EvaluationOfTumorEfficacy = 2,

            //评估病灶明细
            DetailedOfEvaluatedLesion = 3,


        }

        /// <summary>
        /// 获取阅片标准可以导出的列表
        /// </summary>
        /// <param name="trialReadingCriterionId"></param>
        /// <returns></returns>
        public async Task<List<ExportDocumentDes>> GetTrialReadingCriterionCanExportDocumentList(Guid trialReadingCriterionId)
        {

            var list = new List<ExportDocumentDes>();
            var criterion = await _readingQuestionCriterionTrialRepository.Where(t => t.Id == trialReadingCriterionId).Select(t => new { t.CriterionType, t.CriterionName }).FirstNotNullAsync();

            list.Add(new ExportDocumentDes() { Code = StaticData.Export.CommonReading_Export, ExportCatogory = ExportCatogory.OverallTumorEvaluation });
            list.Add(new ExportDocumentDes() { Code = StaticData.Export.CommonReadingDetail_Export, ExportCatogory = ExportCatogory.OverallTumorEvaluation });
            list.Add(new ExportDocumentDes() { Code = StaticData.Export.CommonJudgeReadingDetail_Export, ExportCatogory = ExportCatogory.OverallTumorEvaluation });


            if (criterion.CriterionType == CriterionType.RECIST1Point1 || criterion.CriterionType == CriterionType.RECIST1Pointt1_MB)
            {
                list.Add(new ExportDocumentDes() { Code = StaticData.Export.OverallTumorEvaluation_Export, ExportCatogory = ExportCatogory.OverallTumorEvaluation });
                list.Add(new ExportDocumentDes() { Code = StaticData.Export.RECIST1Point1EvaluationOfTumorEfficacy_Export, ExportCatogory = ExportCatogory.EvaluationOfTumorEfficacy });
                list.Add(new ExportDocumentDes() { Code = StaticData.Export.RECIST1Point1DetailedOfEvaluatedLesion_Export, ExportCatogory = ExportCatogory.DetailedOfEvaluatedLesion });
            }

            else if (criterion.CriterionType == CriterionType.PCWG3)
            {
                list.Add(new ExportDocumentDes() { Code = StaticData.Export.OverallTumorEvaluation_Export, ExportCatogory = ExportCatogory.OverallTumorEvaluation });
                list.Add(new ExportDocumentDes() { Code = StaticData.Export.PCWG3Point1DetailedOfEvaluatedLesion_Export, ExportCatogory = ExportCatogory.DetailedOfEvaluatedLesion });
            }
            else if (criterion.CriterionType == CriterionType.IRECIST1Point1)
            {
                list.Add(new ExportDocumentDes() { Code = StaticData.Export.OverallTumorEvaluation_Export, ExportCatogory = ExportCatogory.OverallTumorEvaluation });
                list.Add(new ExportDocumentDes() { Code = StaticData.Export.IRECIST1Point1EvaluationOfTumorEfficacy_Export, ExportCatogory = ExportCatogory.DetailedOfEvaluatedLesion });
            }
            else if (criterion.CriterionType == CriterionType.Lugano2014)
            {
                list.Add(new ExportDocumentDes() { Code = StaticData.Export.OverallTumorEvaluation_Export, ExportCatogory = ExportCatogory.OverallTumorEvaluation });
                list.Add(new ExportDocumentDes() { Code = StaticData.Export.Lugano2014EvaluationOfTumorEfficacy_Export, ExportCatogory = ExportCatogory.DetailedOfEvaluatedLesion });
            }

            var result = _commonDocumentRepository.Where(t => list.Select(c => c.Code).Contains(t.Code)).Select(c => new ExportDocumentDes() { Code = c.Code, FileName = _userInfo.IsEn_Us ? c.Name : c.NameCN }).ToList();

            foreach (var item in list)
            {
                item.FileName = result.Where(t => t.Code == item.Code).FirstOrDefault()?.FileName;
            }
            return list;
        }

        public List<T> DealJudgeMark<T>(ArbitrationRule arbitrationRule, IEnumerable<T> list) where T : OverallTumorEvaluationExport
        {
            //处理访视任务的裁判标记
            var resultExceptJudgeList = list.Where(t => t.ReadingCategory != ReadingCategory.Judge).ToList();

            var judegeList = list.Where(t => t.ReadingCategory == ReadingCategory.Judge).ToList();

            if (arbitrationRule == ArbitrationRule.Visit)
            {

                foreach (var item in resultExceptJudgeList)
                {
                    item.IsJudgeSelect = judegeList.FirstOrDefault(t => t.SubjectCode == item.SubjectCode
                    && (t.VisitTaskNum - ReadingCommon.TaskNumDic[ReadingCategory.Judge]) == item.VisitTaskNum)?.JudgeArmEnum == item.ArmEnum ? true : false;
                }

                //如果没有产生裁判，默认选择R1

                //找到没有裁判的访视任务
                var notJudgeList = resultExceptJudgeList.GroupBy(t => new { t.SubjectCode, t.VisitTaskNum }).Where(g => g.All(t => t.IsJudgeSelect == false)).Select(g => new { g.Key.SubjectCode, g.Key.VisitTaskNum }).ToList();

                foreach (var item in resultExceptJudgeList)
                {
                    if (notJudgeList.Any(t => t.SubjectCode == item.SubjectCode && t.VisitTaskNum == item.VisitTaskNum) && item.ArmEnum == Arm.DoubleReadingArm1)
                    {
                        item.IsJudgeSelect = true;
                    }
                }

            }
            if (arbitrationRule == ArbitrationRule.Reading)
            {
                //处理访视裁判标记
                foreach (var visitItem in resultExceptJudgeList.Where(t => t.ReadingCategory == ReadingCategory.Visit))
                {
                    //默认设置为false  只处理为true 和 空的情况
                    visitItem.IsJudgeSelect = false;

                    if (judegeList.Count > 0)
                    {

                        var maxFinishedJudge = judegeList.Where(t => t.ReadingTaskState == ReadingTaskState.HaveSigned).FirstOrDefault();

                        var maxNotFinishedJudge = judegeList.Where(t => t.ReadingTaskState != ReadingTaskState.HaveSigned).FirstOrDefault();

                        if (maxFinishedJudge == null && maxNotFinishedJudge != null)
                        {
                            //仅有一个未完成的全局裁判，那么都是null
                            if (visitItem.VisitTaskNum < maxNotFinishedJudge.VisitTaskNum)
                            {
                                visitItem.IsJudgeSelect = null;
                            }
                        }
                        else if (maxFinishedJudge != null && maxNotFinishedJudge == null)
                        {
                            //全局裁判都完成了，那么以最后一次裁判选择的为准

                            if (visitItem.ArmEnum == maxFinishedJudge.JudgeArmEnum && visitItem.VisitTaskNum < maxFinishedJudge.VisitTaskNum)
                            {
                                visitItem.IsJudgeSelect = true;
                                visitItem.JudgeNote = maxFinishedJudge.JudgeNote;
                            }
                        }
                        else
                        {
                            //两个都不为null  肯定是不同的裁判

                            //在完成裁判之后的，和未完成裁判之前的
                            if (/*visitItem.VisitTaskNum < maxNotFinishedJudge.VisitTaskNum &&*/ visitItem.VisitTaskNum > maxFinishedJudge.VisitTaskNum)
                            {
                                visitItem.IsJudgeSelect = null;
                            }
                            else if (visitItem.ArmEnum == maxFinishedJudge.JudgeArmEnum && visitItem.VisitTaskNum < maxFinishedJudge.VisitTaskNum)
                            {
                                visitItem.IsJudgeSelect = true;
                                visitItem.JudgeNote = maxFinishedJudge.JudgeNote;
                            }


                        }
                    }
                    else
                    {
                        //不存在裁判  将R1设置
                        if (visitItem.ArmEnum == Arm.DoubleReadingArm1)
                        {
                            visitItem.IsJudgeSelect = true;
                        }
                    }
                }
            }
            return resultExceptJudgeList;
        }



        /// <summary>
        /// 整体肿瘤评估  （目前仅仅 RECIST1.1   多个标准一个接口   Excel 列是一样的 ）
        /// </summary>
        /// <param name="inQuery"></param>
        /// <param name="_commonDocumentRepository"></param>
        /// <param name="_dictionaryService"></param>
        /// <param name="_trialRepository"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> GetOverallTumorEvaluationList_Export(VisitTaskQuery inQuery,
                [FromServices] IRepository<CommonDocument> _commonDocumentRepository,
                [FromServices] IDictionaryService _dictionaryService,
                [FromServices] IRepository<Trial> _trialRepository)
        {
            //每次查询必须是单标准的
            var criterion = await _readingQuestionCriterionTrialRepository.Where(t => t.Id == inQuery.TrialReadingCriterionId).Select(t => new { t.CriterionType, t.CriterionName, t.ArbitrationRule }).FirstNotNullAsync();

            if (criterion.CriterionType != CriterionType.RECIST1Point1
                && criterion.CriterionType != CriterionType.PCWG3
                && criterion.CriterionType != CriterionType.RECIST1Pointt1_MB
                && criterion.CriterionType != CriterionType.Lugano2014 /*&& criterion.CriterionType != CriterionType.Lugano2014WithoutPET*/
                && criterion.CriterionType != CriterionType.IRECIST1Point1)
            {
                //---当前标准导出还未支持
                throw new Exception(_localizer["ExcelExport_UnsupportedExport"]);
            }

            var list = await _visitTaskRepository.Where(t => t.TrialId == inQuery.TrialId && t.IsAnalysisCreate == false && t.TaskState == TaskState.Effect)

                //访视和全局查询已签名完成的，裁判可以是未签名，未完成的
                .Where(t => (t.ReadingTaskState == ReadingTaskState.HaveSigned && (t.ReadingCategory == ReadingCategory.Visit || t.ReadingCategory == ReadingCategory.Global)) || (t.ReadingCategory == ReadingCategory.Judge))
               //.WhereIf(inQuery.SubjectId != null, t => t.SubjectId == inQuery.SubjectId)
               //.WhereIf(inQuery.TaskState != null, t => t.TaskState == inQuery.TaskState)
               //.WhereIf(inQuery.IsSelfAnalysis != null, t => t.IsSelfAnalysis == inQuery.IsSelfAnalysis)

               .WhereIf(inQuery.TrialReadingCriterionId != null, t => t.TrialReadingCriterionId == inQuery.TrialReadingCriterionId)
               .WhereIf(inQuery.TrialSiteId != null, t => t.Subject.TrialSiteId == inQuery.TrialSiteId)

               .WhereIf(inQuery.IsUrgent != null, t => t.IsUrgent == inQuery.IsUrgent)
               .WhereIf(inQuery.DoctorUserId != null, t => t.DoctorUserId == inQuery.DoctorUserId)
               .WhereIf(inQuery.ReadingCategory != null, t => t.ReadingCategory == inQuery.ReadingCategory)
               .WhereIf(inQuery.ReadingTaskState != null, t => t.ReadingTaskState == inQuery.ReadingTaskState)
               .WhereIf(inQuery.TaskAllocationState != null, t => t.TaskAllocationState == inQuery.TaskAllocationState)
               .WhereIf(inQuery.ArmEnum != null, t => t.ArmEnum == inQuery.ArmEnum)
               .WhereIf(!string.IsNullOrEmpty(inQuery.TrialSiteCode), t => (t.BlindTrialSiteCode.Contains(inQuery.TrialSiteCode!) && t.IsAnalysisCreate) || (t.Subject.TrialSite.TrialSiteCode.Contains(inQuery.TrialSiteCode!) && t.IsAnalysisCreate == false))
               .WhereIf(!string.IsNullOrEmpty(inQuery.TaskName), t => t.TaskName.Contains(inQuery.TaskName) || t.TaskBlindName.Contains(inQuery.TaskName))
               .WhereIf(!string.IsNullOrEmpty(inQuery.SubjectCode), t => t.Subject.Code.Contains(inQuery.SubjectCode))
               .WhereIf(inQuery.BeginAllocateDate != null, t => t.AllocateTime > inQuery.BeginAllocateDate)
               .WhereIf(inQuery.EndAllocateDate != null, t => t.AllocateTime < inQuery.EndAllocateDate!.Value.AddDays(1))
               .ProjectTo<OverallTumorEvaluationExport>(_mapper.ConfigurationProvider, new { criterionType = criterion.CriterionType, arbitrationRule = criterion.ArbitrationRule, trialReadingCriterionId = inQuery.TrialReadingCriterionId }).ToListAsync();

            list = list.OrderBy(t => t.SubjectCode).ThenBy(t => t.ArmEnum).ThenBy(t => t.VisitTaskNum).ToList();

            var exportInfo = (await _trialRepository.Where(t => t.Id == inQuery.TrialId).IgnoreQueryFilters().ProjectTo<ExcelExportInfo>(_mapper.ConfigurationProvider).FirstOrDefaultAsync()).IfNullThrowException();
            exportInfo.CriterionName = criterion.CriterionName;

            //处理裁判标记
            list = DealJudgeMark(criterion.ArbitrationRule, list);

            exportInfo.List = ExportExcelConverterDate.ConvertToClientTimeInObject(list.Where(t => t.ReadingCategory != ReadingCategory.Global).ToList(), _userInfo.TimeZoneId);
            exportInfo.CurrentTime = ExportExcelConverterDate.DateTimeInternationalToString(DateTime.Now, _userInfo.TimeZoneId);



            return await ExcelExportHelper.DataExportAsync(StaticData.Export.OverallTumorEvaluation_Export, exportInfo, $"{exportInfo.ResearchProgramNo}_{exportInfo.CriterionName}", _commonDocumentRepository, _hostEnvironment, _dictionaryService, typeof(OverallTumorEvaluationExport), criterion.CriterionType);
       
        }

        /// <summary>
        /// 肿瘤疗效评估表   ( 目前仅仅 RECIST1.1)
        /// </summary>
        /// <param name="inQuery"></param>
        /// <param name="_commonDocumentRepository"></param>
        /// <param name="_dictionaryService"></param>
        /// <param name="_trialRepository"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        [HttpPost]
        public async Task<IActionResult> GetEvaluationOfTumorEfficacy_Export(VisitTaskQuery inQuery,
                [FromServices] IRepository<CommonDocument> _commonDocumentRepository,
                [FromServices] IDictionaryService _dictionaryService,
                [FromServices] IRepository<Trial> _trialRepository)
        {

            //每次查询必须是单标准的
            var criterion = await _readingQuestionCriterionTrialRepository.Where(t => t.Id == inQuery.TrialReadingCriterionId).Select(t => new { t.CriterionType, t.CriterionName, t.ArbitrationRule }).FirstOrDefaultAsync();

            var query = _visitTaskRepository.Where(t => t.TrialId == inQuery.TrialId && t.TaskState == TaskState.Effect && t.IsAnalysisCreate == false && t.ReadingTaskState == ReadingTaskState.HaveSigned)

               //.WhereIf(inQuery.SubjectId != null, t => t.SubjectId == inQuery.SubjectId)
               //.WhereIf(inQuery.TaskState != null, t => t.TaskState == inQuery.TaskState)
               //.WhereIf(inQuery.IsSelfAnalysis != null, t => t.IsSelfAnalysis == inQuery.IsSelfAnalysis)

               .WhereIf(inQuery.TrialReadingCriterionId != null, t => t.TrialReadingCriterionId == inQuery.TrialReadingCriterionId)
               .WhereIf(inQuery.TrialSiteId != null, t => t.Subject.TrialSiteId == inQuery.TrialSiteId)

               .WhereIf(inQuery.IsUrgent != null, t => t.IsUrgent == inQuery.IsUrgent)
               .WhereIf(inQuery.DoctorUserId != null, t => t.DoctorUserId == inQuery.DoctorUserId)
               .WhereIf(inQuery.ReadingCategory != null, t => t.ReadingCategory == inQuery.ReadingCategory)
               .WhereIf(inQuery.ReadingTaskState != null, t => t.ReadingTaskState == inQuery.ReadingTaskState)
               .WhereIf(inQuery.TaskAllocationState != null, t => t.TaskAllocationState == inQuery.TaskAllocationState)
               .WhereIf(inQuery.ArmEnum != null, t => t.ArmEnum == inQuery.ArmEnum)
               .WhereIf(!string.IsNullOrEmpty(inQuery.TrialSiteCode), t => (t.BlindTrialSiteCode.Contains(inQuery.TrialSiteCode!) && t.IsAnalysisCreate) || (t.Subject.TrialSite.TrialSiteCode.Contains(inQuery.TrialSiteCode!) && t.IsAnalysisCreate == false))
               .WhereIf(!string.IsNullOrEmpty(inQuery.TaskName), t => t.TaskName.Contains(inQuery.TaskName) || t.TaskBlindName.Contains(inQuery.TaskName))
               .WhereIf(!string.IsNullOrEmpty(inQuery.SubjectCode), t => t.Subject.Code.Contains(inQuery.SubjectCode))
               .WhereIf(inQuery.BeginAllocateDate != null, t => t.AllocateTime > inQuery.BeginAllocateDate)
               .WhereIf(inQuery.EndAllocateDate != null, t => t.AllocateTime < inQuery.EndAllocateDate!.Value.AddDays(1));

            var exportInfo = (await _trialRepository.Where(t => t.Id == inQuery.TrialId).IgnoreQueryFilters().ProjectTo<ExcelExportInfo>(_mapper.ConfigurationProvider).FirstOrDefaultAsync()).IfNullThrowException();
            exportInfo.CriterionName = criterion.CriterionName;

            if (criterion.CriterionType == CriterionType.RECIST1Point1 || criterion.CriterionType == CriterionType.RECIST1Pointt1_MB)
            {
                var list = await query.ProjectTo<RECIST1Point1EvaluationOfTumorEfficacyExport>(_mapper.ConfigurationProvider, new { criterionType = criterion.CriterionType, arbitrationRule = criterion.ArbitrationRule, trialReadingCriterionId = inQuery.TrialReadingCriterionId }).ToListAsync();

                list = list.OrderBy(t => t.SubjectCode).ThenBy(t => t.ArmEnum).ThenBy(t => t.VisitTaskNum).ToList();

                //处理裁判标记
                list = DealJudgeMark(criterion.ArbitrationRule, list);

                exportInfo.List = ExportExcelConverterDate.ConvertToClientTimeInObject(list.Where(t => t.ReadingCategory != ReadingCategory.Global).ToList(), _userInfo.TimeZoneId);
                exportInfo.CurrentTime = ExportExcelConverterDate.DateTimeInternationalToString(DateTime.Now, _userInfo.TimeZoneId);


                return await ExcelExportHelper.DataExportAsync(StaticData.Export.RECIST1Point1EvaluationOfTumorEfficacy_Export, exportInfo, $"{exportInfo.ResearchProgramNo}_{exportInfo.CriterionName}", _commonDocumentRepository, _hostEnvironment, _dictionaryService, typeof(RECIST1Point1EvaluationOfTumorEfficacyExport), criterion.CriterionType);
            }

            else if (criterion.CriterionType == CriterionType.Lugano2014 /*|| criterion.CriterionType == CriterionType.Lugano2014WithoutPET*/)
            {
                var list = await query.ProjectTo<Lugano2014EvaluationOfTumorEfficacyExport>(_mapper.ConfigurationProvider, new { criterionType = criterion.CriterionType, arbitrationRule = criterion.ArbitrationRule, trialReadingCriterionId = inQuery.TrialReadingCriterionId }).ToListAsync();

                list = list.OrderBy(t => t.SubjectCode).ThenBy(t => t.ArmEnum).ThenBy(t => t.VisitTaskNum).ToList();

                //处理裁判标记
                list = DealJudgeMark(criterion.ArbitrationRule, list);

                exportInfo.List = ExportExcelConverterDate.ConvertToClientTimeInObject(list.Where(t => t.ReadingCategory != ReadingCategory.Global).ToList(), _userInfo.TimeZoneId);
                exportInfo.CurrentTime = ExportExcelConverterDate.DateTimeInternationalToString(DateTime.Now, _userInfo.TimeZoneId);

                return await ExcelExportHelper.DataExportAsync(StaticData.Export.Lugano2014EvaluationOfTumorEfficacy_Export, exportInfo, $"{exportInfo.ResearchProgramNo}_{exportInfo.CriterionName}", _commonDocumentRepository, _hostEnvironment, _dictionaryService, typeof(Lugano2014EvaluationOfTumorEfficacyExport), criterion.CriterionType);

            }
            else if (criterion.CriterionType == CriterionType.IRECIST1Point1)
            {
                var list = await query.ProjectTo<IRECIST1Point1EvaluationOfTumorEfficacyExport>(_mapper.ConfigurationProvider, new { criterionType = criterion.CriterionType, arbitrationRule = criterion.ArbitrationRule, trialReadingCriterionId = inQuery.TrialReadingCriterionId }).ToListAsync();

                list = list.OrderBy(t => t.SubjectCode).ThenBy(t => t.ArmEnum).ThenBy(t => t.VisitTaskNum).ToList();

                //处理裁判标记
                list = DealJudgeMark(criterion.ArbitrationRule, list);

                exportInfo.List = ExportExcelConverterDate.ConvertToClientTimeInObject(list.Where(t => t.ReadingCategory != ReadingCategory.Global).ToList(), _userInfo.TimeZoneId);
                exportInfo.CurrentTime = ExportExcelConverterDate.DateTimeInternationalToString(DateTime.Now, _userInfo.TimeZoneId);

                return await ExcelExportHelper.DataExportAsync(StaticData.Export.IRECIST1Point1EvaluationOfTumorEfficacy_Export, exportInfo, $"{exportInfo.ResearchProgramNo}_{exportInfo.CriterionName}", _commonDocumentRepository, _hostEnvironment, _dictionaryService, typeof(IRECIST1Point1EvaluationOfTumorEfficacyExport), criterion.CriterionType);

            }

            else
            {
                //---当前标准导出还未支持
                throw new Exception(_localizer["ExcelExport_UnsupportedExport"]);
            }


        }


        /// <summary>
        /// 评估病灶明细表   (目前仅仅 RECIST1.1    RECIST1.1  PGW3 表都是不同的)
        /// </summary>
        /// <param name="inQuery"></param>
        /// <param name="_commonDocumentRepository"></param>
        /// <param name="_dictionaryService"></param>
        /// <param name="_trialRepository"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> GetDetailedOfEvaluatedLesion_Export(VisitTaskQuery inQuery,
                [FromServices] IRepository<CommonDocument> _commonDocumentRepository,
                [FromServices] IDictionaryService _dictionaryService,
                [FromServices] IRepository<Trial> _trialRepository)
        {

            //每次查询必须是单标准的
            var criterion = await _readingQuestionCriterionTrialRepository.Where(t => t.Id == inQuery.TrialReadingCriterionId).Select(t => new { t.CriterionType, t.CriterionName, t.ArbitrationRule }).FirstOrDefaultAsync();

            var query = _visitTaskRepository.Where(t => t.TrialId == inQuery.TrialId && t.TaskState == TaskState.Effect && t.IsAnalysisCreate == false && t.ReadingTaskState == ReadingTaskState.HaveSigned)

               .WhereIf(inQuery.TrialReadingCriterionId != null, t => t.TrialReadingCriterionId == inQuery.TrialReadingCriterionId)
               .WhereIf(inQuery.TrialSiteId != null, t => t.Subject.TrialSiteId == inQuery.TrialSiteId)

               .WhereIf(inQuery.IsUrgent != null, t => t.IsUrgent == inQuery.IsUrgent)
               .WhereIf(inQuery.DoctorUserId != null, t => t.DoctorUserId == inQuery.DoctorUserId)
               .WhereIf(inQuery.ReadingCategory != null, t => t.ReadingCategory == inQuery.ReadingCategory)
               .WhereIf(inQuery.ReadingTaskState != null, t => t.ReadingTaskState == inQuery.ReadingTaskState)
               .WhereIf(inQuery.TaskAllocationState != null, t => t.TaskAllocationState == inQuery.TaskAllocationState)
               .WhereIf(inQuery.ArmEnum != null, t => t.ArmEnum == inQuery.ArmEnum)
               .WhereIf(!string.IsNullOrEmpty(inQuery.TrialSiteCode), t => (t.BlindTrialSiteCode.Contains(inQuery.TrialSiteCode!) && t.IsAnalysisCreate) || (t.Subject.TrialSite.TrialSiteCode.Contains(inQuery.TrialSiteCode!) && t.IsAnalysisCreate == false))
               .WhereIf(!string.IsNullOrEmpty(inQuery.TaskName), t => t.TaskName.Contains(inQuery.TaskName) || t.TaskBlindName.Contains(inQuery.TaskName))
               .WhereIf(!string.IsNullOrEmpty(inQuery.SubjectCode), t => t.Subject.Code.Contains(inQuery.SubjectCode))
               .WhereIf(inQuery.BeginAllocateDate != null, t => t.AllocateTime > inQuery.BeginAllocateDate)
               .WhereIf(inQuery.EndAllocateDate != null, t => t.AllocateTime < inQuery.EndAllocateDate!.Value.AddDays(1));

            var exportInfo = (await _trialRepository.Where(t => t.Id == inQuery.TrialId).IgnoreQueryFilters().ProjectTo<ExcelExportInfo>(_mapper.ConfigurationProvider).FirstOrDefaultAsync()).IfNullThrowException();
            exportInfo.CriterionName = criterion.CriterionName;

            if (criterion.CriterionType == CriterionType.RECIST1Point1 || criterion.CriterionType == CriterionType.RECIST1Pointt1_MB)
            {
                var list = await query.ProjectTo<RECIST1Point1DetailedOfEvaluatedLesionExport>(_mapper.ConfigurationProvider, new { criterionType = criterion.CriterionType, arbitrationRule = criterion.ArbitrationRule, trialReadingCriterionId = inQuery.TrialReadingCriterionId, isEn_Us = _userInfo.IsEn_Us }).ToListAsync();

                list = list.OrderBy(t => t.SubjectCode).ThenBy(t => t.ArmEnum).ThenBy(t => t.VisitTaskNum).ToList();

                var exportList = list.SelectMany(c =>
                {

                    return c.LesionList.Select(u =>
                    {
                        var clone = c.Clone();
                        clone.LessionCode = u.LessionCode;
                        clone.LessionType = u.LessionType;
                        clone.BeforeTranslateLessionTypeValue = u.LessionType;

                        clone.IsLymph = u.IsLymph;

                        clone.LessionLocation = u.LessionLocation;
                        clone.LessionOrgan = u.LessionOrgan;
                        clone.BodyPartDescription = u.BodyPartDescription;

                        //clone.MeasurementResult = u.MeasurementResult;
                        clone.LongDiameter = u.LongDiameter;
                        clone.ShortDiameter = u.ShortDiameter;
                        clone.LessionState = u.LessionState;

                        return clone;
                    });
                }).ToList();

                //处理裁判标记
                list = DealJudgeMark(criterion.ArbitrationRule, list);
                exportInfo.List = ExportExcelConverterDate.ConvertToClientTimeInObject(exportList, _userInfo.TimeZoneId);
                exportInfo.CurrentTime = ExportExcelConverterDate.DateTimeInternationalToString(DateTime.Now, _userInfo.TimeZoneId);


                return await ExcelExportHelper.DataExportAsync(StaticData.Export.RECIST1Point1DetailedOfEvaluatedLesion_Export, exportInfo, $"{exportInfo.ResearchProgramNo}", _commonDocumentRepository, _hostEnvironment, _dictionaryService, typeof(RECIST1Point1DetailedOfEvaluatedLesionExport), criterion.CriterionType);


            }
            else if (criterion.CriterionType == CriterionType.PCWG3)
            {
                var list = await query.ProjectTo<PCWG3DetailedOfEvaluatedLesionExport>(_mapper.ConfigurationProvider, new { criterionType = criterion.CriterionType, arbitrationRule = criterion.ArbitrationRule, trialReadingCriterionId = inQuery.TrialReadingCriterionId, isEn_Us = _userInfo.IsEn_Us }).ToListAsync();


                var exportList = list.SelectMany(c =>
                {

                    return c.LesionList.Select(u =>
                    {
                        var clone = c.Clone();
                        clone.LessionCode = u.LessionCode;
                        clone.LessionType = u.LessionType;

                        clone.LessionOrgan = u.LessionOrgan;
                        clone.LessionLocation = u.LessionLocation;
                        clone.BodyPartDescription = u.BodyPartDescription;

                        clone.LessionState = u.LessionState;

                        return clone;
                    });
                }).ToList();

                //处理裁判标记
                list = DealJudgeMark(criterion.ArbitrationRule, list);

                exportInfo.List = ExportExcelConverterDate.ConvertToClientTimeInObject(exportList, _userInfo.TimeZoneId); ;
                exportInfo.CurrentTime = ExportExcelConverterDate.DateTimeInternationalToString(DateTime.Now, _userInfo.TimeZoneId);


                return await ExcelExportHelper.DataExportAsync(StaticData.Export.PCWG3Point1DetailedOfEvaluatedLesion_Export, exportInfo, $"{exportInfo.ResearchProgramNo}", _commonDocumentRepository, _hostEnvironment, _dictionaryService, typeof(PCWG3DetailedOfEvaluatedLesionExport), criterion.CriterionType);

            }

            else
            {
                //---当前标准导出还未支持
                throw new Exception(_localizer["ExcelExport_UnsupportedExport"]);
            }


        }




        #endregion

        #region 通用阅片结果导出
        [HttpPost]
        public async Task<IActionResult> GetCommonEvaluationList_Export(VisitTaskQuery inQuery,
        [FromServices] IRepository<CommonDocument> _commonDocumentRepository,
        [FromServices] IDictionaryService _dictionaryService,
        [FromServices] IRepository<Trial> _trialRepository)
        {
            //每次查询必须是单标准的
            var criterion = await _readingQuestionCriterionTrialRepository.Where(t => t.Id == inQuery.TrialReadingCriterionId).Select(t => new { t.CriterionType, t.CriterionName, t.ArbitrationRule }).FirstNotNullAsync();


            var list = await _visitTaskRepository.Where(t => t.TrialId == inQuery.TrialId && t.IsAnalysisCreate == false && t.TaskState == TaskState.Effect)

                //访视和全局查询已签名完成的，裁判可以是未签名，未完成的
                .Where(t => (t.ReadingTaskState == ReadingTaskState.HaveSigned && (t.ReadingCategory == ReadingCategory.Visit || t.ReadingCategory == ReadingCategory.Global)) || (t.ReadingCategory == ReadingCategory.Judge))
               //.WhereIf(inQuery.SubjectId != null, t => t.SubjectId == inQuery.SubjectId)
               //.WhereIf(inQuery.TaskState != null, t => t.TaskState == inQuery.TaskState)
               //.WhereIf(inQuery.IsSelfAnalysis != null, t => t.IsSelfAnalysis == inQuery.IsSelfAnalysis)

               .WhereIf(inQuery.TrialReadingCriterionId != null, t => t.TrialReadingCriterionId == inQuery.TrialReadingCriterionId)
               .WhereIf(inQuery.TrialSiteId != null, t => t.Subject.TrialSiteId == inQuery.TrialSiteId)

               .WhereIf(inQuery.IsUrgent != null, t => t.IsUrgent == inQuery.IsUrgent)
               .WhereIf(inQuery.DoctorUserId != null, t => t.DoctorUserId == inQuery.DoctorUserId)
               .WhereIf(inQuery.ReadingCategory != null, t => t.ReadingCategory == inQuery.ReadingCategory)
               .WhereIf(inQuery.ReadingTaskState != null, t => t.ReadingTaskState == inQuery.ReadingTaskState)
               .WhereIf(inQuery.TaskAllocationState != null, t => t.TaskAllocationState == inQuery.TaskAllocationState)
               .WhereIf(inQuery.ArmEnum != null, t => t.ArmEnum == inQuery.ArmEnum)
               .WhereIf(!string.IsNullOrEmpty(inQuery.TrialSiteCode), t => (t.BlindTrialSiteCode.Contains(inQuery.TrialSiteCode!) && t.IsAnalysisCreate) || (t.Subject.TrialSite.TrialSiteCode.Contains(inQuery.TrialSiteCode!) && t.IsAnalysisCreate == false))
               .WhereIf(!string.IsNullOrEmpty(inQuery.TaskName), t => t.TaskName.Contains(inQuery.TaskName) || t.TaskBlindName.Contains(inQuery.TaskName))
               .WhereIf(!string.IsNullOrEmpty(inQuery.SubjectCode), t => t.Subject.Code.Contains(inQuery.SubjectCode))
               .WhereIf(inQuery.BeginAllocateDate != null, t => t.AllocateTime > inQuery.BeginAllocateDate)
               .WhereIf(inQuery.EndAllocateDate != null, t => t.AllocateTime < inQuery.EndAllocateDate!.Value.AddDays(1))
               .ProjectTo<CommonEvaluationExport>(_mapper.ConfigurationProvider, new { criterionType = criterion.CriterionType, arbitrationRule = criterion.ArbitrationRule, trialReadingCriterionId = inQuery.TrialReadingCriterionId, isEn_Us = _userInfo.IsEn_Us }).ToListAsync();

            list = list.OrderBy(t => t.SubjectCode).ThenBy(t => t.ArmEnum).ThenBy(t => t.VisitTaskNum).ToList();

            var exportInfo = (await _trialRepository.Where(t => t.Id == inQuery.TrialId).IgnoreQueryFilters().ProjectTo<ExcelExportInfo>(_mapper.ConfigurationProvider).FirstOrDefaultAsync()).IfNullThrowException();
            exportInfo.CriterionName = criterion.CriterionName;

            //处理裁判标记
            list = DealJudgeMark(criterion.ArbitrationRule, list);

            exportInfo.List = ExportExcelConverterDate.ConvertToClientTimeInObject(list.Where(t => t.ReadingCategory != ReadingCategory.Global).ToList(), _userInfo.TimeZoneId);
            exportInfo.CurrentTime = ExportExcelConverterDate.DateTimeInternationalToString(DateTime.Now, _userInfo.TimeZoneId);

            var dynamicColumnConfig = new DynamicColumnConfig() { AutoColumnTitleRowIndex = 2, AutoColumnStartIndex = 6,
                TempalteLastColumnIndex = 8,
                DynamicItemDicName = "TranslateDicName",
                DynamicItemValueName = "QuestionValue",
                DynamicListName = "JudgeQuestionAnswerList",
                RemoveColunmIndexList = new List<int>() { 1, 7 },
                ColumnNameList = list.FirstOrDefault()?.JudgeQuestionAnswerList.Select(t => t.QuestionName).ToList() ?? new List<string>(),
                TranslateDicNameList = list.FirstOrDefault()?.JudgeQuestionAnswerList.Select(t => t.TranslateDicName).ToList() ?? new List<string>()
            };

            var (memoryStream, fileName) = await ExcelExportHelper.DataExport_NpoiTestAsync(StaticData.Export.CommonReading_Export, exportInfo, _commonDocumentRepository, _hostEnvironment, _dictionaryService, typeof(CommonEvaluationExport), criterion.CriterionType, dynamicColumnConfig);


            #region 废弃
            //var isEn_US = CultureInfo.CurrentCulture.Name == StaticData.CultureInfo.en_US;
            //var dynamicTranslateDataList = await _dictionaryService.GetBasicDataSelect(list.FirstOrDefault()?.JudgeQuestionAnswerList.Select(t => t.JudgeTranslateDicName).Distinct().ToArray());


            //// 使用NPOI  进行二次处理
            //var wb = new XSSFWorkbook(memoryStream);

            //var sheet = wb.GetSheetAt(0);

            //foreach (var itemResult in list)
            //{
            //    var index = list.IndexOf(itemResult);

            //    //从第四行开始处理动态列
            //    var row = sheet.GetRow(index + 3);

            //    foreach (var item in itemResult.JudgeQuestionAnswerList)
            //    {
            //        var writeIndex = itemResult.JudgeQuestionAnswerList.IndexOf(item) + dynamicColumnConfig.AutoColumnStartIndex;


            //        if (item.JudgeTranslateDicName.IsNotNullOrEmpty())
            //        {

            //            var translateData = dynamicTranslateDataList[item.JudgeTranslateDicName].Where(t => t.Code.ToLower() == item.JudgeQuestionValue?.ToLower()).Select(t => isEn_US ? t.Value : t.ValueCN).FirstOrDefault() ?? String.Empty;

            //            row.GetCell(writeIndex).SetCellValue(translateData);
            //        }
            //        else
            //        {
            //            row.GetCell(writeIndex).SetCellValue(item.JudgeQuestionValue);

            //        }

            //    }
            //}

            //var memoryStream2 = new MemoryStream();
            //wb.Write(memoryStream2, true);
            //memoryStream2.Seek(0, SeekOrigin.Begin);
            #endregion

            return new FileStreamResult(memoryStream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
            {
                FileDownloadName = $"{exportInfo.ResearchProgramNo}_{exportInfo.CriterionName}_{fileName}_{DateTime.Now.ToString("yyyyMMddHHmmss")}.xlsx"
            };
        }

        /// <summary>
        /// 裁判阅片明细表
        /// </summary>
        /// <param name="inQuery"></param>
        /// <param name="_commonDocumentRepository"></param>
        /// <param name="_dictionaryService"></param>
        /// <param name="_trialRepository"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> GetCommonJudgeEvaluationList_Export(VisitTaskQuery inQuery,
            [FromServices] IRepository<CommonDocument> _commonDocumentRepository,
            [FromServices] IDictionaryService _dictionaryService,
            [FromServices] IRepository<Trial> _trialRepository)
        {
            //每次查询必须是单标准的
            var criterion = await _readingQuestionCriterionTrialRepository.Where(t => t.Id == inQuery.TrialReadingCriterionId).Select(t => new { t.CriterionType, t.CriterionName, t.ArbitrationRule }).FirstNotNullAsync();


            var list = await _visitTaskRepository.Where(t => t.TrialId == inQuery.TrialId && t.IsAnalysisCreate == false && t.TaskState == TaskState.Effect)

                //访视和全局查询已签名完成的，裁判可以是未签名，未完成的
                .Where(t => (t.ReadingTaskState == ReadingTaskState.HaveSigned && (t.ReadingCategory == ReadingCategory.Visit || t.ReadingCategory == ReadingCategory.Global)) || (t.ReadingCategory == ReadingCategory.Judge))
               //.WhereIf(inQuery.SubjectId != null, t => t.SubjectId == inQuery.SubjectId)
               //.WhereIf(inQuery.TaskState != null, t => t.TaskState == inQuery.TaskState)
               //.WhereIf(inQuery.IsSelfAnalysis != null, t => t.IsSelfAnalysis == inQuery.IsSelfAnalysis)

               .WhereIf(inQuery.TrialReadingCriterionId != null, t => t.TrialReadingCriterionId == inQuery.TrialReadingCriterionId)
               .WhereIf(inQuery.TrialSiteId != null, t => t.Subject.TrialSiteId == inQuery.TrialSiteId)

               .WhereIf(inQuery.IsUrgent != null, t => t.IsUrgent == inQuery.IsUrgent)
               .WhereIf(inQuery.DoctorUserId != null, t => t.DoctorUserId == inQuery.DoctorUserId)
               .WhereIf(inQuery.ReadingCategory != null, t => t.ReadingCategory == inQuery.ReadingCategory)
               .WhereIf(inQuery.ReadingTaskState != null, t => t.ReadingTaskState == inQuery.ReadingTaskState)
               .WhereIf(inQuery.TaskAllocationState != null, t => t.TaskAllocationState == inQuery.TaskAllocationState)
               .WhereIf(inQuery.ArmEnum != null, t => t.ArmEnum == inQuery.ArmEnum)
               .WhereIf(!string.IsNullOrEmpty(inQuery.TrialSiteCode), t => (t.BlindTrialSiteCode.Contains(inQuery.TrialSiteCode!) && t.IsAnalysisCreate) || (t.Subject.TrialSite.TrialSiteCode.Contains(inQuery.TrialSiteCode!) && t.IsAnalysisCreate == false))
               .WhereIf(!string.IsNullOrEmpty(inQuery.TaskName), t => t.TaskName.Contains(inQuery.TaskName) || t.TaskBlindName.Contains(inQuery.TaskName))
               .WhereIf(!string.IsNullOrEmpty(inQuery.SubjectCode), t => t.Subject.Code.Contains(inQuery.SubjectCode))
               .WhereIf(inQuery.BeginAllocateDate != null, t => t.AllocateTime > inQuery.BeginAllocateDate)
               .WhereIf(inQuery.EndAllocateDate != null, t => t.AllocateTime < inQuery.EndAllocateDate!.Value.AddDays(1))
               .ProjectTo<CommonEvaluationExport>(_mapper.ConfigurationProvider, new { criterionType = criterion.CriterionType, arbitrationRule = criterion.ArbitrationRule, trialReadingCriterionId = inQuery.TrialReadingCriterionId, isEn_Us = _userInfo.IsEn_Us }).ToListAsync();

            list = list.OrderBy(t => t.SubjectCode).ThenBy(t => t.ArmEnum).ThenBy(t => t.VisitTaskNum).ToList();

            //R1 R2 两个人的访视都阅片完成了才可以，去除只有一个人阅片完成的访视

            //找到只有一个人阅片的受试者 和访视
            var exceptVisit = list.GroupBy(t => new { t.SubjectCode, t.TaskName }).Where(g => g.Count() == 1).Select(g => new { g.Key.SubjectCode, g.Key.TaskName }).ToList();
            list = list.Where(t => !exceptVisit.Any(ev => ev.SubjectCode == t.SubjectCode && ev.TaskName == t.TaskName)).ToList();

            var exportInfo = (await _trialRepository.Where(t => t.Id == inQuery.TrialId).IgnoreQueryFilters().ProjectTo<ExcelExportInfo>(_mapper.ConfigurationProvider).FirstOrDefaultAsync()).IfNullThrowException();
            exportInfo.CriterionName = criterion.CriterionName;

            //处理裁判标记
            list = DealJudgeMark(criterion.ArbitrationRule, list);

            exportInfo.List = ExportExcelConverterDate.ConvertToClientTimeInObject(list.Where(t => t.ReadingCategory != ReadingCategory.Global).ToList(), _userInfo.TimeZoneId);
            exportInfo.CurrentTime = ExportExcelConverterDate.DateTimeInternationalToString(DateTime.Now, _userInfo.TimeZoneId);

            var dynamicColumnConfig = new DynamicColumnConfig() { AutoColumnTitleRowIndex = 2, AutoColumnStartIndex = 6, ColumnNameList = list.FirstOrDefault()?.JudgeQuestionAnswerList.Select(t => t.QuestionName).ToList() };

            var (memoryStream, fileName) = await ExcelExportHelper.DataExport_NpoiTestAsync(StaticData.Export.CommonJudgeReadingDetail_Export, exportInfo, _commonDocumentRepository, _hostEnvironment, _dictionaryService, typeof(CommonEvaluationExport), criterion.CriterionType, dynamicColumnConfig);


            return new FileStreamResult(memoryStream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
            {
                FileDownloadName = $"{exportInfo.ResearchProgramNo}_{exportInfo.CriterionName}_{fileName}_{DateTime.Now.ToString("yyyyMMddHHmmss")}.xlsx"
            };
        }
        /// <summary>
        /// 阅片结果明细表
        /// </summary>
        /// <param name="inQuery"></param>
        /// <param name="_commonDocumentRepository"></param>
        /// <param name="_dictionaryService"></param>
        /// <param name="_trialRepository"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> GetCommonEvaluationDetailList_Export(VisitTaskQuery inQuery,
       [FromServices] IRepository<CommonDocument> _commonDocumentRepository,
       [FromServices] IDictionaryService _dictionaryService,
       [FromServices] IRepository<Trial> _trialRepository)
        {
            //每次查询必须是单标准的
            var criterion = await _readingQuestionCriterionTrialRepository.Where(t => t.Id == inQuery.TrialReadingCriterionId).Select(t => new { t.CriterionType, t.CriterionName, t.ArbitrationRule }).FirstNotNullAsync();


            var list = await _visitTaskRepository.Where(t => t.TrialId == inQuery.TrialId && t.IsAnalysisCreate == false && t.TaskState == TaskState.Effect)

                //访视和全局查询已签名完成的，裁判可以是未签名，未完成的
                .Where(t => (t.ReadingTaskState == ReadingTaskState.HaveSigned && (t.ReadingCategory == ReadingCategory.Visit || t.ReadingCategory == ReadingCategory.Global)) || (t.ReadingCategory == ReadingCategory.Judge))
               //.WhereIf(inQuery.SubjectId != null, t => t.SubjectId == inQuery.SubjectId)
               //.WhereIf(inQuery.TaskState != null, t => t.TaskState == inQuery.TaskState)
               //.WhereIf(inQuery.IsSelfAnalysis != null, t => t.IsSelfAnalysis == inQuery.IsSelfAnalysis)

               .WhereIf(inQuery.TrialReadingCriterionId != null, t => t.TrialReadingCriterionId == inQuery.TrialReadingCriterionId)
               .WhereIf(inQuery.TrialSiteId != null, t => t.Subject.TrialSiteId == inQuery.TrialSiteId)

               .WhereIf(inQuery.IsUrgent != null, t => t.IsUrgent == inQuery.IsUrgent)
               .WhereIf(inQuery.DoctorUserId != null, t => t.DoctorUserId == inQuery.DoctorUserId)
               .WhereIf(inQuery.ReadingCategory != null, t => t.ReadingCategory == inQuery.ReadingCategory)
               .WhereIf(inQuery.ReadingTaskState != null, t => t.ReadingTaskState == inQuery.ReadingTaskState)
               .WhereIf(inQuery.TaskAllocationState != null, t => t.TaskAllocationState == inQuery.TaskAllocationState)
               .WhereIf(inQuery.ArmEnum != null, t => t.ArmEnum == inQuery.ArmEnum)
               .WhereIf(!string.IsNullOrEmpty(inQuery.TrialSiteCode), t => (t.BlindTrialSiteCode.Contains(inQuery.TrialSiteCode!) && t.IsAnalysisCreate) || (t.Subject.TrialSite.TrialSiteCode.Contains(inQuery.TrialSiteCode!) && t.IsAnalysisCreate == false))
               .WhereIf(!string.IsNullOrEmpty(inQuery.TaskName), t => t.TaskName.Contains(inQuery.TaskName) || t.TaskBlindName.Contains(inQuery.TaskName))
               .WhereIf(!string.IsNullOrEmpty(inQuery.SubjectCode), t => t.Subject.Code.Contains(inQuery.SubjectCode))
               .WhereIf(inQuery.BeginAllocateDate != null, t => t.AllocateTime > inQuery.BeginAllocateDate)
               .WhereIf(inQuery.EndAllocateDate != null, t => t.AllocateTime < inQuery.EndAllocateDate!.Value.AddDays(1))
               .ProjectTo<CommonEvaluationDetailExport>(_mapper.ConfigurationProvider, new { criterionType = criterion.CriterionType, arbitrationRule = criterion.ArbitrationRule, trialReadingCriterionId = inQuery.TrialReadingCriterionId, isEn_Us = _userInfo.IsEn_Us }).ToListAsync();

            list = list.OrderBy(t => t.SubjectCode).ThenBy(t => t.ArmEnum).ThenBy(t => t.VisitTaskNum).ToList();

            var exportInfo = (await _trialRepository.Where(t => t.Id == inQuery.TrialId).IgnoreQueryFilters().ProjectTo<ExcelExportInfo>(_mapper.ConfigurationProvider).FirstOrDefaultAsync()).IfNullThrowException();
            exportInfo.CriterionName = criterion.CriterionName;

            //处理裁判标记
            list = DealJudgeMark(criterion.ArbitrationRule, list);

            exportInfo.List = ExportExcelConverterDate.ConvertToClientTimeInObject(list.Where(t => t.ReadingCategory != ReadingCategory.Global).ToList(), _userInfo.TimeZoneId);
            exportInfo.CurrentTime = ExportExcelConverterDate.DateTimeInternationalToString(DateTime.Now, _userInfo.TimeZoneId);

            var dynamicColumnConfig = new DynamicColumnConfig() { AutoColumnTitleRowIndex = 2, AutoColumnStartIndex = 6, ColumnNameList = list.FirstOrDefault()?.QuestionAnswerList.Select(t => t.QuestionName).ToList() };

            var (memoryStream, fileName) = await ExcelExportHelper.DataExport_NpoiTestAsync(StaticData.Export.CommonReadingDetail_Export, exportInfo, _commonDocumentRepository, _hostEnvironment, _dictionaryService, typeof(CommonEvaluationExport), criterion.CriterionType, dynamicColumnConfig);


            return new FileStreamResult(memoryStream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
            {
                FileDownloadName = $"{exportInfo.ResearchProgramNo}_{exportInfo.CriterionName}_{fileName}_{DateTime.Now.ToString("yyyyMMddHHmmss")}.xlsx"
            };
        }


        [HttpPost]
        public async Task<IActionResult> GetCommonJudgeRatioList_Export(VisitTaskQuery inQuery,
        [FromServices] IRepository<CommonDocument> _commonDocumentRepository,
        [FromServices] IDictionaryService _dictionaryService,
        [FromServices] IRepository<Trial> _trialRepository)
        {
            //每次查询必须是单标准的
            var criterion = await _readingQuestionCriterionTrialRepository.Where(t => t.Id == inQuery.TrialReadingCriterionId).Select(t => new { t.CriterionType, t.CriterionName, t.ArbitrationRule }).FirstNotNullAsync();

         

            var trialReadingCriterionId = inQuery.TrialReadingCriterionId;
            Expression<Func<VisitTask, bool>> comonTaskFilter = u => u.TrialId == inQuery.TrialId && u.IsAnalysisCreate == false && u.TaskState == TaskState.Effect && u.TrialReadingCriterionId == trialReadingCriterionId;

            if (criterion.ArbitrationRule == ArbitrationRule.Visit)
            {

                var exportInfo = (await _trialRepository.Where(t => t.Id == inQuery.TrialId).IgnoreQueryFilters().ProjectTo<VisitJudgeExportInfo>(_mapper.ConfigurationProvider).FirstOrDefaultAsync()).IfNullThrowException();
                exportInfo.CriterionName = criterion.CriterionName;
                exportInfo.CurrentTime = ExportExcelConverterDate.DateTimeInternationalToString(DateTime.Now, _userInfo.TimeZoneId);


                //按照访视维度统计
                // 1、裁判量J：所有完成阅片的访视里面触发裁判的访视数；
                //2、完成阅片的病例数Q：R1,R2均完成阅片的访视数；

                exportInfo.VisitCount = _visitTaskRepository.Where(comonTaskFilter).Where(t => t.ReadingCategory == ReadingCategory.Visit && t.ReadingTaskState == ReadingTaskState.HaveSigned)
                    .GroupBy(t => new { t.SubjectId, t.DoctorUserId, t.SourceSubjectVisitId })
                    .Where(g => g.Count() == 2).Select(g => g.Key.SourceSubjectVisitId).Distinct().Count();

                exportInfo.JudgeVisitCount = _visitTaskRepository.Where(comonTaskFilter).Where(t => t.ReadingCategory == ReadingCategory.Judge && t.ReadingTaskState == ReadingTaskState.HaveSigned).Count();

                //3、裁判认同数M：触发裁判的受试者访视中，阅片人被裁判认同的访视数量；
                //4、总裁判数N：阅片人所阅的受试者访视中，触发裁判的访视数量；

                var doctorList = _visitTaskRepository.Where(comonTaskFilter).Where(t => t.ReadingCategory == ReadingCategory.Visit && t.ReadingTaskState == ReadingTaskState.HaveSigned)
                    .GroupBy(t => new { t.DoctorUserId, t.DoctorUser.UserName, t.DoctorUser.FullName })
                    .Select(g => new DoctorJudgeRatio()
                    {
                        DoctorUserId = g.Key.DoctorUserId,
                        UserName = g.Key.UserName,
                        FullName = g.Key.FullName,

                        //访视产生裁判的访视数量
                        TotalJudgeCount = g.Where(t => t.JudgeVisitTaskId != null && t.JudgeVisitTask.ReadingTaskState ==  ReadingTaskState.HaveSigned).Count(),

                        JudgeAgreeCount = g.Where(t => t.JudgeVisitTaskId != null && t.JudgeVisitTask.JudgeResultTaskId == t.Id).Count(),


                    });
             
                exportInfo.List = ExportExcelConverterDate.ConvertToClientTimeInObject(doctorList, _userInfo.TimeZoneId);

                return await ExcelExportHelper.DataExportAsync(StaticData.Export.VisitJudgeRatio_Export, exportInfo, $"{exportInfo.ResearchProgramNo}_{exportInfo.CriterionName}", _commonDocumentRepository, _hostEnvironment);


            }
            else if (criterion.ArbitrationRule == ArbitrationRule.Reading)
            {
                var exportInfo = (await _trialRepository.Where(t => t.Id == inQuery.TrialId).IgnoreQueryFilters().ProjectTo<ReadingPeriodJudgeExportInfo>(_mapper.ConfigurationProvider).FirstOrDefaultAsync()).IfNullThrowException();
                exportInfo.CriterionName = criterion.CriterionName;
                exportInfo.CurrentTime = ExportExcelConverterDate.DateTimeInternationalToString(DateTime.Now, _userInfo.TimeZoneId);


                #region 按照受试者维度统计
                //1、裁判量M：所有完成阅片病例（至少一个阅片期）里面触发裁判的受试者数量；
                //2、总样本量N：R1,R2均完成阅片（至少一个阅片期）的受试者数量；

                exportInfo.SubjectCount = _subjectRepository.Where(t => t.TrialId == inQuery.TrialId).Where(t =>
                  t.SubjectVisitTaskList.AsQueryable().Where(comonTaskFilter).Any(t => t.ReadingCategory == ReadingCategory.Global && t.ReadingTaskState == ReadingTaskState.HaveSigned)
                ).Count();

                exportInfo.judgeSubjectCount = _subjectRepository.Where(t => t.TrialId == inQuery.TrialId).Where(t =>
                  t.SubjectVisitTaskList.AsQueryable().Where(comonTaskFilter).Any(t => t.ReadingCategory == ReadingCategory.Global && t.ReadingTaskState == ReadingTaskState.HaveSigned)
                  && t.SubjectVisitTaskList.AsQueryable().Where(comonTaskFilter).Any(t => t.ReadingCategory == ReadingCategory.Judge)
                ).Count();

                var doctorList = _visitTaskRepository.Where(comonTaskFilter).Where(t => t.ReadingTaskState == ReadingTaskState.HaveSigned)
                    .GroupBy(t => new { t.DoctorUserId, t.DoctorUser.UserName, t.DoctorUser.FullName })
                    .Select(g => new DoctorJudgeRatio()
                    {
                        DoctorUserId = g.Key.DoctorUserId,
                        UserName = g.Key.UserName,
                        FullName = g.Key.FullName,

                        //触发裁判的受试者数量
                        TotalJudgeCount = g.Where(t => t.ReadingCategory == ReadingCategory.Global && t.JudgeVisitTaskId != null).Select(t => t.SubjectId).Distinct().Count(),

                        JudgeAgreeCount = g.Where(t => t.ReadingCategory == ReadingCategory.Global && t.JudgeVisitTaskId != null && t.JudgeVisitTask.JudgeResultTaskId == t.Id).Select(t => t.SubjectId).Distinct().Count(),

                    }).ToList();

                #endregion

                #region 按照阅片期维度统计
                //、裁判量J：所有完成阅片（R1和R2均完成）的阅片期里面触发裁判的阅片期数量；
                //2、总样本量Q：R1,R2均完成阅片的阅片期数量；

                exportInfo.ReadingPeriodCount = _visitTaskRepository.Where(comonTaskFilter).Where(t => t.ReadingCategory == ReadingCategory.Global && t.ReadingTaskState == ReadingTaskState.HaveSigned)
                    .GroupBy(t => new { t.SubjectId, t.DoctorUserId, t.SouceReadModuleId })
                    .Where(g => g.Count() == 2).Select(g => g.Key.SouceReadModuleId).Distinct().Count();

                exportInfo.judgeReadingPeriodCount = _visitTaskRepository.Where(comonTaskFilter).Where(t => t.ReadingCategory == ReadingCategory.Global && t.ReadingTaskState == ReadingTaskState.HaveSigned)
                   .GroupBy(t => new { t.SubjectId, t.DoctorUserId, t.SouceReadModuleId })
                   .Where(g => g.Count() == 2 && g.Any(c => c.JudgeVisitTaskId != null)).Select(g => g.Key.SouceReadModuleId).Distinct().Count();

                //3、裁判认同数J：触发裁判的阅片期中，阅片人被裁判认同的阅片期数量；
                //4、总裁判数Q：阅片人完成阅片的阅片期中，触发裁判的阅片期数量；

                var doctor2List = _visitTaskRepository.Where(comonTaskFilter).Where(t => t.ReadingTaskState == ReadingTaskState.HaveSigned)
                  .GroupBy(t => new { t.DoctorUserId, t.DoctorUser.UserName, t.DoctorUser.FullName })
                  .Where(g => g.Any(t => t.ReadingCategory == ReadingCategory.Global && t.JudgeVisitTaskId != null))
                  .Select(g => new DoctorJudgeRatio()
                  {
                      DoctorUserId = g.Key.DoctorUserId,
                      UserName = g.Key.UserName,
                      FullName = g.Key.FullName,

                      //触发裁判的阅片期的数量
                      TotalJudgeCount = g.Where(t => t.ReadingCategory == ReadingCategory.Judge && t.SouceReadModuleId != null).Select(t => t.SouceReadModuleId).Distinct().Count(),

                      JudgeAgreeCount = g.Where(t => t.ReadingCategory == ReadingCategory.Global && t.JudgeVisitTaskId != null && t.JudgeVisitTask.JudgeResultTaskId == t.Id)
                      .Select(t => t.SouceReadModuleId).Distinct().Count(),

                  }).ToList();

                #endregion

                exportInfo.DoctorSubjectStatList = doctorList;

                exportInfo.DoctorPeriodStatList = doctor2List;

                return await ExcelExportHelper.DataExportAsync(StaticData.Export.ReadingPeriodJudgeRatio_Export, exportInfo, $"{exportInfo.ResearchProgramNo}_{exportInfo.CriterionName}", _commonDocumentRepository, _hostEnvironment);



            }
            else
            {
                throw new Exception("不支持该配置的导出");
            }

        }

        #endregion
    }
}
