using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using HtmlAgilityPack;
using System.Linq;
using System.Diagnostics;
class Update
{
    public void Update1()
    {
        string iisServerBaseUrl = "http://192.168.202.23:8080/"; // IIS服务器基本URL
        string iisFolder = ""; // IIS服务器上的文件夹路径
        string localFolderBase = @"D:\"; // 本地文件夹的基本路径
        string localFolder = FindLocalFolder(localFolderBase);
        SynchronizeFiles(iisServerBaseUrl, iisFolder, localFolder);

        // 继续运行应用程序的主要逻辑
        Console.WriteLine("应用程序启动...");
        // 在这里添加你的应用程序的主要逻辑

        Console.ReadLine();
    }

    public string FindLocalFolder(string localFolderBase)
    {
        for (int i = 1; i <= 8; i++)
        {
            string localFolder = Path.Combine(localFolderBase, $"C{i}");

            if (Directory.Exists(localFolder))
            {
                return localFolder;
            }
        }

        return null;
    }

    public void SynchronizeFiles(string serverBaseUrl, string serverFolder, string localFolder)
    {
        using (HttpClient client = new HttpClient())
        {
            try
            {
                HttpResponseMessage response = client.GetAsync(new Uri(serverBaseUrl + serverFolder)).Result;
                response.EnsureSuccessStatusCode();

                string responseContent = response.Content.ReadAsStringAsync().Result;

                // 使用HtmlAgilityPack解析HTML内容
                HtmlDocument doc = new HtmlDocument();
                doc.LoadHtml(responseContent);

                // 查找所有包含文件名和文件夹名的<a>标签
                var links = doc.DocumentNode.SelectNodes("//a");

                if (links != null)
                {
                    foreach (var link in links)
                    {
                        string itemName = link.InnerText;
                        string itemUrl = serverBaseUrl + serverFolder + itemName;
                        string localPath = Path.Combine(localFolder, itemName);

                        if (link.InnerText.StartsWith("<dir>"))
                        {
                            // 这是一个文件夹
                            if (!Directory.Exists(localPath))
                            {
                                Directory.CreateDirectory(localPath);
                            }

                            // 递归处理文件夹中的内容
                            SynchronizeFiles(serverBaseUrl, serverFolder + itemName + "/", localPath);
                        }
                        else
                        {
                            // 这是一个文件
                            if (!string.Equals(itemName, "web.config", StringComparison.OrdinalIgnoreCase))
                            {
                                // 检查文件类型是否需要更新
                                string fileExtension = Path.GetExtension(itemName).ToLower();
                                if (ShouldUpdateFile(fileExtension))
                                {
                                    if (File.Exists(localPath))
                                    {
                                        bool filesAreEqual = AreFilesEqual(itemUrl, localPath);

                                        if (!filesAreEqual)
                                        {
                                            DownloadFile(itemUrl, localPath);
                                            Console.WriteLine($"已下载并覆盖文件: {itemName}");
                                        }
                                        else
                                        {
                                            Console.WriteLine($"该文件为最新版本: {itemName}!!!");
                                        }
                                    }
                                    else
                                    {
                                        DownloadFile(itemUrl, localPath);
                                        Console.WriteLine($"已下载文件: {itemName}");
                                    }
                                }
                                else
                                {
                                    Console.WriteLine($"不需要更新的文件类型: {fileExtension}");
                                }
                            }
                        }
                    }
                    // 在配置文件更新后，执行以下代码重启程序
                    Process.Start("Up.bat");
                }
                else
                {
                    Console.WriteLine("未找到文件列表");
                }
            }
            catch (HttpRequestException ex)
            {
                Console.WriteLine($"HTTP请求失败: {ex.Message}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"发生错误: {ex.Message}");
            }
        }
    }

    public bool ShouldUpdateFile(string fileExtension)
    {
        // 添加需要更新的文件类型
        string[] allowedExtensions = { ".exe", ".dll", ".json", ".xml" };

        // 如果文件类型在允许更新的文件类型列表中，则返回 true，否则返回 false
        return allowedExtensions.Contains(fileExtension);
    }




    public void DownloadFile(string fileUrl, string localFilePath)
    {
        using (HttpClient client = new HttpClient())
        {
            try
            {
                HttpResponseMessage response = client.GetAsync(new Uri(fileUrl)).Result;
                response.EnsureSuccessStatusCode();

                using (Stream contentStream = response.Content.ReadAsStreamAsync().Result)
                {
                    using (Stream fileStream = File.Create(localFilePath))
                    {
                        contentStream.CopyTo(fileStream);
                    }
                }

                Console.WriteLine($"已成功下载文件: {localFilePath}");
            }
            catch (HttpRequestException ex)
            {
                // 处理连接断开或其他HTTP请求错误
                Console.WriteLine($"HTTP请求失败: {ex.Message}");
                // 在这里可以添加重试逻辑或其他处理方式
            }
            catch (Exception ex)
            {
                Console.WriteLine($"发生错误: {ex.Message}");
            }
        }
    }


    public bool AreFilesEqual(string file1Url, string file2Path)
    {
        byte[] file1Content = File.ReadAllBytes(file2Path);

        using (HttpClient client = new HttpClient())
        {
            byte[] file2Content = client.GetByteArrayAsync(file1Url).Result;

            return StructuralComparisons.StructuralEqualityComparer.Equals(file1Content, file2Content);
        }
    }
}
