PgCurve.xaml.cs 32.8 KB
Newer Older
潘栩锋's avatar
潘栩锋 committed
1
using CommunityToolkit.Mvvm.Input;
潘栩锋's avatar
潘栩锋 committed
2
using FLY.Thick.Base.Common;
3
using FLY.Thick.Base.IService;
潘栩锋's avatar
潘栩锋 committed
4 5
using FLY.Thick.Base.Server;
using Microsoft.Win32;
6 7
using OfficeOpenXml;
using OfficeOpenXml.Table;
潘栩锋's avatar
潘栩锋 committed
8 9 10 11
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
12 13
using System.Data;
using System.IO;
潘栩锋's avatar
潘栩锋 committed
14
using System.Linq;
15
using System.Threading.Tasks;
潘栩锋's avatar
潘栩锋 committed
16 17 18
using System.Windows;
using System.Windows.Controls;
using Unity;
潘栩锋's avatar
潘栩锋 committed
19

潘栩锋's avatar
潘栩锋 committed
20
namespace FLY.Thick.Base.UI
潘栩锋's avatar
潘栩锋 committed
21 22 23 24
{
    /// <summary>
    /// Page_Curve.xaml 的交互逻辑
    /// </summary>
潘栩锋's avatar
潘栩锋 committed
25
    public partial class PgCurve : Page
潘栩锋's avatar
潘栩锋 committed
26
    {
潘栩锋's avatar
潘栩锋 committed
27 28
        PgCurveVm viewModel;
        public PgCurve()
潘栩锋's avatar
潘栩锋 committed
29 30 31
        {
            InitializeComponent();
            InitializeComponent2();
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
            if (System.ComponentModel.LicenseManager.UsageMode != System.ComponentModel.LicenseUsageMode.Runtime)
                return;

            this.Loaded += UcGridGraph_Loaded;
            this.Unloaded += UcGridGraph_Unloaded;
        }

        private void UcGridGraph_Unloaded(object sender, RoutedEventArgs e)
        {
            viewModel.DisposeBinding();
        }

        private void UcGridGraph_Loaded(object sender, RoutedEventArgs e)
        {
            viewModel.SetBinding();
潘栩锋's avatar
潘栩锋 committed
47 48 49 50 51 52 53
        }

        void InitializeComponent2()
        {
            System.Windows.Forms.DataVisualization.Charting.ChartArea chartArea1 = new System.Windows.Forms.DataVisualization.Charting.ChartArea();
            System.Windows.Forms.DataVisualization.Charting.Legend legend1 = new System.Windows.Forms.DataVisualization.Charting.Legend();
            System.Windows.Forms.DataVisualization.Charting.Series series1 = new System.Windows.Forms.DataVisualization.Charting.Series();
54

潘栩锋's avatar
潘栩锋 committed
55 56 57 58 59 60 61 62
            chart1.Name = "chart1";
            // 
            // chart1
            // 
            chartArea1.Name = "Default";
            chartArea1.AxisX.LabelStyle.Font = new System.Drawing.Font("Trebuchet MS", 8.25F, System.Drawing.FontStyle.Bold);
            chartArea1.AxisX.LineColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
            chartArea1.AxisX.MajorGrid.LineColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
63 64 65
            //chartArea1.AxisX.LabelStyle.Format = "%F2";


潘栩锋's avatar
潘栩锋 committed
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
            chartArea1.AxisY.LabelStyle.Font = new System.Drawing.Font("Trebuchet MS", 8.25F, System.Drawing.FontStyle.Bold);
            chartArea1.AxisY.LineColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
            chartArea1.AxisY.MajorGrid.LineColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
            chartArea1.BackColor = System.Drawing.Color.OldLace;
            //chartArea1.BackGradientStyle = System.Windows.Forms.DataVisualization.Charting.GradientStyle.TopBottom;
            //chartArea1.BackSecondaryColor = System.Drawing.Color.White;
            chartArea1.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
            chartArea1.BorderDashStyle = System.Windows.Forms.DataVisualization.Charting.ChartDashStyle.Solid;
            chartArea1.ShadowColor = System.Drawing.Color.Transparent;
            //对数坐标
            //chartArea1.AxisY.IsLogarithmic = true;
            //chartArea1.AxisY.LogarithmBase = Math.E;
            this.chart1.ChartAreas.Add(chartArea1);


            legend1.Name = "Default";
            legend1.BackColor = System.Drawing.Color.Transparent;
            legend1.Enabled = false;
            legend1.Font = new System.Drawing.Font("Trebuchet MS", 8.25F, System.Drawing.FontStyle.Bold);
            legend1.IsTextAutoFit = false;
86

潘栩锋's avatar
潘栩锋 committed
87 88 89 90 91 92 93 94 95 96 97 98
            this.chart1.Legends.Add(legend1);
            //this.chart1.Location = new System.Drawing.Point(16, 32);

            series1.Name = "Series 1";
            series1.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(180)))), ((int)(((byte)(26)))), ((int)(((byte)(59)))), ((int)(((byte)(105)))));
            series1.BorderWidth = 3;
            series1.ChartArea = "Default";
            series1.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
            series1.Color = System.Drawing.Color.FromArgb(((int)(((byte)(220)))), ((int)(((byte)(65)))), ((int)(((byte)(140)))), ((int)(((byte)(240)))));
            series1.Legend = "Default";
            series1.MarkerSize = 8;
            series1.MarkerStyle = System.Windows.Forms.DataVisualization.Charting.MarkerStyle.Circle;
99

潘栩锋's avatar
潘栩锋 committed
100 101 102 103
            series1.ShadowColor = System.Drawing.Color.Black;
            series1.ShadowOffset = 2;
            series1.XValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Double;
            series1.YValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Int32;
104

潘栩锋's avatar
潘栩锋 committed
105 106 107 108 109 110 111


            this.chart1.Series.Add(series1);

            this.chart1.BackColor = System.Drawing.Color.Transparent;
        }

潘栩锋's avatar
潘栩锋 committed
112

113
        [InjectionMethod]
114
        public void Init(ICurveService curveService)
潘栩锋's avatar
潘栩锋 committed
115
        {
潘栩锋's avatar
潘栩锋 committed
116 117
            viewModel = new PgCurveVm();
            viewModel.Init(curveService, chart1, this);
潘栩锋's avatar
潘栩锋 committed
118

潘栩锋's avatar
潘栩锋 committed
119 120 121 122 123 124 125 126
            this.DataContext = viewModel;
        }
    }

    public class PgCurveVm : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

127

潘栩锋's avatar
潘栩锋 committed
128 129 130 131 132 133 134 135 136
        #region 参数
        /// <summary>
        /// AD曲线校正方式
        /// </summary>
        public CurveCorrectWay CorrectWay { get; set; }
        /// <summary>
        /// 标记,用于告诉 客户端,当前的曲线类型, 自然对数 / 直线拟合 / 二次拟合
        /// </summary>
        public CurveType Flag { get; set; }
潘栩锋's avatar
潘栩锋 committed
137

138
        public ObservableCollection<CurveCell2> Curves { get; } = new ObservableCollection<CurveCell2>();
潘栩锋's avatar
潘栩锋 committed
139 140 141 142

        #endregion

        #region Command
143
        public RelayCommand ApplyCmd { get; }
144 145 146 147 148
        public RelayCommand AdScaleCmd { get; }
        public RelayCommand ValueScaleCmd { get; }
        public RelayCommand SetRevisedCmd { get; }
        public RelayCommand SaveXlsxCmd { get; }
        public RelayCommand LoadXlsxCmd { get; }
潘栩锋's avatar
潘栩锋 committed
149 150 151 152 153 154
        #endregion


        ICurveService mCurveService;
        System.Windows.Forms.DataVisualization.Charting.Chart chart1;
        Page page;
155 156 157 158 159 160 161 162

        Dictionary<object, List<Misc.BindingOperations.PropertyChangedEventContexts>> bindingConexts = new Dictionary<object, List<Misc.BindingOperations.PropertyChangedEventContexts>>();

        /// <summary>
        /// 数据已经绑定了
        /// </summary>
        bool isBinding;

163
        public PgCurveVm()
潘栩锋's avatar
潘栩锋 committed
164 165
        {
            ApplyCmd = new RelayCommand(Apply);
166 167 168 169 170
            AdScaleCmd = new RelayCommand(AdScale);
            ValueScaleCmd = new RelayCommand(ValueScale);
            SetRevisedCmd = new RelayCommand(SetRevised);
            SaveXlsxCmd = new RelayCommand(SaveXlsx);
            LoadXlsxCmd = new RelayCommand(LoadXlsx);
潘栩锋's avatar
潘栩锋 committed
171
        }
潘栩锋's avatar
潘栩锋 committed
172

173 174


潘栩锋's avatar
潘栩锋 committed
175 176 177 178
        public void Init(
            ICurveService curveService,
            System.Windows.Forms.DataVisualization.Charting.Chart chart,
            Page page)
潘栩锋's avatar
潘栩锋 committed
179
        {
潘栩锋's avatar
潘栩锋 committed
180 181 182
            mCurveService = curveService;
            this.chart1 = chart;
            this.page = page;
183 184 185 186 187 188 189 190 191 192 193
            SetBinding();
        }

        /// <summary>
        /// 参数绑定
        /// </summary>
        public void SetBinding()
        {
            if (isBinding)
                return;
            isBinding = true;
潘栩锋's avatar
潘栩锋 committed
194

195 196
            //下面全部event保存在bindingConexts
            Misc.BindingOperations.StartMarkdownEvents(bindingConexts);
197 198
            Misc.BindingOperations.SetBinding(mCurveService, nameof(mCurveService.CorrectWay), this, nameof(CorrectWay));
            Misc.BindingOperations.SetBinding(mCurveService, nameof(mCurveService.Flag), this, nameof(Flag));
199
            Misc.BindingOperations.SetBinding(mCurveService, nameof(mCurveService.Curves), this, () =>
200 201
            {
                update_curves();
202
            });
203 204
            //备份event完毕, 必须关闭记录
            Misc.BindingOperations.StopMarkdownEvents();
潘栩锋's avatar
潘栩锋 committed
205

潘栩锋's avatar
潘栩锋 committed
206
            this.PropertyChanged += PgCurveVm_PropertyChanged;
潘栩锋's avatar
潘栩锋 committed
207
        }
208 209 210 211 212 213 214 215
        /// <summary>
        /// 解除绑定
        /// </summary>
        public void DisposeBinding()
        {
            if (!isBinding)//已经解除绑定了
                return;
            isBinding = false;
潘栩锋's avatar
潘栩锋 committed
216

217 218 219 220 221
            //释放全部 event
            Misc.BindingOperations.DisposeEventTargetObject(bindingConexts);

            this.PropertyChanged -= PgCurveVm_PropertyChanged;
        }
潘栩锋's avatar
潘栩锋 committed
222
        private void PgCurveVm_PropertyChanged(object sender, PropertyChangedEventArgs e)
潘栩锋's avatar
潘栩锋 committed
223
        {
224
            if (e.PropertyName == nameof(Flag))
潘栩锋's avatar
潘栩锋 committed
225 226 227
            {
                DataBindAll();
            }
228

潘栩锋's avatar
潘栩锋 committed
229 230
        }

231
        void update_curves()
潘栩锋's avatar
潘栩锋 committed
232
        {
潘栩锋's avatar
潘栩锋 committed
233 234 235 236 237 238
            Curves.CollectionChanged -= Curves_CollectionChanged;
            Curves.Clear();
            if (mCurveService.Curves != null)
            {
                foreach (var cell in mCurveService.Curves)
                {
239 240 241
                    var cell2 = new CurveCell2() { AD = cell.AD, Value = cell.Value };
                    cell2.PropertyChanged += Cell_PropertyChanged;
                    Curves.Add(cell2);
潘栩锋's avatar
潘栩锋 committed
242 243 244
                }
            }
            Curves.CollectionChanged += Curves_CollectionChanged;
潘栩锋's avatar
潘栩锋 committed
245 246
            DataBindAll();
        }
247 248

        private void Cell_PropertyChanged(object sender, PropertyChangedEventArgs e)
潘栩锋's avatar
潘栩锋 committed
249
        {
250
            DataBindAll();
潘栩锋's avatar
潘栩锋 committed
251
        }
潘栩锋's avatar
潘栩锋 committed
252 253 254 255 256

        void Curves_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add)
            {
257
                foreach (CurveCell2 c in e.NewItems)
潘栩锋's avatar
潘栩锋 committed
258
                {
潘栩锋's avatar
潘栩锋 committed
259
                    c.PropertyChanged += (_s, _e) => { DataBindAll(); };
潘栩锋's avatar
潘栩锋 committed
260 261 262 263 264
                }
                DataBindAll();
            }
            else if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Remove)
            {
潘栩锋's avatar
潘栩锋 committed
265
                DataBindAll();
潘栩锋's avatar
潘栩锋 committed
266 267 268 269 270 271
            }
        }

        void DataBindAll()
        {

潘栩锋's avatar
潘栩锋 committed
272 273
            CurveCore CurveCore = new CurveCore();
            CurveCore.Flag = Flag;
274 275

            CurveCore.Curves = Curves.Select(c2 => new CurveCell() { AD = c2.AD, Value = c2.Value }).ToList();
潘栩锋's avatar
潘栩锋 committed
276 277 278

            var curves = CurveCore.Curves;

潘栩锋's avatar
潘栩锋 committed
279
            chart1.Series["Series 1"].Points.Clear();
潘栩锋's avatar
潘栩锋 committed
280
            for (int i = 0; i < curves.Count(); i++)
潘栩锋's avatar
潘栩锋 committed
281
            {
潘栩锋's avatar
潘栩锋 committed
282
                int ad = curves[i].AD;
283
                double thick = curves[i].Value;
潘栩锋's avatar
潘栩锋 committed
284

285
                chart1.Series["Series 1"].Points.AddXY(thick, ad);
潘栩锋's avatar
潘栩锋 committed
286

潘栩锋's avatar
潘栩锋 committed
287
                if ((i + 1) <= (curves.Count() - 1))
潘栩锋's avatar
潘栩锋 committed
288 289 290 291
                {
                    //补齐点, 以thick=100 步进
                    int step = 100;
                    bool isDescending = true;//降序排列
潘栩锋's avatar
潘栩锋 committed
292
                    if (curves[i].AD < curves[i + 1].AD)
潘栩锋's avatar
潘栩锋 committed
293 294
                        isDescending = false;

潘栩锋's avatar
潘栩锋 committed
295
                    while (true)
潘栩锋's avatar
潘栩锋 committed
296 297 298 299
                    {
                        if (isDescending)
                        {
                            ad -= step;
潘栩锋's avatar
潘栩锋 committed
300
                            if (ad <= curves[i + 1].AD)
潘栩锋's avatar
潘栩锋 committed
301 302 303 304 305
                                break;
                        }
                        else
                        {
                            ad += step;
潘栩锋's avatar
潘栩锋 committed
306
                            if (ad >= curves[i + 1].AD)
潘栩锋's avatar
潘栩锋 committed
307 308 309
                                break;
                        }

潘栩锋's avatar
潘栩锋 committed
310
                        thick = CurveCore.AD2Value(ad, AD2ValueFlag.NoRevised);
311
                        thick = Math.Round(thick, 2);
312
                        chart1.Series["Series 1"].Points.AddXY(thick, ad);
潘栩锋's avatar
潘栩锋 committed
313
                        chart1.Series["Series 1"].Points[chart1.Series["Series 1"].Points.Count() - 1].MarkerStyle =
潘栩锋's avatar
潘栩锋 committed
314 315 316 317 318
                            System.Windows.Forms.DataVisualization.Charting.MarkerStyle.None;
                    }
                }
            }
        }
潘栩锋's avatar
潘栩锋 committed
319 320 321 322
        private void Apply()
        {
            if (!WdPassword.Authorize("Curve"))
                return;
潘栩锋's avatar
潘栩锋 committed
323

324
            mCurveService.Apply(this.CorrectWay, this.Flag, this.Curves.ToArray());
325 326 327

            string tit = (string)Application.Current.TryFindResource("str.PgCurve.ApplySuccessfully");
            FLY.ControlLibrary.Window_Tip.Show(tit,null,TimeSpan.FromSeconds(2));
328

潘栩锋's avatar
潘栩锋 committed
329
        }
330
        private void AdScale()
潘栩锋's avatar
潘栩锋 committed
331
        {
潘栩锋's avatar
潘栩锋 committed
332 333
            var curves = Curves;
            if (curves.Count > 1)
潘栩锋's avatar
潘栩锋 committed
334
            {
潘栩锋's avatar
潘栩锋 committed
335 336 337 338 339
                WdAdScale w = new WdAdScale();
                w.Old = curves[0].AD;
                w.New = curves[0].AD;
                w.Owner = FLY.ControlLibrary.COMMON.GetWindow(page);
                if (w.ShowDialog() == true)
潘栩锋's avatar
潘栩锋 committed
340
                {
潘栩锋's avatar
潘栩锋 committed
341
                    if ((w.Old != w.New) && (w.New != 0) && (w.Old != 0))
潘栩锋's avatar
潘栩锋 committed
342 343
                    {
                        double scale = (double)w.New / w.Old;
潘栩锋's avatar
潘栩锋 committed
344
                        for (int i = 0; i < curves.Count(); i++)
潘栩锋's avatar
潘栩锋 committed
345
                        {
346 347 348
                            curves[i].AD = (int)Math.Round(scale * curves[i].AD);
                        }
                    }
349 350
                    string tit = (string)Application.Current.TryFindResource("str.PgCurve.OperateSuccessfully");
                    FLY.ControlLibrary.Window_Tip.Show(tit, null, TimeSpan.FromSeconds(2));
351 352 353 354 355 356 357
                }
            }
        }

        private async void LoadXlsx()
        {
            //加载数据
358 359 360

            //检查是否存在默认曲线,没有就新建
            CreateDefaultCurve();
潘栩锋's avatar
潘栩锋 committed
361

362 363 364 365 366 367 368

            string dirPath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "adcurve");
            if (!Directory.Exists(dirPath))
            {
                //上面创建失败了。。。
                dirPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
            }
369 370 371

            OpenFileDialog sfd = new OpenFileDialog();
            sfd.Filter = "xlsx files (*.xlsx)|*.xlsx";
372
            sfd.InitialDirectory = dirPath;
373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393

            if (sfd.ShowDialog() == true)
            {
                string filename = sfd.FileName;
                Exception error = null;
                var ret = await Task.Factory.StartNew(() =>
                {
                    try
                    {
                        LoadXlsx(filename);
                    }
                    catch (Exception e)
                    {
                        error = e;
                        return false;
                    }
                    return true;
                });
                if (ret)
                {
                    DataBindAll();
394 395
                    string tit = (string)Application.Current.TryFindResource("str.PgCurve.OperateSuccessfully");
                    FLY.ControlLibrary.Window_Tip.Show(tit, filename, TimeSpan.FromSeconds(2));
396 397 398
                }
                else
                {
399 400
                    string tit = (string)Application.Current.TryFindResource("str.PgCurve.OperateFailed");
                    MessageBox.Show($"{error}", tit, MessageBoxButton.OK, MessageBoxImage.Error);
401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426
                }

            }
        }
        private void LoadXlsx(string filepath)
        {
            //检测标题

            DataTable dataTable_curve = new DataTable("table_curve");
            dataTable_curve.Columns.Add(new DataColumn() { ColumnName = "AD", DataType = typeof(double), Caption = "0" });
            dataTable_curve.Columns.Add(new DataColumn() { ColumnName = "VALUE", DataType = typeof(double), Caption = "0.00" });

            DataTable dataTable_info = new DataTable("table_info");
            dataTable_info.Columns.Add(new DataColumn() { ColumnName = "曲线类型", DataType = typeof(string) });
            dataTable_info.Columns.Add(new DataColumn() { ColumnName = "校正方式", DataType = typeof(string) });

            using (ExcelPackage p = new ExcelPackage(new FileInfo(filepath)))
            {
                ExcelWorksheet sheet = p.Workbook.Worksheets["AD曲线"];
                FromSheet(sheet, dataTable_curve);

                sheet = p.Workbook.Worksheets["辅助信息"];
                FromSheet(sheet, dataTable_info);
            }


427

428
            page.Dispatcher.Invoke(() =>
429
            {
430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453
                Curves.CollectionChanged -= Curves_CollectionChanged;
                this.PropertyChanged -= PgCurveVm_PropertyChanged;

                Curves.Clear();
                for (int i = 0; i < dataTable_curve.Rows.Count; i++)
                {
                    var dataRow = dataTable_curve.Rows[i];
                    int ad = System.Convert.ToInt32(dataRow["AD"]);
                    double value = System.Convert.ToDouble(dataRow["VALUE"]);
                    Curves.Add(new CurveCell2() { AD = ad, Value = value });
                }

                if (dataTable_info.Rows.Count > 0)
                {
                    var dataRow = dataTable_info.Rows[0];
                    Flag = (CurveType)Enum.Parse(typeof(CurveType), (string)dataRow["曲线类型"]);
                    CorrectWay = (CurveCorrectWay)Enum.Parse(typeof(CurveCorrectWay), (string)dataRow["校正方式"]);
                }


                this.PropertyChanged += PgCurveVm_PropertyChanged;
                Curves.CollectionChanged += Curves_CollectionChanged;
            });

454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532
        }

        void FromSheet(ExcelWorksheet sheet, DataTable dataTable)
        {

            int from_row = 1;
            int row = from_row;


            for (int i = 0; i < dataTable.Columns.Count; i++)
            {
                int col = i + 1;
                if ((string)(sheet.Cells[row, col].Value) != dataTable.Columns[i].ColumnName)
                {
                    throw new Exception($"格式出错, 第{i}列 不是{dataTable.Columns[i].ColumnName}");
                }
            }

            row++;
            while (true)
            {
                var newRow = dataTable.NewRow();
                //当一行都是空的,认为没有数据
                int nullCnt = 0;
                for (int j = 0; j < dataTable.Columns.Count; j++)
                {
                    int col = j + 1;
                    object value = sheet.Cells[row, col].Value;

                    if (value is string || value == null)
                    {
                        if (string.IsNullOrEmpty((string)(value)))
                        {
                            //空的
                            nullCnt++;
                            //continue;
                            return;
                        }

                    }
                    try
                    {
                        newRow[j] = sheet.Cells[row, col].Value;
                    }
                    catch (Exception e)
                    {
                        throw e;
                    }
                }
                if (nullCnt == dataTable.Columns.Count)
                {
                    //没有数据了
                    break;
                }
                dataTable.Rows.Add(newRow);
                row++;
            }

        }


        private async void SaveXlsx()
        {
            //下载数据
            string strDesktopPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);

            string filename = $"AD曲线_{DateTime.Now:yyyyMMddHHmmss}.xlsx";
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Filter = "xlsx files (*.xlsx)|*.xlsx";
            sfd.InitialDirectory = strDesktopPath;
            sfd.FileName = filename;
            if (sfd.ShowDialog() == true)
            {
                filename = sfd.FileName;

                await Task.Factory.StartNew(() =>
                {
                    SaveToXlsx(filename);
                });
533

534 535
                string tit = (string)Application.Current.TryFindResource("str.PgCurve.OperateSuccessfully");
                FLY.ControlLibrary.Window_Tip.Show(tit, filename, TimeSpan.FromSeconds(2));
536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571
            }
        }

        private void SaveToXlsx(string filepath)
        {
            if (File.Exists(filepath))
            {
                File.Delete(filepath);
            }
            using (ExcelPackage p = new ExcelPackage(new FileInfo(filepath)))
            {
                ExcelWorksheet sheet = p.Workbook.Worksheets.Add("AD曲线");
                DataTable dataTable = new DataTable("table_curve");
                dataTable.Columns.Add(new DataColumn() { ColumnName = "AD", DataType = typeof(double), Caption = "0" });
                dataTable.Columns.Add(new DataColumn() { ColumnName = "VALUE", DataType = typeof(double), Caption = "0.00" });

                for (int i = 0; i < Curves.Count(); i++)
                {
                    try
                    {
                        var dataRow = dataTable.NewRow();
                        dataRow["AD"] = Curves[i].AD;
                        dataRow["VALUE"] = Curves[i].Value;
                        dataTable.Rows.Add(dataRow);
                    }
                    catch
                    {
                        break;
                    }
                }

                ToSheet(sheet, dataTable);


                sheet = p.Workbook.Worksheets.Add("辅助信息");
                dataTable = new DataTable("table_info");
572
                dataTable.Columns.Add(new DataColumn() { ColumnName = "曲线类型", DataType = typeof(string) });
573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622
                dataTable.Columns.Add(new DataColumn() { ColumnName = "校正方式", DataType = typeof(string) });
                {
                    var dataRow = dataTable.NewRow();
                    dataRow["曲线类型"] = Flag.ToString();
                    dataRow["校正方式"] = CorrectWay.ToString();
                    dataTable.Rows.Add(dataRow);
                }
                ToSheet(sheet, dataTable);

                p.Save();

            }

        }
        void ToSheet(ExcelWorksheet sheet, DataTable dataTable)
        {
            int from_row = 1;
            int row = from_row;
            //添加标题
            for (int i = 0; i < dataTable.Columns.Count; i++)
            {
                int col = i + 1;
                sheet.Cells[row, col].Value = dataTable.Columns[i].ColumnName;
                //格式
                sheet.Column(col).Style.Numberformat.Format = dataTable.Columns[i].Caption;
            }

            row++;
            for (int i = 0; i < dataTable.Rows.Count; i++)
            {
                for (int j = 0; j < dataTable.Columns.Count; j++)
                {
                    int col = j + 1;
                    sheet.Cells[row, col].Value = dataTable.Rows[i][j];
                }
                row++;
            }

            int colcnt = dataTable.Columns.Count;
            int rowcnt = dataTable.Rows.Count;
            var range = sheet.Cells[from_row, 1, from_row + rowcnt, colcnt];

            var tbl = sheet.Tables.Add(range, dataTable.TableName);
            tbl.TableStyle = TableStyles.Medium9;
            sheet.Cells[sheet.Dimension.Address].AutoFitColumns();
        }


        private void SetRevised()
        {
623 624
            if (mCurveService.Curves != null)
            {
625 626 627 628 629 630 631 632 633 634
                Curves.CollectionChanged -= Curves_CollectionChanged;
                Curves.Clear();

                foreach (var cell in mCurveService.Curves)
                {
                    Curves.Add(new CurveCell2() { AD = cell.RevisedAD, Value = cell.Value });
                    cell.PropertyChanged += (s, e) => { DataBindAll(); };
                }
                Curves.CollectionChanged += Curves_CollectionChanged;
                DataBindAll();
635 636
                string tit = (string)Application.Current.TryFindResource("str.PgCurve.OperateSuccessfully");
                FLY.ControlLibrary.Window_Tip.Show(tit,null,TimeSpan.FromSeconds(2));
637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656
            }
        }

        private void ValueScale()
        {
            var curves = Curves;
            if (curves.Count > 1)
            {
                WdAdScale w = new WdAdScale();
                w.Old = curves[0].Value;
                w.New = curves[0].Value;
                w.Owner = FLY.ControlLibrary.COMMON.GetWindow(page);
                if (w.ShowDialog() == true)
                {
                    if ((w.Old != w.New) && (w.New != 0) && (w.Old != 0))
                    {
                        double scale = w.New / w.Old;
                        for (int i = 0; i < curves.Count(); i++)
                        {
                            curves[i].Value = Math.Round(scale * curves[i].Value, 2);
潘栩锋's avatar
潘栩锋 committed
657 658
                        }
                    }
659 660
                    string tit = (string)Application.Current.TryFindResource("str.PgCurve.OperateSuccessfully");
                    FLY.ControlLibrary.Window_Tip.Show(tit, null, TimeSpan.FromSeconds(2));
潘栩锋's avatar
潘栩锋 committed
661 662 663
                }
            }
        }
664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805


        CurveCollectionJsonDb curve_k85 = new CurveCollectionJsonDb()
        {
            Curves = new CurveCell2[] {
                new CurveCell2() { AD = 58790, Value = 0 },
                new CurveCell2() { AD = 39460, Value = 238.38 },
                new CurveCell2() { AD = 39070, Value = 244.88 },
                new CurveCell2() { AD = 38450, Value = 255.48 },
                new CurveCell2() { AD = 37920, Value = 263.08 },
                new CurveCell2() { AD = 37436, Value = 270.68 },
                new CurveCell2() { AD = 36990, Value = 281.98 },
                new CurveCell2() { AD = 36527, Value = 287.08 },
                new CurveCell2() { AD = 35892, Value = 296.28 },
                new CurveCell2() { AD = 35622, Value = 305.88 },
                new CurveCell2() { AD = 35222, Value = 311.58 },
                new CurveCell2() { AD = 34552, Value = 321.58 },
                new CurveCell2() { AD = 35655, Value = 300.58 },
                new CurveCell2() { AD = 34812, Value = 316.78 },
                new CurveCell2() { AD = 33700, Value = 335.18 },
                new CurveCell2() { AD = 32824, Value = 351.38 },
                new CurveCell2() { AD = 31785, Value = 370.78 },
                new CurveCell2() { AD = 30896, Value = 386.58 },
                new CurveCell2() { AD = 30130, Value = 403.88 },
                new CurveCell2() { AD = 29022, Value = 422.48 },
                new CurveCell2() { AD = 28520, Value = 433.18 },
                new CurveCell2() { AD = 27696, Value = 455.58 }
            },
            CorrectWay = CurveCorrectWay.OnePointIsScale,
            Flag = CurveType.E
        };
        CurveCollectionJsonDb curve_4k = new CurveCollectionJsonDb()
        {
            Curves = new CurveCell2[] {
                new CurveCell2() { AD =     50300   , Value =   0    },
                new CurveCell2() { AD =     46505   , Value =   19   },
                new CurveCell2() { AD =     42999   , Value =   38   },
                new CurveCell2() { AD =     39698   , Value =   58   },
                new CurveCell2() { AD =     36646   , Value =   78   },
                new CurveCell2() { AD =     33894   , Value =   98   },
                new CurveCell2() { AD =     31229   , Value =   118  },
                new CurveCell2() { AD =     28934   , Value =   137  },
                new CurveCell2() { AD =     26818   , Value =   156  },
                new CurveCell2() { AD =     24908   , Value =   175  },
                new CurveCell2() { AD =     23220   , Value =   194  },
                new CurveCell2() { AD =     21558   , Value =   213  },
                new CurveCell2() { AD =     20057   , Value =   232  },
                new CurveCell2() { AD =     18606   , Value =   251  },
                new CurveCell2() { AD =     17283   , Value =   271  },
                new CurveCell2() { AD =     16035   , Value =   290  }
            },
            CorrectWay = CurveCorrectWay.OnePointIsScale,
            Flag = CurveType.E
        };
        CurveCollectionJsonDb curve_20k = new CurveCollectionJsonDb()
        {
            Curves = new CurveCell2[] {
                new CurveCell2() { AD =     59297   , Value =   0    },
                new CurveCell2() { AD =     22988   , Value =   153.52   },
                new CurveCell2() { AD =     22032   , Value =   160.32   },
                new CurveCell2() { AD =     20822   , Value =   167.92   },
                new CurveCell2() { AD =     19570   , Value =   177.62   },
                new CurveCell2() { AD =     17811   , Value =   192.72   },
                new CurveCell2() { AD =     16857   , Value =   202.42   },
                new CurveCell2() { AD =     16193   , Value =   209.62   },
                new CurveCell2() { AD =     15120   , Value =   218.52   },
                new CurveCell2() { AD =     14609   , Value =   227.32   },
                new CurveCell2() { AD =     13917   , Value =   233.62   },
                new CurveCell2() { AD =     11142   , Value =   275.62   },
                new CurveCell2() { AD =     10284   , Value =   291.52   },
                new CurveCell2() { AD =     9196    , Value =   308.12   },
                new CurveCell2() { AD =     8690    , Value =   319.92   },
                new CurveCell2() { AD =     8007    , Value =   334.72   },
                new CurveCell2() { AD =     7291    , Value =   353.02   },
                new CurveCell2() { AD =     6743    , Value =   368.32   },
                new CurveCell2() { AD =     6224    , Value =   386.32   },
                new CurveCell2() { AD =     5616    , Value =   402.72   },
                new CurveCell2() { AD =     5331    , Value =   417.02   },
                new CurveCell2() { AD =     4982    , Value =   433.12   }
            },
            CorrectWay = CurveCorrectWay.OnePointIsScale,
            Flag = CurveType.E
        };
        CurveCollectionJsonDb curve_laser = new CurveCollectionJsonDb()
        {
            Curves = new CurveCell2[] {
                new CurveCell2() { AD =     22130   , Value =   186.00    },
                new CurveCell2() { AD =     36774   , Value =   672.00   }
            },
            CorrectWay = CurveCorrectWay.OnePointIsOffset,
            Flag = CurveType.Line
        };
        private void SaveToXlsx(string filepath, CurveCollectionJsonDb curve)
        {
            if (File.Exists(filepath))
            {
                File.Delete(filepath);
            }
            using (ExcelPackage p = new ExcelPackage(new FileInfo(filepath)))
            {
                ExcelWorksheet sheet = p.Workbook.Worksheets.Add("AD曲线");
                DataTable dataTable = new DataTable("table_curve");
                dataTable.Columns.Add(new DataColumn() { ColumnName = "AD", DataType = typeof(double), Caption = "0" });
                dataTable.Columns.Add(new DataColumn() { ColumnName = "VALUE", DataType = typeof(double), Caption = "0.00" });

                for (int i = 0; i < curve.Curves.Count(); i++)
                {
                    try
                    {
                        var dataRow = dataTable.NewRow();
                        dataRow["AD"] = curve.Curves[i].AD;
                        dataRow["VALUE"] = curve.Curves[i].Value;
                        dataTable.Rows.Add(dataRow);
                    }
                    catch
                    {
                        break;
                    }
                }

                ToSheet(sheet, dataTable);


                sheet = p.Workbook.Worksheets.Add("辅助信息");
                dataTable = new DataTable("table_info");
                dataTable.Columns.Add(new DataColumn() { ColumnName = "曲线类型", DataType = typeof(string) });
                dataTable.Columns.Add(new DataColumn() { ColumnName = "校正方式", DataType = typeof(string) });
                {
                    var dataRow = dataTable.NewRow();
                    dataRow["曲线类型"] = curve.Flag.ToString();
                    dataRow["校正方式"] = curve.CorrectWay.ToString();
                    dataTable.Rows.Add(dataRow);
                }
                ToSheet(sheet, dataTable);

                p.Save();

            }

        }


潘栩锋's avatar
潘栩锋 committed
806
        private void CreateDefaultCurve()
807 808 809 810 811 812 813 814 815 816 817 818 819 820
        {
            Dictionary<string, CurveCollectionJsonDb> defaultCurve = new Dictionary<string, CurveCollectionJsonDb>();

            string dirPath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "adcurve");
            if (!Directory.Exists(dirPath))
            {
                Directory.CreateDirectory(dirPath);
            }

            defaultCurve.Add(System.IO.Path.Combine(dirPath, "K85.xlsx"), curve_k85);
            defaultCurve.Add(System.IO.Path.Combine(dirPath, "X光4K.xlsx"), curve_4k);
            defaultCurve.Add(System.IO.Path.Combine(dirPath, "X光20K.xlsx"), curve_20k);
            defaultCurve.Add(System.IO.Path.Combine(dirPath, "激光.xlsx"), curve_laser);

潘栩锋's avatar
潘栩锋 committed
821 822
            foreach (var kv in defaultCurve)
            {
823
                string filepath = kv.Key;
潘栩锋's avatar
潘栩锋 committed
824
                if (!File.Exists(filepath))
825 826 827
                    SaveToXlsx(filepath, defaultCurve[filepath]);
            }
        }
潘栩锋's avatar
潘栩锋 committed
828
    }
829

潘栩锋's avatar
潘栩锋 committed
830
}