using IRaCIS.Core.Domain.Share;
using IRaCIS.Core.Infrastructure;
using Microsoft.AspNetCore.Hosting;
namespace IRaCIS.Core.Application.Helper;
public static class FileStoreHelper
{
    //处理文件名  压缩包,或者目录类的  会带上相对路径
    public static (string TrustedFileNameForFileStorage, string RealName) GetStoreFileName(string fileName)
    {
        //带目录层级,需要后端处理前端的路径
        if (fileName.Contains("\\"))
        {
            fileName = fileName.Split("\\").Last();
        }
        if (fileName.Contains("/"))
        {
            fileName = fileName.Split("/").Last();
        }
        var trustedFileNameForFileStorage = Guid.NewGuid().ToString() + fileName;
        return (trustedFileNameForFileStorage, fileName);
    }
    //API  vue  部署目录
    public static string GetIRaCISRootPath(IWebHostEnvironment _hostEnvironment)
    {
        var rootPath = (Directory.GetParent(_hostEnvironment.ContentRootPath.TrimEnd('\\'))).IfNullThrowException().FullName;
        return rootPath;
    }
    //获取环境存储根目录
    public static string GetIRaCISRootDataFolder(IWebHostEnvironment _hostEnvironment)
    {
        var rootPath = GetIRaCISRootPath(_hostEnvironment);
        var rootFolder = Path.Combine(rootPath, StaticData.Folder.IRaCISDataFolder);
        return rootFolder;
    }
    //根据相对路径  获取具体文件物理地址
    public static string GetPhysicalFilePath(IWebHostEnvironment _hostEnvironment, string relativePath)
    {
        var rootPath = GetIRaCISRootPath(_hostEnvironment);
        var physicalFilePath = Path.Combine(rootPath, relativePath.Trim('/'));
        return physicalFilePath;
    }
    /// 
    /// 
    /// 
    /// 
    /// 
    /// 
    /// 
    /// 
    public static async Task<(string PhysicalPath, string FileName)> GetSystemClinicalPathAsync(IWebHostEnvironment _hostEnvironment, IRepository _clinicalDataTrialSetRepository, Guid id)
    {
        var systemClinicalData = await _clinicalDataTrialSetRepository.FirstOrDefaultAsync(t => t.Id == id);
        if (systemClinicalData == null || systemClinicalData.Path == string.Empty)
        {
            throw new BusinessValidationFailedException("数据库没有找到对应的数据模板文件,请联系系统运维人员。");
        }
        var filePath = FileStoreHelper.GetPhysicalFilePath(_hostEnvironment, systemClinicalData.Path);
        if (!System.IO.File.Exists(filePath))
        {
            throw new BusinessValidationFailedException("数据模板文件存储路径上未找对应文件,请联系系统运维人员。");
        }
        return (filePath, systemClinicalData.FileName);
    }
    /// 
    /// 
    /// 
    /// 
    /// 
    /// 
    /// 
    /// 
    public static async Task<(string PhysicalPath, string FileName)> GetTrialClinicalPathAsync(IWebHostEnvironment _hostEnvironment, IRepository _clinicalDataTrialSetRepository, Guid id)
    {
        var trialClinicalData = await _clinicalDataTrialSetRepository.FirstOrDefaultAsync(t => t.Id == id);
        if (trialClinicalData == null|| trialClinicalData.Path==string.Empty)
        {
            throw new BusinessValidationFailedException("数据库没有找到对应的数据模板文件,请联系系统运维人员。");
        }
        var filePath = FileStoreHelper.GetPhysicalFilePath(_hostEnvironment, trialClinicalData.Path);
        if (!System.IO.File.Exists(filePath))
        {
            throw new BusinessValidationFailedException("数据模板文件存储路径上未找对应文件,请联系系统运维人员。");
        }
        return (filePath, trialClinicalData.FileName);
    }
    //通过编码获取通用文档具体物理路径  
    public static async Task<(string PhysicalPath, string FileName)> GetCommonDocPhysicalFilePathAsync(IWebHostEnvironment _hostEnvironment, IRepository _commonDocumentRepository, string code)
    {
        var doc = await _commonDocumentRepository.FirstOrDefaultAsync(t => t.Code == code);
        if (doc == null)
        {
            throw new BusinessValidationFailedException("数据库没有找到对应的数据模板文件,请联系系统运维人员。");
        }
        var filePath = FileStoreHelper.GetPhysicalFilePath(_hostEnvironment, doc.Path);
        if (!System.IO.File.Exists(filePath))
        {
            throw new BusinessValidationFailedException("数据模板文件存储路径上未找对应文件,请联系系统运维人员。");
        }
        return (filePath, doc.Name.Trim('/'));
    }
    /// 
    /// 写文件导到磁盘
    /// 
    /// 流
    /// 文件保存路径
    /// 
    public static async Task WriteFileAsync(System.IO.Stream stream, string path)
    {
        const int FILE_WRITE_SIZE = 84975;//写出缓冲区大小
        int writeCount = 0;
        using (FileStream fileStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Write, FILE_WRITE_SIZE, true))
        {
            byte[] byteArr = new byte[FILE_WRITE_SIZE];
            int readCount = 0;
            while ((readCount = await stream.ReadAsync(byteArr, 0, byteArr.Length)) > 0)
            {
                await fileStream.WriteAsync(byteArr, 0, readCount);
                writeCount += readCount;
            }
        }
        return writeCount;
    }
    // 获取项目签名文档存放路径
    public static (string PhysicalPath, string RelativePath) GetTrialSignDocPath(IWebHostEnvironment _hostEnvironment, Guid trialId, string fileName)
    {
        var rootPath = FileStoreHelper.GetIRaCISRootDataFolder(_hostEnvironment);
        //文件类型路径处理
        var uploadFolderPath = Path.Combine(rootPath, StaticData.Folder.TrialDataFolder, trialId.ToString(), StaticData.Folder.SignDocumentFolder);
        if (!Directory.Exists(uploadFolderPath)) Directory.CreateDirectory(uploadFolderPath);
        var (trustedFileNameForFileStorage, fileRealName) = FileStoreHelper.GetStoreFileName(fileName);
        var relativePath = $"/{StaticData.Folder.IRaCISDataFolder}/{StaticData.Folder.TrialDataFolder}/{trialId}/{StaticData.Folder.SignDocumentFolder}/{trustedFileNameForFileStorage}";
        var serverFilePath = Path.Combine(uploadFolderPath, trustedFileNameForFileStorage);
        return (serverFilePath, relativePath);
    }
    // 获取系统签名文档存放路径
    public static (string PhysicalPath, string RelativePath) GetSystemSignDocPath(IWebHostEnvironment _hostEnvironment, string fileName)
    {
        var rootPath = FileStoreHelper.GetIRaCISRootDataFolder(_hostEnvironment);
        //文件类型路径处理
        var uploadFolderPath = Path.Combine(rootPath, StaticData.Folder.SystemDataFolder, StaticData.Folder.SignDocumentFolder);
        if (!Directory.Exists(uploadFolderPath)) Directory.CreateDirectory(uploadFolderPath);
        var (trustedFileNameForFileStorage, fileRealName) = FileStoreHelper.GetStoreFileName(fileName);
        var relativePath = $"/{StaticData.Folder.IRaCISDataFolder}/{StaticData.Folder.SystemDataFolder}/{ StaticData.Folder.SignDocumentFolder}/{trustedFileNameForFileStorage}";
        var serverFilePath = Path.Combine(uploadFolderPath, trustedFileNameForFileStorage);
        return (serverFilePath, relativePath);
    }
    // 获取通用文档存放路径(excel模板 )
    public static (string PhysicalPath, string RelativePath) GetCommonDocPath(IWebHostEnvironment _hostEnvironment, string fileName)
    {
        var rootPath = FileStoreHelper.GetIRaCISRootDataFolder(_hostEnvironment);
        //文件类型路径处理
        var uploadFolderPath = Path.Combine(rootPath, StaticData.Folder.SystemDataFolder, StaticData.Folder.DataTemplate);
        if (!Directory.Exists(uploadFolderPath)) Directory.CreateDirectory(uploadFolderPath);
        var (trustedFileNameForFileStorage, fileRealName) = FileStoreHelper.GetStoreFileName(fileName);
        var relativePath = $"/{StaticData.Folder.IRaCISDataFolder}/{StaticData.Folder.SystemDataFolder}/{StaticData.Folder.DataTemplate}/{trustedFileNameForFileStorage}";
        var serverFilePath = Path.Combine(uploadFolderPath, trustedFileNameForFileStorage);
        return (serverFilePath, relativePath);
    }
    //获取系统通知文档存放路径
    public static (string PhysicalPath, string RelativePath) GetSystemNoticePath(IWebHostEnvironment _hostEnvironment, string fileName)
    {
        var rootPath = FileStoreHelper.GetIRaCISRootDataFolder(_hostEnvironment);
        //文件类型路径处理
        var uploadFolderPath = Path.Combine(rootPath, StaticData.Folder.SystemDataFolder, StaticData.Folder.NoticeAttachment);
        if (!Directory.Exists(uploadFolderPath)) Directory.CreateDirectory(uploadFolderPath);
        var (trustedFileNameForFileStorage, fileRealName) = FileStoreHelper.GetStoreFileName(fileName);
        var relativePath = $"/{StaticData.Folder.IRaCISDataFolder}/{StaticData.Folder.SystemDataFolder}/{StaticData.Folder.NoticeAttachment}/{trustedFileNameForFileStorage}";
        var serverFilePath = Path.Combine(uploadFolderPath, trustedFileNameForFileStorage);
        return (serverFilePath, relativePath);
    }
    // 获取一致性核查路径
    public static (string PhysicalPath, string RelativePath) GetTrialCheckFilePath(IWebHostEnvironment _hostEnvironment, string fileName,Guid trialId)
    {
        var rootPath = FileStoreHelper.GetIRaCISRootDataFolder(_hostEnvironment);
        //上传根路径
        string uploadFolderPath = Path.Combine(rootPath, StaticData.Folder.TrialDataFolder, trialId.ToString(), StaticData.Folder.UploadEDCData);
        if (!Directory.Exists(uploadFolderPath)) Directory.CreateDirectory(uploadFolderPath);
        //存放核对表
        var (trustedFileNameForFileStorage, realFileName) = FileStoreHelper.GetStoreFileName(fileName);
        var relativePath = $"/{StaticData.Folder.IRaCISDataFolder}/{StaticData.Folder.TrialDataFolder}/{trialId}/{StaticData.Folder.UploadEDCData}/{trustedFileNameForFileStorage}";
        var serverFilePath = Path.Combine(uploadFolderPath, trustedFileNameForFileStorage);
        return (serverFilePath, relativePath);
    }
    public static (string PhysicalPath, string RelativePath, string FileRealName) GetClinicalTemplatePath(IWebHostEnvironment _hostEnvironment, string fileName,Guid trialId)
    {
      
        var rootPath = FileStoreHelper.GetIRaCISRootDataFolder(_hostEnvironment);
        string uploadFolderPath = Path.Combine(rootPath, StaticData.Folder.TrialDataFolder, "ClinicalTemplate", trialId.ToString(), StaticData.Folder.TreatmenthistoryFolder);
        if (!Directory.Exists(uploadFolderPath)) Directory.CreateDirectory(uploadFolderPath);
        var (trustedFileNameForFileStorage, fileRealName) = FileStoreHelper.GetStoreFileName(fileName);
        var relativePath = $"/{StaticData.Folder.IRaCISDataFolder}/{StaticData.Folder.TrialDataFolder}/ClinicalTemplate/{trialId}/{StaticData.Folder.TreatmenthistoryFolder}/{trustedFileNameForFileStorage}";
        var serverFilePath = Path.Combine(uploadFolderPath, trustedFileNameForFileStorage);
        return (serverFilePath, relativePath, fileRealName);
    }
    public  static (string PhysicalPath, string RelativePath, string FileRealName) GetReadClinicalDataPath(IWebHostEnvironment _hostEnvironment, string fileName, Guid trialId, Guid siteId, Guid subjectId, Guid readingId)
    {
        var rootPath = FileStoreHelper.GetIRaCISRootDataFolder(_hostEnvironment);
        string uploadFolderPath = Path.Combine(rootPath, StaticData.Folder.TrialDataFolder, trialId.ToString(), siteId.ToString(), subjectId.ToString(), StaticData.Folder.Reading, readingId.ToString());
        if (!Directory.Exists(uploadFolderPath)) Directory.CreateDirectory(uploadFolderPath);
        var (trustedFileNameForFileStorage, fileRealName) = FileStoreHelper.GetStoreFileName(fileName);
        var relativePath = $"/{StaticData.Folder.IRaCISDataFolder}/{StaticData.Folder.TrialDataFolder}/{trialId}/{siteId}/{subjectId}/{StaticData.Folder.Reading}/{readingId}/{trustedFileNameForFileStorage}";
        var serverFilePath = Path.Combine(uploadFolderPath, trustedFileNameForFileStorage);
        return (serverFilePath, relativePath, fileRealName);
    }
    //获取临床数据存放路径
    public static (string PhysicalPath, string RelativePath,string FileRealName) GetClinicalDataPath(IWebHostEnvironment _hostEnvironment, string fileName,Guid trialId,Guid siteId,Guid subjectId,Guid subjectVisitId)
    {
        var rootPath = FileStoreHelper.GetIRaCISRootDataFolder(_hostEnvironment);
        string uploadFolderPath = Path.Combine(rootPath, StaticData.Folder.TrialDataFolder, trialId.ToString(),siteId.ToString(), subjectId.ToString(), subjectVisitId.ToString(), StaticData.Folder.TreatmenthistoryFolder);
        if (!Directory.Exists(uploadFolderPath)) Directory.CreateDirectory(uploadFolderPath);
        var (trustedFileNameForFileStorage, fileRealName) = FileStoreHelper.GetStoreFileName(fileName);
        var relativePath = $"/{StaticData.Folder.IRaCISDataFolder}/{StaticData.Folder.TrialDataFolder}/{trialId}/{siteId}/{subjectId}/{subjectVisitId}/{StaticData.Folder.TreatmenthistoryFolder}/{trustedFileNameForFileStorage}";
        var serverFilePath = Path.Combine(uploadFolderPath, trustedFileNameForFileStorage);
        return (serverFilePath, relativePath, fileRealName);
    }
    public static (string PhysicalPath, string RelativePath, string FileRealName) GetClinicalDataPath(IWebHostEnvironment _hostEnvironment, string fileName, Guid trialId , Guid subjectId)
    {
        var rootPath = FileStoreHelper.GetIRaCISRootDataFolder(_hostEnvironment);
        string uploadFolderPath = Path.Combine(rootPath, StaticData.Folder.TrialDataFolder, trialId.ToString(),  subjectId.ToString(),  StaticData.Folder.TreatmenthistoryFolder);
        if (!Directory.Exists(uploadFolderPath)) Directory.CreateDirectory(uploadFolderPath);
        var (trustedFileNameForFileStorage, fileRealName) = FileStoreHelper.GetStoreFileName(fileName);
        var relativePath = $"/{StaticData.Folder.IRaCISDataFolder}/{StaticData.Folder.TrialDataFolder}/{trialId}/{subjectId}/{StaticData.Folder.TreatmenthistoryFolder}/{trustedFileNameForFileStorage}";
        var serverFilePath = Path.Combine(uploadFolderPath, trustedFileNameForFileStorage);
        return (serverFilePath, relativePath, fileRealName);
    }
    /// 
    /// 通用获取文件路径
    /// 
    /// 
    /// 
    /// 
    /// 
    /// 
    /// 
    public static (string PhysicalPath, string RelativePath, string FileRealName) GetFilePath(IWebHostEnvironment _hostEnvironment, string fileName, Guid trialId, Guid id,string type)
    {
        var rootPath = FileStoreHelper.GetIRaCISRootDataFolder(_hostEnvironment);
        string uploadFolderPath = Path.Combine(rootPath, StaticData.Folder.TrialDataFolder, trialId.ToString(), id.ToString(), type);
        if (!Directory.Exists(uploadFolderPath)) Directory.CreateDirectory(uploadFolderPath);
        var (trustedFileNameForFileStorage, fileRealName) = FileStoreHelper.GetStoreFileName(fileName);
        var relativePath = $"/{StaticData.Folder.IRaCISDataFolder}/{StaticData.Folder.TrialDataFolder}/{trialId}/{id}/{type}/{trustedFileNameForFileStorage}";
        var serverFilePath = Path.Combine(uploadFolderPath, trustedFileNameForFileStorage);
        return (serverFilePath, relativePath, fileRealName);
    }
    public static (string PhysicalPath, string RelativePath, string FileRealName) GetMedicalReviewImage(IWebHostEnvironment _hostEnvironment, string fileName, Guid trialId, Guid taskMedicalReviewId)
    {
        var rootPath = FileStoreHelper.GetIRaCISRootDataFolder(_hostEnvironment);
        string uploadFolderPath = Path.Combine(rootPath, StaticData.Folder.TrialDataFolder, trialId.ToString(), taskMedicalReviewId.ToString(), StaticData.Folder.MedicalReview);
        if (!Directory.Exists(uploadFolderPath)) Directory.CreateDirectory(uploadFolderPath);
        var (trustedFileNameForFileStorage, fileRealName) = FileStoreHelper.GetStoreFileName(fileName);
        var relativePath = $"/{StaticData.Folder.IRaCISDataFolder}/{StaticData.Folder.TrialDataFolder}/{trialId}/{taskMedicalReviewId}/{StaticData.Folder.MedicalReview}/{trustedFileNameForFileStorage}";
        var serverFilePath = Path.Combine(uploadFolderPath, trustedFileNameForFileStorage);
        return (serverFilePath, relativePath, fileRealName);
    }
    //获取非dicom文件存放路径
    public static (string PhysicalPath, string RelativePath, string FileRealName) GetNoneDicomFilePath(IWebHostEnvironment _hostEnvironment, string fileName, Guid trialId, Guid siteId, Guid subjectId, Guid subjectVisitId)
    {
        var rootPath = FileStoreHelper.GetIRaCISRootDataFolder(_hostEnvironment);
        string uploadFolderPath = Path.Combine(rootPath, StaticData.Folder.TrialDataFolder, trialId.ToString(), siteId.ToString(), subjectId.ToString(), subjectVisitId.ToString(), StaticData.Folder.NoneDicomFolder);
        if (!Directory.Exists(uploadFolderPath)) Directory.CreateDirectory(uploadFolderPath);
        var (trustedFileNameForFileStorage, fileRealName) = FileStoreHelper.GetStoreFileName(fileName);
        var relativePath = $"/{StaticData.Folder.IRaCISDataFolder}/{StaticData.Folder.TrialDataFolder}/{trialId}/{siteId}/{subjectId}/{subjectVisitId}/{StaticData.Folder.NoneDicomFolder}/{trustedFileNameForFileStorage}";
        var serverFilePath = Path.Combine(uploadFolderPath, trustedFileNameForFileStorage);
        return (serverFilePath, relativePath, fileRealName);
    }
    public static string GetSubjectVisitDicomFolderPhysicalPath(IWebHostEnvironment _hostEnvironment,Guid trialId, Guid siteId, Guid subjectId, Guid subjectVisitId)
    {
        var rootPath = FileStoreHelper.GetIRaCISRootDataFolder(_hostEnvironment);
        return Path.Combine(rootPath, StaticData.Folder.TrialDataFolder, trialId.ToString(), siteId.ToString(), subjectId.ToString(), subjectVisitId.ToString(), StaticData.Folder.DicomFolder);
    }
    public static (string PhysicalPath, string RelativePath) GetDicomInstanceFilePath(IWebHostEnvironment _hostEnvironment, Guid trialId, Guid siteId, Guid subjectId, Guid subjectVisitId, Guid studyId, Guid instanceId)
    {
        var rootPath = FileStoreHelper.GetIRaCISRootDataFolder(_hostEnvironment);
        //加入访视层级  和Data
        var path = Path.Combine(rootPath, StaticData.Folder.TrialDataFolder, trialId.ToString(),
            siteId.ToString(), subjectId.ToString(), subjectVisitId.ToString(), StaticData.Folder.DicomFolder, studyId.ToString());
        if (!Directory.Exists(path))
        {
            Directory.CreateDirectory(path);
        }
        var physicalPath = Path.Combine(path, instanceId.ToString() );
        var relativePath = $"/{StaticData.Folder.IRaCISDataFolder}/{StaticData.Folder.TrialDataFolder}/{trialId}/{siteId}/{subjectId}/{subjectVisitId}/{StaticData.Folder.DicomFolder}/{studyId}/{instanceId}";
        //var physicalPath = Path.Combine(path, instanceId.ToString() + ".dcm");
        //var relativePath = $"/{StaticData.Folder.IRaCISDataFolder}/{StaticData.Folder.TrialDataFolder}/{trialId}/{siteId}/{subjectId}/{subjectVisitId}/{StaticData.Folder.DicomFolder}/{studyId}/{instanceId}.dcm";
        return (physicalPath, relativePath);
    }
   
    // 获取医生通用文件存放路径
    public static (string PhysicalPath, string RelativePath) GetDoctorOrdinaryFilePath(IWebHostEnvironment _hostEnvironment, string fileName,Guid doctorId,string attachmentType)
    {
        var rootPath = FileStoreHelper.GetIRaCISRootDataFolder(_hostEnvironment);
        //文件类型路径处理
        var uploadFolderPath = Path.Combine(rootPath, "UploadFile", doctorId.ToString(), attachmentType);
        if (!Directory.Exists(uploadFolderPath)) Directory.CreateDirectory(uploadFolderPath);
        var (trustedFileNameForFileStorage, fileRealName) = FileStoreHelper.GetStoreFileName(fileName);
        var relativePath = $"/{StaticData.Folder.IRaCISDataFolder}/{StaticData.Folder.UploadFileFolder}/{doctorId}/{attachmentType}/{trustedFileNameForFileStorage}";
        var serverFilePath = Path.Combine(uploadFolderPath, trustedFileNameForFileStorage);
        return (serverFilePath, relativePath);
    }
    public static (string PhysicalPath, string RelativePath) GetNonDoctorFilePath(IWebHostEnvironment _hostEnvironment, string fileName,  string attachmentType)
    {
        var rootPath = FileStoreHelper.GetIRaCISRootDataFolder(_hostEnvironment);
        //文件类型路径处理
        var uploadFolderPath = Path.Combine(rootPath, StaticData.Folder.UploadFileFolder, attachmentType);
        if (!Directory.Exists(uploadFolderPath)) Directory.CreateDirectory(uploadFolderPath);
        var (trustedFileNameForFileStorage, fileRealName) = FileStoreHelper.GetStoreFileName(fileName);
        var relativePath = $"/{StaticData.Folder.IRaCISDataFolder}/{StaticData.Folder.UploadFileFolder}/{attachmentType}/{trustedFileNameForFileStorage}";
        var serverFilePath = Path.Combine(uploadFolderPath, trustedFileNameForFileStorage);
        return (serverFilePath, relativePath);
    }
    
}