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

using IRaCIS.Core.Application.Filter;
using IRaCIS.Core.Application.Interfaces;
using IRaCIS.Core.Application.ViewModel;
using IRaCIS.Core.Domain.Share;
using IRaCIS.Core.Infrastructure;
using Microsoft.AspNetCore.Mvc;

namespace IRaCIS.Core.Application.Service
{
    /// <summary>
    /// 任务医学审核
    /// </summary>	
    [ApiExplorerSettings(GroupName = "Trial")]
    public class TaskMedicalReviewService(IRepository<TaskMedicalReview> _taskMedicalReviewRepository,
        IRepository<TrialUserRole> _trialUserRoleRepository,
        IRepository<ReadingQuestionCriterionTrial> _readingQuestionCriterionTrialRepository,
        IRepository<VisitTask> _visitTaskRepository, IMapper _mapper, IUserInfo _userInfo, IStringLocalizer _localizer) : BaseService, ITaskMedicalReviewService
    {



        /// <summary>
        /// PM  医学审核（挑选任务生成后的列表）
        /// </summary>
        /// <param name="inQuery"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<PageOutput<TaskMedicalReviewView>> GetMedicalReviewTaskList(TaskMedicalReviewQuery inQuery)
        {

            var taskMedicalReviewQueryable = _taskMedicalReviewRepository.Where(t => t.VisitTask.TrialId == inQuery.TrialId)

                             .WhereIf(inQuery.TrialSiteId != null, t => t.VisitTask.Subject.TrialSiteId == inQuery.TrialSiteId)
                             .WhereIf(inQuery.SubjectId != null, t => t.VisitTask.SubjectId == inQuery.SubjectId)
                             .WhereIf(!string.IsNullOrEmpty(inQuery.SubjectCode), t => t.VisitTask.Subject.Code.Contains(inQuery.SubjectCode) || t.VisitTask.Subject.MedicalNo.Contains(inQuery.SubjectCode))
                             .WhereIf(!string.IsNullOrEmpty(inQuery.TaskName), t => t.VisitTask.TaskName.Contains(inQuery.TaskName) || t.VisitTask.TaskBlindName.Contains(inQuery.TaskName))
                             .WhereIf(inQuery.IsUrgent != null, t => t.VisitTask.IsUrgent == inQuery.IsUrgent)
                             .WhereIf(inQuery.DoctorUserId != null, t => t.VisitTask.DoctorUserId == inQuery.DoctorUserId)
                             .WhereIf(!string.IsNullOrEmpty(inQuery.TrialSiteCode), t => (t.VisitTask.BlindTrialSiteCode.Contains(inQuery.TrialSiteCode) && t.VisitTask.IsAnalysisCreate) || (t.VisitTask.Subject.TrialSite.TrialSiteCode.Contains(inQuery.TrialSiteCode) && t.VisitTask.IsAnalysisCreate == false))
                             .WhereIf(inQuery.ReadingCategory != null, t => t.VisitTask.ReadingCategory == inQuery.ReadingCategory)
                             .WhereIf(inQuery.TaskState != null, t => t.VisitTask.TaskState == inQuery.TaskState)
                             .WhereIf(inQuery.ArmEnum != null, t => t.VisitTask.ArmEnum == inQuery.ArmEnum)
                             .WhereIf(inQuery.AuditState != null, t => t.AuditState == inQuery.AuditState)
                             .WhereIf(inQuery.MedicalManagerUserId != null, t => t.MedicalManagerUserId == inQuery.MedicalManagerUserId)
                             .WhereIf(inQuery.BeginSignTime != null, t => t.VisitTask.SignTime > inQuery.BeginSignTime)
                             .WhereIf(inQuery.EndSignTime != null, t => t.VisitTask.SignTime < inQuery.EndSignTime)
                             .WhereIf(inQuery.AuditAdviceEnum != null, t => t.AuditAdviceEnum == inQuery.AuditAdviceEnum)

                             .WhereIf(inQuery.DoctorUserIdeaEnum != null, t => t.DoctorUserIdeaEnum == inQuery.DoctorUserIdeaEnum)
                             .WhereIf(inQuery.TrialReadingCriterionId != null, t => t.VisitTask.TrialReadingCriterionId == inQuery.TrialReadingCriterionId)
                             .WhereIf(inQuery.IsInvalid != null, t => t.IsInvalid == inQuery.IsInvalid)
                             .WhereIf(inQuery.IsHaveQuestion != null, t => t.IsHaveQuestion == inQuery.IsHaveQuestion)

                             .WhereIf(inQuery.BeginAllocateDate != null, t => t.AllocateTime >= inQuery.BeginAllocateDate)
                             .WhereIf(inQuery.EndAllocateDate != null, t => t.AllocateTime <= inQuery.EndAllocateDate)
                             .WhereIf(inQuery.BeginAuditSignTime != null, t => t.AuditSignTime >= inQuery.BeginAuditSignTime)
                              .WhereIf(inQuery.EndAuditSignTime != null, t => t.AuditSignTime <= inQuery.EndAuditSignTime)
                             .ProjectTo<TaskMedicalReviewView>(_mapper.ConfigurationProvider);

            var defalutSortArray = new string[] { nameof(TaskMedicalReviewView.AuditState), nameof(TaskMedicalReviewView.SubjectCode), nameof(TaskMedicalReviewView.ArmEnum), nameof(TaskMedicalReviewView.VisitTaskNum) };
            var pageList = await taskMedicalReviewQueryable.ToPagedListAsync(inQuery, defalutSortArray);

            return pageList;
        }


        /// <summary>
        ///  产生医学审核列表  
        /// </summary>
        /// <param name="inQuery"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<PageOutput<GenerateMedicalReviewTaskView>> GetGenerateMedicalReviewTaskList(GenerateMedicalReviewTaskQuery inQuery)
        {
            var visitTaskQueryable = _visitTaskRepository.Where(t => t.TrialId == inQuery.TrialId)
               .Where(t => t.IsAnalysisCreate == false && (t.TaskState == TaskState.Effect || t.TaskState == TaskState.Freeze) && t.ReadingTaskState == ReadingTaskState.HaveSigned)

              .WhereIf(inQuery.TrialSiteId != null, t => t.Subject.TrialSiteId == inQuery.TrialSiteId)
              .WhereIf(inQuery.SubjectId != null, t => t.SubjectId == inQuery.SubjectId)
              .WhereIf(inQuery.IsUrgent != null, t => t.IsUrgent == inQuery.IsUrgent)
              .WhereIf(inQuery.DoctorUserId != null, t => t.DoctorUserId == inQuery.DoctorUserId)
              .WhereIf(inQuery.ReadingCategory != null, t => t.ReadingCategory == inQuery.ReadingCategory)
              .WhereIf(inQuery.ReadingTaskState != null, t => t.ReadingTaskState == inQuery.ReadingTaskState)
              .WhereIf(inQuery.IsGeneratedJudge != null, t => t.JudgeVisitTaskId != null)
              .WhereIf(inQuery.IsGlobalHaveUpdate != null, t => t.IsGlobalHaveUpdate == inQuery.IsGlobalHaveUpdate)
              .WhereIf(inQuery.ArmEnum != null, t => t.ArmEnum == inQuery.ArmEnum)

               .WhereIf(inQuery.TrialReadingCriterionId != null, t => t.TrialReadingCriterionId == inQuery.TrialReadingCriterionId)
              .WhereIf(!string.IsNullOrEmpty(inQuery.TaskName), t => t.TaskName.Contains(inQuery.TaskName) || t.TaskBlindName.Contains(inQuery.TaskName))
              .WhereIf(!string.IsNullOrEmpty(inQuery.SubjectCode), t => t.Subject.Code.Contains(inQuery.SubjectCode))

                .WhereIf(inQuery.BeginSignTime != null, t => t.SignTime > inQuery.BeginSignTime)
               .WhereIf(inQuery.EndSignTime != null, t => t.SignTime < inQuery.EndSignTime)
              .ProjectTo<GenerateMedicalReviewTaskView>(_mapper.ConfigurationProvider);

            var defalutSortArray = new string[] { nameof(GenerateMedicalReviewTaskView.IsUrgent) + " desc", nameof(GenerateMedicalReviewTaskView.SubjectCode) };
            var pageList = await visitTaskQueryable.ToPagedListAsync(inQuery, defalutSortArray);


            return pageList;
        }

        /// <summary>
        /// 手动生成并分配医学审核
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        [TrialGlobalLimit( "AfterStopCannNotOpt" )]
        public async Task<IResponseOutput> ManuallyGeneratedAndAssignedMedicalReview(ManuallyGeneratedAndAssignedMedicalReviewCommand command)
        {

            foreach (var taskId in command.TaskIdList)
            {
                await _taskMedicalReviewRepository.AddAsync(new TaskMedicalReview() { TrialId = command.TrialId, VisitTaskId = taskId, MedicalManagerUserId = command.MedicalManagerUserId, AllocateTime = DateTime.Now });
            }

            await _taskMedicalReviewRepository.SaveChangesAsync();

            return ResponseOutput.Ok();
        }


        /// <summary>
        /// 获取下一个医学审核任务
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        /// <exception cref="BusinessValidationFailedException"></exception>
        [HttpPost]
        public async Task<TaskMedicalReviewView> GetNextMedicalReviewTask(GetNextMedicalReviewTaskInDto inDto)
        {
            var medicalReview = await _taskMedicalReviewRepository.Where(x => x.Id == inDto.MedicalReviewId).Include(x => x.VisitTask).FirstNotNullAsync();



            var data = (await GetMIMMedicalReviewTaskList(new TaskMedicalReviewQuery()
            {

                TrialId = medicalReview.TrialId,
                Id = inDto.MedicalReviewId,
                TrialReadingCriterionId = medicalReview.VisitTask.TrialReadingCriterionId,
                IsGetNextMedicalReviewTask = true,
                PageIndex = 1,
                PageSize = 99999,
            })).Data;


            if (data.CurrentPageData.Count > 0)
            {

                var index = data.CurrentPageData.ToList().FindIndex(x => x.Id == inDto.MedicalReviewId);

                var result = new TaskMedicalReviewView() { };

                if (index + 1 == data.CurrentPageData.Count()) // 最后一个
                {
                    throw new BusinessValidationFailedException(_localizer["MedicalReview_Finish"]);
                }
                else if (index == -1 || data.CurrentPageData.Count == 1) // 第一个或者只有一个
                {
                    if (data.CurrentPageData[0].Id == inDto.MedicalReviewId)
                    {
                        throw new BusinessValidationFailedException(_localizer["MedicalReview_Finish"]);
                    }
                    result = data.CurrentPageData[0];
                }
                else
                {
                    result = data.CurrentPageData.Skip(index + 1).Take(1).First();

                }
                return result;

            }
            else
            {
                throw new BusinessValidationFailedException(_localizer["MedicalReview_Finish"]);
            }

        }



        /// <summary>
        /// MIM  医学审核
        /// </summary>
        /// <param name="inQuery"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IResponseOutput<PageOutput<TaskMedicalReviewView>>> GetMIMMedicalReviewTaskList(TaskMedicalReviewQuery inQuery)
        {

            var taskMedicalReviewQueryable = _taskMedicalReviewRepository.Where(t => t.VisitTask.TrialId == inQuery.TrialId && t.MedicalManagerUserId == _userInfo.UserRoleId && t.VisitTask.TrialReadingCriterionId == inQuery.TrialReadingCriterionId)

                .WhereIf(inQuery.IsGetNextMedicalReviewTask,
                x => (
                !x.IsInvalid && x.AuditState == MedicalReviewAuditState.Auditing &
               (x.ReadingMedicalReviewDialogList.Count() != 0 &&
                x.ReadingMedicalReviewDialogList.Count() > 0 &&
                x.ReadingMedicalReviewDialogList.OrderByDescending(x => x.CreateTime).FirstOrDefault().UserTypeEnumInt == (int)UserTypeEnum.IndependentReviewer)
                )  // 审核中最新回复为IR的 
                || (!x.IsInvalid && x.AuditState == MedicalReviewAuditState.WaitAudit)
                || x.Id == inQuery.Id   // 这里必须找传入id 因为要找到这条的索引 获取下一条
                )
                .WhereIf(inQuery.SubjectId != null, t => t.VisitTask.SubjectId == inQuery.SubjectId)
                             .WhereIf(inQuery.TrialSiteId != null, t => t.VisitTask.Subject.TrialSiteId == inQuery.TrialSiteId)
                             .WhereIf(inQuery.IsUrgent != null, t => t.VisitTask.IsUrgent == inQuery.IsUrgent)
                             .WhereIf(inQuery.AuditState != null, t => t.AuditState == inQuery.AuditState)
                             .WhereIf(inQuery.DoctorUserIdeaEnum != null, t => t.DoctorUserIdeaEnum == inQuery.DoctorUserIdeaEnum)
                             .WhereIf(inQuery.TaskState != null, t => t.VisitTask.TaskState == inQuery.TaskState)
                             .WhereIf(!string.IsNullOrEmpty(inQuery.SubjectCode), t => t.VisitTask.Subject.Code.Contains(inQuery.SubjectCode) || t.VisitTask.Subject.MedicalNo.Contains(inQuery.SubjectCode))
                             .WhereIf(!string.IsNullOrEmpty(inQuery.TaskName), t => t.VisitTask.TaskName.Contains(inQuery.TaskName) || t.VisitTask.TaskBlindName.Contains(inQuery.TaskName))
                             .WhereIf(inQuery.DoctorUserId != null, t => t.VisitTask.DoctorUserId == inQuery.DoctorUserId)
                             .WhereIf(inQuery.ReadingCategory != null, t => t.VisitTask.ReadingCategory == inQuery.ReadingCategory)
                             .WhereIf(inQuery.ReadingTaskState != null, t => t.VisitTask.ReadingTaskState == inQuery.ReadingTaskState)
                             .WhereIf(inQuery.IsInvalid != null, t => t.IsInvalid == inQuery.IsInvalid)
                             .WhereIf(inQuery.IsGetBeRead, x => !x.IsInvalid && x.AuditState != MedicalReviewAuditState.HaveSigned)
                             .WhereIf(inQuery.TrialReadingCriterionId != null, t => t.VisitTask.TrialReadingCriterionId == inQuery.TrialReadingCriterionId)
                             .WhereIf(inQuery.BeginAuditSignTime != null, t => t.AuditSignTime >= inQuery.BeginAuditSignTime)
                             .WhereIf(inQuery.EndAuditSignTime != null, t => t.AuditSignTime <= inQuery.EndAuditSignTime)
                             .WhereIf(inQuery.BeginAllocateDate != null, t => t.AllocateTime >= inQuery.BeginAllocateDate)
                             .WhereIf(inQuery.EndAllocateDate != null, t => t.AllocateTime <= inQuery.EndAllocateDate)

                             .WhereIf(inQuery.ArmEnum != null, t => t.VisitTask.ArmEnum == inQuery.ArmEnum)
                             .WhereIf(inQuery.MedicalManagerUserId != null, t => t.MedicalManagerUserId == inQuery.MedicalManagerUserId)
                             .WhereIf(inQuery.BeginSignTime != null, t => t.VisitTask.SignTime > inQuery.BeginSignTime)
                             .WhereIf(inQuery.EndSignTime != null, t => t.VisitTask.SignTime < inQuery.EndSignTime)
                             .WhereIf(inQuery.AuditAdviceEnum != null, t => t.AuditAdviceEnum == inQuery.AuditAdviceEnum)
                             .WhereIf(inQuery.IsHaveQuestion != null, t => t.IsHaveQuestion == inQuery.IsHaveQuestion)
                             .ProjectTo<TaskMedicalReviewView>(_mapper.ConfigurationProvider);


            var defalutSortArray = new string[] { nameof(TaskMedicalReviewView.SubjectCode), nameof(TaskMedicalReviewView.ArmEnum), nameof(TaskMedicalReviewView.VisitTaskNum) };
            var pageList = await taskMedicalReviewQueryable.ToPagedListAsync(inQuery, defalutSortArray);

            return ResponseOutput.Ok(pageList, new
            {

                IsConfirmMedicineQuestion = await _readingQuestionCriterionTrialRepository.Where(x => x.Id == inQuery.TrialReadingCriterionId).Select(x => x.IsConfirmMedicineQuestion).FirstOrDefaultAsync()
            });
        }


        /// <summary>
        /// 设置医学审核失效
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IResponseOutput> SetMedicalReviewInvalid(SetMedicalReviewInvalidCommand command)
        {

            if (await _taskMedicalReviewRepository.Where(t => command.MedicalReviewIdList.Contains(t.Id)).AnyAsync(t => t.AuditState == MedicalReviewAuditState.HaveSigned))
            {
                //"已签名的不允许设置为失效"
                return ResponseOutput.NotOk(_localizer["TaskMedical_DirtyData"]);
            }

            await _taskMedicalReviewRepository.UpdatePartialFromQueryAsync(t => command.MedicalReviewIdList.Contains(t.Id), c => new TaskMedicalReview() { IsInvalid = true }, true);

            return ResponseOutput.Ok();

        }





        /// <summary>
        ///   123 分别是  分配，重新分配，取消分配
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        [UnitOfWork]
        [HttpPost]
        [TrialGlobalLimit( "AfterStopCannNotOpt" )]

        public async Task<IResponseOutput> AssignMedicalReviewTask(AssignMedicalReviewTaskCommand command)
        {

            foreach (var id in command.IdList)
            {
                var task = await _taskMedicalReviewRepository.FirstOrDefaultAsync(t => t.Id == id);

                if (command.TaskOptType == MedicalReviewTaskOptType.Assign)
                {
                    if (task.MedicalManagerUserId != null && task.MedicalManagerUserId != command.MedicalManagerUserId)
                    {
                        //"当前有任务已分配给其他人，不允许分配,请刷新列表"
                        throw new BusinessValidationFailedException(_localizer["TaskMedical_SubjectInOtherArm"]);
                    }

                    task.MedicalManagerUserId = command.MedicalManagerUserId;
                    task.AllocateTime = DateTime.Now;

                }
                else if (command.TaskOptType == MedicalReviewTaskOptType.ReAssign)
                {
                    task.MedicalManagerUserId = command.MedicalManagerUserId;
                    task.AllocateTime = DateTime.Now;
                }

                else if (command.TaskOptType == MedicalReviewTaskOptType.CancelAssign)
                {
                    task.MedicalManagerUserId = null;
                    task.AllocateTime = null;
                }
            }



            await _taskMedicalReviewRepository.SaveChangesAsync();

            return ResponseOutput.Ok();
        }


        /// <summary>
        /// 获取医学经理列表
        /// </summary>
        /// <returns></returns>
        [HttpGet("{trialId:guid}")]
        public async Task<List<UserSimpleInfo>> GetMIMUserList(Guid trialId)
        {
            var query = _trialUserRoleRepository.Where(t => (t.UserRole.UserTypeEnum == Domain.Share.UserTypeEnum.MIM || t.UserRole.UserTypeEnum == Domain.Share.UserTypeEnum.MC) && t.TrialId == trialId).Select(t => t.UserRole).ProjectTo<UserSimpleInfo>(_mapper.ConfigurationProvider);

            return await query.ToListAsync();
        }

    }
}
