using System;
using System.Collections.Generic;
using System.Net;
using System.IO;
using System.Threading;

namespace Common
{
    public class FtpAux2
    {
        private string strFilePath = System.Environment.CurrentDirectory;//路径
        private string _remote_path = "";
        //private string FtpIP = "192.1.3.240";//192.1.3.240
        public string IP { get; set; }
        public string RemotePath
        {
            get { return _remote_path; }
            set
            {
                _remote_path = value;
                if (!_remote_path.EndsWith("/")) _remote_path += "/";
            }
        }
        public string UserName { get; set; }
        public string Password { get; set; }
        public string LocalPath { get; set; }
        public bool Passive { get; set; }
        public bool Binary { get; set; }

        public FtpAux2()
        {
            IP = AppConfigCache.ftpIp;
            Passive = true;
            _remote_path = "";
            LocalPath = "c:/";
            UserName = AppConfigCache.ftpUid;
            Password = AppConfigCache.ftpPwd;
            Binary = true;
        }
        public void DownLoadFile(string filename)
        {

            Uri uri = new Uri("ftp://" + IP + RemotePath + filename);
            FtpWebRequest req = (FtpWebRequest)WebRequest.Create(uri);
            req.Method = WebRequestMethods.Ftp.DownloadFile;
            req.UseBinary = Binary;
            req.UsePassive = Passive;
            req.Credentials = new NetworkCredential(UserName, Password);
            using (FtpWebResponse res = (FtpWebResponse)req.GetResponse())
            {
                string localfile = Path.Combine(LocalPath, filename);
                FileStream fs = new FileStream(localfile, FileMode.Create, FileAccess.Write);
                int buffer = 1024;  //1K缓冲   
                byte[] b = new byte[buffer];
                int i = 0;
                Stream stream = res.GetResponseStream();
                while ((i = stream.Read(b, 0, buffer)) > 0)
                {
                    fs.Write(b, 0, i);
                }

                fs.Flush();
                fs.Close();
            }
        }
        /// <summary>
        /// 创建一个目录
        /// </summary>
        public void CreateDirectory()
        {
            try
            {
                FileInfo fi = new FileInfo(RemotePath);
                Uri uri = new Uri("ftp://" + IP + RemotePath);
                List<string> list = new List<string>();
                FtpWebRequest req = (FtpWebRequest)WebRequest.Create(uri); //
                req.Credentials = new NetworkCredential(UserName, Password);
                req.Method = WebRequestMethods.Ftp.MakeDirectory;
                req.UseBinary = Binary;
                FtpWebResponse res = (FtpWebResponse)req.GetResponse();
                GetFileList();
            }
            catch (Exception exp)
            {

            }
        }
        /// <summary>   
        /// 获取FTP文件列表 /jldata/ftppicture/
        /// </summary>   
        /// <returns></returns>   
        public List<String> GetFileList()
        {

            List<string> list = new List<string>();
            try
            {
                FtpWebRequest req = (FtpWebRequest)WebRequest.Create(new Uri("ftp://" + IP + RemotePath)); //
                req.Credentials = new NetworkCredential(UserName, Password);
                req.Method = WebRequestMethods.Ftp.ListDirectory;
                req.UseBinary = Binary;
                req.UsePassive = Passive;
                using (FtpWebResponse res = (FtpWebResponse)req.GetResponse())
                {
                    using (StreamReader sr = new StreamReader(res.GetResponseStream()))
                    {
                        string s;
                        while ((s = sr.ReadLine()) != null)
                        {
                            list.Add(s);
                        }
                    }
                }
                return list;
            }
            catch (Exception exp)
            {
                CreateDirectory();
                return list;
            }

        }

        public void UploadFile(string localFile)
        {

            FileInfo fi = new FileInfo(localFile);
            FileStream fs = fi.OpenRead();
            long length = fs.Length;

            FtpWebRequest req = (FtpWebRequest)WebRequest.Create("ftp://" + IP + RemotePath + fi.Name);
            req.Credentials = new NetworkCredential(UserName, Password);
            req.Method = WebRequestMethods.Ftp.UploadFile;
            req.UseBinary = Binary;
            req.ContentLength = length;
            req.Timeout = 10 * 1000;
            Stream stream = req.GetRequestStream();
            int BufferLength = 2048; //2K   
            byte[] b = new byte[BufferLength];
            int i;

            while ((i = fs.Read(b, 0, BufferLength)) > 0)
            {
                stream.Write(b, 0, i);
            }
            stream.Close();
            stream.Dispose();
            fs.Close();
        }

        public void UploadFile(string fileName, byte[] data)
        {
            long length = data.Length;
            FtpWebRequest req = (FtpWebRequest)WebRequest.Create("ftp://" + IP + RemotePath + fileName);
            req.Credentials = new NetworkCredential(UserName, Password);
            req.Method = WebRequestMethods.Ftp.UploadFile;
            req.UseBinary = Binary;
            req.ContentLength = length;
            req.Timeout = 10 * 1000;
            Stream stream = req.GetRequestStream();
            stream.Write(data, 0, data.Length);
            stream.Close();
            stream.Dispose();
        }
        /// <summary>
        /// FTP图片上传
        /// </summary>
        /// <param name="strPath"></param>
        /// <param name="strWgtNo"></param>
        public bool FtpUp(string strPath, string strWgtNo)
        {
            try
            {
                Thread.Sleep(500);
                LocalPath = "d:/";
                UserName = "ftpuser";
                Password = "admin_2019";//ftpuser    admin_2019
                //ftp.RemotePath = "//home/xgkftp/image/" + DateTime.Now.ToString("yyyy-MM-dd");///home/xgkftp/image/
                RemotePath = "//Image/mcms/testCAR/" + DateTime.Now.ToString("yyyy-MM-dd");//RemotePath
                GetFileList();
                string[] arrayFileImage = new string[6];

                for (int i = 1; i < 8; i++)
                {
                    string strPathImage = strPath + "_" + i.ToString() + ".jpg";
                    if (File.Exists(strPathImage))
                    {//存在的图片进行上传操作
                        UploadFile(strPathImage);
                        WriteLog("图片上传后，进行删除操作，图片路径：" + strPathImage);
                        File.Delete(strPathImage);
                    }
                    //else
                    //{//未截图成功的，也上传一个图片
                    //    File.Copy(strFilePath + "\\image\\null.jpg", strPathImage);
                    //    UploadFile(strPathImage);
                    //}
                    arrayFileImage[i - 1] = RemotePath + strWgtNo + "_" + i.ToString() + ".jpg";
                }
                return true;
            }
            catch (Exception exp)
            {
                WriteLog("FTP图片上传失败！" + strPath + exp.Message + exp.StackTrace);
                return false;
            }
        }
        private void WriteLog(string str)
        {
            if (System.IO.Directory.Exists(strFilePath + "\\log") == false)
            {
                System.IO.Directory.CreateDirectory(strFilePath + "\\log");
            }
            string strDate = System.DateTime.Now.ToString("yyyyMMdd");
            System.IO.TextWriter tw = new System.IO.StreamWriter(strFilePath + "\\log\\" + "FTP_" + strDate + ".log", true);

            tw.WriteLine(System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            tw.WriteLine(str);
            tw.WriteLine("\r\n");

            tw.Close();
        }
    }
}
