//--------------------------------------------------------------------
//     此代码由T4模板自动生成  byzhouhang 20210918
//	   生成时间 2021-11-22 11:29:44 
//     对此文件的更改可能会导致不正确的行为，并且如果重新生成代码，这些更改将会丢失。
//--------------------------------------------------------------------
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Hosting;
using IRaCIS.Core.Domain.Share;

namespace IRaCIS.Core.Application.Contracts
{
    /// <summary>
    ///受试者临床信息
    /// </summary>	
    [ApiExplorerSettings(GroupName = "Image")]
    public class ClinicalDataService : BaseService, IClinicalDataService
    {
        public IRepository<PreviousOther> _previousOtherRepository { get; }
        private readonly IRepository<PreviousHistory> _previousHistoryRepository;
        private readonly IRepository<PreviousSurgery> _previousSurgeryRepository;
        private readonly IRepository<PreviousPDF> _previousPdfRepository;



        public ClinicalDataService(IRepository<PreviousHistory> previousHistoryRepository, 
            IRepository<PreviousOther> previousOtherRepository,
            IRepository<PreviousSurgery> previousSurgeryRepository,
            IRepository<PreviousPDF> previousPDFRepository)
        {
            _previousOtherRepository = previousOtherRepository;
            _previousHistoryRepository = previousHistoryRepository;
            _previousSurgeryRepository = previousSurgeryRepository;
            _previousPdfRepository = previousPDFRepository;
        }


        /// <summary>
        /// 上传临床数据
        /// </summary>
        /// <param name="formCollection"></param>
        /// <param name="subjectVisitId"></param>
        /// <param name="_hostEnvironment"></param>
        /// <returns></returns>
        [HttpPost("{trialId:guid}/{subjectVisitId:guid}")]
        [DisableRequestSizeLimit]
        public async Task<IResponseOutput> UploadVisitClinicalData(IFormCollection formCollection, Guid subjectVisitId, [FromServices] IWebHostEnvironment _hostEnvironment)
        {
           

            var rootPath = Directory.GetParent(_hostEnvironment.ContentRootPath.TrimEnd('\\')).IfNullThrowException().FullName;

            //上传根路径
            var _fileStorePath = Path.Combine(rootPath, StaticData.TrialDataFolder);

            var sv = _repository.Where<SubjectVisit>(t => t.Id == subjectVisitId).Select(t => new { t.TrialId, t.SiteId, t.SubjectId }).FirstOrDefault().IfNullThrowException();

            string uploadFolderPath = Path.Combine(_fileStorePath, sv.TrialId.ToString(),
                sv.SiteId.ToString(), sv.SubjectId.ToString(), subjectVisitId.ToString(), StaticData.TreatmenthistoryFolder);

            if (!Directory.Exists(uploadFolderPath))
            {
                Directory.CreateDirectory(uploadFolderPath);
            }

            foreach (IFormFile file in formCollection.Files)
            {
                var realName = file.FileName;
                var fileNameEX = Path.GetExtension(realName);
                var trustedFileNameForFileStorage = Guid.NewGuid().ToString() + fileNameEX;

                var relativePath = $"/{StaticData.TrialDataFolder}/{sv.TrialId}/{sv.SiteId}/{sv.SubjectId}/{subjectVisitId}/{StaticData.TreatmenthistoryFolder}/{trustedFileNameForFileStorage}";

                var filePath = Path.Combine(uploadFolderPath, trustedFileNameForFileStorage);

                using (FileStream fs = System.IO.File.Create(filePath))
                {
                    await file.CopyToAsync(fs);
                    await fs.FlushAsync();
                }

                //插入临床pdf 路径
                await _previousPdfRepository.AddAsync(new PreviousPDF() { SubjectVisitId = subjectVisitId, Path = relativePath, FileName = realName });
            }


            await _repository.SaveChangesAsync();

            return ResponseOutput.Ok();

            //return ResponseOutput.Ok(new
            //{
            //    FilePath = relativePath,
            //    FullFilePath =  relativePath + "?access_token=" + _userInfo.UserToken

            //});
        }



        /// <summary>
        /// 获取访视+受试者级别的数据
        /// </summary>
        /// <param ></param>
        /// <returns></returns>
        [HttpGet("{subjectVisitId:guid}")]
        public async Task<SubjectClinicalDataDto> GetSubjectVisitClinicalData(Guid subjectVisitId)
        {

            // 最完美方式  其中TrialSite 通过导航属性 两个字段连接出来

            var clinicalObj = await _repository.Where<SubjectVisit>(t => t.Id == subjectVisitId)
            .ProjectTo<SubjectClinicalDataDto>(_mapper.ConfigurationProvider, new { subjectVisitId = subjectVisitId, token = _userInfo.UserToken }).FirstOrDefaultAsync().IfNullThrowException();

            return clinicalObj;

            #region 老方式  linq join 而且需要映射  


            //var query = from sv in _subjectVisitRepository.GetAll()
            //            join subject in _subjectRepository.GetAll() on sv.SubjectId equals subject.Id
            //            join trialSite in _trialSiteRepository.Find(t => t.TrialId == subjectClinicalDataQuery.TrialId) on sv.SiteId equals trialSite.SiteId
            //            select new SubjectClinicalDataDto()
            //            {
            //                SubjectId = sv.SubjectId,
            //                SubjectCode = subject.Code,
            //                SubjectVisitId = sv.Id,
            //                VisitName = sv.VisitName,
            //                VisitNum = sv.VisitNum,
            //                TrialSiteCode = trialSite.TrialSiteCode
            //            };

            //var clinicalObj = query.FirstOrDefault(t => t.SubjectVisitId == subjectClinicalDataQuery.SubjectVisitId);

            //clinicalObj.PreviousHistoryList = _previousHistoryRepository.Find(t => t.SubjectVisitId == subjectClinicalDataQuery.SubjectVisitId)
            //                                   .ProjectTo<PreviousHistoryView>(_mapper.ConfigurationProvider).ToList();
            //clinicalObj.PreviousOtherList = _previousOtherRepository.Find(t => t.SubjectVisitId == subjectClinicalDataQuery.SubjectVisitId)
            //                                   .ProjectTo<PreviousOtherView>(_mapper.ConfigurationProvider).ToList();
            //clinicalObj.PreviousSurgeryList = _previousSurgeryRepository.Find(t => t.SubjectVisitId == subjectClinicalDataQuery.SubjectVisitId)
            //                                   .ProjectTo<PreviousSurgeryView>(_mapper.ConfigurationProvider).ToList();

            #endregion

        }


        public async Task<List<PreviousHistoryView>> GetPreviousHistoryList(PreviousHistoryQuery queryPreviousHistory)
        {

            var previousHistoryQueryable = _previousHistoryRepository.WhereIf(queryPreviousHistory.IsSubjectLevel != null, t => t.IsSubjectLevel == queryPreviousHistory.IsSubjectLevel)
             .ProjectTo<PreviousHistoryView>(_mapper.ConfigurationProvider, new { token = _userInfo.UserToken });

            return await previousHistoryQueryable.ToListAsync();
        }

        [HttpPost("{trialId:guid}")]
        public async Task<IResponseOutput<Guid>> AddOrUpdatePreviousHistory(PreviousHistoryAddOrEdit addOrEditPreviousHistory)
        {
           
            var entity = await _previousHistoryRepository.InsertOrUpdateAsync(addOrEditPreviousHistory, true);
            return ResponseOutput.Ok(entity.Id);
        }


        [HttpDelete("{trialId:guid}/{subjectVisitId:guid}/{previousHistoryId:guid}")]
        public async Task<IResponseOutput> DeletePreviousHistory(Guid previousHistoryId)
        {        
            await _previousHistoryRepository.DeleteFromQueryAsync(t => t.Id == previousHistoryId,true);
            return ResponseOutput.Ok();
        }


        public async Task<List<PreviousOtherView>> GetPreviousOtherList(PreviousOtherQuery queryPreviousOther)
        {
            var previousOtherQueryable = _previousOtherRepository.WhereIf(queryPreviousOther.IsSubjectLevel != null, t => t.IsSubjectLevel == queryPreviousOther.IsSubjectLevel)
                .ProjectTo<PreviousOtherView>(_mapper.ConfigurationProvider, new { token = _userInfo.UserToken });
            return await previousOtherQueryable.ToListAsync();
        }


        [HttpPost("{trialId:guid}")]
        public async Task<IResponseOutput<Guid>> AddOrUpdatePreviousOther(PreviousOtherAddOrEdit addOrEditPreviousOther)
        {          
            var entity = await _previousOtherRepository.InsertOrUpdateAsync(addOrEditPreviousOther, true);
            return ResponseOutput.Ok(entity.Id);

        }


        [HttpDelete("{trialId:guid}/{subjectVisitId:guid}/{previousOtherId:guid}")]
        public async Task<IResponseOutput> DeletePreviousOther(Guid previousOtherId)
        {          
            await _previousOtherRepository.DeleteFromQueryAsync(t => t.Id == previousOtherId,true);
            return ResponseOutput.Ok();
        }


        public async Task<List<PreviousSurgeryView>> GetPreviousSurgeryList(PreviousSurgeryQuery queryPreviousSurgery)
        {
            var previousSurgeryQueryable = _previousSurgeryRepository.WhereIf(queryPreviousSurgery.IsSubjectLevel != null, t => t.IsSubjectLevel == queryPreviousSurgery.IsSubjectLevel)
             .ProjectTo<PreviousSurgeryView>(_mapper.ConfigurationProvider, new { token = _userInfo.UserToken });

            return await previousSurgeryQueryable.ToListAsync();
        }

        [HttpPost("{trialId:guid}")]
        public async Task<IResponseOutput<Guid>> AddOrUpdatePreviousSurgery(PreviousSurgeryAddOrEdit addOrEditPreviousSurgery)
        {
          
            var entity = await _previousSurgeryRepository.InsertOrUpdateAsync(addOrEditPreviousSurgery, true);
            return ResponseOutput.Ok(entity.Id);
        }


        [HttpDelete("{trialId:guid}/{subjectVisitId:guid}/{previousSurgeryId:guid}")]
        public async Task<IResponseOutput> DeletePreviousSurgery(Guid previousSurgeryId)
        {
            var success = await _previousSurgeryRepository.DeleteFromQueryAsync(t => t.Id == previousSurgeryId,true);
            return ResponseOutput.Ok();
        }

        [HttpGet("{subjectVisitId:guid}")]
        public async Task<List<PreviousPDFView>> GetPreviousPDFList(Guid subjectVisitId)
        {

            var previousPDFQueryable = _previousPdfRepository.Where(t => t.SubjectVisitId == subjectVisitId).ProjectTo<PreviousPDFView>(_mapper.ConfigurationProvider);

            return await previousPDFQueryable.ToListAsync();
        }


        public async Task<IResponseOutput> AddOrUpdatePreviousPDF(PreviousPDFAddOrEdit addOrEditPreviousPDF)
        {
           
            var entity = await _previousPdfRepository.InsertOrUpdateAsync(addOrEditPreviousPDF, true);
            return ResponseOutput.Ok(entity.Id);

        }

        [HttpDelete("{trialId:guid}/{subjectVisitId:guid}/{previousPDFId:guid}")]
        public async Task<IResponseOutput> DeletePreviousPDF(Guid previousPDFId)
        {
           
            await _previousPdfRepository.DeleteFromQueryAsync(t => t.Id == previousPDFId,true);
            return ResponseOutput.Ok();
        }




    }
}
