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

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

namespace IRaCIS.Core.Application.Service
{
    /// <summary>
    /// 医学审核生成规则   废弃
    /// </summary>	
    [ApiExplorerSettings(GroupName = "Trial")]
    public class TaskMedicalReviewRuleService : BaseService, ITaskMedicalReviewRuleService
    {

        private readonly IRepository<TaskMedicalReviewRule> _taskMedicalReviewRuleRepository;
        private readonly IRepository<TaskMedicalReview> _taskMedicalReviewRepository;
        public TaskMedicalReviewRuleService(IRepository<TaskMedicalReviewRule> taskMedicalReviewRuleRepository,IRepository<TaskMedicalReview> taskMedicalReviewRepository)
        {
            _taskMedicalReviewRuleRepository = taskMedicalReviewRuleRepository;
            _taskMedicalReviewRepository = taskMedicalReviewRepository;
        }


        [HttpPost]
        public async Task<(List<TaskMedicalReviewRuleView>,object)> GetTaskMedicalReviewRuleList(TaskMedicalReviewRuleQuery inQuery)
        {


            var taskTaskMedicalReviewRuleQueryable = _taskMedicalReviewRuleRepository.Where(t => t.TrialId == inQuery.TrialId)
            .ProjectTo<TaskMedicalReviewRuleView>(_mapper.ConfigurationProvider);

            var isHaveMIM = await _repository.AnyAsync<TrialUser>(t => t.User.UserTypeEnum == Domain.Share.UserTypeEnum.MIM && t.TrialId==inQuery.TrialId);

            return (await taskTaskMedicalReviewRuleQueryable.ToListAsync(),new {IsHaveMIM=isHaveMIM});
        }

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

        public async Task<IResponseOutput> AddOrUpdateTaskMedicalReviewRule(TaskMedicalReviewRuleAddOrEdit addOrEditTaskTaskMedicalReviewRule)
        {
            var verifyExp1 = new EntityVerifyExp<TaskMedicalReviewRule>()
            {
                VerifyExp = t => t.DoctorUserId == addOrEditTaskTaskMedicalReviewRule.DoctorUserId && t.TrialId == addOrEditTaskTaskMedicalReviewRule.TrialId,
                VerifyMsg = "已有该医生配置，不允许继续增加"
            };

            var entity = await _taskMedicalReviewRuleRepository.InsertOrUpdateAsync(addOrEditTaskTaskMedicalReviewRule, true, verifyExp1);

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

        }


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

        public async Task<IResponseOutput> DeleteTaskMedicalReviewRule(Guid taskMedicalReviewRuleId)
        {

            if(await _taskMedicalReviewRuleRepository.Where(t=>t.Id== taskMedicalReviewRuleId).AnyAsync(t => t.TaskMedicalReviewList.Any()))
            {
                return ResponseOutput.NotOk("已产生医学审核任务");
            }

            var success = await _taskMedicalReviewRuleRepository.DeleteFromQueryAsync(t => t.Id == taskMedicalReviewRuleId,true);

            return ResponseOutput.Ok();
        }

        /// <summary>
        /// 产生医学审核
        /// </summary>
        /// <returns></returns>
        [Obsolete]
        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();



            Guid? defalutMIMUserId = null /*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.ExceptBy(item.GeneratedGlobalTaskList.Select(t => t.TaskId), t => t.TaskId).Take(toGenerateCount).ToList();

                            foreach (var toGenerateTask in toGenerateTaskList)
                            {
                                await _taskMedicalReviewRepository.AddAsync(new TaskMedicalReview() { DoctorUserId = toGenerateTask.DoctorUserId!.Value, 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.ExceptBy(item.GeneratedJudgeTaskList.Select(t => t.TaskId), t => t.TaskId).Take(toGenerateCount).ToList();

                            foreach (var toGenerateTask in toGenerateTaskList)
                            {
                                await _taskMedicalReviewRepository.AddAsync(new TaskMedicalReview() { DoctorUserId = toGenerateTask.DoctorUserId!.Value, 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.ExceptBy(item.GeneratedTumorTaskList.Select(t => t.TaskId), t => t.TaskId).Take(toGenerateCount).ToList();

                            foreach (var toGenerateTask in toGenerateTaskList)
                            {
                                await _taskMedicalReviewRepository.AddAsync(new TaskMedicalReview() { DoctorUserId = toGenerateTask.DoctorUserId!.Value, 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.ExceptBy(item.GeneratedVisitTaskList.Select(t => t.TaskId), t => t.TaskId).Take(toGenerateCount).ToList();

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

                    }

                }

            }


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

        }


    }
}
