using AutoMapper;
using IRaCIS.Application.Interfaces;
using IRaCIS.Core.Application.Contracts.Dicom.DTO;
using IRaCIS.Core.Infra.EFCore;
using IRaCIS.Core.Domain.Share;

using IRaCIS.Core.Application.Contracts;
using IRaCIS.Core.Application.Service.Inspection.Interface;
using IRaCIS.Core.Application.Service.Inspection.DTO;
using Newtonsoft.Json;

namespace IRaCIS.Application.Services
{
    //[Intercept(typeof(QANoticeAOP))]
    public class StudyService : IStudyService
    {
        private readonly IRepository<DicomStudy> _studyRepository;

        private readonly IRepository<SubjectVisit> _subjectVisitRepository;
        private readonly IRepository<DicomInstance> _dicomInstanceRepository;
        private readonly IRepository<DicomSeries> _dicomSeriesRepository;
        private readonly IInspectionService _inspectionService;
        private readonly IUserInfo _userInfo;

        private readonly IMapper _mapper;


        private static string _fileStorePath = string.Empty;

        private readonly IRepository<StudyMonitor> _dicomStudyMonitorRepository;
       




        public StudyService(IRepository<DicomStudy> studyRepository,
            IRepository<SubjectVisit> subjectVisitRepository,
            IRepository<DicomInstance> dicomInstanceRepository,
            IRepository<DicomSeries> dicomSeriesRepository,
            IInspectionService inspectionService,
            IUserInfo userInfo,

             IRepository<StudyMonitor> dicomStudyMonitorRepository,

            IMapper mapper)
        {
            _dicomStudyMonitorRepository = dicomStudyMonitorRepository;

         
            _userInfo = userInfo;
            _studyRepository = studyRepository;

            _subjectVisitRepository = subjectVisitRepository;
            _dicomInstanceRepository = dicomInstanceRepository;
            _dicomSeriesRepository = dicomSeriesRepository;
            this._inspectionService = inspectionService;
            _mapper = mapper;
        }





        /// <summary>
        /// 获取保存到Dicom文件中的信息
        /// </summary>
        /// <param name="subjectVisitId"></param>
        /// <returns></returns>
        public DicomTrialSiteSubjectInfo GetSaveToDicomInfo(Guid subjectVisitId)
        {
            //6表连接 subject trial trialSite sponsor subjectVisit   site 
            var info = _subjectVisitRepository.Where(t => t.Id == subjectVisitId).ProjectTo<DicomTrialSiteSubjectInfo>(_mapper.ConfigurationProvider).FirstOrDefault().IfNullThrowException();

            return info;
        }

        public void GetHasUploadSeriesAndInstance(Guid studyId, ref List<string> seriesInstanceUidList, ref List<string> sopInstanceUidList)
        {
            seriesInstanceUidList = _dicomSeriesRepository.Where(t => t.StudyId == studyId).Select(t => t.SeriesInstanceUid).ToList();

            sopInstanceUidList = _dicomInstanceRepository.Where(t => t.StudyId == studyId).Select(t => t.SopInstanceUid).ToList();
        }

        public  void UploadOrReUploadNeedTodo(ArchiveStudyCommand archiveStudyCommand, List<Guid> archiveStudyIds, ref DicomArchiveResult result,StudyMonitor monitor)
        {


            var archivedStudyId = archiveStudyIds[0];

            result.ArchivedDicomStudies = _studyRepository.Where(t => t.SubjectVisitId == archiveStudyCommand.SubjectVisitId)
                .ProjectTo<DicomStudyBasicDTO>(_mapper.ConfigurationProvider).ToList();

            #region 更新受试者访视信息 及访视状态为待提交  最早最晚拍片时间   访视已执行

            var subjectVisit = _subjectVisitRepository.FirstOrDefaultAsync(t => t.Id == archiveStudyCommand.SubjectVisitId).Result;

            //正常情况下  上传或者重传(待提交之前 要改为待提交 ) QA后上传 不能改为待提交
            if (subjectVisit.SubmitState == SubmitStateEnum.None)
            {
                subjectVisit.SubmitState = SubmitStateEnum.ToSubmit;
            }

            subjectVisit.VisitExecuted = VisitExecutedEnum.Executed;







            ////处理拍片日期
            //var svTime = _subjectVisitRepository.Where(t => t.Id == archiveStudyCommand.SubjectVisitId).Select(t => new
            //{
            //    DicomStudyMinStudyTime = t.StudyList.Min(t => (DateTime?)t.StudyTime),
            //    DicomStudyMaxStudyTime = t.StudyList.Max(t => (DateTime?)t.StudyTime),
            //    NoneDicomStudyMinStudyTime = t.NoneDicomStudyList.Min(t => (DateTime?)t.ImageDate),
            //    NoneDicomStudyMaxStudyTime = t.NoneDicomStudyList.Max(t => (DateTime?)t.ImageDate)
            //}).FirstOrDefault();

            //var minArray = new DateTime?[] { svTime.DicomStudyMinStudyTime, svTime.NoneDicomStudyMinStudyTime };
            //var maxArray = new DateTime?[] { svTime.DicomStudyMaxStudyTime, svTime.NoneDicomStudyMaxStudyTime };

            //subjectVisit.EarliestScanDate = minArray.Min();
            //subjectVisit.LatestScanDate = maxArray.Max();

            #endregion


            //按照访视维度，上传只存在重传同一份，和上传新的(不存在之前检查维度 重传同一份 和重传不同的)

            if (archiveStudyCommand.AbandonStudyId != null && archiveStudyCommand.AbandonStudyId == archivedStudyId)
            {
                result.ReuploadNewStudyId = archivedStudyId;


                // 1、普通上传后重传
                // 2、QC后重传                             
                //_studyService.ReUploadSameStudy(archiveStudyCommand.SubjectVisitId, archivedDicomStudy.Id);

            }//上传
            else
            {
                //汇总  Series的Modality 更新到检查里面 检查状态  上传人
                var seriesModalityList = _dicomSeriesRepository.Where(t => t.StudyId == archivedStudyId).Select(u => u.Modality).Distinct();
                string ModaliyStr = string.Join('、', seriesModalityList.ToList());

                var study = _studyRepository.FirstOrDefaultAsync(t => t.Id == archivedStudyId).Result.IfNullThrowException();
                study.Status = (int)StudyStatus.Uploaded;
                study.Modalities = ModaliyStr;

            }
            _ = _dicomStudyMonitorRepository.AddAsync(monitor).Result;
            _ = _studyRepository.SaveChangesAsync().Result;

       



        }





        //public virtual IResponseOutput ForwardStudy(Guid studyId)
        //{

        //    var study = _studyRepository.FirstOrDefault(u => u.Id == studyId);



        //    //数据库状态，其他人已经操作过了，此时提醒
        //    if (study.Status != (int)StudyStatus.Anonymized)
        //    {
        //        ResponseOutput.NotOk($"当前界面Study:{study.StudyCode} 状态被其他人已变更，不允许该操作，请刷新界面");
        //    }

        //    _studyRepository.Update(t => t.Id == studyId, u => new DicomStudy()
        //    {
        //        Status = (int)StudyStatus.Forwarding
        //    });

        //    var subject = _subjectRepository.FirstOrDefault(u => u.Id == study.SubjectId);
        //    var trial = _trialRepository.FirstOrDefault(u => u.Id == study.TrialId);
        //    var subjectVisit = _subjectVisitRepository.FirstOrDefault(u => u.Id == study.SubjectVisitId);
        //    var targetPath = Path.Combine("/IMPORT-IMAGES",
        //        trial.TrialCode + "_" + subject.Code + "_" + subjectVisit.VisitName + "_" + study.StudyCode);
        //    var path = Path.Combine(_fileStorePath, study.CreateTime.Year.ToString(), study.TrialId.ToString(),
        //        study.SiteId.ToString(), study.SubjectId.ToString(), study.SubjectVisitId.ToString(), study.Id.ToString(), "Data");
        //    try
        //    {
        //        // 主机及端口信息后面可以改到 配置文件
        //        SessionOptions sessionOptions = new SessionOptions
        //        {
        //            Protocol = Protocol.Sftp,
        //            PortNumber = 8022,
        //            HostName = "CS-690-sftp.mint-imaging.com",
        //            UserName = "zdong",
        //            Password = "Everest@2021",
        //            //GiveUpSecurityAndAcceptAnySshHostKey = true,
        //            SshHostKeyFingerprint = @"ecdsa-sha2-nistp384 384 59gkjJ5lMwv3jsB8Wz2B35tBAIor5pSd8PcJYtoamPo="
        //        };
        //        using (Session session = new Session())
        //        {
        //            session.Open(sessionOptions);
        //            if (!session.FileExists(targetPath))
        //            {
        //                session.CreateDirectory(targetPath);
        //            }

        //            var files = (new DirectoryInfo(path)).GetFiles();
        //            foreach (var file in files)
        //            {
        //                if (file.Name.Contains("Anonymize") && file.Extension.Contains("dcm"))
        //                {
        //                    string remoteFilePath =
        //                        RemotePath.TranslateLocalPathToRemote(file.FullName, path, targetPath);
        //                    var result = session.PutFiles(file.FullName, remoteFilePath, false);
        //                    if (!result.IsSuccess)
        //                    {
        //                        return ResponseOutput.NotOk("Forward Failed");
        //                    }
        //                }
        //            }

        //            //_studyStatusDetailRepository.Add(new StudyStatusDetail
        //            //{
        //            //    Status = (int)StudyStatus.Forwarded,
        //            //    StudyId = studyId,
        //            //    Note = string.Empty,
        //            //    OptUserName = _userInfo.RealName,
        //            //    OptTime = DateTime.Now
        //            //});

        //            study.Status = (int)StudyStatus.Forwarded;
        //            _studyRepository.Update(study);

        //            //_workloadTPRepository.Add(new WorkloadTP
        //            //{
        //            //    SiteId = study.SiteId,
        //            //    StudyId = study.Id,
        //            //    SubjectId = study.SubjectId,
        //            //    SubjectVisitId = study.SubjectVisitId,
        //            //    Status = 0,
        //            //    ReviewerId = Guid.Empty,
        //            //    TrialId = study.TrialId,
        //            //    UpdateTime = DateTime.Now,
        //            //    TimepointCode = study.StudyCode + "_T01"
        //            //});
        //            //if (study.IsDoubleReview) //双重阅片，则再添加一条，编号变为T02
        //            //{
        //            //    _workloadTPRepository.Add(new WorkloadTP
        //            //    {
        //            //        SiteId = study.SiteId,
        //            //        StudyId = study.Id,
        //            //        SubjectId = study.SubjectId,
        //            //        SubjectVisitId = study.SubjectVisitId,
        //            //        Status = 0,
        //            //        ReviewerId = Guid.Empty,
        //            //        TrialId = study.TrialId,
        //            //        UpdateTime = DateTime.Now,
        //            //        TimepointCode = study.StudyCode + "_T02"
        //            //    });
        //            //}


        //            return ResponseOutput.Result(_studyRepository.SaveChanges());
        //        }
        //    }
        //    catch (Exception e)
        //    {
        //        _studyRepository.Update(t => t.Id == studyId, u => new DicomStudy()
        //        {
        //            Status = (int)StudyStatus.ForwardFailed
        //        });
        //        return ResponseOutput.NotOk("Forward Failed " + e.Message);
        //    }
        //}








        #region 暂存 读片

        //public IEnumerable<DicomSeriesDTO> GetSeriesList(Guid studyId)
        //{
        //    return _dicomSeriesRepository.Where(s => s.StudyId == studyId).OrderBy(s => s.SeriesNumber).
        //        ThenBy(s => s.SeriesTime).ThenBy(s => s.CreateTime)
        //        .ProjectTo<DicomSeriesDTO>(_mapper.ConfigurationProvider);
        //}


        //public IEnumerable<ImageLabelDTO> GetImageLabel(string tpCode)
        //{
        //    return _imageLabelRepository.Where(s => s.TpCode == tpCode)
        //    .ProjectTo<ImageLabelDTO>(_mapper.ConfigurationProvider);
        //}

        //public bool SaveImageLabelList(ImageLabelCommand imageLabelCommand)
        //{
        //    var success = _imageLabelRepository.Delete(u => u.TpCode == imageLabelCommand.TpCode);
        //    _keyInstanceRepository.Delete(u => u.TpCode == imageLabelCommand.TpCode);
        //    if (imageLabelCommand.ImageLabelList.Count == 0)
        //    {
        //        return true;
        //    }
        //    else
        //    {

        //        foreach (var label in imageLabelCommand.ImageLabelList)
        //        {
        //            _imageLabelRepository.Add(new ImageLabel
        //            {
        //                TpCode = imageLabelCommand.TpCode,
        //                StudyId = label.StudyId,
        //                SeriesId = label.SeriesId,
        //                InstanceId = label.InstanceId,
        //                LabelValue = label.LabelValue
        //            });
        //            _keyInstanceRepository.Add(new KeyInstance
        //            {
        //                TpCode = imageLabelCommand.TpCode,
        //                SeriesId = label.SeriesId,
        //                InstanceId = label.InstanceId,
        //            });
        //        }
        //        success = _imageLabelRepository.SaveChanges();
        //        return success;
        //    }
        //}


        #endregion




        #region 废弃
        //public DicomStudyDTO GetStudyItem(Guid studyId)
        //{
        //    return _mapper.Map<DicomStudyDTO>(_studyRepository.FirstOrDefault(s => s.Id == studyId));
        //}
        //public virtual async Task<IResponseOutput> DicomAnonymize(Guid studyId, string optUserName)
        //{
        //    var study = _studyRepository.FirstOrDefault(t => t.Id == studyId);

        //    //数据库状态，其他人已经操作过了，此时提醒
        //    if (study.Status != (int)StudyStatus.QAFinish)
        //    {
        //        ResponseOutput.NotOk($"当前界面Study:{study.StudyCode} 状态被其他人已变更，不允许该操作，请刷新界面");
        //    }

        //    var subject = _subjectRepository.Select(t => new { Id = t.Id, Code = t.Code }).FirstOrDefault(u => u.Id == study.SubjectId).IfNullThrowException();
        //    var trial = _trialRepository.Select(t => new { Id = t.Id, Code = t.TrialCode }).FirstOrDefault(u => u.Id == study.TrialId).IfNullThrowException();

        //    study.Status = (int)StudyStatus.Anonymizing;


        //    // 查询受试者 信息
        //    //string subjectCde = string.Empty;
        //    //string subjectSex = string.Empty;

        //    //读取Dicom 文件，匿名化

        //    //按照配置文件 匿名化
        //    var dicomSeries = _dicomSeriesRepository.Where(s => s.StudyId == studyId).ToList();
        //    foreach (var seriesItem in dicomSeries)
        //    {
        //        var dicomInstances = _dicomInstanceRepository.Where(s => s.SeriesId == seriesItem.Id).ToList();

        //        foreach (var instanceItem in dicomInstances)
        //        {
        //            _dicomInstanceRepository.Attach(instanceItem);

        //            try
        //            {
        //                string filePath = _dicomFileStoreHelper.CreateInstanceFilePath(study, seriesItem.Id, instanceItem.Id);
        //                DicomFile dicomFile = await DicomFile.OpenAsync(filePath, Encoding.Default);

        //                #region 废弃

        //                //if (SystemConfig.AddClinicalInfo) //是否需要写入临床信息
        //                //{
        //                //    dicomFile.Dataset.AddOrUpdate(DicomTag.ClinicalTrialSubjectID, subjectCde + " " + subjectSex);//SubjectId
        //                //}
        //                //DicomDataset dataset = dicomFile.Dataset;

        //                #endregion

        //                foreach (var anonymizeItem in AppSettings.AnonymizeTagList)
        //                {
        //                    if (anonymizeItem.Enable)
        //                    {
        //                        ushort group = Convert.ToUInt16(anonymizeItem.Group, 16);
        //                        ushort element = Convert.ToUInt16(anonymizeItem.Element, 16);
        //                        dicomFile.Dataset.AddOrUpdate(new DicomTag(group, element), anonymizeItem.ReplaceValue);
        //                    }
        //                }

        //                dicomFile.Dataset.AddOrUpdate(DicomTag.PatientID, trial.Code + "_" + subject.Code);

        //                //_dicomFileStoreHelper.CreateInstanceFilePath(study, seriesItem.Id, instanceItem.Id);

        //                string path = Path.Combine(_fileStorePath, study.CreateTime.Year.ToString(),
        //                    study.TrialId.ToString(),
        //                    study.SiteId.ToString(), study.SubjectId.ToString(), study.SubjectVisitId.ToString(), study.Id.ToString(), "Data");

        //                //await dicomFile.SaveAsync(Path.Combine(path, instanceItem.Id.ToString() + ".dcm"));
        //                await dicomFile.SaveAsync(
        //                    Path.Combine(path, instanceItem.Id.ToString() + ".Anonymize" + ".dcm"));

        //                instanceItem.Anonymize = true;

        //                //_dicomInstanceRepository.Update(instanceItem);
        //            }
        //            catch (Exception ex)
        //            {

        //                study.Status = (int)StudyStatus.AnonymizeFailed;

        //                _dicomInstanceRepository.SaveChanges();

        //                //这个地方返回没用  
        //                return ResponseOutput.NotOk(ex.Message);
        //            }
        //        }

        //    }

        //    study.Status = (int)StudyStatus.Anonymized;

        //    var success = _dicomInstanceRepository.SaveChanges();

        //    return ResponseOutput.Result(success);
        //}
        //public string GetStudyPreview(Guid studyId)
        //{
        //    DicomInstance dicomInstance = _dicomInstanceRepository.FirstOrDefault(s => s.StudyId == studyId);
        //    if (dicomInstance != null)
        //    {
        //        DicomStudy dicomStudy = _studyRepository.FirstOrDefault(s => s.Id == dicomInstance.StudyId);
        //        if (dicomStudy != null)
        //        {
        //            return _dicomFileStoreHelper.GetInstanceFilePath(dicomStudy, dicomInstance.SeriesId, dicomInstance.Id.ToString());
        //        }
        //    }
        //    return string.Empty;
        //}

        //public IEnumerable<RelationStudyDTO> GetAllRelationStudyList(Guid subjectVisitId)
        //{
        //    #region 废弃
        //    //var studylist = _studyRepository.Where(u => u.SubjectVisitId == subjectVisitId && u.IsDeleted == false).Select(t => new { StudyId = t.Id, t.SubjectId, t.TrialId }).ToList();
        //    //var subjectId = studylist.FirstOrDefault().SubjectId;
        //    //var trialId = studylist.FirstOrDefault().TrialId;
        //    //var studyIds = studylist.Select(t => t.StudyId).ToList();


        //    //var query = from studyItem in _studyRepository.Where(u => u.SubjectId == subjectId
        //    //                                                                   && u.TrialId == trialId && u.IsDeleted == false &&
        //    //                                                                   !studyIds.Contains(u.Id)
        //    //                                                                    /* && u.Status != (int)StudyStatus.Abandon*/)
        //    //            join visitItem in _subjectVisitRepository.AsQueryable()
        //    //                on studyItem.SubjectVisitId equals visitItem.Id
        //    //            select new RelationStudyDTO
        //    //            {
        //    //                StudyId = studyItem.Id,
        //    //                StudyCode = studyItem.StudyCode,
        //    //                VisitName = visitItem.VisitName,
        //    //                Modalities = studyItem.Modalities,
        //    //                Description = studyItem.Description,
        //    //                SeriesCount = studyItem.SeriesCount
        //    //            };
        //    #endregion

        //    var studyInfo = _studyRepository.Where(u => u.SubjectVisitId == subjectVisitId).Select(t => new { t.SubjectId, t.TrialId }).FirstOrDefault().IfNullThrowException();

        //    var query = _studyRepository.Where(t => t.SubjectVisitId != subjectVisitId && t.TrialId == studyInfo.TrialId && t.SubjectId == studyInfo.SubjectId)
        //        .ProjectTo<RelationStudyDTO>(_mapper.ConfigurationProvider).ToList();

        //    return query.OrderBy(u => u.VisitName).ThenBy(s => s.StudyCode).ToList();
        //}


        ///// <summary>
        ///// 检查列表
        ///// </summary>
        ///// <param name="queryDto"></param>
        ///// <returns></returns>
        //public PageOutput<StudyDTO> GetStudyList(StudyQueryDTO queryDto)
        //{
        //    var query = _studyRepository.Where(x => x.TrialId == queryDto.TrialId)
        //          .WhereIf(queryDto.SubjectId != null, t => t.SubjectId == queryDto.SubjectId)
        //          .WhereIf(queryDto.SubjectVisitId != null, t => t.SubjectId == queryDto.SubjectVisitId)
        //          .WhereIf(!string.IsNullOrEmpty(queryDto.VisitPlanInfo), queryDto.VisitPlanInfo.Contains('.') ? t => t.SubjectVisit.VisitNum.ToString().Contains(".") : t => t.SubjectVisit.VisitNum == decimal.Parse(queryDto.VisitPlanInfo))
        //          .WhereIf(queryDto.StudyTimeBegin != null, t => t.StudyTime >= queryDto.StudyTimeBegin)
        //          .WhereIf(queryDto.StudyTimeEnd != null, t => t.StudyTime <= queryDto.StudyTimeEnd)
        //          .WhereIf(queryDto.UpdateTimeBegin != null, t => t.StudyTime >= queryDto.UpdateTimeBegin)
        //          .WhereIf(queryDto.UpdateTimeEnd != null, t => t.StudyTime <= queryDto.UpdateTimeEnd)
        //          .WhereIf(queryDto.SiteId != null, t => t.SiteId == queryDto.SiteId)
        //          .WhereIf(_userInfo.UserTypeEnumInt == (int)UserTypeEnum.ClinicalResearchCoordinator, t => t.TrialSite.CRCUserList.Any(t => t.UserId == _userInfo.Id))
        //          .WhereIf(!string.IsNullOrWhiteSpace(queryDto.SubjectInfo), t => t.Subject.Code.Contains(queryDto.SubjectInfo))
        //          .ProjectTo<StudyDTO>(_mapper.ConfigurationProvider);


        //    var list = query.ToPagedList(queryDto.PageIndex, queryDto.PageSize, queryDto.SortField == string.Empty ? "StudyCode" : queryDto.SortField, queryDto.Asc);


        //    foreach (var item in list.CurrentPageData)
        //    {
        //        if (item.PatientBirthDate.Length == 8)
        //        {
        //            item.PatientBirthDate =
        //                $"{item.PatientBirthDate[0]}{item.PatientBirthDate[1]}{item.PatientBirthDate[2]}{item.PatientBirthDate[3]}-{item.PatientBirthDate[4]}{item.PatientBirthDate[5]}-{item.PatientBirthDate[6]}{item.PatientBirthDate[7]}";
        //        }
        //    }

        //    return list;
        //}



        //public IResponseOutput DeleteStudy(Guid id)
        //{
        //    var needDelete = _studyRepository.FirstOrDefault(t => t.Id == id);

        //    if (needDelete == null)
        //    {
        //        return ResponseOutput.DBNotExistIfNUll(needDelete);
        //    }
        //    else //移除内存中缓存的StudyCode  这样刚上传的，删除 再上传还是用同样的Code
        //    {

        //        if (_provider.Get<string>($"{needDelete.TrialId }_{ StaticData.StudyMaxCode}").Value == needDelete.StudyCode)
        //        {
        //            _provider.Remove($"{needDelete.TrialId }_{ StaticData.StudyMaxCode}");
        //        }
        //    }



        //    //if (study.Status != (int)StudyStatus.Uploaded)
        //    //{
        //    //    return ResponseOutput.NotOk("This study has been quality controlled and couldn't be deleted ");
        //    //}

        //    #region 废弃的直接删除了  这里不用处理了

        //    ////处理废弃的Study  如果有的话  
        //    //var oldStudy = _studyRepository.FirstOrDefault(t => t.StudyCode == study.StudyCode && t.Id != id);
        //    //if (oldStudy != null)
        //    //{
        //    //    _studyRepository.Delete(t => t.Id == oldStudy.Id);
        //    //    _dicomInstanceRepository.Delete(t => t.StudyId == oldStudy.Id);
        //    //    _dicomSeriesRepository.Delete(t => t.StudyId == oldStudy.Id);
        //    //}
        //    //处理废弃的Study
        //    //var success5 = _studyRepository.Delete(t => t.StudyCode == study.StudyCode);
        //    #endregion


        //    //清除现有Study记录
        //    var success1 = _studyRepository.Delete(t => t.Id == id);
        //    var succeess2 = _dicomInstanceRepository.Delete(t => t.StudyId == id);
        //    var success3 = _dicomSeriesRepository.Delete(t => t.StudyId == id);


        //    //一个访视下面有多个检查，所以需要检测 没有的时候才清空
        //    if (_studyRepository.Count(t => t.SubjectVisitId == needDelete.SubjectVisitId) == 0)
        //    {
        //        _subjectVisitRepository.Update(t => t.Id == needDelete.SubjectVisitId,

        //         u => new SubjectVisit() { VisitExecuted = VisitExecutedEnum.UnExecuted, SVENDTC = null, SVSTDTC = null });

        //        _qcChallengeRepository.Delete(t => t.SubjectVisitId == needDelete.SubjectVisitId);

        //        //_qcChallengeRepository.Delete(t => t.SubjectVisitId == subjectVisitId);

        //        //_trialQCQuestionAnswerRepository.Delete(t => t.SubjectVisitId == subjectVisitId);
        //    }





        //    return ResponseOutput.Result(success1 || succeess2 || success3);
        //}

        //public void ClearStudyInstanceAndSeriseData(Guid studyId)
        //{
        //    //重新开始计数，怕数据库又脏数据，影响数量
        //    _studyRepository.Update(t => t.Id == studyId, u => new DicomStudy()
        //    {
        //        InstanceCount = 0,
        //        SeriesCount = 0
        //    });

        //    _dicomSeriesRepository.Delete(t => t.StudyId == studyId);
        //    _dicomInstanceRepository.Delete(t => t.StudyId == studyId);
        //}



        //public bool ReUploadDifferentStudy(Guid subjectVisitId, Guid abandonStudyId, Guid newStudyId)
        //{
        //    //_qcChallengeRepository.Update(t => t.SubjectVisitId == subjectVisitId && t.NeedReUpload == true, u => new QCChallenge() { ReUploadedTime = DateTime.Now, ReUploader = _userInfo.RealName });

        //    //注意这里不是用SeqId  主键查询，因为Seq id 是后续加的，为了不改变代码和前端接口参数
        //    var study = _studyRepository.FirstOrDefault(t => t.Id == abandonStudyId);

        //    var code = study.StudyCode;

        //    //清理以前的数据
        //    _studyRepository.Delete(t => t.Id == abandonStudyId);
        //    _dicomInstanceRepository.Delete(t => t.StudyId == abandonStudyId);
        //    _dicomSeriesRepository.Delete(t => t.StudyId == abandonStudyId);

        //    ////将以前的qa记录数据绑定到现在新生成的Study上
        //    //_qaNoticeRepository.Update(t => t.SubjectVisitId == abandonStudyId, u => new QANotice() { SubjectVisitId = newStudyId });
        //    //_qaNoticeUserRepository.Update(t => t.SubjectVisitId == abandonStudyId,
        //    //    u => new QANoticeUser() { SubjectVisitId = newStudyId });
        //    //_qaRecordRepository.Update(t => t.SubjectVisitId == abandonStudyId, u => new QARecord() { SubjectVisitId = newStudyId });


        //    var success = false;
        //    if (study.Status == (int)StudyStatus.Uploading)
        //    {
        //        success = _studyRepository.Update(t => t.Id == newStudyId, u => new DicomStudy()
        //        {
        //            Status = (int)StudyStatus.Uploaded,
        //            StudyCode = code
        //        });
        //    }
        //    else
        //    {
        //        //新一份的影像状态为旧影像的状态  不改变
        //        success = _studyRepository.Update(t => t.Id == newStudyId, u => new DicomStudy()
        //        {
        //            Status = study.Status,
        //            StudyCode = code
        //        });
        //    }



        //    #region 废弃之前的Study记录  讲新产生的记录的StudyCode  变更为老的  这样可以关联在一起

        //    //var realName = _userInfo.RealName;
        //    //var code = _studyRepository.GetAll().First(t => t.Id == abandonStudyId).StudyCode;
        //    //_studyRepository.Update(t => t.Id == abandonStudyId, u => new DicomStudy()
        //    //{
        //    //    Status = (int)StudyStatus.Abandon
        //    //});
        //    //_studyRepository.Update(t => t.Id == newStudyId, u => new DicomStudy()
        //    //{
        //    //    Status = (int)StudyStatus.Uploaded,
        //    //    StudyCode = code
        //    //});
        //    //_studyStatusDetailRepository.Add(new StudyStatusDetail
        //    //{
        //    //    Status = (int)StudyStatus.Abandon,
        //    //    StudyId = abandonStudyId,
        //    //    Note = string.Empty,
        //    //    OptUserName = realName,
        //    //    OptTime = DateTime.Now
        //    //});
        //    //_studyStatusDetailRepository.Add(new StudyStatusDetail
        //    //{
        //    //    Status = (int)StudyStatus.Uploaded,
        //    //    StudyId = newStudyId,
        //    //    Note = string.Empty,
        //    //    OptUserName = realName,
        //    //    OptTime = DateTime.Now
        //    //});

        //    //_studyStatusDetailRepository.SaveChanges();

        //    #endregion


        //    return success;

        //}


        //public virtual void ReUploadSameStudy(Guid subjectVisitId, Guid studyId)
        //{
        //    //_qcChallengeRepository.Update(t => t.SubjectVisitId == subjectVisitId && t.NeedReUpload == true, u => new QCChallenge() { ReUploadedTime = DateTime.Now, ReUploader = _userInfo.RealName });

        //    #region  之前整个上传过程操作没有放在一个整体事务  会有脏数据    现在整体一个事务，不会产生，废弃 但是切入AOP 所以保留空方法
        //    //var study = _studyRepository.FirstOrDefault(t=>t.Id== studyId);
        //    //var status = study.Status;

        //    //if (status == (int)StudyStatus.Uploading)
        //    //{
        //    //    _studyRepository.Update(t => t.Id == studyId, u => new DicomStudy()
        //    //    {
        //    //        Status = (int)StudyStatus.Uploaded
        //    //    });
        //    //}
        //    #endregion
        //}
        ///// <summary>
        ///// 上传完检查后，处理检查 汇总  Series的Modality 更新到检查里面 检查状态  上传人
        ///// </summary>
        ///// <param name="studyId"></param>
        //public void UploadStudyDeal(Guid studyId)
        //{

        //    var seriesModalityList = _dicomSeriesRepository.Where(t => t.StudyId == studyId).Select(u => u.Modality).Distinct();
        //    string ModaliyStr = string.Join('、', seriesModalityList.ToList());

        //    var study = _studyRepository.FirstOrDefault(t => t.Id == studyId);
        //    study.Status = (int)StudyStatus.Uploaded;
        //    study.Modalities = ModaliyStr;
        //    _studyRepository.SaveChanges();
        //}


        //public List<SubjectVisitStudyDTO> GetSubjectVisitStudyList(Guid trialId, Guid siteId, Guid subjectId, Guid subjectVisitId)
        //{
        //    var query = _studyRepository.Where(t => t.TrialId == trialId && t.SiteId == siteId && t.SubjectId == t.SubjectId && t.SubjectVisitId == subjectVisitId)
        //        .Select(u => new SubjectVisitStudyDTO() { Modalities = u.Modalities, StudyCode = u.StudyCode, StudyId = u.Id, Status = u.Status });

        //    return query.ToList();
        //}

        ////此处有AOP操作，不要更改为动态Api
        //public virtual IResponseOutput UpdateStudyStatus(StudyStatusDetailCommand studyStatus)
        //{

        //    //注意这里不是用SeqId  主键查询，因为Seq id 是后续加的，为了不改变代码和前端接口参数
        //    var study = _studyRepository.FirstOrDefault(t => t.Id == studyStatus.StudyId);

        //    //数据库状态，其他人已经操作过了，此时提醒
        //    if (study.Status > studyStatus.Status)
        //    {
        //        ResponseOutput.NotOk($"当前界面Study:{study.StudyCode} 状态被其他人已变更，不允许该操作，请刷新界面");
        //    }

        //    ////防止多次调用，更新 没必要
        //    //if (study.Status == studyStatus.Status)
        //    //{
        //    //    return ResponseOutput.Ok();
        //    //}

        //    study.Status = studyStatus.Status;
        //    study.UpdateTime = DateTime.Now;

        //    //if (studyStatus.Status == (int)StudyStatus.Uploaded)
        //    //{
        //    //    study.UploadedTime = DateTime.Now;
        //    //    study.Uploader = _userInfo.RealName;


        //    //}
        //    //if (study.Status == (int)StudyStatus.QAing)
        //    //{
        //    //    study.DeadlineTime = studyStatus.DeadlineTime;
        //    //}

        //    if (studyStatus.Status == (int)StudyStatus.QAFInishNotPass)
        //    {
        //        study.QAComment = studyStatus.QAComment;
        //    }


        //    return ResponseOutput.Ok(_studyRepository.SaveChanges());
        //}

        //public List<StudyStatusDetailDTO> GetStudyStatusDetailList(Guid studyId)
        //{
        //    return _studyStatusDetailRepository.Where(s => s.StudyId == studyId).OrderByDescending(s => s.OptTime)
        //        .ProjectTo<StudyStatusDetailDTO>(_mapper.ConfigurationProvider).ToList();
        //}


        //public bool DistributeStudy(StudyReviewerCommand studyReviewer)
        //{
        //    //更新Study表中，总的状态
        //    // 插入中间表
        //    studyReviewer.StudyList.ForEach(study =>
        //    {
        //        var workloadType = 1;
        //        StudyStatus studyStatus = StudyStatus.Distributed;

        //        if (study.Status >= (int)StudyStatus.NeedAd)
        //        {
        //            workloadType = 2;
        //            studyStatus = StudyStatus.AdDistributed;
        //        }

        //        var tempStudy = _studyRepository.FirstOrDefault(s => s.Id == study.StudyId);
        //        tempStudy.Status = (int)studyStatus;
        //        _studyRepository.Update(tempStudy);

        //        _studyReviewerRepository.Add(new StudyReviewer()
        //        {
        //            ReviewerId = studyReviewer.ReviewerId,
        //            StudyId = study.StudyId,
        //            WorkloadType = workloadType,
        //            TrialId = studyReviewer.TrialId,
        //            Status = (int)studyStatus
        //        });
        //    });

        //    return _studyReviewerRepository.SaveChanges();
        //}


        //public IResponseOutput EditStudyReviewer(StudyReviewerEditCommand studyReviewerEditCommand)
        //{
        //    _studyReviewerRepository.Delete(t => studyReviewerEditCommand.StudyId == t.StudyId);

        //    if (studyReviewerEditCommand.IsDoubleReview)
        //    {
        //        if (studyReviewerEditCommand.ReviewerId1 != null)
        //        {
        //            _studyReviewerRepository.Add(
        //                new StudyReviewer()
        //                {
        //                    StudyId = studyReviewerEditCommand.StudyId,
        //                    TrialId = studyReviewerEditCommand.TrialId,
        //                    ReviewerId = studyReviewerEditCommand.ReviewerId1.Value,
        //                    WorkloadType = 1
        //                });
        //        }

        //        if (studyReviewerEditCommand.ReviewerId2 != null)
        //        {
        //            _studyReviewerRepository.Add(
        //                new StudyReviewer()
        //                {
        //                    StudyId = studyReviewerEditCommand.StudyId,
        //                    TrialId = studyReviewerEditCommand.TrialId,
        //                    ReviewerId = studyReviewerEditCommand.ReviewerId2.Value,
        //                    WorkloadType = 1
        //                });
        //        }

        //        if (studyReviewerEditCommand.ReviewerIdForAD != null)
        //        {
        //            _studyReviewerRepository.Add(
        //                new StudyReviewer()
        //                {
        //                    StudyId = studyReviewerEditCommand.StudyId,
        //                    TrialId = studyReviewerEditCommand.TrialId,
        //                    ReviewerId = studyReviewerEditCommand.ReviewerIdForAD.Value,
        //                    WorkloadType = 2
        //                });
        //        }

        //        if (studyReviewerEditCommand.ReviewerId2 == null || studyReviewerEditCommand.ReviewerId1 == null)
        //        {
        //            _studyRepository.Update(t => t.Id == studyReviewerEditCommand.StudyId,
        //                u => new DicomStudy()
        //                {
        //                    Status = (int)StudyStatus.QAFinish
        //                });
        //        }
        //    }
        //    else
        //    {
        //        if (studyReviewerEditCommand.ReviewerId1 != null)
        //        {
        //            _studyReviewerRepository.Add(
        //                new StudyReviewer()
        //                {
        //                    StudyId = studyReviewerEditCommand.StudyId,
        //                    TrialId = studyReviewerEditCommand.TrialId,
        //                    ReviewerId = studyReviewerEditCommand.ReviewerId1.Value,
        //                    WorkloadType = 1
        //                });
        //        }
        //        else
        //        {
        //            _studyRepository.Update(t => t.Id == studyReviewerEditCommand.StudyId,
        //                u => new DicomStudy()
        //                {
        //                    Status = (int)StudyStatus.QAFinish
        //                });
        //        }
        //    }

        //    var success = _studyReviewerRepository.SaveChanges();
        //    return ResponseOutput.Result(success);
        //}

        //public List<ReviewerDistributionDTO> GetReviewerListByTrialId(Guid trialId)
        //{
        //    var query = from enrollItem in _enrollRepository
        //            .Where(t => t.TrialId == trialId && t.EnrollStatus >= 10)
        //                join doctorItem in _doctorRepository.AsQueryable()
        //                    on enrollItem.DoctorId equals doctorItem.Id into g
        //                from doctor in g.DefaultIfEmpty()
        //                select new
        //                {
        //                    ReviewerCode = doctor.ReviewerCode,
        //                    FirstName = doctor.FirstName,
        //                    LastName = doctor.LastName,
        //                    ReviewerId = enrollItem.DoctorId,
        //                    ActivelyReading = doctor.ActivelyReading,
        //                };

        //    return query.Where(s => s.ActivelyReading).Select(s => new ReviewerDistributionDTO
        //    {
        //        ReviewerCode = s.ReviewerCode,
        //        FirstName = s.FirstName,
        //        LastName = s.LastName,
        //        ReviewerId = s.ReviewerId,

        //    }).ToList();
        //}


        //public PageOutput<DistributeReviewerStudyStatusDTO> GetDistributeStudyList(
        //  StudyStatusQueryDTO studyStatusQueryDto)
        //{
        //    Expression<Func<StudyReviewer, bool>> studyReviewerLambda = x => x.TrialId == studyStatusQueryDto.TrialId;

        //    if (studyStatusQueryDto.ReviewerId != null)
        //    {
        //        studyReviewerLambda = studyReviewerLambda.And(t => t.ReviewerId == studyStatusQueryDto.ReviewerId);
        //    }

        //    if (studyStatusQueryDto.StudyStatus != null)
        //    {
        //        studyReviewerLambda = studyReviewerLambda.And(t => t.Status == studyStatusQueryDto.StudyStatus);
        //    }

        //    var query = from studyReviewer in _studyReviewerRepository.Where(studyReviewerLambda)
        //                join doctor in _doctorRepository.AsQueryable() on studyReviewer.ReviewerId equals doctor.Id
        //                join study in _studyRepository.AsQueryable() on studyReviewer.StudyId equals study.Id
        //                select new DistributeReviewerStudyStatusDTO()
        //                {
        //                    Name = doctor.LastName + " / " + doctor.FirstName,
        //                    NameCN = doctor.ChineseName,
        //                    ReviewerCode = doctor.ReviewerCode,
        //                    Status = studyReviewer.Status,
        //                    StudyCode = study.StudyCode
        //                };

        //    return query.ToPagedList(studyStatusQueryDto.PageIndex,
        //        studyStatusQueryDto.PageSize, studyStatusQueryDto.SortField == string.Empty
        //            ? "ReviewerCode"
        //            : studyStatusQueryDto.SortField, studyStatusQueryDto.Asc);


        //}

        //public IEnumerable<RelationVisitDTO> GetRelationVisitList(decimal visitNum, string tpCode)
        //{
        //    string tpGroup = tpCode.Substring(tpCode.Length - 3, 3);
        //    var tp = _workloadTPRepository.FirstOrDefault(u => u.TimepointCode == tpCode);
        //    var query = from workloadTp in _workloadTPRepository.Where(u => u.SubjectId == tp.SubjectId
        //                                                                             && u.TrialId == tp.TrialId &&
        //                                                                             u.TimepointCode.Contains(tpGroup))
        //                join subjectVisit in _subjectVisitRepository.Where(u => u.VisitNum <= visitNum)
        //                    on workloadTp.SubjectVisitId equals subjectVisit.Id
        //                select new RelationVisitDTO
        //                {
        //                    StudyId = workloadTp.StudyId,
        //                    TpCode = workloadTp.TimepointCode,
        //                    VisitName = subjectVisit.VisitName
        //                };
        //    return query.ToList();
        //}

        //public List<QANoticeDTO> GetQANoticeList(Guid subjectVisitId)
        //{

        //    var query = from noticeUser in _qaNoticeUserRepository.AsQueryable()
        //            .Where(t => t.ToUserId == _userInfo.Id && t.SubjectVisitId == subjectVisitId)
        //                join notice in _qaNoticeRepository.Where(u => u.NeedDeal == true && u.SubjectVisitId == subjectVisitId) on
        //                    noticeUser.QANoticeId equals notice.Id
        //                select notice.Id;

        //    var noticeUserList = query.ToList();

        //    //待处理的消息数量
        //    var count = noticeUserList.Count;


        //    var list = _qaNoticeRepository.Where(t => t.SubjectVisitId == subjectVisitId)
        //        .ProjectTo<QANoticeDTO>(_mapper.ConfigurationProvider).OrderByDescending(t => t.SendTime).ToList();

        //    list.ForEach(t => t.IsMessageReceiver = count > 0 && noticeUserList.Contains(t.Id) ? t.NeedDeal : false);


        //    return list;
        //}

        //public IResponseOutput DealNonDicomFile(Dictionary<string, string> filePathDic,
        //    ArchiveStudyCommand archiveStudyCommand)
        //{


        //    var savedInfo = GetSaveToDicomInfo(archiveStudyCommand.SubjectVisitId);

        //    var dicomStudy = new DicomStudy
        //    {
        //        Id = Guid.NewGuid(),

        //        //SiteId = addtionalInfo.SiteId,
        //        //TrialId = addtionalInfo.TrialId,
        //        //SubjectId = addtionalInfo.SubjectId,
        //        //SubjectVisitId = addtionalInfo.SubjectVisitId,
        //        IsDoubleReview = savedInfo.IsDoubleReview,
        //        Comment = savedInfo.Comment
        //    };



        //    #region Setting Code

        //    //var last = _studyRepository.Where(s => s.TrialId == addtionalInfo.TrialId)
        //    //    .OrderByDescending(c => c.StudyCode).FirstOrDefault();
        //    //if (last != null)
        //    //{
        //    //    var len = last.StudyCode.Length;
        //    //    if (len > 5 && int.TryParse(last.StudyCode.Substring(len - 5, 5), out var num))
        //    //    {
        //    //        dicomStudy.StudyCode = "ST" + (++num).ToString().PadLeft(5, '0');
        //    //    }
        //    //    else
        //    //    {
        //    //        return ResponseOutput.NotOk("Generate StudyCode failed");
        //    //    }
        //    //}
        //    //else
        //    //{
        //    //    dicomStudy.StudyCode = "ST" + 1.ToString().PadLeft(5, '0');
        //    //}

        //    #endregion

        //    var study = _studyRepository.Add(dicomStudy);
        //    var saveFileList = new List<NoneDicomFile>();

        //    foreach (var key in filePathDic.Keys)
        //    {
        //        saveFileList.Add(new NoneDicomFile() { FileName = filePathDic[key], StudyId = study.Id, Path = key });
        //    }


        //    _noneDicomFileRepository.AddRange(saveFileList);



        //    var success = _noneDicomFileRepository.SaveChanges();

        //    UpdateStudyStatus(new StudyStatusDetailCommand
        //    {
        //        StudyId = study.Id,
        //        Status = (int)StudyStatus.Uploaded,
        //        Note = string.Empty
        //    });


        //    return ResponseOutput.Result(success);

        //}
        #endregion


    }
}
