using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace XmlDucumentAnalysis
{
    public class FtpHelper
    {

        /// <summary>
        /// 初始ftp路径
        /// </summary>
        public static string initFtpPath = ConfigurationManager.AppSettings["xmlBasePath"];



        /// <summary>  
        /// 单个文件下载方法  
        /// </summary>  
        /// <param name="localPath">保存文件的本地路径</param>  
        /// <param name="ftpPath">下载文件的FTP路径</param>  
        public void Download(string ftpPath, string localSavePath)
        {
            try
            {
                //FileMode常数确定如何打开或创建文件,指定操作系统应创建新文件。  
                //FileMode.Create如果文件已存在，它将被改写  
                string fileName = ftpPath.Substring(ftpPath.LastIndexOf("/")+1);
                string downloadFilePath = Path.Combine(localSavePath, fileName);  // Replace "file.txt" with the actual file name
                FileStream fs = new FileStream(downloadFilePath, FileMode.Create);
                FtpWebRequest downRequest = (FtpWebRequest)WebRequest.Create(new Uri(ftpPath));
                //设置要发送到 FTP 服务器的命令  
                downRequest.Method = WebRequestMethods.Ftp.DownloadFile;
                FtpWebResponse response = (FtpWebResponse)downRequest.GetResponse();
                Stream ftpStream = response.GetResponseStream();
                long cl = response.ContentLength;
                int bufferSize = 2048;
                int readCount;
                byte[] buffer = new byte[bufferSize];
                readCount = ftpStream.Read(buffer, 0, bufferSize);
                while (readCount > 0)
                {
                    fs.Write(buffer, 0, readCount);
                    readCount = ftpStream.Read(buffer, 0, bufferSize);
                }
                ftpStream.Close();
                fs.Close();
                response.Close();
            }
            catch (Exception ee)
            {
                Console.WriteLine("Download方法异常:" + ee.ToString());
            }
        }


        /// <summary>
        /// 整个文件夹的文件及子目录 下载方法
        /// </summary>
        /// <param name="ftpPath">FTP路径</param>
        /// <param name="localSavePath">保存的本地路径</param>
        public void DownFtp(string ftpPath, string localSavePath)
        {
            try
            {

                string downloadDir = localSavePath;
                string ftpdir = ftpPath;
                List<string> fullname = GetDirctory(ftpdir);
                // 如果不存在 则创建新的目录
                if (!Directory.Exists(downloadDir))
                {
                    Directory.CreateDirectory(downloadDir);
                }
                if (fullname == null || fullname.Count == 0)
                {
                    return;
                }
                foreach (string names in fullname)
                {
                    if (names.Trim() == "")
                    {
                        continue;
                    }
                    //判断是否具有文件夹标识<DIR>或者names的首字符是d  （两者均表示此路径是文件夹而非文件）
                    if (!names.Contains("."))
                    {
                        DownFtp(ftpdir + names + "/", downloadDir + "\\" + names);
                    }
                    else
                    {
                        string fileFullName = ftpdir + names;
                        //在本地查找是否已存在此文件，若已存在，则不再下载
                        if (File.Exists(localSavePath+"\\"+names))
                        {
                            Log.Info(names+"已存在");
                        }
                        Download(fileFullName, downloadDir);
                    }

                }
            }
            catch (Exception ee)
            {
                Console.WriteLine("异常信息:" + ee.ToString());
            }
        }
        /// 清空指定的文件夹(包括子目录文件夹)，但不删除文件夹  
        /// </summary>  
        /// <param name="dir">指定目录</param>  
        public static void DeleteFolder(string dir)
        {
            foreach (string d in Directory.GetFileSystemEntries(dir))
            {
                if (System.IO.File.Exists(d))
                {
                    FileInfo fi = new FileInfo(d);
                    if (fi.Attributes.ToString().IndexOf("ReadOnly") != -1)
                        fi.Attributes = FileAttributes.Normal;
                    System.IO.File.Delete(d);//直接删除其中的文件    
                }
                else
                {
                    DirectoryInfo d1 = new DirectoryInfo(d);
                    if (d1.GetFiles().Length != 0 || d1.GetDirectories().Length != 0)
                    {
                        DeleteFolder(d1.FullName); // 递归删除子文件夹
                    }
                    Directory.Delete(d);
                }
            }
        }

        /// <summary>
        /// 从ftp服务器上获得文件夹列表
        /// </summary>
        /// <param name="RequedstPath">服务器下的相对路径</param>
        /// <returns></returns>
        public List<string> GetDirctory(string RequedstPath)
        {
            Log.Debug("开始获取"+RequedstPath+"列表");
            List<string> strs = new List<string>();
            try
            {
                string uri = RequedstPath;   //目标路径 path为服务器地址
                FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
                // ftp用户名和密码
                reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
                WebResponse response = reqFTP.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream());//中文文件名
                string line = reader.ReadLine();
                while (line != null)
                {   
                    string temp = line.Substring(line.LastIndexOf(" ")+1);
                    string temp1 = line.Substring(0, 1);
                    if (line.Contains("<DIR>"))
                    {
                        string msg = line.Substring(line.LastIndexOf("<DIR>") + 5).Trim();
                        strs.Add(msg);
                    } else if (temp1.Equals("d") && temp!="." && temp!="..")
                    {
                        strs.Add(temp);
                    }else if (!temp1.Equals("d"))
                    {
                        strs.Add(temp);
                    }
                    line = reader.ReadLine();
                }
                reader.Close();
                response.Close();
                return strs;
            }
            catch (Exception ex)
            {
                Console.WriteLine("获取目录出错：" + ex.Message);
            }
            return strs;
        }
    }
}
