using IRaCIS.Core.Domain.Share;
using IRaCIS.Core.Infrastructure;
using Microsoft.AspNetCore.Mvc;

using IRaCIS.Core.Application.Service.Reading.Dto;
using IRaCIS.Core.Application.ViewModel;

namespace IRaCIS.Core.Application.Service.ReadingCalculate
{
    [ApiExplorerSettings(GroupName = "Image")]
    public class ReadingCalculateService : BaseService, IReadingCalculateService
    {

        /// <summary>
        /// 标准和服务对应
        /// </summary>
        Dictionary<CriterionType, Type> CalculateServiceDic = new Dictionary<CriterionType, Type>()
        {
            {CriterionType.RECIST1Point1,typeof(RECIST1Point1CalculateService) }, //RECIST1.1
            {CriterionType.PCWG3,typeof(PCWG3CalculateService) },
            {CriterionType.SelfDefine,typeof(SelfDefineCalculateService) },
            {CriterionType.RECIST1Pointt1_MB,typeof(RECIST1Point1_BMCalculateService) },
            {CriterionType.IRECIST1Point1,typeof(IRECIST1Point1CalculateService) }
        };



        private readonly IEnumerable<ICriterionCalculateService> _criterionServices;
        private readonly IRepository<VisitTask> _visitTaskRepository;
        private readonly IRepository<ReadingQuestionCriterionTrial> _readingQuestionCriterionTrialRepository;
        private ICriterionCalculateService _useCriterion;


        public ReadingCalculateService(IEnumerable<ICriterionCalculateService> criterionServices,
                IRepository<VisitTask> visitTaskRepository,
                  IRepository<ReadingQuestionCriterionTrial> readingQuestionCriterionTrialRepository

            )
        {

            _criterionServices = criterionServices;
            this._visitTaskRepository = visitTaskRepository;
            this._readingQuestionCriterionTrialRepository = readingQuestionCriterionTrialRepository;
        }

        /// <summary>
        /// 获取Service
        /// </summary>
        /// <param name="visitTaskId"></param>
        /// <returns></returns>
        public async Task<ICriterionCalculateService> GetService(Guid visitTaskId)
        {
            if (_useCriterion == null)
            {
                var criterionId = await _visitTaskRepository.Where(x => x.Id == visitTaskId).Select(x => x.TrialReadingCriterionId).FirstNotNullAsync();

                var criterionType = await _readingQuestionCriterionTrialRepository.Where(x => x.Id == criterionId).Select(x => x.CriterionType).FirstOrDefaultAsync();

                if (criterionType == null)
                {
                    throw new BusinessValidationFailedException(_localizer["ReadingCalculate_NoDeveloped"]);
                }

                try
                {
                    CriterionType thisCriterionType = criterionType;
                    Type thisServiceType = CalculateServiceDic[thisCriterionType];
                    _useCriterion = _criterionServices.FirstOrDefault(x => x.GetType().Name == thisServiceType.Name + "Proxy");



                }
                catch (Exception)
                {

                    _useCriterion = null;
                }

                return _useCriterion;


            }
            else
            {
                return _useCriterion;
            }
        }

        /// <summary>
        /// 自动计算 并修改值
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        public async Task CalculateTask(CalculateTaskInDto inDto)
        {

            var service = await this.GetService(inDto.VisitTaskId);
            if (service != null)
            {
                await service.CalculateTask(inDto);
            }

        }

        /// <summary>
        /// 验证访视提交
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        public async Task VerifyVisitTaskQuestions(VerifyVisitTaskQuestionsInDto inDto)
        {
            var service = await this.GetService(inDto.VisitTaskId);
            if (service != null)
            {
                await service.VerifyVisitTaskQuestions(inDto);
            }

        }

        /// <summary>
        /// 将上一次的访视病灶添加到这一次
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        public async Task<AddTaskLesionAnswerFromLastTaskOutDto> AddTaskLesionAnswerFromLastTask(AddTaskLesionAnswerFromLastTaskInDto inDto)
        {
            var service = await this.GetService(inDto.VisitTaskId);
            var visitTaskInfo = await _visitTaskRepository.Where(x => x.Id == inDto.VisitTaskId).FirstNotNullAsync();
            if (service != null && visitTaskInfo.SourceSubjectVisitId != null)
            {
                var readingTaskState = visitTaskInfo.ReadingTaskState;
                var result = new AddTaskLesionAnswerFromLastTaskOutDto();

                if (readingTaskState == ReadingTaskState.WaitReading)
                {
                    result = await service.AddTaskLesionAnswerFromLastTask(inDto);
                    await service.CalculateTask(new CalculateTaskInDto()
                    {
                        IsChangeOtherTask = false,
                        VisitTaskId = inDto.VisitTaskId,
                    });

                    await _visitTaskRepository.BatchUpdateNoTrackingAsync(x => x.Id == inDto.VisitTaskId, x => new VisitTask()
                    {
                        ReadingTaskState = ReadingTaskState.Reading,

                    });

                }

                return result;
            }
            else
            {
                return new AddTaskLesionAnswerFromLastTaskOutDto();
            }

        }

        /// <summary>
        /// 获取报告验证的信息(这里每个标准可能不一样 返回用object)
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        public async Task<GetReportVerifyOutDto> GetReportVerify(GetReportVerifyInDto inDto)
        {

            var service = await this.GetService(inDto.VisitTaskId);

            if (service != null)
            {
                return await service.GetReportVerify(inDto);
            }
            else
            {
                return new GetReportVerifyOutDto() { };
            }

        }

        /// <summary>
        /// 获取阅片报告
        /// </summary>
        /// <param name="indto"></param>
        /// <returns></returns>
        public async Task<GetReadingReportEvaluationOutDto> GetReadingReportEvaluation(GetReadingReportEvaluationInDto inDto)
        {
            var service = await this.GetService(inDto.VisitTaskId);

            if (service != null)
            {

                var taskInfo = await _visitTaskRepository.Where(x => x.Id == inDto.VisitTaskId).FirstNotNullAsync();
                if (taskInfo.ReadingTaskState != ReadingTaskState.HaveSigned && inDto.IsCalculate)
                {
                    await service.CalculateTask(new CalculateTaskInDto()
                    {

                        VisitTaskId = inDto.VisitTaskId
                    });
                }

                var result = await service.GetReadingReportEvaluation(inDto);


                // 这里统一处理字典

                Dictionary<Guid,List<CrterionDictionaryGroup>> dictionaryGroup = result.VisitTaskList.ToDictionary(x => x.VisitTaskId, x => x.CrterionDictionaryGroup);

                result.TaskQuestions.ForEach(y =>
                {
                    SetCrterionDictionaryGroup(y, dictionaryGroup);
                });


                return result;
            }
            else
            {
                return new GetReadingReportEvaluationOutDto();
            }
        }


        public void SetCrterionDictionaryGroup(ReadingReportDto item, Dictionary<Guid, List<CrterionDictionaryGroup>> dictionaryGroup)
        {
            item.Answer.ForEach(z =>
            {
                try
                {
                    z.CrterionDictionaryGroup = dictionaryGroup[z.VisitTaskId];
                }
                catch (Exception)
                {


                }
            });

            item.Childrens.ForEach(x => {

                SetCrterionDictionaryGroup(x, dictionaryGroup);
            });
        }

           


        /// <summary>
        /// 删除病灶获取起始病灶序号
        /// </summary>
        /// <returns></returns>
        public async Task<int> GetDeleteLesionStatrIndex(DeleteReadingRowAnswerInDto inDto)
        {
            var service = await this.GetService(inDto.VisitTaskId);

            if (service != null)
            {
                return await service.GetDeleteLesionStatrIndex(inDto);
            }
            else
            {
                return 1;
            }
        }
    }


   
}
