using IRaCIS.Application.Interfaces;
using System.Text;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using IRaCIS.Core.Infrastructure;
using IRaCIS.Core.Application.Helper;
using Microsoft.AspNetCore.Hosting;

namespace IRaCIS.Application.Services
{
    public class FileService : IFileService
    {

        private readonly IDoctorService _doctorService;
        private readonly IAttachmentService _attachmentService;
        private readonly IWebHostEnvironment _hostEnvironment;
        private string defaultUploadFilePath = string.Empty;
        private readonly ILogger<FileService> _logger;
        public FileService(IDoctorService doctorService, IAttachmentService attachmentService,
            IWebHostEnvironment hostEnvironment, ILogger<FileService> logger)
        {
            _doctorService = doctorService;
            _attachmentService = attachmentService;
            _hostEnvironment = hostEnvironment;

            defaultUploadFilePath = FileStoreHelper.GetIRaCISRootPath(_hostEnvironment);
            _logger = logger;
        }

        /// <summary>
        ///  打包医生官方简历
        /// </summary>
        /// <param name="language"></param>
        /// <param name="doctorIds"></param>
        /// <returns></returns>
        public async Task<string> CreateOfficialResumeZip(int language, Guid[] doctorIds)
        {

            //准备下载文件的临时路径
            var guidStr = Guid.NewGuid().ToString();

            string uploadFolderPath = Path.Combine(FileStoreHelper.GetIRaCISRootDataFolder(_hostEnvironment), "UploadFile");

         

            var tempSavePath = Path.Combine(uploadFolderPath, "temp", guidStr); //待压缩的文件夹,将需要下载的文件拷贝到此文件夹
            if (!Directory.Exists(tempSavePath))
            {
                Directory.CreateDirectory(tempSavePath);
            }

            //找到服务器简历路径 循环拷贝简历到临时路径
            foreach (var doctorId in doctorIds)
            {
                var doctor = await _doctorService.GetBasicInfo(doctorId);
                var doctorName = doctor.FirstName + "_" + doctor.LastName;

                //找官方简历存在服务器的相对路径
                var sourceCvPath = await _attachmentService.GetDoctorOfficialCV(language, doctorId);
                if (!string.IsNullOrWhiteSpace(sourceCvPath))
                {
                    //服务器简历文件实际路径
                    //var sourceCvFullPath = HostingEnvironment.MapPath(sourceCvPath);
                    var sourceCvPathTemp = sourceCvPath.Substring(1, sourceCvPath.Length - 1);//.Replace('/','\\');
                    string sourceCvFullPath = Path.Combine(defaultUploadFilePath, sourceCvPathTemp);

                    var arr = sourceCvPath.Split('.');
                    string extensionName = arr[arr.Length - 1]; //得到扩展名

                    //需要拷贝到的路径
                    var doctorPath = Path.Combine(tempSavePath, doctor.ReviewerCode.ToString() + "_" + doctorName + "." + extensionName);

                    if (File.Exists(sourceCvFullPath))
                    {
                        File.Copy(sourceCvFullPath, doctorPath, true);
                    }
                }
            }

            //创建ZIP
            DateTime now = DateTime.Now;
            StringBuilder sb = new StringBuilder();
            sb.Append(now.Year).Append(now.Month.ToString().PadLeft(2, '0')).Append(now.Day.ToString().PadLeft(2, '0'))
                .Append(now.Hour.ToString().PadLeft(2, '0')).Append(now.Minute.ToString().PadLeft(2, '0'))
                .Append(now.Second.ToString().PadLeft(2, '0')).Append(now.Millisecond.ToString().PadLeft(3, '0'));

            string targetZipPath = Path.Combine(uploadFolderPath, "CV_" + sb.ToString() + ".zip");
            ZipHelper.CreateZip(tempSavePath, targetZipPath);

            //返回Zip路径
            return Path.Combine("/IRaCISData/UploadFile/", "CV_" + sb.ToString() + ".zip");
        }

        /// <summary>
        /// 打包医生的所有附件
        /// </summary>
        /// <param name="doctorIds"></param>
        /// <returns></returns>
        public async Task<string> CreateDoctorsAllAttachmentZip(Guid[] doctorIds)
        {
            //准备下载文件的临时路径
            var guidStr = Guid.NewGuid().ToString();
            //string uploadFolderPath = HostingEnvironment.MapPath("/UploadFile/");
            string uploadFolderPath = Path.Combine(FileStoreHelper.GetIRaCISRootDataFolder(_hostEnvironment), "UploadFile");
            var tempSavePath = Path.Combine(uploadFolderPath, "temp", guidStr); //待压缩的文件夹,将需要下载的文件拷贝到此文件夹
            if (!Directory.Exists(tempSavePath))
            {
                Directory.CreateDirectory(tempSavePath);
            }


            foreach (var doctorId in doctorIds)
            {
                //获取医生基本信息
                var doctor = await _doctorService.GetBasicInfo(doctorId);
                var doctorName = doctor.FirstName + "_" + doctor.LastName;
                var doctorCode = doctor.ReviewerCode;

                var doctorDestPath = Path.Combine(tempSavePath, doctorCode + "_" + doctorName);
                if (!Directory.Exists(doctorDestPath))
                {
                    Directory.CreateDirectory(doctorDestPath);
                }

                //服务器上传后的源路径
                string doctorFileSourcePath = Path.Combine(uploadFolderPath, doctorId.ToString());

                if (Directory.Exists(doctorFileSourcePath))
                {
                    CopyDirectory(doctorFileSourcePath, doctorDestPath);
                }
            }
            string target = Guid.NewGuid().ToString();
            string targetPath = Path.Combine(uploadFolderPath, target + ".zip");
            ZipHelper.CreateZip(tempSavePath, targetPath);
            return Path.Combine("/IRaCISData/UploadFile/", target + ".zip");
        }


        public async Task<string> CreateZipPackageByAttachment(Guid doctorId, Guid[] attachmentIds)
        {
            var doctor = await _doctorService.GetBasicInfo(doctorId);
            var doctorName = doctor.FirstName + "_" + doctor.LastName;

            Guid temp = Guid.NewGuid();
            //string root = HostingEnvironment.MapPath("/UploadFile/"); //文件根目录
            string root = Path.Combine(defaultUploadFilePath, "UploadFile");

            var tempPath = Path.Combine(root, "temp", temp.ToString(), doctor.ReviewerCode + doctorName); //待压缩的文件夹,将需要下载的文件拷贝到此文件夹
            var packagePath = Path.Combine(root, "temp", temp.ToString()); //打包目录
            if (!Directory.Exists(tempPath))
            {
                Directory.CreateDirectory(tempPath);
            }
            var attachemnts = (await _attachmentService.GetAttachments(doctorId)).Where(a => attachmentIds.Contains(a.Id));

            foreach (var item in attachemnts)
            {
                var arr = item.Path.Trim().Split('/');
                var myPath = string.Empty;
                var myFile = string.Empty;
                //需要改进
                if (arr.Length > 0)
                {
                    myFile = arr[arr.Length - 1];
                    foreach (var arrItem in arr)
                    {
                        if (arrItem != string.Empty && !"UploadFile".Equals(arrItem))
                        {
                            myPath += (arrItem + "/");
                        }
                    }
                    myPath = myPath.TrimEnd('/');
                }
                var sourcePath = Path.Combine(root, myPath);

                if (!string.IsNullOrWhiteSpace(sourcePath) && File.Exists(sourcePath))
                {
                    File.Copy(sourcePath, Path.Combine(tempPath, myFile), true);
                }
            }
            string target = Guid.NewGuid().ToString();
            string targetPath = Path.Combine(root, target + ".zip");
            ZipHelper.CreateZip(packagePath, targetPath);

            return Path.Combine("/IRaCISData/UploadFile/", target + ".zip");
        }

        private static void CopyDirectory(string srcPath, string destPath)
        {

            DirectoryInfo dir = new DirectoryInfo(srcPath);
            FileSystemInfo[] fileInfoArray = dir.GetFileSystemInfos();  //获取目录下(不包含子目录)的文件和子目录
            foreach (FileSystemInfo fileInfo in fileInfoArray)
            {
                if (fileInfo is DirectoryInfo)     //判断是否文件夹
                {
                    if (!Directory.Exists(destPath + "\\" + fileInfo.Name))
                    {
                        Directory.CreateDirectory(destPath + "\\" + fileInfo.Name);   //目标目录下不存在此文件夹即创建子文件夹
                    }
                    CopyDirectory(fileInfo.FullName, destPath + "\\" + fileInfo.Name);    //递归调用复制子文件夹
                }
                else
                {
                    File.Copy(fileInfo.FullName, destPath + "\\" + fileInfo.Name, true);      //不是文件夹即复制文件,true表示可以覆盖同名文件
                }
            }

        }
    }
}