using IRaCIS.Core.Application.Service.Reading.Dto;
using IRaCIS.Core.Application.ViewModel;
using IRaCIS.Core.Infra.EFCore.Common;
using MassTransit;
using Microsoft.AspNetCore.Mvc;

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


        private List<SiteVisitForTumor> siteVisitForTumorList = new List<SiteVisitForTumor>();

        /// <summary>
        /// 阅片导入
        /// </summary>
        /// <returns></returns>
        public async Task ReadingImport()
        {
        }

        /// <summary>
        /// 获取阅片的计算数据
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        public async Task<object> GetReadingCalculationData(GetReadingCalculationDataInDto inDto)
        {
            return new
            {
            };
        }

        #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 globalanswerList = await _readingGlobalTaskInfoRepository.Where(x => visitTaskIds.Contains(x.TaskId) && x.GlobalVisitTask.TaskState == TaskState.Effect && x.Answer != string.Empty).Select(x => new Globalanswer()
            {
                TaskId = x.TaskId,
                VisitTaskNum = x.GlobalVisitTask.VisitTaskNum,
                QuestionId = x.QuestionId,
                Answer = x.Answer
            }).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,
            };

            // 第一级

            List<ReadingReportDto> questions = await _generalCalculateService.GetReadingReportQuestion
       (
        questionList,
        taskInfoList,
       globalanswerList,
        answers,
        tableAnsweRowInfos,
         tableQuestionList,
         alltableAnsweRowInfos,
         tableAnswers,
        organInfos,
         needChangeType
       );



            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 trialReadingCriterion = await _readingQuestionCriterionTrialRepository.Where(x => x.Id == taskinfo.TrialReadingCriterionId).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();

            List<ReadingTableAnswerRowInfo> addRowList = new List<ReadingTableAnswerRowInfo>();
            List<ReadingTableQuestionAnswer> addTableQuestionAnswerList = new List<ReadingTableQuestionAnswer>();

            if (!(await _readingTableQuestionAnswerRepository.AnyAsync(x => x.VisitTaskId == visitTaskId)))
            {  
                // 添加 是否预设
                var tableQuestionList = await _readingTableQuestionTrialRepository.Where(x => x.ReadingQuestionTrial.ReadingQuestionCriterionTrialId == taskinfo.TrialReadingCriterionId && x.IsPreinstall).Include(x => x.ReadingQuestionTrial).ToListAsync();
                // 是否有预设
                if (tableQuestionList.Count() > 0)
                {

                    foreach (var tableQuestion in tableQuestionList)
                    {
                        var thisTableQuestionList = await _readingTableQuestionTrialRepository.Where(x => x.ReadingQuestionId == tableQuestion.ReadingQuestionId).ToListAsync();

                        decimal index = 1;

                        foreach (var item in tableQuestion.TypeValue.Split('|'))
                        {
                            var newRowId = NewId.NextGuid();
                            addRowList.Add(new ReadingTableAnswerRowInfo()
                            {
                                Id = newRowId,
                                QuestionId = tableQuestion.ReadingQuestionId,
                                VisitTaskId = taskinfo.Id,
                                TrialId = taskinfo.TrialId,
                                RowIndex = index,
                                IsCurrentTaskAdd = true,
                                BlindName = taskinfo.TaskBlindName,
                                OrderMark = tableQuestion.ReadingQuestionTrial.OrderMark,
                                FristAddTaskId = taskinfo.Id,
                                RowMark = tableQuestion.ReadingQuestionTrial.OrderMark + decimal.Parse(index.ToString()).GetLesionMark()

                            });

                            foreach (var thisTableQuestion in thisTableQuestionList)
                            {
                                addTableQuestionAnswerList.Add(new ReadingTableQuestionAnswer()
                                {
                                    Answer = thisTableQuestion.Id == tableQuestion.Id ? item : string.Empty,
                                    QuestionId = tableQuestion.ReadingQuestionId,
                                    TrialId = taskinfo.TrialId,
                                    VisitTaskId = taskinfo.Id,
                                    RowId = newRowId,
                                    RowIndex = index,
                                    TableQuestionId = thisTableQuestion.Id,
                                });
                            }
                            index++;
                        }

                    }
                }

                if (taskinfo.SourceSubjectVisitId != baseLineVisitId && isReadingTaskViewInOrder == ReadingOrder.InOrder)
                {

                    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.ReadingTableQuestionTrial.IsCopy).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.ReadingTableQuestionTrialList.Any(x=>x.IsCopy)).ProjectTo<CopyTableAnswerRowInfo>(_mapper.ConfigurationProvider).ToListAsync();

                    tableRowAnswers.ForEach(x =>
                    {

                        var rowinfo = addRowList.Where(y => y.QuestionId == x.QuestionId && y.RowIndex == x.RowIndex).FirstOrDefault();

                        x.VisitTaskId = visitTaskId;
                        x.IsCurrentTaskAdd = false;
                        x.Id = rowinfo == null ? NewId.NextGuid() : rowinfo.Id;
                        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).FirstOrDefault()?.Id;
                        x.MergeRowId = tableRowAnswers.Where(y => y.OriginalId == x.MergeRowId).FirstOrDefault()?.Id;

                    });

                    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);


                    addRowList.AddRange(addList);
                    addTableQuestionAnswerList.AddRange(tableAnswers);

                    addRowList = addRowList.GroupBy(x => new { x.Id }).Select(x => x.ToList().FirstOrDefault()).ToList();
                    addTableQuestionAnswerList = addTableQuestionAnswerList.GroupBy(x =>
                    new
                    {
                        x.RowId,
                        x.TableQuestionId,
                    }).Select(x => new ReadingTableQuestionAnswer()
                    {
                        Id = NewId.NextGuid(),
                        Answer = x.Select(y => y.Answer).Max() ?? string.Empty,
                        QuestionId = x.Select(y => y.QuestionId).Max(),
                        RowIndex = x.Select(y => y.RowIndex).Max(),
                        RowId = x.Key.RowId,
                        TableQuestionId = x.Key.TableQuestionId,
                        TrialId = x.Select(y => y.TrialId).Max(),
                        VisitTaskId = visitTaskId,
                    }).ToList();

                }
            }

            // 自定义的复制
            await _generalCalculateService.CopyHistoryAnswer(taskinfo, addRowList, addTableQuestionAnswerList);

            await _readingTableAnswerRowInfoRepository.AddRangeAsync(addRowList);
            await _readingTableQuestionAnswerRepository.AddRangeAsync(addTableQuestionAnswerList);
            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)
        {

        }
    }
}
