using ClosedXML.Excel;
using DocumentFormat.OpenXml.Spreadsheet;
using IRaCIS.Application.Contracts;
using IRaCIS.Core.API._ServiceExtensions.NewtonsoftJson;
using IRaCIS.Core.Application.Contracts;
using IRaCIS.Core.Application.Contracts.DTO;
using IRaCIS.Core.Application.Service.Reading.Dto;
using IRaCIS.Core.Application.ViewModel;
using IRaCIS.Core.Infra.EFCore.Common;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System.Reflection;
using System.Text;
using static IRaCIS.Core.Application.Service.ExcelExportHelper;
using IDictionaryService = IRaCIS.Application.Interfaces.IDictionaryService;
using TrialIdentityUser = IRaCIS.Core.Domain.Models.TrialIdentityUser;

namespace IRaCIS.Core.Application.Service.Common
{

    [ApiExplorerSettings(GroupName = "Common")]
    public class ExcelExportService(IRepository<TrialUserRole> _trialUserRoleRepository,
        IRepository<VisitTask> _visitTaskRepository,
        IRepository<Dictionary> _dictionaryRepository,
        IRepository<Internationalization> _internationalizationRepository,
        IRepository<ReadingQuestionCriterionTrial> _readingQuestionCriterionTrialRepository,
        IRepository<SystemDocNeedConfirmedUserType> _systemDocNeedConfirmedUserTypeRepository,
        IRepository<DicomStudy> _dicomStudyRepository,
        IRepository<QCChallenge> _qcChallengeRepository,
        IRepository<ReadModule> _readModuleRepository,
        IRepository<Trial> _trialRepository,
        IRepository<NoneDicomStudy> _noneDicomStudyRepository,
        IRepository<StudyMonitor> _studyMonitorRepository,
        IRepository<CommonDocument> _commonDocumentRepository,
        IRepository<SystemDocConfirmedIdentityUser> _systemDocConfirmedUserRepository,
        IRepository<TrialDocNeedConfirmedUserType> _trialDocNeedConfirmedUserTypeRepository,
        IRepository<TrialDocConfirmedIdentityUser> _trialDocConfirmedUserRepository,
        IRepository<Subject> _subjectRepository,
        IMapper _mapper, IUserInfo _userInfo, IStringLocalizer _localizer, IWebHostEnvironment _hostEnvironment) : BaseService
    {


        #region 中心调研导出

        [HttpPost]
        public async Task<IActionResult> GetTrialSiteSurveyList_Export(TrialSiteSurveyQueryDTO inQuery,
            [FromServices] IRepository<TrialSiteSurvey> _trialSiteSurveyRepository,
            [FromServices] IDictionaryService _dictionaryService)
        {
            var trialSiteSurveyQueryable = _trialSiteSurveyRepository.Where(t => t.TrialId == inQuery.TrialId).IgnoreQueryFilters()
             .WhereIf(inQuery.TrialSiteId != null, t => t.TrialSiteId == inQuery.TrialSiteId)
             .WhereIf(inQuery.IsDeleted != null, t => t.IsDeleted == inQuery.IsDeleted)
             .WhereIf(!string.IsNullOrWhiteSpace(inQuery.UserKeyInfo), t => t.UserName.Contains(inQuery.UserKeyInfo) || t.Phone.Contains(inQuery.UserKeyInfo) || t.Email.Contains(inQuery.UserKeyInfo))
             .WhereIf(inQuery.State != null, t => t.State == inQuery.State)
             .WhereIf(inQuery.UpdateTimeBegin != null, t => t.UpdateTime >= inQuery.UpdateTimeBegin)
             .WhereIf(inQuery.UpdateTimeEnd != null, t => t.UpdateTime <= inQuery.UpdateTimeEnd)

             .ProjectTo<TrialSiteSurveyView>(_mapper.ConfigurationProvider, new { isEn_Us = _userInfo.IsEn_Us })
              .WhereIf(!string.IsNullOrWhiteSpace(inQuery.PreliminaryUserName), t => t.PreliminaryUser.RealName.Contains(inQuery.PreliminaryUserName))
              .WhereIf(!string.IsNullOrWhiteSpace(inQuery.ReviewerUserName), t => t.ReviewerUser.RealName.Contains(inQuery.ReviewerUserName))
             ;

            //var defalutSortArray = new string[] { /*nameof(TrialSiteSurveyView.LanguageType) + " desc", nameof(TrialSiteSurveyView.ShowOrder)*/ };


            var list = await trialSiteSurveyQueryable.SortToListAsync(inQuery /*,defalutSortArray*/);

            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.TrialSiteSurvey_BasicInfo_Export, exportInfo, exportInfo.TrialCode, _commonDocumentRepository, _hostEnvironment, _dictionaryService, typeof(TrialSiteSurveyView));

        }


        /// <summary>
        /// 获取中心设备信息
        /// </summary>
        /// <param name="inQuery"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> GetSiteSurveyEquipmentList_Export(SiteSurveyEquipmentQuery inQuery,
             [FromServices] IRepository<TrialSiteEquipmentSurvey> _trialSiteEquipmentSurveyRepository,
             [FromServices] IRepository<TrialSiteSurvey> _trialSiteSurveyRepository,
            [FromServices] IDictionaryService _dictionaryService)
        {


            //找到该中心最新的调研记录
            var groupSelectIdQuery =
                _trialSiteSurveyRepository.Where(t => t.TrialId == inQuery.TrialId)
                    .WhereIf(inQuery.TrialSiteId != null, t => t.TrialSiteId == inQuery.TrialSiteId)
                    .GroupBy(t => t.TrialSiteId)
                    .Select(g => g.OrderByDescending(u => u.CreateTime).Select(t => t.Id).First());


            var query = _trialSiteEquipmentSurveyRepository.Where(t => t.TrialSiteSurvey.TrialId == inQuery.TrialId)
                .IgnoreQueryFilters().Where(t => groupSelectIdQuery.Contains(t.TrialSiteSurveyId))
                .WhereIf(inQuery.IsDeleted != null, t => t.TrialSiteSurvey.IsDeleted == inQuery.IsDeleted)
                .WhereIf(inQuery.State != null, t => t.TrialSiteSurvey.State == inQuery.State)
                .WhereIf(inQuery.TrialSiteId != null, t => t.TrialSiteSurvey.TrialSiteId == inQuery.TrialSiteId)
                .WhereIf(inQuery.TrialSiteCode.IsNotNullOrEmpty(), t => t.TrialSiteSurvey.TrialSite.TrialSiteCode.Contains(inQuery.TrialSiteCode))
                .WhereIf(inQuery.TrialSiteName.IsNotNullOrEmpty(), t => t.TrialSiteSurvey.TrialSite.TrialSiteAliasName.Contains(inQuery.TrialSiteName) ||
                 t.TrialSiteSurvey.TrialSite.TrialSiteName.Contains(inQuery.TrialSiteName))
                .ProjectTo<SiteSurveyEquipmentDto>(_mapper.ConfigurationProvider);

            var siteSurveryConfig = _trialRepository.Where(t => t.Id == inQuery.TrialId).Select(t => t.TrialExtraConfigJsonStr).FirstOrDefault() ?? string.Empty;

            var config = JsonConvert.DeserializeObject<TrialExtraConfig>(siteSurveryConfig) ?? new TrialExtraConfig();


            var fields = new List<(string FieldName, int excelIndex)>()
               {

                  ("Parameters", 9),
                  ("ManufacturerType", 10),
                  ("ScannerType", 11),
                  ("MagneticFieldStrengthType", 12),
                  ("BodyCoilChannelCount", 13),
                  ("HasDedicatedPdfFatQuantificationSequence", 14),
                  ("PdfFatQuantificationSequenceType", 15),
                  //("OtherSequenceSpecification", 15),
                  ("HasT2R2Correction", 16),
                  ("CanFullyExportPdfParameterMapsAndRawDicom", 17),
                  ("Note", 18),
               };


            var viewNameList = config.EquipmentControlFieldList.Where(t => t.IsView == true).Select(t => t.FiledName).ToList();

            var columnsToDelete = fields.Where(f => !viewNameList.Any(t => f.FieldName == t)).Select(f => f.excelIndex).Distinct().OrderByDescending(i => i).ToList();


            //var defalutSortArray = new string[] { /*nameof(TrialSiteSurveyView.LanguageType) + " desc", nameof(TrialSiteSurveyView.ShowOrder)*/ };


            var list = await query.SortToListAsync(inQuery /*,defalutSortArray*/);

            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.TrialSiteSurvey_Equipment_Export, exportInfo, exportInfo.TrialCode, _commonDocumentRepository, _hostEnvironment, _dictionaryService, typeof(SiteSurveyEquipmentDto), removeExcelIndexList: columnsToDelete);

        }

        /// <summary>
        /// 调研表基本信息
        /// </summary>
        /// <param name="inQuery"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> GetSiteSurveyInfoList_Export(SiteSurveyInfoQuery inQuery,
            [FromServices] IRepository<TrialSiteSurvey> _trialSiteSurveyRepository,
            [FromServices] IDictionaryService _dictionaryService)
        {

            //找到该中心最新的调研记录
            var groupSelectIdQuery =
                _trialSiteSurveyRepository.Where(t => t.TrialId == inQuery.TrialId)
                    .WhereIf(inQuery.TrialSiteId != null, t => t.TrialSiteId == inQuery.TrialSiteId)
                    .GroupBy(t => t.TrialSiteId)
                    .Select(g => g.OrderByDescending(u => u.CreateTime).Select(t => t.Id).First());

            var query = _trialSiteSurveyRepository.Where(t => t.TrialId == inQuery.TrialId).IgnoreQueryFilters()
                .Where(t => groupSelectIdQuery.Contains(t.Id))
                .WhereIf(inQuery.IsDeleted != null, t => t.IsDeleted == inQuery.IsDeleted)
                .WhereIf(inQuery.State != null, t => t.State == inQuery.State)
                .WhereIf(inQuery.TrialSiteId != null, t => t.TrialSiteId == inQuery.TrialSiteId)
                .WhereIf(inQuery.TrialSiteCode.IsNotNullOrEmpty(), t => t.TrialSite.TrialSiteCode.Contains(inQuery.TrialSiteCode))
                .WhereIf(inQuery.TrialSiteName.IsNotNullOrEmpty(), t => t.TrialSite.TrialSiteAliasName.Contains(inQuery.TrialSiteName) ||
                 t.TrialSite.TrialSiteName.Contains(inQuery.TrialSiteName))

                .ProjectTo<TrialSiteSurveyView>(_mapper.ConfigurationProvider);


            var siteSurveryConfig = _trialRepository.Where(t => t.Id == inQuery.TrialId).Select(t => t.TrialExtraConfigJsonStr).FirstOrDefault() ?? string.Empty;

            var config = JsonConvert.DeserializeObject<TrialExtraConfig>(siteSurveryConfig) ?? new TrialExtraConfig();


            var fields = new List<(string FieldName, int excelIndex)>()
                {

                   ("AverageEngravingCycle", 8),
                   ("IsRoutineMRIPDEE", 9),
                   ("MRIPDFFScanTime", 10),
                   ("MRIPDFFLeadTime", 11),
                   ("MRIPDFFOther", 12),
                   ("IsAuthorizeRadiologistsParticipate", 13),
                   ("AssignFixedTechnologists", 14),
                   ("IsConfirmImagingTechnologist", 15),
                   ("NotConfirmReson", 16),
                   ("EfficacyEvaluatorType", 17),

                   ("IsFollowStudyParameters", 18),
                   ("NotFollowReson", 19),
                   ("ISStrictManualBurnFlag", 20),
                   ("NotStrictManualBurnFlagReason",21)
                };


            //var viewNameList = config.NotShowFieldList;

            var columnsToDelete = fields.Where(f => config.NotShowFieldList.Any(t => f.FieldName == t)).Select(f => f.excelIndex).Distinct().OrderByDescending(i => i).ToList();


            //var defalutSortArray = new string[] { /*nameof(TrialSiteSurveyView.LanguageType) + " desc", nameof(TrialSiteSurveyView.ShowOrder)*/ };


            var list = await query.SortToListAsync(inQuery /*,defalutSortArray*/);

            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.TrialSiteSurvey_Info_Export, exportInfo, exportInfo.TrialCode, _commonDocumentRepository, _hostEnvironment, _dictionaryService, typeof(TrialSiteSurveyView), removeExcelIndexList: columnsToDelete);

        }

        #endregion

        /// <summary>
        /// 质控问题答案导出
        /// </summary>
        /// <param name="trialId"></param>
        /// <param name="_trialQCQuestionAnswerRepository"></param>
        /// <param name="_trialRepository"></param>
        /// <param name="_dictionaryService"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> GetTrialQCQuestionAnserList_Export(GetQCQuestionAnswerQuery inQuery,
            [FromServices] IRepository<TrialQCQuestionAnswer> _trialQCQuestionAnswerRepository,
            [FromServices] IRepository<Trial> _trialRepository,
             [FromServices] IRepository<UserRole> _userRoleRepository,
            [FromServices] IRepository<TrialQCQuestion> _trialQCQuestionRepository,
            [FromServices] IDictionaryService _dictionaryService)
        {
            //var query = from sv in _subjectVisitRepository.Where(t => t.TrialId == trialId && t.AuditState == AuditStateEnum.QCPassed)

            //            join u in _userRoleRepository.AsQueryable() on sv.UpdateUserId equals u.Id
            //            select new QCQuestionReusult_export()
            //            {
            //                TrialSiteCode = sv.TrialSite.TrialSiteCode,
            //                SubjectCode = sv.Subject.Code,
            //                VisitName = sv.VisitName,
            //                SubjectVisitId = sv.Id,

            //                CurrentQCEnum = qa.CurrentQCEnum,
            //                AuditTime = qa.UpdateTime,
            //                SecondReviewTime = qa.SecondReviewTime,
            //                AuditUserName = u.UserName,
            //                AuditUserFullName = u.FullName,
            //                QuesitonName = qa.TrialQCQuestionConfigure.QuestionName,

            //                ShowOrder = qa.TrialQCQuestionConfigure.ShowOrder,
            //                Answer = qa.Answer

            //            }

            var trialId = inQuery.TrialId;

            var query = from qa in _trialQCQuestionAnswerRepository.Where(t => t.TrialId == trialId && t.SubjectVisit.IsDeleted == false &&
               ((t.SubjectVisit.AuditState >= AuditStateEnum.PrimaryQCPassed && t.SecondReviewTime == null) ||
               (t.SubjectVisit.SecondReviewState == SecondReviewState.AuditPassed && t.SecondReviewTime <= t.SubjectVisit.Trial.QCQuestionConfirmedTime) ||
               (t.SubjectVisit.SecondReviewState == SecondReviewState.WaitAudit && t.SecondReviewTime < t.SubjectVisit.Trial.QCQuestionConfirmedTime)))
                        join u in _userRoleRepository.AsQueryable() on qa.UpdateUserId equals u.Id
                        select new QCQuestionAnswerResult_export()
                        {
                            SubjectVisitId = qa.SubjectVisitId,
                            SecondReviewTime = qa.SecondReviewTime,

                            VisitNum = qa.SubjectVisit.VisitNum,

                            TrialSiteCode = qa.SubjectVisit.TrialSite.TrialSiteCode,
                            SubjectCode = qa.SubjectVisit.Subject.Code,
                            VisitName = qa.SubjectVisit.VisitName,
                            CurrentQCEnum = qa.CurrentQCEnum,

                            AuditTime = qa.CurrentQCEnum == CurrentQC.First ? qa.SubjectVisit.PreliminaryAuditTime : (qa.CurrentQCEnum == CurrentQC.Second ? qa.SubjectVisit.ReviewAuditTime : qa.UpdateTime),
                            AuditUserName = qa.CurrentQCEnum == CurrentQC.First ? qa.SubjectVisit.PreliminaryAuditUser.UserName : (qa.CurrentQCEnum == CurrentQC.Second ? qa.SubjectVisit.ReviewAuditUser.UserName : u.UserName),
                            AuditUserFullName = qa.CurrentQCEnum == CurrentQC.First ? qa.SubjectVisit.PreliminaryAuditUser.FullName : (qa.CurrentQCEnum == CurrentQC.Second ? qa.SubjectVisit.ReviewAuditUser.FullName : u.FullName),

                            QuestionId = qa.TrialQCQuestionConfigure.Id,
                            QuesitonName = qa.TrialQCQuestionConfigure.QuestionName,
                            ShowOrder = qa.TrialQCQuestionConfigure.ShowOrder,
                            Answer = qa.Answer,


                        };

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

            var list = result.Where(t => t.AuditTime != null).GroupBy(t => new { t.SubjectVisitId, t.SecondReviewTime, t.TrialSiteCode, t.VisitNum, t.SubjectCode, t.VisitName, t.CurrentQCEnum })
                 .Select(g => new QCQuestionResult_Export()
                 {
                     TrialSiteCode = g.Key.TrialSiteCode,
                     SubjectCode = g.Key.SubjectCode,
                     VisitName = g.Key.VisitName,
                     CurrentQCEnum = g.Key.CurrentQCEnum,
                     VisitNum = g.Key.VisitNum,

                     AuditTime = g.Select(t => t.AuditTime).First(),
                     AuditUserName = g.Select(t => t.AuditUserName).First(),
                     AuditUserFullName = g.Select(t => t.AuditUserFullName).First(),

                     QuestionAnswerList = g.Select(t => new QCQuestionAnswerExport() { Answer = t.Answer, QuestionName = t.QuesitonName, ShowOrder = t.ShowOrder, QuestionId = t.QuestionId }).OrderBy(t => t.ShowOrder).ToList()


                 }).OrderBy(t => t.TrialSiteCode).ThenBy(t => t.SubjectCode).ThenBy(t => t.VisitNum).ThenBy(t => t.CurrentQCEnum).ThenBy(t => t.AuditTime).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);


            var columNameList = _trialQCQuestionRepository.Where(t => t.TrialId == trialId).OrderBy(t => t.ShowOrder).Select(t => new { t.QuestionName, t.Id }).ToList();


            var dynamicColumnConfig = new DynamicColumnConfig()
            {
                AutoColumnTitleRowIndex = 3, //2
                AutoColumnStartIndex = 8, //7
                TempalteLastColumnIndex = 7, //6
                DynamicItemDicName = "TranslateDicName",
                DynamicItemValueName = "Answer",
                DynamicItemTitleName = "QuestionName",
                DynamicListName = "QuestionAnswerList",
                DynamicItemTitleId = "QuestionId",
                RemoveColunmIndexList = new List<int>() { },
                ColumnIdNameList = columNameList.Select(t => new DynamicColumnConfig.ColumItem() { Id = t.Id, Name = t.QuestionName }).ToList(),
                TranslateDicNameList = new List<string>()
            };


            var (memoryStream, fileName) = await ExcelExportHelper.DataExport_ClosedXMLAsync(StaticData.Export.TrialQCResult_Export, exportInfo, _commonDocumentRepository, _hostEnvironment, _dictionaryService, typeof(QCQuestionResult_Export), dynamicColumnConfig: 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="inDto"></param>
        /// <param name="_readingMedicineSystemQuestionRepository"></param>
        /// <param name="_dictionaryService"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> GetReadingMedicineSystemQuestionList_Export(ReadingMedicineSystemQuestionQuery inDto,
           [FromServices] IRepository<ReadingMedicineSystemQuestion> _readingMedicineSystemQuestionRepository,
           [FromServices] IDictionaryService _dictionaryService)
        {
            //避免前端遍历 
            var criterionEnum = inDto.TrialReadingCriterionId != null ? _readingQuestionCriterionTrialRepository.Where(t => t.Id == inDto.TrialReadingCriterionId).Select(t => t.CriterionType).FirstOrDefault() : CriterionType.NoCriterion;

            var query = _readingMedicineSystemQuestionRepository.AsQueryable()
                  .WhereIf(!inDto.TypeValue.IsNullOrEmpty(), x => x.TypeValue.Contains(inDto.TypeValue))
                  .WhereIf(!inDto.ParentTriggerValue.IsNullOrEmpty(), x => x.ParentTriggerValue.Contains(inDto.ParentTriggerValue))
                  .WhereIf(!inDto.QuestionName.IsNullOrEmpty(), x => x.QuestionName.Contains(inDto.QuestionName))
                  .WhereIf(!inDto.Type.IsNullOrEmpty(), x => x.Type.Contains(inDto.Type))
                  .WhereIf(inDto.ReadingCategory != null, x => x.ReadingCategory == inDto.ReadingCategory)
                  .WhereIf(inDto.CurrentCriterionType != null, x => x.CriterionTypeEnum == null || x.CriterionTypeEnum == inDto.CurrentCriterionType)
                  .WhereIf(inDto.CriterionTypeEnum != null, x => x.CriterionTypeEnum == inDto.CriterionTypeEnum)
                  .WhereIf(inDto.TrialReadingCriterionId != null, x => x.CriterionTypeEnum == criterionEnum || x.IsGeneral == true)
                  .WhereIf(inDto.IsGeneral != null, x => x.IsGeneral == inDto.IsGeneral)
                .WhereIf(inDto.LanguageType != null, x => x.LanguageType == inDto.LanguageType!.Value)
                  .ProjectTo<ReadingMedicineSystemQuestionView>(_mapper.ConfigurationProvider).OrderBy(x => x.ShowOrder);

            var defalutSortArray = new string[] { nameof(ReadingMedicineSystemQuestionView.LanguageType) + " desc", nameof(ReadingMedicineSystemQuestionView.ShowOrder) };


            var list = await query.SortToListAsync(inDto);

            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.SystenMedicalQCQuestionsList_Export, exportInfo, exportInfo.TrialCode, _commonDocumentRepository, _hostEnvironment, _dictionaryService, typeof(ReadingMedicineSystemQuestionView));

        }


        /// <summary>
        /// 访视影像统计
        /// </summary>
        /// <param name="inQuery"></param>
        /// <param name="_subjectVisitRepository"></param>
        /// <param name="_trialRepository"></param>
        /// <param name="_dictionaryService"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> GetTrialVisitImageStatList_Export(TrialVisitImageQuery inQuery,
            [FromServices] IRepository<SubjectVisit> _subjectVisitRepository,
            [FromServices] IRepository<Trial> _trialRepository,
            [FromServices] IDictionaryService _dictionaryService)
        {
            var query = _subjectVisitRepository.Where(t => t.TrialId == inQuery.TrialId)
                  .WhereIf(inQuery.TrialSiteId != null, t => t.TrialSiteId == inQuery.TrialSiteId)
                  .WhereIf(inQuery.SubjectCode.IsNotNullOrEmpty(), t => t.Subject.Code.Contains(inQuery.SubjectCode))
                  .WhereIf(inQuery.BeginScanDate != null, t => t.LatestScanDate >= inQuery.BeginScanDate)
                  .WhereIf(inQuery.EndScanDate != null, t => t.LatestScanDate == inQuery.EndScanDate)
                  .Select(t => new TrialVisitImageStatView()
                  {
                      TrialId = t.TrialId,
                      SubjectVisitId = t.Id,
                      SubjectCode = t.Subject.Code,
                      TrialSiteCode = t.TrialSite.TrialSiteCode,
                      TrialSiteId = t.TrialSiteId,
                      VisitName = t.VisitName,
                      VisitNum = t.VisitNum,
                      EarliestScanDate = t.EarliestScanDate,
                      LatestScanDate = t.LatestScanDate,

                      IsHaveDicom = t.StudyList.Any(),

                      IsHaveNoneDicom = t.NoneDicomStudyList.Any(),


                      TotalStudyCount = t.StudyList.Count() + t.NoneDicomStudyList.Count(),

                      TotalImageCount = t.StudyList.Sum(t => t.InstanceCount) + t.NoneDicomStudyList.Sum(t => t.FileCount),

                      TotalImageSize = t.StudyList.SelectMany(t => t.InstanceList).Sum(t => t.FileSize) + t.NoneDicomStudyList.SelectMany(t => t.NoneDicomFileList).Sum(t => t.FileSize),

                  });


            var list = await query.Where(t => t.TotalImageCount > 0).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.TriaVisitImageStat_Export, exportInfo, exportInfo.TrialCode, _commonDocumentRepository, _hostEnvironment, _dictionaryService, typeof(TrialMaintenanceDTO));

        }




        /// <summary>
        /// 项目参与人员导出
        /// </summary>
        /// <param name="param"></param>
        /// <param name="_commonDocumentRepository"></param>
        /// <param name="_dictionaryService"></param>
        /// <param name="_trialRepository"></param>
        /// <param name="_trialUseRoleRepository"></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<TrialUserRole> _trialUseRoleRepository

            )
        {


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

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

                .WhereIf(param.IsDeleted != null, t => t.IsDeleted == param.IsDeleted)
                .WhereIf(!string.IsNullOrWhiteSpace(param.OrganizationName),
                    t => t.UserRole.IdentityUser.OrganizationName.Contains(param.OrganizationName))
                .WhereIf(!string.IsNullOrWhiteSpace(param.UserRealName),
                    t => (t.UserRole.FullName).Contains(param.UserRealName))
                .Select(t => new TrialMaintenanceDTO()
                {
                    UserRealName = t.UserRole.IdentityUser.FullName,
                    UserName = t.UserRole.IdentityUser.UserName,
                    UserType = t.UserRole.UserTypeRole.UserTypeShortName,
                    Phone = t.UserRole.IdentityUser.Phone,
                    EMail = t.UserRole.IdentityUser.EMail,
                    OrganizationName = t.UserRole.IdentityUser.OrganizationName,

                    IsDeleted = t.TrialUser.IsDeleted,
                    JoinTime = t.TrialUser.JoinTime,
                    RemoveTime = t.TrialUser.RemoveTime,

                    //角色授权禁用时间
                    RoleIsDeleted = t.IsDeleted,
                    CreateTime = t.CreateTime,
                    DeletedTime = t.DeletedTime,
                }).OrderBy(t => t.UserRealName)
                .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="_trialSiteUserRoleRepository"></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<TrialSiteUserRole> _trialSiteUserRoleRepository
            )
        {


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

            var list = await _trialSiteUserRoleRepository.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.UserRoleId)
                 .WhereIf(!string.IsNullOrWhiteSpace(param.UserKeyInfo), t => (t.UserRole.FullName).Contains(param.UserKeyInfo)
                     || t.UserRole.IdentityUser.UserName.Contains(param.UserKeyInfo) || t.UserRole.IdentityUser.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.TrialIdentityUserList.Any(t => t.IdentityUserId == _userInfo.IdentityUserId && t.IsDeleted == false
            && t.TrialUserRoleList.Any(t => t.UserId == _userInfo.UserRoleId && 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.TrialUserRoleList.Any(t => t.UserRole.IdentityUser.EMail.Contains(inQuery.PM_EMail) && (t.UserRole.UserTypeEnum == UserTypeEnum.ProjectManager || t.UserRole.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.UserRoleId)
                 .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.UserRoleId)
                 .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.UserRoleId)
                 .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.UserRoleId) && t.IsUrgent).Count() : 0,

                 CRC_CheckQuestionCount = isCRC ? t.SubjectVisitList.Where(c => c.TrialSite.CRCUserList.Any(u => u.UserId == _userInfo.UserRoleId))
                .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.UserRoleId)).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.UserRoleId && t.QCProcessEnum != TrialQCProcess.NotAudit && t.IsUrgent).Count() : 0,

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

                 //质疑待处理
                 IQC_QuestionToBeDealedCount = isIQC ? t.SubjectVisitList.SelectMany(c => c.QCChallengeList)
                .Where(u => u.CreateUserId == _userInfo.UserRoleId && 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.UserRoleId && 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.TrialUserRoleList.Where(t => t.UserRole.UserTypeEnum == UserTypeEnum.ProjectManager || t.UserRole.UserTypeEnum == UserTypeEnum.APM).OrderBy(t => t.UserRole.IdentityUser.EMail).Select(t => t.UserRole.IdentityUser.EMail).ToList() : null,

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


                 IR_UnReadCount = isIR ? t.VisitTaskList
                   .Where(c => c.DoctorUserId == _userInfo.UserRoleId && 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));

        }







        #region 导表查询

        /// <summary>
        /// 重传申请导表
        /// </summary>
        /// <param name="inQuery"></param>
        /// <param name="_subjectVisitImageBackRecordReposiotry"></param>
        /// <param name="_dictionaryService"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> GetImageBackList_Export(ImageBackQueryDto inQuery,
            [FromServices] IRepository<SubjectVisitImageBackRecord> _subjectVisitImageBackRecordReposiotry, [FromServices] IDictionaryService _dictionaryService)
        {
            var svExpression = QCCommon.GetSubjectVisitImageBackRecordFilter(inQuery.VisitPlanArray);

            var query = _subjectVisitImageBackRecordReposiotry.Where(t => t.SubjectVisit.TrialId == inQuery.TrialId)
                     .WhereIf(inQuery.TrialSiteId != null, t => t.SubjectVisit.TrialSiteId == inQuery.TrialSiteId)
                     .WhereIf(!string.IsNullOrEmpty(inQuery.SubjectCode), t => t.SubjectVisit.Subject.Code.Contains(inQuery.SubjectCode))
                      .WhereIf(!string.IsNullOrEmpty(inQuery.VisitName), t => t.SubjectVisit.VisitName.Contains(inQuery.VisitName))
                      .WhereIf(inQuery.VisitPlanArray != null && inQuery.VisitPlanArray?.Length > 0, svExpression)
                     .WhereIf(inQuery.CreateUserId != null, t => t.CreateUserId == inQuery.CreateUserId)
                     .WhereIf(inQuery.ApplyUserRole != null, t => t.ApplyUserRole == inQuery.ApplyUserRole)
                     .WhereIf(inQuery.ApplyBeginTime != null, t => t.CreateTime >= inQuery.ApplyBeginTime)
                     .WhereIf(inQuery.ApplyEndTime != null, t => t.CreateTime <= inQuery.ApplyEndTime)
                     .WhereIf(inQuery.ImageBackState != null, t => t.ImageBackState == inQuery.ImageBackState)
                     .WhereIf(inQuery.AuditBeginTime != null, t => t.AuditTime >= inQuery.AuditBeginTime)
                     .WhereIf(inQuery.AuditEndTime != null, t => t.AuditTime <= inQuery.AuditEndTime)
                     .ProjectTo<ImageBackViewModel>(_mapper.ConfigurationProvider);

            var defalutSortArray = new string[] { nameof(ImageBackViewModel.IsUrgent) + " desc", nameof(ImageBackViewModel.SubjectCode), nameof(ImageBackViewModel.VisitNum) };

            var list = await query.OrderByDescending(t => t.IsUrgent).ThenBy(t => t.SubjectCode).ThenBy(t => t.VisitNum).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.TrialImageBackRecordList_Export, exportInfo, $"{exportInfo.ResearchProgramNo}", _commonDocumentRepository, _hostEnvironment, _dictionaryService, typeof(ImageBackViewModel));

        }

        ///getSysDocumentConfirmList  系统文档培训查询
        ///
        [HttpPost]
        public async Task<IActionResult> GetSysDocumentConfirmList_Export(SystemDocQuery inQuery,
             [FromServices] IRepository<SystemDocument> _systemDocumentRepository,
             [FromServices] IRepository<IdentityUser> _identityUserRepository,
             [FromServices] IDictionaryService _dictionaryService)
        {
            var systemDocQuery =
               from sysDoc in _systemDocumentRepository.AsQueryable(false)
                                              .Where(t => inQuery.UserTypeId != null ? t.NeedConfirmedUserTypeList.Any(t => t.NeedConfirmUserTypeId == inQuery.UserTypeId) : true)
               from identityUser in _identityUserRepository.AsQueryable(false).Where(t => t.Status == UserStateEnum.Enable && t.UserRoleList.Where(t => t.IsUserRoleDisabled == false).Any(t => sysDoc.NeedConfirmedUserTypeList.AsQueryable().Any(c => c.NeedConfirmUserTypeId == t.UserTypeId)))
                  .Where(t => inQuery.UserId != null ? t.Id == inQuery.UserId : true)
                  .Where(t => inQuery.UserTypeId != null ? t.UserRoleList.Any(t => t.UserTypeId == inQuery.UserTypeId && t.IsUserRoleDisabled == false) : true)
               join confirm in _systemDocConfirmedUserRepository.Where() on new { ConfirmUserId = identityUser.Id, SystemDocumentId = sysDoc.Id } equals new { confirm.ConfirmUserId, confirm.SystemDocumentId } into cc
               from confirm in cc.DefaultIfEmpty()
               select new TrainingRecordExportDTO()
               {
                   IsSystemDoc = true,
                   Id = sysDoc.Id,
                   CreateTime = sysDoc.CreateTime,
                   IsDeleted = sysDoc.IsDeleted,
                   Name = sysDoc.Name,
                   FileType = _userInfo.IsEn_Us ? sysDoc.FileType.Value : sysDoc.FileType.ValueCN,
                   FileTypeId = sysDoc.FileTypeId,
                   //IsConfirmed = confirm.ConfirmTime != null,

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

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


                   //UpdateTime = sysDoc.UpdateTime,
                   //SignViewMinimumMinutes = sysDoc.SignViewMinimumMinutes,
                   //UserTypeId = trialUser.UserRole.UserTypeId,
                   //UserTypeShortName = trialUser.UserRole.UserTypeRole.UserTypeShortName,
                   //Path = sysDoc.Path,
                   //FullFilePath = sysDoc.Path
               };

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

            var list = await unionQuery.SortToListAsync(inQuery);

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

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

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

            var identityUserIdList = list.Select(t => t.ConfirmUserId).Distinct().ToList();


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

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

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

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

            foreach (var item in list)
            {

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

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


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


            #endregion

            var exportInfo = new ExcelExportInfo();

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



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


        }


        /// <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,
            [FromServices] IRepository<TrialDocument> _trialDocumentRepository,
           [FromServices] IRepository<TrialIdentityUser> _trialIdentityUserRepository,
           [FromServices] IRepository<SystemDocument> _systemDocumentRepository
            )
        {


            #region 导表新

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

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

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

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


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

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

                  };



            var systemDocQuery =
                 from sysDoc in _systemDocumentRepository.AsQueryable(false).Where(u => trialInfo.TrialFinishedTime != null ? u.CreateTime < trialInfo.TrialFinishedTime : true)
                 from trialUser in _trialIdentityUserRepository.AsQueryable(false).Where(t => t.TrialId == inQuery.TrialId
                       && t.TrialUserRoleList.Any(t => sysDoc.NeedConfirmedUserTypeList.AsQueryable().Any(c => c.NeedConfirmUserTypeId == t.UserRole.UserTypeId)))
                    .Where(t => inQuery.UserId != null ? t.IdentityUserId == inQuery.UserId : true)

                 join confirm in _systemDocConfirmedUserRepository.Where() on new { ConfirmUserId = trialUser.IdentityUserId, SystemDocumentId = sysDoc.Id } equals new { confirm.ConfirmUserId, confirm.SystemDocumentId } into cc
                 from confirm in cc.DefaultIfEmpty()
                 select new TrainingRecordExportDTO()
                 {
                     IsSystemDoc = true,

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

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

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

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

                 };

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

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

            #region 废弃
            //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 _trialUserRoleRepository.Where(t => t.TrialId == inQuery.TrialId)
            //                                                                  .WhereIf(inQuery.UserId != null, t => t.UserId == inQuery.UserId)
            //                                                                  .WhereIf(inQuery.UserTypeId != null, t => t.UserRole.UserTypeId == inQuery.UserTypeId)
            //                                    on trialDocumentNeedConfirmedUserType.NeedConfirmUserTypeId equals trialUser.UserRole.UserTypeId

            //                    join confirm in _trialDocConfirmedUserRepository.Where(t => t.TrialDocument.TrialId == inQuery.TrialId) on
            //                     new { trialUser.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.UserRole.FullName,
            //                        UserName = trialUser.UserRole.IdentityUser.UserName,
            //                        UserTypeId = trialUser.UserRole.UserTypeId,
            //                        UserTypeShortName = trialUser.UserRole.UserTypeRole.UserTypeShortName,

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



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

            //                     join trialUser in _trialUserRoleRepository.Where(t => t.TrialId == inQuery.TrialId)
            //                                                           .WhereIf(inQuery.UserId != null, t => t.UserId == inQuery.UserId)
            //                           on needConfirmEdUserType.NeedConfirmUserTypeId equals trialUser.UserRole.UserTypeId
            //                     join confirm in _systemDocConfirmedUserRepository.Where() on new { ConfirmUserId = trialUser.UserId, SystemDocumentId = needConfirmEdUserType.SystemDocumentId } equals new { confirm.ConfirmUserId, confirm.SystemDocumentId } into cc
            //                     from confirm in cc.DefaultIfEmpty()
            //                     select new 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.UserRole.FullName,
            //                         UserName = trialUser.UserRole.IdentityUser.UserName,
            //                         UserTypeId = trialUser.UserRole.UserTypeId,
            //                         UserTypeShortName = trialUser.UserRole.UserTypeRole.UserTypeShortName,

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

            //var unionQuery = trialDocQuery.Union(systemDocQuery)
            //    .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);

            #endregion

            var list = await unionQuery.ToListAsync();

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

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

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

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

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

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


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

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


            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.IsSubjectQuit == false || t.SubmitState >= SubmitStateEnum.ToSubmit)
                        .WhereIf(inQuery.SubjectStatus != null, t => t.Subject.Status == inQuery.SubjectStatus)
                       .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.UserRoleId))
                       .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)

                         .Where(t => t.Subject.IsSubjectQuit == false || t.AuditState > AuditStateEnum.ToAudit)
                          .WhereIf(inQuery.SubjectStatus != null, t => t.Subject.Status == inQuery.SubjectStatus)
                         .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.UserRoleId))

                .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.UserRoleId))
                 .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
                            }).OrderBy(t => t.VisitTaskNum).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_ClosedXMLAsync(StaticData.Export.TrialSubjectProgressList_Export, exportInfo, /*"", */_commonDocumentRepository, _hostEnvironment, _dictionaryService, typeof(SubjectProgressDto));


            // 使用 ClosedXML 进行二次处理
            using var workbook = new XLWorkbook(memoryStream);
            var worksheet = workbook.Worksheet(1);  // 获取第一个工作表，索引从1开始

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

                // ClosedXML 行索引从1开始，原来 NPOI 从0开始，所以 +1
                var row = worksheet.Row(index + 4 + 1);  // NPOI: index + 4, ClosedXML: +1 = index + 5


                foreach (var item in subject.TotalList)
                {
                    // 从第五列开始动态写（ClosedXML 列索引从1开始）
                    var visitIndex = subject.TotalList.IndexOf(item) + 4 + 1;  // NPOI: +4, ClosedXML: +1 = +5

                    var cell = row.Cell(visitIndex);

                    if (item.IsLostVisit == true)
                    {
                        //cell.CellStyle = sheet.GetRow(1).GetCell(7).CellStyle;

                        // 复制样式 - ClosedXML 需要先获取源样式，然后应用到目标单元格
                        var sourceCell = worksheet.Row(2).Cell(8);  // 原 NPOI: GetRow(1).GetCell(7) -> +1 转换

                        cell.Style = sourceCell.Style;

                    }
                    else
                    {
                        switch (item.ReadingStatus)
                        {
                            case ReadingStatusEnum.ImageNotSubmit:
                                cell.Style = worksheet.Row(2).Cell(2).Style; // NPOI: (1,1) -> ClosedXML: (2,2)

                                break;
                            case ReadingStatusEnum.ImageQuality:
                                cell.Style = worksheet.Row(2).Cell(3).Style; // (1,2) -> (2,3)
                                break;
                            case ReadingStatusEnum.ConsistencyCheck:
                                cell.Style = worksheet.Row(2).Cell(4).Style;  // (1,3) -> (2,4)
                                break;
                            case ReadingStatusEnum.TaskAllocate:
                                cell.Style = worksheet.Row(2).Cell(5).Style;// (1,4) -> (2,5)
                                break;
                            case ReadingStatusEnum.ImageReading:
                                cell.Style = worksheet.Row(2).Cell(6).Style;// (1,5) -> (2,6)
                                break;
                            case ReadingStatusEnum.ReadCompleted:
                                cell.Style = worksheet.Row(2).Cell(7).Style; // (1,6) -> (2,7)
                                break;

                            default:
                                break;
                        }
                    }



                    cell.SetValue(item.TaskName);
                }
            }

            // 保存到 MemoryStream
            var memoryStream2 = new MemoryStream();
            workbook.SaveAs(memoryStream2);
            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.UserRoleId))
                  //.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.CreateUserRole.IdentityUser.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.CreateUserRole.IdentityUser.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)

                                       .Where(t => t.Subject.IsSubjectQuit == false || t.SubjectVisit.CheckState >= CheckStateEnum.CVIng)

                    .WhereIf(_userInfo.UserTypeEnumInt == (int)UserTypeEnum.ClinicalResearchCoordinator || _userInfo.UserTypeEnumInt == (int)UserTypeEnum.CRA, t => t.Subject.TrialSite.CRCUserList.Any(t => t.UserId == _userInfo.UserRoleId))
                    .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

                        SubjectStatus = t.Subject.Status

                    });

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


            var nodeDicomStudyQuery = _noneDicomStudyRepository.Where(t => t.TrialId == studyQuery.TrialId)

                 .Where(t => t.Subject.IsSubjectQuit == false || t.SubjectVisit.CheckState >= CheckStateEnum.CVIng)

                .WhereIf(_userInfo.UserTypeEnumInt == (int)UserTypeEnum.ClinicalResearchCoordinator || _userInfo.UserTypeEnumInt == (int)UserTypeEnum.CRA, t => t.Subject.TrialSite.CRCUserList.Any(t => t.UserId == _userInfo.UserRoleId))
                 .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
                     SubjectStatus = t.Subject.Status
                 });



            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(t => t.Subject.IsSubjectQuit == false || t.CheckState >= CheckStateEnum.CVIng)

                        .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.UserRoleId))//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)

                .Where(t => t.Subject.IsSubjectQuit == false || t.ReadingTaskState >= ReadingTaskState.Reading)

                           .WhereIf(inQuery.IsEffect == true, t => t.TaskState == TaskState.Effect || t.TaskState == TaskState.Freeze)
             .WhereIf(inQuery.IsEffect == false, t => t.TaskState == TaskState.Adbandon || t.TaskState == TaskState.HaveReturned)

           .WhereIf(inQuery.TaskState != null, t => t.TaskState == inQuery.TaskState)
           .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(inQuery.ReReadingApplyState != null, t => t.ReReadingApplyState == inQuery.ReReadingApplyState)

            .WhereIf(inQuery.CompleteClinicalDataEnum == CompleteClinicalDataEnum.Complete, t => t.IsClinicalDataSign && t.IsNeedClinicalDataSign == true)
            .WhereIf(inQuery.CompleteClinicalDataEnum == CompleteClinicalDataEnum.NotComplete, t => t.IsClinicalDataSign == false && t.IsNeedClinicalDataSign == true)
            .WhereIf(inQuery.CompleteClinicalDataEnum == CompleteClinicalDataEnum.NA, t => t.IsNeedClinicalDataSign == false)
           .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.IsAnalysisCreate == false) || (t.BlindSubjectCode.Contains(inQuery.SubjectCode) && t.IsAnalysisCreate))
           .WhereIf(inQuery.BeginAllocateDate != null, t => t.AllocateTime > inQuery.BeginAllocateDate)
           .WhereIf(inQuery.EndAllocateDate != null, t => t.AllocateTime < inQuery.EndAllocateDate)
           .WhereIf(inQuery.BeginSignTime != null, t => t.SignTime > inQuery.BeginSignTime)
           .WhereIf(inQuery.EndSignTime != null, t => t.SignTime < inQuery.EndSignTime)
           .WhereIf(inQuery.RandomOrder != null, t => t.RandomOrder == inQuery.RandomOrder)
           .WhereIf(inQuery.IsRandomOrderList == true, t => (t.ReadingTaskState == ReadingTaskState.WaitReading || t.ReadingTaskState == ReadingTaskState.Reading) && t.TaskAllocationState == TaskAllocationState.Allocated)

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

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



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

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


            if (inQuery.IsRandomOrderList == true)
            {
                list = list.OrderBy(t => t.RandomOrder).ToList();

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

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

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

                exportInfo.List = ExportExcelConverterDate.ConvertToClientTimeInObject(list, _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();


            #region 处理翻译对话 by he wen tao

            Dictionary<string, string> i18NKeys = new Dictionary<string, string>()
           {
             { "Msg1","trials:medicalFeedback:message:msg1"},
             { "Msg2","trials:medicalFeedback:message:msg2"},
             { "Msg3","trials:medicalFeedback:message:msg3"},
             { "Msg4", "trials:medicalFeedback:message:msg4"},
             { "Msg5", "trials:medicalFeedback:message:msg5"},
             { "CloseReasonEnum", "trials:medicalFeedback:title:closeReasonEnum"},
             { "IsEndorse", "trials:medicalFeedback:title:isEndorse"},
             { "Reason", "trials:medicalFeedback:title:reason"},
             { "IsRequestReread", "trials:medicalFeedback:title:isRequestReread"},
            };

            var i18Values = i18NKeys.Select(x => x.Value).ToList();
            var i18nList = await _internationalizationRepository.Where(x => i18Values.Contains(x.Code))
                .Select(x => new
                {
                    Code = x.Code,
                    Value = _userInfo.IsEn_Us ? x.Value : x.ValueCN
                }).ToListAsync();

            List<string> dictionaryCodeList = new List<string>()
            {
                    "AuditAdvice",
                    "MedicalDialogCloseEnum",
                    "MedicalReviewDoctorUserIdea",
                    "YesOrNo",
            };

            var dictionadParents = await _dictionaryRepository.Where(x => dictionaryCodeList.Contains(x.Parent.Code))
              .Select(x => new
              {
                  ParentCode = x.Parent.Code,
                  Code = x.Code,
                  Value = _userInfo.IsEn_Us ? x.Value : x.ValueCN
              }).ToListAsync();

            JointMedicalReviewI18n i18N = new JointMedicalReviewI18n() { };
            foreach (var kv in i18NKeys)
            {
                PropertyInfo? pi = i18N.GetType().GetProperty(kv.Key);
                if (pi != null && pi.CanWrite)
                {
                    var value = i18nList.Where(x => x.Code == kv.Value).Select(x => x.Value).FirstOrDefault() ?? string.Empty;
                    object safeValue = Convert.ChangeType(value, pi.PropertyType);
                    pi.SetValue(i18N, safeValue);
                }
            }
            foreach (var item in dictionaryCodeList)
            {
                PropertyInfo? pi = i18N.GetType().GetProperty(item);
                if (pi != null && pi.CanWrite)
                {
                    var value = dictionadParents.Where(x => x.ParentCode == item).ToDictionary(x => x.Code, x => x.Value);
                    object safeValue = Convert.ChangeType(value, pi.PropertyType);
                    pi.SetValue(i18N, safeValue);
                }
            }


            foreach (var item in list)
            {
                foreach (var dialog in item.DialogList)
                {
                    dialog.ResultContent = JointMedicalReviewDialog(dialog, i18N);
                }
            }


            #endregion


            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="record"></param>
        /// <param name="i18NAndDic"></param>
        /// <returns></returns>
        private string JointMedicalReviewDialog(GetMedicalReviewDialogOutDto record, JointMedicalReviewI18n i18NAndDic)
        {
            StringBuilder str = new StringBuilder() { };
            var userTypes = new List<int>() { 14, 30 };

            // 这里userTypes.Contains(record.UserTypeEnumInt) 可以提出来 但是还是按照前端写吧 免得不好对照

            // v-if="[14, 30].includes(record.UserTypeEnumInt) && record.Questioning
            if (userTypes.Contains(record.UserTypeEnumInt) && record.Questioning.IsNotNullOrEmpty())
            {
                //   <!-- 您好，根据医学审核反馈，该阅片任务的评估有如下问题需要您确认或澄清： -->
                str.AppendLine(i18NAndDic.Msg1);

                str.AppendLine(record.Questioning);

                if (record.FileList.Count() > 0)
                {
                    str.AppendLine(i18NAndDic.Msg2);
                    record.FileList.ForEach(x =>
                    {
                        str.AppendLine(x.FileName);
                    });
                }

                str.AppendLine(i18NAndDic.Msg3);

                str.AppendLine(i18NAndDic.AuditAdvice[record.AuditAdviceEnum.GetEnumInt()]);

                str.AppendLine(i18NAndDic.Msg4);
            }

            //v-if="[14, 30].includes(record.UserTypeEnumInt) && record.MedicalDialogCloseEnum!== null"
            if (userTypes.Contains(record.UserTypeEnumInt) && record.MedicalDialogCloseEnum != null)
            {
                str.AppendLine(i18NAndDic.CloseReasonEnum + i18NAndDic.MedicalDialogCloseEnum[record.MedicalDialogCloseEnum.Value.GetEnumInt()]);
            }

            // v-if="[14, 30].includes(record.UserTypeEnumInt) && record.Content 
            if (userTypes.Contains(record.UserTypeEnumInt) && record.Content.IsNotNullOrEmpty())
            {
                str.AppendLine(record.Content);
            }

            //  v-if="[13].includes(record.UserTypeEnumInt)"

            if (13 == record.UserTypeEnumInt)
            {
                str.AppendLine(i18NAndDic.IsEndorse + i18NAndDic.MedicalReviewDoctorUserIdea[record.DoctorUserIdeaEnum.GetEnumInt()]);

                //  v-if="record.DoctorUserIdeaEnum===2"
                if ((int)record.DoctorUserIdeaEnum == 2)
                {
                    str.AppendLine(i18NAndDic.Reason + record.DisagreeReason);
                }

                // record.MedicalDialogCloseEnum!== null

                if (record.MedicalDialogCloseEnum != null)
                {
                    str.AppendLine(i18NAndDic.IsRequestReread + i18NAndDic.YesOrNo[record.IsApplyHeavyReading.ToString()]);
                }

                // v-if="record.FileList && record.FileList.length > 0"

                if (record.FileList.Count() > 0)
                {
                    record.FileList.ForEach(x =>
                    {
                        str.AppendLine(x.FileName);
                    });
                }
            }

            return str.ToString();

        }

        /// <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.CreateUserRole.IdentityUser.UserName.Contains(inQuery.Name) || t.CreateUserRole.FullName.Contains(inQuery.Name))
                  .WhereIf(inQuery.ImageType != null, t => t.ImageType == inQuery.ImageType)
                  .WhereIf(inQuery.UserType != null, t => t.CreateUserRole.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))
                 .WhereIf(inQuery.BeginCreateTime != null, t => t.CreateTime >= inQuery.BeginCreateTime)
                .WhereIf(inQuery.EndCreatTime != null, t => t.CreateTime <= inQuery.EndCreatTime)
                 .WhereIf(inQuery.BeginUpdateTime != null, t => t.UpdateTime >= inQuery.BeginUpdateTime)
                .WhereIf(inQuery.EndUpdateTime != null, t => t.UpdateTime <= inQuery.EndUpdateTime)
                .ProjectTo<InternationExportDTO>(_mapper.ConfigurationProvider);

            var list = await 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.Internationalization_Export, exportInfo, $"{exportInfo.ResearchProgramNo}", _commonDocumentRepository, _hostEnvironment, _dictionaryService, typeof(InternationExportDTO));

        }

        /// <summary>
        ///影像检查列表-患者为维度组织
        /// </summary>
        /// <param name="inQuery"></param>
        /// <param name="_patientRepository"></param>
        /// <param name="_dictionaryService"></param>
        /// <param name="_trialRepository"></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>
        /// 邮件导出
        /// </summary>
        /// <param name="inQuery"></param>
        /// <param name="_emailNoticeConfigrepository"></param>
        /// <param name="_dictionaryService"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> GetEmailNoticeConfigList_Export(EmailNoticeConfigQuery inQuery,
            [FromServices] IRepository<EmailNoticeConfig> _emailNoticeConfigrepository,
             [FromServices] IDictionaryService _dictionaryService)
        {
            var emailNoticeConfigQueryable = _emailNoticeConfigrepository
            //.WhereIf(inQuery.SystemLevel == null, t => t.SystemLevel == SysEmailLevel.not_sys)
            .WhereIf(inQuery.SystemLevel != null, t => t.SystemLevel == inQuery.SystemLevel)
            .WhereIf(inQuery.IsDistinguishCriteria != null, t => t.IsDistinguishCriteria == inQuery.IsDistinguishCriteria)
            .WhereIf(inQuery.CriterionTypeEnum != null, t => t.CriterionTypeList.Any(c => c == inQuery.CriterionTypeEnum))
            .WhereIf(inQuery.BusinessScenarioEnum != null, t => t.BusinessScenarioEnum == inQuery.BusinessScenarioEnum)
            .WhereIf(inQuery.IsReturnRequired != null, t => t.IsReturnRequired == inQuery.IsReturnRequired)
            .WhereIf(inQuery.IsEnable != null, t => t.IsEnable == inQuery.IsEnable)
            .ProjectTo<EmailNoticeConfigExportDto>(_mapper.ConfigurationProvider);

            var list = await emailNoticeConfigQueryable.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.EmailNoticeConfig_Export, exportInfo, $"{exportInfo.ResearchProgramNo}", _commonDocumentRepository, _hostEnvironment, _dictionaryService, typeof(EmailNoticeConfigExportDto));

        }
        #endregion

        #region 导表公用

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

            public string FileName { get; set; }

            public ExportResult ExportCatogory { get; set; }
        }


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

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

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

            //阅片结果
            CommonReading_Export = 1,

            //阅片结果明细
            CommonReadingDetail_Export = 2,

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

            //裁判阅片明细
            CommonJudgeReadingDetail_Export = 4,

            //访视一致率
            VisitJudgeRatio_Export = 5,

            //阅片期一致率
            ReadingPeriodJudgeRatio_Export = 6,

        }

        public List<T> DealOncologyResult<T>(IRepository<ReadingOncologyTaskInfo> _oncologyRepository, bool isOncology, List<T> list) where T : CommonEvaluationExport
        {
            if (isOncology)
            {

                var subjectIdList = list.Select(t => t.SubjectId).Distinct().ToList();

                //已阅片完的肿瘤学结果
                var oncologyResultList = _oncologyRepository.Where(t => subjectIdList.Contains(t.OncologyVisitTask.SubjectId)
                    && t.OncologyVisitTask.IsAnalysisCreate == false && t.OncologyVisitTask.ReadingTaskState == ReadingTaskState.HaveSigned && t.OncologyVisitTask.TaskState == TaskState.Effect)

                        .Select(t => new { t.OncologyVisitTask.SubjectId, OncologyVisitTaskNum = t.OncologyVisitTask.VisitTaskNum, OncologyUserName = t.OncologyVisitTask.DoctorUser.UserName, t.VisitTask.VisitTaskNum, t.VisitTaskId, t.EvaluationReason, t.EvaluationResult })
                        .ToList();

                foreach (var subjectOncologyResult in oncologyResultList.GroupBy(t => t.SubjectId))
                {
                    //最后已完成的肿瘤学任务号
                    var lastOncologyVisitTaskNum = subjectOncologyResult.OrderByDescending(t => t.OncologyVisitTaskNum).FirstOrDefault().OncologyVisitTaskNum;

                    //需要填充的肿瘤学结果
                    var subjectOncologyList = subjectOncologyResult.Where(t => t.OncologyVisitTaskNum == lastOncologyVisitTaskNum).ToList();


                    foreach (var subjectOncology in subjectOncologyList)
                    {

                        foreach (var item in list)
                        {
                            if (item.SubjectId == subjectOncology.SubjectId && item.VisitTaskNum == subjectOncology.VisitTaskNum)
                            {
                                item.OncologyReason = subjectOncology.EvaluationReason;
                                item.OncologyResult = subjectOncology.EvaluationResult;
                                item.OncologyUserName = subjectOncology.OncologyUserName;
                            }
                        }
                    }



                }


            }

            return list;
        }
        public List<T> DealJudgeMark<T>(ArbitrationRule arbitrationRule, bool isGlobalReading, IEnumerable<T> list) where T : CommonEvaluationExport
        {
            //处理访视任务的裁判标记
            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)
                {
                    var findJudge = judegeList.FirstOrDefault(t => t.SubjectCode == item.SubjectCode
                    && (t.VisitTaskNum - ReadingCommon.TaskNumDic[ReadingCategory.Judge]) == item.VisitTaskNum);

                    if (findJudge != null)
                    {
                        if (findJudge.ReadingTaskState == ReadingTaskState.HaveSigned)
                        {
                            item.IsJudgeSelect = findJudge.JudgeArmEnum == item.ArmEnum ? true : false;

                            item.JudgeNote = findJudge.JudgeArmEnum == item.ArmEnum ? findJudge.JudgeNote : string.Empty;
                        }
                        else
                        {
                            //默认也是null 其实不用赋值
                            item.IsJudgeSelect = null;
                        }
                    }
                    else
                    {

                        //两个人都做了
                        if (resultExceptJudgeList.Where(t => t.VisitTaskNum == item.VisitTaskNum && t.SubjectCode == item.SubjectCode).Select(t => t.ArmEnum).Distinct().Count() == 2)
                        {
                            //如果没有产生裁判，默认选择R1
                            if (item.ArmEnum == Arm.DoubleReadingArm1)
                            {
                                item.IsJudgeSelect = true;
                            }
                            else
                            {
                                item.IsJudgeSelect = false;
                            }
                        }
                        else
                        {
                            item.IsJudgeSelect = null;
                            item.IsTrigerJudge = null;
                        }



                    }
                }

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

                    var subjectJudgeList = judegeList.Where(t => t.SubjectCode == visitItem.SubjectCode).ToList();

                    //阅片期访视号
                    var subjectReadingPeriondVisitNumList = resultExceptJudgeList.Where(t => t.SubjectCode == visitItem.SubjectCode).FirstOrDefault()?.SubjectCriterionReadingPeriodVisitNumList;

                    //两个人完成最大得任务号(访视+全局)
                    var subjectMaxFinishedTaskNum = resultExceptJudgeList.Where(t => t.SubjectCode == visitItem.SubjectCode)
                       .GroupBy(t => t.VisitTaskNum).Where(g => g.Count() == 2).Select(g => g.Key).DefaultIfEmpty().Max();

                    var addReadingPeriodNum = isGlobalReading ? ReadingCommon.TaskNumDic[ReadingCategory.Global] : 0;

                    var finishedGlobalCount = 0;

                    //没有配置阅片期
                    if (subjectReadingPeriondVisitNumList == null)
                    {
                        finishedGlobalCount = 0;
                    }
                    else
                    {
                        //已完成的全局数量
                        finishedGlobalCount = resultExceptJudgeList.Where(t => t.SubjectCode == visitItem.SubjectCode && subjectReadingPeriondVisitNumList.Any(c => (c + addReadingPeriodNum) == t.VisitTaskNum)
                        /*&& t.ReadingCategory == ReadingCategory.Global*/)
                           .Select(t => new { t.VisitTaskNum, t.ArmEnum }).Distinct()
                          .GroupBy(t => t.VisitTaskNum).Where(g => g.Count() == 2).Select(g => g.Key).Count();
                    }


                    visitItem.IsJudgeSelect = null;
                    visitItem.IsTrigerJudge = null;

                    if (finishedGlobalCount != 0)
                    {
                        //最大的全局是否产生裁判

                        var subjectMaxFinishedGlobalTaskNum = resultExceptJudgeList.Where(t => t.SubjectCode == visitItem.SubjectCode && subjectReadingPeriondVisitNumList.Any(c => (c + addReadingPeriodNum) == t.VisitTaskNum)
                        /*&& t.ReadingCategory == ReadingCategory.Global*/)
                      .Select(t => new { t.VisitTaskNum, t.ArmEnum }).Distinct()
                      .GroupBy(t => t.VisitTaskNum).Where(g => g.Count() == 2).Select(g => g.Key).DefaultIfEmpty().Max();

                        //最大的完成的全局是否产生裁判
                        if (subjectJudgeList.Any(t => t.VisitTaskNum == (subjectMaxFinishedGlobalTaskNum + ReadingCommon.TaskNumDic[ReadingCategory.Judge])))
                        {

                            var maxJudge = subjectJudgeList.FirstOrDefault(t => t.VisitTaskNum == (subjectMaxFinishedGlobalTaskNum + ReadingCommon.TaskNumDic[ReadingCategory.Judge]));

                            //最大裁判完成了
                            if (maxJudge.ReadingTaskState == ReadingTaskState.HaveSigned)
                            {
                                if (visitItem.VisitTaskNum < maxJudge.VisitTaskNum)
                                {
                                    //触发裁判
                                    visitItem.IsTrigerJudge = true;

                                    if (visitItem.ArmEnum == maxJudge.JudgeArmEnum)
                                    {
                                        visitItem.IsJudgeSelect = true;
                                        visitItem.JudgeNote = maxJudge.JudgeNote;
                                    }
                                    //裁判没选择的人设置为false
                                    else
                                    {
                                        visitItem.IsJudgeSelect = false;
                                    }
                                }
                                else
                                {
                                    //后续访视  未知 默认都是null

                                }
                            }
                            else
                            {
                                //找到当前未阅最大裁判之前的已完成的最大裁判任务
                                var maxFinishedJudge = subjectJudgeList.Where(t => t.ReadingTaskState == ReadingTaskState.HaveSigned).OrderByDescending(t => t.VisitTaskNum).FirstOrDefault();

                                if (maxFinishedJudge == null)
                                {
                                    // 为空 裁判选择标记默认就是null  不用处理

                                    if (visitItem.VisitTaskNum < maxJudge.VisitTaskNum)
                                    {
                                        visitItem.IsTrigerJudge = true;
                                    }

                                }
                                else
                                {
                                    if (visitItem.VisitTaskNum < maxFinishedJudge.VisitTaskNum)
                                    {
                                        visitItem.IsTrigerJudge = true;

                                        if (visitItem.ArmEnum == maxFinishedJudge.JudgeArmEnum)
                                        {
                                            visitItem.IsJudgeSelect = true;
                                            visitItem.JudgeNote = maxFinishedJudge.JudgeNote;
                                        }
                                        //裁判没选择的人设置为false
                                        else
                                        {
                                            visitItem.IsJudgeSelect = false;
                                        }
                                    }
                                    else if (visitItem.VisitTaskNum > maxFinishedJudge.VisitTaskNum && visitItem.VisitTaskNum < maxJudge.VisitTaskNum)
                                    {
                                        //完成裁判 和未完成裁判之间的 裁判选择标记默认是null

                                        visitItem.IsTrigerJudge = true;
                                    }
                                    else
                                    {
                                        //在未完成全局裁判之后的访视  未知   默认都是null


                                    }

                                }

                            }


                        }
                        else
                        {
                            //最大的完成的全局未产生裁判

                            if (visitItem.VisitTaskNum <= subjectMaxFinishedGlobalTaskNum)
                            {
                                visitItem.IsTrigerJudge = false;

                                if (visitItem.ArmEnum == Arm.DoubleReadingArm1)
                                {
                                    visitItem.IsJudgeSelect = true;

                                }
                                else
                                {
                                    visitItem.IsJudgeSelect = false;
                                }
                            }
                            else
                            {
                                //未产生裁判的全局之后的访视 两个标记都是null (后续可能还有全局，但是全局两个人没做完)
                            }


                        }


                    }



                }
            }
            else
            {
                foreach (var visitItem in resultExceptJudgeList.Where(t => t.ReadingCategory == ReadingCategory.Visit))
                {
                    visitItem.IsJudgeSelect = null;
                    visitItem.IsTrigerJudge = null;
                }

            }
            return resultExceptJudgeList;
        }

        #endregion




        #region 通用阅片结果导出

        /// <summary>
        /// 一致性分析结果导出   7 8  分别是自身 和组件一致性
        /// </summary>
        /// <param name="inQuery"></param>
        /// <param name="_commonDocumentRepository"></param>
        /// <param name="_dictionaryService"></param>
        /// <param name="_trialRepository"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> GetAnalysisTaskList_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 query = _visitTaskRepository.Where(t => t.TrialId == inQuery.TrialId && t.TaskAllocationState == TaskAllocationState.Allocated && (t.TaskState == TaskState.Effect || t.TaskState == TaskState.Freeze))

                //一致性分析
                .WhereIf(inQuery.ReadingExportType == ExportResult.DetailedTableOfIntraReaderAnalysisResults, t => t.IsSelfAnalysis == true || t.IsSelfAnalysis == null)
                .WhereIf(inQuery.ReadingExportType == ExportResult.DetailedTableOfIntraReaderAnalysisResults, t => t.IsSelfAnalysis == null ? t.Subject.SubjectVisitTaskList.Any(u => u.IsSelfAnalysis == true && u.VisitTaskNum == t.VisitTaskNum && u.DoctorUserId == t.DoctorUserId && u.TrialReadingCriterionId == t.TrialReadingCriterionId) : true)
                .WhereIf(inQuery.ReadingExportType == ExportResult.DetailedTableOfInterReaderAnalysisResults, t => t.IsSelfAnalysis == false || t.IsSelfAnalysis == null)

               //访视和全局查询已签名完成的，裁判可以是未签名，未完成的
               .Where(t => (t.ReadingTaskState == ReadingTaskState.HaveSigned && (t.ReadingCategory == ReadingCategory.Visit || t.ReadingCategory == ReadingCategory.Global)) || t.ReadingCategory == ReadingCategory.Judge)
               .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);

            var list = await query.ProjectTo<AnalysisDynamicCommonExport>(_mapper.ConfigurationProvider,
                                     new
                                     {
                                         readingExportType = inQuery.ReadingExportType,
                                         criterionType = criterion.CriterionType,
                                         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;

            #region 处理系统标准存在疾病和整体肿瘤合并

            //如果是以合并后的找翻译字典，会少，所以必须放在前面
            var translateDicNameList = list.SelectMany(t => t.QuestionAnswerList).Where(t => t.TranslateDicName.IsNotNullOrEmpty()).Select(t => t.TranslateDicName).Distinct().ToList();

            //针对1.1 整体肿瘤评估 有的两列要合并一列
            if (criterion.CriterionType == CriterionType.RECIST1Point1 || criterion.CriterionType == CriterionType.RECIST1Pointt1_MB || criterion.CriterionType == CriterionType.IRECIST1Point1)
            {
                foreach (var item in list)
                {
                    //处理合并表头

                    var questionType = item.IsBaseline == true ? QuestionType.ExistDisease : QuestionType.Tumor;

                    var findItem = item.QuestionAnswerList.Where(t => t.QuestionType == questionType).FirstOrDefault();

                    if (findItem != null)
                    {
                        findItem.QuestionName = _userInfo.IsEn_Us ? "Overall Response" : "整体肿瘤评估";
                    }


                    if (item.IsBaseline == true)
                    {
                        item.QuestionAnswerList = item.QuestionAnswerList.Where(t => t.QuestionType != QuestionType.Tumor).ToList();
                    }
                    else
                    {
                        item.QuestionAnswerList = item.QuestionAnswerList.Where(t => t.QuestionType != QuestionType.ExistDisease).ToList();
                    }
                }
            }
            else if (criterion.CriterionType == CriterionType.Lugano2014 || criterion.CriterionType == CriterionType.Lugano2014WithoutPET)
            {

                foreach (var item in list)
                {
                    //处理合并表头

                    var questionType = item.IsBaseline == true ? QuestionType.ExistDisease : QuestionType.ImgOncology;

                    var findItem = item.QuestionAnswerList.Where(t => t.QuestionType == questionType).FirstOrDefault();

                    if (findItem != null)
                    {
                        findItem.QuestionName = _userInfo.IsEn_Us ? "Overall Response" : "整体肿瘤评估";
                    }

                    if (item.IsBaseline == true)
                    {
                        item.QuestionAnswerList = item.QuestionAnswerList.Where(t => t.QuestionType != QuestionType.ImgOncology).ToList();
                    }
                    else
                    {
                        item.QuestionAnswerList = item.QuestionAnswerList.Where(t => t.QuestionType != QuestionType.ExistDisease).ToList();
                    }
                }
            }
            else if (criterion.CriterionType == CriterionType.PCWG3)
            {

            }
            else if (criterion.CriterionType == CriterionType.SelfDefine)
            {
                //自定义的又问题名称重复  所以统一加上组名

                //有重复的就加，没有重复的就不加
                if (list.Any(t => t.QuestionAnswerList.Select(t => t.QuestionName).Count() != t.QuestionAnswerList.Select(t => t.QuestionName).Distinct().Count()))
                {
                    foreach (var item in list)
                    {
                        foreach (var qs in item.QuestionAnswerList)
                        {
                            qs.QuestionName = qs.Group + "_" + qs.QuestionName;
                        }
                    }
                }


            }

            #endregion

            var export_Template = StaticData.Export.TrialSelfAnalysisList_Export;

            #region 自身一致性分析和组间一致性分析

            if (inQuery.ReadingExportType == ExportResult.DetailedTableOfIntraReaderAnalysisResults)
            {
                //找到非一致性分析的任务
                var selfExportList = list.Where(t => t.IsSelfAnalysis == null).ToList();

                //处理一致性分析结果是否和原始阅片是否一致
                foreach (var item in selfExportList)
                {
                    //找到一致性分析的结果
                    var selfAnalysisTask = list.Where(t => t.IsSelfAnalysis == true && t.SubjectCode == item.SubjectCode && t.VisitTaskNum == item.VisitTaskNum && t.TaskName == t.TaskName && t.UserName == item.UserName).FirstOrDefault();

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

                    //处理再次阅片人的结果               
                    if (selfAnalysisTask != null)
                    {
                        var cloneQuestionAnswerList = selfAnalysisTask.QuestionAnswerList.Clone();

                        foreach (var qItem in cloneQuestionAnswerList)
                        {
                            qItem.QuestionName = qItem.QuestionName + $"{(_userInfo.IsEn_Us ? "(Again)" : "(再次)")}";
                        }

                        item.QuestionAnswerList = item.QuestionAnswerList.Union(cloneQuestionAnswerList).ToList();
                    }
                }

                list = selfExportList;
            }
            else
            {
                export_Template = StaticData.Export.TrialGroupAnalysisList_Export;

                var newList = new List<AnalysisDynamicCommonExport>();

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


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

                    var groupOtherTaskList = subjectVisitGroupList.Where(t => t.IsSelfAnalysis == false).ToList();

                    foreach (var subjectVisitTaskArm in subjectVisitGroupList.Where(t => t.IsSelfAnalysis == null).OrderBy(t => t.ArmEnum))
                    {
                        foreach (var otherTask in groupOtherTaskList)
                        {
                            //非一致性分析任务
                            var cloneObj = subjectVisitTaskArm.Clone();

                            var otherTaskQuestionAnserList = otherTask.QuestionAnswerList.Clone();

                            foreach (var qItem in otherTaskQuestionAnserList)
                            {
                                qItem.QuestionName = qItem.QuestionName + $"{(_userInfo.IsEn_Us ? "(Again)" : "(再次)")}";
                            }

                            //处理 再次阅片人，再次阅片人角色 两列
                            var addQuestionList = new List<CommonQuesionInfo>();

                            addQuestionList.Add(new CommonQuesionInfo() { QuestionName = _userInfo.IsEn_Us ? "Reviwer(Again)" : "阅片人(再次)", QuestionValue = otherTask.UserName });
                            addQuestionList.Add(new CommonQuesionInfo() { QuestionName = _userInfo.IsEn_Us ? "Reviwer Role(Again)" : "阅片人角色(再次)", QuestionValue = ((int)otherTask.ArmEnum).ToString(), TranslateDicName = "ArmEnum" });


                            cloneObj.QuestionAnswerList = cloneObj.QuestionAnswerList.Union(addQuestionList).Union(otherTaskQuestionAnserList).ToList();


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

                            newList.Add(cloneObj);
                        }
                    }
                }
                translateDicNameList.Add("ArmEnum");

                list = newList;

            }

            #endregion

            var columNameList = list.SelectMany(t => t.QuestionAnswerList).Where(t => t.QuestionName.IsNotNullOrEmpty()).Select(t => t.QuestionName).Distinct().ToList();

            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 = 3,   //2
                AutoColumnStartIndex = 6,      //5
                TempalteLastColumnIndex = 5,  //4

                DynamicItemDicName = "TranslateDicName",
                DynamicItemValueName = "QuestionValue",
                DynamicItemTitleName = "QuestionName",
                DynamicListName = "QuestionAnswerList",
                RemoveColunmIndexList = new List<int>() { },
                ColumnIdNameList = columNameList.Select(t => new DynamicColumnConfig.ColumItem() { Id = Guid.Empty, Name = t }).ToList(),
                TranslateDicNameList = translateDicNameList ?? new List<string>()
            };


            var (memoryStream, fileName) = await ExcelExportHelper.DataExport_ClosedXMLAsync(export_Template, exportInfo, _commonDocumentRepository, _hostEnvironment, _dictionaryService, typeof(AnalysisDynamicCommonExport), 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="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.CriterionGroup, t.CriterionName, t.ArbitrationRule, t.IsArbitrationReading }).FirstNotNullAsync();

            list.Add(new ExportDocumentDes() { Code = StaticData.Export.CommonReading_Export, ExportCatogory = ExportResult.TableOfAssessmentResults });

            list.Add(new ExportDocumentDes() { Code = StaticData.Export.CommonReadingDetail_Export, ExportCatogory = ExportResult.DetailedTableOfAssessmentResults });

            if (criterion.IsArbitrationReading)
            {
                //仲裁阅片 才有裁判阅片明细表  同时要把模板里面的三列给去掉
                list.Add(new ExportDocumentDes() { Code = StaticData.Export.CommonJudgeReadingDetail_Export, ExportCatogory = ExportResult.DetailedTableOfAdjudicationResults });

            }

            if (criterion.CriterionGroup == CriterionGroup.Tumor)
            {
                list.Add(new ExportDocumentDes() { Code = StaticData.Export.ReadingLession_Export, ExportCatogory = ExportResult.DetailedTableOfLesions });
            }

            if (criterion.CriterionType == CriterionType.RECIST1Point1 || criterion.CriterionType == CriterionType.Lugano2014)
            {
                list.Add(new ExportDocumentDes() { Code = StaticData.Export.TumorCDISC_Export, ExportCatogory = ExportResult.TumorCDISC_Export });
            }

            if (criterion.CriterionType == CriterionType.OCT)
            {
                list.Add(new ExportDocumentDes() { Code = StaticData.Export.OCT_ReadingLession_Export, ExportCatogory = ExportResult.OCT_ReadingLession_Export });
                //list.Add(new ExportDocumentDes() { Code = StaticData.Export.OCT_CDISC_Export, ExportCatogory = ExportResult.OCT_CDISC_Export });
            }
            if (criterion.CriterionType == CriterionType.IVUS)
            {
                //list.Add(new ExportDocumentDes() { Code = StaticData.Export.IVUS_CDISC_Export, ExportCatogory = ExportResult.IVUS_CDISC_Export });
            }
            if (criterion.CriterionGroup != CriterionGroup.Tumor /*&& criterion.CriterionType != CriterionType.OCT && criterion.CriterionType != CriterionType.IVUS*/)
            {
                list.Add(new ExportDocumentDes() { Code = StaticData.Export.CDISC_Reading_Export, ExportCatogory = ExportResult.NoneTumorCDISC });
            }

            switch (criterion.ArbitrationRule)
            {
                case ArbitrationRule.None:
                    break;

                case ArbitrationRule.Visit:
                    list.Add(new ExportDocumentDes() { Code = StaticData.Export.VisitJudgeRatio_Export, ExportCatogory = ExportResult.VisitJudgeRatio_Export });

                    break;
                case ArbitrationRule.Reading:
                    list.Add(new ExportDocumentDes() { Code = StaticData.Export.ReadingPeriodJudgeRatio_Export, ExportCatogory = ExportResult.ReadingPeriodJudgeRatio_Export });

                    break;
                case ArbitrationRule.NA:
                    break;
                default:
                    break;
            }


            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;
        }

        /// <summary>
        /// 阅片结果表、阅片结果明细，评估病灶明细表, 裁判明细表导出，条件通过  ReadingExportType （ 1，2，3,4）区分
        /// </summary>
        /// <param name="inQuery"></param>
        /// <param name="_commonDocumentRepository"></param>
        /// <param name="_dictionaryService"></param>
        /// <param name="_trialRepository"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> GetCommonEvaluationList_Export(VisitTaskQuery inQuery,
        [FromServices] IRepository<CommonDocument> _commonDocumentRepository,
        [FromServices] IDictionaryService _dictionaryService,
        [FromServices] IRepository<ReadingQuestionTrial> _trialReadingQuestionRepository,
         [FromServices] IRepository<ReadingTableQuestionTrial> _trialReadingTableQuestionRepository,
        [FromServices] IRepository<ReadingOncologyTaskInfo> _oncologyRepository,
        [FromServices] IRepository<Trial> _trialRepository)
        {
            var trialId = inQuery.TrialId;
            var trialReadingCriterionId = inQuery.TrialReadingCriterionId;
            //每次查询必须是单标准的
            var criterion = await _readingQuestionCriterionTrialRepository.Where(t => t.Id == inQuery.TrialReadingCriterionId).Select(t => new { t.CriterionType, t.CriterionGroup, t.IsGlobalReading, t.IsArbitrationReading, t.IsOncologyReading, t.CriterionName, t.ArbitrationRule }).FirstNotNullAsync();


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

               //访视和全局查询已签名完成的，裁判可以是未签名，未完成的
               .Where(t => (t.ReadingTaskState == ReadingTaskState.HaveSigned && (t.ReadingCategory == ReadingCategory.Visit || t.ReadingCategory == ReadingCategory.Global)) || t.ReadingCategory == ReadingCategory.Judge)
               .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);


            var list = new List<CommonEvaluationExport>();

            var taskList = new List<CommonLessionExport>();

            #region 区分导表类型

            var removeColumnIndexList = new List<int>() { };

            if (inQuery.ReadingExportType == ExportResult.DetailedTableOfAdjudicationResults ||
                inQuery.ReadingExportType == ExportResult.DetailedTableOfAssessmentResults ||
                inQuery.ReadingExportType == ExportResult.DetailedTableOfLesions ||
               inQuery.ReadingExportType == ExportResult.TableOfAssessmentResults)
            {
                if (!criterion.IsArbitrationReading)
                {
                    //仲裁阅片 才有裁判阅片明细表  同时要把模板里面的三列给去掉
                    //removeColumnIndexList = new List<int>() { 6, 7, 8 };
                    removeColumnIndexList = new List<int>() { 7, 8, 9 };
                }

                //阅片结果表 和阅片结果明细表 没有肿瘤学的时候需要移除肿瘤学三个字段

                if (!criterion.IsOncologyReading)
                {
                    if (inQuery.ReadingExportType == ExportResult.TableOfAssessmentResults || inQuery.ReadingExportType == ExportResult.DetailedTableOfAssessmentResults)
                    {
                        //removeColumnIndexList = removeColumnIndexList.Union(new List<int>() { 9, 10, 11 }).ToList();
                        removeColumnIndexList = removeColumnIndexList.Union(new List<int>() { 10, 11, 12 }).ToList();
                    }
                }
            }

            var export_Template = StaticData.Export.CommonReading_Export;

            if (inQuery.ReadingExportType == ExportResult.DetailedTableOfAdjudicationResults)
            {
                //裁判明表
                export_Template = StaticData.Export.CommonJudgeReadingDetail_Export;
            }
            else if (inQuery.ReadingExportType == ExportResult.DetailedTableOfAssessmentResults)
            {
                //阅片明细表
                export_Template = StaticData.Export.CommonReadingDetail_Export;
            }
            else if (inQuery.ReadingExportType == ExportResult.DetailedTableOfLesions)
            {
                //病灶明细表
                export_Template = StaticData.Export.ReadingLession_Export;
            }
            else if (inQuery.ReadingExportType == ExportResult.TableOfAssessmentResults)
            {
                //阅片结果表
                export_Template = StaticData.Export.CommonReading_Export;
            }
            //斑块表
            else if (inQuery.ReadingExportType == ExportResult.OCT_ReadingLession_Export)
            {
                //OCT
                export_Template = StaticData.Export.OCT_ReadingLession_Export;
            }
            else
            {
                //CDISC
                export_Template = StaticData.Export.CDISC_Reading_Export;
            }


            // 肿瘤标准  按照任务级别
            if ((inQuery.ReadingExportType == ExportResult.TableOfAssessmentResults ||
                    inQuery.ReadingExportType == ExportResult.DetailedTableOfAssessmentResults ||
                    inQuery.ReadingExportType == ExportResult.DetailedTableOfAdjudicationResults) &&
                    (criterion.CriterionGroup == CriterionGroup.Tumor)
                )

            {
                //其他可以统一处理
                list = await query.ProjectTo<CommonEvaluationExport>(_mapper.ConfigurationProvider,
                 new
                 {
                     readingExportType = inQuery.ReadingExportType,
                     criterionType = criterion.CriterionType,
                     arbitrationRule = criterion.ArbitrationRule,
                     trialReadingCriterionId = inQuery.TrialReadingCriterionId,
                     isEn_Us = _userInfo.IsEn_Us
                 }).AsSplitQuery().ToListAsync();

            }
            //肿瘤标准 病灶明细表   按照病灶级别  (OCT 暂时不删除，先看是否能覆盖)
            else if (
                    (inQuery.ReadingExportType == ExportResult.DetailedTableOfLesions &&
                    criterion.CriterionGroup == CriterionGroup.Tumor
                    ) || inQuery.ReadingExportType == ExportResult.OCT_ReadingLession_Export
                    )
            {

                taskList = await query.ProjectTo<CommonLessionExport>(_mapper.ConfigurationProvider,
                new
                {
                    readingExportType = inQuery.ReadingExportType,
                    criterionType = criterion.CriterionType,
                    arbitrationRule = criterion.ArbitrationRule,
                    trialReadingCriterionId = inQuery.TrialReadingCriterionId,
                    isEn_Us = _userInfo.IsEn_Us
                }).AsSplitQuery().ToListAsync();

            }
            // 非肿瘤标准  包括自定义，以及系统非肿瘤    会配置到表格层级  问题名称是 表格名称_表格子问题名
            else if (
                    criterion.CriterionGroup == CriterionGroup.Nontumorous && inQuery.ReadingExportType != ExportResult.NoneTumorCDISC
                )
            {

                // 配置在外层问题 或者表格问题上
                taskList = await query.ProjectTo<CommonLessionExport>(_mapper.ConfigurationProvider,
                                   new
                                   {
                                       readingExportType = inQuery.ReadingExportType,
                                       criterionType = criterion.CriterionType,
                                       arbitrationRule = criterion.ArbitrationRule,
                                       trialReadingCriterionId = inQuery.TrialReadingCriterionId,
                                       isEn_Us = _userInfo.IsEn_Us
                                   }).AsSplitQuery().ToListAsync();

            }
            // CDISC 导出  只管到 外层问题层级  和阅片结果表是保持一致
            else if (inQuery.ReadingExportType == ExportResult.NoneTumorCDISC)
            {

                if (criterion.CriterionGroup == CriterionGroup.Tumor)
                {

                    list = await query.ProjectTo<CommonEvaluationExport>(_mapper.ConfigurationProvider,
                                    new
                                    {
                                        readingExportType = inQuery.ReadingExportType,
                                        criterionType = criterion.CriterionType,
                                        arbitrationRule = criterion.ArbitrationRule,
                                        trialReadingCriterionId = inQuery.TrialReadingCriterionId,
                                        isEn_Us = _userInfo.IsEn_Us
                                    }).AsSplitQuery().ToListAsync();
                }
                else
                {
                    taskList = await query.ProjectTo<CommonLessionExport>(_mapper.ConfigurationProvider,
                            new
                            {
                                readingExportType = inQuery.ReadingExportType,
                                criterionType = criterion.CriterionType,
                                arbitrationRule = criterion.ArbitrationRule,
                                trialReadingCriterionId = inQuery.TrialReadingCriterionId,
                                isEn_Us = _userInfo.IsEn_Us
                            }).AsSplitQuery().ToListAsync();
                }

            }

            #endregion





            var dynamicColumnConfig = new DynamicColumnConfig();

            //查询配置的问题名称，不是从答案表中连接取问题名称，因为目前有些保存，有些问题，虽然配置了，但是没填,导致导表有些配置的列没出来
            var trialConfigQuestionList = _trialReadingQuestionRepository.Where(t => t.TrialId == trialId && t.ReadingQuestionCriterionTrialId == trialReadingCriterionId).Where(t => t.ExportResultStr.Contains(((int)inQuery.ReadingExportType).ToString())).OrderBy(t => t.ShowOrder).Select(t => new ExportQuestionBasicInfo()
            {
                QuestionId = t.Id,
                QuestionType = t.QuestionType,
                TableName = "",
                QuestionName = _userInfo.IsEn_Us ? t.QuestionEnName : t.QuestionName,
                CDISCCode = t.CDISCCode,
                TranslateDicName = t.DictionaryCode,
                GroupName = _userInfo.IsEn_Us ? t.GroupInfo.GroupEnName : t.GroupInfo.GroupName
            }).ToList();

            #region 外层问题有重复，针对重复的加上组名

            //foreach (var item in trialConfigQuestionList.GroupBy(t => t.QuestionName).Where(g => g.Count() > 1))
            //{
            //    var qName = item.Key;

            //    foreach (var configQuestion in trialConfigQuestionList)
            //    {
            //        if (configQuestion.QuestionName == qName)
            //        {
            //            configQuestion.QuestionName = $"{configQuestion.GroupName}_{configQuestion.QuestionName}";
            //        }
            //    }
            //}
            #endregion


            if (inQuery.ReadingExportType != ExportResult.NoneTumorCDISC)
            {
                //最终EXCEL 列
                var configCoumNameList = new List<DynamicColumnConfig.ColumItem>();

                //最终翻译字典
                var translateDicNameList = new List<string>();


                //表格全问题名
                var trialConfigTableQuestionList = _trialReadingTableQuestionRepository.Where(t => t.TrialId == trialId && t.TrialCriterionId == trialReadingCriterionId).Where(t => t.ExportResultStr.Contains(((int)inQuery.ReadingExportType).ToString()))
                    .OrderBy(t => t.ShowOrder).Select(t => new ExportQuestionBasicInfo()
                    {
                        QuestionId = t.Id,
                        TableName = _userInfo.IsEn_Us ? t.ReadingQuestionTrial.QuestionEnName : t.ReadingQuestionTrial.QuestionName,
                        QuestionName = _userInfo.IsEn_Us ? t.QuestionEnName : t.QuestionName,
                        CDISCCode = t.CDISCCode,
                        TranslateDicName = t.DictionaryCode
                    }).ToList();



                var fistLeveLNameList = new List<DynamicColumnConfig.ColumItem>();

                //肿瘤评估，非CDISC 导出
                if (criterion.CriterionGroup == CriterionGroup.Tumor)
                {
                    #region 外层问题处理

                    if (criterion.CriterionType == CriterionType.RECIST1Point1 || criterion.CriterionType == CriterionType.RECIST1Pointt1_MB
                        || criterion.CriterionType == CriterionType.IRECIST1Point1 || criterion.CriterionType == CriterionType.mRECISTHCC)
                    {

                        fistLeveLNameList = trialConfigQuestionList.Select(t => new DynamicColumnConfig.ColumItem()
                        {
                            Id = Guid.Empty,
                            Name = (t.QuestionType == QuestionType.ExistDisease || t.QuestionType == QuestionType.Tumor) ? (_userInfo.IsEn_Us ? "Overall Response" : "整体肿瘤评估") : t.QuestionName
                        }).Distinct().ToList();




                    }
                    else if (criterion.CriterionType == CriterionType.Lugano2014 || criterion.CriterionType == CriterionType.Lugano2014WithoutPET)
                    {

                        fistLeveLNameList = trialConfigQuestionList.Select(t => new DynamicColumnConfig.ColumItem()
                        {
                            Id = Guid.Empty,
                            Name = (t.QuestionType == QuestionType.ExistDisease || t.QuestionType == QuestionType.ImgOncology) ? (_userInfo.IsEn_Us ? "Overall Response" : "整体肿瘤评估") : t.QuestionName
                        }).Distinct().ToList();

                    }
                    else if (criterion.CriterionType == CriterionType.PCWG3)
                    {
                        fistLeveLNameList = trialConfigQuestionList.Select(t => new DynamicColumnConfig.ColumItem()
                        {
                            Id = Guid.Empty,
                            Name = t.QuestionName
                        }).Distinct().ToList();

                    }

                    #endregion

                    var exTralDicNameList = new List<string>() { "LesionType" };

                    translateDicNameList = trialConfigQuestionList.Union(trialConfigTableQuestionList).Where(t => t.TranslateDicName.IsNotNullOrEmpty()).Select(t => t.TranslateDicName).Union(exTralDicNameList).Distinct().ToList();

                    #region 表格问题处理  肿瘤  表格问题直接去重、同时添加一些列
                    var extralNameList = new List<DynamicColumnConfig.ColumItem>();

                    if (criterion.CriterionType == CriterionType.RECIST1Point1 || criterion.CriterionType == CriterionType.RECIST1Pointt1_MB
                       || criterion.CriterionType == CriterionType.IRECIST1Point1 || criterion.CriterionType == CriterionType.mRECISTHCC
                       || criterion.CriterionType == CriterionType.Lugano2014 || criterion.CriterionType == CriterionType.Lugano2014WithoutPET)
                    {

                        //if(inQuery.ReadingExportType == ExportResult.DetailedTableOfLesions)
                        {
                            extralNameList.Add(new DynamicColumnConfig.ColumItem() { Id = Guid.Empty, Name = _userInfo.IsEn_Us ? "Lesion ID" : "病灶编号" });
                            extralNameList.Add(new DynamicColumnConfig.ColumItem() { Id = Guid.Empty, Name = _userInfo.IsEn_Us ? "Lesion Type" : "病灶类型" });
                        }

                    }
                    else if (criterion.CriterionType == CriterionType.PCWG3)
                    {
                        //if (inQuery.ReadingExportType == ExportResult.DetailedTableOfLesions)
                        {
                            extralNameList.Add(new DynamicColumnConfig.ColumItem() { Id = Guid.Empty, Name = _userInfo.IsEn_Us ? "Lesion Type" : "病灶类型" });

                        }
                    }

                    //肿瘤评估标准目前是去重  按照问题名称填充 不是Id
                    var tableQuestionNameList = trialConfigTableQuestionList.Select(t => t.QuestionName).Distinct().Select(t => new DynamicColumnConfig.ColumItem() { Id = Guid.Empty, Name = t }).Distinct().ToList();

                    //有表格问题 那么就是三部分，否则就是外层问题
                    configCoumNameList = tableQuestionNameList.Count == 0 ? fistLeveLNameList : fistLeveLNameList.Union(extralNameList).Union(tableQuestionNameList).ToList();


                    #region 扩展病灶


                    //最终的病灶列表  要把裁判的也要加进去，需要处理裁判标记

                    foreach (var item in taskList.OrderBy(t => t.SubjectCode).ThenBy(t => t.ArmEnum).ThenBy(t => t.VisitTaskNum))
                    {
                        if (item.LesionList.Count > 0)
                        {
                            foreach (var lession in item.LesionList.OrderBy(t => t.LessionType).ThenBy(t => t.LessionCode))
                            {

                                var addLessionInfoList = new List<CommonQuesionInfo>();

                                if (criterion.CriterionType == CriterionType.RECIST1Point1 || criterion.CriterionType == CriterionType.RECIST1Pointt1_MB
                               || criterion.CriterionType == CriterionType.IRECIST1Point1 || criterion.CriterionType == CriterionType.mRECISTHCC
                               || criterion.CriterionType == CriterionType.Lugano2014 || criterion.CriterionType == CriterionType.Lugano2014WithoutPET)
                                {
                                    //病灶编号 和病灶类型没有配置，但是需要有的
                                    addLessionInfoList.Add(new CommonQuesionInfo() { QuestionName = _userInfo.IsEn_Us ? "Lesion ID" : "病灶编号", QuestionValue = lession.LessionCode });
                                    addLessionInfoList.Add(new CommonQuesionInfo() { QuestionName = _userInfo.IsEn_Us ? "Lesion Type" : "病灶类型", QuestionValue = lession.LessionType, TranslateDicName = "LesionType" });

                                }
                                else if (criterion.CriterionType == CriterionType.PCWG3)
                                {
                                    addLessionInfoList.Add(new CommonQuesionInfo() { QuestionName = _userInfo.IsEn_Us ? "Lesion Type" : "病灶类型", QuestionValue = lession.LessionType, TranslateDicName = "LesionType" });
                                }

                                var dynamicPartialLessionInfoList = lession.LessionAnswerList.Select(t => new CommonQuesionInfo() { QuestionName = t.QuestionName, OptionTypeEnum = t.OptionTypeEnum, QuestionValue = t.QuestionValue, TranslateDicName = t.TranslateDicName, Unit = t.Unit });

                                //有三部分组成  外层问题+ 没有配置病灶编号和类型+ 动态的表格问题
                                var dynamicLessionInfoList = item.QuestionAnswerList.Union(addLessionInfoList).Union(dynamicPartialLessionInfoList).ToList();

                                //OCT 多个表格，但是只导出一个表格,有的问题答案就是空的
                                if (dynamicLessionInfoList.Count > 0)
                                {

                                    var cloneItem = item.Clone();
                                    cloneItem.QuestionAnswerList = dynamicLessionInfoList;

                                    list.Add(cloneItem);
                                }

                            }
                        }
                        else
                        {
                            //要把裁判任务加进去 裁判任务上没有病灶

                            list.Add(item);
                        }
                    }

                    #endregion

                    #region  不管是list 还是taskList 最终处理的数据都是list    处理好数据后合并
                    if (criterion.CriterionType == CriterionType.RECIST1Point1 || criterion.CriterionType == CriterionType.RECIST1Pointt1_MB
                        || criterion.CriterionType == CriterionType.IRECIST1Point1 || criterion.CriterionType == CriterionType.mRECISTHCC)
                    {
                        //针对1.1 整体肿瘤评估 有的两列要合并一列
                        foreach (var item in list)
                        {
                            //处理合并表头

                            var questionType = item.IsBaseline == true ? QuestionType.ExistDisease : QuestionType.Tumor;

                            var findItem = item.QuestionAnswerList.Where(t => t.QuestionType == questionType).FirstOrDefault();

                            if (findItem != null)
                            {
                                findItem.QuestionName = _userInfo.IsEn_Us ? "Overall Response" : "整体肿瘤评估";
                            }


                            if (item.IsBaseline == true)
                            {
                                item.QuestionAnswerList = item.QuestionAnswerList.Where(t => t.QuestionType != QuestionType.Tumor).ToList();
                            }
                            else
                            {
                                item.QuestionAnswerList = item.QuestionAnswerList.Where(t => t.QuestionType != QuestionType.ExistDisease).ToList();
                            }
                        }
                    }
                    else if (criterion.CriterionType == CriterionType.Lugano2014 || criterion.CriterionType == CriterionType.Lugano2014WithoutPET)
                    {
                        foreach (var item in list)
                        {
                            //处理合并表头

                            var questionType = item.IsBaseline == true ? QuestionType.ExistDisease : QuestionType.ImgOncology;

                            var findItem = item.QuestionAnswerList.Where(t => t.QuestionType == questionType).FirstOrDefault();

                            if (findItem != null)
                            {
                                findItem.QuestionName = _userInfo.IsEn_Us ? "Overall Response" : "整体肿瘤评估";
                            }

                            if (item.IsBaseline == true)
                            {
                                item.QuestionAnswerList = item.QuestionAnswerList.Where(t => t.QuestionType != QuestionType.ImgOncology).ToList();
                            }
                            else
                            {
                                item.QuestionAnswerList = item.QuestionAnswerList.Where(t => t.QuestionType != QuestionType.ExistDisease).ToList();
                            }
                        }
                    }

                    #endregion

                    #endregion
                }
                else
                //非肿瘤评估，非CDISC 导出
                {
                    //外层问题处理
                    fistLeveLNameList = trialConfigQuestionList.Select(t => new DynamicColumnConfig.ColumItem()
                    {
                        Id = t.QuestionId,
                        Name = t.QuestionName
                    }).ToList();

                    translateDicNameList = trialConfigQuestionList.Union(trialConfigTableQuestionList).Where(t => t.TranslateDicName.IsNotNullOrEmpty()).Select(t => t.TranslateDicName).Distinct().ToList();

                    #region 表格问题处理  问题名称是 表格名称_表格子问题名

                    var isMutiTable = trialConfigTableQuestionList.Select(t => t.TableName).Distinct().Count() > 1;

                    //多表格问题
                    if (isMutiTable)
                    {
                        //多表格，增加的一列，就用Guid.Empty 标识
                        var extralNameList = new List<DynamicColumnConfig.ColumItem>() { new DynamicColumnConfig.ColumItem() { Id = Guid.Empty, Name = _userInfo.IsEn_Us ? "Table Name" : "表格名称" } };

                        var tableQuestionNameList = trialConfigTableQuestionList.OrderBy(t => t.TableName).Select(t => new DynamicColumnConfig.ColumItem() { Id = t.QuestionId, Name = t.TableName + "_" + t.QuestionName }).ToList();

                        configCoumNameList = fistLeveLNameList.Union(extralNameList).Union(tableQuestionNameList).ToList();
                    }
                    else
                    {
                        //单表格问题(直接用表格问题名称) 或者没有表格问题   

                        var tableNameList = trialConfigTableQuestionList.Select(t => new DynamicColumnConfig.ColumItem() { Id = t.QuestionId, Name = t.QuestionName }).ToList();

                        configCoumNameList = fistLeveLNameList.Union(tableNameList).ToList();
                    }




                    #region 扩展表格问题


                    //最终的病灶列表  要把裁判的也要加进去，需要处理裁判标记
                    foreach (var item in taskList.OrderBy(t => t.SubjectCode).ThenBy(t => t.ArmEnum).ThenBy(t => t.VisitTaskNum))
                    {
                        //有病灶，并且至少配置了一个病灶问题
                        if (item.LesionList.Count > 0 && item.LesionList.SelectMany(t => t.LessionAnswerList).Any())
                        {
                            foreach (var lession in item.LesionList.OrderBy(t => t.LessionType).ThenBy(t => t.LessionCode))
                            {
                                //病灶配置了问题 才进行导出
                                if (lession.LessionAnswerList.Count > 0)
                                {
                                    var firstLessionAnser = lession.LessionAnswerList.FirstOrDefault();

                                    var dynamicLessionInfoList = new List<CommonQuesionInfo>();

                                    if (isMutiTable)
                                    {
                                        var addLessionInfoList = new List<CommonQuesionInfo>();

                                        addLessionInfoList.Add(new CommonQuesionInfo() { QuestionId = Guid.Empty, QuestionName = _userInfo.IsEn_Us ? "Table Name" : "表格名称", QuestionValue = firstLessionAnser.TableName });

                                        var dynamicPartialLessionInfoList = lession.LessionAnswerList.Select(t => new CommonQuesionInfo() { QuestionId = t.TableQuesionId, OptionTypeEnum = t.OptionTypeEnum, QuestionName = t.TableName + "_" + t.QuestionName, QuestionValue = t.QuestionValue, TranslateDicName = t.TranslateDicName, CDISCCode = t.CDISCCode, Unit = t.Unit });

                                        //有三部分组成  外层问题+  固定列表格名称 + 动态的表格问题
                                        dynamicLessionInfoList = item.QuestionAnswerList.Union(addLessionInfoList).Union(dynamicPartialLessionInfoList).ToList();
                                    }
                                    else
                                    {
                                        var dynamicPartialLessionInfoList = lession.LessionAnswerList.Select(t => new CommonQuesionInfo() { QuestionId = t.TableQuesionId, OptionTypeEnum = t.OptionTypeEnum, QuestionName = t.QuestionName, QuestionValue = t.QuestionValue, TranslateDicName = t.TranslateDicName, CDISCCode = t.CDISCCode, Unit = t.Unit });

                                        //两部分组成  外层问题+   动态的表格问题
                                        dynamicLessionInfoList = item.QuestionAnswerList.Union(dynamicPartialLessionInfoList).ToList();
                                    }



                                    var cloneItem = item.Clone();
                                    cloneItem.QuestionAnswerList = dynamicLessionInfoList;
                                    list.Add(cloneItem);
                                }

                            }
                        }
                        else
                        {
                            //要把裁判任务加进去 裁判任务上没有病灶

                            list.Add(item);
                        }

                    }

                    #endregion

                    #endregion
                }



                dynamicColumnConfig = new DynamicColumnConfig()
                {

                    AutoColumnTitleRowIndex = 3, //2
                    AutoColumnStartIndex = 7, //6
                    TempalteLastColumnIndex = 12,//11
                    DynamicItemDicName = "TranslateDicName",
                    DynamicItemValueName = "QuestionValue",
                    DynamicItemTitleName = "QuestionName",
                    DynamicItemTitleId = "QuestionId",
                    DynamicListName = "QuestionAnswerList",
                    RemoveColunmIndexList = removeColumnIndexList,
                    ColumnIdNameList = configCoumNameList,
                    //CDISCList = new List<string>(),
                    TranslateDicNameList = translateDicNameList
                };

                if (export_Template == StaticData.Export.ReadingLession_Export || export_Template == StaticData.Export.CommonJudgeReadingDetail_Export || export_Template == StaticData.Export.OCT_ReadingLession_Export)
                {
                    dynamicColumnConfig.TempalteLastColumnIndex = 8;
                }

            }

            else
            {

                if (criterion.CriterionGroup == CriterionGroup.Nontumorous)
                {
                    //最终EXCEL 列
                    var configCoumNameList = new List<DynamicColumnConfig.ColumItem>();

                    //表格全问题名
                    var trialConfigTableQuestionList = _trialReadingTableQuestionRepository.Where(t => t.TrialId == trialId && t.TrialCriterionId == trialReadingCriterionId).Where(t => t.ExportResultStr.Contains(((int)inQuery.ReadingExportType).ToString()))
                        .Select(t => new ExportQuestionBasicInfo()
                        {
                            QuestionId = t.Id,
                            TableName = _userInfo.IsEn_Us ? t.ReadingQuestionTrial.QuestionEnName : t.ReadingQuestionTrial.QuestionName,
                            QuestionName = _userInfo.IsEn_Us ? t.QuestionEnName : t.QuestionName,
                            CDISCCode = t.CDISCCode,
                            TranslateDicName = t.DictionaryCode,
                            ShowOrder = t.ShowOrder
                        }).OrderBy(t => t.TableName).ThenBy(t => t.ShowOrder).ToList();

                    var isMutiTable = trialConfigTableQuestionList.Select(t => t.TableName).Distinct().Count() > 1;


                    //外层问题处理
                    var fistLeveLNameList = trialConfigQuestionList.Select(t => new DynamicColumnConfig.ColumItem()
                    {
                        Id = t.QuestionId,
                        Name = t.QuestionName,
                        CDISCCode = t.CDISCCode
                    }).ToList();

                    var translateDicNameList = trialConfigQuestionList.Union(trialConfigTableQuestionList).Where(t => t.TranslateDicName.IsNotNullOrEmpty()).Select(t => t.TranslateDicName).Distinct().ToList();

                    //单表格问题(直接用表格问题名称) 或者没有表格问题   
                    if (isMutiTable == false)
                    {
                        //一个表格，或者没有表格
                        var tableNameList = trialConfigTableQuestionList.Select(t => new DynamicColumnConfig.ColumItem() { Id = t.QuestionId, Name = t.QuestionName, CDISCCode = t.CDISCCode }).ToList();

                        configCoumNameList = fistLeveLNameList.Union(tableNameList).ToList();

                        //最终的病灶列表  要把裁判的也要加进去，需要处理裁判标记
                        foreach (var item in taskList.OrderBy(t => t.SubjectCode).ThenBy(t => t.ArmEnum).ThenBy(t => t.VisitTaskNum))
                        {
                            //有病灶，并且至少配置了一个病灶问题
                            if (item.LesionList.Count > 0 && item.LesionList.SelectMany(t => t.LessionAnswerList).Any())
                            {
                                foreach (var lession in item.LesionList.OrderBy(t => t.LessionType).ThenBy(t => t.LessionCode))
                                {
                                    //病灶配置了问题 才进行导出
                                    if (lession.LessionAnswerList.Count > 0)
                                    {

                                        var dynamicLessionInfoList = new List<CommonQuesionInfo>();


                                        var dynamicPartialLessionInfoList = lession.LessionAnswerList.Select(t => new CommonQuesionInfo() { QuestionId = t.TableQuesionId, OptionTypeEnum = t.OptionTypeEnum, QuestionName = t.QuestionName, QuestionValue = t.QuestionValue, TranslateDicName = t.TranslateDicName, CDISCCode = t.CDISCCode, Unit = t.Unit });

                                        //两部分组成  外层问题+   动态的表格问题
                                        dynamicLessionInfoList = item.QuestionAnswerList.Union(dynamicPartialLessionInfoList).ToList();

                                        var cloneItem = item.Clone();
                                        cloneItem.QuestionAnswerList = dynamicLessionInfoList;
                                        list.Add(cloneItem);
                                    }

                                }
                            }
                            else
                            {
                                //要把裁判任务加进去 裁判任务上没有病灶

                                list.Add(item);
                            }

                        }

                        dynamicColumnConfig = new DynamicColumnConfig()
                        {
                            AutoColumnTitleRowIndex = 2,   //1
                            AutoColumnStartIndex = 7,      //6
                            TempalteLastColumnIndex = 11,  //10
                            DynamicItemDicName = "TranslateDicName",
                            DynamicItemValueName = "QuestionValue",
                            DynamicItemTitleName = "QuestionName",
                            DynamicItemTitleId = "QuestionId",
                            DynamicListName = "QuestionAnswerList",
                            RemoveColunmIndexList = removeColumnIndexList,
                            ColumnIdNameList = configCoumNameList,
                            IsCDISCExport = true,
                            //CDISCList = cdiscCodeList,
                            TranslateDicNameList = translateDicNameList
                        };
                    }
                    else
                    {
                        //多表格问题，需要用新的模板，并且用行的方式展示  （不是之前表格名称_表格子问题名的方式）

                        export_Template = StaticData.Export.CDISC_MutiTable_Reading_Export;

                        configCoumNameList = fistLeveLNameList.ToList();

                        var translateUnitList = await _dictionaryService.GetBasicDataSelect("ValueUnit");


                        foreach (var item in taskList.OrderBy(t => t.SubjectCode).ThenBy(t => t.ArmEnum).ThenBy(t => t.VisitTaskNum))
                        {
                            //有病灶，并且至少配置了一个病灶问题
                            if (item.LesionList.Count > 0 && item.LesionList.SelectMany(t => t.LessionAnswerList).Any())
                            {
                                foreach (var lession in item.LesionList.OrderBy(t => t.LessionType).ThenBy(t => t.LessionCode))
                                {
                                    //病灶配置了问题 才进行导出
                                    if (lession.LessionAnswerList.Count > 0)
                                    {

                                        //遍历病灶的每个问题
                                        foreach (var lessionItem in lession.LessionAnswerList.OrderBy(t => t.ShowOrder))
                                        {

                                            var cloneItem = item.Clone();


                                            string unitText = lessionItem.Unit switch
                                            {
                                                ValueUnit.Custom => lessionItem.CustomUnit,
                                                null => "",
                                                _ => _userInfo.IsEn_Us ? translateUnitList.FirstOrDefault(t => t.Code == ((int)lessionItem.Unit).ToString())?.Value ?? ""
                                                : translateUnitList.FirstOrDefault(t => t.Code == ((int)lessionItem.Unit).ToString())?.ValueCN ?? ""
                                            };


                                            cloneItem.Group = lessionItem.TableName;
                                            cloneItem.TRLINKID = lessionItem.RowId.ToString();
                                            cloneItem.TRORRES = lessionItem.QuestionValue;
                                            cloneItem.TRTEST = lessionItem.CDISCCode;
                                            cloneItem.TRORRESU = unitText;


                                            list.Add(cloneItem);
                                        }

                                        //var dynamicLessionInfoList = new List<CommonQuesionInfo>();

                                        //var dynamicPartialLessionInfoList = lession.LessionAnswerList.Select(t => new CommonQuesionInfo() { QuestionId = t.TableQuesionId, QuestionName = t.QuestionName, QuestionValue = t.QuestionValue, TranslateDicName = t.TranslateDicName, CDISCCode = t.CDISCCode });

                                        ////两部分组成  外层问题+   动态的表格问题
                                        //dynamicLessionInfoList = item.QuestionAnswerList.Union(dynamicPartialLessionInfoList).ToList();

                                    }

                                }
                            }
                            else
                            {
                                //要把裁判任务加进去 裁判任务上没有病灶

                                list.Add(item);
                            }

                        }

                        dynamicColumnConfig = new DynamicColumnConfig()
                        {
                            AutoColumnTitleRowIndex = 2,   //1
                            AutoColumnStartIndex = 7,      //6
                            TempalteLastColumnIndex = 16,  //15
                            DynamicItemDicName = "TranslateDicName",
                            DynamicItemValueName = "QuestionValue",
                            DynamicItemTitleName = "QuestionName",
                            DynamicItemTitleId = "QuestionId",
                            DynamicListName = "QuestionAnswerList",
                            RemoveColunmIndexList = removeColumnIndexList,
                            ColumnIdNameList = configCoumNameList,
                            IsCDISCExport = true,
                            //CDISCList = cdiscCodeList,
                            TranslateDicNameList = translateDicNameList
                        };
                    }





                }
                else
                {
                    //CDISC 导出 只到外层问题级别  使用Id 填充Excel

                    var totalConfigCoumNameList = trialConfigQuestionList.ToList();

                    var configCoumNameList = totalConfigCoumNameList.Select(t => new DynamicColumnConfig.ColumItem() { Id = t.QuestionId, Name = t.QuestionName, CDISCCode = t.CDISCCode }).ToList();

                    var translateDicList = totalConfigCoumNameList.Where(t => t.TranslateDicName.IsNotNullOrEmpty()).Select(t => t.TranslateDicName).Distinct().ToList();

                    var cdiscCodeList = totalConfigCoumNameList.Select(t => t.CDISCCode).ToList();

                    dynamicColumnConfig = new DynamicColumnConfig()
                    {
                        AutoColumnTitleRowIndex = 2,   //1
                        AutoColumnStartIndex = 7,      //6
                        TempalteLastColumnIndex = 11,  //10
                        DynamicItemDicName = "TranslateDicName",
                        DynamicItemValueName = "QuestionValue",
                        DynamicItemTitleName = "QuestionName",
                        DynamicItemTitleId = "QuestionId",
                        DynamicListName = "QuestionAnswerList",
                        RemoveColunmIndexList = removeColumnIndexList,
                        ColumnIdNameList = configCoumNameList,
                        IsCDISCExport = true,
                        //CDISCList = cdiscCodeList,
                        TranslateDicNameList = translateDicList
                    };
                }









            }


            #region 最终导出参数处理

            //裁判阅片明细表
            if (export_Template == StaticData.Export.CommonJudgeReadingDetail_Export)
            {
                //R1 R2 两个人的访视都阅片完成了才可以，去除只有一个人阅片完成的访视
                //找到只有一个人阅片的受试者 和访视
                var exceptVisit = list.Where(t => t.ReadingCategory == ReadingCategory.Visit)
                    .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();

            }

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

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

            //处理肿瘤学结果
            list = DealOncologyResult(_oncologyRepository, criterion.IsOncologyReading, list);

            //裁判阅片明细表  处理完标记后处理
            if (export_Template == StaticData.Export.CommonJudgeReadingDetail_Export)
            {
                //裁判产生标记为空的数据过滤掉
                list = list.Where(t => t.IsTrigerJudge != null).ToList();
            }



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

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

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


            MemoryStream? memoryStream = null;

            string fileName = "";

            if (inQuery.ReadingExportType == ExportResult.NoneTumorCDISC)
            {
                (memoryStream, fileName) = await ExcelExportHelper.DataExport_ClosedXMLAsync(export_Template, exportInfo, _commonDocumentRepository, _hostEnvironment, _dictionaryService, typeof(CommonEvaluationExport), criterion.CriterionType, dynamicColumnConfig);

            }
            else
            {
                (memoryStream, fileName) = await ExcelExportHelper.DataExport_ClosedXMLAsync(export_Template, 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"
            };

            #endregion

        }




        /// <summary>
        /// 裁判一致率导出
        /// </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> GetCommonJudgeRatioList_Export(VisitTaskQuery inQuery,
        [FromServices] IRepository<CommonDocument> _commonDocumentRepository,
        [FromServices] IDictionaryService _dictionaryService,
        [FromServices] IRepository<SubjectUser> _subjectUserRepository,
        [FromServices] IRepository<Trial> _trialRepository)
        {
            //每次查询必须是单标准的
            var criterion = await _readingQuestionCriterionTrialRepository.Where(t => t.Id == inQuery.TrialReadingCriterionId).Select(t => new { t.CriterionType, t.CriterionName, t.ArbitrationRule, t.IsGlobalReading }).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.SourceSubjectVisitId })
                    .Where(g => g.Count() == 2).Select(g => g.Key.SourceSubjectVisitId).Distinct().Count();

                //裁判不需要完成阅片
                exportInfo.JudgeVisitCount = _visitTaskRepository.Where(comonTaskFilter).Where(t => t.ReadingCategory == ReadingCategory.Judge).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 && t.JudgeVisitTask.ReadingTaskState == ReadingTaskState.HaveSigned).Count(),


                    }).ToList();

                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);

                var isGlobalReading = criterion.IsGlobalReading;
                var addReadingPeriodNum = isGlobalReading ? ReadingCommon.TaskNumDic[ReadingCategory.Global] : 0;

                // 有阅片期没有全局   和有阅片期有全局，主要变化点在于 t.ReadingCategory == ReadingCategory.Global  变成了 t.Subject.ReadModuleList.Any(c => c.SubjectVisit.VisitNum == (t.VisitTaskNum - addReadingPeriodNum) && c.TrialReadingCriterionId==trialReadingCriterionId)  
                // 或者使用  isGlobalReading ? t.ReadModule.SubjectVisit.VisitNum == (t.VisitTaskNum - addReadingPeriodNum) : t.SourceSubjectVisit.VisitNum == (t.VisitTaskNum - addReadingPeriodNum)

                #region 患者统计部分

                //1、裁判量M：所有完成阅片病例 最后一个阅片期触发裁判的受试者数量；
                //2、总样本量N：R1,R2均完成阅片（至少一个阅片期）的受试者数量；
                exportInfo.SubjectCount = _subjectRepository.Where(t => t.TrialId == inQuery.TrialId)
                       .Where(t => t.SubjectVisitTaskList.AsQueryable().Where(comonTaskFilter).Where(t => t.ReadingTaskState == ReadingTaskState.HaveSigned)
                       //找到两个人完成的阅片期
                       .Where(t => t.Subject.ReadModuleList.Any(c => c.SubjectVisit.VisitNum == (t.VisitTaskNum - addReadingPeriodNum) && c.TrialReadingCriterionId == trialReadingCriterionId))
                       .GroupBy(t => new { t.SubjectId, t.VisitTaskNum })
                       .Where(g => g.Count() == 2).Any())
                       .Count();

                #region 废弃
                ////最后一个已完成的全局  没产生裁判 （之前有裁判），不算入裁判量
                //exportInfo.judgeSubjectCount = _subjectRepository.Where(t => t.TrialId == inQuery.TrialId)
                //  .Where(t => t.SubjectVisitTaskList.AsQueryable().Where(comonTaskFilter).Where(t => t.ReadingTaskState == ReadingTaskState.HaveSigned)
                //  .Where(t => t.Subject.ReadModuleList.Any(c => c.SubjectVisit.VisitNum == (t.VisitTaskNum - addReadingPeriodNum) && c.TrialReadingCriterionId == trialReadingCriterionId))
                //  .GroupBy(t => new { t.SubjectId, t.VisitTaskNum })
                //  .Where(g => g.Count() == 2 )
                //  .Any(g => g.Any(t => t.JudgeVisitTaskId != null)))
                //  .Count();

                //exportInfo.judgeSubjectCount = _subjectRepository.Where(t => t.TrialId == inQuery.TrialId)
                //  .Where(t => t.SubjectVisitTaskList.AsQueryable().Where(comonTaskFilter).Where(t => t.ReadingTaskState == ReadingTaskState.HaveSigned)
                //          .Where(t => t.Subject.ReadModuleList.Any(c => c.SubjectVisit.VisitNum == (t.VisitTaskNum - addReadingPeriodNum) && c.TrialReadingCriterionId == trialReadingCriterionId))
                //          .GroupBy(t => new { t.SubjectId, t.VisitTaskNum })
                //          .Where(g => g.Count() == 2)
                //          .Any(g => g.OrderByDescending(c => c.VisitTaskNum).FirstOrDefault().JudgeVisitTaskId != null)
                //      )
                //  .Count();

                //exportInfo.DoctorSubjectStatList = _visitTaskRepository.Where(comonTaskFilter).Where(t => t.ReadingTaskState == ReadingTaskState.HaveSigned)
                //  //筛选全局 已完成的任务
                //  .Where(t => t.Subject.ReadModuleList.Any(c => c.SubjectVisit.VisitNum == (t.VisitTaskNum - addReadingPeriodNum) && c.TrialReadingCriterionId == trialReadingCriterionId))
                //  .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)
                //      .Where(t => t.VisitTaskNum == g.Where(c => c.SubjectId == t.SubjectId && c.JudgeVisitTaskId != null && c.JudgeVisitTask.ReadingTaskState == ReadingTaskState.HaveSigned)
                //                                     .Max(t => t.VisitTaskNum))
                //      .Select(t => t.SubjectId).Distinct().Count(),

                //      // G-2  G-4 可能选择的是不同的医生，要以最后一次选择的为准
                //      JudgeAgreeCount = g.Where(t => t.JudgeVisitTaskId != null && t.JudgeVisitTask.ReadingTaskState == ReadingTaskState.HaveSigned)
                //      .Where(t => t.VisitTaskNum == g.Where(c => c.SubjectId == t.SubjectId && c.JudgeVisitTaskId != null && c.JudgeVisitTask.ReadingTaskState == ReadingTaskState.HaveSigned)
                //                                     .Max(t => t.VisitTaskNum))
                //      .Where(t => t.JudgeVisitTask.JudgeResultTaskId == t.Id)
                //      .Select(t => t.SubjectId).Distinct().Count(),

                //  }).ToList();
                #endregion

                // subject（G1 产生裁判  G2 不产生裁判  那么该患者不计入总量）
                var subjectReadingPeriodList = _visitTaskRepository.Where(comonTaskFilter).Where(t => t.ReadingTaskState == ReadingTaskState.HaveSigned)
                  .Where(t => t.Subject.ReadModuleList.Any(c => c.SubjectVisit.VisitNum == (t.VisitTaskNum - addReadingPeriodNum) && c.TrialReadingCriterionId == trialReadingCriterionId))
                  .GroupBy(t => new { t.SubjectId, t.VisitTaskNum, t.JudgeVisitTaskId })
                  .Where(g => g.Count() == 2)
                  .Select(g => new { g.Key.SubjectId, g.Key.VisitTaskNum, g.Key.JudgeVisitTaskId })
                  .ToList();

                exportInfo.judgeSubjectCount = subjectReadingPeriodList.GroupBy(x => x.SubjectId) // 按 SubjectId 分组
                                        .Select(g => g.OrderByDescending(x => x.VisitTaskNum).First()) // 每组取 VisitTaskNum 最大的记录
                                        .Where(t => t.JudgeVisitTaskId != null)
                                        .Count();

                var subjectReadingPeriodDoctorList = _visitTaskRepository.Where(comonTaskFilter).Where(t => t.ReadingTaskState == ReadingTaskState.HaveSigned)
                  .Where(t => t.Subject.ReadModuleList.Any(c => c.SubjectVisit.VisitNum == (t.VisitTaskNum - addReadingPeriodNum) && c.TrialReadingCriterionId == trialReadingCriterionId))
                  .GroupBy(t => new { t.SubjectId, t.VisitTaskNum })
                  .Where(g => g.Count() == 2)
                  .Select(g => new
                  {
                      g.Key.SubjectId,
                      g.Key.VisitTaskNum,

                      GlobalList = g.Select(t => new
                      {
                          t.Id,
                          t.VisitTaskNum,
                          t.DoctorUserId,
                          t.DoctorUser.UserName,
                          t.DoctorUser.FullName,
                          t.JudgeVisitTaskId,
                          t.ReadingTaskState,
                          t.JudgeVisitTask.JudgeResultTaskId,
                          JudgeTaskState = (ReadingTaskState?)t.JudgeVisitTask.ReadingTaskState
                      }).ToList()
                  })
                  .ToList();

                #region 调试注释
                //var cc = subjectReadingPeriodDoctorList.GroupBy(x => x.SubjectId) // 按 SubjectId 分组

                //        .Where(g => g.OrderByDescending(x => x.VisitTaskNum).First().GlobalList.Any(c => c.JudgeVisitTaskId != null))

                //        .ToList();

                //var ss = subjectReadingPeriodDoctorList.GroupBy(x => x.SubjectId) // 按 SubjectId 分组
                //                                                                  //最后一个全局没有产生裁判的subject要过滤掉 过滤后
                //         .Where(g => g.OrderByDescending(x => x.VisitTaskNum).First().GlobalList.Any(c => c.JudgeVisitTaskId != null))

                //         .Select(g => g.Where(c => c.GlobalList.Any(k => k.JudgeTaskState == ReadingTaskState.HaveSigned)).OrderByDescending(c => c.VisitTaskNum).FirstOrDefault())

                //         .ToList();


                //var kk = subjectReadingPeriodDoctorList.GroupBy(x => x.SubjectId) // 按 SubjectId 分组
                //                                                                  //最后一个全局没有产生裁判的subject要过滤掉 过滤后
                //                         .Where(g => g.OrderByDescending(x => x.VisitTaskNum).First().GlobalList.Any(c => c.JudgeVisitTaskId != null))
                //                         // 存在 已完成的全局裁判
                //                         .Where(subg => subg.Any(t => t.GlobalList.Any(c => c.JudgeTaskState == ReadingTaskState.HaveSigned)))
                //                         .Select(g => g.Where(c => c.GlobalList.Any(k => k.JudgeTaskState == ReadingTaskState.HaveSigned)).OrderByDescending(c => c.VisitTaskNum).FirstOrDefault())

                //                         .ToList();
                #endregion



                var filteredList = subjectReadingPeriodDoctorList.GroupBy(x => x.SubjectId) // 按 SubjectId 分组
                                                                                            //最后一个全局没有产生裁判的subject要过滤掉 过滤后
                                         .Where(g => g.OrderByDescending(x => x.VisitTaskNum).First().GlobalList.Any(c => c.JudgeVisitTaskId != null))
                                          // subject 存在 已完成的全局裁判
                                          .Where(subg => subg.Any(t => t.GlobalList.Any(c => c.JudgeTaskState == ReadingTaskState.HaveSigned)))
                                         //找到最大完成裁判的阅片期              // 每个subject 仅仅留最后一个已完成的全局
                                         .Select(g => g.Where(c => c.GlobalList.Any(k => k.JudgeTaskState == ReadingTaskState.HaveSigned)).OrderByDescending(c => c.VisitTaskNum).FirstOrDefault())
                                         .SelectMany(t => t.GlobalList.Select(u => new
                                         {
                                             t.SubjectId,
                                             t.VisitTaskNum,
                                             u.JudgeVisitTaskId,
                                             u.DoctorUserId,
                                             u.UserName,
                                             u.FullName,
                                             u.JudgeResultTaskId,
                                             VisitTaskId = u.Id
                                         }))
                                            .ToList();



                //找到该标准的阅片人 
                var armList = new List<Arm>() { Arm.SingleReadingArm, Arm.DoubleReadingArm1, Arm.DoubleReadingArm2 };

                exportInfo.DoctorSubjectStatList = _subjectUserRepository.Where(t => t.TrialId == inQuery.TrialId && t.TrialReadingCriterionId == inQuery.TrialReadingCriterionId && armList.Contains(t.ArmEnum))
                    .Select(t => new DoctorJudgeRatio()
                    {
                        DoctorUserId = t.DoctorUserId,
                        UserName = t.DoctorUser.UserName,
                        FullName = t.DoctorUser.FullName,

                        TotalJudgeCount = 0,

                        JudgeAgreeCount = 0

                    }).Distinct().ToList();

                foreach (var doctor in exportInfo.DoctorSubjectStatList)
                {
                    if (filteredList.Any(t => t.DoctorUserId == doctor.DoctorUserId))
                    {
                        doctor.TotalJudgeCount = filteredList.Where(t => t.DoctorUserId == doctor.DoctorUserId).Count();

                        doctor.JudgeAgreeCount = filteredList.Where(t => t.DoctorUserId == doctor.DoctorUserId).Count(t => t.JudgeResultTaskId == t.VisitTaskId);
                    }
                }

                #endregion

                #region 阅片期部分

                exportInfo.ReadingPeriodCount = _visitTaskRepository.Where(comonTaskFilter).Where(t => t.ReadingTaskState == ReadingTaskState.HaveSigned)
                    //找到阅片期已阅片完
                    .Where(t => t.Subject.ReadModuleList.Any(c => c.SubjectVisit.VisitNum == (t.VisitTaskNum - addReadingPeriodNum) && c.TrialReadingCriterionId == trialReadingCriterionId))
                    .GroupBy(t => new { t.SubjectId, t.VisitTaskNum })
                    .Where(g => g.Count() == 2)
                    .Select(g => new { g.Key.SubjectId, g.Key.VisitTaskNum }).Distinct().Count();

                exportInfo.judgeReadingPeriodCount = _visitTaskRepository.Where(comonTaskFilter).Where(t => t.ReadingTaskState == ReadingTaskState.HaveSigned)
                    //找到阅片期已阅片完
                    .Where(t => t.Subject.ReadModuleList.Any(c => c.SubjectVisit.VisitNum == (t.VisitTaskNum - addReadingPeriodNum) && c.TrialReadingCriterionId == trialReadingCriterionId))
                   .GroupBy(t => new { t.SubjectId, t.VisitTaskNum })
                   //裁判不要求做完
                   .Where(g => g.Count() == 2 && g.Any(c => c.JudgeVisitTaskId != null))
                   .Select(g => new { g.Key.SubjectId, g.Key.VisitTaskNum }).Distinct().Count();


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

                exportInfo.DoctorPeriodStatList = _visitTaskRepository.Where(comonTaskFilter).Where(t => t.ReadingTaskState == ReadingTaskState.HaveSigned)
                   .Where(t => t.Subject.ReadModuleList.Any(c => c.SubjectVisit.VisitNum == (t.VisitTaskNum - addReadingPeriodNum) && t.TrialReadingCriterionId == trialReadingCriterionId))
                  .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.JudgeVisitTaskId != null && t.JudgeVisitTask.ReadingTaskState == ReadingTaskState.HaveSigned)
                      .Select(t => new { t.SubjectId, t.VisitTaskNum }).Distinct().Count(),

                      JudgeAgreeCount = g
                      .Where(t => t.JudgeVisitTaskId != null && t.JudgeVisitTask.ReadingTaskState == ReadingTaskState.HaveSigned)
                      .Where(t => t.JudgeVisitTask.JudgeResultTaskId == t.Id)
                      .Select(t => new { t.SubjectId, t.VisitTaskNum }).Distinct().Count(),

                  }).ToList();


                #endregion

                return await ExcelExportHelper.DataExportAsync(StaticData.Export.ReadingPeriodJudgeRatio_Export, exportInfo, $"{exportInfo.ResearchProgramNo}_{exportInfo.CriterionName}", _commonDocumentRepository, _hostEnvironment);
            }
            else
            {
                throw new Exception("不支持该配置的导出");
            }

        }

        #endregion


    }
}
