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.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Columns;
using SystemX.Product.TRA.UIControl.Helper;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using SystemX.Product.ALIS.Interface;
using static SystemX.Net.Platform.Common.Util.LogMessage;
using SystemX.Net.Platform.Common.Util;
using static SystemX.Product.CP.TRA.Commons;

namespace SystemX.Product.TRA.UIControl
{
    public partial class UcTRADetailOverview : UcTRABaseView
    {
        public enum eColHide
        {
            TestlistNo,
            StepVersion,
            RN
        }

        DMDetailOverview DataManager { get; set; }

        public string GetUseQuery()
        {
            return DataManager.strDetailOverviewUseQuery;
        }

        public OverviewSearchOption Option { get; set; }

        public delegate void evtDataSelectHandler(SelectedDataCollection data);
        public event evtDataSelectHandler OnSelect;

        public DateTime SearchStart { get; set; }
        public DateTime SearchEnd { get; set; }

        private IChildController refChildInterface;

        private string GridViewGetActiveFilterText;

        private bool bProductMergeOption = false;

        private int nMergeDataCnt;

        private string[] strMergeReqIDs;

        public UcTRADetailOverview(IChildController getChildControl, bool bAllowMerge = false, bool bAutoFilterRow = false)
        {
            ContentsType = eContents.DetailOverview;

            refChildInterface = getChildControl;

            this.ContextMenuStrip = base.contextMenuStripTest;

            this.ContextMenuStrip.ItemClicked += contextMenuStrip_ItemClicked;

            base.toolStripMenuItemBeginRelDate.Click += contextMenuStripBeginRelDate_ItemClicked;

            SetMenuEnabled(ContentsType);

            bProductMergeOption = bAllowMerge;

            InitializeComponent();

            gridViewMain.OptionsView.AllowCellMerge = true;
            gridViewMain.OptionsView.ShowAutoFilterRow = bAutoFilterRow;
        }

        ~UcTRADetailOverview()
        {
            this.ContextMenuStrip.ItemClicked -= contextMenuStrip_ItemClicked;

            base.toolStripMenuItemBeginRelDate.Click -= contextMenuStripBeginRelDate_ItemClicked;
        }

        private void contextMenuStripBeginRelDate_ItemClicked(object sender, EventArgs e)
        {
            int nTag = Convert.ToInt32(((ToolStripMenuItem)sender).Tag);

            switch (nTag)
            {
                case 7:
                    {
                        string GetDateValue = base.toolStripTextBoxBeginRelDate.Text;
                        int nGetDateValue = int.MaxValue;

                        if (int.TryParse(GetDateValue, out nGetDateValue))
                        {
                            if (nGetDateValue > 7)
                                nGetDateValue = 7;
                            if (nGetDateValue < -7)
                                nGetDateValue = -7;

                            ViewData(nGetDateValue);
                        }
                    }
                    break;
            }
        }
        private void contextMenuStrip_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            ToolStripItem tsp = e.ClickedItem;

            int nTag = Convert.ToInt32(tsp.Tag);

            switch (nTag)
            {
                case 0:
                    refChildInterface.SetOverview();
                    break;
                case 1:
                    refChildInterface.SetHistoryView();
                    break;
                case 2:
                    break;
                case 3:
                    break;
                case 4:
                    refChildInterface.SetNgHistView(ContentsType);
                    break;
            }
        }

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

        public void SetGridViewStyle()
        {
            gridViewMain.BeginUpdate();

            foreach (GridColumn gc in gridViewMain.Columns)
            {
                if (gc.FieldName.CompareTo("TestDate") == 0)
                    gc.OptionsColumn.AllowMerge = DevExpress.Utils.DefaultBoolean.True;
                else if (gc.FieldName.CompareTo("Host") == 0)
                    gc.OptionsColumn.AllowMerge = DevExpress.Utils.DefaultBoolean.True;
                else
                    gc.OptionsColumn.AllowMerge = DevExpress.Utils.DefaultBoolean.False;
            }

            gridViewMain.EndUpdate();

            gridViewMain.ActiveFilterString = GridViewGetActiveFilterText;
        }

        public void ViewData(int nGetDateValue = int.MaxValue)
        {
            Option = new OverviewSearchOption();

            Option.DisplayByStation = !refChildInterface.GetOverviewMergeState();

            DataTable dtResult = DataManager.GetDataView(refChildInterface.GetSelectDataOverView(nGetDateValue), Option);

            GridViewGetActiveFilterText = gridViewMain.ActiveFilterString;

            gridControlMain.DataSource = null;
            gridControlMain.RefreshDataSource();
            gridViewMain.RefreshData();

            gridControlMain.DataSource = dtResult;
            gridControlMain.RefreshDataSource();
            gridViewMain.RefreshData();
            gridControlMain.ForceInitialize();
            gridViewMain.PopulateColumns(dtResult);

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

            gridControlMain.Update();

            SetGridViewStyle();
        }


        public void ViewData(SelectedDataCollection data, bool bMergeByPartNumber = false)
        {
            Option = new OverviewSearchOption(); 
        
            Option.DisplayByStation = !bMergeByPartNumber;

            DataTable dtResult = DataManager.GetDataView(data, Option);

            if(bProductMergeOption)
            {
                nMergeDataCnt = DataManager.dtSubRaw.Rows.Count;

                strMergeReqIDs = new string[nMergeDataCnt];

                for (int i = 0; i < nMergeDataCnt; i++)
                    strMergeReqIDs[i] = DataManager.dtSubRaw.Rows[i]["TestListCntID"].ToString();
            }

            GridViewGetActiveFilterText = gridViewMain.ActiveFilterString;

            gridControlMain.DataSource = null;
            gridControlMain.RefreshDataSource();
            gridViewMain.RefreshData();

            gridControlMain.DataSource = dtResult;
            gridControlMain.RefreshDataSource();
            gridViewMain.RefreshData();
            gridControlMain.ForceInitialize();
            gridViewMain.PopulateColumns(dtResult);

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

            gridControlMain.Update();

            SetGridViewStyle();
        }

        public bool DoSelect(DataRow dtRow)
        {
            if (dtRow == null)
                return false;

            bool bDataCheckResult = true;

            try
            {
                string strDate = dtRow[DMDetailOverview.eColList.TestDate.ToString()].ToString();
                string strStartTime = dtRow[DMDetailOverview.eColList.FirstTestTime.ToString()].ToString();
                string strEndTime = dtRow[DMDetailOverview.eColList.FinalTestTime.ToString()].ToString();

                DateTime dtDate = DateTime.Parse(strDate);

                strStartTime = dtDate.ToShortDateString() + " " + strStartTime;
                strEndTime = dtDate.ToShortDateString() + " " + strEndTime;

                DateTime dtStart = DateTime.Parse(strStartTime);
                DateTime dtEnd = DateTime.Parse(strEndTime);

                //dtEnd = dtEnd.AddHours(-dtStart.Hour);
                //dtEnd = dtEnd.AddHours(23.9999);

                //string strStnName, string strHostID, string strSectionID, string strTestType,
                //string strProdNo, string strTestCode, string strParentNo, string strProdCode, 
                //string strFileVer, string strStepVer)

                string strTestListCntID = string.Empty;

                if (bProductMergeOption == false)
                    strTestListCntID = dtRow[DMDetailOverview.eColList.TestListCntID.ToString()].ToString();

                SelectedDataCollection selData = new SelectedDataCollection(
                    SearchStart,
                    SearchEnd,
                    dtStart,
                    dtEnd,
                    Option.DisplayByStation ? dtRow[DMDetailOverview.eColList.StationName.ToString()].ToString() : string.Empty,
                    Option.DisplayByStation ? dtRow[DMDetailOverview.eColList.Host.ToString()].ToString() : string.Empty,
                    Option.DisplayByStation ? dtRow[DMDetailOverview.eColList.Section.ToString()].ToString() : string.Empty,
                    dtRow[DMDetailOverview.eColList.TestType.ToString()].ToString(),
                    dtRow[DMDetailOverview.eColList.ProductNo.ToString()].ToString(),
                    dtRow[DMDetailOverview.eColList.TestCode.ToString()].ToString(),
                    dtRow[DMDetailOverview.eColList.ParentNo.ToString()].ToString(),
                    dtRow[DMDetailOverview.eColList.FileCode.ToString()].ToString(),
                    dtRow[DMOverview.eColList.TestListFileNo.ToString()].ToString(),
                    dtRow[DMOverview.eColList.TestListVariantNo.ToString()].ToString(),
                    dtRow[DMDetailOverview.eColList.FileVersion.ToString()].ToString(),
                    dtRow[DMDetailOverview.eColList.StepVersion.ToString()].ToString(),
                    strTestListCntID);

                if (bProductMergeOption)
                {
                    selData.SetCountRequestID(nMergeDataCnt);

                    selData.CopyReqIDs(strMergeReqIDs);
                }

                refChildInterface.AnnounceContentsType(ContentsType);

                OnSelect(selData);
            }
            catch (Exception e)
            {
                MessageOutput.ConsoleWrite($"Detail Overview DoSelect Error: {e.Message}", ConsoleColor.Red, LogMessage.LogMessageLevel.FATAL);

                bDataCheckResult = false;
            }
            finally
            {
                ;//
            }

            return bDataCheckResult;
        }

        private DataRow GetRowInfo(object Viewer, int nRowHndl)
        {
            DataRow dtRow = null;

            try
            {
                GridView view = Viewer as GridView;
                var dvRow = view.GetRow(nRowHndl);
                dtRow = (dvRow as DataRowView).Row;
            }
            catch
            {
                dtRow = null;
            }

            return dtRow;
        }

        private void gridViewMain_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {
            int nRowHndl = e.RowHandle;

            if (nRowHndl < 0)
                return;

            DoSelect(GetRowInfo(sender, nRowHndl));
        }

        private void gridViewMain_RowStyle(object sender, RowStyleEventArgs e)
        {
            GridView view = sender as GridView;
            if (view.FocusedRowHandle == e.RowHandle)
            {
                GridViewInfo viewInfo = gridViewMain.GetViewInfo() as GridViewInfo;
                e.Appearance.Assign(viewInfo.PaintAppearance.FocusedRow);
                e.HighPriority = true;
            }
        }

        private void gridViewMain_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                GridHitInfo hInfo = gridViewMain.CalcHitInfo(gridControlMain.PointToClient(Cursor.Position));

                if (hInfo.RowInfo != null)
                {
                    int nGetRowHandle = hInfo.RowInfo.RowHandle;

                    DoSelect(GetRowInfo(gridViewMain, nGetRowHandle));
                }
            }
        }

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

            if (nClickCnt < 2)
                return;

            int nRowHndl = e.RowHandle;

            if (nRowHndl < 0)
                return;

            if(DoSelect(GetRowInfo(sender, nRowHndl)))
                refChildInterface.SetHistoryView();
        }
    }
}
