using DocumentFormat.OpenXml.Office2010.ExcelAc;
using DocumentFormat.OpenXml.Spreadsheet;
using IRaCIS.Application.Contracts;
using IRaCIS.Application.Interfaces;
using IRaCIS.Core.Application.Contracts;
using IRaCIS.Core.Application.Service.Reading.Dto;
using IRaCIS.Core.Application.ViewModel;
using IRaCIS.Core.Domain.Share;
using IRaCIS.Core.Infra.EFCore.Common;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using MiniExcelLibs;
using MiniExcelLibs.OpenXml;
using NPOI.HPSF;
using NPOI.HSSF.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IRaCIS.Core.Application.Service.Common
{

    [ApiExplorerSettings(GroupName = "Common")]
    public class ExcelExportService : BaseService
    {

        #region 导表查询


        /// <summary>
        /// 影像上传列表    只导出已上传状态的检查批次记录
        /// </summary>
        /// <param name="visitSearchDTO"></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 visitSearchDTO,
            [FromServices] IRepository<CommonDocument> _commonDocumentRepository,
            [FromServices] IDictionaryService _dictionaryService,
            [FromServices] IRepository<SubjectVisit> _subjectVisitRepository,
            [FromServices] IRepository<Trial> _trialRepository
            )
        {

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

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

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

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

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

            exportInfo.List = list;



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

        }




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

        {

            var svExpression = QCCommon.GetQCChallengeFilter(challengeQuery.VisitPlanArray);

            var list = await _repository.Where<QCChallenge>(x => x.TrialId == challengeQuery.TrialId)
                //.WhereIf(challengeQuery.ChallengeState != null, t => t.SubjectVisit.ChallengeState == challengeQuery.ChallengeState)
                .WhereIf(challengeQuery.ReuploadEnum != null, t => t.ReuploadEnum == challengeQuery.ReuploadEnum)
                .WhereIf(challengeQuery.IsClosed != null, t => t.IsClosed == challengeQuery.IsClosed)
                .WhereIf(challengeQuery.SiteId != null, t => t.SubjectVisit.SiteId == challengeQuery.SiteId)
                .WhereIf(challengeQuery.SubjectId != null, t => t.SubjectVisit.SubjectId == challengeQuery.SubjectId)
                .WhereIf(challengeQuery.CreateUserId != null, t => t.CreateUserId == challengeQuery.CreateUserId)
                .WhereIf(!string.IsNullOrEmpty(challengeQuery.SubjectCode), t => t.SubjectVisit.Subject.Code.Contains(challengeQuery.SubjectCode))
                .WhereIf(challengeQuery.VisitPlanArray != null && challengeQuery.VisitPlanArray?.Length > 0, svExpression)
                //.WhereIf(!string.IsNullOrEmpty(challengeQuery.VisitPlanInfo), challengeQuery.VisitPlanInfo.Contains('.') ? t => t.SubjectVisit.InPlan == false : t => t.SubjectVisit.VisitNum == decimal.Parse(challengeQuery.VisitPlanInfo))
                .WhereIf(challengeQuery.IsUrgent != null, t => t.SubjectVisit.IsUrgent == challengeQuery.IsUrgent)
                .WhereIf(challengeQuery.IsOverTime != null && challengeQuery.IsOverTime == true, t => t.IsClosed ? t.ClosedTime > t.DeadlineTime : DateTime.Now > t.DeadlineTime)
                .WhereIf(challengeQuery.IsOverTime != null && challengeQuery.IsOverTime == false, t => t.IsClosed ? t.ClosedTime < t.DeadlineTime : DateTime.Now < t.DeadlineTime)
                .ProjectTo<QCChanllengeExportDto>(_mapper.ConfigurationProvider).ToListAsync();

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

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

            exportInfo.List = list;

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


        /// <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> GetSubjectList_Export(SubjectQueryParam param,
                [FromServices] IRepository<CommonDocument> _commonDocumentRepository,
                [FromServices] IDictionaryService _dictionaryService,
                 [FromServices] IRepository<Trial> _trialRepository)
        {

            var list = await _repository.Where<Subject>(u => u.TrialId == param.TrialId)
                  .WhereIf(!string.IsNullOrWhiteSpace(param.Code), t => t.Code.Contains(param.Code))
                  .WhereIf(!string.IsNullOrWhiteSpace(param.Name), t => t.ShortName.Contains(param.Name))
                  .WhereIf(!string.IsNullOrWhiteSpace(param.Sex), t => t.Sex.Contains(param.Sex))
                  .WhereIf(param.Status != null, t => t.Status == param.Status)
                  .WhereIf(param.SiteId != null, t => t.SiteId == param.SiteId)
                  // IC  只负责他管理site的患者
                  .WhereIf(_userInfo.UserTypeEnumInt == (int)UserTypeEnum.ClinicalResearchCoordinator || _userInfo.UserTypeEnumInt == (int)UserTypeEnum.CRA, t => t.TrialSite.CRCUserList.Any(t => t.UserId == _userInfo.Id))
                  .ProjectTo<SubjectExportDTO>(_mapper.ConfigurationProvider).ToListAsync();


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

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

            exportInfo.List = list;

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

        }



        ///// <summary>
        ///// 患者 阅片期 进度表 导出
        ///// </summary>
        ///// <param name="param"></param>
        ///// <param name="_commonDocumentRepository"></param>
        ///// <param name="_dictionaryService"></param>
        ///// <returns></returns>
        //[HttpPost]
        //public async Task<IActionResult> GetSubjectReadingPeriod_Export(GetReadModuleDto dto,
        //        [FromServices] IRepository<CommonDocument> _commonDocumentRepository,
        //        [FromServices] IDictionaryService _dictionaryService,
        //         [FromServices] IRepository<Trial> _trialRepository)
        //{


        //    var list = await _repository.Where<Subject>(u => u.TrialId == dto.TrialId)
        //            .WhereIf(dto.SubjectId != null, x => x.Id == dto.SubjectId)
        //            .WhereIf(dto.TrialSiteCode != null && dto.TrialSiteCode != string.Empty, x => x.TrialSite.TrialSiteCode == dto.TrialSiteCode)
        //            .WhereIf(dto.SubjectCode != null && dto.SubjectCode != string.Empty, x => x.Code == dto.SubjectCode)
        //            //.WhereIf(dto.ReadingStatus != null, x => x.ReadingStatus == dto.ReadingStatus)

        //            .ProjectTo<SubjectExportDTO>(_mapper.ConfigurationProvider).ToListAsync();


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

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

        //    exportInfo.List = list;

        //    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 _repository.Where<Subject>(u => u.TrialId == dto.TrialId)
                        join trialReadingCriterion in _repository.Where<ReadingQuestionCriterionTrial>(u => u.TrialId == dto.TrialId && u.IsConfirm && u.Id == dto.TrialReadingCriterionId) on subject.TrialId equals trialReadingCriterion.TrialId

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


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

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


                        }
               ;


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



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

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

            exportInfo.List = list;

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


            // 使用NPOI  进行二次处理

            var wb = new XSSFWorkbook(memoryStream);

            var sheet = wb.GetSheetAt(0);

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


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

                    var cell = row.CreateCell(visitIndex);

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

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

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

                            default:
                                break;
                        }
                    }



                    cell.SetCellValue(item.TaskName);
                }
            }

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

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

        }


        /// <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> GetStudyUploadMonitor_Export(StudyQuery studyQuery,
        [FromServices] IRepository<CommonDocument> _commonDocumentRepository,
        [FromServices] IDictionaryService _dictionaryService,
         [FromServices] IRepository<Trial> _trialRepository)
        {

            var svExpression = QCCommon.GetStudyMonitorSubjectVisitFilter(studyQuery.VisitPlanArray);
            var StudyMonitorQuery = _repository.Where<StudyMonitor>(t => t.TrialId == studyQuery.TrialId)
                 .WhereIf(_userInfo.UserTypeEnumInt == (int)UserTypeEnum.ClinicalResearchCoordinator || _userInfo.UserTypeEnumInt == (int)UserTypeEnum.CRA, t => t.TrialSite.CRCUserList.Any(t => t.UserId == _userInfo.Id))
                  .WhereIf(studyQuery.VisitPlanArray != null && studyQuery.VisitPlanArray?.Length > 0, svExpression)
                 .WhereIf(!string.IsNullOrWhiteSpace(studyQuery.SubjectInfo), t => t.Subject.Code.Contains(studyQuery.SubjectInfo))
                 .WhereIf(studyQuery.SubjectId != null, t => t.SubjectId == studyQuery.SubjectId)
                 .WhereIf(studyQuery.SubjectVisitId != null, t => t.SubjectId == studyQuery.SubjectVisitId)
                 .WhereIf(studyQuery.SiteId != null, t => t.SiteId == studyQuery.SiteId)
                 .Select(t => new UnionStudyMonitorExportDto()
                 {
                     TrialSiteCode = t.TrialSite.TrialSiteCode,
                     TrialSiteAliasName = t.TrialSite.TrialSiteAliasName,

                     SubjectCode = t.Subject.Code,


                     VisitName = t.SubjectVisit.VisitName,

                     StudyCode = t.StudyCode,

                     IsDicom = t.IsDicom,

                     Uploader = t.Uploader.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 == studyQuery.TrialId).IgnoreQueryFilters().ProjectTo<ExcelExportInfo>(_mapper.ConfigurationProvider).FirstOrDefaultAsync()).IfNullThrowException();

            exportInfo.List = list;

            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 _repository.Where<ReadModule>(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 = list;

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

                        TrialSiteAliasName = t.TrialSite.TrialSiteAliasName,

                        TrialSiteCode = t.TrialSite.TrialSiteCode,

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

                    });

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


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

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

                     TrialSiteAliasName = t.TrialSite.TrialSiteAliasName,

                     TrialSiteCode = t.TrialSite.TrialSiteCode,

                     CheckState = t.SubjectVisit.CheckState,

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

                 });



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

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

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

            exportInfo.List = list;

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


        /// <summary>
        /// 一致性核查记录表  
        /// </summary>
        /// <param name="checkQuery"></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 checkQuery,
                [FromServices] IRepository<CommonDocument> _commonDocumentRepository,
                [FromServices] IDictionaryService _dictionaryService,
                [FromServices] IRepository<Trial> _trialRepository,
                 [FromServices] IRepository<SubjectVisit> _subjectVisitRepository)
        {

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

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

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

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

            exportInfo.List = list;

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




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

                .WhereIf(queryVisitTask.TaskState != null, t => t.TaskState == queryVisitTask.TaskState)
               .WhereIf(queryVisitTask.SiteId != null, t => t.Subject.SiteId == queryVisitTask.SiteId)
               .WhereIf(queryVisitTask.SubjectId != null, t => t.SubjectId == queryVisitTask.SubjectId)
               .WhereIf(queryVisitTask.IsUrgent != null, t => t.IsUrgent == queryVisitTask.IsUrgent)
               .WhereIf(queryVisitTask.DoctorUserId != null, t => t.DoctorUserId == queryVisitTask.DoctorUserId)
               .WhereIf(queryVisitTask.ReadingCategory != null, t => t.ReadingCategory == queryVisitTask.ReadingCategory)
               .WhereIf(queryVisitTask.ReadingTaskState != null, t => t.ReadingTaskState == queryVisitTask.ReadingTaskState)
               .WhereIf(queryVisitTask.TaskAllocationState != null, t => t.TaskAllocationState == queryVisitTask.TaskAllocationState)
               .WhereIf(queryVisitTask.TrialReadingCriterionId != null, t => t.TrialReadingCriterionId == queryVisitTask.TrialReadingCriterionId)


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

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

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


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

            exportInfo.List = list;

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




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


            var list = await _repository.Where<VisitTaskReReading>(t => t.OriginalReReadingTask.TrialId == queryVisitTask.TrialId /*&& t.OriginalReReadingTask.IsAnalysisCreate == false*/)
                .WhereIf(queryVisitTask.RootReReadingTaskId != null, t => t.RootReReadingTaskId == queryVisitTask.RootReReadingTaskId || t.OriginalReReadingTaskId == queryVisitTask.RootReReadingTaskId)
                .WhereIf(!string.IsNullOrEmpty(queryVisitTask.TaskCode), t => t.OriginalReReadingTask.TaskCode.Contains(queryVisitTask.TaskCode!) || t.RootReReadingTask.TaskCode.Contains(queryVisitTask.TaskCode!))
                .WhereIf(queryVisitTask.SiteId != null, t => t.OriginalReReadingTask.Subject.SiteId == queryVisitTask.SiteId)
                .WhereIf(queryVisitTask.TaskState != null, t => t.OriginalReReadingTask.TaskState == queryVisitTask.TaskState)
                .WhereIf(queryVisitTask.ReReadingApplyState != null, t => t.OriginalReReadingTask.ReReadingApplyState == queryVisitTask.ReReadingApplyState)
                .WhereIf(queryVisitTask.SubjectId != null, t => t.OriginalReReadingTask.SubjectId == queryVisitTask.SubjectId)
                .WhereIf(queryVisitTask.IsUrgent != null, t => t.OriginalReReadingTask.IsUrgent == queryVisitTask.IsUrgent)
                .WhereIf(queryVisitTask.DoctorUserId != null, t => t.OriginalReReadingTask.DoctorUserId == queryVisitTask.DoctorUserId)
                .WhereIf(queryVisitTask.ReadingTaskState != null, t => t.OriginalReReadingTask.ReadingTaskState == queryVisitTask.ReadingTaskState)
                .WhereIf(queryVisitTask.TaskAllocationState != null, t => t.OriginalReReadingTask.TaskAllocationState == queryVisitTask.TaskAllocationState)
                 .WhereIf(queryVisitTask.TrialReadingCriterionId != null, t => t.OriginalReReadingTask.TrialReadingCriterionId == queryVisitTask.TrialReadingCriterionId)

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

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

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

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

            exportInfo.List = list;

            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="_dictionaryService"></param>
        /// <param name="_trialRepository"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> GetMedicalReviewTaskList_Export(TaskMedicalReviewQuery inQuery,
                [FromServices] IRepository<CommonDocument> _commonDocumentRepository,
                [FromServices] IDictionaryService _dictionaryService,
                [FromServices] IRepository<Trial> _trialRepository)
        {

            var list = await _repository.Where<TaskMedicalReview>(t => t.VisitTask.TrialId == inQuery.TrialId)
                             .WhereIf(inQuery.SiteId != null, t => t.VisitTask.Subject.SiteId == inQuery.SiteId)
                             .WhereIf(inQuery.SubjectId != null, t => t.VisitTask.SubjectId == inQuery.SubjectId)
                             .WhereIf(!string.IsNullOrEmpty(inQuery.SubjectCode), t => t.VisitTask.Subject.Code.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.ReadingTaskState != null, t => t.VisitTask.ReadingTaskState == inQuery.ReadingTaskState)

                               .WhereIf(inQuery.TrialReadingCriterionId != null, t => t.VisitTask.TrialReadingCriterionId == inQuery.TrialReadingCriterionId)
                             .ProjectTo<TaskMedicalReviewExportDto>(_mapper.ConfigurationProvider).ToListAsync();

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


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

            exportInfo.List = list;

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



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

            var criterion = await _repository.Where<ReadingQuestionCriterionTrial>(t => t.Id == queryVisitTask.TrialReadingCriterionId).Select(t => new { t.CriterionType, t.CriterionName }).FirstOrDefaultAsync();

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

            var subjectQuerybal = _repository.Where<VisitTask>(t => t.TrialId == queryVisitTask.TrialId && t.TaskState == TaskState.Effect && t.IsSelfAnalysis == true).Select(t => t.SubjectId).Distinct();

            var allList = await _repository.Where<VisitTask>(t => t.TrialId == queryVisitTask.TrialId && t.TaskState == TaskState.Effect && subjectQuerybal.Contains(t.SubjectId) && t.ReadingCategory == ReadingCategory.Visit)
                .Where(t => (t.IsSelfAnalysis == true || t.IsSelfAnalysis == null)&& t.VisitTaskNum>0) //一致性分析的结果 + 正常任务的结果 + 仅仅检查批次的结果 +去除基线

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

               .WhereIf(queryVisitTask.TrialReadingCriterionId != null, t => t.TrialReadingCriterionId == queryVisitTask.TrialReadingCriterionId)
               .WhereIf(queryVisitTask.SiteId != null, t => t.Subject.SiteId == queryVisitTask.SiteId)

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



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

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

            //基线和检查批次的评估结果翻译枚举 分别对应着

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


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

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

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

            }


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

            exportInfo.CriterionName = await _repository.Where<ReadingQuestionCriterionTrial>(u => u.TrialId == queryVisitTask.TrialId && u.IsConfirm && u.Id == queryVisitTask.TrialReadingCriterionId).Select(t => t.CriterionName).FirstOrDefaultAsync();
            exportInfo.List = list;

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


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

            if (criterion.CriterionType != CriterionType.RECIST1Pointt1)
            {
                throw new Exception("当前标准导出还未支持");
            }

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

            var subjectQuerybal = _repository.Where<VisitTask>(t => t.TrialId == queryVisitTask.TrialId && t.TaskState == TaskState.Effect && t.IsSelfAnalysis == false).Select(t => t.SubjectId).Distinct();

            var allList = await _repository.Where<VisitTask>(t => t.TrialId == queryVisitTask.TrialId && t.TaskState == TaskState.Effect && subjectQuerybal.Contains(t.SubjectId) && t.ReadingCategory == ReadingCategory.Visit)
                .Where(t => (t.IsSelfAnalysis == false || t.IsSelfAnalysis == null) && t.VisitTaskNum > 0) //一致性分析的结果 + 正常任务的结果 +仅仅检查批次的结果

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

               .WhereIf(queryVisitTask.TrialReadingCriterionId != null, t => t.TrialReadingCriterionId == queryVisitTask.TrialReadingCriterionId)
               .WhereIf(queryVisitTask.SiteId != null, t => t.Subject.SiteId == queryVisitTask.SiteId)

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



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


            var newList = new List<GroupAnalysisExport>();

            // 每个subject检查批次进行分组

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


                //找到当前检查批次组间一致性分析的任务结果

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

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

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


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

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

                        newList.Add(cloneObj);
                    }
                }

            }




            var exportInfo = (await _trialRepository.Where(t => t.Id == queryVisitTask.TrialId).IgnoreQueryFilters().ProjectTo<ExcelExportInfo>(_mapper.ConfigurationProvider).FirstOrDefaultAsync()).IfNullThrowException();
            exportInfo.CriterionName = await _repository.Where<ReadingQuestionCriterionTrial>(u => u.TrialId == queryVisitTask.TrialId && u.IsConfirm && u.Id == queryVisitTask.TrialReadingCriterionId).Select(t => t.CriterionName).FirstOrDefaultAsync();
            exportInfo.List = newList;

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


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

            public string FileName { get; set; }

            public ExportCatogory ExportCatogory { get; set; }
        }


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

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

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


        }

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

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

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

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

            var result = _repository.Where<CommonDocument>(t => list.Select(c => c.Code).Contains(t.Code)).Select(c => new ExportDocumentDes() { Code = c.Code, FileName = c.Name }).ToList();

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

            return list;

        }



        /// <summary>
        /// 整体肿瘤评估  （目前仅仅 RECIST1.1   多个标准一个接口   Excel 列是一样的 ）
        /// </summary>
        /// <param name="queryVisitTask"></param>
        /// <param name="_commonDocumentRepository"></param>
        /// <param name="_dictionaryService"></param>
        /// <param name="_trialRepository"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> GetOverallTumorEvaluationList_Export(VisitTaskQuery queryVisitTask,
                [FromServices] IRepository<CommonDocument> _commonDocumentRepository,
                [FromServices] IDictionaryService _dictionaryService,
                [FromServices] IRepository<Trial> _trialRepository)
        {




            //每次查询必须是单标准的
            var criterion = await _repository.Where<ReadingQuestionCriterionTrial>(t => t.Id == queryVisitTask.TrialReadingCriterionId).Select(t => new { t.CriterionType, t.CriterionName }).FirstNotNullAsync();

            if (criterion.CriterionType != CriterionType.RECIST1Pointt1 && criterion.CriterionType != CriterionType.PCWG3)
            {
                throw new Exception("当前标准导出还未支持");
            }

            var list = await _repository.Where<VisitTask>(t => t.TrialId == queryVisitTask.TrialId && t.TaskState == TaskState.Effect && t.IsAnalysisCreate == false && t.ReadingTaskState == ReadingTaskState.HaveSigned)

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

               .WhereIf(queryVisitTask.TrialReadingCriterionId != null, t => t.TrialReadingCriterionId == queryVisitTask.TrialReadingCriterionId)
               .WhereIf(queryVisitTask.SiteId != null, t => t.Subject.SiteId == queryVisitTask.SiteId)

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

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

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

            exportInfo.List = list;


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

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

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

            var query = _repository.Where<VisitTask>(t => t.TrialId == queryVisitTask.TrialId && t.TaskState == TaskState.Effect && t.IsAnalysisCreate == false && t.ReadingTaskState == ReadingTaskState.HaveSigned)

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

               .WhereIf(queryVisitTask.TrialReadingCriterionId != null, t => t.TrialReadingCriterionId == queryVisitTask.TrialReadingCriterionId)
               .WhereIf(queryVisitTask.SiteId != null, t => t.Subject.SiteId == queryVisitTask.SiteId)

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

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

            if (criterion.CriterionType == CriterionType.RECIST1Pointt1)
            {
                var list = await query.ProjectTo<RECIST1Point1EvaluationOfTumorEfficacyExport>(_mapper.ConfigurationProvider, new { criterionType = criterion.CriterionType }).ToListAsync();

                exportInfo.List = list;

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

            else
            {
                throw new Exception("当前标准导出还未支持");
            }


        }


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

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

            var query = _repository.Where<VisitTask>(t => t.TrialId == queryVisitTask.TrialId && t.TaskState == TaskState.Effect && t.IsAnalysisCreate == false && t.ReadingTaskState == ReadingTaskState.HaveSigned)

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

               .WhereIf(queryVisitTask.TrialReadingCriterionId != null, t => t.TrialReadingCriterionId == queryVisitTask.TrialReadingCriterionId)
               .WhereIf(queryVisitTask.SiteId != null, t => t.Subject.SiteId == queryVisitTask.SiteId)

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

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

            if (criterion.CriterionType == CriterionType.RECIST1Pointt1)
            {
                var list = await query.ProjectTo<RECIST1Point1DetailedOfEvaluatedLesionExport>(_mapper.ConfigurationProvider, new { criterionType = criterion.CriterionType, isEn_Us = _userInfo.IsEn_Us }).ToListAsync();


                var exportList = list.SelectMany(c =>
                {

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

                        clone.IsLymph = u.IsLymph;

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

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

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

                exportInfo.List = exportList;

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


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


                var exportList = list.SelectMany(c =>
                {

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

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

                        clone.LessionState = u.LessionState;

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

                exportInfo.List = exportList;

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

            }

            else
            {
                throw new Exception("当前标准导出还未支持");
            }


        }




        #endregion
    }
}
