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 SystemX.Net.Platform.Common.Util;

using static SystemX.Net.Platform.Common.Util.LogMessage;
using static SystemX.Product.CP.TRA.Commons;

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

        DMOverview DataManager { get; set; }

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

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

        public bool bAllowCheckedState;

        private IChildController refChildInterface;

        private string GridViewGetActiveFilterText;

        public UcTRAOverview(IChildController getChildControl, eContents SetContentsType = eContents.Overview, bool bAllowMerge = false, bool bAutoFilterRow = false)
        {
            ContentsType = SetContentsType;

            refChildInterface = getChildControl;

            this.ContextMenuStrip = base.contextMenuStripTest;

            this.ContextMenuStrip.ItemClicked += contextMenuStrip_ItemClicked;

            SetMenuEnabled(ContentsType);

            InitializeComponent();

            gridViewMain.OptionsView.AllowCellMerge = true;
            bAllowCheckedState = bAllowMerge;

            gridViewMain.OptionsView.ShowAutoFilterRow = bAutoFilterRow;

            /*MergedRowsHelper helper = new MergedRowsHelper();
            helper.Register(gridViewMain);

            gridViewMain.FocusRectStyle = DevExpress.XtraGrid.Views.Grid.DrawFocusRectStyle.RowFocus;
            gridViewMain.OptionsBehavior.Editable = false;
            gridViewMain.OptionsSelection.EnableAppearanceFocusedCell = false;
            DevExpress.Skins.Skin currentSkin = DevExpress.Skins.CommonSkins.GetSkin(gridControlMain.LookAndFeel);
            Color color = currentSkin.Colors["Highlight"];
            gridViewMain.Appearance.FocusedRow.BackColor = color;*/
        }

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

        public void SetSqlCommandCancel()
        {
            DataManager.SetSqlCommandCancel();
        }

        public bool GetSqlCommandCancelState()
        {
            return DataManager.GetSqlCommandCancelState();
        }

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

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

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

        public void SetSQLConnection(eSelectDataView SelectView, eOverviewModelNameInfo SelectInfo, IDataBaseController getDBController)
        {
            DataManager = new DMOverview(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;
                    gc.DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime;

                    if(ContentsType == eContents.HostUseHistory)
                        gc.DisplayFormat.FormatString = "yyyy-MM-dd HH:mm:ss.fff";
                }
                else if (gc.FieldName.CompareTo("Host") == 0)
                    gc.OptionsColumn.AllowMerge = DevExpress.Utils.DefaultBoolean.True;
                else
                {
                    /*                    
                    if (bAllowCheckedState)
                    {
                        if (gc.FieldName.CompareTo("ProductNo") == 0)
                            gc.OptionsColumn.AllowMerge = DevExpress.Utils.DefaultBoolean.True;
                        else if (gc.FieldName.CompareTo("TestCode") == 0)
                            gc.OptionsColumn.AllowMerge = DevExpress.Utils.DefaultBoolean.True;
                        else
                            gc.OptionsColumn.AllowMerge = DevExpress.Utils.DefaultBoolean.False;
                    }
                    else
                        gc.OptionsColumn.AllowMerge = DevExpress.Utils.DefaultBoolean.False;
                    */

                    gc.OptionsColumn.AllowMerge = DevExpress.Utils.DefaultBoolean.False;
                }
            }

            /*
            int[] nGroupIdx = null;

            nGroupIdx = new int[2] { 5, 6 };

            for (int i = 0; i < nGroupIdx.Count(); i++)
            {
                if (bAllowCheckedState)
                    gridViewMain.Columns[nGroupIdx[0]].Group();
                else
                    gridViewMain.Columns[nGroupIdx[0]].UnGroup();
            }

            if (bAllowCheckedState)
                gridViewMain.CollapseAllGroups();
            */

            gridViewMain.EndUpdate();

            gridViewMain.ActiveFilterString = GridViewGetActiveFilterText;
        }

        public async Task<OverviewSearchOption> ViewData(DateTime dtStart, DateTime dtEnd, OverviewSearchOption OvOp, bool bMergeByPartNumber = false, bool bUseMainConn = false, string strTestQuery = "")
        {
            FrmOptionOverview dlgOption = new FrmOptionOverview();

            Option = dlgOption.GetSelectedResult();

            Option.DisplayByStation = OvOp.DisplayByStation;
            Option.ViewOptionPanel = OvOp.ViewOptionPanel;
            Option.FullScanData = OvOp.FullScanData;
            Option.ProductID = OvOp.ProductID;

            if (OvOp.ViewOptionPanel)
            {
                dlgOption.ShowDialog();

                Option = dlgOption.GetSelectedResult();
            }
            else
            {
                Option.DisplayByStation = !bMergeByPartNumber;
            }

            if (bMergeByPartNumber)
                SetMenuFindErrorEnabled(!bMergeByPartNumber);

            DataTable dtResult = await DataManager.GetDataView(dtStart, dtEnd, Option, bUseMainConn, strTestQuery);

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

            return Option;
        }

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

            bool bDataCheckResult = true;

            try
            {
                string strDate = dtRow[DMOverview.eColList.TestDate.ToString()].ToString();
                string strStartTime = dtRow[DMOverview.eColList.FirstTestTime.ToString()].ToString();
                string strEndTime = dtRow[DMOverview.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);

                //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 (Option.DisplayByStation)
                    strTestListCntID = dtRow[DMOverview.eColList.TestListCntID.ToString()].ToString();

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

                if (Option.ProductID.Length > 0)
                    selData.SetProdcutID(Option.ProductID);

                refChildInterface.AnnounceContentsType(ContentsType);

                OnSelect(selData);
            }
            catch(Exception e)
            {
                MessageOutput.ConsoleWrite($"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_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.CallDetailOverView();
        }

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