//--------------------------------------------------------------------
//     此代码由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;

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

        private readonly IRepository<TaskMedicalReview> _taskMedicalReviewRepository;

        private readonly IRepository<TrialUser> _trialUserRepository;

        private readonly IRepository<TaskMedicalReviewRule> _taskMedicalReviewRuleRepository;

        public TaskMedicalReviewService(IRepository<TaskMedicalReview> taskMedicalReviewRepository, IRepository<TrialUser> trialUserRepository, IRepository<TaskMedicalReviewRule> taskMedicalReviewRuleRepository)
        {
            _taskMedicalReviewRepository = taskMedicalReviewRepository;

            _trialUserRepository = trialUserRepository;

            _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(!string.IsNullOrEmpty(inQuery.SubjectCode), t => t.VisitTask.Subject.Code.Contains(inQuery.SubjectCode))
                             .WhereIf(inQuery.IsUrgent != null, t => t.VisitTask.IsUrgent == inQuery.IsUrgent)
                             .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)
                             .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>
        /// <returns></returns>
        public async Task<IResponseOutput> GenerateMedicalReviewTask(GenerateMedicalReviewTaskCommand generateCommand)
        {
            var trialId = generateCommand.TrialId;

            var mimUserList = await _trialUserRepository.Where(t => t.User.UserTypeEnum == Domain.Share.UserTypeEnum.MIM && t.TrialId == trialId).Select(t => t.User).ProjectTo<UserSimpleInfo>(_mapper.ConfigurationProvider).ToListAsync();

            //if (mimUserList.Count == 0)
            //{
            //    return ResponseOutput.NotOk("没有MIM");
            //}

            var defalutMIMUserId = mimUserList.FirstOrDefault()?.UserId;

            //获取当前医生数据  已经生成的，和配置的数量
            var taskTaskMedicalReviewRuleList = await _taskMedicalReviewRuleRepository.Where(t => t.TrialId == trialId).ProjectTo<TaskMedicalReviewRuleView>(_mapper.ConfigurationProvider).ToListAsync();

            foreach (var item in taskTaskMedicalReviewRuleList)
            {

                if (item.IsEnable)
                {

                    if (item.PlanGlobalCount > item.GeneratedGlobalCount)
                    {
                        var needGenerateCount = item.PlanGlobalCount - item.GeneratedGlobalCount;

                        var canGenerateCount = item.ActualGlobalCount - item.GeneratedGlobalCount;

                        var toGenerateCount = canGenerateCount > needGenerateCount ? needGenerateCount : canGenerateCount;

                        //分配给MIM  

                        if (toGenerateCount > 0)
                        {
                            var toGenerateTaskList = item.ActualGlobalTaskList.Except(item.GeneratedGlobalTaskList).Take(toGenerateCount).ToList();

                            foreach (var toGenerateTask in toGenerateTaskList)
                            {
                                await _taskMedicalReviewRepository.AddAsync(new TaskMedicalReview() { DoctorUserId = (Guid)toGenerateTask.DoctorUserId, TrialId = toGenerateTask.TrialId, VisitTaskId = toGenerateTask.TaskId ,MedicalManagerUserId= defalutMIMUserId });
                            }
                        }


                    }
                    if (item.PlanJudgeCount > item.GeneratedJudgeCount)
                    {
                        var needGenerateCount = item.PlanJudgeCount - item.GeneratedJudgeCount;

                        var canGenerateCount = item.ActualJudgeCount - item.GeneratedGlobalCount;

                        var toGenerateCount = canGenerateCount > needGenerateCount ? needGenerateCount : canGenerateCount;

                        if (toGenerateCount > 0)
                        {
                            var toGenerateTaskList = item.ActualJudgeTaskList.Except(item.GeneratedJudgeTaskList).Take(toGenerateCount).ToList();

                            foreach (var toGenerateTask in toGenerateTaskList)
                            {
                                await _taskMedicalReviewRepository.AddAsync(new TaskMedicalReview() { DoctorUserId = (Guid)toGenerateTask.DoctorUserId, TrialId = toGenerateTask.TrialId, VisitTaskId = toGenerateTask.TaskId, MedicalManagerUserId = defalutMIMUserId });
                            }
                        }

                    }
                    if (item.PlanTumorCount > item.GeneratedTumorCount)
                    {
                        var needGenerateCount = item.PlanTumorCount - item.GeneratedTumorCount;

                        var canGenerateCount = item.ActualTumorCount - item.GeneratedGlobalCount;

                        var toGenerateCount = canGenerateCount > needGenerateCount ? needGenerateCount : canGenerateCount;

                        if (toGenerateCount > 0)
                        {
                            var toGenerateTaskList = item.ActualTumorTaskList.Except(item.GeneratedTumorTaskList).Take(toGenerateCount).ToList();

                            foreach (var toGenerateTask in toGenerateTaskList)
                            {
                                await _taskMedicalReviewRepository.AddAsync(new TaskMedicalReview() { DoctorUserId = (Guid)toGenerateTask.DoctorUserId, TrialId = toGenerateTask.TrialId, VisitTaskId = toGenerateTask.TaskId, MedicalManagerUserId = defalutMIMUserId });
                            }
                        }

                    }
                    if (item.PlanVisitCount > item.GeneratedVisitCount)
                    {
                        var needGenerateCount = item.PlanVisitCount - item.GeneratedVisitCount;

                        var canGenerateCount = item.ActualVisitCount - item.GeneratedGlobalCount;

                        var toGenerateCount = canGenerateCount > needGenerateCount ? needGenerateCount : canGenerateCount;

                        if (toGenerateCount > 0)
                        {

                            var toGenerateTaskList = item.ActualVisitTaskList.Except(item.GeneratedVisitTaskList).Take(toGenerateCount).ToList();

                            foreach (var toGenerateTask in toGenerateTaskList)
                            {
                                await _taskMedicalReviewRepository.AddAsync(new TaskMedicalReview() { DoctorUserId = (Guid)toGenerateTask.DoctorUserId, TrialId = toGenerateTask.TrialId, VisitTaskId = toGenerateTask.TaskId, MedicalManagerUserId = defalutMIMUserId });
                            }
                        }

                    }

                }

            }


            await _taskMedicalReviewRepository.SaveChangesAsync();
            return ResponseOutput.Ok();

        }


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

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

                             .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.IsUrgent != null, t => t.VisitTask.IsUrgent == inQuery.IsUrgent)
                             .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)
                             .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>
        ///   123 分别是  分配，重新分配，取消分配
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        public async Task<IResponseOutput> AssignMedicalReviewTask(AssignMedicalReviewTaskCommand command)
        {

            var task = await _taskMedicalReviewRepository.FirstOrDefaultAsync(t => t.Id == command.Id);

            if (command.TaskOptType == MedicalReviewTaskOptType.Assign || 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();
        }

    }
}
