using IRaCIS.Core.Application.Contracts.Dicom.DTO;

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using IRaCIS.Core.Application.Helper;

namespace IRaCIS.Core.Application.Services
{
    [ApiExplorerSettings(GroupName = "Image")]
    [AllowAnonymous]
    public class SeriesService : BaseService
    {
        private readonly IRepository<ImageLabel> _imageLabelRepository;
        private readonly IRepository<DicomSeries> _seriesRepository;
        private readonly IRepository<DicomInstance> _instanceRepository;
        private readonly IRepository<DicomStudy> _studyRepository;
        private readonly IRepository<KeyInstance> _keyInstanceRepository;
        public SeriesService(IRepository<DicomInstance> instanceRepository, IRepository<DicomStudy> studyRepository,
            IRepository<KeyInstance> keyInstanceRepository, IRepository<DicomSeries> seriesRepository, IRepository<ImageLabel> imageLabelRepository)
        {
            _seriesRepository = seriesRepository;
            _instanceRepository = instanceRepository;
            _studyRepository = studyRepository;
            _keyInstanceRepository = keyInstanceRepository;
            _imageLabelRepository = imageLabelRepository;
        }



        //医生读片那一块有耦合，关键序列   这里暂时留存
        /// <summary> 指定资源Id，获取Dicom检查所属序列信息列表 </summary>
        /// <param name="studyId"> Dicom检查的Id </param>
        [HttpGet, Route("{studyId:guid}")]
        public async Task<IResponseOutput<List<DicomSeriesDTO>>> List(Guid studyId)
        {

            var seriesList = await _seriesRepository.Where(s => s.StudyId == studyId).OrderBy(s => s.SeriesNumber).
              ThenBy(s => s.SeriesTime).ThenBy(s => s.CreateTime)
              .ProjectTo<DicomSeriesDTO>(_mapper.ConfigurationProvider).ToListAsync();

            var idList = await _instanceRepository.Where(s => s.StudyId == studyId).OrderBy(t => t.SeriesId).ThenBy(t => t.InstanceNumber)
                        .ThenBy(s => s.InstanceTime).ThenBy(s => s.CreateTime)
                .Select(t => new { t.SeriesId, t.Id, t.Path, t.NumberOfFrames,t.InstanceNumber }).ToListAsync();//.GroupBy(u => u.SeriesId);

            foreach (var item in seriesList)
            {
                item.InstanceList = idList.Where(s => s.SeriesId == item.Id).Select(u => u.Id).ToList();

                //处理多帧
                item.InstancePathList = idList.Where(s => s.SeriesId == item.Id).OrderBy(t => t.InstanceNumber)
                    .SelectMany(u =>
                    {

                        if (u.NumberOfFrames > 1)
                        {
                            var pathList = new List<string>();

                            for (int i = 1; i <= u.NumberOfFrames; i++)
                            {
                                pathList.Add(u.Path + "?frame=" + (i - 1));
                            }
                            return pathList;
                        }
                        else
                        {
                            return new List<string> { u.Path };

                        }
                    })
                    .ToList();
            }

            #region 暂时废弃

            //bool hasKeyInstance = false;
            //var SeriesIdList = _imageLabelRepository.Where(u => u.TpCode == tpCode).Select(s => s.SeriesId).Distinct().ToList();
            //var instanceIdList = _imageLabelRepository.Where(u => u.TpCode == tpCode).Select(s => s.InstanceId).Distinct().ToList();
            //foreach (var item in seriesList)
            //{
            //    if (SeriesIdList.Contains(item.Id))
            //    {
            //        item.HasLabel = true;
            //        hasKeyInstance = true;
            //    }
            //    else item.HasLabel = false;
            //}
            //if (hasKeyInstance)
            //{
            //    seriesList.Add(new DicomSeriesWithLabelDTO
            //    {
            //        KeySeries = true,
            //        Id = SeriesIdList[0],
            //        InstanceCount = instanceIdList.Count,
            //        HasLabel = true,
            //        Modality = seriesList[0].Modality,
            //        Description = "Key Series"
            //    });
            //}

            //var idList = await _instanceRepository.Where(s => s.StudyId == studyId).OrderBy(t => t.SeriesId).ThenBy(t => t.InstanceNumber)
            //            .ThenBy(s => s.InstanceTime).ThenBy(s => s.CreateTime)
            //    .Select(t => new { t.SeriesId, t.Id, t.Path }).ToListAsync();//.GroupBy(u => u.SeriesId);

            //foreach (var item in seriesList)
            //{
            //    if (item.KeySeries)
            //    {
            //        item.InstanceList = instanceIdList;
            //    }
            //    else
            //    {
            //        //item.InstanceList = idList.Where(s => s.SeriesId == item.Id).OrderBy(t => t.InstanceNumber)
            //        //    .ThenBy(s => s.InstanceTime).ThenBy(s => s.CreateTime).Select(u => u.Id).ToList();

            //        item.InstanceList = idList.Where(s => s.SeriesId == item.Id).Select(u => u.Id).ToList();

            //        item.InstancePathList = idList.Where(s => s.SeriesId == item.Id).Select(u => u.Path).ToList();
            //    }
            //}


            #endregion



            return ResponseOutput.Ok(seriesList);
        }





        /// <summary> 指定资源Id，渲染Dicom序列的Jpeg预览图像 </summary>
        /// <param name="seriesId"> Dicom序列的Id </param>
        [HttpGet, Route("{seriesId:guid}")]
        [AllowAnonymous]
        public async Task<FileContentResult> Preview(Guid seriesId)
        {
            string path = string.Empty;

            path = (await _instanceRepository.Where(s => s.SeriesId == seriesId).Select(t => t.Path).FirstOrDefaultAsync()).IfNullThrowException();

            #region 切换磁盘存储之前
            //var physicalPath = FileStoreHelper.GetPhysicalFilePath(_hostEnvironment, path);

            #endregion

            #region 切换磁盘存储后

            var physicalPath  = FileStoreHelper.GetPhysicalFilePath(_hostEnvironment, path);

            //不存在，去其他路径找
            if (!File.Exists(physicalPath))
            {
                //找到所有磁盘
                var drives = DriveInfo.GetDrives()
                         .Where(d => d.DriveType == DriveType.Fixed && d.IsReady)
                         //剩余空间最多的
                         .OrderByDescending(d => d.AvailableFreeSpace)

                         //存储空间相同，则按照按照总空间从大到小排序
                         .ThenByDescending(d => d.TotalSize - d.TotalFreeSpace)
                         .Select(d => d.RootDirectory.FullName)
                         .ToList();


                foreach (var drive in drives)
                {
                    physicalPath = Path.Combine(drive, _hostEnvironment.EnvironmentName, path.Trim('/'));

                    if (File.Exists(physicalPath))
                    {
                        break;
                    }
                }
            }

           

            #endregion



            using (var sw = ImageHelper.RenderPreviewJpeg(physicalPath))
            {
                var bytes = new byte[sw.Length];
                sw.Read(bytes, 0, bytes.Length);
                sw.Close();
                return new FileContentResult(bytes, "image/jpeg");
            }
        }


    }
}