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

namespace MeterPlugInLibrary
{
    public class VSFTPHelper
    {
        #region 字段或属性
        public string IP { get; set; }
        public string UserName { get; set; }
        public string Password { get; set; }
        public bool Passive { get; set; }
        public bool Binary { get; set; }
        #endregion

        #region 构造
        /// <summary>
        /// 构造
        /// </summary>
        public VSFTPHelper()
        {
            IP = AppConfigCache.ftpIp;
            Passive = true;
            UserName = "";
            Password = "";
            Binary = true;
            WriteLog(string.Format("VSFTP参数设定: {0} {1} {2}", IP, UserName, Password));
        }

        public VSFTPHelper(string ip,string userNmae, string password )
        {
            IP = ip;
            Passive = true;
            UserName = userNmae;
            Password = password;
            Binary = true;
            WriteLog(string.Format("VSFTP参数设定: {0} {1} {2}", IP, UserName, Password));
        }
        #endregion

        #region 创建文件夹
        /// <summary>
        /// 创建一个目录
        /// </summary>
        public void CreateDirectory(string filesUrl)
        {
            try
            {
                Uri uri = new Uri("ftp://" + IP + AppConfigCache.ftpPath + filesUrl);
                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(filesUrl); //假如创建不成功，反复调用。。。
            }
            catch (Exception exp)
            {
                //WriteLog("FTP图片上传失败CreateDirectory创建一个目录！" + exp.Message);
            }
        }

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

            List<string> list = new List<string>();
            try
            {
                FtpWebRequest req = (FtpWebRequest)WebRequest.Create(new Uri("ftp://" + IP + AppConfigCache.ftpPath + "/" + filesUrl)); //
                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);
                        }
                    }
                }
                //这里的list是文件夹下的文件信息

                return list;
            }
            catch (Exception exp)
            {
                CreateDirectory(filesUrl);
                return list;
            }

        }
        #endregion

        #region 上传文件
        /// <summary>
        /// FTP图片上传
        /// </summary>
        /// <param name="localPath">本地文件夹路径</param>
        public bool FtpUp(string localPath)
        {
            try
            {
                //创建文件夹
                CreateDirectory(DateTime.Now.ToString("yyyy-MM-dd"));
                //上传文件
                UploadFile(localPath);
                
                //未截图成功的，也上传一个图片
                //File.Copy(strFilePath + "\\image\\null.jpg", strPathImage);
                //UploadFile(strPathImage);
                return true;
            }
            catch (Exception exp)
            {
                WriteLog("FTP图片上传失败！" + exp.Message);
                return false;
            }
        }

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="localPath"></param>
        private void UploadFile(string localPath)
        {
            FileInfo fi = new FileInfo(localPath);
            FileStream fs = fi.OpenRead();
            long length = fs.Length;

            FtpWebRequest req = (FtpWebRequest)WebRequest.Create("ftp://" + IP + AppConfigCache.ftpPath + DateTime.Now.ToString("yyyy-MM-dd") + "/" + 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();
        }
#endregion

#region 写日志
        private static void WriteLog(string str)
        {
            string m_szRunPath;
            try
            {
                m_szRunPath = System.Environment.CurrentDirectory;
                if (System.IO.Directory.Exists(m_szRunPath + "\\log") == false)
                {
                    System.IO.Directory.CreateDirectory(m_szRunPath + "\\log");
                }
                string strDate = System.DateTime.Now.ToString("yyyyMMdd");
                string strPathFile = m_szRunPath + "\\log\\" + strDate;
                if (!Directory.Exists(strPathFile))//如果不存在就创建file文件夹
                {
                    Directory.CreateDirectory(strPathFile);
                }
                System.IO.TextWriter tw = new System.IO.StreamWriter(strPathFile + "\\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();
            }
            catch { }
        }
#endregion
    }
}
