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

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 IRaCIS.Core.Application.Filter;

namespace IRaCIS.Core.Application.Service
{
    /// <summary>
    /// 任务医学审核
    /// </summary>	
    [ApiExplorerSettings(GroupName = "Trial")]
    public class TaskMedicalReviewService : BaseService, ITaskMedicalReviewService
    {

        private readonly IRepository<TaskMedicalReview> _taskMedicalReviewRepository;
        private readonly IRepository<Trial> _trialRepository;
        private readonly IRepository<TrialUser> _trialUserRepository;
        private readonly IRepository<ReadingQuestionCriterionTrial> _readingQuestionCriterionTrialRepository;
        private readonly IRepository<VisitTask> _visitTaskRepository;
        private readonly IRepository<TaskMedicalReviewRule> _taskMedicalReviewRuleRepository;

        public TaskMedicalReviewService(IRepository<TaskMedicalReview> taskMedicalReviewRepository,
               IRepository<Trial> trialRepository,
            IRepository<TrialUser> trialUserRepository,
              IRepository<ReadingQuestionCriterionTrial> readingQuestionCriterionTrialRepository,
            IRepository<VisitTask> visitTaskRepository,
            IRepository<TaskMedicalReviewRule> taskMedicalReviewRuleRepository)
        {
            _taskMedicalReviewRepository = taskMedicalReviewRepository;
            this._trialRepository = trialRepository;
            _trialUserRepository = trialUserRepository;
            this._readingQuestionCriterionTrialRepository = readingQuestionCriterionTrialRepository;
            _visitTaskRepository = visitTaskRepository;
            _taskMedicalReviewRuleRepository = taskMedicalReviewRuleRepository;

        }

        /// <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.SiteId != null, t => t.VisitTask.Subject.SiteId == inQuery.SiteId)
                             .WhereIf(inQuery.SubjectId != null, t => t.VisitTask.SubjectId == inQuery.SubjectId)
                             .WhereIf(!string.IsNullOrEmpty(inQuery.SubjectCode), t => t.VisitTask.Subject.Code.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.AuditState != null, t => t.AuditState == inQuery.AuditState)

                               .WhereIf(inQuery.TrialReadingCriterionId != null, t => t.VisitTask.TrialReadingCriterionId == inQuery.TrialReadingCriterionId)
                             .ProjectTo<TaskMedicalReviewView>(_mapper.ConfigurationProvider);

            var pageList = await taskMedicalReviewQueryable.ToPagedListAsync(inQuery.PageIndex, inQuery.PageSize, string.IsNullOrWhiteSpace(inQuery.SortField) ? nameof(TaskMedicalReviewView.Id) : inQuery.SortField, inQuery.Asc);

            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.SiteId != null, t => t.Subject.SiteId == inQuery.SiteId)
              .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.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))

              .ProjectTo<GenerateMedicalReviewTaskView>(_mapper.ConfigurationProvider);

            var defalutSortArray = new string[] { nameof(TaskMedicalReviewView.IsUrgent) + " desc", nameof(TaskMedicalReviewView.SubjectId) };
            var pageList = await visitTaskQueryable.ToPagedListAsync(inQuery.PageIndex, inQuery.PageSize, inQuery.SortField, inQuery.Asc, string.IsNullOrWhiteSpace(inQuery.SortField), defalutSortArray);


            return pageList;
        }

        /// <summary>
        /// 手动生成并分配医学审核
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        [TypeFilter(typeof(TrialResourceFilter), Arguments = new object[] { "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 subjectReview = (await GetMIMMedicalReviewTaskList(new TaskMedicalReviewQuery()
            {

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

            if (subjectReview.CurrentPageData.Count == 1)
            {
                return subjectReview.CurrentPageData[0];
            }

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

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

            if (data.CurrentPageData.Count == 1)
            {
                return data.CurrentPageData[0];
            }
            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.Id&&t.VisitTask.TrialReadingCriterionId==inQuery.TrialReadingCriterionId)
                  .WhereIf(inQuery.SubjectId != null, t => t.VisitTask.SubjectId == inQuery.SubjectId)
                             .WhereIf(inQuery.SiteId != null, t => t.VisitTask.Subject.SiteId == inQuery.SiteId)
                             .WhereIf(!string.IsNullOrEmpty(inQuery.SubjectCode), t => t.VisitTask.Subject.Code.Contains(inQuery.SubjectCode))
                                  .WhereIf(inQuery.Id != null, t => t.Id != inQuery.Id)
                             .WhereIf(inQuery.IsUrgent != null, t => t.VisitTask.IsUrgent == inQuery.IsUrgent)
                              .WhereIf(inQuery.AuditState != null, t => t.AuditState == inQuery.AuditState)
                               .WhereIf(inQuery.TaskState != null, t => t.VisitTask.TaskState == inQuery.TaskState)
                             .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.IsGetBeRead,x=>!x.IsInvalid&&x.AuditState!= MedicalReviewAuditState.HaveSigned)
                              .WhereIf(inQuery.TrialReadingCriterionId != null, t => t.VisitTask.TrialReadingCriterionId == inQuery.TrialReadingCriterionId)
                             .ProjectTo<TaskMedicalReviewView>(_mapper.ConfigurationProvider);

            var pageList = await taskMedicalReviewQueryable.ToPagedListAsync(inQuery.PageIndex, inQuery.PageSize, string.IsNullOrWhiteSpace(inQuery.SortField) ? nameof(TaskMedicalReviewView.Id) : inQuery.SortField, inQuery.Asc);

            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]
        [TypeFilter(typeof(TrialResourceFilter), Arguments = new object[] { "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 = _trialUserRepository.Where(t => t.User.UserTypeEnum == Domain.Share.UserTypeEnum.MIM && t.TrialId == trialId).Select(t => t.User).ProjectTo<UserSimpleInfo>(_mapper.ConfigurationProvider);

            return await query.ToListAsync();
        }

    }
}
