using IRaCIS.Core.Application.Service.Reading.Dto;
using IRaCIS.Core.Domain.Share;
using Microsoft.AspNetCore.Mvc;
using IRaCIS.Core.Domain.Models;
using Microsoft.AspNetCore.Mvc;
using IRaCIS.Core.Application.Interfaces;
using IRaCIS.Core.Application.ViewModel;
using Panda.DynamicWebApi.Attributes;
using IRaCIS.Core.Infra.EFCore.Common;
using Microsoft.Extensions.Caching.Memory;

using IRaCIS.Core.Infrastructure;
using MassTransit;

namespace IRaCIS.Core.Application.Service.ReadingCalculate
{
    [ApiExplorerSettings(GroupName = "Reading")]
    public class SelfDefineCalculateService : BaseService, ICriterionCalculateService
    {
        private readonly IRepository<ReadingTableQuestionAnswer> _readingTableQuestionAnswerRepository;
        private readonly IRepository<VisitTask> _visitTaskRepository;
        private readonly IRepository<ReadingQuestionCriterionTrial> _readingQuestionCriterionTrialRepository;
        private readonly IRepository<ReadingTableQuestionTrial> _readingTableQuestionTrialRepository;
        private readonly IRepository<ReadingTableAnswerRowInfo> _readingTableAnswerRowInfoRepository;
        private readonly IRepository<ReadingQuestionTrial> _readingQuestionTrialRepository;
        private readonly IRepository<SubjectVisit> _subjectVisitRepository;
        private readonly IRepository<OrganInfo> _organInfoRepository;
        private readonly IRepository<DicomStudy> _dicomStudyRepository;
        private readonly IRepository<NoneDicomStudy> _noneDicomStudyRepository;
        private readonly IRepository<TumorAssessment_RECIST1Point1> _tumorAssessmentRepository;
        private readonly IGeneralCalculateService _generalCalculateService;
        private readonly IRepository<ReadingTaskQuestionAnswer> _readingTaskQuestionAnswerRepository;

        public SelfDefineCalculateService(
            IRepository<ReadingTableQuestionAnswer> readingTableQuestionAnswerRepository,
            IRepository<VisitTask> visitTaskRepository,
            IRepository<ReadingQuestionCriterionTrial> readingQuestionCriterionTrialRepository,
            IRepository<ReadingTableQuestionTrial> readingTableQuestionTrialRepository,
            IRepository<ReadingTableAnswerRowInfo> readingTableAnswerRowInfoRepository,
            IRepository<ReadingQuestionTrial> readingQuestionTrialRepository,
            IRepository<SubjectVisit> subjectVisitRepository,
              IRepository<OrganInfo> organInfoRepository,
            IRepository<DicomStudy> dicomStudyRepository,
            IRepository<NoneDicomStudy> noneDicomStudyRepository,
            IRepository<TumorAssessment_RECIST1Point1> tumorAssessmentRepository,
            IGeneralCalculateService generalCalculateService,
            IRepository<ReadingTaskQuestionAnswer> readingTaskQuestionAnswerRepository
            )
        {
            this._readingTableQuestionAnswerRepository = readingTableQuestionAnswerRepository;
            this._visitTaskRepository = visitTaskRepository;
            this._readingQuestionCriterionTrialRepository = readingQuestionCriterionTrialRepository;
            this._readingTableQuestionTrialRepository = readingTableQuestionTrialRepository;
            this._readingTableAnswerRowInfoRepository = readingTableAnswerRowInfoRepository;
            this._readingQuestionTrialRepository = readingQuestionTrialRepository;
            this._subjectVisitRepository = subjectVisitRepository;
            this._organInfoRepository = organInfoRepository;
            this._dicomStudyRepository = dicomStudyRepository;
            this._noneDicomStudyRepository = noneDicomStudyRepository;
            this._tumorAssessmentRepository = tumorAssessmentRepository;
            this._generalCalculateService = generalCalculateService;
            this._readingTaskQuestionAnswerRepository = readingTaskQuestionAnswerRepository;
        }

        private List<SiteVisitForTumor> siteVisitForTumorList = null;


        #region 删除病灶获取起始病灶序号
        /// <summary>
        /// 删除病灶获取起始病灶序号
        /// </summary>
        /// <returns></returns>
        public async Task<int> GetDeleteLesionStatrIndex(DeleteReadingRowAnswerInDto inDto)
        {
            return 1;


        }
        #endregion

        #region 获取阅片报告
        /// <summary>
        /// 获取阅片报告
        /// </summary>
        /// <param name="indto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<GetReadingReportEvaluationOutDto> GetReadingReportEvaluation(GetReadingReportEvaluationInDto indto)
        {
            GetReadingReportEvaluationOutDto result = new GetReadingReportEvaluationOutDto();

            result.CalculateResult = await this.GetReportVerify(new GetReportVerifyInDto()
            {
                VisitTaskId = indto.VisitTaskId
            });

            var visitTaskInfo = await _visitTaskRepository.Where(x => x.Id == indto.VisitTaskId).FirstNotNullAsync();


            result.ReadingTaskState = visitTaskInfo.ReadingTaskState;
            var taskInfoList = await _generalCalculateService.GetReadingReportTaskList(indto.VisitTaskId);

            result.VisitTaskList = taskInfoList;

            var visitTaskIds = taskInfoList.Select(x => x.VisitTaskId).ToList();

            var criterionId = visitTaskInfo.TrialReadingCriterionId;
            var questionList = await _readingQuestionTrialRepository.Where(x => x.ReadingQuestionCriterionTrialId == criterionId && x.ShowQuestion != ShowQuestion.Hide).ToListAsync();
            var tableQuestionList = await _readingTableQuestionTrialRepository.Where(x => x.TrialCriterionId == criterionId).OrderBy(x => x.ShowOrder).ToListAsync();

            var lesionsIndexs = await _readingTableAnswerRowInfoRepository.Where(x => visitTaskIds.Contains(x.VisitTaskId)).GroupBy(x => new { x.QuestionId }).Select(x => new lesionsIndexDto()
            {
                QuestionId = x.Key.QuestionId,
                Rowindexs = x.Select(x => x.RowIndex).Distinct().OrderBy(x => x).ToList()

            }).ToListAsync();

            var tableAnsweRowInfos = await _readingTableAnswerRowInfoRepository.Where(x => x.VisitTaskId == indto.VisitTaskId).ProjectTo<TableAnsweRowInfo>(_mapper.ConfigurationProvider).ToListAsync();

            var answers = await _readingTaskQuestionAnswerRepository.Where(x => visitTaskIds.Contains(x.VisitTaskId)).ToListAsync();
            var tableAnswers = await _readingTableQuestionAnswerRepository.Where(x => visitTaskIds.Contains(x.VisitTaskId)).ToListAsync();

            var alltableAnsweRowInfos = await _readingTableAnswerRowInfoRepository.Where(x => visitTaskIds.Contains(x.VisitTaskId)).ToListAsync();
            var organIds = alltableAnsweRowInfos.Where(x => x.OrganInfoId != null).Select(x => x.OrganInfoId).Distinct().ToList();
            var organInfos = await _organInfoRepository.Where(x => organIds.Contains(x.Id)).ToListAsync();

            var needChangeType = new List<QuestionMark?>() {
                QuestionMark.Organ,
                QuestionMark.Location,
                QuestionMark.Part,
            };

            // 第一级

            #region 构造问题
            List<ReadingReportDto> questions = questionList.Where(x => x.Type == ReadingQestionType.Group).OrderBy(x => x.ShowOrder).Select(x => new ReadingReportDto()
            {
                QuestionId = x.Id,
                GroupName = x.GroupName,
                IsShowInDicom = x.IsShowInDicom,
                Type = x.Type,
                GroupId=x.GroupId,
                GroupEnName=x.GroupEnName,
                QuestionType = x.QuestionType,
                DataSource=   x.DataSource,
                LesionType = x.LesionType,
                QuestionGenre = x.QuestionGenre,
                DictionaryCode = x.DictionaryCode,
                LimitEdit=  x.LimitEdit,
                MaxAnswerLength=x.MaxAnswerLength,
                FileType=x.FileType,
                TypeValue = x.TypeValue,
                QuestionName = x.QuestionName.LanguageName(x.QuestionEnName, _userInfo.IsEn_Us),
                ShowOrder = x.ShowOrder,
                ValueType = x.ValueType,
                Unit = x.Unit,
                CustomUnit=x.CustomUnit,
                ReportLayType = ReportLayType.Group,
            }).ToList();

            // 分组
            foreach (var item in questions)
            {
                item.Childrens = questionList.Where(x => x.GroupId==item.QuestionId).OrderBy(x => x.ShowOrder).Select(x => new ReadingReportDto()
                {
                    GroupName = x.GroupName,
                    QuestionId = x.Id,
                    IsShowInDicom = x.IsShowInDicom,
                    QuestionName = x.QuestionName.LanguageName(x.QuestionEnName, _userInfo.IsEn_Us),
                    LesionType = x.LesionType,
                    DataSource = x.DataSource,
                    QuestionGenre = x.QuestionGenre,
                    GroupEnName=x.GroupEnName,
                    LimitEdit = x.LimitEdit,
                    MaxAnswerLength=x.MaxAnswerLength,
                    FileType=x.FileType,
                    DictionaryCode = x.DictionaryCode,
                    Type = x.Type,
                    QuestionType = x.QuestionType,
                    TypeValue = x.TypeValue,
                    ShowOrder = x.ShowOrder,
                    OrderMark = x.OrderMark,
                    ValueType = x.ValueType,
                    Unit = x.Unit,
                    CustomUnit=x.CustomUnit,
                    ReportLayType = ReportLayType.Question,
                }).ToList();

                // 问题
                foreach (var question in item.Childrens)
                {

                    foreach (var task in taskInfoList)
                    {

                        var answer = answers.Where(x => x.VisitTaskId == task.VisitTaskId && x.ReadingQuestionTrialId == question.QuestionId).FirstOrDefault();
                        question.Answer.Add(new TaskQuestionAnswer()
                        {
                            Answer = answer == null ? string.Empty : answer.Answer,
                            IsGlobalChange = answer == null ? false : answer.IsGlobalChange,
                            GlobalChangeAnswer = answer == null ? string.Empty : answer.GlobalChangeAnswer,
                            TaskName = task.TaskName,
                            VisitTaskId = task.VisitTaskId,

                        });
                    }

                    // 构造表格行数据


                    var rowlist = tableAnsweRowInfos.Where(x => x.QuestionId == question.QuestionId).OrderBy(x => x.RowIndex).ToList();

                    question.Childrens = new List<ReadingReportDto>();

                    var rowoindexs = lesionsIndexs.Where(x => x.QuestionId == question.QuestionId).Select(x => x.Rowindexs.OrderBy(y => y).ToList()).FirstOrDefault();
                    rowoindexs = rowoindexs == null ? new List<decimal>() : rowoindexs;
                    foreach (var rowoindex in rowoindexs)
                    {
                        var rowinfo = rowlist.Where(x => x.RowIndex == rowoindex).FirstOrDefault();
                        question.Childrens.Add(new ReadingReportDto()
                        {
                            QuestionName = question.OrderMark + rowoindex.GetLesionMark(),
                            RowId = rowinfo?.Id,
                            IsShowInDicom = question.IsShowInDicom,
                            SplitOrMergeLesionName = rowinfo!=null? (rowinfo.MergeName.IsNullOrEmpty() ? rowinfo.SplitName : rowinfo.MergeName):string.Empty,
                            SplitOrMergeType = rowinfo != null ? (rowinfo.SplitOrMergeType):null,
                            LesionType = question.LesionType,
                            IsCanEditPosition = rowinfo != null ? (rowinfo.IsCanEditPosition):false,
                            RowIndex = rowoindex,
                            BlindName = rowinfo != null ? rowinfo.BlindName : string.Empty,
                            ReportLayType = ReportLayType.Lesions,
                        });
                    }

                  


                    foreach (var row in question.Childrens)
                    {
                        // tableQuestion
                        row.Childrens = tableQuestionList.Where(x => x.ReadingQuestionId == question.QuestionId).Select(x => new ReadingReportDto()
                        {
                            QuestionName = x.QuestionName.LanguageName(x.QuestionEnName, _userInfo.IsEn_Us),
                            QuestionId = x.ReadingQuestionId,
                            TableQuestionId = x.Id,
                            Type = x.Type,
                            IsShowInDicom = question.IsShowInDicom,
                            DataSource = x.DataSource,
                            LimitEdit = x.LimitEdit,
                            MaxAnswerLength=x.MaxAnswerLength,
                            FileType=x.FileType,
                            LesionType = question.LesionType,
                            TableQuestionType = x.TableQuestionType,
                            DictionaryCode = x.DictionaryCode,
                            QuestionMark = x.QuestionMark,
                            TypeValue = x.TypeValue,
                            RowIndex = row.RowIndex,
                            RowId=row.RowId,
                            ShowOrder = x.ShowOrder,
                            ValueType = x.ValueType,
                            CustomUnit=x.CustomUnit,
                            Unit = x.Unit,
                            ReportLayType = ReportLayType.TableQuestion,
                        }).ToList();


                        foreach (var tableQuestion in row.Childrens)
                        {
                            foreach (var task in taskInfoList)
                            {
                                var rowinfo = alltableAnsweRowInfos.Where(x => x.VisitTaskId == task.VisitTaskId && x.QuestionId == tableQuestion.QuestionId && x.RowIndex == tableQuestion.RowIndex).FirstOrDefault();
                                var taskQuestionAnswer = new TaskQuestionAnswer()
                                {
                                    Answer = tableAnswers.Where(x => x.VisitTaskId == task.VisitTaskId && x.QuestionId == tableQuestion.QuestionId && x.RowIndex == tableQuestion.RowIndex && x.TableQuestionId == tableQuestion.TableQuestionId).Select(x => x.Answer).FirstIsNullReturnEmpty(),
                                    TaskName = task.TaskName,
                                    VisitTaskId = task.VisitTaskId,
                                };
                                if (rowinfo != null && rowinfo.OrganInfoId != null)
                                {
                                    var organInfo = organInfos.Where(x => x.Id == rowinfo.OrganInfoId).FirstOrDefault();


                                    if (organInfo != null && needChangeType.Contains(tableQuestion.QuestionMark))
                                    {
                                        if (_userInfo.IsEn_Us)
                                        {
                                            switch (tableQuestion.QuestionMark)
                                            {
                                                case QuestionMark.Organ:
                                                    taskQuestionAnswer.Answer = organInfo.TULOCEN;

                                                    break;
                                                case QuestionMark.Location:
                                                    if (organInfo.IsCanEditPosition)
                                                    {

                                                    }
                                                    else
                                                    {
                                                        taskQuestionAnswer.Answer = organInfo.TULATEN;

                                                    }
                                                    break;
                                                case QuestionMark.Part:

                                                    taskQuestionAnswer.Answer = organInfo.PartEN;

                                                    break;

                                            }

                                        }
                                        else
                                        {
                                            switch (tableQuestion.QuestionMark)
                                            {
                                                case QuestionMark.Organ:
                                                    taskQuestionAnswer.Answer = organInfo.TULOC;
                                                    break;
                                                case QuestionMark.Location:
                                                    if (organInfo.IsCanEditPosition)
                                                    {

                                                    }
                                                    else
                                                    {
                                                        taskQuestionAnswer.Answer = organInfo.TULAT;

                                                    }
                                                    break;
                                                case QuestionMark.Part:
                                                    taskQuestionAnswer.Answer = organInfo.Part;
                                                    break;

                                            }
                                        }

                                    }
                                }
                                tableQuestion.Answer.Add(taskQuestionAnswer);
                            }
                        }


                    }


                };
            }
            #endregion



            result.TaskQuestions = questions;



            return result;


        }
        #endregion

        /// <summary>
        /// 将上一次的访视病灶添加到这一次
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        public async Task<AddTaskLesionAnswerFromLastTaskOutDto> AddTaskLesionAnswerFromLastTask(AddTaskLesionAnswerFromLastTaskInDto inDto)
        {
            var visitTaskId = inDto.VisitTaskId;
            var taskinfo = await _visitTaskRepository.Where(x => x.Id == visitTaskId).FirstNotNullAsync();
            var isReadingTaskViewInOrder =await _readingQuestionCriterionTrialRepository.Where(x => x.Id == taskinfo.TrialReadingCriterionId).Select(x => x.IsReadingTaskViewInOrder).FirstOrDefaultAsync();
            var baseLineVisitId = await _subjectVisitRepository.Where(x => x.SubjectId == taskinfo.SubjectId && x.IsBaseLine).Select(x => x.Id).FirstOrDefaultAsync();

            // 判断当前任务是否是基线
            if (taskinfo.SourceSubjectVisitId != baseLineVisitId&& isReadingTaskViewInOrder)
            {
                // 判断当前任务是是否有表格问题答案
                if (!(await _readingTableQuestionAnswerRepository.AnyAsync(x => x.VisitTaskId == visitTaskId)))
                {

                    var LastVisitTaskId = await _visitTaskRepository.Where(x => x.ReadingCategory == ReadingCategory.Visit &&
                    x.TrialReadingCriterionId == taskinfo.TrialReadingCriterionId &&
                    x.IsAnalysisCreate == taskinfo.IsAnalysisCreate &&
                     //x.DoctorUserId == taskinfo.DoctorUserId &&
                     x.IsSelfAnalysis == taskinfo.IsSelfAnalysis &&
                    x.SubjectId == taskinfo.SubjectId && x.ReadingTaskState == ReadingTaskState.HaveSigned && x.VisitTaskNum < taskinfo.VisitTaskNum && x.TaskState == TaskState.Effect && x.ArmEnum == taskinfo.ArmEnum
                    ).OrderByDescending(x => x.VisitTaskNum).Select(x => x.Id).FirstOrDefaultAsync();



                    var copyTableAnswers = await _readingTableQuestionAnswerRepository.Where(x => x.VisitTaskId == LastVisitTaskId&&x.ReadingQuestionTrial.IsCopyLesions).Select(x => new CopyTableAnswerDto()
                    {
                        Answer = x.Answer,
                        QuestionId = x.QuestionId,
                        RowId = x.RowId,
                        QuestionMark = x.ReadingTableQuestionTrial.QuestionMark,
                        TableQuestionId = x.TableQuestionId,
                        RowIndex = x.RowIndex,
                        IsCopy=x.ReadingTableQuestionTrial.IsCopy,
                        TrialId = x.TrialId,
                    }).ToListAsync();

                    var tableRowAnswers = await _readingTableAnswerRowInfoRepository.Where(x => x.VisitTaskId == LastVisitTaskId&&x.ReadingQuestionTrial.IsCopyLesions).ProjectTo<CopyTableAnswerRowInfo>(_mapper.ConfigurationProvider).ToListAsync();


                    tableRowAnswers.ForEach(x =>
                    {
                        x.VisitTaskId = visitTaskId;
                        x.IsCurrentTaskAdd = false;
                        x.Id = NewId.NextGuid();
                        x.SeriesId = null;
                        x.InstanceId = null;
                        x.MeasureData = string.Empty;
                        x.PicturePath = string.Empty;
                    });

                    tableRowAnswers.ForEach(x =>
                    {
                        x.SplitRowId = tableRowAnswers.Where(y => y.OriginalId == x.SplitRowId).Select(y => y.Id).FirstOrDefault();
                        x.MergeRowId = tableRowAnswers.Where(y => y.OriginalId == x.MergeRowId).Select(y => y.Id).FirstOrDefault();

                    });

                  

                    var tableAnswers = copyTableAnswers.Select(x => new ReadingTableQuestionAnswer
                    {
                        Id = NewId.NextGuid(),
                        Answer = x.IsCopy ? x.Answer:string.Empty ,
                        QuestionId = x.QuestionId,
                        RowIndex = x.RowIndex,
                        RowId = tableRowAnswers.Where(y => y.OriginalId == x.RowId).Select(x => x.Id).FirstOrDefault(),
                        TableQuestionId = x.TableQuestionId,
                        TrialId = x.TrialId,
                        VisitTaskId = visitTaskId,
                    });



                    var addList = _mapper.Map<List<ReadingTableAnswerRowInfo>>(tableRowAnswers);

                    await _readingTableAnswerRowInfoRepository.AddRangeAsync(addList);
                    await _readingTableQuestionAnswerRepository.AddRangeAsync(tableAnswers);
                    await _readingTableQuestionAnswerRepository.SaveChangesAsync();

                }
            }

            return new AddTaskLesionAnswerFromLastTaskOutDto()
            {

                IsBaseLine = taskinfo.SourceSubjectVisitId == baseLineVisitId,
            };

        }

        /// <summary>
        /// 测试计算
        /// </summary>
        /// <param name="visitTaskId"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task TestCalculate(Guid visitTaskId, QuestionType type)
        {
            ReadingCalculateDto readingData = await _generalCalculateService.GetReadingCalculateDto(visitTaskId);
            await ReadingCalculate(readingData, new List<QuestionType>() { type });
        }

        /// <summary>
        /// 计算任务
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task CalculateTask(CalculateTaskInDto inDto)
        {
            ReadingCalculateDto readingData = await _generalCalculateService.GetReadingCalculateDto(inDto.VisitTaskId);
            readingData.IsChangeOtherTask = inDto.IsChangeOtherTask;
            await ReadingCalculate(readingData);
        }


        /// <summary>
        /// 自动计算
        /// </summary>
        /// <param name="inDto"></param>
        /// <param name="calculateType"></param>
        /// <returns></returns>
        public async Task ReadingCalculate(ReadingCalculateDto inDto, List<QuestionType> calculateType = null)
        {
            //var questionList = await _readingQuestionTrialRepository.Where(x => x.ReadingQuestionCriterionTrialId == inDto.CriterionId && x.CustomCalculateMark != null).ToListAsync();
            //var tableQuestionList = await _readingTableQuestionTrialRepository.Where(x => x.TrialCriterionId == inDto.CriterionId && x.CustomCalculateMark != null).ToListAsync();


          


        }


   

     


        public async Task<GetReportVerifyOutDto> GetReportVerify(GetReportVerifyInDto inDto)
        {
            return new GetReportVerifyOutDto() { 
            
            };
        }

        public async Task VerifyVisitTaskQuestions(VerifyVisitTaskQuestionsInDto inDto)
        {
           
        }
    }
}
