using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using SystemX.Product.TRA.DataManager;
using DevExpress.Utils;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using DevExpress.XtraPrinting;
using SystemX.Product.ALIS.Interface;
using DevExpress.XtraGrid.Columns;
using SystemX.Product.CP.TRA;
using System.Diagnostics;

using static SystemX.Product.CP.TRA.MainForm;
using static SystemX.Product.CP.TRA.Commons;

namespace SystemX.Product.TRA.UIControl
{
    public partial class UcTRATestNgHist : UcTRABaseView
    {
        public enum eColHide
        {
            No,
            AccessKey
        }

        DMTestNgHistory DataManager { get; set; }
        TestHistorySearchOption Option { get; set; }
        SelectedDataCollection SelectedData { get; set; }

        DetailTestDataCollection[] drNgDetailInfo;

        DMTestDetail DetailDataManager { get; set; }


        private bool bSelectedTime_DaySearched = false;

        public DataTable DataResult { get; private set; }

        public delegate void evtDataDetailViewHandler(DetailTestDataCollection data);
        public event evtDataDetailViewHandler OnDetailSelect;

        private IChildController refChildInterface;

        int nCurrentRowSelected = int.MaxValue;

        private bool bSearchVisibleOption = false;

        private string GridViewGetActiveFilterText;

        public UcTRATestNgHist(IChildController getChildControl, bool bSearchOptionVisible = false, bool bSelectTime_Day = false)
        {
            ContentsType = eContents.NgHistory;

            refChildInterface = getChildControl;

            SetMenuEnabled(ContentsType);

            bSelectedTime_DaySearched = bSelectTime_Day;

            InitializeComponent();

            gridViewMain.RowClick += gridViewMain_Click;

            bSearchVisibleOption = bSearchOptionVisible;

            drNgDetailInfo = null;
        }

        ~UcTRATestNgHist()
        {
        }

        public void SetSQLConnection(eSelectDataView SelectView, IDataBaseController getDBController)
        {
            DataManager = new DMTestNgHistory(SelectView, getDBController);

            DetailDataManager = new DMTestDetail(SelectView, getDBController);
        }

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

            SelectedData = data;

            /*
            DataTable dtResult = DataManager.SearchTestHistory(data, Option);
            DataColumn dcVal = dtResult.Columns.Add("No.", typeof(int));

            DisplayResultTable(dtResult);
            */

            DataTable dtResult = null;
            DataTable dtMergeResult = new DataTable();

            if (SelectedData.GetCountRequestID() > 1)
            {
                int nCnt = SelectedData.GetCountRequestID();
                for (int i = 0; i < nCnt; i++)
                {
                    dtResult = DataManager.SearchTestNgHistory(data, Option, i);

                    dtMergeResult.Merge(dtResult);
                }
            }
            else
            {
                dtResult = DataManager.SearchTestNgHistory(data, Option);

                dtMergeResult.Merge(dtResult);
            }

            DataColumn dcVal = dtMergeResult.Columns.Add("No.", typeof(int));

            DisplayResultTable(dtMergeResult);
        }

        void DisplayResultSummary(DataTable dtResult)
        {
            int nOKTestCount = (from drData in dtResult.AsEnumerable()
                                where drData[DMTestHistory.eColList.TestResult.ToString()].ToString() == "OK"
                                select drData).Count();
            int nNGTestCount = (from drData in dtResult.AsEnumerable()
                                where drData[DMTestHistory.eColList.TestResult.ToString()].ToString() == "NG"
                                select drData).Count();
            List<int> vnTestTime = (from drData in dtResult.AsEnumerable()
                                            where drData[DMTestHistory.eColList.TestResult.ToString()].ToString() == "OK"
                                                || drData[DMTestHistory.eColList.TestResult.ToString()].ToString() == "NG"
                                            let nTime = Convert.ToInt32(drData[DMTestHistory.eColList.Duration.ToString()].ToString())
                                            select nTime).ToList();

            double dRatio = (((double)(nOKTestCount * 100)) / (nOKTestCount + nNGTestCount));
            labelControlTestResult.Text = $"{nOKTestCount + nNGTestCount} (OK: {nOKTestCount}/NG: {nNGTestCount}) - Ratio: {dRatio.ToString(".##")}%";

            labelControlTestTime.Text = vnTestTime.Count > 0 ? 
                $"Average = {(vnTestTime.Average()/1000).ToString(".##")}s, Min = {(((double)vnTestTime.Min()) / 1000).ToString(".##")}s, Max = {(((double)vnTestTime.Max()) / 1000).ToString(".##")}s" :
                $"Average = -, Min = -, Max = -";
        }

        private DataTable MakeNgTable()
        {
            // Create a new DataTable titled 'Names.'
            DataTable NgTable = new DataTable("TestResult");

            /*
            public ulong LogNo { get; set; }
            public int LogCount { get; set; }
            public ulong AccessStart { get; set; }
            public ulong AccessEnd { get; set; }
            public DateTime StartTime { get; set; }
            public long Duration { get; set; }
            public string StationName { get; set; }
            public string HostID { get; set; }
            public string SectionID { get; set; }
            public string TestType { get; set; }
            public string ProductID { get; set; }
            public string ProductNo { get; set; }
            public string TestCode { get; set; }
            public string ParentNo { get; set; }
            public string FileCode { get; set; }
            public string FileVersion { get; set; }
            public string TestlistFile { get; set; }
            public string TestlistNo { get; set; }
            public string StepVersion { get; set; }
            public string TestRequestID { get; set; }
            public string TestResult { get; set; } 
            */

            // Add three column objects to the table.
            DataColumn Column1000 = new DataColumn();
            Column1000.DataType = System.Type.GetType("System.Int64");
            Column1000.ColumnName = "No.";
            Column1000.AllowDBNull = true;
            NgTable.Columns.Add(Column1000);

            DataColumn Column0 = new DataColumn();
            Column0.DataType = System.Type.GetType("System.DateTime");
            Column0.ColumnName = "StartTime";
            Column0.AllowDBNull = true;
            NgTable.Columns.Add(Column0);

            DataColumn Column1 = new DataColumn();
            Column1.DataType = System.Type.GetType("System.Int64");
            Column1.ColumnName = "Duration";
            Column1.AllowDBNull = true;
            NgTable.Columns.Add(Column1);

            DataColumn Column2 = new DataColumn();
            Column2.DataType = System.Type.GetType("System.String");
            Column2.ColumnName = "StationName";
            Column2.AllowDBNull = true;
            NgTable.Columns.Add(Column2);

            DataColumn Column3= new DataColumn();
            Column3.DataType = System.Type.GetType("System.String");
            Column3.ColumnName = "HostID";
            Column3.AllowDBNull = true;
            NgTable.Columns.Add(Column3);

            DataColumn Column4= new DataColumn();
            Column4.DataType = System.Type.GetType("System.String");
            Column4.ColumnName = "SectionID";
            Column4.AllowDBNull = true;
            NgTable.Columns.Add(Column4);

            DataColumn Column5 = new DataColumn();
            Column5.DataType = System.Type.GetType("System.String");
            Column5.ColumnName = "ProductID";
            Column5.AllowDBNull = true;
            NgTable.Columns.Add(Column5);

            DataColumn Column6= new DataColumn();
            Column6.DataType = System.Type.GetType("System.String");
            Column6.ColumnName = "ProductNo";
            Column6.AllowDBNull = true;
            NgTable.Columns.Add(Column6);

            DataColumn Column7 = new DataColumn();
            Column7.DataType = System.Type.GetType("System.String");
            Column7.ColumnName = "ParentNo";
            Column7.AllowDBNull = true;
            NgTable.Columns.Add(Column7);

            DataColumn Column101 = new DataColumn();
            Column101.DataType = System.Type.GetType("System.Int64");
            Column101.ColumnName = "AccessKey";
            Column101.AutoIncrement = false;
            Column101.AllowDBNull = false;
            NgTable.Columns.Add(Column101);

            DataColumn Column102 = new DataColumn();
            Column102.DataType = System.Type.GetType("System.Int64");
            Column102.ColumnName = "Position";
            Column102.AllowDBNull = true;
            NgTable.Columns.Add(Column102);

            DataColumn Column103 = new DataColumn();
            Column103.DataType = System.Type.GetType("System.Int64");
            Column103.ColumnName = "Step";
            Column103.AllowDBNull = false;
            NgTable.Columns.Add(Column103);

            DataColumn Column104 = new DataColumn();
            Column104.DataType = System.Type.GetType("System.String");
            Column104.ColumnName = "ModName";
            Column104.AllowDBNull = false;
            NgTable.Columns.Add(Column104);

            DataColumn Column105 = new DataColumn();
            Column105.DataType = System.Type.GetType("System.String");
            Column105.ColumnName = "Min";
            Column105.AllowDBNull = true;
            NgTable.Columns.Add(Column105);

            DataColumn Column106 = new DataColumn();
            Column106.DataType = System.Type.GetType("System.String");
            Column106.ColumnName = "Value";
            Column106.AllowDBNull = true;
            NgTable.Columns.Add(Column106);

            DataColumn Column107 = new DataColumn();
            Column107.DataType = System.Type.GetType("System.String");
            Column107.ColumnName = "Max";
            Column107.AllowDBNull = true;
            NgTable.Columns.Add(Column107);

            DataColumn Column1001 = new DataColumn();
            Column1001.DataType = System.Type.GetType("System.String");
            Column1001.ColumnName = "Dim";
            Column1001.AllowDBNull = true;
            NgTable.Columns.Add(Column1001);

            /*
            DataColumn Column103= new DataColumn();
            Column103.DataType = System.Type.GetType("System.Decimal");
            Column103.ColumnName = "MeasVal";
            Column103.AllowDBNull = true;
            NgTable.Columns.Add(Column103);

            DataColumn Column104 = new DataColumn();
            Column104.DataType = System.Type.GetType("System.String");
            Column104.ColumnName = "MeasValStr";
            Column104.AllowDBNull = true;
            NgTable.Columns.Add(Column104);

            DataColumn Column105 = new DataColumn();
            Column105.DataType = System.Type.GetType("System.String");
            Column105.ColumnName = "Message";
            Column105.AllowDBNull = true;
            NgTable.Columns.Add(Column105);

            DataColumn Column106 = new DataColumn();
            Column106.DataType = System.Type.GetType("System.String");
            Column106.ColumnName = "GlobalMin";
            Column106.AllowDBNull = true;
            NgTable.Columns.Add(Column106);

            DataColumn Column107 = new DataColumn();
            Column107.DataType = System.Type.GetType("System.String");
            Column107.ColumnName = "GlobalMax";
            Column107.AllowDBNull = true;
            NgTable.Columns.Add(Column107);
            */

            DataColumn Column108 = new DataColumn();
            Column108.DataType = System.Type.GetType("System.String");
            Column108.ColumnName = "Result";
            Column108.AllowDBNull = false;
            NgTable.Columns.Add(Column108);

            DataColumn Column109 = new DataColumn();
            Column109.DataType = System.Type.GetType("System.String");
            Column109.ColumnName = "SpentTime";
            Column109.AllowDBNull = true;
            NgTable.Columns.Add(Column109);

            // Create an array for DataColumn objects.
            DataColumn[] keys = new DataColumn[1];
            keys[0] = Column101;
            NgTable.PrimaryKey = keys;

            // Return the new DataTable.
            return NgTable;
        }

        void DisplayResultTable(DataTable dtResult)
        {
            DataResult = dtResult;

            int nLoopCnt = 0;
            /* DataResult.Rows.Count;
            for (int i = 0; i < nLoopCnt; i++)
            {
                for (int j = 0; j < DataResult.Rows.Count; j++)
                {
                    string strResult = DataResult.Rows[j][DMTestHistory.eColList.TestResult.ToString()].ToString();

                    if (strResult != "NG" && strResult != "SYSTEM_ERROR" && strResult != "STOP")
                    {
                        DataResult.Rows.RemoveAt(j);

                        break;
                    }
                }
            }
            */
            //

            nLoopCnt = DataResult.Rows.Count;
            DataRow[] drNgs = new DataRow[nLoopCnt];
            DataTable dtNg = MakeNgTable();

            drNgDetailInfo = new DetailTestDataCollection[nLoopCnt];

            int[] nCheckTestListFileNo = new int[2];
            nCheckTestListFileNo[0] = int.MinValue;
            nCheckTestListFileNo[1] = int.MinValue;

            string[] strCheckTestListFileNo = new string[2];
            strCheckTestListFileNo[0] = string.Empty;
            strCheckTestListFileNo[1] = string.Empty;

            int nSetTestListFileNo = int.MinValue;

            int nUseVersion = int.MaxValue;

            DataTable dtTLInfo = null;

            StringBuilder sbCheckTestListInfo = new StringBuilder();

            /*
            Stopwatch stTimeCheck = new Stopwatch();
            stTimeCheck.Start();
            */

            for (int i = 0; i < nLoopCnt; i++)
            {
                drNgDetailInfo[i] = new DetailTestDataCollection();
                DataRow dr = DataResult.Rows[i];

                drNgDetailInfo[i] = GetSearchInfo(dr);

                int nSetCurTestListFileNo = int.MinValue;
                int nUseTestListFileNo = int.MaxValue;

                int nUseTestListVariantNo = int.MaxValue;
                if (int.TryParse(drNgDetailInfo[i].TestListFileNo, out nUseTestListFileNo) == false)
                    continue;
                if (int.TryParse(drNgDetailInfo[i].TestListVariantNo, out nUseTestListVariantNo) == false)
                    continue;

                int nCurUseVersion = int.MaxValue;
                if (int.TryParse(drNgDetailInfo[i].StepVersion, out nCurUseVersion) == false)
                    continue;

                if (sbCheckTestListInfo.Length <= 0)
                {
                    sbCheckTestListInfo.Append(drNgDetailInfo[i].ProductNo +
                        drNgDetailInfo[i].TestCode +
                        drNgDetailInfo[i].TestType +
                        drNgDetailInfo[i].FileVersion + 
                        drNgDetailInfo[i].FileCode);

                    nCheckTestListFileNo = DataManager.CheckTestListFileNo(drNgDetailInfo[i].ProductNo, drNgDetailInfo[i].TestCode, drNgDetailInfo[i].TestType, drNgDetailInfo[i].FileVersion, drNgDetailInfo[i].FileCode);
                }
                else
                {
                    string strSetTestListInfo = drNgDetailInfo[i].ProductNo +
                        drNgDetailInfo[i].TestCode +
                        drNgDetailInfo[i].TestType +
                        drNgDetailInfo[i].FileVersion +
                        drNgDetailInfo[i].FileCode;

                    if (sbCheckTestListInfo.ToString().CompareTo(strSetTestListInfo) != 0)
                    {
                        sbCheckTestListInfo.Clear();
                        sbCheckTestListInfo.Append(strSetTestListInfo);

                        nCheckTestListFileNo = DataManager.CheckTestListFileNo(drNgDetailInfo[i].ProductNo, drNgDetailInfo[i].TestCode, drNgDetailInfo[i].TestType, drNgDetailInfo[i].FileVersion, drNgDetailInfo[i].FileCode);
                    }
                }

                strCheckTestListFileNo[0] = nCheckTestListFileNo[0].ToString();
                strCheckTestListFileNo[1] = nCheckTestListFileNo[1].ToString();

                if (nCheckTestListFileNo[0] == int.MinValue)
                    nSetCurTestListFileNo = nUseTestListFileNo;
                else
                {
                    if (strCheckTestListFileNo[0].CompareTo(nUseTestListFileNo.ToString()) == 0 &&
                        strCheckTestListFileNo[1].CompareTo(nUseTestListVariantNo.ToString()) == 0)
                        nSetCurTestListFileNo = nUseTestListFileNo;
                    else
                        nSetCurTestListFileNo = nCheckTestListFileNo[0];
                }

                if (nSetTestListFileNo == int.MinValue || nUseVersion == int.MaxValue)
                {
                    nSetTestListFileNo = nSetCurTestListFileNo;
                    nUseVersion = nCurUseVersion;

                    dtTLInfo = DataManager.GetUseTestListInformation(nSetTestListFileNo, nUseVersion);
                }
                else
                {
                    if(nSetTestListFileNo != nSetCurTestListFileNo || nUseVersion != nCurUseVersion)
                    {
                        nSetTestListFileNo = nSetCurTestListFileNo;
                        nUseVersion = nCurUseVersion;

                        dtTLInfo = DataManager.GetUseTestListInformation(nSetTestListFileNo, nUseVersion);
                    }    
                }

                if (Commons.isHasRow(dtTLInfo) == false)
                    continue;

                DataTable dtTestLog = DetailDataManager.SearchTestHistory(drNgDetailInfo[i]);

                drNgs[i] = null;

                Int64 nAccessKey = Int64.MaxValue;

                try
                {
                    drNgs[i] = dtNg.NewRow();

                    DataRow drNgInfo = null;
                    //drNgInfo = dtTestLog.AsEnumerable().Where(Row => Row.Field<string>("Result") == "NG").OrderBy(Row => Row.Field<Int64>("StepID")).ElementAt(0);
                    //lTime[6] = stTime.ElapsedMilliseconds;
                    //drNgInfo = dtTestLog.AsEnumerable().First(Row => Row.Field<string>("Result") == "NG");
                    //lTime[7] = stTime.ElapsedMilliseconds;
                    drNgInfo = dtTestLog.Select("Result = 'NG'", "StepID ASC").First();

                    if (drNgInfo != null)
                    {
                        drNgs[i][0] = (i + 1).ToString();
                        drNgs[i][1] = drNgDetailInfo[i].StartTime;
                        drNgs[i][2] = drNgDetailInfo[i].Duration;
                        drNgs[i][3] = drNgDetailInfo[i].StationName;
                        drNgs[i][4] = drNgDetailInfo[i].HostID;
                        drNgs[i][5] = drNgDetailInfo[i].SectionID;
                        drNgs[i][6] = drNgDetailInfo[i].ProductID;
                        drNgs[i][7] = drNgDetailInfo[i].ProductNo;
                        drNgs[i][8] = drNgDetailInfo[i].ParentNo;

                        DataRow GetTLRow = null;

                        try
                        {
                            GetTLRow = dtTLInfo.Rows.Find(drNgInfo["StepID"]);
                        }
                        catch
                        {
                            GetTLRow = null;
                        }
                        /*
                        DataRow[] GetTLRows = null;
                        try
                        {
                            GetTLRows = dtTLInfo.Select($"StepID = {drNgInfo["StepID"].ToString()}", "StepVersion DESC");
                        }
                        catch
                        {
                            GetTLRows = null;
                        }

                        DataRow GetTLRow = null;

                        if (GetTLRows != null)
                        {
                            try
                            {
                                GetTLRow = GetTLRows.First(x => x.ItemArray[6].ToString() == nUseVersion.ToString());
                            }
                            catch
                            {
                                GetTLRow = null;
                            }
                            finally
                            {
                                if (GetTLRow == null)
                                    GetTLRow = GetTLRows[0];
                            }
                        }
                        */

                        bool bIsGlobal = (Convert.ToInt32(GetTLRow["IsGlobal"])) > 0 ? true : false;

                        nAccessKey = Int64.Parse(drNgInfo["AccessKey"].ToString());
                        drNgs[i][9] = drNgInfo["AccessKey"];

                        drNgs[i][10] = (GetTLRow != null) ? GetTLRow[8] : "";
                        drNgs[i][11] = drNgInfo["StepID"];
                        drNgs[i][12] = (GetTLRow != null) ? GetTLRow[9] : "";
                        //
                        drNgs[i][13] = bIsGlobal ? drNgInfo["GlobalMin"] : GetTLRow["SpecMin"];

                        if (GetTLRow != null)
                        {
                            if (drNgInfo["Message"].ToString().Length > 0)
                                drNgs[i][14] = drNgInfo["Message"];
                            else if (drNgInfo["MeasValStr"].ToString().Length > 0)
                                drNgs[i][14] = drNgInfo["MeasValStr"];
                            else
                                drNgs[i][14] = drNgInfo["MeasVal"].ToString();
                        }
                        else
                            drNgs[i][14] = "";

                        drNgs[i][15] = bIsGlobal ? drNgInfo["GlobalMax"] : GetTLRow["SpecMax"];
                        //
                        drNgs[i][16] = (GetTLRow != null) ? GetTLRow[16] : "";
                        drNgs[i][17] = drNgInfo["Result"];
                        drNgs[i][18] = drNgInfo["SpentTime"];
                    }
                }
                catch (Exception e)
                {
                    drNgs[i] = null;
                }

                if (drNgs[i] != null)
                {
                    if (dtNg.Rows.Find(nAccessKey) == null)
                        dtNg.Rows.Add(drNgs[i]);
                    else
                    {
                        ;// Debug Pt
                    }
                }
            }

            //long lCheckTime = stTimeCheck.ElapsedMilliseconds;

            GridViewGetActiveFilterText = gridViewMain.ActiveFilterString;

            gridControlMain.BeginInit();

            gridControlMain.DataSource = dtNg;

            gridControlMain.Update();
            gridControlMain.RefreshDataSource();
            gridControlMain.ForceInitialize();
            gridViewMain.PopulateColumns(dtNg);

            foreach (string strColName in Enum.GetNames(typeof(eColHide)))
            {
                if (gridViewMain.Columns.ColumnByFieldName(strColName) != null)
                    gridViewMain.Columns[strColName].Visible = false;
            }

            gridControlMain.EndInit();
            gridViewMain.BeginUpdate();

            foreach (GridColumn gc in gridViewMain.Columns)
            {
                if (gc.FieldName.CompareTo("StartTime") == 0)
                {
                    gc.OptionsColumn.AllowMerge = DevExpress.Utils.DefaultBoolean.True;
                    gc.DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime;
                    gc.DisplayFormat.FormatString = "yyyy-MM-dd HH:mm:ss.fff";
                }
                else
                    gc.OptionsColumn.AllowMerge = DevExpress.Utils.DefaultBoolean.False;
            }

            /*
            int nRowNoIdx = 0;

            for (int i = 0; i < gridViewMain.RowCount; i++)
            {
                DataRowView drvRow = gridViewMain.GetRow(i) as DataRowView;
                string strResult = drvRow[DMTestHistory.eColList.TestResult.ToString()].ToString();

                if (strResult == "NG" || strResult == "OK" || strResult == "STOP")
                {
                    nRowNoIdx++;

                    drvRow["No."] = nRowNoIdx;
                }
                else
                    drvRow["No."] = -1;
            }

            gridViewMain.Columns["No."].VisibleIndex = 0;
            gridViewMain.OptionsView.AllowCellMerge = true;
            gridViewMain.Columns[DMTestHistory.eColList.TestlistReqID.ToString()].OptionsColumn.AllowMerge = DefaultBoolean.True;
            */

            gridViewMain.BestFitColumns();
            gridViewMain.EndUpdate();

            gridViewMain.ActiveFilterString = GridViewGetActiveFilterText;         
        }

        public DetailTestDataCollection GetSearchInfo(DataRow dtRow)
        {
            DetailTestDataCollection drDetail = new DetailTestDataCollection();

            //drDetail.TestID = dtRow[DMTestHistory.eColList.TestID.ToString()].ToString();
            drDetail.StartTime = DateTime.Parse(dtRow[DMTestHistory.eColList.TestDateTime.ToString()].ToString());

            string strGetLogNo = dtRow[DMTestHistory.eColList.LogNo.ToString()].ToString();
            if (strGetLogNo.Length > 0)
                drDetail.LogNo = Convert.ToUInt64(dtRow[DMTestHistory.eColList.LogNo.ToString()]);
            else
                drDetail.LogNo = ulong.MinValue;

            drDetail.LogCount = Convert.ToInt32(dtRow[DMTestHistory.eColList.LogCount.ToString()]);
            drDetail.AccessStart = Convert.ToUInt64(dtRow[DMTestHistory.eColList.AccessStart.ToString()]);
            drDetail.AccessEnd = Convert.ToUInt64(dtRow[DMTestHistory.eColList.AccessEnd.ToString()]);
            drDetail.Duration =  Convert.ToInt64(dtRow[DMTestHistory.eColList.Duration.ToString()]);
            drDetail.StationName = dtRow[DMTestHistory.eColList.StationName.ToString()].ToString();
            drDetail.HostID = dtRow[DMTestHistory.eColList.Host.ToString()].ToString();
            drDetail.SectionID = dtRow[DMTestHistory.eColList.Section.ToString()].ToString();
            drDetail.TestType = dtRow[DMTestHistory.eColList.TestType.ToString()].ToString();
            drDetail.ProductID = dtRow[DMTestHistory.eColList.ProductID.ToString()].ToString();
            drDetail.ProductNo = dtRow[DMTestHistory.eColList.ProductNo.ToString()].ToString();
            drDetail.TestCode = dtRow[DMTestHistory.eColList.TestCode.ToString()].ToString();
            drDetail.ParentNo = dtRow[DMTestHistory.eColList.ParentNo.ToString()].ToString();
            drDetail.FileCode = dtRow[DMTestHistory.eColList.FileCode.ToString()].ToString();
            drDetail.FileVersion = dtRow[DMTestHistory.eColList.FileVersion.ToString()].ToString();
            drDetail.TestlistFileName = dtRow[DMTestHistory.eColList.TestlistFileName.ToString()].ToString();
            drDetail.TestListFileNo = dtRow[DMTestHistory.eColList.TestListFileNo.ToString()].ToString();
            drDetail.TestListVariantNo = dtRow[DMTestHistory.eColList.TestListVariantNo.ToString()].ToString();
            drDetail.StepVersion = dtRow[DMTestHistory.eColList.StepVersion.ToString()].ToString();
            drDetail.TestRequestID = dtRow[DMTestHistory.eColList.TestlistReqID.ToString()].ToString();
            drDetail.TestResult = dtRow[DMTestHistory.eColList.TestResult.ToString()].ToString();

            return drDetail;
        }

        private void UcTRATestHistHost_Load(object sender, EventArgs e)
        {
            Option = new TestHistorySearchOption();

            FrmOptionStationSearch dlgSearch = new FrmOptionStationSearch(bSearchVisibleOption, bSelectedTime_DaySearched);

            if (bSearchVisibleOption)
            {
                dlgSearch.ShowDialog();

                if (dlgSearch.DialogResult == DialogResult.OK)
                    Option = dlgSearch.GetSelectedResult();
            }
            else
                Option = dlgSearch.GetSelectedResult();
        }

        private void SetDetailDataView()
        {
            if(nCurrentRowSelected != int.MaxValue)
            {
                var dvRow = gridViewMain.GetRow(nCurrentRowSelected);
                DataRow dtRow = (dvRow as DataRowView).Row;
                DetailTestDataCollection drDetail = GetSearchInfo(dtRow);

                OnDetailSelect(drDetail);
            }
        }
        private void gridViewMain_Click(object sender, EventArgs e)
        {
            DXMouseEventArgs ea = e as DXMouseEventArgs;
            GridView view = sender as GridView;

            GridHitInfo info = view.CalcHitInfo(ea.Location);

            if (info.InRow || info.InRowCell)
                nCurrentRowSelected = info.RowHandle;
            else
                nCurrentRowSelected = int.MaxValue;
        }

        private void gridViewMain_DoubleClick(object sender, EventArgs e)
        {
            DXMouseEventArgs ea = e as DXMouseEventArgs;
            GridView view = sender as GridView;
            GridHitInfo info = view.CalcHitInfo(ea.Location);

            if (info.InRow || info.InRowCell)
            {
                int nRow = int.MinValue;

                nRow = info.RowHandle;

                if (nRow < 0)
                    return;

                /*
                var dvRow = view.GetRow(nRow);
                DataRow dtRow = (dvRow as DataRowView).Row;
                DetailTestDataCollection drDetail = GetSearchInfo(dtRow);

                OnDetailSelect(drDetail);
                */

                if (drNgDetailInfo != null)
                    OnDetailSelect(drNgDetailInfo[nRow]);
            }
        }

        public List<DetailTestDataCollection> GetResultContents()
        {
            List<DetailTestDataCollection> vDetailData = new List<DetailTestDataCollection>();
            GridView view = gridViewMain as GridView;

            for(int i=0; i<view.RowCount; i++)
            {
                DataRow dtRow = (view.GetRow(i) as DataRowView).Row;
                DetailTestDataCollection dtContent = GetSearchInfo(dtRow);

                vDetailData.Add(dtContent);
            }

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

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

            return strFileName;
        }

        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 = "Test History";
                gridControlMain.ExportToXlsx(strFile, option);
                
            }
        }

        private void gridViewMain_CellMerge(object sender, CellMergeEventArgs e)
        {
            if (e.Column.FieldName == DMTestHistory.eColList.TestlistReqID.ToString())
            {
                GridView view = sender as GridView;
                string val1 = view.GetRowCellValue(e.RowHandle1, e.Column).ToString();
                string val2 = view.GetRowCellValue(e.RowHandle2, e.Column).ToString();
                e.Merge = val1 == val2;
                e.Handled = true;
            }
            else
            {
                e.Merge = false;
                e.Handled = true;
            }                    
        }
    }
}
