using AutoMapper;

using IRaCIS.Core.Domain.Models;

using IRaCIS.Core.Infra.EFCore;

using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.StaticFiles;
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using IRaCIS.Core.Domain.Share;
using Microsoft.EntityFrameworkCore;

namespace IRaCIS.Core.API.Controllers
{
    [ApiExplorerSettings(GroupName = "Trial")]
    [ApiController]
    public class DownLoadController : ControllerBase
    {
        public IMapper _mapper { get; set; }
        public IUserInfo _userInfo { get; set; }

        private readonly IWebHostEnvironment _hostEnvironment;



        public DownLoadController(IMapper mapper, IUserInfo userInfo, IMediator mediator, IWebHostEnvironment hostEnvironment)
        {
            _hostEnvironment = hostEnvironment;
            _mapper = mapper;
            _userInfo = userInfo;
        }

        //[HttpGet("VisitPlan/DownloadInflunceStudyList{trialId:guid}/{createTime:dateTime}")]
        //public async Task<IActionResult> DownloadInflunceStudyList(Guid trialId, DateTime createTime, [FromServices] IRepository<VisitPlanInfluenceSubjectVisit> _influnceRepository)
        //{
        //    var list = _influnceRepository.Where(t => t.TrialId == trialId && t.CreateTime == createTime)
        //        .ProjectTo<VisitPlanInfluenceSubjectVisitDTO>(_mapper.ConfigurationProvider).ToList();

        //    if (list.Count == 0)
        //    {
        //        list.Add(new VisitPlanInfluenceSubjectVisitDTO() { CreateTime = DateTime.Now, SubjectCode = "test", StudyTime = DateTime.Now, IsDicomStudy = false, HistoryWindow = "test" });
        //    }

        //    IExporter exporter = new ExcelExporter();

        //    var result = await exporter.ExportAsByteArray(list);


        //    return new XlsxFileResult(bytes: bytes);

        //    //return File(result, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", $"检查导出_{DateTime.Now}.xlsx");

        //}


        [AllowAnonymous]
        [HttpGet("CommonDocument/DownloadCommonDoc")]
        public async Task<IActionResult> DownloadCommonFile(string code, [FromServices] IRepository<CommonDocument> _commonDocumentRepository)
        {
            var doc =  await _commonDocumentRepository.AsQueryable(true).FirstOrDefaultAsync(t => t.Code == code);

            if (doc == null)
            {
                throw new Exception("当前code 没要找到对应的文件");
            }

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

            var filePath = Path.Combine(rootPath, doc.Path.Trim('/'));

            if (!System.IO.File.Exists(filePath))
            {
                throw new Exception("服务器本地不存在该路径文件");
            }

            new FileExtensionContentTypeProvider().Mappings.TryGetValue(Path.GetExtension(filePath), out var contentType);


            return File(System.IO.File.OpenRead(filePath), contentType ?? "application/octet-stream", doc.Name);


        }


    }
}