//--------------------------------------------------------------------
//     此代码由T4模板自动生成  byzhouhang 20210918
//	   生成时间 2022-07-01 15:33:04 
//     对此文件的更改可能会导致不正确的行为，并且如果重新生成代码，这些更改将会丢失。
//--------------------------------------------------------------------

using IRaCIS.Core.Domain.Models;
using Microsoft.AspNetCore.Mvc;
using IRaCIS.Core.Application.Interfaces;
using IRaCIS.Core.Application.ViewModel;
using IRaCIS.Core.Infrastructure;
using IRaCIS.Core.Domain.Share;
using System.Linq.Expressions;
using IRaCIS.Core.Infra.EFCore.Common;
using System.Linq;
using Nito.AsyncEx;
using IRaCIS.Core.Application.Contracts;
using IRaCIS.Core.Application.Filter;

namespace IRaCIS.Core.Application.Service
{
    /// <summary>
    /// 一致性分析配置表
    /// </summary>	
    [ApiExplorerSettings(GroupName = "Trial")]
    public class TaskConsistentRuleService : BaseService, ITaskConsistentRuleService
    {

        private readonly IRepository<TaskConsistentRule> _taskConsistentRuleRepository;
        private readonly IRepository<VisitTask> _visitTaskRepository;
        private readonly IRepository<SubjectUser> _subjectUserRepository;
        private readonly IRepository<Subject> _subjectRepository;
        private readonly IRepository<Enroll> _enrollRepository;

        private readonly AsyncLock _mutex = new AsyncLock();

        public TaskConsistentRuleService(IRepository<VisitTask> visitTaskRepository, IRepository<Enroll> enrollRepository, IRepository<TaskConsistentRule> taskConsistentRuleRepository, IRepository<SubjectUser> subjectUserRepository, IRepository<Subject> subjectRepository)
        {
            _taskConsistentRuleRepository = taskConsistentRuleRepository;
            _visitTaskRepository = visitTaskRepository;
            _subjectUserRepository = subjectUserRepository;
            _subjectRepository = subjectRepository;
            _enrollRepository = enrollRepository;
        }

        /// <summary>
        /// 设置一致性分析任务失效
        /// </summary>
        /// <param name="taskIdList"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IResponseOutput> SetAnalysisTaskInvalid(List<Guid> taskIdList)
        {


            await _visitTaskRepository.UpdatePartialFromQueryAsync(t => taskIdList.Contains(t.Id), u => new VisitTask() { TaskState = TaskState.NotEffect },true);

            await _visitTaskRepository.SaveChangesAsync();

            return ResponseOutput.Ok();

        }


        /// <summary>
        /// 一致性分析列表  (自身 组内  最后勾选 产生的任务)
        /// </summary>
        /// <param name="queryVisitTask"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<PageOutput<AnalysisTaskView>> GetAnalysisTaskList(VisitTaskQuery queryVisitTask)
        {
            var visitTaskQueryable = _visitTaskRepository.Where(t => t.TrialId == queryVisitTask.TrialId)
                .Where(t => t.IsAnalysisCreate)

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

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

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

            var pageList = await visitTaskQueryable.ToPagedListAsync(queryVisitTask.PageIndex, queryVisitTask.PageSize, queryVisitTask.SortField, queryVisitTask.Asc, string.IsNullOrWhiteSpace(queryVisitTask.SortField), defalutSortArray);

            //var trialTaskConfig = _repository.Where<Trial>(t => t.Id == queryVisitTask.TrialId).ProjectTo<TrialTaskConfigView>(_mapper.ConfigurationProvider).FirstOrDefault();
            return pageList;
        }


        /// <summary>
        /// 为自身一致性分析医生，选择Subejct 列表
        /// </summary>
        /// <param name="inQuery"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<PageOutput<DoctorSelfConsistentSubjectView>> GetDoctorSelfConsistentRuleSubjectList(ConsistentQuery inQuery)
        {
            var filterObj = await _taskConsistentRuleRepository.FirstOrDefaultAsync(t => t.Id == inQuery.TaskConsistentRuleId);

            var pagedList = await GetIQueryableDoctorSelfConsistentSubjectView(filterObj, inQuery.DoctorUserId).ToPagedListAsync(inQuery.PageIndex, inQuery.PageSize, string.IsNullOrWhiteSpace(inQuery.SortField) ? nameof(DoctorSelfConsistentSubjectView.SubjectCode) : inQuery.SortField, inQuery.Asc);

            return pagedList;
        }



        /// <summary>
        /// 确认生成自身一致性分析任务
        /// </summary>
        /// <param name="inCommand"></param>
        /// <param name="_visitTaskCommonService"></param>
        /// <returns></returns>
        [HttpPost]
        [UnitOfWork]
        [TypeFilter(typeof(TrialResourceFilter), Arguments = new object[] { "AfterStopCannNotOpt" })]

        public async Task<IResponseOutput> ConfirmGenerateSelfConsistentTask(ConsistentConfirmGenerateCommand inCommand, [FromServices] IVisitTaskHelpeService _visitTaskCommonService)
        {


            var filterObj = await _taskConsistentRuleRepository.FirstOrDefaultAsync(t => t.Id == inCommand.TaskConsistentRuleId);
            var doctorUserId = inCommand.DoctorUserId;
            var trialReadingCriterionId = filterObj.TrialReadingCriterionId;

            var list = await GetIQueryableDoctorSelfConsistentSubjectView(filterObj, doctorUserId, inCommand.SubejctIdList).ToListAsync();

            //var (group, query) = GetIQueryableDoctorSelfConsistentRuleSubjectView(filterObj, inCommand.SubejctIdList);

            //var list = query.OrderByDescending(t => t.IsHaveGeneratedTask).ToList();

            using (await _mutex.LockAsync())
            {
                int maxCodeInt = 0;

                foreach (var subject in list)
                {
                    //处理 Subject 编号 

                    var blindSubjectCode = string.Empty;

                    var subjectTask = _visitTaskRepository.Where(t => t.SubjectId == subject.SubjectId && t.TrialReadingCriterionId==trialReadingCriterionId && t.IsSelfAnalysis == true).OrderByDescending(t => t.BlindSubjectCode).FirstOrDefault();

                    if (subjectTask!=null &&  subjectTask.BlindSubjectCode != String.Empty)
                    {
                        blindSubjectCode = subjectTask.BlindSubjectCode;
                    }
                    else
                    {
                        var maxCodeStr = _visitTaskRepository.Where(t => t.TrialId == subject.TrialId && t.TrialReadingCriterionId == trialReadingCriterionId && t.IsSelfAnalysis == true).OrderByDescending(t => t.BlindSubjectCode).Select(t => t.BlindSubjectCode).FirstOrDefault();

                        if ( !string.IsNullOrEmpty(maxCodeStr))
                        {
                            int.TryParse(maxCodeStr.Substring(maxCodeStr.Length - filterObj.BlindSubjectNumberOfPlaces), out maxCodeInt);

                        }                      

                        blindSubjectCode = filterObj.BlindTrialSiteCode + (maxCodeInt + 1).ToString($"D{filterObj.BlindSubjectNumberOfPlaces}");
                    }

                    subject.VisitTaskList = subject.VisitTaskList.Take(filterObj.PlanVisitCount).ToList();

                    subject.VisitTaskList.ForEach(t =>
                    {
                        t.DoctorUserId = doctorUserId;
                        //t.TaskConsistentRuleId = filterObj.Id;
                        t.BlindTrialSiteCode = filterObj.BlindTrialSiteCode;
                        t.BlindSubjectCode = blindSubjectCode;
                    });


                    //最后一个检查批次添加全局
                    if (filterObj.IsGenerateGlobalTask)
                    {
                        var lastTask = (subject.VisitTaskList.Take(filterObj.PlanVisitCount).Last()).Clone();

                        var existGlobal = _visitTaskRepository.Where(t => t.SubjectId == lastTask.SubjectId &&t.TrialReadingCriterionId==trialReadingCriterionId && t.TaskState == TaskState.Effect && t.ReadingCategory == ReadingCategory.Global && t.VisitTaskNum == lastTask.VisitTaskNum + ReadingCommon.TaskNumDic[ReadingCategory.Global]).ProjectTo<VisitTaskSimpleDTO>(_mapper.ConfigurationProvider).FirstOrDefault();


                        if (existGlobal == null)
                        {
                            existGlobal = new VisitTaskSimpleDTO()
                            {
                                SubjectId = lastTask.SubjectId,
                                TrialId = lastTask.TrialId,
                                ArmEnum = lastTask.ArmEnum,
                                ReadingCategory = ReadingCategory.Global,
                                TaskName = lastTask.TaskName + "_Global",
                                TaskBlindName = lastTask.TaskBlindName + "_Global",
                                TrialReadingCriterionId=trialReadingCriterionId,
                            };
                        }


                        existGlobal.DoctorUserId = doctorUserId;
                        existGlobal.BlindSubjectCode = lastTask.BlindSubjectCode;
                        existGlobal.BlindTrialSiteCode = lastTask.BlindTrialSiteCode;

                        subject.VisitTaskList.Add(existGlobal);
                    }



                    await _visitTaskCommonService.AddTaskAsync(new GenerateTaskCommand()
                    {
                        TrialId = filterObj.TrialId,

                        ReadingCategory = GenerateTaskCategory.SelfConsistent,


                        //产生的过滤掉已经生成的
                        GenerataConsistentTaskList = subject.VisitTaskList.Where(t => t.IsHaveGeneratedTask == false).ToList()
                    });

                    await _visitTaskRepository.SaveChangesAsync();

                }
            }

            return ResponseOutput.Ok();


        }


        /// <summary>
        /// 组间一致性分析  选择Subejct 列表
        /// </summary>
        /// <param name="inQuery"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<PageOutput<DoctorGroupConsistentSubjectView>> GetGroupConsistentRuleSubjectList(GroupConsistentQuery inQuery)
        {
            var trialId = inQuery.TrialId;

            var filterObj = await _taskConsistentRuleRepository.FirstOrDefaultAsync(t => t.TrialId == trialId && t.TrialReadingCriterionId==inQuery.TrialReadingCriterionId  &&  t.IsSelfAnalysis == false);


            if (filterObj == null)
            {
                return new PageOutput<DoctorGroupConsistentSubjectView>();
            }

            var query = await GetGroupConsistentQueryAsync(filterObj);


            var pagedList = await query.ToPagedListAsync(inQuery.PageIndex, inQuery.PageSize, string.IsNullOrWhiteSpace(inQuery.SortField) ? nameof(DoctorSelfConsistentSubjectView.SubjectCode) : inQuery.SortField, inQuery.Asc);

            return pagedList;
        }



        /// <summary>
        /// 确认生成组间一致性分析任务
        /// </summary>
        /// <param name="inCommand"></param>
        /// <param name="_visitTaskCommonService"></param>
        /// <returns></returns>
        [HttpPost]
        [UnitOfWork]
        [TypeFilter(typeof(TrialResourceFilter), Arguments = new object[] { "AfterStopCannNotOpt" })]

        public async Task<IResponseOutput> ConfirmGenerateGroupConsistentTask(GroupConsistentConfirmGenrateCommand inCommand, [FromServices] IVisitTaskHelpeService _visitTaskCommonService)
        {
            var trialId = inCommand.TrialId;

            var filterObj = await _taskConsistentRuleRepository.FirstOrDefaultAsync(t => t.TrialId == trialId && t.IsSelfAnalysis == false);

            var trialReadingCriterionId = filterObj.TrialReadingCriterionId;


            var query = await GetGroupConsistentQueryAsync(filterObj, inCommand.SubejctIdList);

            var subjectList = query.ToList();

            var doctorUserIdQuery = from enroll in _repository.Where<Enroll>(t => t.TrialId == trialId).Where(t => t.EnrollReadingCategoryList.Where(t=>t.TrialReadingCriterionId==trialReadingCriterionId).Any(c => c.ReadingCategory == ReadingCategory.Global || c.ReadingCategory == ReadingCategory.Visit))
                                    join user in _repository.Where<User>() on enroll.DoctorId equals user.DoctorId
                                    select user.Id;

            var configDoctorUserIdList = await doctorUserIdQuery.ToListAsync();

            using (await _mutex.LockAsync())
            {
                int maxCodeInt = 0;

                foreach (var subject in subjectList.Where(t => t.IsHaveGeneratedTask == false))
                {

                    //组间一致性分析 也用盲态SubjectCode
                    //处理 Subject 编号 

                    var blindSubjectCode = string.Empty;

                    var subjectTask = _visitTaskRepository.Where(t => t.SubjectId == subject.SubjectId && t.TrialReadingCriterionId == trialReadingCriterionId && t.IsSelfAnalysis==false).OrderByDescending(t => t.BlindSubjectCode).FirstOrDefault();
                    if (subjectTask != null && subjectTask.BlindSubjectCode != String.Empty)
                    {
                        blindSubjectCode = subjectTask.BlindSubjectCode;
                    }
                    else
                    {
                        var maxCodeStr = _visitTaskRepository.Where(t => t.TrialId == subject.TrialId && t.TrialReadingCriterionId == trialReadingCriterionId && t.IsSelfAnalysis == false).OrderByDescending(t => t.BlindSubjectCode).Select(t => t.BlindSubjectCode).FirstOrDefault();

                        if (!string.IsNullOrEmpty(maxCodeStr))
                        {
                            int.TryParse(maxCodeStr.Substring(maxCodeStr.Length - filterObj.BlindSubjectNumberOfPlaces), out maxCodeInt);

                        }

                        blindSubjectCode = filterObj.BlindTrialSiteCode + (maxCodeInt + 1).ToString($"D{filterObj.BlindSubjectNumberOfPlaces}");
                    }






                    var subjectAddTaskList = new List<VisitTaskGroupSimpleDTO>();


                    //需要处理的医生

                    var needAddDoctorUserIdList = configDoctorUserIdList.Except(subject.VisitTaskList.Select(t => (Guid)t.DoctorUserId)).ToList();

                    if (needAddDoctorUserIdList.Count == 0)
                    {
                        throw new BusinessValidationFailedException("请配置一致性分析的医生");
                    }


                    foreach (var needAddDoctorUserId in needAddDoctorUserIdList)
                    {

                        //每个医生 都生成处理的任务
                        foreach (var task in subject.SubjectTaskVisitList.Take(filterObj.PlanVisitCount))
                        {

                            subjectAddTaskList.Add(new VisitTaskGroupSimpleDTO()
                            {
                                ReadingCategory = task.ReadingCategory,
                                ReadingTaskState = task.ReadingTaskState,
                                TaskBlindName = task.TaskBlindName,
                                TaskName = task.TaskName,
                                TaskState = task.TaskState,
                                SubjectId = task.SubjectId,
                                VisitTaskNum = task.VisitTaskNum,
                                TrialId = task.TrialId,
                                DoctorUserId = needAddDoctorUserId,
                                ArmEnum = Arm.GroupConsistentArm,
                                SouceReadModuleId = task.SouceReadModuleId,
                                SourceSubjectVisitId = task.SourceSubjectVisitId,

                                TrialReadingCriterionId = task.TrialReadingCriterionId,

                                BlindSubjectCode=blindSubjectCode,
                                BlindTrialSiteCode=filterObj.BlindTrialSiteCode

                                
                            });

                        }

                        //最后一个检查批次添加全局

                        if (filterObj.IsGenerateGlobalTask)
                        {
                            var lastTask = (subjectAddTaskList.Take(filterObj.PlanVisitCount).Last()).Clone();


                            var existGlobal = _visitTaskRepository.Where(t => t.SubjectId == lastTask.SubjectId && t.TrialReadingCriterionId == trialReadingCriterionId && t.TaskState == TaskState.Effect && t.ReadingCategory == ReadingCategory.Global && t.VisitTaskNum == lastTask.VisitTaskNum + ReadingCommon.TaskNumDic[ReadingCategory.Global]).ProjectTo<VisitTaskGroupSimpleDTO>(_mapper.ConfigurationProvider).FirstOrDefault();


                            if (existGlobal == null)
                            {
                                existGlobal = new VisitTaskSimpleDTO()
                                {
                                    SubjectId = lastTask.SubjectId,
                                    TrialId = lastTask.TrialId,
                                    ReadingCategory = ReadingCategory.Global,
                                    TaskName = lastTask.TaskName + "_Global",
                                    TaskBlindName = lastTask.TaskBlindName + "_Global",

                                    TrialReadingCriterionId = trialReadingCriterionId,

                                    BlindSubjectCode = blindSubjectCode,
                                    BlindTrialSiteCode = filterObj.BlindTrialSiteCode

                                };
                            }


                            existGlobal.BlindSubjectCode = blindSubjectCode;
                            existGlobal.BlindTrialSiteCode = filterObj.BlindTrialSiteCode;
                            existGlobal.ArmEnum = Arm.GroupConsistentArm;
                            existGlobal.DoctorUserId = needAddDoctorUserId;

                            subjectAddTaskList.Add(existGlobal);
                        }

                    }


                    await _visitTaskCommonService.AddTaskAsync(new GenerateTaskCommand()
                    {
                        TrialId = filterObj.TrialId,

                        ReadingCategory = GenerateTaskCategory.GroupConsistent,


                        GenerataGroupConsistentTaskList = subjectAddTaskList
                    });


                    await _taskConsistentRuleRepository.SaveChangesAsync();
                }

            }



            return ResponseOutput.Ok();


        }




        /// <summary>
        /// 仅仅自身一致性时使用（
        /// </summary>
        /// <param name="filterObj"></param>
        /// <param name="doctorUserId"></param>
        /// <param name="subejctIdList"></param>
        /// <returns></returns>
        private IQueryable<DoctorSelfConsistentSubjectView> GetIQueryableDoctorSelfConsistentSubjectView(TaskConsistentRule filterObj, Guid doctorUserId, List<Guid>? subejctIdList = null)
        {
            var trialId = filterObj.TrialId;

            var trialReadingCriterionId = filterObj.TrialReadingCriterionId;

            #region Subejct 维度

            Expression<Func<VisitTask, bool>> comonTaskFilter = u => u.TrialId == trialId && u.IsAnalysisCreate == false && u.TaskState == TaskState.Effect && u.ReadingTaskState == ReadingTaskState.HaveSigned && u.TrialReadingCriterionId== trialReadingCriterionId &&
            u.SignTime!.Value.AddDays(filterObj.IntervalWeeks * 7) < DateTime.Now && (u.ReReadingApplyState == ReReadingApplyState.Default || u.ReReadingApplyState == ReReadingApplyState.Reject) && u.DoctorUserId == doctorUserId;




            if (subejctIdList != null && subejctIdList?.Count > 0)
            {
                comonTaskFilter = comonTaskFilter.And(t => subejctIdList.Contains(t.SubjectId));
            }


            Expression<Func<VisitTask, bool>> visitTaskFilter = comonTaskFilter.And(t => t.ReadingCategory == ReadingCategory.Visit);

            ////所选检查批次数量 的检查批次  其中必有一个检查批次后有全局任务
            //if (filterObj.IsHaveReadingPeriod == true)
            //{
            //    //这里的过滤条件  不能用 where(comonTaskFilter)  会报错，奇怪的问题   只能重新写一遍
            //    visitTaskFilter = visitTaskFilter.And(c => c.Subject.SubjectVisitTaskList.Any(t => t.VisitTaskNum == c.VisitTaskNum + ReadingCommon.TaskNumDic[ReadingCategory.Global] && t.ReadingCategory == ReadingCategory.Global && t.IsAnalysisCreate == false && t.TaskState == TaskState.Effect && t.ReadingTaskState == ReadingTaskState.HaveSigned &&
            //            t.SignTime!.Value.AddDays(filterObj.IntervalWeeks * 7) < DateTime.Now && (t.ReReadingApplyState == ReReadingApplyState.Default || t.ReReadingApplyState == ReReadingApplyState.Reject)));

            //}


            var subjectQuery = _subjectRepository.Where(t => t.TrialId == trialId &&
                 t.SubjectVisitTaskList.AsQueryable().Where(visitTaskFilter).Count() >= filterObj.PlanVisitCount)
                .WhereIf(filterObj.IsHaveReadingPeriod == true, u => u.SubjectVisitTaskList.AsQueryable().Where(comonTaskFilter).Where(t => t.ReadingCategory == ReadingCategory.Visit || t.ReadingCategory == ReadingCategory.Global).OrderBy(t => t.VisitTaskNum).Take(filterObj.PlanVisitCount + 1).Any(t => t.ReadingCategory == ReadingCategory.Global))
                ;



            var query = subjectQuery.Select(t => new DoctorSelfConsistentSubjectView()
            {
                TrialId = t.TrialId,
                SiteId = t.SiteId,
                SubjectCode = t.Code,
                TrialSiteCode = t.TrialSite.TrialSiteCode,
                SubjectId = t.Id,

                IsReReadingOrBackInfluenceAnalysis=t.IsReReadingOrBackInfluenceAnalysis,

                BlindSubjectCode = t.SubjectVisitTaskList.Where(t => t.IsAnalysisCreate && t.TrialReadingCriterionId == trialReadingCriterionId).OrderByDescending(t => t.BlindSubjectCode).Select(t => t.BlindSubjectCode).FirstOrDefault(),

                IsHaveGeneratedTask = t.SubjectVisitTaskList.Any(c => c.DoctorUserId == doctorUserId && c.IsSelfAnalysis == true && c.TrialReadingCriterionId==trialReadingCriterionId),


                ValidVisitCount = t.SubjectVisitTaskList.AsQueryable().Where(visitTaskFilter).Count(),

                VisitTaskList = t.SubjectVisitTaskList.AsQueryable().Where(visitTaskFilter).OrderBy(t => t.VisitTaskNum).Select(c => new VisitTaskSimpleDTO()
                {
                    Id = c.Id,
                    ReadingCategory = c.ReadingCategory,
                    ReadingTaskState = c.ReadingTaskState,
                    TaskBlindName = c.TaskBlindName,
                    TaskCode = c.TaskCode,
                    TaskName = c.TaskName,
                    TaskState = c.TaskState,
                    ArmEnum = c.ArmEnum,
                    SubjectId = c.SubjectId,
                    VisitTaskNum = c.VisitTaskNum,
                    TrialId = c.TrialId,
                    SourceSubjectVisitId = c.SourceSubjectVisitId,
                    SouceReadModuleId = c.SouceReadModuleId,



                    TrialReadingCriterionId=c.TrialReadingCriterionId,
                    IsClinicalDataSign = c.IsClinicalDataSign,
                    IsNeedClinicalDataSign = c.IsNeedClinicalDataSign,

                    //自身一致性才有意义
                    //IsHaveGeneratedTask = c.Subject.SubjectVisitTaskList.Any(t => t.ConsistentAnalysisOriginalTaskId == c.Id),

                    GlobalVisitTaskList = c.Subject.SubjectVisitTaskList.AsQueryable().Where(comonTaskFilter).Where(t => t.VisitTaskNum == c.VisitTaskNum + ReadingCommon.TaskNumDic[ReadingCategory.Global]).Select(c => new VisitTaskSimpleDTO()
                    {
                        Id = c.Id,
                        ReadingCategory = c.ReadingCategory,
                        ReadingTaskState = c.ReadingTaskState,
                        TaskBlindName = c.TaskBlindName,
                        TaskCode = c.TaskCode,
                        TaskName = c.TaskName,
                        TaskState = c.TaskState,
                        ArmEnum = c.ArmEnum,
                        SubjectId = c.SubjectId,
                        VisitTaskNum = c.VisitTaskNum,
                        TrialId = c.TrialId,
                        SourceSubjectVisitId = c.SourceSubjectVisitId,
                        SouceReadModuleId = c.SouceReadModuleId,

                        TrialReadingCriterionId = c.TrialReadingCriterionId,
                        IsClinicalDataSign = c.IsClinicalDataSign,
                        IsNeedClinicalDataSign = c.IsNeedClinicalDataSign,
                    }).ToList(),

                }).ToList()
            });

            return query.OrderByDescending(t => t.IsHaveGeneratedTask);

            #endregion
        }




        private async Task<IQueryable<DoctorGroupConsistentSubjectView>> GetGroupConsistentQueryAsync(TaskConsistentRule filterObj, List<Guid>? subejctIdList = null)
        {

            var trialId = filterObj.TrialId;
            var trialReadingCriterionId = filterObj.TrialReadingCriterionId;

            //var trialConfig = (await _repository.Where<Trial>(t => t.Id == trialId).Select(t => new { TrialId = t.Id, t.ReadingType, t.IsReadingTaskViewInOrder }).FirstOrDefaultAsync()).IfNullThrowException();



            Expression<Func<VisitTask, bool>> comonTaskFilter = u => u.TrialId == trialId && u.IsAnalysisCreate == false && u.TaskState == TaskState.Effect && u.ReadingTaskState == ReadingTaskState.HaveSigned && u.TrialReadingCriterionId == trialReadingCriterionId 
            && (u.ReReadingApplyState == ReReadingApplyState.Default || u.ReReadingApplyState == ReReadingApplyState.Reject);


            if (subejctIdList != null && subejctIdList?.Count > 0)
            {
                comonTaskFilter = comonTaskFilter.And(t => subejctIdList.Contains(t.SubjectId));
            }

            Expression<Func<VisitTask, bool>> visitTaskFilter = comonTaskFilter.And(t => t.ReadingCategory == ReadingCategory.Visit);


            ////所选检查批次数量 的检查批次  其中必有一个检查批次后有全局任务
            //if (filterObj.IsHaveReadingPeriod == true)
            //{
            //    //visitTaskFilter = visitTaskFilter.And(t => t.Subject.SubjectVisitTaskList.AsQueryable().Where(comonTaskFilter).Any(u => u.VisitTaskNum == t.VisitTaskNum + ReadingCommon.TaskNumDic[ReadingCategory.Global] && u.ReadingCategory == ReadingCategory.Global));

            //    //这里的过滤条件  不能用 where(comonTaskFilter)  会报错，奇怪的问题   只能重新写一遍
            //    visitTaskFilter = visitTaskFilter.And(c => c.Subject.SubjectVisitTaskList.Any(t => t.VisitTaskNum == c.VisitTaskNum + ReadingCommon.TaskNumDic[ReadingCategory.Global] && t.ReadingCategory == ReadingCategory.Global && t.IsAnalysisCreate == false && t.TaskState == TaskState.Effect && t.ReadingTaskState == ReadingTaskState.HaveSigned &&
            //            t.SignTime!.Value.AddDays(filterObj.IntervalWeeks * 7) < DateTime.Now && (t.ReReadingApplyState == ReReadingApplyState.Default || t.ReReadingApplyState == ReReadingApplyState.Reject)));

            //}


            IQueryable<Subject> subjectQuery = default;

            //单重阅片没有组件一致性

            subjectQuery = _subjectRepository.Where(t => t.TrialId == trialId &&
            t.SubjectVisitTaskList.AsQueryable().Where(comonTaskFilter).Where(t => t.ReadingCategory == ReadingCategory.Visit || t.ReadingCategory == ReadingCategory.Global).Select(t => t.DoctorUserId).Distinct().Count() == 2 &&
            t.SubjectVisitTaskList.AsQueryable().Where(visitTaskFilter).GroupBy(t => new { t.SubjectId, t.VisitTaskNum }).Where(g => g.Count() == 2).Count() >= filterObj.PlanVisitCount
            )
                 .WhereIf(filterObj.IsHaveReadingPeriod == true, u => u.SubjectVisitTaskList.AsQueryable().Where(comonTaskFilter).Where(t => t.ReadingCategory == ReadingCategory.Visit || t.ReadingCategory == ReadingCategory.Global).OrderBy(t => t.VisitTaskNum).Take(filterObj.PlanVisitCount * 2 + 2).Any(t => t.ReadingCategory == ReadingCategory.Global))

                ;



            var query = subjectQuery.Select(t => new DoctorGroupConsistentSubjectView()
            {
                TrialId = t.TrialId,
                SiteId = t.SiteId,
                SubjectCode = t.Code,
                TrialSiteCode = t.TrialSite.TrialSiteCode,
                SubjectId = t.Id,
                IsReReadingOrBackInfluenceAnalysis = t.IsReReadingOrBackInfluenceAnalysis,

                IsHaveGeneratedTask = t.SubjectVisitTaskList.Any(c => c.IsSelfAnalysis == false && c.TrialReadingCriterionId==trialReadingCriterionId),


                ValidVisitCount = t.SubjectVisitTaskList.AsQueryable().Where(visitTaskFilter).GroupBy(t => new { t.SubjectId, t.VisitTaskNum }).Where(g => g.Count() == 2).Count(),

                VisitTaskList = t.SubjectVisitTaskList.AsQueryable().Where(visitTaskFilter)
                .Select(c => new VisitTaskGroupSimpleDTO()
                {
                    ReadingCategory = c.ReadingCategory,
                    ReadingTaskState = c.ReadingTaskState,
                    TaskBlindName = c.TaskBlindName,
                    TaskName = c.TaskName,
                    TaskState = c.TaskState,
                    SubjectId = c.SubjectId,
                    VisitTaskNum = c.VisitTaskNum,
                    TrialId = c.TrialId,
                    DoctorUserId = c.DoctorUserId,

                    SourceSubjectVisitId = c.SourceSubjectVisitId,
                    SouceReadModuleId = c.SouceReadModuleId,

                    TrialReadingCriterionId = c.TrialReadingCriterionId,
                    IsClinicalDataSign = c.IsClinicalDataSign,
                    IsNeedClinicalDataSign = c.IsNeedClinicalDataSign,

                }).ToList()

                //
            });

            query = query.OrderByDescending(t => t.IsHaveGeneratedTask);

            return query;
        }




        [HttpPost]
        public async Task<TaskConsistentRuleBasic?> GetConsistentRule(TaskConsistentRuleQuery inQuery)
        {
            return await _taskConsistentRuleRepository.Where(t => t.TrialId == inQuery.TrialId && t.IsSelfAnalysis == inQuery.IsSelfAnalysis && t.TrialReadingCriterionId==inQuery.TrialReadingCriterionId).ProjectTo<TaskConsistentRuleBasic>(_mapper.ConfigurationProvider).FirstOrDefaultAsync();
        }

        /// <summary>
        /// 自身一致性分配 配置+  统计已经生成数量统计表
        /// </summary>
        /// <param name="inQuery"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<List<TaskConsistentRuleView>> GetSelfConsistentDoctorStatList(TaskConsistentRuleQuery inQuery)
        {
            var trialId = inQuery.TrialId;

            var taskConsistentRuleQueryable = from enroll in _repository.Where<Enroll>(t => t.TrialId == trialId && t.EnrollStatus==EnrollStatus.ConfirmIntoGroup)
                                              join user in _repository.Where<User>() on enroll.DoctorId equals user.DoctorId
                                              join taskConsistentRule in _repository.Where<TaskConsistentRule>(t => t.TrialId == trialId &&t.TrialReadingCriterionId==inQuery.TrialReadingCriterionId  && t.IsSelfAnalysis) on enroll.TrialId equals taskConsistentRule.TrialId
                                              select new TaskConsistentRuleView()
                                              {
                                                  Id = taskConsistentRule.Id,
                                                  CreateTime = taskConsistentRule.CreateTime,
                                                  BlindTrialSiteCode = taskConsistentRule.BlindTrialSiteCode,
                                                  BlindSubjectNumberOfPlaces = taskConsistentRule.BlindSubjectNumberOfPlaces,
                                                  CreateUserId = taskConsistentRule.CreateUserId,
                                                  IntervalWeeks = taskConsistentRule.IntervalWeeks,
                                                  IsEnable = taskConsistentRule.IsEnable,
                                                  PlanSubjectCount = taskConsistentRule.PlanSubjectCount,
                                                  Note = taskConsistentRule.Note,
                                                  TrialId = taskConsistentRule.TrialId,
                                                  UpdateTime = taskConsistentRule.UpdateTime,
                                                  UpdateUserId = taskConsistentRule.UpdateUserId,
                                                  IsGenerateGlobalTask = taskConsistentRule.IsGenerateGlobalTask,
                                                  IsHaveReadingPeriod = taskConsistentRule.IsHaveReadingPeriod,
                                                  PlanVisitCount = taskConsistentRule.PlanVisitCount,

                                                  GeneratedSubjectCount = taskConsistentRule.Trial.VisitTaskList.Where(t => t.IsAnalysisCreate && t.TrialReadingCriterionId == inQuery.TrialReadingCriterionId && t.IsSelfAnalysis == true && t.DoctorUserId == user.Id).Select(t => t.SubjectId).Distinct().Count(),

                                                  AnalysisDoctorUser = new UserSimpleInfo()
                                                  {
                                                      UserId = user.Id,
                                                      UserCode = user.UserCode,
                                                      FullName = user.FullName,
                                                      UserName = user.UserName
                                                  }
                                              };



            //if (await _taskConsistentRuleRepository.AnyAsync(t => t.TrialId == inQuery.TrialId))
            //{
            //    var rule = await _taskConsistentRuleRepository.Where(t => t.TrialId == inQuery.TrialId).ProjectTo<TaskConsistentRuleBatchAddOrEdit>(_mapper.ConfigurationProvider).FirstAsync();

            //    rule.IsBatchAdd = true;

            //    await BatchAddOrUpdateTaskConsistentRule(rule);
            //}

            //#endregion

            //var taskConsistentRuleQueryable = _taskConsistentRuleRepository.Where(t => t.TrialId == inQuery.TrialId)
            // .ProjectTo<TaskConsistentRuleView>(_mapper.ConfigurationProvider);

            return await taskConsistentRuleQueryable.ToListAsync();
        }




        [TypeFilter(typeof(TrialResourceFilter), Arguments = new object[] { "AfterStopCannNotOpt" })]

        public async Task<IResponseOutput> AddOrUpdateTaskConsistentRule(TaskConsistentRuleAddOrEdit addOrEditTaskConsistentRule)
        {

            var verifyExp1 = new EntityVerifyExp<TaskConsistentRule>()
            {
                VerifyExp = t => t.TrialId == addOrEditTaskConsistentRule.TrialId && t.IsSelfAnalysis == addOrEditTaskConsistentRule.IsSelfAnalysis && t.TrialReadingCriterionId==addOrEditTaskConsistentRule.TrialReadingCriterionId,
                VerifyMsg = "已有该项目配置，不允许继续增加"
            };

            if (await _visitTaskRepository.AnyAsync(t => t.IsSelfAnalysis == addOrEditTaskConsistentRule.IsSelfAnalysis && t.TrialId == addOrEditTaskConsistentRule.TrialId && t.TrialReadingCriterionId == addOrEditTaskConsistentRule.TrialReadingCriterionId))
            {
                return ResponseOutput.NotOk("该标准已有Subject 生成了任务，不允许修改配置");
            }

            var entity = await _taskConsistentRuleRepository.InsertOrUpdateAsync(addOrEditTaskConsistentRule, true, verifyExp1);

            return ResponseOutput.Ok(entity.Id.ToString());

        }

        [TypeFilter(typeof(TrialResourceFilter), Arguments = new object[] { "AfterStopCannNotOpt" })]

        [HttpDelete("{taskConsistentRuleId:guid}")]
        public async Task<IResponseOutput> DeleteTaskConsistentRule(Guid taskConsistentRuleId)
        {
            var config = await _taskConsistentRuleRepository.FirstOrDefaultAsync(t => t.Id == taskConsistentRuleId);


            if (await _visitTaskRepository.AnyAsync(t => t.IsAnalysisCreate && t.TrialId == config.TrialId && t.IsSelfAnalysis == config.IsSelfAnalysis && t.TrialReadingCriterionId==config.TrialReadingCriterionId))
            {
                throw new BusinessValidationFailedException("该标准已产生一致性分析任务，不允许删除");
            }



            var success = await _taskConsistentRuleRepository.DeleteFromQueryAsync(t => t.Id == taskConsistentRuleId, true);
            return ResponseOutput.Ok();
        }





    }
}
