using IRaCIS.Core.Domain.Share;
using Microsoft.AspNetCore.Mvc;
using IRaCIS.Core.Application.Service.Reading.Dto;
using IRaCIS.Core.Infra.EFCore.Common;
using Panda.DynamicWebApi.Attributes;
using IRaCIS.Core.Application.Contracts;
using MassTransit;
using IRaCIS.Core.Application.Filter;

namespace IRaCIS.Application.Services
{

    /// <summary>
    /// 非Dicom
    /// </summary>
    public partial class ReadingImageTaskService : BaseService, IReadingImageTaskService
    {
        /// <summary>
        /// 提交检查批次阅片问题
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        [NonDynamicMethod]
        public async Task<IResponseOutput> SubmitVisitTaskQuestions(SubmitVisitTaskQuestionsInDto inDto)
        {
            await VerifyTaskIsSign(inDto.VisitTaskId);
            await this.SaveVisitTaskQuestions(inDto);


            await this.SubmitTaskChangeState(inDto.VisitTaskId);
            return ResponseOutput.Ok(true);
        }


        /// <summary>
        /// 保存任务问题
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        [HttpPost]
        [TypeFilter(typeof(TrialResourceFilter), Arguments = new object[] { "AfterStopCannNotOpt" })]
        public async Task<IResponseOutput> SaveVisitTaskQuestions(SubmitVisitTaskQuestionsInDto inDto)
        {
            await VerifyTaskIsSign(inDto.VisitTaskId);
            var subjectId = await _visitTaskRepository.Where(x => x.Id == inDto.VisitTaskId).Select(x => x.SubjectId).FirstOrDefaultAsync();
            await _readingTaskQuestionAnswerRepository.BatchDeleteNoTrackingAsync(x => x.VisitTaskId == inDto.VisitTaskId && x.ReadingQuestionCriterionTrialId == inDto.ReadingQuestionCriterionTrialId);
            List<ReadingTaskQuestionAnswer> readingTaskAnswerList = inDto.AnswerList.Select(x => new ReadingTaskQuestionAnswer()
            {
                Id = NewId.NextGuid(),
                SubjectId = subjectId,
                Answer = x.Answer,
                ReadingQuestionCriterionTrialId = inDto.ReadingQuestionCriterionTrialId,
                ReadingQuestionTrialId = x.ReadingQuestionTrialId,
                VisitTaskId = inDto.VisitTaskId,
                TrialId = inDto.TrialId
            }).ToList();

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

            });
            await _readingTaskQuestionAnswerRepository.AddRangeAsync(readingTaskAnswerList);
            var result = await _visitTaskRepository.SaveChangesAsync();
            return ResponseOutput.Ok(result);
        }

        /// <summary>
        /// 获取阅片非Dicom文件
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<(List<NoneDicomStudyView>, object)> GetReadingImageFile(GetReadingImgInDto inDto)
        {
            var task = await GetNextTask(new GetNextTaskInDto()
            {
                TrialId = inDto.TrialId,
                SubjectId = inDto.SubjectId,
                VisitTaskId = inDto.VisistTaskId,
            });
            List<Guid> visitIds = new List<Guid>();
            if (task.ReadingCategory == ReadingCategory.Visit)
            {
                visitIds.Add(task.VisistId);
            }
            else
            {
                // 阅片期取前面所有的图像
                visitIds.AddRange(await _subjectVisitRepository.Where(x => x.VisitNum <= task.VisitNum && x.SubjectId == task.SubjectId).Select(x => x.Id).ToListAsync());
            }
            List<NoneDicomStudyView> result = await _noneDicomStudyRepository.Where(t => visitIds.Contains(t.SubjectVisitId))
                .ProjectTo<NoneDicomStudyView>(_mapper.ConfigurationProvider, new { token = _userInfo.UserToken }).ToListAsync();

            var taskinfo = await _visitTaskRepository.Where(x => x.Id == inDto.VisistTaskId).FirstNotNullAsync();

            var trialInfo = await _trialRepository.Where(x => x.Id == inDto.TrialId).Select(x => new
            {
                x.ClinicalInformationTransmissionEnum,
            }).FirstOrDefaultAsync();


            var criterionInfo = await _readingQuestionCriterionTrialRepository.Where(x => x.Id == taskinfo.TrialReadingCriterionId).Select(x => new
            {
                x.IsReadingShowPreviousResults,
                x.IsReadingShowSubjectInfo,
                x.CriterionName,
                x.Id,
                x.ReadingTool,

            }).FirstOrDefaultAsync();


            bool isExistsClinicalData = false;
            if (trialInfo.ClinicalInformationTransmissionEnum == 1)
            {
                isExistsClinicalData = (await _readingClinicalDataService.GetClinicalDataList(new GetReadingOrTaskClinicalDataListInDto()
                {

                    SubjectId = task.SubjectId,
                    TrialId = inDto.TrialId,
                    VisitTaskId = task.VisitTaskId,
                })).Count() > 0;
            }


            var taskInfo = await _visitTaskRepository.Where(x => x.Id == task.VisitTaskId).FirstNotNullAsync();

            return (result, new
            {
                VisitTaskId = task.VisitTaskId,
                SubjectId = task.SubjectId,
                SubjectCode = taskInfo.BlindSubjectCode.IsNullOrEmpty() ? task.SubjectCode : taskInfo.BlindSubjectCode,
                ReadingCategory = task.ReadingCategory,
                TaskBlindName = task.TaskBlindName,
                IsReadingShowPreviousResults = criterionInfo.IsReadingShowPreviousResults,
                IsReadingShowSubjectInfo = criterionInfo.IsReadingShowSubjectInfo,
                IsExistsClinicalData = isExistsClinicalData,
                TrialCriterionName = criterionInfo.CriterionName,
                TrialCriterionId = criterionInfo.Id

            });
        }



    }
}
