using DevExpress.DataAccess.Excel;
using DevExpress.Export.Xl;
using DevExpress.Utils;
using DevExpress.XtraCharts;
using DevExpress.XtraPrinting;
using DevExpress.XtraVerticalGrid;
using DevExpress.XtraVerticalGrid.Rows;
using DevExpress.Spreadsheet;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using SystemX.Net.Platform.Common.ExtensionMethods;
using SystemX.Product.ALIS.UI.Subs;
using SystemX.Product.TRA.DataManager;
using DevExpress.XtraGrid.Views.Grid;
using SystemX.Product.ALIS.Interface;

using static SystemX.Product.TRA.DataManager.DMTestHistory;
using static SystemX.Product.TRA.DataManager.DMTestSummary;
using static SystemX.Product.TRA.UIControl.UcTRAStepTrend.TrendDataResult;
using static SystemX.Product.CP.TRA.Commons;
using Newtonsoft.Json;
using CPXV2Log = SystemX.Net.Platform.SystemX.Net.XEFCore.DBContext.CPXV2Log;
using SystemX.Common.Util;

namespace SystemX.Product.TRA.UIControl
{
    public partial class UcTRAStepTrend : UcTRABaseView
    {
        public enum eColDataTable
        {
            RowNo,
            TestTime,
            ProductID,
            Min,
            Value,
            Max,
            Result,
            Duration
        }

        public enum eResultType
        {
            OK,
            NG,
            NONE
        }

        DMStepTrend DataManager { get; set; }
        TestTrendDataCollection SelectedData { get; set; }
        DataTable DTTestlistSrc { get; set; } = null;
        DataTable DTTestLogList { get; set; } = null;
        DataTable DTTestSummary { get; set; } = null;

        WaitProgressForm SplashFormWaiting = null;

        List<string> NoChartDispSpec = new List<string>();

        delegate void evtDBQueryFinished();
        event evtDBQueryFinished evtDBFin;

        private string GridViewGetActiveFilterText;

        private double dThisMaxLimit;
        private double dThisMinLimit;
        private double dThisUnitSize;
        public UcTRAStepTrend()
        {
            ContentsType = eContents.TestTrend;

            //this.ContextMenuStrip = base.contextMenuStripTest;

            InitializeComponent();

            FileStream fs = new FileStream("NoChartSpec.def", FileMode.Open, FileAccess.Read);
            StreamReader sr = new StreamReader(fs);

            while (!sr.EndOfStream)
                NoChartDispSpec.Add(sr.ReadLine());

            sr.Close();
            fs.Close();
        }

        public void SetSQLConnection(eSelectDataView SelectView, IDataBaseController getDBController, DateTime dtStart)
        {
            DataManager = new DMStepTrend(SelectView, getDBController, dtStart);
        }

        public override void ExportData()
        {
            FolderBrowserDialog dlg = new FolderBrowserDialog();

            if (dlg.ShowDialog() == DialogResult.OK)
            {

                string strFileName = CreateExportFileName();
                string strExpPath = dlg.SelectedPath + "\\" + strFileName;
                XlsxExportOptionsEx option = new XlsxExportOptionsEx();
                string strFile = strExpPath + ".xlsx";

                option.ShowGridLines = true;
                option.ExportType = DevExpress.Export.ExportType.WYSIWYG;
                option.ExportMode = XlsxExportMode.SingleFile;
                option.SheetName = "Trend Data";
                gridControlMain.ExportToXlsx(strFile, option);


                Workbook wbook = new Workbook();

                wbook.LoadDocument(strFile);

                Worksheet worksheetInfo = wbook.Worksheets.Add("Test Trend Info.");

                int nIdx = 0;

                foreach (var row in vGridControlInfo.Rows)
                {
                    if (row is CategoryRow)
                    {
                        worksheetInfo.Cells[nIdx, 0].Value = row.Properties.Caption.ToString();

                        CellRange cr = worksheetInfo.Range.FromLTRB(0, nIdx, 2, nIdx);

                        worksheetInfo.MergeCells(cr);
                    }
                    else
                    {
                        worksheetInfo.Cells[nIdx, 1].Value = row.Properties.Caption.ToString();
                        worksheetInfo.Cells[nIdx, 2].Value = row.Properties.Value.ToString();
                    }

                    nIdx++;
                }

                worksheetInfo.Cells[nIdx, 0].Value = "Test Step Analysis";
                nIdx++;

                foreach (var row in vGridControlStepSummary.Rows)
                {
                    if (row is CategoryRow)
                    {
                        worksheetInfo.Cells[nIdx, 0].Value = row.Properties.Caption.ToString();

                        CellRange cr = worksheetInfo.Range.FromLTRB(0, nIdx, 2, nIdx);

                        worksheetInfo.MergeCells(cr);
                    }
                    else
                    {
                        worksheetInfo.Cells[nIdx, 1].Value = row.Properties.Caption.ToString();
                        worksheetInfo.Cells[nIdx, 2].Value = row.Properties.Value.ToString();
                    }

                    nIdx++;
                }

                worksheetInfo.Columns.AutoFit(0, 3);
                worksheetInfo.AutoOutline();
                wbook.SaveDocument(strFile);
            }
        }

        public string CreateExportFileName()
        {
            string strFileName = $"{this.ContentsType.ToString()}_{SelectedData.SelectedData.ProductNo}_{SelectedData.SelectedData.TestCode}_{SelectedData.SelectedData.StationName}_{SelectedData.StepNo}";

            strFileName += $"_{SelectedData.SelectedData.StartTime.ToString("yyyyMMddHHmmss")}-{SelectedData.SelectedData.StartTime.ToString("yyyyMMddHHmmss")}";

            return strFileName;
        }

        public void ViewData(TestTrendDataCollection data)
        {
            if (data == null)
                return;

            SelectedData = data;
            DTTestlistSrc = data.DTTestlistSrc;
            DTTestLogList = data.DTTestLogList;

            try
            {
                DataRow dtRow = GetTestStepInfo(data.StepNo, data.DTTestlistSrc);
                List<DataRow> vdtRowLogs = DTTestLogList.AsEnumerable().Where(x =>
                    (!Enum.GetNames(typeof(DMOverview.eCommand)).Contains(x[DMTestHistory.eColList.ProductNo.ToString()].ToString())
                    && !Enum.GetNames(typeof(DMOverview.eCommand)).Contains(x[DMTestHistory.eColList.ProductID.ToString()].ToString()))).ToList();

                ShowProperties(data, dtRow);

                DataRow dtRowLogFirst = vdtRowLogs[0];
                DateTime dtTested = Convert.ToDateTime(dtRowLogFirst[DMTestHistory.eColList.TestDateTime.ToString()]);
                CPXV2Log.Tables.HIST_TestResult drStep = null;

                for (int i = 0; i < vdtRowLogs.Count; i++)
                {
                    dtRowLogFirst = vdtRowLogs[i];
                    dtTested = Convert.ToDateTime(dtRowLogFirst[DMTestHistory.eColList.TestDateTime.ToString()]);                   

                    DataTable dtFirstLog = DataManager.SearchTestResult(dtTested);

                    var logData = dtFirstLog.Rows[0]["LogData"].ToString();
                    var decompStr = logData.GzipDecompress();

                    var list = JsonConvert.DeserializeObject<List<CPXV2Log.Tables.HIST_TestResult>>(decompStr);

                    drStep = list.Where(x => x.StepID.ToString() == data.StepNo.ToString()).FirstOrDefault();

                    if (drStep != null)
                        break;
                }

                if (drStep == null)
                    return;
           
                DataTable dtResult = GetTrendData(dtTested, vdtRowLogs);

                dtResult = CombineLogForm(dtResult, dtRow);

                TrendDataResult resultUnit = MakeTrendSummary(dtResult, dtRow, data);

                ShowDataTable(dtResult);
                ShowTestStepSummary(resultUnit);
                ShowTrendChart(resultUnit);

            }
            catch (Exception ex)
            {
                MessageBox.Show($"Searching Failure - {ex.Message}", "Test Trend - Error");
            }
        }

        void CloseWaitingForm()
        {
            this.Do(() => SplashFormWaiting.Close());
        }

        DataTable GetTrendData(DateTime dtTested, List<DataRow> vnData)
        {
            DataTable dtResult = DataManager.GetTestStepResults(dtTested, vnData.Select(x => Convert.ToUInt64(x[0])).ToList());

            dtResult.Columns.Add(eColDataTable.RowNo.ToString(), typeof(int));

            for (int i = 0; i < dtResult.Rows.Count; i++)
                dtResult.Rows[i][eColDataTable.RowNo.ToString()] = i + 1;


            return dtResult;
        }


        DataTable CombineLogForm(DataTable dtResult, DataRow dtRowTestlistSpec)
        {
            DataTable dtFinal = new DataTable();

            foreach (string strCol in Enum.GetNames(typeof(eColDataTable)))
            {
                Type typCol = strCol == eColDataTable.RowNo.ToString() ? typeof(int) : typeof(string);

                dtFinal.Columns.Add(strCol, typCol);
            }

            foreach (DataRow drLog in dtResult.AsEnumerable())
            {
                /*string strValue = drLog[DMTestHistory.eColList.TestID.ToString()].ToString();
                DataRow drTL = DTTestLogList.AsEnumerable().Where(x => 
                x[DMTestHistory.eColList.TestID.ToString()].ToString() == drLog[DMTestHistory.eColList.TestID.ToString()].ToString()).FirstOrDefault();*/

                //string strValue = drLog[DMTestHistory.eColList.No.ToString()].ToString();

                DataRow drTL = DTTestLogList.AsEnumerable()
                    .Where(x => Convert.ToInt64(x[DMTestHistory.eColList.No.ToString()]) == Convert.ToInt64(drLog[0].ToString())).FirstOrDefault();

                DataRow drDisp = dtFinal.NewRow();

                if (drTL == null)
                    continue;

                var logData = drLog["LogData"].ToString();
                var decompStr = logData.GzipDecompress();
                var list = JsonConvert.DeserializeObject<List<CPXV2Log.Tables.HIST_TestResult>>(decompStr);
                var row = list.Where(x => x.StepID == Convert.ToInt64(dtRowTestlistSpec[2].ToString())).First();

                drDisp[eColDataTable.RowNo.ToString()] = (int)drLog[eColDataTable.RowNo.ToString()];
                drDisp[eColDataTable.TestTime.ToString()] = drTL[1].ToString();
                drDisp[eColDataTable.ProductID.ToString()] = drTL[5].ToString();
                drDisp[eColDataTable.Result.ToString()] = row.Result.ToString();

                bool bIsGlobal = (Convert.ToInt32(dtRowTestlistSpec[eColTestlist.IsGlobal.ToString()])) > 0 ? true : false;
                
                drDisp[eColDataTable.Min.ToString()] = bIsGlobal ? row.GlobalMin.ToString() : dtRowTestlistSpec[eColTestlist.SpecMin.ToString()].ToString();
                drDisp[eColDataTable.Max.ToString()] = bIsGlobal ? row.GlobalMAx.ToString() : dtRowTestlistSpec[eColTestlist.SpecMax.ToString()].ToString();

                string strMessage = row.Message.ToString();
                string strMeasValStr = row.MeasValStr.ToString();
                string strMeasVal = row.MeasVal.ToString();

                drDisp[eColDataTable.Value.ToString()] = string.IsNullOrWhiteSpace(strMessage) ? (string.IsNullOrWhiteSpace(strMeasValStr) ? strMeasVal : strMeasValStr) : strMessage;
                drDisp[eColDataTable.Result.ToString()] = row.Result.ToString();

                dtFinal.Rows.Add(drDisp);
            }

            return dtFinal;
        }

        void ShowDataTable(DataTable dtResult)
        {
            GridViewGetActiveFilterText = gridViewMain.ActiveFilterString;

            gridControlMain.BeginInit();

            gridControlMain.DataSource = dtResult;

            gridControlMain.Update();
            gridControlMain.RefreshDataSource();
            gridControlMain.ForceInitialize();
            gridViewMain.PopulateColumns(dtResult);
            gridControlMain.EndInit();

            gridViewMain.BestFitColumns();

            gridViewMain.ActiveFilterString = GridViewGetActiveFilterText;
        }

        void ShowTrendChart(TrendDataResult resultUnit, bool bAutoRange = false)
        {
            foreach (Series srsData in chartControlMain.Series)
                srsData.Points.Clear();

            chartControlMain.Series.Clear();

            if (resultUnit == null || resultUnit.DataElements == null || resultUnit.DataElements.Count <= 0)
                return;

            chartControlMain.CrosshairOptions.ArgumentLineColor = Color.Black;
            chartControlMain.CrosshairOptions.CrosshairLabelTextOptions.TextColor = Color.Black;
            chartControlMain.CrosshairOptions.CrosshairLabelBackColor = Color.White;
            chartControlMain.CrosshairOptions.ValueLineColor = Color.Black;
            chartControlMain.CrosshairOptions.GroupHeaderTextOptions.TextColor = Color.Blue;
            
            int nSrsIdxValue = AddSeries("Value", ScaleType.Qualitative, ScaleType.Numerical, Color.Red);
            int nSrsIdxMin = AddSeries("Lower Limit", ScaleType.Qualitative, ScaleType.Numerical, Color.Blue);
            int nSrsIdxMax = AddSeries("Upper Limit", ScaleType.Qualitative, ScaleType.Numerical, Color.Blue);

            AddToolTip("{HINT} \r\n {Value:#0.00}");

            SetAxisXRange(DateTimeMeasureUnit.Second, DateTimeGridAlignment.Second);
            AxisYRangeAuto(bAutoRange, resultUnit);

            SwiftPlotDiagram diagram = (SwiftPlotDiagram)chartControlMain.Diagram;

            foreach (StepDataElement item in resultUnit.DataElements)
            {
                if (item.Result == eResultType.NONE && item.Value == 0)
                    continue;

                if (item.UseMin)
                    chartControlMain.Series[nSrsIdxMin].Points.Add(new SeriesPoint(item.RowNo, item.Min));
                if (item.UseMax)
                    chartControlMain.Series[nSrsIdxMax].Points.Add(new SeriesPoint(item.RowNo, item.Max));

                chartControlMain.Series[nSrsIdxValue].Points.Add(new SeriesPoint(item.RowNo, item.Value));

                if (item.Value < item.Min || item.Value > item.Max)
                {
                    if (diagram.AxisY.WholeRange.Auto != true)
                    {
                        diagram.AxisY.WholeRange.Auto = true;

                        if (chartControlMain.BackColor != Color.WhiteSmoke)
                            chartControlMain.BackColor = Color.WhiteSmoke;
                    }
                }
            }

            //diagram.AxisX.Interlaced = false;
            diagram.DefaultPane.BackColor = Color.White;
            diagram.DefaultPane.RuntimeCollapse = DefaultBoolean.False;
        }


        private void SetAxisXRange(DateTimeMeasureUnit dtimeUnit, DateTimeGridAlignment dtimeGrid)
        {
            SwiftPlotDiagram diagram = (SwiftPlotDiagram)chartControlMain.Diagram;
            diagram.AxisX.NumericScaleOptions.ScaleMode = ScaleMode.Continuous;
            diagram.AxisX.NumericScaleOptions.AutoGrid = true;
            diagram.AxisX.Logarithmic = false;

            //diagram.AxisX.DateTimeScaleOptions.MeasureUnit = dtimeUnit;
            //.AxisX.DateTimeScaleOptions.GridAlignment = dtimeGrid;

            diagram.AxisX.Interlaced = true;
            diagram.AxisX.InterlacedColor = Color.GhostWhite;
            diagram.AxisX.InterlacedFillStyle.FillMode = FillMode.Solid;

            diagram.AxisX.NumericScaleOptions.ScaleMode = ScaleMode.Automatic;
            diagram.AxisX.LabelPosition = AxisLabelPosition.Outside;

            diagram.EnableAxisXScrolling = true;
            diagram.EnableAxisXZooming = true;
            //
            diagram.EnableAxisYScrolling = true;
            diagram.EnableAxisYZooming = true;
            //
            diagram.AxisX.Color = Color.Black;
            diagram.AxisX.Label.TextColor = Color.Black;

            diagram.AxisY.Color = Color.Black;
            diagram.AxisY.Label.TextColor = Color.Black;

            chartControlMain.BackColor = Color.White;
        }

        public void AxisYRangeAuto(bool bAuto, TrendDataResult resultUnit)
        {
            SwiftPlotDiagram diagram = (SwiftPlotDiagram)chartControlMain.Diagram;
            if (diagram == null)
                return;

            diagram.AxisY.WholeRange.Auto = bAuto;

            if (!bAuto)
            {
                dThisMaxLimit = resultUnit.MaxSpec == resultUnit.dSpecNotUse ? resultUnit.Max : resultUnit.MaxSpec;
                dThisMinLimit = resultUnit.MinSpec == resultUnit.dSpecNotUse ? resultUnit.Min : resultUnit.MinSpec;
                dThisUnitSize = Math.Abs((dThisMaxLimit - dThisMinLimit) / 10);

                diagram.AxisY.WholeRange.SetMinMaxValues(dThisMinLimit - dThisUnitSize, dThisMaxLimit + dThisUnitSize);
            }
        }
        public int AddSeries(string name, ScaleType ArgumentType, ScaleType ValueType, Color seriesColor)
        {
            Series series = new Series(name, ViewType.SwiftPlot);
            chartControlMain.Series.Add(series);
            series.ArgumentScaleType = ArgumentType;
            series.ValueScaleType = ValueType;

            SwiftPlotSeriesView plotSeriesView = new DevExpress.XtraCharts.SwiftPlotSeriesView();
            plotSeriesView.Color = seriesColor;
            //plotSeriesView.LineMarkerOptions.Color = seriesColor;
            //plotSeriesView.LineMarkerOptions.Size = 3;
            plotSeriesView.LineStyle.Thickness = 2;
            //plotSeriesView.MarkerVisibility = DefaultBoolean.True;
            series.View = plotSeriesView;

            return chartControlMain.Series.Count - 1;
        }

        private void AddToolTip(string ToolTipPattern)
        {
            // Disable a crosshair cursor.
            chartControlMain.CrosshairEnabled = DefaultBoolean.True;

            // Enable chart tooltips. 
            chartControlMain.ToolTipEnabled = DefaultBoolean.True;

            ToolTipController controller = new ToolTipController();
            chartControlMain.ToolTipController = controller;
            controller.ShowBeak = true;

            // Change the default tooltip mouse position to relative position.
            ToolTipRelativePosition relativePosition = new ToolTipRelativePosition();
            chartControlMain.ToolTipOptions.ToolTipPosition = relativePosition;

            // Specify the tooltip relative position offsets.  
            relativePosition.OffsetX = 2;
            relativePosition.OffsetY = 2;

            // Specify the tooltip point pattern.
            chartControlMain.Series[0].ToolTipPointPattern = ToolTipPattern;
        }

        TrendDataResult MakeTrendSummary(DataTable dtResult, DataRow dtRowTestlist, TestTrendDataCollection data, bool bOKDataOnly = true)
        {
            string strDim = dtRowTestlist[DMTestDetail.eColTestlist.Dim.ToString()].ToString();

            if (NoChartDispSpec.Contains(strDim))
                return null;

            bool bIsGlobal = (Convert.ToInt32(dtRowTestlist[DMTestDetail.eColTestlist.IsGlobal.ToString()])) > 0 ? true : false;
            TrendDataResult resultUnit = new TrendDataResult();
            StepDataElement elemUnit = null;

            foreach (DataRow drValue in dtResult.AsEnumerable())
            {
                DateTime dtTestedTime = DateTime.Parse(drValue[eColDataTable.TestTime.ToString()].ToString());
                string strProdID = drValue[eColDataTable.ProductID.ToString()].ToString();
                string strValue = drValue[eColDataTable.Value.ToString()].ToString();
                string strMin = drValue[eColDataTable.Min.ToString()].ToString();
                string strMax = drValue[eColDataTable.Max.ToString()].ToString();
                string strResult = drValue[eColDataTable.Result.ToString()].ToString();
                double dValue = 0.0;

                if (string.IsNullOrWhiteSpace(strValue))
                    continue;
                if (!double.TryParse(strValue, out dValue))
                    continue;

                elemUnit = new StepDataElement();

                elemUnit.RowNo = (int)drValue[eColDataTable.RowNo.ToString()];
                elemUnit.TestTime = dtTestedTime;
                elemUnit.ProductID = strProdID;
                elemUnit.Value = dValue;

                if (string.IsNullOrWhiteSpace(strMin))
                    elemUnit.UseMin = false;
                else
                {
                    elemUnit.UseMin = true;
                    elemUnit.Min = Convert.ToDouble(strMin);
                }
                if (string.IsNullOrWhiteSpace(strMax))
                    elemUnit.UseMax = false;
                else
                {
                    elemUnit.UseMax = true;
                    elemUnit.Max = Convert.ToDouble(strMax);
                }

                if (elemUnit.UseMin && elemUnit.UseMax)
                    elemUnit.Tolerance = elemUnit.Max - elemUnit.Min;

                elemUnit.Result = strResult == "NG" || strResult == "ERROR" ? eResultType.NG : strResult == "OK" ? eResultType.OK : eResultType.NONE;

                if (bOKDataOnly && elemUnit.Result != eResultType.OK)
                    continue;

                resultUnit.DataElements.Add(elemUnit);
            }

            if (resultUnit.DataElements == null || resultUnit.DataElements.Count <= 0)
                return null;

            double dSpecNotUse = -999999;
            List<double> vdValue = (from elem in resultUnit.DataElements let dValue = elem.Value select dValue).ToList();

            resultUnit.Average = vdValue.Average();
            resultUnit.Min = vdValue.Min();
            resultUnit.Max = vdValue.Max();
            resultUnit.Variance = vdValue.Variance();
            resultUnit.StdDev = vdValue.StandardDeviation();

            resultUnit.MinSpec = resultUnit.DataElements[0].UseMin ?
                                (from elem in resultUnit.DataElements let dValue = elem.Min select dValue).Average() : dSpecNotUse;
            resultUnit.MaxSpec = resultUnit.DataElements[0].UseMax ?
                                (from elem in resultUnit.DataElements let dValue = elem.Max select dValue).Average() : dSpecNotUse;

            resultUnit.Cp = resultUnit.DataElements[0].UseMin && resultUnit.DataElements[0].UseMax ?
                            vdValue.Cp(resultUnit.MaxSpec - resultUnit.MinSpec) : 0.0;
            resultUnit.Cpk = resultUnit.DataElements[0].UseMin && resultUnit.DataElements[0].UseMax ?
                            vdValue.Cpk(resultUnit.MaxSpec, resultUnit.MinSpec) : 0.0;
            resultUnit.Cg = resultUnit.DataElements[0].UseMin && resultUnit.DataElements[0].UseMax ?
                            vdValue.Cg(resultUnit.MaxSpec - resultUnit.MinSpec) : 0.0;

            return resultUnit;
        }


        DataRow GetTestStepInfo(string strStepID, DataTable dtTestlist)
        {
            int nStepID = Convert.ToInt32(strStepID);

            DataRow dtRow = (from dtStepRow in dtTestlist.AsEnumerable()
                             where dtStepRow[eColTestlist.StepID.ToString()].ToString() == strStepID
                             select dtStepRow).FirstOrDefault();

            return dtRow;
        }

        void ShowTestStepSummary(TrendDataResult resultUnit)
        {
            vGridControlStepSummary.Rows.Clear();

            if (resultUnit == null || resultUnit.DataElements == null || resultUnit.DataElements.Count <= 0)
                return;

            EditorRow etRowStep;

            etRowStep = new EditorRow();
            etRowStep.Properties.Caption = "Average";
            etRowStep.Properties.Value = resultUnit.Average.ToString();
            vGridControlStepSummary.Rows.Add(etRowStep);

            etRowStep = new EditorRow();
            etRowStep.Properties.Caption = "Min";
            etRowStep.Properties.Value = resultUnit.Min.ToString();
            vGridControlStepSummary.Rows.Add(etRowStep);

            etRowStep = new EditorRow();
            etRowStep.Properties.Caption = "Max";
            etRowStep.Properties.Value = resultUnit.Max.ToString();
            vGridControlStepSummary.Rows.Add(etRowStep);

            etRowStep = new EditorRow();
            etRowStep.Properties.Caption = "Varaince";
            etRowStep.Properties.Value = resultUnit.Variance.ToString();
            vGridControlStepSummary.Rows.Add(etRowStep);

            etRowStep = new EditorRow();
            etRowStep.Properties.Caption = "Std. Dev.";
            etRowStep.Properties.Value = resultUnit.StdDev.ToString();
            vGridControlStepSummary.Rows.Add(etRowStep);

            etRowStep = new EditorRow();
            etRowStep.Properties.Caption = "Cp";
            etRowStep.Properties.Value = resultUnit.Cp.ToString();
            vGridControlStepSummary.Rows.Add(etRowStep);

            etRowStep = new EditorRow();
            etRowStep.Properties.Caption = "Cpk";
            etRowStep.Properties.Value = resultUnit.Cpk.ToString();
            vGridControlStepSummary.Rows.Add(etRowStep);

            etRowStep = new EditorRow();
            etRowStep.Properties.Caption = "Cg";
            etRowStep.Properties.Value = resultUnit.Cg.ToString();
            vGridControlStepSummary.Rows.Add(etRowStep);

            OnSizeChanged(vGridControlStepSummary);
        }

        void ShowProperties(TestTrendDataCollection data, DataRow dtRow)
        {
            vGridControlInfo.Rows.Clear();

            CategoryRow ctRow = new CategoryRow("Step Info.");
            vGridControlInfo.Rows.Add(ctRow);

            EditorRow etRowStep = new EditorRow();
            etRowStep.Properties.Caption = eColTestlist.StepID.ToString();
            etRowStep.Properties.Value = dtRow[eColTestlist.StepID.ToString()].ToString();
            vGridControlInfo.Rows.Add(etRowStep);

            etRowStep = new EditorRow();
            etRowStep.Properties.Caption = eColTestlist.Variant.ToString();
            etRowStep.Properties.Value = dtRow[eColTestlist.Variant.ToString()].ToString();
            vGridControlInfo.Rows.Add(etRowStep);

            etRowStep = new EditorRow();
            etRowStep.Properties.Caption = eColTestlist.Gate.ToString();
            etRowStep.Properties.Value = dtRow[eColTestlist.Gate.ToString()].ToString();
            vGridControlInfo.Rows.Add(etRowStep);

            etRowStep = new EditorRow();
            etRowStep.Properties.Caption = eColTestlist.Position.ToString();
            etRowStep.Properties.Value = dtRow[eColTestlist.Position.ToString()].ToString();
            vGridControlInfo.Rows.Add(etRowStep);

            etRowStep = new EditorRow();
            etRowStep.Properties.Caption = eColTestlist.StepDesc.ToString();
            etRowStep.Properties.Value = dtRow[eColTestlist.StepDesc.ToString()].ToString();
            vGridControlInfo.Rows.Add(etRowStep);

            etRowStep = new EditorRow();
            etRowStep.Properties.Caption = eColTestlist.UseFunction.ToString();
            etRowStep.Properties.Value = dtRow[eColTestlist.UseFunction.ToString()].ToString();
            vGridControlInfo.Rows.Add(etRowStep);

            etRowStep = new EditorRow();
            etRowStep.Properties.Caption = eColTestlist.Dim.ToString();
            etRowStep.Properties.Value = dtRow[eColTestlist.Dim.ToString()].ToString();
            vGridControlInfo.Rows.Add(etRowStep);

            etRowStep = new EditorRow();
            etRowStep.Properties.Caption = "Total";
            etRowStep.Properties.Value = data.Total.ToString();
            vGridControlInfo.Rows.Add(etRowStep);

            etRowStep = new EditorRow();
            etRowStep.Properties.Caption = "OK";
            etRowStep.Properties.Value = data.OK.ToString();
            vGridControlInfo.Rows.Add(etRowStep);

            etRowStep = new EditorRow();
            etRowStep.Properties.Caption = "NG";
            etRowStep.Properties.Value = data.NG.ToString();
            vGridControlInfo.Rows.Add(etRowStep);

            ctRow = new CategoryRow("Test Data Info.");
            vGridControlInfo.Rows.Add(ctRow);
            foreach (PropertyInfo propInf in data.SelectedData.GetType().GetProperties())
            {
                EditorRow etRow = new EditorRow();

                etRow.Properties.FieldName = propInf.Name;
                etRow.Name = propInf.Name;
                etRow.Properties.Caption = propInf.Name;

                if (propInf.Name == "TestRequestID")
                    etRow.Properties.Value = ((string[])propInf.GetValue(data.SelectedData, null))[0];
                else
                    etRow.Properties.Value = propInf.GetValue(data.SelectedData, null)?.ToString();

                //etRow.Properties.Value = propInf.GetValue(data.SelectedData, null)?.ToString();

                vGridControlInfo.Rows.Add(etRow);
            }

            OnSizeChanged(vGridControlInfo);
        }

        void OnSizeChanged(VGridControl grid)
        {
            int width = grid.ClientSize.Width / (grid.RecordCount + 1);
            grid.RecordWidth = width;
            grid.RowHeaderWidth = width;
        }

        private void UcTRADetailTestResult_Load(object sender, System.EventArgs e)
        {
        }

        private void simpleButtonAllData_Click(object sender, EventArgs e)
        {
            DataRow dtTestlistRow = GetTestStepInfo(SelectedData.StepNo, DTTestlistSrc);
            DataTable dtResult = gridControlMain.DataSource as DataTable;
            TrendDataResult resultUnit = MakeTrendSummary(dtResult, dtTestlistRow, SelectedData, false);
            bool bAutoRange = toggleSwitchAutoRange.IsOn;

            ShowTestStepSummary(resultUnit);
            ShowTrendChart(resultUnit, bAutoRange);
        }

        private void simpleButtonOKDataOnly_Click(object sender, EventArgs e)
        {
            DataRow dtTestlistRow = GetTestStepInfo(SelectedData.StepNo, DTTestlistSrc);
            DataTable dtResult = gridControlMain.DataSource as DataTable;
            TrendDataResult resultUnit = MakeTrendSummary(dtResult, dtTestlistRow, SelectedData);
            bool bAutoRange = toggleSwitchAutoRange.IsOn;

            ShowTestStepSummary(resultUnit);
            ShowTrendChart(resultUnit, bAutoRange);
        }

        public class TrendDataResult
        {
            public class StepDataElement
            {
                public int RowNo { get; set; }
                public DateTime TestTime { get; set; }
                public string ProductID { get; set; }
                public double Value { get; set; }
                public bool UseMin { get; set; }
                public bool UseMax { get; set; }
                public double Min { get; set; }
                public double Max { get; set; }
                public double Tolerance { get; set; }
                public eResultType Result { get; set; }
            }

            public double dSpecNotUse = -999999;
            public List<StepDataElement> DataElements { get; set; } = new List<StepDataElement>();
            public double Average { get; set; }
            public double Min { get; set; }
            public double Max { get; set; }
            public double Variance { get; set; }
            public double StdDev { get; set; }
            public double MinSpec { get; set; }
            public double MaxSpec { get; set; }
            public double Cp { get; set; }
            public double Cpk { get; set; }
            public double Cg { get; set; }

        }

        private void gridViewMain_RowCellClick(object sender, RowCellClickEventArgs e)
        {
            int nClickCnt = e.Clicks;

            int nRowHndl = e.RowHandle;

            if (nRowHndl < 0)
                return;

            string strGetId = DTTestLogList.Rows[e.RowHandle][18].ToString();

            BaseRow br = vGridControlInfo.Rows.GetRowByFieldName("TestRequestID");
            vGridControlInfo.SetCellValue(br, 0, strGetId);
        }

        private void chartControlMain_DoubleClick(object sender, EventArgs e)
        {
            SwiftPlotDiagram diagram = (SwiftPlotDiagram)chartControlMain.Diagram;

            if (diagram != null)
            {
                diagram.AxisY.WholeRange.Auto = !diagram.AxisY.WholeRange.Auto;

                if (diagram.AxisY.WholeRange.Auto)
                    chartControlMain.BackColor = Color.WhiteSmoke;
                else
                {
                    diagram.AxisY.WholeRange.SetMinMaxValues(dThisMinLimit - dThisUnitSize, dThisMaxLimit + dThisUnitSize);

                    chartControlMain.BackColor = Color.White;
                }
            }
        }
    }
}
