//--------------------------------------------------------------------
//     此代码由T4模板自动生成  byzhouhang 20210918
//	   生成时间 2021-12-06 10:54:55 
//     对此文件的更改可能会导致不正确的行为，并且如果重新生成代码，这些更改将会丢失。
//--------------------------------------------------------------------
using Microsoft.AspNetCore.Mvc;
using IRaCIS.Core.Application.Filter;
using Nito.AsyncEx;
using System.ComponentModel.DataAnnotations;
using IRaCIS.Core.Application.Service;
using IRaCIS.Core.Domain.Share;

namespace IRaCIS.Core.Application.Contracts
{
    /// <summary>
    /// NoneDicomStudyService
    /// </summary>	
    [ApiExplorerSettings(GroupName = "Image")]
    public class NoneDicomStudyService : BaseService, INoneDicomStudyService
    {
        private readonly IRepository<NoneDicomStudy> _noneDicomStudyRepository;
        private readonly IRepository<NoneDicomStudyFile> _noneDicomStudyFileRepository;
        private readonly AsyncLock _mutex = new AsyncLock();
        private readonly QCCommon _qCCommon;


        public NoneDicomStudyService(IRepository<NoneDicomStudy> noneDicomStudyRepository,
             QCCommon qCCommon,
            IRepository<NoneDicomStudyFile> noneDicomStudyFileRepository)
        {
            _qCCommon = qCCommon;
            _noneDicomStudyRepository = noneDicomStudyRepository;

            _noneDicomStudyFileRepository = noneDicomStudyFileRepository;

        }


        [HttpGet]
        public async Task<List<NoneDicomStudyView>> GetNoneDicomStudyList([FromQuery, NotDefault] Guid subjectVisitId, Guid? nonedicomStudyId)
        {

            var noneDicomStudyQueryable = _noneDicomStudyRepository.Where(t => t.SubjectVisitId == subjectVisitId).WhereIf(nonedicomStudyId != null, t => t.Id == nonedicomStudyId)

                .ProjectTo<NoneDicomStudyView>(_mapper.ConfigurationProvider, new { token = _userInfo.UserToken });

            return await noneDicomStudyQueryable.ToListAsync();
        }


        [UnitOfWork]
         [TypeFilter(typeof(TrialResourceFilter),Arguments = new object[] { "AfterStopCannNotOpt" })]
        public async Task<IResponseOutput<NoneDicomStudyAddReturnDto>> AddOrUpdateNoneDicomStudy(NoneDicomStudyAddOrEdit addOrEditNoneDicomStudy)
        {

            await _qCCommon.VerifyIsCRCSubmmitAsync(_repository, _userInfo,  addOrEditNoneDicomStudy.SubjectVisitId);

            if (_repository.Where<Trial>(t => t.Id == addOrEditNoneDicomStudy.TrialId).Any(t => t.IsVerifyVisitImageDate==true))
            {
                await _qCCommon.VerifyStudyImageDataAsync(_repository, addOrEditNoneDicomStudy.SubjectId, addOrEditNoneDicomStudy.SubjectVisitId, addOrEditNoneDicomStudy.ImageDate);

            }

            NoneDicomStudy? optEntity = null;
            using (await _mutex.LockAsync())
            {
                if (addOrEditNoneDicomStudy.Id == Guid.Empty || addOrEditNoneDicomStudy.Id == null)
                {
                    //默认会是0  
                    var code = await _noneDicomStudyRepository.Where(t => t.TrialId == addOrEditNoneDicomStudy.TrialId).Select(x => x.Code).DefaultIfEmpty().MaxAsync();

                    addOrEditNoneDicomStudy.Code = code + 1;

                    optEntity = await _noneDicomStudyRepository.InsertFromDTOAsync(addOrEditNoneDicomStudy);

                    optEntity.StudyCode = AppSettings.GetCodeStr(optEntity.Code, nameof(NoneDicomStudy));
                }
                else
                {

                    optEntity = await _noneDicomStudyRepository.UpdateFromDTOAsync(addOrEditNoneDicomStudy);
                }

                await _noneDicomStudyRepository.SaveChangesAsync();
            }


            NoneDicomStudyAddReturnDto noneDicom = new NoneDicomStudyAddReturnDto()
            {
                StudyCode = optEntity.StudyCode,
                Id = optEntity.Id
            };
            return ResponseOutput.Ok(noneDicom);

        }

         [TypeFilter(typeof(TrialResourceFilter),Arguments = new object[] { "AfterStopCannNotOpt" })]
        [HttpDelete("{trialId:guid}/{subjectVisitId:guid}/{noneDicomStudyId:guid}")]
        public async Task<IResponseOutput> DeleteNoneDicomStudy(Guid noneDicomStudyId, Guid subjectVisitId)
        {
            //提交了 但是IQC同意的时候 是可以删除的 | 普通提交后也不能删除


            await _qCCommon.VerifyIsCRCSubmmitAsync(_repository, _userInfo, subjectVisitId);

            await _noneDicomStudyRepository.DeleteFromQueryAsync(noneDicomStudyId);

            await _noneDicomStudyFileRepository.DeleteFromQueryAsync(t => t.NoneDicomStudyId == noneDicomStudyId);

            //确认需求 不删除
            //await _studyMonitorRepository.BatchDeleteNoTrackingAsync(t => t.StudyId == noneDicomStudyId);

            await _noneDicomStudyRepository.SaveChangesAsync();

            return ResponseOutput.Ok();
        }


        [HttpDelete("{trialId:guid}/{subjectVisitId:guid}/{noneDicomStudyFileId:guid}")]
         [TypeFilter(typeof(TrialResourceFilter),Arguments = new object[] { "AfterStopCannNotOpt" })]
        public async Task<IResponseOutput> DeleteNoneDicomStudyFile(Guid noneDicomStudyFileId, Guid subjectVisitId)
        {
            //提交了 但是IQC同意的时候 是可以删除的 | 普通提交后也不能删除
            await _qCCommon.VerifyIsCRCSubmmitAsync(_repository, _userInfo, subjectVisitId);

            var noneDicomStudyFile = await _noneDicomStudyFileRepository.FirstOrDefaultAsync(t => t.Id == noneDicomStudyFileId);

            var success = await _noneDicomStudyFileRepository.DeleteAsync(noneDicomStudyFile, true);

            //维护文件数量数字
            var noneDicomStudy = await _noneDicomStudyRepository.FirstOrDefaultAsync(t => t.Id == noneDicomStudyFile.NoneDicomStudyId);
            noneDicomStudy.FileCount = await _noneDicomStudyFileRepository.CountAsync(t => t.NoneDicomStudyId == noneDicomStudyFile.NoneDicomStudyId);
            await _noneDicomStudyRepository.SaveChangesAsync();

            return ResponseOutput.Ok();
        }

        /// <summary>
        /// 非Dicom检查 文件列表
        /// </summary>
        /// <param name="noneDicomStudyId"></param>
        /// <returns></returns>
        [HttpGet("{noneDicomStudyId:guid}")]
        public async Task<List<NoneDicomStudyFileView>> GetNoneDicomStudyFileList(Guid noneDicomStudyId)
        {
            return await _noneDicomStudyFileRepository.Where(t => t.NoneDicomStudyId == noneDicomStudyId)
                .ProjectTo<NoneDicomStudyFileView>(_mapper.ConfigurationProvider, new { token = _userInfo.UserToken }).ToListAsync();
        }

        [HttpGet("{subjectVisitId:guid}")]
        public async Task<List<NoneDicomStudyFileView>> GetVisitNoneDicomStudyFileList(Guid subjectVisitId)
        {
            return await _repository.Where<NoneDicomStudyFile>(t => t.NoneDicomStudy.SubjectVisitId == subjectVisitId)
                .ProjectTo<NoneDicomStudyFileView>(_mapper.ConfigurationProvider, new { token = _userInfo.UserToken }).ToListAsync();
        }



    }
}
