using IRaCIS.Application.Contracts;
using IRaCIS.Core.Application.Contracts;
using IRaCIS.Core.Application.Interfaces;
using IRaCIS.Core.Application.ViewModel;
using IRaCIS.Core.Domain.Models;
using IRaCIS.Core.Domain.Share;
using IRaCIS.Core.Infrastructure;
using IRaCIS.Core.Infrastructure.Extention;
using MathNet.Numerics;
using Microsoft.AspNetCore.Mvc;
using System.Linq;
using System.Linq.Dynamic.Core;

namespace IRaCIS.Core.Application
{
    [ApiExplorerSettings(GroupName = "Trial")]
    public class PersonalWorkstation : BaseService
    {
        private readonly IRepository<Trial> _trialRepository;
        private readonly IRepository<TrialUser> _trialUserRepository;
        private readonly IRepository<TrialDocument> _trialDocumentRepository;
        private readonly IRepository<SystemDocument> _systemDocumentRepository;
        private readonly IRepository<ReadModule> _readModuleRepository;
        private readonly IRepository<SystemNotice> _systemNoticeRepository;

        public PersonalWorkstation(IRepository<Trial> trialRepository, IRepository<TrialUser> trialUserRepository, IRepository<TrialDocument> trialDocumentRepository,
            IRepository<SystemDocument> systemDocumentRepository,
             IRepository<ReadModule> readModuleRepository,
            IRepository<SystemNotice> systemNoticeRepository)
        {
            _trialRepository = trialRepository;
            _trialUserRepository = trialUserRepository;
            _trialDocumentRepository = trialDocumentRepository;
            _systemDocumentRepository = systemDocumentRepository;
            this._readModuleRepository = readModuleRepository;
            _systemNoticeRepository = systemNoticeRepository;
        }

        /// <summary>
        /// 个人面板 统计值
        /// </summary>
        /// <returns></returns>
        public async Task<PersonalStataDTO> GetBasicStat()
        {

            return new PersonalStataDTO()
            {
                //正参与的数量
                TrialCount = _userInfo.UserTypeEnumInt == (int)UserTypeEnum.SuperAdmin
                    ? await _trialRepository.CountAsync()
                    : await _trialUserRepository.Where(t => t.UserId == _userInfo.Id).CountAsync(),

                DeletedCount = _userInfo.UserTypeEnumInt == (int)UserTypeEnum.SuperAdmin
                    ? await _trialRepository.AsQueryable(true).CountAsync(t => t.IsDeleted)
                    : await _trialUserRepository.AsQueryable(true).Where(t => t.UserId == _userInfo.Id && t.IsDeleted)
                        .CountAsync(),


                TotalNeedSignTrialDocCount = _userInfo.UserTypeEnumInt == (int)UserTypeEnum.SuperAdmin
                    ? 0
                    : await _trialDocumentRepository.AsQueryable(true).Where(t => t.Trial.TrialStatusStr != StaticData.TrialState.TrialStopped)
                        .Where(t => t.Trial.TrialUserList.Any(t => t.UserId == _userInfo.Id))
                        .Where(t => t.IsDeleted == false || (t.IsDeleted == true && t.TrialDocConfirmedUserList.Any(t => t.ConfirmUserId == _userInfo.Id && t.ConfirmTime != null)))

                        .SelectMany(t => t.NeedConfirmedUserTypeList)
                        .CountAsync(t => t.NeedConfirmUserTypeId == _userInfo.UserTypeId),

                HaveSignedTrialDocCount = _userInfo.UserTypeEnumInt == (int)UserTypeEnum.SuperAdmin
                    ? 0
                    //废除了 已经签署了也要算进去
                    : await _trialDocumentRepository.AsQueryable(true).Where(t => t.Trial.TrialStatusStr != StaticData.TrialState.TrialStopped)
                        .Where(t => t.Trial.TrialUserList.Any(t => t.UserId == _userInfo.Id))
                        .Where(t => t.NeedConfirmedUserTypeList.Any(t => t.NeedConfirmUserTypeId == _userInfo.UserTypeId))
                        .SelectMany(t => t.TrialDocConfirmedUserList)
                        .CountAsync(t => t.ConfirmUserId == _userInfo.Id && t.ConfirmTime != null),

                TotalNeedSignSystemDocCount = _userInfo.UserTypeEnumInt == (int)UserTypeEnum.SuperAdmin
                    ? 0
                    : await _systemDocumentRepository
                        .Where(t => t.IsDeleted == false || (t.IsDeleted == true && t.SystemDocConfirmedUserList.Any(t => t.ConfirmUserId == _userInfo.Id && t.ConfirmTime != null)))
                        .SelectMany(t => t.NeedConfirmedUserTypeList)
                        .CountAsync(t => t.NeedConfirmUserTypeId == _userInfo.UserTypeId),


                HaveSignedSystemDocCount = _userInfo.UserTypeEnumInt == (int)UserTypeEnum.SuperAdmin
                    ? 0
                    : await _systemDocumentRepository
                        .Where(t => t.NeedConfirmedUserTypeList.Any(t => t.NeedConfirmUserTypeId == _userInfo.UserTypeId))
                        .SelectMany(t => t.SystemDocConfirmedUserList)
                        .CountAsync(t => t.ConfirmUserId == _userInfo.Id && t.ConfirmTime != null),

                TotalApprovalRequiredCount =
                    _userInfo.UserTypeEnumInt == (int)UserTypeEnum.ProjectManager || _userInfo.UserTypeEnumInt == (int)UserTypeEnum.APM ?
                    _trialRepository.Where(t => t.TrialUserList.Any(t => t.UserId == _userInfo.Id)).SelectMany(t => t.TrialSiteSurveyList).Where(t => t.State == TrialSiteSurveyEnum.SPMApproved).Count()
                    : _userInfo.UserTypeEnumInt == (int)UserTypeEnum.CPM || _userInfo.UserTypeEnumInt == (int)UserTypeEnum.SPM
                    ? _trialRepository.Where(t => t.TrialUserList.Any(t => t.UserId == _userInfo.Id)).SelectMany(t => t.TrialSiteSurveyList).Where(t => t.State == TrialSiteSurveyEnum.CRCSubmitted).Count()
                    : 0,


                TotalSystemNoticeCount = _userInfo.UserTypeEnumInt == (int)UserTypeEnum.SuperAdmin
                    ? 0 : await _systemNoticeRepository.Where(t => t.NoticeUserTypeList.Any(t => t.UserTypeId == _userInfo.UserTypeId) && t.NoticeStateEnum == Domain.Share.Management.SystemNotice_NoticeStateEnum.HavePublished)

                    .CountAsync(),

                NeedReadSystemNoticeCount = _userInfo.UserTypeEnumInt == (int)UserTypeEnum.SuperAdmin
                    ? 0 : await _systemNoticeRepository.Where(t => t.NoticeUserTypeList.Any(t => t.UserTypeId == _userInfo.UserTypeId) && t.NoticeStateEnum == Domain.Share.Management.SystemNotice_NoticeStateEnum.HavePublished
                     && !t.NoticeUserReadList.Any(t => t.CreateUserId == _userInfo.Id))
                    .Where(t => t.EndDate == null || t.EndDate != null && t.EndDate > DateTime.Now)
                    .CountAsync(),


            };

        }


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


            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.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(query.PageIndex, query.PageSize, query.SortField, query.Asc);
            }

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

            }

        }


        /// <summary>
        ///   待签署的项目文件      需要签署文件数量  系统级别的在第一行
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<PageOutput<DocSignStat>> GetTrialDocStatList(TrialSiteSurveyStatQuery query)
        {
            if (_userInfo.IsAdmin)
            {
                return new PageOutput<DocSignStat>(query.PageIndex, query.PageSize, 0, new List<DocSignStat>());
            }
            else
            {
                var trialDocStat = await _trialRepository/*.AsQueryable(true)*/.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)
                    .ProjectTo<DocSignStat>(_mapper.ConfigurationProvider, new { userTypeEnumInt = _userInfo.UserTypeEnumInt, userId = _userInfo.Id, userTypeId = _userInfo.UserTypeId })
                    .OrderByDescending(t => t.WaitSignCount)
                    .ToPagedListAsync(query.PageIndex, query.PageSize, query.SortField, query.Asc);


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



            var result = await query.ToPagedListAsync(inQuery.PageIndex, inQuery.PageSize, string.IsNullOrEmpty(inQuery.SortField) ? nameof(CheckToBeDoneDto.TrialId) : inQuery.SortField, inQuery.Asc);

            var totalToBeCheckedCount = await _subjectVisitRepository.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.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.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 result = await query.ToPagedListAsync(inQuery.PageIndex, inQuery.PageSize, string.IsNullOrEmpty(inQuery.SortField) ? nameof(ReReadingApplyToBeDoneDto.TrialId) : inQuery.SortField, inQuery.Asc);


            var toBeApprovalCount = _visitTaskReReadingRepository
                 .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核对临床数据
        /// </summary>
        /// <param name="inQuery"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IResponseOutput<PageOutput<GetPMClinicalDataToBeDoneListOutDto>>> GetPMClinicalDataToBeDoneList(ReviewerSelectToBeDoneQuery inQuery)
        {
            
            var query = _trialRepository
                .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 result = await query.ToPagedListAsync(inQuery.PageIndex, inQuery.PageSize, string.IsNullOrEmpty(inQuery.SortField) ? nameof(ReviewerSelectToBeDoneDto.TrialId) : inQuery.SortField, inQuery.Asc);
       

            var all =await _trialRepository
                .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="_visitTaskReReadingRepository"></param>
        /// <param name="_trialRepository"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IResponseOutput<PageOutput<ReReadingApprovalToBeDoneDto>>> GetSPMReReadingApprovalToBeDone(ReReadingApprovalToBeDoneQuery inQuery,
           [FromServices] IRepository<VisitTaskReReading> _visitTaskReReadingRepository,
              [FromServices] IRepository<Trial> _trialRepository)

        {
            var query = _visitTaskReReadingRepository
                .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 result = await query.ToPagedListAsync(inQuery.PageIndex, inQuery.PageSize, string.IsNullOrEmpty(inQuery.SortField) ? nameof(ReReadingApprovalToBeDoneDto.TrialId) : inQuery.SortField, inQuery.Asc);

            var toBeApprovalCount = _visitTaskReReadingRepository
                 .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>
        /// <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.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.ToBeDealedCount > 0);

            var result = await query.ToPagedListAsync(inQuery.PageIndex, inQuery.PageSize, string.IsNullOrEmpty(inQuery.SortField) ? nameof(ImageClinicalDataToBeDoneDto.TrialId) : inQuery.SortField, inQuery.Asc);

            var toBeDealedCount = _subjectVisitRepository
                 //.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>
        /// <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.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.ReadModuleCount > 0);

            var result = await query.ToPagedListAsync(inQuery.PageIndex, inQuery.PageSize, string.IsNullOrEmpty(inQuery.SortField) ? nameof(ImageClinicalDataToBeDoneDto.TrialId) : inQuery.SortField, inQuery.Asc);

            var toBeDealedCount = _subjectVisitRepository
                 //.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.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).Count(),

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

            var result = await query.ToPagedListAsync(inQuery.PageIndex, inQuery.PageSize, string.IsNullOrEmpty(inQuery.SortField) ? nameof(ImageQuestionToBeDoneDto.TrialId) : inQuery.SortField, inQuery.Asc);

            var toBeDealedCount = _subjectVisitRepository
                  .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>
        /// <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.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 result = await query.ToPagedListAsync(inQuery.PageIndex, inQuery.PageSize, string.IsNullOrEmpty(inQuery.SortField) ? nameof(ImageCheckQuestionToBeDoneDto.TrialId) : inQuery.SortField, inQuery.Asc);

            var toBeDealedCount = _subjectVisitRepository
                  .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>
        /// <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.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.SubmitState == SubmitStateEnum.ToSubmit && u.IsUrgent && u.IsPMBackOrReReading).Count(),

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

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

            var result = await query.ToPagedListAsync(inQuery.PageIndex, inQuery.PageSize, string.IsNullOrEmpty(inQuery.SortField) ? nameof(ImageReUploadToBeDoneDto.TrialId) : inQuery.SortField, inQuery.Asc);

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

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

        }




        /// <summary>
        /// 加急影像提交   --CRC 待办
        /// </summary>
        /// <param name="inQuery"></param>
        /// <param name="_subjectVisitRepository"></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.TrialUserList.Any(t => t.UserId == _userInfo.Id))
                .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.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 result = await query.ToPagedListAsync(inQuery.PageIndex, inQuery.PageSize, string.IsNullOrEmpty(inQuery.SortField) ? nameof(ImageSubmittedToBeDoneDto.TrialId) : inQuery.SortField, inQuery.Asc);

            var toBeDealedCount = _subjectVisitRepository
                  .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>
        /// <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.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(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.UrgentCount > 0); 

            var result = await query.ToPagedListAsync(inQuery.PageIndex, inQuery.PageSize, string.IsNullOrEmpty(inQuery.SortField) ? nameof(ImageQualityToBeDoneDto.TrialId) : inQuery.SortField, inQuery.Asc);


            var toBeClaimedCount = _subjectVisitRepository
                .Where(t => t.Trial.TrialUserList.Any(t => t.UserId == _userInfo.Id))
                .Where(u => u.CurrentActionUserId == null && (u.PreliminaryAuditUserId == null || (u.PreliminaryAuditUserId != _userInfo.Id && u.ReviewAuditUserId == null))).Count();


            var toBeReviwedCount = _subjectVisitRepository.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>
        /// <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.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 result = await query.ToPagedListAsync(inQuery.PageIndex, inQuery.PageSize, string.IsNullOrEmpty(inQuery.SortField) ? nameof(ImageQuestionToBeDoneDto.TrialId) : inQuery.SortField, inQuery.Asc);

            var toBeDealedCount = _subjectVisitRepository
                  .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.IsConfirm == true && 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 ? !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 ? !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 result = await newQuery.ToPagedListAsync(inQuery.PageIndex, inQuery.PageSize, string.IsNullOrEmpty(inQuery.SortField) ? nameof(IRImageReadingToBeDoneDto.TrialId) : inQuery.SortField, inQuery.Asc);

            var toBeDealedCount = _trialRepository
                   .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)
                   // 前序 不存在 未一致性核查未通过的
                   .Where(t => !t.Subject.SubjectVisitList.Any(sv => sv.CheckState != CheckStateEnum.CVPassed && t.VisitTaskNum > sv.VisitNum))

                  .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>

        /// <returns></returns>
        [HttpPost]
        public async Task<IResponseOutput<PageOutput<MedicalCommentsToBeDoneDto>>> GetIRMedicalCommentsToBeDoneList(MedicalCommentsToBeDoneQuery inQuery,
             [FromServices] IRepository<TaskMedicalReview> _taskMedicalReviewRepository)
        {

            var query = _taskMedicalReviewRepository
                .Where(t => t.Trial.TrialUserList.Any(t => t.UserId == _userInfo.Id))
                .Where(t => t.IsClosedDialog == false)
                .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
                    //&& 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(),

                });

            var result = await query.ToPagedListAsync(inQuery.PageIndex, inQuery.PageSize, string.IsNullOrEmpty(inQuery.SortField) ? nameof(MedicalCommentsToBeDoneDto.TrialId) : inQuery.SortField, inQuery.Asc);

            var toBeDealedCount = _taskMedicalReviewRepository
                .Where(t => t.Trial.TrialUserList.Any(t => t.UserId == _userInfo.Id))
                .Where(t => t.IsClosedDialog == false && t.VisitTask.DoctorUserId == _userInfo.Id)
                .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>

        /// <returns></returns>
        [HttpPost]
        public async Task<IResponseOutput<PageOutput<MedicalCommentsToBeDoneDto>>> GetMIMMedicalCommentsToBeDoneList(MedicalCommentsToBeDoneQuery inQuery,
             [FromServices] IRepository<TaskMedicalReview> _taskMedicalReviewRepository)
        {


            #region 废弃不能对包含聚合或子查询的表达式执行聚合函数
            var query = _taskMedicalReviewRepository
                    .Where(t => t.Trial.TrialUserList.Any(t => t.UserId == _userInfo.Id))
                   .Where(t => t.IsClosedDialog == false)
                   .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,

                       //UrgentCount = g.Where(u => u.VisitTask.IsUrgent).Select(u => u.ReadingMedicalReviewDialogList.OrderByDescending(l => l.CreateTime).First()).Count(t => t.UserTypeEnumInt == (int)UserTypeEnum.IndependentReviewer),

                       //ToBeReplyedCount = g.Select(t => t.ReadingMedicalReviewDialogList.OrderByDescending(l => l.CreateTime).First()).Count(t => t.UserTypeEnumInt == (int)UserTypeEnum.IndependentReviewer),

                       ToBeReviewedCount = g.Where(u => !u.IsInvalid && u.AuditState != MedicalReviewAuditState.HaveSigned).Count()

                   });

            #endregion



            var result = await query.ToPagedListAsync(inQuery.PageIndex, inQuery.PageSize, string.IsNullOrEmpty(inQuery.SortField) ? nameof(MedicalCommentsToBeDoneDto.TrialId) : inQuery.SortField, inQuery.Asc);

            var toBeReplyedQuery = _taskMedicalReviewRepository
                  .Where(t => t.Trial.TrialUserList.Any(t => t.UserId == _userInfo.Id))
                  .Where(t => t.IsClosedDialog == false)
                  .Where(u => u.ReadingMedicalReviewDialogList.OrderByDescending(l => l.CreateTime).First().UserTypeEnumInt == (int)UserTypeEnum.IndependentReviewer);

            var toBeReplyedCount = toBeReplyedQuery.Count();

            var tobeReviewedCount = _taskMedicalReviewRepository
                  .Where(t => t.Trial.TrialUserList.Any(t => t.UserId == _userInfo.Id))
                  .Where(t => t.IsClosedDialog == false)
                  .Where(u => !u.IsInvalid && u.AuditState != MedicalReviewAuditState.HaveSigned).Count();

            //var firstToBeDone = toBeDealedQuery.ProjectTo<TaskMedicalReviewView>(_mapper.ConfigurationProvider).FirstOrDefault();

            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 项目列表查询  +  待办详情


        [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 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, t => t.TrialUserList.Any(t => t.UserId == _userInfo.Id && t.IsDeleted == false) && t.IsDeleted == false)
             .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



             });



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

            var result = await query.ToPagedListAsync(inQuery.PageIndex, inQuery.PageSize, string.IsNullOrWhiteSpace(inQuery.SortField) ? "CreateTime" : inQuery.SortField, inQuery.Asc);

            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,

               

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


        #region 废弃
        #region 上传影像

        #endregion

        #region QC

        #endregion

        #region 一致性核查

        #endregion

        #region 阅片

        #endregion

        #endregion

        #endregion




        #endregion
    }
}
