using IRaCIS.Core.Application.Contracts;
using IRaCIS.Core.Application.Interfaces;
using IRaCIS.Core.Application.Service.Reading.Interface;
using IRaCIS.Core.Application.ViewModel;
using IRaCIS.Core.Domain.Share;
using IRaCIS.Core.Infrastructure;
using Microsoft.AspNetCore.Mvc;
using System.Linq.Dynamic.Core;

namespace IRaCIS.Core.Application
{
    [ApiExplorerSettings(GroupName = "Trial")]
    public class PersonalWorkstation(
        IRepository<Trial> _trialRepository,
        IRepository<TrialDocument> _trialDocumentRepository,
        IRepository<SystemDocument> _systemDocumentRepository,
        IClinicalAnswerService _clinicalAnswerService,
        IRepository<SystemNotice> _systemNoticeRepository,
        IMapper _mapper, IUserInfo _userInfo, IStringLocalizer _localizer) : BaseService
    {




        /// <summary>
        /// 中心调研    每个项目 需要处理的审批统计
        /// </summary>
        /// <param name="inQuery"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<PageOutput<TrialSiteSurveyStat>> GetSiteSurveyApprovalList(TrialSiteSurveyStatQuery inQuery)
        {


            if (_userInfo.UserTypeEnumInt == (int)UserTypeEnum.ProjectManager ||
                _userInfo.UserTypeEnumInt == (int)UserTypeEnum.APM ||
                _userInfo.UserTypeEnumInt == (int)UserTypeEnum.CPM ||
                _userInfo.UserTypeEnumInt == (int)UserTypeEnum.SPM)
            {
                return await _trialRepository
                    .Where(t => t.TrialStatusStr == StaticData.TrialState.TrialOngoing)
                    .Where(t => t.TrialUserList.Any(t => t.UserId == _userInfo.Id))
                    .WhereIf(_userInfo.UserTypeEnumInt == (int)UserTypeEnum.ProjectManager || _userInfo.UserTypeEnumInt == (int)UserTypeEnum.APM, c => c.TrialSiteSurveyList.Where(t => t.State == TrialSiteSurveyEnum.SPMApproved).Count() > 0)
                    .WhereIf(_userInfo.UserTypeEnumInt == (int)UserTypeEnum.CPM || _userInfo.UserTypeEnumInt == (int)UserTypeEnum.SPM, c => c.TrialSiteSurveyList.Where(t => t.State == TrialSiteSurveyEnum.CRCSubmitted).Count() > 0)
                    .ProjectTo<TrialSiteSurveyStat>(_mapper.ConfigurationProvider, new { userTypeEnumInt = _userInfo.UserTypeEnumInt, userId = _userInfo.Id })
                    .OrderByDescending(t => t.ApprovalRequiredCount).ToPagedListAsync(inQuery);
            }

            else
            {
                return new PageOutput<TrialSiteSurveyStat>(inQuery.PageIndex, inQuery.PageSize, 0, new List<TrialSiteSurveyStat>());

            }

        }


        /// <summary>
        ///   待签署的项目文件      需要签署文件数量  系统级别的在第一行
        /// </summary>
        /// <param name="inQuery"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<PageOutput<DocSignStat>> GetTrialDocStatList(TrialSiteSurveyStatQuery inQuery)
        {
            if (_userInfo.IsAdmin)
            {
                return new PageOutput<DocSignStat>(inQuery.PageIndex, inQuery.PageSize, 0, new List<DocSignStat>());
            }
            else
            {
                var trialDocStat = await _trialRepository.Where(t => t.TrialStatusStr == StaticData.TrialState.TrialOngoing)
                    .Where(t => t.TrialUserList.Any(t => t.UserId == _userInfo.Id))
                    .WhereIf(!_userInfo.IsAdmin, c => c.TrialDocumentList.Where(t => t.IsDeleted == false && t.NeedConfirmedUserTypeList.Any(t => t.NeedConfirmUserTypeId == _userInfo.UserTypeId) && !t.TrialDocConfirmedUserList.Any(t => t.ConfirmUserId == _userInfo.Id && t.ConfirmTime != null))
                            .Count() > 0)
                    .ProjectTo<DocSignStat>(_mapper.ConfigurationProvider, new { userTypeEnumInt = _userInfo.UserTypeEnumInt, userId = _userInfo.Id, userTypeId = _userInfo.UserTypeId })
                    .OrderByDescending(t => t.WaitSignCount)
                    .ToPagedListAsync(inQuery);


                return trialDocStat;
            }

        }


        #region PM  APM 待办

        /// <summary>
        /// 一致性核查待处理  -- PM  APM 待办
        /// </summary>
        /// <param name="inQuery"></param>
        /// <param name="_subjectVisitRepository"></param>
        /// <param name="_trialRepository"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IResponseOutput<PageOutput<CheckToBeDoneDto>>> GetCheckToBeDoneList(CheckToBeDoneQuery inQuery,
            [FromServices] IRepository<SubjectVisit> _subjectVisitRepository,
              [FromServices] IRepository<Trial> _trialRepository)
        {

            var query = _trialRepository
                .Where(t => t.TrialStatusStr == StaticData.TrialState.TrialOngoing)
                .Where(t => t.TrialUserList.Any(t => t.UserId == _userInfo.Id))
                .Select(t => new CheckToBeDoneDto()
                {
                    TrialId = t.Id,
                    ResearchProgramNo = t.ResearchProgramNo,
                    ExperimentName = t.ExperimentName,
                    TrialCode = t.TrialCode,
                    UrgentCount = t.SubjectVisitList.Where(u => (u.CheckState == CheckStateEnum.ToCheck || u.CheckState == CheckStateEnum.CVIng) && u.IsUrgent).Count(),

                    ToBeCheckedCount = t.SubjectVisitList.Where(u => u.CheckState == CheckStateEnum.ToCheck).Count(),

                    ToBeRepliedCount = t.SubjectVisitList.Where(u => u.CheckState == CheckStateEnum.CVIng &&
                    u.CheckChallengeDialogList.OrderByDescending(t => t.CreateTime).First().UserTypeEnum == UserTypeEnum.ClinicalResearchCoordinator).Count(),
                }).Where(x => x.ToBeRepliedCount + x.ToBeCheckedCount > 0);


            var defalutSortArray = new string[] { nameof(CheckToBeDoneDto.UrgentCount) + " desc", nameof(CheckToBeDoneDto.ToBeCheckedCount) + " desc" };

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

            var totalToBeCheckedCount = await _subjectVisitRepository.Where(t => t.Trial.TrialStatusStr == StaticData.TrialState.TrialOngoing)
                .Where(t => t.Trial.TrialUserList.Any(t => t.UserId == _userInfo.Id))
                .Where(u => u.CheckState == CheckStateEnum.ToCheck).CountAsync();

            var totalToBeRepliedCount = await _subjectVisitRepository.Where(t => t.Trial.TrialStatusStr == StaticData.TrialState.TrialOngoing)
                .Where(t => t.Trial.TrialUserList.Any(t => t.UserId == _userInfo.Id))
                .Where(u => u.CheckState == CheckStateEnum.CVIng &&
                    u.CheckChallengeDialogList.OrderByDescending(t => t.CreateTime).First().UserTypeEnum == UserTypeEnum.ClinicalResearchCoordinator).CountAsync();

            return ResponseOutput.Ok(result, new { TotalToBeCheckedCount = totalToBeCheckedCount, TotalToBeRepliedCount = totalToBeRepliedCount });

        }

        /// <summary>
        /// 重阅申请待审核  -- PM  APM 待办
        /// </summary>
        /// <param name="inQuery"></param>
        /// <param name="_visitTaskReReadingRepository"></param>
        /// <param name="_trialRepository"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IResponseOutput<PageOutput<ReReadingApplyToBeDoneDto>>> GetReReadingApplyToBeDoneList(ReReadingApplyToBeDoneQuery inQuery,
            [FromServices] IRepository<VisitTaskReReading> _visitTaskReReadingRepository,
              [FromServices] IRepository<Trial> _trialRepository)
        {

            var query = _visitTaskReReadingRepository.Where(t => t.Trial.TrialStatusStr == StaticData.TrialState.TrialOngoing)
                .Where(t => t.OriginalReReadingTask.Trial.TrialUserList.Any(t => t.UserId == _userInfo.Id))
                .Where(t => t.OriginalReReadingTask.ReReadingApplyState == ReReadingApplyState.DocotorHaveApplyed)
                .GroupBy(t => new { t.OriginalReReadingTask.Trial.ExperimentName, t.OriginalReReadingTask.Trial.ResearchProgramNo, t.OriginalReReadingTask.Trial.TrialCode, t.OriginalReReadingTask.TrialId })
                 .Select(g => new ReReadingApplyToBeDoneDto()
                 {
                     TrialId = g.Key.TrialId,
                     ResearchProgramNo = g.Key.ResearchProgramNo,
                     ExperimentName = g.Key.ExperimentName,
                     TrialCode = g.Key.TrialCode,
                     UrgentCount = g.Where(u => u.OriginalReReadingTask.IsUrgent == true).Count(),
                     ToBeApprovalCount = g.Count(),

                 }).Where(x => x.ToBeApprovalCount > 0);


            var defalutSortArray = new string[] { nameof(ReReadingApplyToBeDoneDto.UrgentCount) + " desc", nameof(ReReadingApplyToBeDoneDto.ToBeApprovalCount) + " desc" };

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


            var toBeApprovalCount = _visitTaskReReadingRepository.Where(t => t.Trial.TrialStatusStr == StaticData.TrialState.TrialOngoing)
                 .Where(t => t.OriginalReReadingTask.Trial.TrialUserList.Any(t => t.UserId == _userInfo.Id))
                .Where(t => t.OriginalReReadingTask.ReReadingApplyState == ReReadingApplyState.DocotorHaveApplyed).Count();

            return ResponseOutput.Ok(result, new { TotalToBeApprovalCount = toBeApprovalCount });

        }


        /// <summary>
        ///PM  阅片人筛选   -- PM  APM 待办
        /// </summary>
        /// <param name="inQuery"></param>
        /// <param name="_enrollRepository"></param>
        /// <param name="_trialRepository"></param>
        /// <returns></returns>                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              vvv
        [HttpPost]
        public async Task<IResponseOutput<PageOutput<ReviewerSelectToBeDoneDto>>> GetPM_ReviewerSelectToBeDoneList(ReviewerSelectToBeDoneQuery inQuery
            , [FromServices] IRepository<Enroll> _enrollRepository,
             [FromServices] IRepository<Trial> _trialRepository)
        {
            var query = _trialRepository.Where(t => t.TrialStatusStr == StaticData.TrialState.TrialOngoing)
                .Where(t => t.TrialUserList.Any(t => t.UserId == _userInfo.Id))
                    .Select(t => new ReviewerSelectToBeDoneDto()
                    {
                        TrialId = t.Id,
                        ResearchProgramNo = t.ResearchProgramNo,
                        ExperimentName = t.ExperimentName,
                        TrialCode = t.TrialCode,

                        IsUrgent = t.IsUrgent || t.IsSubjectExpeditedView,
                        ToBeApprovalCount = t.EnrollList.Where(u => u.EnrollStatus == EnrollStatus.InviteIntoGroup).Count()
                    }).Where(x => x.ToBeApprovalCount > 0);

            var defalutSortArray = new string[] { nameof(ReviewerSelectToBeDoneDto.IsUrgent) + " desc", nameof(ReReadingApplyToBeDoneDto.ToBeApprovalCount) + " desc" };

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


            var toBeApprovalCount = await _enrollRepository.Where(t => t.Trial.TrialStatusStr == StaticData.TrialState.TrialOngoing)
                .Where(t => t.Trial.TrialUserList.Any(t => t.UserId == _userInfo.Id))
                .Where(u => u.EnrollStatus == EnrollStatus.HasCommittedToCRO).CountAsync();

            return ResponseOutput.Ok(result, new { ToBeApprovalCount = toBeApprovalCount }); ;

        }


        /// <summary>
        /// 获取PM核对临床数据
        /// </summary>
        /// <param name="inQuery"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IResponseOutput<PageOutput<GetPMClinicalDataToBeDoneListOutDto>>> GetPMClinicalDataToBeDoneList(ReviewerSelectToBeDoneQuery inQuery)
        {

            var query = _trialRepository.Where(t => t.TrialStatusStr == StaticData.TrialState.TrialOngoing)
                .Where(t => t.TrialUserList.Any(t => t.UserId == _userInfo.Id))
                .Select(t => new GetPMClinicalDataToBeDoneListOutDto()
                {
                    TrialId = t.Id,
                    ResearchProgramNo = t.ResearchProgramNo,
                    ExperimentName = t.ExperimentName,
                    TrialCode = t.TrialCode,


                    ToBeApprovalCount = t.ReadModuleList.Where(u => u.IsCRCConfirm && !u.IsPMConfirm).Count()
                }).Where(x => x.ToBeApprovalCount > 0);


            var defalutSortArray = new string[] { nameof(GetPMClinicalDataToBeDoneListOutDto.ToBeApprovalCount) + " desc" };

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



            var all = await _trialRepository.Where(t => t.TrialStatusStr == StaticData.TrialState.TrialOngoing)
                .Where(t => t.TrialUserList.Any(t => t.UserId == _userInfo.Id))
                .Select(t => new GetPMClinicalDataToBeDoneListOutDto()
                {


                    ToBeApprovalCount = t.ReadModuleList.Where(u => u.IsCRCConfirm && !u.IsPMConfirm).Count()
                }).ToListAsync();

            return ResponseOutput.Ok(result, new { ToBeApprovalCount = all.Sum(x => x.ToBeApprovalCount) }); ;
        }

        #endregion


        #region SPM  CPM 待办

        /// <summary>
        ///SPM  阅片人筛选 
        /// </summary>
        /// <param name="inQuery"></param>
        /// <param name="_enrollRepository"></param>
        /// <param name="_trialRepository"></param>
        /// <returns></returns>                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              vvv
        [HttpPost]
        public async Task<IResponseOutput<PageOutput<ReviewerSelectToBeDoneDto>>> GetSPM_ReviewerSelectToBeDoneList(ReviewerSelectToBeDoneQuery inQuery
            , [FromServices] IRepository<Enroll> _enrollRepository,
             [FromServices] IRepository<Trial> _trialRepository)
        {
            var query = _trialRepository.Where(t => t.TrialStatusStr == StaticData.TrialState.TrialOngoing)
                .Where(t => t.TrialUserList.Any(t => t.UserId == _userInfo.Id))
                    .Select(t => new ReviewerSelectToBeDoneDto()
                    {
                        TrialId = t.Id,
                        ResearchProgramNo = t.ResearchProgramNo,
                        ExperimentName = t.ExperimentName,
                        TrialCode = t.TrialCode,

                        IsUrgent = t.IsUrgent || t.IsSubjectExpeditedView,
                        ToBeApprovalCount = t.EnrollList.Where(u => u.EnrollStatus == EnrollStatus.HasCommittedToCRO).Count()
                    }).Where(x => x.ToBeApprovalCount > 0);


            var defalutSortArray = new string[] { nameof(ReviewerSelectToBeDoneDto.IsUrgent) + " desc", nameof(ReviewerSelectToBeDoneDto.ToBeApprovalCount) + " desc" };

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


            var toBeApprovalCount = await _enrollRepository.Where(t => t.Trial.TrialStatusStr == StaticData.TrialState.TrialOngoing)
                .Where(t => t.Trial.TrialUserList.Any(t => t.UserId == _userInfo.Id))
                .Where(u => u.EnrollStatus == EnrollStatus.HasCommittedToCRO).CountAsync();

            return ResponseOutput.Ok(result, new { TotalToBeApprovalCount = toBeApprovalCount }); ;

        }

        /// <summary>
        /// SPM 重阅审批
        /// </summary>
        /// <param name="inQuery"></param>
        /// <param name="_visitTaskReReadingRepository"></param>
        /// <param name="_trialRepository"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IResponseOutput<PageOutput<ReReadingApprovalToBeDoneDto>>> GetSPMReReadingApprovalToBeDoneList(ReReadingApprovalToBeDoneQuery inQuery,
           [FromServices] IRepository<VisitTaskReReading> _visitTaskReReadingRepository,
              [FromServices] IRepository<Trial> _trialRepository)

        {
            var query = _visitTaskReReadingRepository.Where(t => t.Trial.TrialStatusStr == StaticData.TrialState.TrialOngoing)
                .Where(t => t.OriginalReReadingTask.Trial.TrialUserList.Any(t => t.UserId == _userInfo.Id))
                .Where(t => t.OriginalReReadingTask.ReReadingApplyState == ReReadingApplyState.TrialGroupHaveApplyed)
               .GroupBy(t => new { t.OriginalReReadingTask.Trial.ExperimentName, t.OriginalReReadingTask.Trial.ResearchProgramNo, t.OriginalReReadingTask.Trial.TrialCode, t.OriginalReReadingTask.TrialId })
                .Select(g => new ReReadingApprovalToBeDoneDto()
                {
                    TrialId = g.Key.TrialId,
                    ResearchProgramNo = g.Key.ResearchProgramNo,
                    ExperimentName = g.Key.ExperimentName,
                    TrialCode = g.Key.TrialCode,
                    UrgentCount = g.Where(u => u.OriginalReReadingTask.IsUrgent == true).Count(),
                    ToBeApprovalCount = g.Count(),

                }).Where(x => x.ToBeApprovalCount > 0);


            var defalutSortArray = new string[] { nameof(ReReadingApprovalToBeDoneDto.UrgentCount) + " desc", nameof(ReReadingApprovalToBeDoneDto.ToBeApprovalCount) + " desc" };

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


            var toBeApprovalCount = _visitTaskReReadingRepository.Where(t => t.Trial.TrialStatusStr == StaticData.TrialState.TrialOngoing)
                 .Where(t => t.OriginalReReadingTask.Trial.TrialUserList.Any(t => t.UserId == _userInfo.Id))
                .Where(t => t.OriginalReReadingTask.ReReadingApplyState == ReReadingApplyState.TrialGroupHaveApplyed).Count();

            return ResponseOutput.Ok(result, new { TotalToBeApprovalCount = toBeApprovalCount });

        }

        #endregion


        #region CRC 待办


        /// <summary>
        /// 临床数据  --CRC 待办
        /// </summary>
        /// <param name="inQuery"></param>
        /// <param name="_subjectVisitRepository"></param>
        /// <param name="_trialRepository"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IResponseOutput<PageOutput<ImageClinicalDataToBeDoneDto>>> GetImageClinicalDataToBeDoneList(ImageClinicalDataToBeDoneQuery inQuery,
            [FromServices] IRepository<SubjectVisit> _subjectVisitRepository,
              [FromServices] IRepository<Trial> _trialRepository)
        {

            var query = _trialRepository.Where(t => t.TrialStatusStr == StaticData.TrialState.TrialOngoing)
                .Where(t => t.TrialUserList.Any(t => t.UserId == _userInfo.Id))
                //.Where(t => t.clinicalDataTrialSets.Any(t => t.ClinicalDataLevel == ClinicalLevel.Subject && t.IsConfirm))
                .Select(t => new ImageClinicalDataToBeDoneDto()
                {
                    TrialId = t.Id,
                    ResearchProgramNo = t.ResearchProgramNo,
                    ExperimentName = t.ExperimentName,
                    TrialCode = t.TrialCode,
                    UrgentCount = t.SubjectVisitList.Where(u => u.IsBaseLine && u.SubmitState != SubmitStateEnum.Submitted && u.IsUrgent).Count(),
                    ToBeDealedCount = t.ReadingClinicalDataList.Where(x => !x.IsSign && x.ClinicalDataTrialSet.UploadRole == UploadRole.CRC && x.ClinicalDataTrialSet.ClinicalDataLevel != ClinicalLevel.SubjectVisit && x.ClinicalDataTrialSet.ClinicalDataLevel != ClinicalLevel.Subject).Count(),
                    ToBeVisitCount = t.ReadingClinicalDataList.Where(x => !x.IsSign && x.ClinicalDataTrialSet.UploadRole == UploadRole.CRC && x.ClinicalDataTrialSet.ClinicalDataLevel == ClinicalLevel.SubjectVisit).Count(),
                    ToAllCount = t.ReadingClinicalDataList.Where(x => !x.IsSign && x.ClinicalDataTrialSet.UploadRole == UploadRole.CRC).Count(),
                    ReadModuleCount = t.ReadModuleList.Where(x => !x.IsPMConfirm).Count(),
                }).Where(x => x.ToAllCount > 0);

            var defalutSortArray = new string[] { nameof(ImageClinicalDataToBeDoneDto.UrgentCount) + " desc", nameof(ImageClinicalDataToBeDoneDto.ReadModuleCount) + " desc" };

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

            var toBeDealedCount = _subjectVisitRepository.Where(t => t.Trial.TrialStatusStr == StaticData.TrialState.TrialOngoing)
                 //.Where(t => t.Trial.TrialUserList.Any(t => t.UserId == _userInfo.Id) && t.Trial.clinicalDataTrialSets.Any(t => t.ClinicalDataLevel == ClinicalLevel.Subject && t.IsConfirm))
                 .Where(u => u.IsBaseLine && u.SubmitState != SubmitStateEnum.Submitted).Count();

            return ResponseOutput.Ok(result, new { TotalToBeDealedCount = toBeDealedCount });

        }


        /// <summary>
        /// 临床数据  --CRC 待确认
        /// </summary>
        /// <param name="inQuery"></param>
        /// <param name="_subjectVisitRepository"></param>
        /// <param name="_trialRepository"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IResponseOutput<PageOutput<ImageClinicalDataToBeDoneDto>>> GetImageClinicalDataToBeConfirmList(ImageClinicalDataToBeDoneQuery inQuery,
            [FromServices] IRepository<SubjectVisit> _subjectVisitRepository,
              [FromServices] IRepository<Trial> _trialRepository)
        {

            var query = _trialRepository.Where(t => t.TrialStatusStr == StaticData.TrialState.TrialOngoing)
                .Where(t => t.TrialUserList.Any(t => t.UserId == _userInfo.Id))
                //.Where(t => t.clinicalDataTrialSets.Any(t => t.ClinicalDataLevel == ClinicalLevel.Subject && t.IsConfirm))
                .Select(t => new ImageClinicalDataToBeDoneDto()
                {
                    TrialId = t.Id,
                    ResearchProgramNo = t.ResearchProgramNo,
                    ExperimentName = t.ExperimentName,
                    TrialCode = t.TrialCode,
                    UrgentCount = t.SubjectVisitList.Where(u => u.IsBaseLine && u.SubmitState != SubmitStateEnum.Submitted && u.IsUrgent).Count(),
                    ToBeDealedCount = t.ReadingClinicalDataList.Where(x => !x.IsSign && x.ClinicalDataTrialSet.UploadRole == UploadRole.CRC && x.ClinicalDataTrialSet.ClinicalDataLevel != ClinicalLevel.SubjectVisit && x.ClinicalDataTrialSet.ClinicalDataLevel != ClinicalLevel.Subject).Count(),
                    ToBeVisitCount = t.ReadingClinicalDataList.Where(x => !x.IsSign && x.ClinicalDataTrialSet.UploadRole == UploadRole.CRC && x.ClinicalDataTrialSet.ClinicalDataLevel == ClinicalLevel.SubjectVisit).Count(),
                    ToAllCount = t.ReadingClinicalDataList.Where(x => !x.IsSign && x.ClinicalDataTrialSet.UploadRole == UploadRole.CRC).Count(),
                    ReadModuleCount = t.ReadModuleList.Where(x => !x.IsCRCConfirm).Count(),
                }).Where(x => x.ReadModuleCount > 0);

            var defalutSortArray = new string[] { nameof(ImageClinicalDataToBeDoneDto.UrgentCount) + " desc", nameof(ImageClinicalDataToBeDoneDto.ToBeDealedCount) + " desc" };

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

            // ReadModuleCount情况太多了 暂时用之前的方法
            foreach (var item in result.CurrentPageData)
            {
                item.ReadModuleCount = (await _clinicalAnswerService.GetCRCConfirmList(new Service.Reading.Dto.GetCRCConfirmListInDto()
                {
                    TrialId = item.TrialId,
                    IsPMConfirm = false,
                    PageIndex = 1,
                    PageSize = 9999,

                })).CurrentPageData.Count();
            }


            result.CurrentPageData = result.CurrentPageData.Where(x => x.ReadModuleCount != 0).ToList();

            var toBeDealedCount = _subjectVisitRepository.Where(t => t.Trial.TrialStatusStr == StaticData.TrialState.TrialOngoing)
                 //.Where(t => t.Trial.TrialUserList.Any(t => t.UserId == _userInfo.Id) && t.Trial.clinicalDataTrialSets.Any(t => t.ClinicalDataLevel == ClinicalLevel.Subject && t.IsConfirm))
                 .Where(u => u.IsBaseLine && u.SubmitState != SubmitStateEnum.Submitted).Count();

            return ResponseOutput.Ok(result, new { TotalToBeDealedCount = toBeDealedCount });

        }





        /// <summary>
        /// CRC影像质疑待处理  --CRC 待办
        /// </summary>
        /// <param name="inQuery"></param>
        /// <param name="_subjectVisitRepository"></param>
        /// <param name="_trialRepository"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IResponseOutput<PageOutput<ImageQuestionToBeDoneDto>>> GetCRCImageQuestionToBeDoneList(ImageQuestionToBeDoneQuery inQuery,
            [FromServices] IRepository<SubjectVisit> _subjectVisitRepository,
              [FromServices] IRepository<Trial> _trialRepository)
        {

            var query = _trialRepository.Where(t => t.TrialStatusStr == StaticData.TrialState.TrialOngoing)
                .Where(t => t.TrialUserList.Any(t => t.UserId == _userInfo.Id))
                .Select(t => new ImageQuestionToBeDoneDto()
                {
                    TrialId = t.Id,
                    ResearchProgramNo = t.ResearchProgramNo,
                    ExperimentName = t.ExperimentName,
                    TrialCode = t.TrialCode,

                    UrgentCount = t.SubjectVisitList.Where(c => c.TrialSite.CRCUserList.Any(u => u.UserId == _userInfo.Id))
                    .SelectMany(c => c.QCChallengeList)
                    .Where(u => u.IsClosed == false && u.LatestReplyUser.UserTypeEnum == UserTypeEnum.IQC && u.SubjectVisit.IsUrgent).Count(),

                    ToBeDealedCount = t.SubjectVisitList.Where(c => c.TrialSite.CRCUserList.Any(u => u.UserId == _userInfo.Id))
                    .SelectMany(c => c.QCChallengeList)

                    .Where(u => u.IsClosed == false && (u.LatestReplyUser.UserTypeEnum == UserTypeEnum.IQC || u.LatestReplyUserId == null)).Count(),

                }).Where(x => x.ToBeDealedCount > 0); ;

            var defalutSortArray = new string[] { nameof(ImageQuestionToBeDoneDto.UrgentCount) + " desc", nameof(ImageQuestionToBeDoneDto.ToBeDealedCount) + " desc" };

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


            var toBeDealedCount = _subjectVisitRepository.Where(t => t.Trial.TrialStatusStr == StaticData.TrialState.TrialOngoing)
                  .Where(t => t.Trial.TrialUserList.Any(t => t.UserId == _userInfo.Id))
                  .Where(c => c.TrialSite.CRCUserList.Any(u => u.UserId == _userInfo.Id))
                  .SelectMany(c => c.QCChallengeList)
                  .Where(u => u.IsClosed == false && u.LatestReplyUser.UserTypeEnum == UserTypeEnum.IQC).Count();

            return ResponseOutput.Ok(result, new { TotalToBeDealedCount = toBeDealedCount });

        }

        /// <summary>
        /// 核查质疑待处理  --CRC 待办
        /// </summary>
        /// <param name="inQuery"></param>
        /// <param name="_subjectVisitRepository"></param>
        /// <param name="_trialRepository"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IResponseOutput<PageOutput<ImageCheckQuestionToBeDoneDto>>> GetImageCheckQuestionToBeDoneList(ImageCheckQuestionToBeDoneQuery inQuery,
            [FromServices] IRepository<SubjectVisit> _subjectVisitRepository,
              [FromServices] IRepository<Trial> _trialRepository)
        {

            var query = _trialRepository.Where(t => t.TrialStatusStr == StaticData.TrialState.TrialOngoing)
                .Where(t => t.TrialUserList.Any(t => t.UserId == _userInfo.Id))
                .Select(t => new ImageCheckQuestionToBeDoneDto()
                {
                    TrialId = t.Id,
                    ResearchProgramNo = t.ResearchProgramNo,
                    ExperimentName = t.ExperimentName,
                    TrialCode = t.TrialCode,

                    UrgentCount = t.SubjectVisitList.Where(c => c.TrialSite.CRCUserList.Any(u => u.UserId == _userInfo.Id))
                    .Where(u => u.CheckState == CheckStateEnum.CVIng && u.CheckChallengeState == CheckChanllengeTypeEnum.PMWaitCRCReply && u.IsUrgent).Count(),

                    ToBeReplyedCount = t.SubjectVisitList.Where(c => c.TrialSite.CRCUserList.Any(u => u.UserId == _userInfo.Id))
                    .Where(u => u.CheckState == CheckStateEnum.CVIng && u.CheckChallengeState == CheckChanllengeTypeEnum.PMWaitCRCReply).Count()

                }).Where(x => x.ToBeReplyedCount > 0);


            var defalutSortArray = new string[] { nameof(ImageCheckQuestionToBeDoneDto.UrgentCount) + " desc", nameof(ImageCheckQuestionToBeDoneDto.ToBeReplyedCount) + " desc" };

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


            var toBeDealedCount = _subjectVisitRepository.Where(t => t.Trial.TrialStatusStr == StaticData.TrialState.TrialOngoing)
                  .Where(t => t.Trial.TrialUserList.Any(t => t.UserId == _userInfo.Id))
                  .Where(c => c.TrialSite.CRCUserList.Any(u => u.UserId == _userInfo.Id))
                  .Where(u => u.CheckState == CheckStateEnum.CVIng && u.CheckChallengeState == CheckChanllengeTypeEnum.PMWaitCRCReply).Count();

            return ResponseOutput.Ok(result, new { TotalToBeReplyedCount = toBeDealedCount });


        }

        /// <summary>
        /// 影像重传  --CRC 待办
        /// </summary>
        /// <param name="inQuery"></param>
        /// <param name="_subjectVisitRepository"></param>
        /// <param name="_trialRepository"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IResponseOutput<PageOutput<ImageReUploadToBeDoneDto>>> GetImageReUploadToBeDoneList(ImageReUploadToBeDoneQuery inQuery,
            [FromServices] IRepository<SubjectVisit> _subjectVisitRepository,
              [FromServices] IRepository<Trial> _trialRepository)
        {

            var query = _trialRepository.Where(t => t.TrialStatusStr == StaticData.TrialState.TrialOngoing)
                .Where(t => t.TrialUserList.Any(t => t.UserId == _userInfo.Id))
                .Select(t => new ImageReUploadToBeDoneDto()
                {
                    TrialId = t.Id,
                    ResearchProgramNo = t.ResearchProgramNo,
                    ExperimentName = t.ExperimentName,
                    TrialCode = t.TrialCode,
                    UrgentCount = t.SubjectVisitList
                    .Where(c => c.TrialSite.CRCUserList.Any(u => u.UserId == _userInfo.Id))
                    .Where(u => u.IsUrgent && ((u.SubmitState == SubmitStateEnum.ToSubmit && u.IsPMBackOrReReading) || u.IsQCConfirmedReupload)).Count(),

                    ToBeReUploadCount = t.SubjectVisitList
                    .Where(c => c.TrialSite.CRCUserList.Any(u => u.UserId == _userInfo.Id))
                    .Where(u => (u.SubmitState == SubmitStateEnum.ToSubmit && u.IsPMBackOrReReading) || (u.IsQCConfirmedReupload)).Count(),

                }).Where(x => x.ToBeReUploadCount > 0);


            var defalutSortArray = new string[] { nameof(ImageReUploadToBeDoneDto.UrgentCount) + " desc", nameof(ImageReUploadToBeDoneDto.ToBeReUploadCount) + " desc" };

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

            var toBeDealedCount = _subjectVisitRepository.Where(t => t.Trial.TrialStatusStr == StaticData.TrialState.TrialOngoing)
                  .Where(t => t.Trial.TrialUserList.Any(t => t.UserId == _userInfo.Id))
                  .Where(u => (u.SubmitState == SubmitStateEnum.ToSubmit && u.IsPMBackOrReReading) || (u.IsQCConfirmedReupload)).Count();

            return ResponseOutput.Ok(result, new { TotalToBeReUploadCount = toBeDealedCount });

        }




        /// <summary>
        ///  加急影像提交   --CRC 待办
        /// </summary>
        /// <param name="inQuery"></param>
        /// <param name="_subjectVisitRepository"></param>
        /// <param name="_trialRepository"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IResponseOutput<PageOutput<ImageSubmittedToBeDoneDto>>> GetImageSubmittedToBeDoneList(ImageSubmittedToBeDoneQuery inQuery,
            [FromServices] IRepository<SubjectVisit> _subjectVisitRepository,
              [FromServices] IRepository<Trial> _trialRepository)
        {

            var query = _trialRepository.Where(t => t.TrialStatusStr == StaticData.TrialState.TrialOngoing)
                .Where(t => t.TrialUserList.Any(t => t.UserId == _userInfo.Id) && (t.IsUrgent || t.IsSubjectExpeditedView || t.IsEnrollementQualificationConfirm || t.IsPDProgressView))
                .Select(t => new ImageSubmittedToBeDoneDto()
                {
                    TrialId = t.Id,
                    ResearchProgramNo = t.ResearchProgramNo,
                    ExperimentName = t.ExperimentName,
                    TrialCode = t.TrialCode,
                    UrgentCount = t.SubjectVisitList
                    .Where(c => c.TrialSite.CRCUserList.Any(u => u.UserId == _userInfo.Id))
                    .Where(u => u.SubmitState == SubmitStateEnum.ToSubmit && (u.IsEnrollmentConfirm || u.PDState == PDStateEnum.PDProgress || u.Trial.IsUrgent || u.Subject.IsUrgent)/*u.IsUrgent*/).Count(),


                    ToBeDealedCount = t.SubjectVisitList
                    .Where(c => c.TrialSite.CRCUserList.Any(u => u.UserId == _userInfo.Id))
                    .Where(u => u.SubmitState == SubmitStateEnum.ToSubmit).Count(),

                }).Where(x => x.ToBeDealedCount > 0);



            var defalutSortArray = new string[] { nameof(ImageSubmittedToBeDoneDto.UrgentCount) + " desc", nameof(ImageSubmittedToBeDoneDto.ToBeDealedCount) + " desc" };

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


            var toBeDealedCount = _subjectVisitRepository.Where(t => t.Trial.TrialStatusStr == StaticData.TrialState.TrialOngoing)
                  .Where(t => t.Trial.TrialUserList.Any(t => t.UserId == _userInfo.Id))
                  .Where(c => c.TrialSite.CRCUserList.Any(u => u.UserId == _userInfo.Id))
                  .Where(u => u.SubmitState == SubmitStateEnum.ToSubmit).Count();

            return ResponseOutput.Ok(result, new { TotalToBeDealedCount = toBeDealedCount });

        }



        #endregion

        #region IQC待办



        /// <summary>
        /// 影像质控     待领取 跟项目配置有关系   --IQC待办
        /// </summary>
        /// <param name="inQuery"></param>
        /// <param name="_subjectVisitRepository"></param>
        /// <param name="_trialRepository"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IResponseOutput<PageOutput<ImageQualityToBeDoneDto>>> GetImageQualityToBeDoneList(ImageQualityToBeDoneQuery inQuery,
            [FromServices] IRepository<SubjectVisit> _subjectVisitRepository,
              [FromServices] IRepository<Trial> _trialRepository)
        {

            var query = _trialRepository.Where(t => t.TrialStatusStr == StaticData.TrialState.TrialOngoing)
                .Where(t => t.TrialUserList.Any(t => t.UserId == _userInfo.Id))
                .Where(t => t.QCProcessEnum != TrialQCProcess.NotAudit)
                .Select(t => new ImageQualityToBeDoneDto()
                {
                    TrialId = t.Id,
                    ResearchProgramNo = t.ResearchProgramNo,
                    ExperimentName = t.ExperimentName,
                    TrialCode = t.TrialCode,

                    // 待审核  加急的（待领取 已领取）--  领取了 还没做完 就是待审核
                    UrgentCount = t.SubjectVisitList.Where(u => u.CurrentActionUserId == _userInfo.Id && u.IsUrgent).Count(),


                    //待领取量
                    ToBeClaimedCount = t.SubjectVisitList.Where(t => t.SubmitState == SubmitStateEnum.Submitted && t.AuditState != AuditStateEnum.QCPassed && t.AuditState != AuditStateEnum.QCFailed)
                    .Where(u => u.CurrentActionUserId == null && (u.PreliminaryAuditUserId == null || (u.PreliminaryAuditUserId != _userInfo.Id && u.ReviewAuditUserId == null))).Count(),

                    //待审核通过，统计从已领取到QC提交之间的      已领取 待审核 审核中   (审核完成  领取人就会清理 所以只用查询当前领取人是自己的就好了)
                    ToBeReviewedCount = t.SubjectVisitList.Where(u => u.CurrentActionUserId == _userInfo.Id).Count()

                }).Where(x => x.ToBeClaimedCount + x.ToBeReviewedCount > 0);


            var defalutSortArray = new string[] { nameof(ImageQualityToBeDoneDto.UrgentCount) + " desc", nameof(ImageQualityToBeDoneDto.ToBeClaimedCount) + " desc" };

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



            var toBeClaimedCount = _subjectVisitRepository.Where(t => t.Trial.TrialStatusStr == StaticData.TrialState.TrialOngoing)
                .Where(t => t.Trial.TrialUserList.Any(t => t.UserId == _userInfo.Id) && t.SubmitState == SubmitStateEnum.Submitted && t.AuditState != AuditStateEnum.QCPassed && t.AuditState != AuditStateEnum.QCFailed)
                .Where(u => u.CurrentActionUserId == null && (u.PreliminaryAuditUserId == null || (u.PreliminaryAuditUserId != _userInfo.Id && u.ReviewAuditUserId == null))).Count();


            var toBeReviwedCount = _subjectVisitRepository.Where(t => t.Trial.TrialStatusStr == StaticData.TrialState.TrialOngoing)
                .Where(t => t.Trial.TrialUserList.Any(t => t.UserId == _userInfo.Id))
                .Where(u => u.CurrentActionUserId == _userInfo.Id).Count();


            return ResponseOutput.Ok(result, new { TotalToBeClaimedCount = toBeClaimedCount, TotalToBeReviewedCount = toBeReviwedCount });

        }


        /// <summary>
        ///  QC 质疑
        /// </summary>
        /// <param name="inQuery"></param>
        /// <param name="_subjectVisitRepository"></param>
        /// <param name="_trialRepository"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IResponseOutput<PageOutput<ImageQuestionToBeDoneDto>>> GetQCImageQuestionToBeDoneList(ImageQuestionToBeDoneQuery inQuery,
            [FromServices] IRepository<SubjectVisit> _subjectVisitRepository,
              [FromServices] IRepository<Trial> _trialRepository)
        {

            var query = _trialRepository.Where(t => t.TrialStatusStr == StaticData.TrialState.TrialOngoing)
                .Where(t => t.TrialUserList.Any(t => t.UserId == _userInfo.Id))
                .Select(t => new ImageQuestionToBeDoneDto()
                {
                    TrialId = t.Id,
                    ResearchProgramNo = t.ResearchProgramNo,
                    ExperimentName = t.ExperimentName,
                    TrialCode = t.TrialCode,
                    UrgentCount = t.SubjectVisitList.SelectMany(c => c.QCChallengeList)
                    .Where(u => u.CreateUserId == _userInfo.Id && u.IsClosed == false && u.LatestReplyUser.UserTypeEnum == UserTypeEnum.ClinicalResearchCoordinator && u.SubjectVisit.IsUrgent).Count(),

                    ToBeDealedCount = t.SubjectVisitList.SelectMany(c => c.QCChallengeList)
                    .Where(u => u.CreateUserId == _userInfo.Id && u.IsClosed == false && u.LatestReplyUser.UserTypeEnum == UserTypeEnum.ClinicalResearchCoordinator).Count(),

                }).Where(x => x.ToBeDealedCount > 0); ;

            var defalutSortArray = new string[] { nameof(ImageQuestionToBeDoneDto.UrgentCount) + " desc", nameof(ImageQuestionToBeDoneDto.ToBeDealedCount) + " desc" };

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


            var toBeDealedCount = _subjectVisitRepository.Where(t => t.Trial.TrialStatusStr == StaticData.TrialState.TrialOngoing)
                  .Where(t => t.Trial.TrialUserList.Any(t => t.UserId == _userInfo.Id))
                  .SelectMany(c => c.QCChallengeList)
                  .Where(u => u.CreateUserId == _userInfo.Id && u.IsClosed == false && u.LatestReplyUser.UserTypeEnum == UserTypeEnum.ClinicalResearchCoordinator).Count();

            return ResponseOutput.Ok(result, new { TotalToBeDealedCount = toBeDealedCount });

        }





        #endregion


        #region IR待办

        /// <summary>
        /// IR 影像阅片 待阅量 
        /// </summary>
        /// <param name="inQuery"></param>
        /// <param name="_visitTaskRepository"></param>
        /// <param name="_trialReadingCriterionRepository"></param>
        /// <param name="_trialRepository"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IResponseOutput<PageOutput<IRImageReadingToBeDoneDto>>> GetIRImageReadingToBeDoneList(IRImageReadingToBeDoneQuery inQuery,
           [FromServices] IRepository<VisitTask> _visitTaskRepository,
            [FromServices] IRepository<ReadingQuestionCriterionTrial> _trialReadingCriterionRepository,
           [FromServices] IRepository<Trial> _trialRepository)
        {


            var newQuery = _trialReadingCriterionRepository.Where(t => t.IsSigned && t.IsConfirm && t.Trial.TrialUserList.Any(t => t.UserId == _userInfo.Id))
                 .Select(c => new IRImageReadingToBeDoneDto()
                 {
                     TrialId = c.TrialId,
                     ResearchProgramNo = c.Trial.ResearchProgramNo,
                     ExperimentName = c.Trial.ExperimentName,
                     TrialCode = c.Trial.TrialCode,
                     CriterionName = c.CriterionName,
                     TrialReadingCriterionId = c.Id,

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

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


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

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



                     HaveSignedCount = c.VisitTaskList.Where(t => t.DoctorUserId == _userInfo.Id && (t.TaskState == TaskState.Effect || t.TaskState == TaskState.Freeze)
                                       && t.ReadingTaskState == ReadingTaskState.HaveSigned).Count(),
                 }).Where(x => x.UnReadCount > 0);

            ;

            #region 废弃
            //var query = _trialRepository
            //  .Select(t => new IRImageReadingToBeDoneDto()
            //  {
            //      TrialId = t.Id,
            //      ResearchProgramNo = t.ResearchProgramNo,
            //      ExperimentName = t.ExperimentName,
            //      TrialCode = t.TrialCode,


            //      UrgentCount = t.SubjectVisitList.SelectMany(c => c.QCChallengeList)
            //      .Where(u => u.IsClosed == false && u.LatestReplyUser.UserTypeEnum == UserTypeEnum.ClinicalResearchCoordinator && u.SubjectVisit.IsUrgent).Count(),

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

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

            //      HaveSignedCount = t.VisitTaskList.Where(t => t.DoctorUserId == _userInfo.Id 
            //      && (t.TaskState == TaskState.Effect || t.TaskState == TaskState.Freeze) 
            //      && t.ReadingTaskState==ReadingTaskState.HaveSigned).Count()

            //  });

            // 不能对包含聚合或子查询的表达式执行聚合函数

            //var query = _visitTaskRepository.Where(t => t.DoctorUserId == _userInfo.Id && (t.TaskState == TaskState.Effect || t.TaskState == TaskState.Freeze))
            //    .GroupBy(t => new { t.TrialId, t.Trial.ResearchProgramNo, t.Trial.TrialCode, t.Trial.ExperimentName, t.TrialReadingCriterionId, t.TrialReadingCriterion.CriterionName, t.TrialReadingCriterion.IsAutoCreate })
            //    .Select(g => new IRImageReadingToBeDoneDto()
            //    {
            //        TrialId = g.Key.TrialId,
            //        ResearchProgramNo = g.Key.ResearchProgramNo,
            //        ExperimentName = g.Key.ExperimentName,
            //        TrialCode = g.Key.TrialCode,
            //        CriterionName = g.Key.CriterionName,
            //        TrialReadingCriterionId = g.Key.TrialReadingCriterionId,

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

            //        //      .Where(y => y.IsFrontTaskNeedSignButNotSign == false && (y.IsNeedClinicalDataSign == false || y.IsClinicalDataSign == true))
            //        //      .Count(t=>t.IsUrgent),

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

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

            //        HaveSignedCount = g.Where(t => t.DoctorUserId == _userInfo.Id && (t.TaskState == TaskState.Effect || t.TaskState == TaskState.Freeze)
            //                            && t.ReadingTaskState == ReadingTaskState.HaveSigned).Count(),

            //    });
            #endregion


            var defalutSortArray = new string[] { nameof(IRImageReadingToBeDoneDto.TrialCode), nameof(IRImageReadingToBeDoneDto.UrgentCount) + " desc", nameof(IRImageReadingToBeDoneDto.UnReadCount) + " desc" };

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

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

                  .Where(y => y.IsFrontTaskNeedSignButNotSign == false && (y.IsNeedClinicalDataSign == false || y.IsClinicalDataSign == true))
                  .Count();

            return ResponseOutput.Ok(result, new { TotalUnReadCount = toBeDealedCount });

        }


        /// <summary>
        /// IR医学反馈 
        /// </summary>
        /// <param name="inQuery"></param>
        /// <param name="_taskMedicalReviewRepository"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IResponseOutput<PageOutput<MedicalCommentsToBeDoneDto>>> GetIRMedicalCommentsToBeDoneList(MedicalCommentsToBeDoneQuery inQuery,
             [FromServices] IRepository<TaskMedicalReview> _taskMedicalReviewRepository)
        {

            var query = _taskMedicalReviewRepository.Where(t => t.Trial.TrialStatusStr == StaticData.TrialState.TrialOngoing)
                .Where(t => t.Trial.TrialUserList.Any(t => t.UserId == _userInfo.Id))
                .Where(t => t.IsClosedDialog == false && t.VisitTask.TaskState == TaskState.Effect && t.IsInvalid == false && t.VisitTask.DoctorUserId == _userInfo.Id)
                .GroupBy(t => new
                {
                    t.TrialId,
                    t.Trial.ResearchProgramNo,
                    t.Trial.ExperimentName,
                    t.Trial.TrialCode,
                    t.VisitTask.TrialReadingCriterionId,
                    t.VisitTask.TrialReadingCriterion.CriterionName
                })
                .Select(g => new MedicalCommentsToBeDoneDto()
                {
                    TrialId = g.Key.TrialId,
                    ResearchProgramNo = g.Key.ResearchProgramNo,
                    ExperimentName = g.Key.ExperimentName,
                    TrialCode = g.Key.TrialCode,
                    CriterionName = g.Key.CriterionName,
                    TrialReadingCriterionId = g.Key.TrialReadingCriterionId,

                    #region 不能对包含聚合或子查询的表达式执行聚合函数


                    UrgentCount = g.Where(u => u.VisitTask.IsUrgent && u.LatestReplyUser.UserTypeEnum == UserTypeEnum.MIM).Count(),

                    ToBeReplyedCount = g.Where(u => u.LatestReplyUser.UserTypeEnum == UserTypeEnum.MIM && u.AuditState == MedicalReviewAuditState.Auditing).Count(),

                    #endregion
                    //UrgentCount = g.Where(u => u.VisitTask.IsUrgent
                    //&& u.ReadingMedicalReviewDialogList.OrderByDescending(l => l.CreateTime).First().UserTypeEnumInt == (int)UserTypeEnum.MIM).Count(),

                    //ToBeReplyedCount = g.Where(u =>
                    // u.ReadingMedicalReviewDialogList.OrderByDescending(l => l.CreateTime).First().UserTypeEnumInt == (int)UserTypeEnum.MIM).Count(),

                }).Where(t => t.ToBeReplyedCount > 0);


            var defalutSortArray = new string[] { nameof(MedicalCommentsToBeDoneDto.UrgentCount) + " desc", nameof(MedicalCommentsToBeDoneDto.ToBeReplyedCount) + " desc" };

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



            var toBeDealedCount = _taskMedicalReviewRepository.Where(t => t.Trial.TrialStatusStr == StaticData.TrialState.TrialOngoing)
                .Where(t => t.Trial.TrialUserList.Any(t => t.UserId == _userInfo.Id))
                .Where(t => t.IsClosedDialog == false && t.VisitTask.DoctorUserId == _userInfo.Id)
                .Where(u => u.LatestReplyUser.UserTypeEnum == UserTypeEnum.MIM)
                //.Where(u => u.ReadingMedicalReviewDialogList.OrderByDescending(l => l.CreateTime).First().UserTypeEnumInt == (int)UserTypeEnum.MIM)
                .Count();

            return ResponseOutput.Ok(result, new { TotalToBeReplyedCount = toBeDealedCount });

        }




        #endregion

        #region MIM待办

        /// <summary>
        /// MIM医学反馈 
        /// </summary>
        /// <param name="inQuery"></param>
        /// <param name="_taskMedicalReviewRepository"></param>
        /// <param name="_trialReadingCriterionRepository"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IResponseOutput<PageOutput<MedicalCommentsToBeDoneDto>>> GetMIMMedicalCommentsToBeDoneList(MedicalCommentsToBeDoneQuery inQuery,
             [FromServices] IRepository<TaskMedicalReview> _taskMedicalReviewRepository,
              [FromServices] IRepository<ReadingQuestionCriterionTrial> _trialReadingCriterionRepository)
        {


            #region 废弃不能对包含聚合或子查询的表达式执行聚合函数
            var query = _taskMedicalReviewRepository.Where(t => t.Trial.TrialStatusStr == StaticData.TrialState.TrialOngoing)
                   .Where(t => t.Trial.TrialUserList.Any(t => t.UserId == _userInfo.Id))
                   .Where(t => t.IsClosedDialog == false && t.VisitTask.TaskState == TaskState.Effect && t.IsInvalid == false && t.MedicalManagerUserId == _userInfo.Id)
                   .GroupBy(t => new
                   {
                       t.TrialId,
                       t.Trial.ResearchProgramNo,
                       t.Trial.ExperimentName,
                       t.Trial.TrialCode,
                       t.VisitTask.TrialReadingCriterionId,
                       t.VisitTask.TrialReadingCriterion.CriterionName
                   })
                   .Select(g => new MedicalCommentsToBeDoneDto()
                   {
                       TrialId = g.Key.TrialId,
                       ResearchProgramNo = g.Key.ResearchProgramNo,
                       ExperimentName = g.Key.ExperimentName,
                       TrialCode = g.Key.TrialCode,
                       CriterionName = g.Key.CriterionName,
                       TrialReadingCriterionId = g.Key.TrialReadingCriterionId,

                       UrgentCount = g.Where(u => u.VisitTask.IsUrgent).Where(u => u.AuditState != MedicalReviewAuditState.HaveSigned).Count(),

                       ToBeReplyedCount = g.Where(u => u.LatestReplyUser.UserTypeEnum == UserTypeEnum.IndependentReviewer && u.AuditState == MedicalReviewAuditState.Auditing).Count(),

                       ToBeReviewedCount = g.Where(u => u.AuditState != MedicalReviewAuditState.HaveSigned && u.LatestReplyUser.UserTypeEnum != UserTypeEnum.IndependentReviewer).Count()

                   }).Where(t => t.ToBeReviewedCount + t.ToBeReplyedCount > 0);

            #endregion


            var defalutSortArray = new string[] { nameof(MedicalCommentsToBeDoneDto.UrgentCount) + " desc", nameof(MedicalCommentsToBeDoneDto.ToBeReplyedCount) + " desc" };

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



            var toBeReplyedQuery = _taskMedicalReviewRepository.Where(t => t.Trial.TrialStatusStr == StaticData.TrialState.TrialOngoing)
                  .Where(t => t.Trial.TrialUserList.Any(t => t.UserId == _userInfo.Id))
                  .Where(t => t.IsClosedDialog == false && t.VisitTask.TaskState == TaskState.Effect && t.IsInvalid == false && t.MedicalManagerUserId == _userInfo.Id)
                  .Where(u => u.LatestReplyUser.UserTypeEnum == UserTypeEnum.IndependentReviewer && u.AuditState == MedicalReviewAuditState.Auditing);


            var toBeReplyedCount = toBeReplyedQuery.Count();

            var tobeReviewedCount = _taskMedicalReviewRepository.Where(t => t.Trial.TrialStatusStr == StaticData.TrialState.TrialOngoing)
                  .Where(t => t.Trial.TrialUserList.Any(t => t.UserId == _userInfo.Id))
                  .Where(t => t.IsClosedDialog == false && t.VisitTask.TaskState == TaskState.Effect && t.IsInvalid == false && t.MedicalManagerUserId == _userInfo.Id)
                  .Where(u => u.AuditState != MedicalReviewAuditState.HaveSigned && u.LatestReplyUser.UserTypeEnum != UserTypeEnum.IndependentReviewer).Count();


            return ResponseOutput.Ok(result, new { TotalToBeReplyedCount = toBeReplyedCount, TotalTobeReviewedCount = tobeReviewedCount });

        }


        /// <summary>
        /// 获取某项目 某标准 第一条未读的医学审核
        /// </summary>
        /// <param name="inQuery"></param>
        /// <param name="_taskMedicalReviewService"></param>
        /// <returns></returns>
        /// <exception cref="BusinessValidationFailedException"></exception>
        public async Task<TaskMedicalReviewView> GetMedicalCommentsFirstToBeDone(MedicalCommentsFirstToBeDoneQuery inQuery,
            [FromServices] ITaskMedicalReviewService _taskMedicalReviewService)
        {
            var result = await _taskMedicalReviewService.GetMIMMedicalReviewTaskList(new TaskMedicalReviewQuery()
            {
                TrialId = inQuery.TrialId,
                IsGetBeRead = true,
                PageIndex = 1,
                PageSize = 1,
                TrialReadingCriterionId = inQuery.TrialReadingCriterionId
            });

            if (result.Data.CurrentPageData.Count == 1)
            {
                return result.Data.CurrentPageData[0];
            }
            else
            {
                throw new BusinessValidationFailedException(_localizer["MedicalReview_Finish"]);
            }
        }




        #endregion


        #region 项目列表查询  +  待办详情


        public async Task<List<Guid>> GetNeedSignTrialDocTrialIdList()
        {
            if (!_userInfo.IsAdmin)
            {
                var list = await _trialRepository.Where(t => t.TrialStatusStr != StaticData.TrialState.TrialStopped)
                    .Where(t => t.TrialUserList.Any(t => t.UserId == _userInfo.Id))
                    .WhereIf(!_userInfo.IsAdmin, c => c.TrialDocumentList.Where(t => t.IsDeleted == false && t.NeedConfirmedUserTypeList.Any(t => t.NeedConfirmUserTypeId == _userInfo.UserTypeId) &&
                    !t.TrialDocConfirmedUserList.Any(t => t.ConfirmUserId == _userInfo.Id && t.ConfirmTime != null)).Count() > 0)
                    .Select(t => t.Id).ToListAsync();

                return list;

            }
            return new List<Guid>();
        }

        public async Task<UserToBeDoneRecord> GetUserTobeDoneRecord([FromServices] IRepository<SubjectVisit> _subjectVisitRepository,
            [FromServices] IRepository<VisitTaskReReading> _visitTaskReReadingRepository,
            [FromServices] IRepository<TaskMedicalReview> _taskMedicalReviewRepository,
            [FromServices] IRepository<ReadingQuestionCriterionTrial> _trialReadingCriterionRepository)
        {
            var isPM = _userInfo.UserTypeEnumInt == (int)UserTypeEnum.ProjectManager || _userInfo.UserTypeEnumInt == (int)UserTypeEnum.APM;
            var isCRC = _userInfo.UserTypeEnumInt == (int)UserTypeEnum.ClinicalResearchCoordinator;
            var isIQC = _userInfo.UserTypeEnumInt == (int)UserTypeEnum.IQC;
            var isMIM = _userInfo.UserTypeEnumInt == (int)UserTypeEnum.MIM;
            var isSPMOrCPM = _userInfo.UserTypeEnumInt == (int)UserTypeEnum.SPM || _userInfo.UserTypeEnumInt == (int)UserTypeEnum.CPM;
            var isIR = _userInfo.UserTypeEnumInt == (int)UserTypeEnum.IndependentReviewer;

            var needSignTrialCount = await _trialRepository.Where(t => t.TrialStatusStr != StaticData.TrialState.TrialStopped)
                .Where(t => t.TrialUserList.Any(t => t.UserId == _userInfo.Id))
               .Where(c => c.TrialDocumentList.Where(t => t.IsDeleted == false && t.NeedConfirmedUserTypeList.Any(t => t.NeedConfirmUserTypeId == _userInfo.UserTypeId)
               && !t.TrialDocConfirmedUserList.Any(t => t.ConfirmUserId == _userInfo.Id && t.ConfirmTime != null)).Count() > 0).CountAsync();

            var needSignSysDocCont = await _systemDocumentRepository
                        .Where(t => t.IsDeleted == false && !t.SystemDocConfirmedUserList.Any(t => t.ConfirmUserId == _userInfo.Id && t.ConfirmTime != null))
                        .SelectMany(t => t.NeedConfirmedUserTypeList)
                        .CountAsync(t => t.NeedConfirmUserTypeId == _userInfo.UserTypeId);

            var signedTrialCount = await _trialDocumentRepository.AsQueryable(true)
            .Where(t => t.Trial.TrialUserList.Any(t => t.UserId == _userInfo.Id))
            .Where(t => t.NeedConfirmedUserTypeList.Any(t => t.NeedConfirmUserTypeId == _userInfo.UserTypeId))
            .Where(t => t.TrialDocConfirmedUserList.Any(t => t.ConfirmUserId == _userInfo.Id && t.ConfirmTime != null)).CountAsync();

            var signedSysDocCont = await _systemDocumentRepository
                       .Where(t => t.IsDeleted == false && t.SystemDocConfirmedUserList.Any(t => t.ConfirmUserId == _userInfo.Id && t.ConfirmTime != null))
                       .SelectMany(t => t.NeedConfirmedUserTypeList)
                       .CountAsync(t => t.NeedConfirmUserTypeId == _userInfo.UserTypeId);


            var siteSurveyCount = await _trialRepository.Where(t => t.TrialStatusStr == StaticData.TrialState.TrialOngoing)
                    .Where(t => t.TrialUserList.Any(t => t.UserId == _userInfo.Id))
                    .WhereIf(_userInfo.UserTypeEnumInt == (int)UserTypeEnum.ProjectManager || _userInfo.UserTypeEnumInt == (int)UserTypeEnum.APM, c => c.TrialSiteSurveyList.Where(t => t.State == TrialSiteSurveyEnum.SPMApproved).Count() > 0)
                    .WhereIf(_userInfo.UserTypeEnumInt == (int)UserTypeEnum.CPM || _userInfo.UserTypeEnumInt == (int)UserTypeEnum.SPM, c => c.TrialSiteSurveyList.Where(t => t.State == TrialSiteSurveyEnum.CRCSubmitted).Count() > 0)
                    .CountAsync();

            //var trialNeedSignList = new List<TrialDocNeedSign>();

            //if (!_userInfo.IsAdmin)
            //{
            //    trialNeedSignList = await _trialRepository.Where(t => t.TrialStatusStr != StaticData.TrialState.TrialStopped)
            //        .Where(t => t.TrialUserList.Any(t => t.UserId == _userInfo.Id))
            //        .WhereIf(!_userInfo.IsAdmin, c => c.TrialDocumentList.Where(t => t.IsDeleted == false && t.NeedConfirmedUserTypeList.Any(t => t.NeedConfirmUserTypeId == _userInfo.UserTypeId) &&
            //        !t.TrialDocConfirmedUserList.Any(t => t.ConfirmUserId == _userInfo.Id && t.ConfirmTime != null)).Count() > 0)
            //        .Select(t=>new TrialDocNeedSign()
            //        {
            //            TrialId=t.Id, 
            //            TrialCode=t.TrialCode,
            //            ExperimentName=t.ExperimentName,
            //            ResearchProgramNo=t.ResearchProgramNo,
            //            IsHaveTrialDocNeedSign=true
            //        }).ToListAsync();

            //}    

            //防止生成sql生成GETDATE() 时区导致的问题
            var appDateTimeNow = DateTime.Now;

            var record = new UserToBeDoneRecord()
            {

                IsHaveSysDocNeedNeedSign = needSignSysDocCont > 0,
                //TrialNeedSignList= trialNeedSignList,

                SysWaitSignDocCount = needSignSysDocCont,
                TrialWaitSignDocCount = needSignTrialCount,

                TrialSignedDocCount = signedTrialCount,
                SysSignedDocCount = signedSysDocCont,

                SysNoticeUnReadCount = await _systemNoticeRepository.Where(t => t.NoticeUserTypeList.Any(t => t.UserTypeId == _userInfo.UserTypeId) && t.NoticeStateEnum == Domain.Share.SystemNotice_NoticeStateEnum.HavePublished
                     && !t.NoticeUserReadList.Any(t => t.CreateUserId == _userInfo.Id))
                    .Where(t => t.EndDate == null || t.EndDate != null && t.EndDate > appDateTimeNow)
                    .CountAsync(),

                #region PM

                PM_SiteSurveryCount = isPM ? siteSurveyCount : 0,

                PM_CheckCount = isPM ? await _trialRepository
                .Where(t => t.TrialUserList.Any(t => t.UserId == _userInfo.Id))
                .Where(u => u.SubjectVisitList.Any(t => t.CheckState == CheckStateEnum.ToCheck || (t.CheckState == CheckStateEnum.CVIng &&
                    t.CheckChallengeDialogList.OrderByDescending(t => t.CreateTime).First().UserTypeEnum == UserTypeEnum.ClinicalResearchCoordinator))).CountAsync() : 0,

                PM_ReviewerSelectCount = isPM ? await _trialRepository
                .Where(t => t.TrialUserList.Any(t => t.UserId == _userInfo.Id))
                .Where(t => t.EnrollList.Where(u => u.EnrollStatus == EnrollStatus.InviteIntoGroup).Count() > 0).CountAsync() : 0,

                PM_ReReadingApprovalCount = isPM ? await _visitTaskReReadingRepository
                .Where(t => t.OriginalReReadingTask.Trial.TrialUserList.Any(t => t.UserId == _userInfo.Id))
                .Where(t => t.OriginalReReadingTask.ReReadingApplyState == ReReadingApplyState.DocotorHaveApplyed)
                .GroupBy(t => t.OriginalReReadingTask.TrialId)
                 .Select(g => new ReReadingApplyToBeDoneDto()
                 {
                     TrialId = g.Key,
                     ToBeApprovalCount = g.Count(),

                 }).Where(x => x.ToBeApprovalCount > 0).CountAsync() : 0,

                PM_ClinicalDataCount = isPM ? await _trialRepository
                .Where(t => t.TrialUserList.Any(t => t.UserId == _userInfo.Id))
                .Where(t => t.ReadModuleList.Where(u => u.IsCRCConfirm && !u.IsPMConfirm).Count() > 0).CountAsync() : 0,

                #endregion

                #region CRC

                CRC_ImageSubmitCount = isCRC ? await _trialRepository
                .Where(t => t.TrialUserList.Any(t => t.UserId == _userInfo.Id) && (t.IsUrgent || t.IsSubjectExpeditedView || t.IsEnrollementQualificationConfirm || t.IsPDProgressView))
                .Where(t => t.SubjectVisitList.Where(c => c.TrialSite.CRCUserList.Any(u => u.UserId == _userInfo.Id)).Where(u => u.SubmitState == SubmitStateEnum.ToSubmit).Count() > 0).CountAsync() : 0,


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



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

                CRC_ImageReUploadCount = isCRC ? await _trialRepository
                .Where(t => t.TrialUserList.Any(t => t.UserId == _userInfo.Id))
                .Where(t => t.SubjectVisitList
                .Where(c => c.TrialSite.CRCUserList.Any(u => u.UserId == _userInfo.Id))
                .Where(u => (u.SubmitState == SubmitStateEnum.ToSubmit && u.IsPMBackOrReReading) || (u.IsQCConfirmedReupload)).Count() > 0).CountAsync() : 0,

                CRC_ClinicalDataTobeDoneCount = isCRC ? await _trialRepository
                .Where(t => t.TrialUserList.Any(t => t.UserId == _userInfo.Id))
                .Where(t => t.ReadingClinicalDataList.Where(x => !x.IsSign && x.ClinicalDataTrialSet.UploadRole == UploadRole.CRC).Count() > 0).CountAsync() : 0,

                CRC_ClinialDataTobeConfirmCount = isCRC ? await _trialRepository
                .Where(t => t.TrialUserList.Any(t => t.UserId == _userInfo.Id))
                .Where(t => t.ReadModuleList.Where(x => !x.IsCRCConfirm).Count() > 0).CountAsync() : 0,



                #endregion


                #region SPM


                SPM_SiteSurveryCount = isSPMOrCPM ? siteSurveyCount : 0,

                SPM_ReviewerApprovalCount = isSPMOrCPM ? await _trialRepository
                .Where(t => t.TrialUserList.Any(t => t.UserId == _userInfo.Id))
                .Where(t => t.EnrollList.Where(u => u.EnrollStatus == EnrollStatus.HasCommittedToCRO).Count() > 0).CountAsync() : 0,

                SPM_ReReadingApprovalCount = isSPMOrCPM ? await _visitTaskReReadingRepository
                .Where(t => t.OriginalReReadingTask.Trial.TrialUserList.Any(t => t.UserId == _userInfo.Id))
                .Where(t => t.OriginalReReadingTask.ReReadingApplyState == ReReadingApplyState.TrialGroupHaveApplyed)
                .GroupBy(t => t.OriginalReReadingTask.TrialId)
                .Select(g => new ReReadingApplyToBeDoneDto()
                {
                    TrialId = g.Key,
                    ToBeApprovalCount = g.Count(),

                }).Where(x => x.ToBeApprovalCount > 0).CountAsync() : 0,

                #endregion


                #region IQC


                IQC_IamgeQCCount = isIQC ? await _trialRepository
                .Where(t => t.TrialUserList.Any(t => t.UserId == _userInfo.Id))
                .Where(t => t.QCProcessEnum != TrialQCProcess.NotAudit)
                .Select(t => new
                {
                    //待领取量
                    ToBeClaimedCount = t.SubjectVisitList.Where(t => t.SubmitState == SubmitStateEnum.Submitted && t.AuditState != AuditStateEnum.QCPassed)
                    .Where(u => u.CurrentActionUserId == null && (u.PreliminaryAuditUserId == null || (u.PreliminaryAuditUserId != _userInfo.Id && u.ReviewAuditUserId == null))).Count(),

                    //待审核通过，统计从已领取到QC提交之间的      已领取 待审核 审核中   (审核完成  领取人就会清理 所以只用查询当前领取人是自己的就好了)
                    ToBeReviewedCount = t.SubjectVisitList.Where(u => u.CurrentActionUserId == _userInfo.Id).Count()

                }).Where(x => x.ToBeClaimedCount + x.ToBeReviewedCount > 0).CountAsync() : 0,

                IQC_QCQuestionCount = isIQC ? await _trialRepository
                .Where(t => t.TrialUserList.Any(t => t.UserId == _userInfo.Id))
                .Where(t => t.SubjectVisitList.SelectMany(c => c.QCChallengeList)
                .Where(u => u.CreateUserId == _userInfo.Id && u.IsClosed == false && u.LatestReplyUser.UserTypeEnum == UserTypeEnum.ClinicalResearchCoordinator).Count() > 0).CountAsync() : 0,



                #endregion


                #region IR

                IR_IamgeWaitReadingCount = isIR ?

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

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


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

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

                          : 0,


                IR_MedicalReviewCount = isIR ? await _taskMedicalReviewRepository.Where(t => t.Trial.TrialUserList.Any(t => t.UserId == _userInfo.Id))
                   .Where(t => t.IsClosedDialog == false && t.VisitTask.TaskState == TaskState.Effect && t.IsInvalid == false && t.VisitTask.DoctorUserId == _userInfo.Id)
                   .GroupBy(t => new { t.TrialId, t.VisitTask.TrialReadingCriterionId })
                   .Where(g => g.Where(u => u.LatestReplyUser.UserTypeEnum == UserTypeEnum.MIM && u.AuditState == MedicalReviewAuditState.Auditing).Count() > 0).CountAsync() : 0,


                #endregion

                #region MIM

                MIM_MedicalReviewCount = isMIM ? await _taskMedicalReviewRepository
                    .Where(t => t.Trial.TrialUserList.Any(t => t.UserId == _userInfo.Id))
                   .Where(t => t.IsClosedDialog == false && t.VisitTask.TaskState == TaskState.Effect && t.IsInvalid == false && t.MedicalManagerUserId == _userInfo.Id)
                   .GroupBy(t => new { t.TrialId, t.VisitTask.TrialReadingCriterionId })
                   .Select(g => new
                   {
                       TrialId = g.Key,

                       ToBeReplyedCount = g.Where(u => u.LatestReplyUser.UserTypeEnum == UserTypeEnum.IndependentReviewer && u.AuditState == MedicalReviewAuditState.Auditing).Count(),

                       ToBeReviewedCount = g.Where(u => u.AuditState != MedicalReviewAuditState.HaveSigned && u.LatestReplyUser.UserTypeEnum != UserTypeEnum.IndependentReviewer).Count()

                   }).Where(t => t.ToBeReviewedCount + t.ToBeReplyedCount > 0).CountAsync() : 0,

                #endregion

            };

            return record;
        }


        [HttpPost]
        public async Task<IResponseOutput<PageOutput<TrialToBeDoneDto>>> GetTrialToBeDoneList(TrialToBeDoneQuery inQuery,
              [FromServices] IRepository<TaskMedicalReview> _taskMedicalReviewRepository)
        {

            var isPM = _userInfo.UserTypeEnumInt == (int)UserTypeEnum.ProjectManager || _userInfo.UserTypeEnumInt == (int)UserTypeEnum.APM;
            var isCRC = _userInfo.UserTypeEnumInt == (int)UserTypeEnum.ClinicalResearchCoordinator;
            var isIQC = _userInfo.UserTypeEnumInt == (int)UserTypeEnum.IQC;
            var isMIM = _userInfo.UserTypeEnumInt == (int)UserTypeEnum.MIM;
            var isSPMOrCPM = _userInfo.UserTypeEnumInt == (int)UserTypeEnum.SPM || _userInfo.UserTypeEnumInt == (int)UserTypeEnum.CPM;
            var isIR = _userInfo.UserTypeEnumInt == (int)UserTypeEnum.IndependentReviewer;


            var query = _trialRepository.AsQueryable().IgnoreQueryFilters()

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

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

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

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

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


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

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

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

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

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

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

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

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


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

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

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

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


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

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

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


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

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

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

             });



            //.ProjectTo<TrialDetailDTO>(_mapper.ConfigurationProvider, new { userTypeEnumInt = _userInfo.UserTypeEnumInt, userId = _userInfo.Id });

            var result = await query.ToPagedListAsync(inQuery, nameof(TrialToBeDoneDto.CreateTime));

            return ResponseOutput.Ok(result);
        }




        #region  项目维度 统计每个人的待办

        [HttpPost]
        public async Task<IResponseOutput<List<TrialUserToBeDoneDto>>> GetTrialUserToBeDoneList(TrialUserToBeDoneQuery inQuery,
      [FromServices] IRepository<TrialUser> _trialUserRepository)
        {

            var query = _trialUserRepository.Where(t => t.TrialId == inQuery.TrialId)
                .Select(t => new TrialUserToBeDoneDto()
                {
                    UserName = t.User.UserName,
                    FullName = t.User.FullName,
                    UserType = t.User.UserTypeEnum,

                    //SPM  阅片人筛选
                    ReviewerSelect_SPM_ToBeApprovalCount =
                    (t.User.UserTypeEnum == UserTypeEnum.SPM || t.User.UserTypeEnum == UserTypeEnum.CPM) ?
                    t.Trial.EnrollList.Where(u => u.EnrollStatus == EnrollStatus.HasCommittedToCRO).Count() : 0,

                    //PM  阅片人确认
                    ReviewerSelect_PM_ToBeConfirmCount =
                     (t.User.UserTypeEnum == UserTypeEnum.APM || t.User.UserTypeEnum == UserTypeEnum.ProjectManager) ?
                    t.Trial.EnrollList.Where(u => u.EnrollStatus == EnrollStatus.InviteIntoGroup).Count() : 0,

                    //CRC  重传 --区分人
                    ImageUpload_CRC_ToBeReUploadCount =
                     (t.User.UserTypeEnum == UserTypeEnum.ClinicalResearchCoordinator || t.User.UserTypeEnum == UserTypeEnum.CRA) ?
                    t.Trial.SubjectVisitList.Where(c => c.TrialSite.CRCUserList.Any(u => u.UserId == t.UserId))
                    .Where(u => u.SubmitState == SubmitStateEnum.ToSubmit && u.IsPMBackOrReReading).Count() : 0,

                    //CRC加急待提交  需确认？--区分人
                    ImageUpload_CRC_ToBeSubmitCount =
                     (t.User.UserTypeEnum == UserTypeEnum.ClinicalResearchCoordinator || t.User.UserTypeEnum == UserTypeEnum.CRA) ?
                    t.Trial.SubjectVisitList.Where(c => c.TrialSite.CRCUserList.Any(u => u.UserId == t.UserId))
                    .Where(u => u.SubmitState == SubmitStateEnum.ToSubmit).Count() : 0,

                    //  QC   IQC 待领取
                    QC_IQC_ToBeClaimedCount =
                     (t.User.UserTypeEnum == UserTypeEnum.IQC) ?
                    t.Trial.SubjectVisitList.Where(u => u.CurrentActionUserId == null && (u.PreliminaryAuditUserId == null || (u.PreliminaryAuditUserId != _userInfo.Id && u.ReviewAuditUserId == null))).Count() : 0,


                    // CRC  质疑待回复 --区分人
                    QC_CRC_ToBeDealedCount =
                    (t.User.UserTypeEnum == UserTypeEnum.ClinicalResearchCoordinator || t.User.UserTypeEnum == UserTypeEnum.CRA) ?
                    t.Trial.SubjectVisitList.Where(c => c.TrialSite.CRCUserList.Any(u => u.UserId == t.UserId))
                    .SelectMany(c => c.QCChallengeList).Where(u => u.IsClosed == false && u.LatestReplyUser.UserTypeEnum == UserTypeEnum.IQC).Count() : 0,


                    //IQC 质疑待处理  --区分人
                    QC_IQC_ToBeDealedCount =
                    (t.User.UserTypeEnum == UserTypeEnum.IQC) ?
                    t.Trial.SubjectVisitList.SelectMany(c => c.QCChallengeList)
                    .Where(u => u.CreateUserId == t.UserId && u.IsClosed == false && u.LatestReplyUser.UserTypeEnum == UserTypeEnum.ClinicalResearchCoordinator).Count() : 0,



                    // IQC  待审核
                    QC_IQC_ToBeReviewedCount =
                    (t.User.UserTypeEnum == UserTypeEnum.IQC) ?
                    t.Trial.SubjectVisitList.Where(u => u.CurrentActionUserId == t.UserId).Count() : 0,



                    //PM 核查待处理
                    Check_PM_ToBeDealedCount =
                    (t.User.UserTypeEnum == UserTypeEnum.APM || t.User.UserTypeEnum == UserTypeEnum.ProjectManager) ?
                    t.Trial.SubjectVisitList.Where(u => u.CheckState == CheckStateEnum.ToCheck).Count() : 0,

                    //PM 质疑待处理
                    Check_PM_ToBeReplyedCount =
                    (t.User.UserTypeEnum == UserTypeEnum.APM || t.User.UserTypeEnum == UserTypeEnum.ProjectManager) ?
                    t.Trial.SubjectVisitList.Where(u => u.CheckState == CheckStateEnum.CVIng &&
                    u.CheckChallengeDialogList.OrderByDescending(t => t.CreateTime).First().UserTypeEnum == UserTypeEnum.ClinicalResearchCoordinator).Count() : 0,


                    // CRC  核查  质疑待处理  --区分人
                    Check_CRC_ToBeDealedCount =
                    (t.User.UserTypeEnum == UserTypeEnum.ClinicalResearchCoordinator || t.User.UserTypeEnum == UserTypeEnum.CRA) ?
                    t.Trial.SubjectVisitList.Where(c => c.TrialSite.CRCUserList.Any(u => u.UserId == t.UserId))
                    .Where(u => u.CheckState == CheckStateEnum.CVIng && u.CheckChallengeState == CheckChanllengeTypeEnum.PMWaitCRCReply).Count() : 0,


                    //IR  未读   --区分人
                    Reading_IR_UnReadCount =
                    (t.User.UserTypeEnum == UserTypeEnum.IndependentReviewer) ?
                    t.Trial.VisitTaskList
                   .Where(c => c.DoctorUserId == t.UserId && c.ReadingTaskState != ReadingTaskState.HaveSigned && c.TaskState == TaskState.Effect)
                   // 前序 不存在 未一致性核查未通过的
                   .Where(t => !t.Subject.SubjectVisitList.Any(sv => sv.CheckState != CheckStateEnum.CVPassed && t.VisitTaskNum > sv.VisitNum))
                   //前序 不存在  未生成任务的访视
                   .Where(t => t.TrialReadingCriterion.IsAutoCreate == false ? !t.Subject.SubjectCriteriaEvaluationVisitFilterList.Where(d => d.TrialReadingCriterionId == t.TrialReadingCriterionId).Any(f => f.IsGeneratedTask == false && t.VisitTaskNum > f.SubjectVisit.VisitNum) : true)

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


                    //SPM   PM重阅审批
                    Reading_SPM_ToBeApprovalCount =
                    (t.User.UserTypeEnum == UserTypeEnum.SPM || t.User.UserTypeEnum == UserTypeEnum.CPM) ?
                    t.Trial.VisitTaskReReadingList.Where(t => t.OriginalReReadingTask.ReReadingApplyState == ReReadingApplyState.TrialGroupHaveApplyed).Count() : 0,

                    //PM   IR重阅审批
                    Reading_PM_ToBeApprovalCount =
                    (t.User.UserTypeEnum == UserTypeEnum.APM || t.User.UserTypeEnum == UserTypeEnum.ProjectManager) ?
                    t.Trial.VisitTaskReReadingList.Where(t => t.OriginalReReadingTask.ReReadingApplyState == ReReadingApplyState.DocotorHaveApplyed).Count() : 0,

                    //IR 医学审核    --区分人
                    Medical_IR_ToBeDealedCount =
                    (t.User.UserTypeEnum == UserTypeEnum.IndependentReviewer) ?
                    t.Trial.TaskMedicalReviewList
                    .Where(c => c.IsClosedDialog == false && c.VisitTask.DoctorUserId == t.UserId && c.IsInvalid == false)
                    .Where(u => u.ReadingMedicalReviewDialogList.OrderByDescending(l => l.CreateTime).First().UserTypeEnumInt == (int)UserTypeEnum.MIM).Count() : 0,


                    Medical_MIM_ToBeDealedCount =
                    (t.User.UserTypeEnum == UserTypeEnum.MIM) ?
                    t.Trial.TaskMedicalReviewList
                    .Where(t => t.IsClosedDialog == false)
                .Where(u => u.ReadingMedicalReviewDialogList.OrderByDescending(l => l.CreateTime).First().UserTypeEnumInt == (int)UserTypeEnum.IndependentReviewer).Count() : 0,

                    Medical_MIM_ToBeReviewedCount =
                    (t.User.UserTypeEnum == UserTypeEnum.MIM) ?
                    t.Trial.TaskMedicalReviewList
                    .Where(t => t.IsClosedDialog == false && t.IsInvalid == false)
                    .Where(u => !u.IsInvalid && u.AuditState != MedicalReviewAuditState.HaveSigned).Count() : 0

                });


            var list = await query.ToListAsync();

            var result = list.Where(t => t.UserTotalToBeDoneCount > 0).OrderBy(t => t.UserType).ToList();

            //var result=   list.GroupBy(t => t.UserType).ToDictionary(g => g.Key, g => g.ToList());

            return ResponseOutput.Ok(result);
        }


        #endregion




        #endregion
    }
}
