using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
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;
using System.Windows.Navigation;
using System.Windows.Shapes;

using System.Net;
using FLY.Thick.Base.Common;
using FLY.Thick.Base.Client;
using FLY.Thick.Base.UI.Converter;
using Unity;
using FLY.Thick.Base.IService;
using System.ComponentModel;
using System.Collections.ObjectModel;
using CommunityToolkit.Mvvm.Input;
using OfficeOpenXml;
using OfficeOpenXml.Table;
using System.Data;
using System.IO;
using Microsoft.Win32;
using System.Threading.Tasks;
using FLY.Thick.Base.Server;

namespace FLY.Thick.Base.UI
{
    /// <summary>
    /// Page_Curve.xaml 的交互逻辑
    /// </summary>
    public partial class PgCurve : Page
    {
        PgCurveVm viewModel;
        public PgCurve()
        {
            InitializeComponent();
            InitializeComponent2();
        }

        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();

            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)))));
            //chartArea1.AxisX.LabelStyle.Format = "%F2";


            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;

            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;

            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;



            this.chart1.Series.Add(series1);

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


        [InjectionMethod]
        public void Init(ICurveService curveService)
        {
            viewModel = new PgCurveVm();
            viewModel.Init(curveService, chart1, this);

            this.DataContext = viewModel;
        }
    }

    public class PgCurveVm : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;


        #region 参数
        /// <summary>
        /// AD曲线校正方式
        /// </summary>
        public CurveCorrectWay CorrectWay { get; set; }
        /// <summary>
        /// 标记，用于告诉 客户端，当前的曲线类型， 自然对数 / 直线拟合 / 二次拟合
        /// </summary>
        public CurveType Flag { get; set; }

        public ObservableCollection<CurveCell2> Curves { get; } = new ObservableCollection<CurveCell2>();

        #endregion

        #region Command
        public RelayCommand ApplyCmd { get; }
        public RelayCommand AdScaleCmd { get; }
        public RelayCommand ValueScaleCmd { get; }
        public RelayCommand SetRevisedCmd { get; }
        public RelayCommand SaveXlsxCmd { get; }
        public RelayCommand LoadXlsxCmd { get; }
        #endregion


        ICurveService mCurveService;
        System.Windows.Forms.DataVisualization.Charting.Chart chart1;
        Page page;
        public PgCurveVm()
        {
            ApplyCmd = new RelayCommand(Apply);
            AdScaleCmd = new RelayCommand(AdScale);
            ValueScaleCmd = new RelayCommand(ValueScale);
            SetRevisedCmd = new RelayCommand(SetRevised);
            SaveXlsxCmd = new RelayCommand(SaveXlsx);
            LoadXlsxCmd = new RelayCommand(LoadXlsx);
        }



        public void Init(
            ICurveService curveService,
            System.Windows.Forms.DataVisualization.Charting.Chart chart,
            Page page)
        {
            mCurveService = curveService;
            this.chart1 = chart;
            this.page = page;

            Misc.BindingOperations.SetBinding(mCurveService, nameof(mCurveService.CorrectWay), this, nameof(CorrectWay));
            Misc.BindingOperations.SetBinding(mCurveService, nameof(mCurveService.Flag), this, nameof(Flag));
            Misc.BindingOperations.SetBinding(mCurveService, nameof(mCurveService.Curves), () =>
            {
                update_curves();
            });

            this.PropertyChanged += PgCurveVm_PropertyChanged;
        }

        private void PgCurveVm_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName == nameof(Flag))
            {
                DataBindAll();
            }

        }

        void update_curves()
        {
            Curves.CollectionChanged -= Curves_CollectionChanged;
            Curves.Clear();
            if (mCurveService.Curves != null)
            {
                foreach (var cell in mCurveService.Curves)
                {
                    var cell2 = new CurveCell2() { AD = cell.AD, Value = cell.Value };
                    cell2.PropertyChanged += Cell_PropertyChanged;
                    Curves.Add(cell2);
                }
            }
            Curves.CollectionChanged += Curves_CollectionChanged;
            DataBindAll();
        }

        private void Cell_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            DataBindAll();
        }

        void Curves_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add)
            {
                foreach (CurveCell2 c in e.NewItems)
                {
                    c.PropertyChanged += (_s, _e) => { DataBindAll(); };
                }
                DataBindAll();
            }
            else if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Remove)
            {
                DataBindAll();
            }
        }

        void DataBindAll()
        {

            CurveCore CurveCore = new CurveCore();
            CurveCore.Flag = Flag;

            CurveCore.Curves = Curves.Select(c2 => new CurveCell() { AD = c2.AD, Value = c2.Value }).ToList();

            var curves = CurveCore.Curves;

            chart1.Series["Series 1"].Points.Clear();
            for (int i = 0; i < curves.Count(); i++)
            {
                int ad = curves[i].AD;
                double thick = curves[i].Value;

                chart1.Series["Series 1"].Points.AddXY(thick, ad);

                if ((i + 1) <= (curves.Count() - 1))
                {
                    //补齐点， 以thick=100 步进
                    int step = 100;
                    bool isDescending = true;//降序排列
                    if (curves[i].AD < curves[i + 1].AD)
                        isDescending = false;

                    while (true)
                    {
                        if (isDescending)
                        {
                            ad -= step;
                            if (ad <= curves[i + 1].AD)
                                break;
                        }
                        else
                        {
                            ad += step;
                            if (ad >= curves[i + 1].AD)
                                break;
                        }

                        thick = CurveCore.AD2Value(ad, AD2ValueFlag.NoRevised);
                        thick = Math.Round(thick, 2);
                        chart1.Series["Series 1"].Points.AddXY(thick, ad);
                        chart1.Series["Series 1"].Points[chart1.Series["Series 1"].Points.Count() - 1].MarkerStyle =
                            System.Windows.Forms.DataVisualization.Charting.MarkerStyle.None;
                    }
                }
            }
        }
        private void Apply()
        {
            if (!WdPassword.Authorize("Curve"))
                return;

            mCurveService.Apply(this.CorrectWay, this.Flag, this.Curves.ToArray());
            FLY.ControlLibrary.Window_Tip.Show("应用成功",
                null,
                TimeSpan.FromSeconds(2));

        }
        private void AdScale()
        {
            var curves = Curves;
            if (curves.Count > 1)
            {
                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)
                {
                    if ((w.Old != w.New) && (w.New != 0) && (w.Old != 0))
                    {
                        double scale = (double)w.New / w.Old;
                        for (int i = 0; i < curves.Count(); i++)
                        {
                            curves[i].AD = (int)Math.Round(scale * curves[i].AD);
                        }
                    }
                    FLY.ControlLibrary.Window_Tip.Show("成功",
                        null,
                        TimeSpan.FromSeconds(2));
                }
            }
        }

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

            //检查是否存在默认曲线，没有就新建
            CreateDefaultCurve();
            

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

            OpenFileDialog sfd = new OpenFileDialog();
            sfd.Filter = "xlsx files (*.xlsx)|*.xlsx";
            sfd.InitialDirectory = dirPath;

            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();
                    FLY.ControlLibrary.Window_Tip.Show("成功", $"加载{filename}", TimeSpan.FromSeconds(2));
                }
                else
                {
                    MessageBox.Show($"{error}", $"加载{filename}失败", MessageBoxButton.OK, MessageBoxImage.Error);
                }

            }
        }
        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);
            }



            page.Dispatcher.Invoke(() =>
            {
                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;
            });

        }

        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);
                });

                FLY.ControlLibrary.Window_Tip.Show("成功", $"导出到{filename}", TimeSpan.FromSeconds(2));
            }
        }

        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");
                dataTable.Columns.Add(new DataColumn() { ColumnName = "曲线类型", DataType = typeof(string) });
                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()
        {
            if (mCurveService.Curves != null)
            {
                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();
                FLY.ControlLibrary.Window_Tip.Show("成功",
                    null,
                    TimeSpan.FromSeconds(2));
            }
        }

        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);
                        }
                    }
                    FLY.ControlLibrary.Window_Tip.Show("成功",
                        null,
                        TimeSpan.FromSeconds(2));
                }
            }
        }


        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();

            }

        }


        private void CreateDefaultCurve() 
        {
            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);

            foreach (var kv in defaultCurve) {
                string filepath = kv.Key;
                if(!File.Exists(filepath))
                    SaveToXlsx(filepath, defaultCurve[filepath]);
            }
        }
    }

}
