using DevExpress.Spreadsheet;
using DevExpress.XtraPrinting;
using DevExpress.XtraVerticalGrid;
using DevExpress.XtraVerticalGrid.Rows;
using System;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Windows.Forms;
using SystemX.Product.ALIS.Interface;
using SystemX.Product.TRA.DataManager;

using static SystemX.Product.CP.TRA.Commons;
using static SystemX.Product.TRA.DataManager.DMTestDetail;

namespace SystemX.Product.TRA.UIControl
{
    public partial class UcTRADetailTestResult : UcTRABaseView
    {
        public enum eColDataTable
        {
            StepNo,
            Position,
            Variant,
            Gate,
            MO,
            Function,
            Min,
            MeasuredValue,
            Max,
            Dimension,
            Result,
            Duration
        }

        DMTestDetail DataManager { get; set; }
        DetailTestDataCollection SearchSource { get; set; }
        DataTable DTTestlistSrc { get; set; } = null;
        DataTable DTTestLogSrc { get; set; } = null;

        string TextShowTL { get; } = "Display the Testlist";
        string TextShowLOG { get; } = "Display the Test Result";

        private string GridViewGetActiveFilterText;

        public UcTRADetailTestResult()
        {
            ContentsType = eContents.TestResult;

            //this.ContextMenuStrip = base.contextMenuStripTest;

            InitializeComponent();
        }

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


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

                Workbook wbook = new Workbook();

                wbook.LoadDocument(strFile);

                Worksheet worksheetInfo = wbook.Worksheets.Add("Detail Test 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.Columns.AutoFit(0, 3);
                worksheetInfo.AutoOutline();
                wbook.SaveDocument(strFile);
            }
        }

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

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

            return strFileName;
        }

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

            SearchSource = data;

            ShowProperties(data);

            DTTestLogSrc = DataManager.SearchTestHistory(data);
            DTTestlistSrc = DataManager.SearchTestlist(data);

            ShowDetailData(data);            
        }

        DataTable CombineLogForm()
        {
            if (DTTestLogSrc == null || DTTestlistSrc == null)
                return null;

            DataTable dtFinal = new DataTable();

            foreach(string strCol in Enum.GetNames(typeof(eColDataTable)))
            {
                Type typCol = typeof(string);

                if (strCol == eColDataTable.StepNo.ToString())
                    typCol = typeof(int);
                if (strCol == eColDataTable.Position.ToString())
                    typCol = typeof(int);
                else if (strCol == eColDataTable.Duration.ToString())
                    typCol = typeof(double);

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

            foreach (DataRow drLog in DTTestLogSrc.AsEnumerable())
            {
                //DataRow drTL = DTTestlistSrc.AsEnumerable().Where(x => Convert.ToInt32(x[eColTestlist.StepID.ToString()]) == Convert.ToInt32(drLog[eColTestLog.StepID.ToString()])).FirstOrDefault();
                
                //PK 기준 검색
                DataRow drTL = DTTestlistSrc.Rows.Find(drLog[eColTestLog.StepID.ToString()]);

                if (drTL == null)
                    continue;

                DataRow drDisp = dtFinal.NewRow();

                drDisp[eColDataTable.StepNo.ToString()] = Convert.ToInt32(Convert.ToInt32(drLog[eColTestLog.StepID.ToString()]));
                drDisp[eColDataTable.Position.ToString()] = Convert.ToInt32(Convert.ToInt32(drTL[eColTestlist.Position.ToString()]));
                drDisp[eColDataTable.Variant.ToString()] = drTL[eColTestlist.Variant.ToString()].ToString();
                drDisp[eColDataTable.Gate.ToString()] = drTL[eColTestlist.Gate.ToString()].ToString();
                drDisp[eColDataTable.MO.ToString()] = drTL[eColTestlist.StepDesc.ToString()].ToString();
                drDisp[eColDataTable.Function.ToString()] = drTL[eColTestlist.UseFunction.ToString()].ToString();

                bool bIsGlobal = (Convert.ToInt32(drTL[eColTestlist.IsGlobal.ToString()])) > 0 ? true : false;

                drDisp[eColDataTable.Min.ToString()] = bIsGlobal ? drLog[eColTestLog.GlobalMin.ToString()].ToString() : drTL[eColTestlist.SpecMin.ToString()].ToString();
                drDisp[eColDataTable.Max.ToString()] = bIsGlobal ? drLog[eColTestLog.GlobalMax.ToString()].ToString() : drTL[eColTestlist.SpecMax.ToString()].ToString();

                string strMessage = drLog[eColTestLog.Message.ToString()].ToString();
                string strMeasValStr = drLog[eColTestLog.MeasValStr.ToString()].ToString();
                string strMeasVal = drLog[eColTestLog.MeasVal.ToString()].ToString();

                string strMin = drDisp[eColDataTable.Min.ToString()].ToString();
                string strMax = drDisp[eColDataTable.Max.ToString()].ToString();

                bool bJustCallMacro = false;

                if (string.IsNullOrWhiteSpace(strMin) &&
                string.IsNullOrWhiteSpace(strMax) &&
                strMeasVal == "0.00000")
                    bJustCallMacro = true;

                /*
                string strDispValue = string.IsNullOrWhiteSpace(strMessage) ?
                    (string.IsNullOrWhiteSpace(strMeasValStr) ? strMeasVal : strMeasValStr) : strMessage;
                */

                string strDispValue = string.IsNullOrWhiteSpace(strMessage) ?
                    (string.IsNullOrWhiteSpace(strMeasValStr) ? (bJustCallMacro ? "" : strMeasVal) : strMeasValStr) : strMessage;

                drDisp[eColDataTable.MeasuredValue.ToString()] = strDispValue;

                drDisp[eColDataTable.Dimension.ToString()] = drTL[eColTestlist.Dim.ToString()].ToString();
                drDisp[eColDataTable.Result.ToString()] = drLog[eColTestLog.Result.ToString()].ToString();

                string strValue = drLog[(int)eColTestLog.Duration].ToString();
                double dVal = string.IsNullOrWhiteSpace(strValue) ? double.NaN : Convert.ToDouble(strValue);

                drDisp[eColDataTable.Duration.ToString()] = dVal;

                dtFinal.Rows.Add(drDisp);
            }

            return dtFinal;
        }

        void ShowDetailData(DetailTestDataCollection data)
        {
            DataTable dtResult = CombineLogForm();

            GridViewGetActiveFilterText = gridViewMain.ActiveFilterString;

            gridControlMain.BeginInit();

            gridControlMain.DataSource = dtResult;

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

            gridViewMain.ActiveFilterString = GridViewGetActiveFilterText;
        }

        void ShowTestlistData(DetailTestDataCollection data)
        {
            DataTable dtResult = DTTestlistSrc;

            GridViewGetActiveFilterText = gridViewMain.ActiveFilterString;

            gridControlMain.BeginInit();

            gridControlMain.DataSource = dtResult;

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

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

            gridControlMain.EndInit();

            gridViewMain.ActiveFilterString = GridViewGetActiveFilterText;
        }

        void ShowProperties(DetailTestDataCollection data)
        {
            vGridControlInfo.Rows.Clear();

            foreach (PropertyInfo propInf in data.GetType().GetProperties())
            {
                EditorRow dtRow = new EditorRow();

                dtRow.Properties.Caption = propInf.Name;
                dtRow.Properties.Value = propInf.GetValue(data, null)?.ToString();

                vGridControlInfo.Rows.Add(dtRow);
            }

            OnSizeChanged(vGridControlInfo);

            if (data.TestResult.ToUpper() == "OK")
                panelControlResult.Appearance.BackColor = Color.LightGreen;
            else
                panelControlResult.Appearance.BackColor = Color.IndianRed;
        }

        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)
        {
            simpleButtonTypeConv.Text = TextShowTL;
        }

        private void simpleButtonTypeConv_Click(object sender, System.EventArgs e)
        {
            if(simpleButtonTypeConv.Text == TextShowLOG)
            {
                simpleButtonTypeConv.Text = TextShowTL;
                ShowDetailData(SearchSource);
            }
            else
            {
                simpleButtonTypeConv.Text = TextShowLOG;
                ShowTestlistData(SearchSource);
            }
        }
    }
}
