using System;
using System.IO;
using System.Windows.Forms;

namespace DeviceRepairAndOptimization.Pages.Common
{
    public partial class dlgProgressBar : DevExpress.XtraEditors.XtraForm
    {
        private string caption = "提示";
        public string Caption
        {
            get { return caption; }
            set { caption = value; Invalidate(); }
        }

        byte[] Datas;
        string Path;
        public dlgProgressBar(byte[] data, string path)
        {
            InitializeComponent();
            Datas = data;
            Path = path;

            this.Load += DlgProgressBar_Load;
        }

        private void DlgProgressBar_Load(object sender, System.EventArgs e)
        {
            //创建一个文件流
            using (FileStream fs = new FileStream(Path, FileMode.Create))
            {
                int totalBytes = Datas.Length;
                int bufferSize = 4096; // 缓冲区大小，可以根据需要进行调整
                int bytesWritten = 0;

                while (bytesWritten < totalBytes)
                {
                    int bytesToWrite = Math.Min(bufferSize, totalBytes - bytesWritten);
                    fs.Write(Datas, bytesWritten, bytesToWrite);
                    bytesWritten += bytesToWrite;

                    // 更新进度条
                    UpdateProgressBar(bytesWritten, totalBytes);
                }
            }
        }

        public void UpdateProgressBar(long bytesRead, long totalBytes)
        {
            if (bytesRead == totalBytes)
                this.DialogResult = DialogResult.OK;

            // 在UI线程上更新进度条
            if (InvokeRequired)
            {
                this.Invoke((MethodInvoker)delegate
                {
                    UpdateProgressBar(bytesRead, totalBytes);
                });
                return;
            }

            int progressPercentage = (int)((double)bytesRead / totalBytes * 100);
            progressBarControl1.EditValue = progressPercentage;
            progressBarControl1.PerformStep();
            progressBarControl1.Update();
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);

            this.Text = Caption;
        }
    }
}