using ICSharpCode.SharpZipLib.Zip;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Web.UI.WebControls;

namespace ExternalDataSync.MessageHanlder
{
    public class LocalNetworkFileHelper
    {
        [DllImport("Shlwapi.dll", SetLastError = true, CharSet = CharSet.Auto)]
        public extern static bool PathFileExists(string path);
        /// <summary>
        /// 连接远程共享文件夹
        /// </summary>
        /// <param name="path">远程共享文件夹的路径</param>
        /// <param name="userName">用户名</param>
        /// <param name="passWord">密码</param>
        public static bool connectState(string path, string userName, string passWord, out string Sharefile_Error)
        {
            Sharefile_Error = "";
            bool Flag = false;
            Process proc = new Process();
            try
            {
                proc.StartInfo.FileName = "cmd.exe";
                proc.StartInfo.UseShellExecute = false;
                proc.StartInfo.RedirectStandardInput = true;
                proc.StartInfo.RedirectStandardOutput = true;
                proc.StartInfo.RedirectStandardError = true;
                proc.StartInfo.CreateNoWindow = true;
                proc.Start();
                string dosLine = "net use " + path + " " + passWord + " /user:" + userName;
                proc.StandardInput.WriteLine(dosLine);
                proc.StandardInput.WriteLine("exit");
                while (!proc.HasExited)
                {
                    proc.WaitForExit(1000);
                }
                string errormsg = proc.StandardError.ReadToEnd();
                proc.StandardError.Close();
                if (string.IsNullOrEmpty(errormsg))
                {
                    Flag = true;
                }
                else
                {
                    Sharefile_Error = errormsg;
                }
            }
            catch (Exception ex)
            {
                Sharefile_Error = ex.Message;
            }
            finally
            {
                proc.Close();
                proc.Dispose();
            }
            return Flag;
        }

        /// <summary>
        /// 从远程服务器下载文件到本地
        /// </summary>
        /// <param name="SourceFile">远程服务器路径（共享文件夹路径）</param>
        /// <param name="LocalFile">下载到本地后的文件路径</param>
        /// <param name="LocalFileName">下载到本地文件名称，包含扩展名:ABC.text</param>
        public static bool TransportRemoteToLocal(string SourceFile, string LocalFile, string LocalFileName, out string Sharefile_Error, out byte[] fileContent)
        {
            fileContent = null;
            Sharefile_Error = "";
            bool rel = false;
            try
            {

                if (Directory.Exists(LocalFile))
                {
                    Directory.Delete(LocalFile, true);
                }
                Directory.CreateDirectory(LocalFile);
                //从远程服务器下载到本地的文件
                if (LocalFile.EndsWith(@"\"))
                {
                    LocalFile = LocalFile + LocalFileName;
                }
                else
                {
                    LocalFile = LocalFile + "\\" + LocalFileName;
                }
                //远程服务器文件  此处假定远程服务器共享文件夹下确实包含本文件，否则程序报错
                FileStream inFileStream = new FileStream(SourceFile, FileMode.Open);
                FileStream outFileStream = new FileStream(LocalFile, FileMode.OpenOrCreate);
                byte[] buf = new byte[inFileStream.Length];
                int byteCount;
                while ((byteCount = inFileStream.Read(buf, 0, buf.Length)) > 0)
                {
                    outFileStream.Write(buf, 0, byteCount);
                    fileContent = new byte[buf.Length];
                    Array.Copy(buf, fileContent, buf.Length);
                }
                inFileStream.Flush();
                inFileStream.Close();
                outFileStream.Flush();
                outFileStream.Close();
                rel = true;
            }
            catch (Exception ex)
            {
                Sharefile_Error = ex.Message;
            }
            return rel;
        }

        /// <summary>
        /// 从远程服务器下载文件到本地
        /// </summary>
        /// <param name="SourceFile">远程服务器路径（共享文件夹路径）</param>
        /// <param name="LocalFile">下载到本地后的文件路径</param>
        public static bool TransportRemoteToLocal(string SourceFilePath, string LocalFilePath, out string Sharefile_Error)
        {
            Sharefile_Error = "";
            bool rel = false;
            try
            {
                if (!Directory.Exists(SourceFilePath))
                {
                    Sharefile_Error = "共享文件路径不存在！" + SourceFilePath;
                    return false;
                }
                if (!Directory.Exists(LocalFilePath))
                {
                    Directory.CreateDirectory(LocalFilePath);
                }
                IEnumerable<string> files = System.IO.Directory.EnumerateFileSystemEntries(SourceFilePath);
                if (files != null && files.Count() > 0)
                {
                    foreach (var item in files)
                    {
                        string desPath = System.IO.Path.Combine(LocalFilePath, System.IO.Path.GetFileName(item));
                        //如果是文件
                        var fileExist = System.IO.File.Exists(item);
                        if (fileExist)
                        {
                            //复制文件到指定目录下                     
                            System.IO.File.Copy(item, desPath, true);
                            continue;
                        }
                        //如果是文件夹                   
                        TransportRemoteToLocal(item, desPath, out string aaa);
                    }
                }
                rel = true;
            }
            catch (Exception ex)
            {
                Sharefile_Error = ex.Message;
            }
            return rel;
        }
        public static class DirectoryExtension
        {
            public static bool IsShareAccessible(string path)
            {

                return true;

                //Ping ping = new Ping();
                //var response = ping.Send(path, 4);


                //string errorMessage;
                //var timeStart = DateTime.Now;
                //using (var process = new Process {
                //    StartInfo = {
                //        FileName = "cmd.exe",
                //        UseShellExecute = false,
                //        RedirectStandardInput = true,
                //        RedirectStandardOutput = true,
                //        CreateNoWindow = true,
                //        RedirectStandardError = true
                //    }
                //})
                //{
                //    process.Start();
                //    process.StandardInput.AutoFlush = true;
                //    process.StandardInput.WriteLine(@"net use " + path);
                //    process.StandardInput.WriteLine("exit");
                //    errorMessage = process.StandardError.ReadToEnd();
                //    process.WaitForExit();
                //    if (string.IsNullOrEmpty(errorMessage))
                //    {
                //        return true;
                //    }
                //    else
                //    {
                //        return false;
                //    }
                //}
            }

            public static bool FtpFolderExists(string folderPath, string username, string password)
            {
                FtpWebRequest request = (FtpWebRequest)WebRequest.Create(folderPath);
                request.Credentials = new NetworkCredential(username, password);
                request.Method = WebRequestMethods.Ftp.ListDirectory;

                try
                {
                    using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
                    {
                        return true; // 如果成功获取响应，则文件夹存在
                    }
                }
                catch (WebException ex)
                {
                    return false; // 文件夹不存在
                }
            }

        }
        /// <summary>
        /// 从远程服务器下载文件到本地
        /// </summary>
        /// <param name="SourceFile">远程服务器路径（共享文件夹路径）</param>
        /// <param name="LocalFile">下载到本地后的文件路径</param>
        /// <param name="LocalFileName">下载到本地文件名称，包含扩展名:ABC.text</param>
        public static bool TransportRemoteToLocalZip(string SourceFile, string LocalFile, string LocalFileName, string zipedFolder, out string Sharefile_Error)
        {
            Sharefile_Error = "";
            bool rel = false;
            try
            {
                //远程服务器文件  此处假定远程服务器共享文件夹下确实包含本文件，否则程序报错
                FileStream inFileStream = new FileStream(SourceFile, FileMode.Open);
                if (Directory.Exists(LocalFile))
                {
                    Directory.Delete(LocalFile, true);
                }
                Directory.CreateDirectory(LocalFile);
                //从远程服务器下载到本地的文件
                if (LocalFile.EndsWith(@"\"))
                {
                    LocalFile = LocalFile + LocalFileName;
                }
                else
                {
                    LocalFile = LocalFile + "\\" + LocalFileName;
                }

                FileStream outFileStream = new FileStream(LocalFile, FileMode.OpenOrCreate);
                byte[] buf = new byte[inFileStream.Length];
                int byteCount;
                while ((byteCount = inFileStream.Read(buf, 0, buf.Length)) > 0)
                {
                    outFileStream.Write(buf, 0, byteCount);
                }
                inFileStream.Flush();
                inFileStream.Close();
                outFileStream.Flush();
                outFileStream.Close();

                ZipHelper.UnZip(LocalFile, zipedFolder);
                rel = true;
            }
            catch (Exception ex)
            {
                Sharefile_Error = ex.Message;
            }
            return rel;
        }

        /// <summary>
        /// 将本地文件上传到远程服务器共享目录
        /// </summary>
        /// <param name="SourceFile">本地文件的绝对路径，包含扩展名</param>
        /// <param name="RemoteFile">远程服务器共享文件路径，不包含文件扩展名</param>
        /// <param name="RemoteFileName">上传到远程服务器后的文件扩展名</param>
        public static bool TransportLocalToRemote(string SourceFile, string RemoteFile, string RemoteFileName, out string Sharefile_Error)    //src
        {
            Sharefile_Error = "";
            //string SourceFile, string LocalFile, string LocalFileName
            bool rel = false;
            try
            {
                FileStream inFileStream = new FileStream(SourceFile, FileMode.Open);    //此处假定本地文件存在，不然程序会报错   
                if (!Directory.Exists(RemoteFile))        //判断上传到的远程服务器路径是否存在
                {
                    Directory.CreateDirectory(RemoteFile);
                }
                //上传到远程服务器共享文件夹后文件的绝对路径
                if (!RemoteFile.EndsWith(@"\"))
                {
                    RemoteFile = RemoteFile + RemoteFileName;
                }
                else
                {
                    RemoteFile = RemoteFile + "\\" + RemoteFileName;
                }
                FileStream outFileStream = new FileStream(RemoteFile, FileMode.OpenOrCreate);
                byte[] buf = new byte[inFileStream.Length];
                int byteCount;
                while ((byteCount = inFileStream.Read(buf, 0, buf.Length)) > 0)
                {
                    outFileStream.Write(buf, 0, byteCount);
                }
                inFileStream.Flush();
                inFileStream.Close();
                outFileStream.Flush();
                outFileStream.Close();
                rel = true;
            }
            catch (Exception ex)
            {
                Sharefile_Error = ex.Message;
            }
            return rel;
        }
    }
}
