using MeterVision.Util;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace MeterVision.Upgrade
{
    /// <summary>
    /// WndUpdateAsk.xaml 的交互逻辑
    /// </summary>
    public partial class WndUpdateAsk : Window
    {
        private UpgradeModel UpgradeModel;
        private WebClient downWebClient = new WebClient();

        public WndUpdateAsk(UpgradeModel upgradeModel)
        {
            InitializeComponent();
            UpgradeModel = upgradeModel;
            txtNewVersion.Text = $"发现新版本 V{upgradeModel.VersionCode}";
            txtInfo.Text = upgradeModel.Updates;
        }


        private void Border_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if(e.LeftButton == MouseButtonState.Pressed)
            {
                DragMove();
            }
        }

        private void BtnIgnore_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void BtnUpdate_Click(object sender, RoutedEventArgs e)
        {
            // 设置下载进度事件
            downWebClient.DownloadProgressChanged += DownWebClient_DownloadProgressChanged;
            downWebClient.DownloadFileCompleted += DownWebClient_DownloadFileCompleted;

            string srcdownFile = Path.Combine(UpgradeHelper.UpgradeUrl, UpgradeModel.ApkName);
            string localFileFolderPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "upgrade");

            // 确保文件夹存在
            if (!Directory.Exists(localFileFolderPath))
            {
                Directory.CreateDirectory(localFileFolderPath);
            }

            string desdownFile = Path.Combine(localFileFolderPath, UpgradeModel.ApkName);

            try
            {
                pnlUpdate.Visibility = Visibility.Collapsed;
                pnlProgress.Visibility = Visibility.Visible;
                downWebClient.DownloadFileAsync(new Uri(srcdownFile), desdownFile,desdownFile);
            }
            catch(WebException ex)
            {
                MessageBox.Show(ex.Message);
                pnlUpdate.Visibility = Visibility.Visible;
                pnlProgress.Visibility = Visibility.Collapsed;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"发生意外错误: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                pnlUpdate.Visibility = Visibility.Visible;
                pnlProgress.Visibility = Visibility.Collapsed;
            }
        }

        private void DownWebClient_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            downWebClient.Dispose();  // 清理资源

            if (e.Error != null)
            {
                MessageBox.Show(e.Error.Message);
                pnlUpdate.Visibility = Visibility.Visible;
                pnlProgress.Visibility = Visibility.Collapsed;
                return;
            }

            try
            {

                string desDownFile = e.UserState.ToString();
                string zipPath = System.IO.Path.GetDirectoryName(desDownFile);
                //string zipPath = AppDomain.CurrentDomain.BaseDirectory;
                ICSharpCode.SharpZipLib.ZipHelper.UnZip(desDownFile, zipPath, "", true);

                string downPath = Path.GetDirectoryName(desDownFile);

                File.Delete(desDownFile);
                MessageBox.Show("升级完成，将自动重新启动程序。", "提示", MessageBoxButton.OK, MessageBoxImage.Information);

                RestartApp(zipPath);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);    
            }
            //move mydown_ty.exe c:\my.exe
        }

        private void DownWebClient_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            // 使用 Dispatcher 来确保在主线程中更新 UI
            Dispatcher.BeginInvoke(new Action(() =>
            {
                downProgress.Value = e.ProgressPercentage;
                txtProgress.Text = $"已下载 {e.ProgressPercentage}%";
            }));
        }

        //移动下载好的文件并启动exe
        private static void RestartApp(string zipPath)
        {
            string baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
            StringBuilder sb = new StringBuilder();
            sb.Append(@" /C ping 1.1.1.1 -n 1 -w 1000 > Nul");
            sb.Append($" & MOVE {zipPath}\\* {baseDirectory}");
            sb.Append($" & rd /s /q {zipPath}");

            string sPf = Path.GetPathRoot(baseDirectory).Substring(0, 2);
            sb.Append($" & {sPf}");
            sb.Append($" & cd {baseDirectory}");
            sb.Append($" & {Path.GetFileName(Process.GetCurrentProcess().MainModule.FileName)}");

            ProcessStartInfo psi = new ProcessStartInfo("cmd.exe", sb.ToString())
            {
                WindowStyle = ProcessWindowStyle.Hidden,
                CreateNoWindow = false
            };

            Process.Start(psi);
            Application.Current.Shutdown();
        }


        /// <summary>
        /// 在命令行窗口中执行
        /// </summary>
        /// <param name="sExePath"></param>
        /// <param name="sArguments"></param>
        static void CmdStartCTIProc(string sExePath, string sArguments)
        {
            Process p = new Process();
            p.StartInfo.FileName = "cmd.exe";
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardInput = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.CreateNoWindow = false;
            //p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            p.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
            //ProcessWindowStyle.Minimized;
            //| ProcessWindowStyle.Hidden;
            //System.Diagnostics.ProcessWindowStyle.Hidden;
            //p.Start();
           
            
            //p.StandardInput.WriteLine(sExePath + " " + sArguments);
            string sPf = Path.GetPathRoot(sExePath);
            sPf = sPf.Substring(0, 2);
            p.StandardInput.WriteLine(sPf);
            string sMl = Path.GetDirectoryName(sExePath);
            p.StandardInput.WriteLine("cd " + sMl);
            //p.StandardInput.WriteLine(Path.get)
            //p.StandardInput.WriteLine(sExePath);
            p.StandardInput.WriteLine(Path.GetFileName(sExePath));
            p.StandardInput.WriteLine("exit");
            p.Close();

            System.Threading.Thread.Sleep(5000);//必须等待，否则重启的程序还未启动完成；根据情况调整等待时间
        }


        /// <summary> 
        /// 转换字节大小 
        /// </summary> 
        /// <param name="byteSize">输入字节数</param> 
        /// <returns>返回值</returns> 
        private static string ConvertSize(long byteSize)
        {
            string str = "";
            float tempf = (float)byteSize;
            if (tempf / 1024 > 1)
            {
                if ((tempf / 1024) / 1024 > 1)
                {
                    str = ((tempf / 1024) / 1024).ToString("##0.00", CultureInfo.InvariantCulture) + "MB";
                }
                else
                {
                    str = (tempf / 1024).ToString("##0.00", CultureInfo.InvariantCulture) + "KB";
                }
            }
            else
            {
                str = tempf.ToString(CultureInfo.InvariantCulture) + "B";
            }
            return str;
        }

        private void BtnClose_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        //------------------------------------------------
        ////////////////////////////////////////////////////////////////
    }
}
