using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;
using System.Net;
using System.Data.SqlClient;

using DataBaseConnection.Control;

using DevExpress.Utils.CodedUISupport;
using DevExpress.XtraEditors;
using DevExpress.XtraBars.Docking2010.Views;
using DevExpress.XtraBars;
using DevExpress.XtraBars.Navigation;

using SystemX.Product.ALIS.UI.Subs;
using SystemX.Net.Platform.Common.Util;
using SystemX.Product.TRA.UIControl;
using SystemX.Net.Platform.Common.ExtensionMethods;

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

using SystemX.Product.ALIS.Interface;
using DevExpress.LookAndFeel;
using SystemX.Product.TRA.Properties;
using SystemX.Product.TRA.DataManager;
using System.Data.Common;
using DevExpress.XtraEditors.Repository;

namespace SystemX.Product.CP.TRA
{
    public partial class MainForm : DevExpress.XtraBars.Ribbon.RibbonForm, IChildController, IDataBaseController
    {
        public class UserInfo
        {
            public string UserID;
            public string Name;
            public string Dept;
            public string Email;
            public string Comment;
            public string Password;

            public UserInfo()
            {
                UserID = "";
                Name = "";
                Dept = "";
                Email = "";
                Comment = "";
                Password = "";
            }
            public void Clear()
            {
                UserID = "";
                Name = "";
                Dept = "";
                Email = "";
                Comment = "";
                Password = "";
            }
        }

        private class OnOperationDBConnMarker : IDisposable
        {
            private MainForm _mainForm;

            private bool bConnBehavior = true;

            public OnOperationDBConnMarker(MainForm mf, bool bSetConnBehavior = true)
            {
                _mainForm = mf;

                bConnBehavior = bSetConnBehavior;

                _mainForm.Do(() =>
                {
                    if (bConnBehavior)
                    {
                        _mainForm.barButtonItemConnect.Enabled = false;
                        _mainForm.barButtonItemLogout.Enabled = false;
                    }
                    else
                    {
                        _mainForm.barButtonItemConnect.Enabled = false;
                        _mainForm.barButtonItemLogout.Enabled = false;

                        _mainForm.barStaticItemConn.Caption = "ConnectDB";
                        _mainForm.barStaticItemConn.Visibility = BarItemVisibility.Never;
                        _mainForm.barStaticItemConn.ShowImageInToolbar = false;
                    }
                });
            }

            public void Dispose()
            {
                _mainForm.Do(() =>
                {
                    if (bConnBehavior)
                    {
                    }
                    else
                    {
                        _mainForm.barButtonItemConnect.Enabled = true;
                        _mainForm.barButtonItemLogout.Enabled = false;
                    }
                });
            }
        }

        public IDisposable GetOnOperationDBConnMarker(bool bSetConnBehavior = true) { return new OnOperationDBConnMarker(this, bSetConnBehavior); }

        BackgroundWorker worker = new BackgroundWorker();
        WaitProgressForm loadForm = null;
        Stopwatch stLoadFormWait = new Stopwatch();

        //Test List Server 
        private SqlConnection DBConnMain { get; set; }

        //Data Server 1
        private SqlConnection DBConnShortTerm1 { get; set; }
        private SqlConnection DBConnLongTerm1 { get; set; }

        //Data Server 2
        private SqlConnection DBConnShortTerm2 { get; set; }
        private SqlConnection DBConnLongTerm2 { get; set; }

        //Test List Server
        public SqlCommand MainSQLCmd { get; set; }
        //Data Server 1
        public SqlCommand ShortTermSQLCmd1 { get; set; }
        public SqlCommand LongTermSQLCmd1 { get; set; }
        //Data Server 2
        public SqlCommand ShortTermSQLCmd2 { get; set; }
        public SqlCommand LongTermSQLCmd2 { get; set; }

        public UserInfo CurrentUser;
        public LoginAccessLevel ACCESS_LEVEL { internal set; get; }

        private string strTitleLabel;

        private string strConnTLLabel;

        private string strConnDT1Label;

        private string strConnDT2Label;

        private Stopwatch stCheckLoginTime;

        //Test List Server
        public string strConnIPAddressTL;

        private int nConnPortTL;

        public string GetTestListServerConnectIP()
        {
            return strConnIPAddressTL;
        }

        public int GetTestListServerConnectPort()
        {
            return nConnPortTL;
        }

        //Data Server 1
        public string strConnIPAddressDT1;

        private int nConnPortDT1;

        public string GetDataServer1Connect()
        {
            return strConnIPAddressDT1;
        }

        public int GetDataServer1ConnectPort()
        {
            return nConnPortDT1;
        }

        //Data Server 2
        public bool bUseDataServer2;

        public string strConnIPAddressDT2;

        private int nConnPortDT2;
        //
        public int nSelectOverC1;

        public int nSelectOverC2;

        public eOverviewModelNameInfo SetOverviewInfoC1;
        public eOverviewModelNameInfo SetOverviewInfoC2;
        //
        public string GetDataServer2Connect()
        {
            return strConnIPAddressDT2;
        }

        public int GetDataServer2ConnectPort()
        {
            return nConnPortDT2;
        }

        private bool bDatabaseConnState;

        private bool bOverviewRunState;
        private bool bOverviewCallState;

        private int nProgressProcValue;

        private UcTRAOverview refRunOverview;

        bool ViewDocMgrLock = false;

        eSelectDataView eCurrentView = eSelectDataView.DataDocumentViewC1;

        Dictionary<string, UcTRABaseView> DicViewFirstMgr = new Dictionary<string, UcTRABaseView>();
        Dictionary<string, UcTRABaseView> DicViewSecondMgr = new Dictionary<string, UcTRABaseView>();

        SelectedDataCollection SelectedData { get; set; }
        SelectedDataCollection SelectedDetailData { get; set; }

        int nFirstViewCount { get; set; } = 0;
        int nSecondViewCount { get; set; } = 0;

        bool bMergeByPartNumberLocker = false;

        private string strUserInputConnectInfo1;
        private string strUserInputConnectInfo2;
        private string strUserInputConnectInfo3;

        private bool GetSearchOption { get { return barToggleSwitchItemShowOption.Checked; } }

        private eContents SelectedContents;

        public MainForm()
        {
            InitializeComponent();

            ConnectInfoINICtrl CCtrl = new ConnectInfoINICtrl();
            UserLookAndFeel.Default.SkinName = CCtrl.GetUserTheme(); //SystemX.Product.TRA.Properties.Settings.Default["ApplicationThemeName"].ToString();

            ConsoleUtil.ConsoleHide();

            CurrentUser = new UserInfo();
            ACCESS_LEVEL = LoginAccessLevel.None;
            strTitleLabel = this.Text;

            stCheckLoginTime = new Stopwatch();
            stCheckLoginTime.Start();

            worker.DoWork += (sender, args) => PerformDatabaseConnect();
            worker.RunWorkerCompleted += (sender, args) => ReadingCompleted(bDatabaseConnState);

            stLoadFormWait.Start();

            this.KeyPreview = true;

            accordionControl.AllowItemSelection = true;
            //accordionControl.SelectedElementChanged += AccordionSelectedElementChangedEvt;
            //accordionControl.MouseUp += AccordionElementClickEvt;

            SelectedContents = eContents.None;

            tabbedView.QueryControl += View_QueryControl;

            barEditItemProductID.EditValue = string.Empty;

            bOverviewRunState = false;
            bOverviewCallState = false;
        }

        private void CheckSqlOption(SqlConnection SqlConn)
        {
            //옵션 확인 및 ON
            //DECLARE @ARITHABORT VARCHAR(3) = 'OFF'; IF ( (64 & @@OPTIONS) = 64 ) SET @ARITHABORT = 'ON'; SELECT @ARITHABORT AS ARITHABORT;
            string strGetQuery1 = "DECLARE @ARITHABORT VARCHAR(3) = 'OFF'; IF ( (64 & @@OPTIONS) = 64 ) SET @ARITHABORT = 'ON'; SELECT @ARITHABORT AS ARITHABORT;";
            string strGetQuery2 = "DECLARE @ARITHIGNORE VARCHAR(3) = 'OFF'; IF ( (128 & @@OPTIONS) = 128 ) SET @ARITHIGNORE = 'ON'; SELECT @ARITHIGNORE AS ARITHIGNORE;";

            /*
            SET ARITHIGNORE ON

             - 쿼리 실행 중 오버플로 또는 0으로 나누기 오류에서 오류 메시지를 반환할지 여부를 제어

　                 오류 메시지가 반환될지 여부만 제어하며 이 설정에 상관 없이 오버플로 또는 0으로 나누기 오류를  
　                 발생시킨 계산에 NULL을 반환한다. 없는 값 처리를 해야하므고 오류를 발생시킨 것에서  null 반환을 받아야 한다!

            SET ARITHABORT ON이면 오버플로 또는 0으로 나누기 오류 발생 시 쿼리나 일괄 처리가 종료 
　                 트랜잭션에서 해당 오류가 발생하면 트랜잭션이 롤백시킨다.  그러나 이 설정이 INSERT, UPDATE, DELETE 문 실행 중에  
　                 발생한 오류에는 영향을 주지 않는다.  
            */

            DataTable dtResult1 = new DataTable();
            DataTable dtResult2 = new DataTable();

            using (SqlCommand SqlCommand = new SqlCommand(strGetQuery1, SqlConn))
            {
                SqlCommand.CommandTimeout = 300;

                DbDataReader dtReader = SqlCommand.ExecuteReader();

                dtResult1.Load(dtReader);

                dtReader.Close();
            }
            //
            using (SqlCommand SqlCommand = new SqlCommand(strGetQuery2, SqlConn))
            {
                SqlCommand.CommandTimeout = 300;

                DbDataReader dtReader = SqlCommand.ExecuteReader();

                dtResult2.Load(dtReader);

                dtReader.Close();
            }
            //
            if (Commons.isHasRow(dtResult1))
            {
                bool bOptionState = dtResult1.Rows[0]["ARITHABORT"].ToString() == "ON" ? true : false;

                if (bOptionState == false)
                    SetSqlOption(SqlConn, "SET ARITHABORT ON");
            }
            if (Commons.isHasRow(dtResult2))
            {
                bool bOptionState = dtResult2.Rows[0]["ARITHIGNORE"].ToString() == "ON" ? true : false;

                if (bOptionState == false)
                    SetSqlOption(SqlConn, "SET ARITHIGNORE ON");
            }
        }

        private void SetSqlOption(SqlConnection SqlConn, string strQuery)
        {
            using (SqlCommand SqlCommand = new SqlCommand(strQuery, SqlConn))
            {
                SqlCommand.CommandTimeout = 300;

                int nRows = SqlCommand.ExecuteNonQuery();
            }
        }

        private async void PerformDatabaseConnect()
        {
            DBConnMain = null;
            DBConnShortTerm1 = null;
            DBConnLongTerm1 = null;
            DBConnShortTerm2 = null;
            DBConnLongTerm2 = null;

            try
            {
                try
                {
                    //TODO : Conn Database
                    if (strConnIPAddressTL == string.Empty)
                    {
                        DatabaseConnControl.ConnectTestListDB();

                        DBConnMain = DatabaseConnControl.GetMainConn();
                    }
                    else
                    {
                        DatabaseConnControl.ConnectTestListDB(strConnIPAddressTL, nConnPortTL);

                        DBConnMain = DatabaseConnControl.GetMainConn();
                    }

                    //Data Server 1
                    if (strConnIPAddressDT1 == string.Empty)
                    {
                        DatabaseConnControl.ConnectDataDB1();

                        DBConnShortTerm1 = DatabaseConnControl.GetShortTermConn1();
                        DBConnLongTerm1 = DatabaseConnControl.GetLongTermConn1();
                    }
                    else
                    {
                        DatabaseConnControl.ConnectDataDB1(strConnIPAddressDT1, nConnPortDT1);

                        DBConnShortTerm1 = DatabaseConnControl.GetShortTermConn1();
                        DBConnLongTerm1 = DatabaseConnControl.GetLongTermConn1();
                    }

                    //Data Server 2
                    if (bUseDataServer2)
                    {
                        if (strConnIPAddressDT2 == string.Empty)
                        {
                            DatabaseConnControl.ConnectDataDB2();

                            DBConnShortTerm2 = DatabaseConnControl.GetShortTermConn2();
                            DBConnLongTerm2 = DatabaseConnControl.GetLongTermConn2();
                        }
                        else
                        {
                            DatabaseConnControl.ConnectDataDB2(strConnIPAddressDT2, nConnPortDT2);

                            DBConnShortTerm2 = DatabaseConnControl.GetShortTermConn2();
                            DBConnLongTerm2 = DatabaseConnControl.GetLongTermConn2();
                        }
                    }
                    //
                    MainSQLCmd = new SqlCommand();
                    MainSQLCmd.Connection = DatabaseConnControl.GetMainConn();
                    //
                    ShortTermSQLCmd1 = new SqlCommand();
                    ShortTermSQLCmd1.Connection = DatabaseConnControl.GetShortTermConn1();

                    LongTermSQLCmd1 = new SqlCommand();
                    LongTermSQLCmd1.Connection = DatabaseConnControl.GetLongTermConn1();
                    //
                    CheckSqlOption(DatabaseConnControl.GetMainConn());
                    CheckSqlOption(DatabaseConnControl.GetShortTermConn1());
                    CheckSqlOption(DatabaseConnControl.GetLongTermConn1());
                    //
                    if (bUseDataServer2)
                    {
                        ShortTermSQLCmd2 = new SqlCommand();
                        ShortTermSQLCmd2.Connection = DatabaseConnControl.GetShortTermConn2();

                        LongTermSQLCmd2 = new SqlCommand();
                        LongTermSQLCmd2.Connection = DatabaseConnControl.GetLongTermConn2();

                        CheckSqlOption(DatabaseConnControl.GetShortTermConn2());
                        CheckSqlOption(DatabaseConnControl.GetLongTermConn2());
                    }

                    bDatabaseConnState = true;
                }
                catch (Exception ex)
                {
                    bDatabaseConnState = false;

                    MessageOutput.ConsoleWrite($"DB Connection Error: {ex.Message}", ConsoleColor.Red, LogMessage.LogMessageLevel.FATAL);
                }
            }
            finally
            {
                if (DBConnMain == null || DBConnShortTerm1 == null || DBConnLongTerm1 == null)
                {
                    bDatabaseConnState = false;

                    MessageBox.Show("DB connection failed. Check DB status. Automatically close the program.", "[SystemX.Product.ALIS.UI]", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                //
                if(bUseDataServer2)
                {
                    if (DBConnShortTerm2 == null || DBConnLongTerm2 == null)
                    {
                        bDatabaseConnState = false;

                        MessageBox.Show("DB connection failed. Check DB status. Automatically close the program.", "[SystemX.Product.ALIS.UI]", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }

            await Task.Delay(1);
        }

        private async void ReadingCompleted(object args)
        {
            loadForm.BringToFront();
            loadForm.Focus();

            if (stLoadFormWait.ElapsedMilliseconds <= 1000)
            {
                int iremainTime = 1000 - (int)stLoadFormWait.ElapsedMilliseconds;
                await Task.Delay(iremainTime);
            }

            loadForm.Close();
            loadForm = null;

            if (DBConnMain == null)
            {
                bDatabaseConnState = false;

                MessageBox.Show("DB connection failed. Check the DB status or check the connection address.", "[SystemX.Product.ALIS.UI]", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            if (bDatabaseConnState == false)
            {
                ;// this.Close();

                SetDBConn();
            }
            else
            {
                ConnectInfoINICtrl CCtrl = new ConnectInfoINICtrl();
                CCtrl.SetLastestConnectInfo(strUserInputConnectInfo1, strUserInputConnectInfo2, strUserInputConnectInfo3, 
                    bUseDataServer2, nSelectOverC1, nSelectOverC2);

                barStaticItemConn.Visibility = BarItemVisibility.Always;

                barStaticItemConn.ShowImageInToolbar = true;

                string strAddress = (strConnIPAddressTL == string.Empty ? "LocalHost" : strConnIPAddressTL);

                strAddress += " , " + nConnPortTL.ToString();

                strConnTLLabel = "TestList Database [" + strAddress + "] [" + DatabaseConnControl.MainCatalogName + "] [" + DatabaseConnControl.CatalogConnUID + "]";

                barStaticItemConn.Caption = strConnTLLabel;

                strAddress = (strConnIPAddressDT1 == string.Empty ? "LocalHost" : strConnIPAddressDT1);

                strAddress += " , " + nConnPortDT1.ToString();

                strConnDT1Label = "Data Database [1][" + strAddress + "] [" + DatabaseConnControl.ShortTermCatalogName + "] [" + DatabaseConnControl.LongTermCatalogName + "]";

                barStaticItemConn.Caption += (" " + strConnDT1Label);

                if (bUseDataServer2)
                {
                    strAddress = (strConnIPAddressDT2 == string.Empty ? "LocalHost" : strConnIPAddressDT2);

                    strAddress += " , " + nConnPortDT2.ToString();

                    strConnDT2Label = "Data Database [2][" + strAddress + "] [" + DatabaseConnControl.ShortTermCatalogName + "] [" + DatabaseConnControl.LongTermCatalogName + "]";

                    //barStaticItemConn.Caption += " Data Database [2][" + strAddress + "] [" + DatabaseConnControl.ShortTermCatalogName + "] [" + DatabaseConnControl.LongTermCatalogName + "]";

                    ribbonPageGroupNavigation.Visible = true;
                    barButtonItemConnSelect.Caption = "Current : Connect [1]";
                }
                else
                {
                    ribbonPageGroupNavigation.Visible = false;
                }

                barButtonItemConnect.Enabled = false;
                barButtonItemLogout.Enabled = true;
            }
        }

        private async Task<bool> OpenOverallDataView(UcTRAOverview view, OverviewSearchOption OvOp, bool bMergeByPartNumber = false, string strTestQuery = "")
        {
            DateTime dtStart = DateTime.Parse(barEditItemDateStart.EditValue.ToString());
            DateTime dtEnd = DateTime.Parse(barEditItemDateEnd.EditValue.ToString());

            dtEnd = dtEnd.AddHours(23.99999);

            bMergeByPartNumberLocker = true;

            OverviewSearchOption oso = await view.ViewData(dtStart, dtEnd, OvOp, bMergeByPartNumber, false, strTestQuery);

            if (oso.ViewOptionPanel)
            {
                if (barToggleSwitchItemOverviewMerge.Checked == !oso.DisplayByStation)
                    bMergeByPartNumberLocker = false;
                else
                    barToggleSwitchItemOverviewMerge.Checked = !oso.DisplayByStation;
            }
            else
                bMergeByPartNumberLocker = false;

            if (eCurrentView == eSelectDataView.DataDocumentViewC1)
            {
                if (DicViewFirstMgr.ContainsKey(eContents.Overview.ToString() + eDataView.C1.ToString()))
                    view.OnSelect -= SetDataView;
            }
            else if (eCurrentView == eSelectDataView.DataDocumentViewC2)
            {
                if (DicViewSecondMgr.ContainsKey(eContents.Overview.ToString() + eDataView.C2.ToString()))
                    view.OnSelect -= SetDataView;
            }

            view.OnSelect += SetDataView;

            barEditItemQuryTest.EditValue = view.GetUseQuery();

            return true;
        }

        private void OpenOverallDetailDataView(UcTRADetailOverview view, SelectedDataCollection data, bool bMergeByPartNumber = false)
        {
            DateTime dtStart = DateTime.Parse(barEditItemDateStart.EditValue.ToString());
            DateTime dtEnd = DateTime.Parse(barEditItemDateEnd.EditValue.ToString());

            dtEnd = dtEnd.AddHours(23.99999);

            data.SearchRangeStart = dtStart;
            data.SearchRangeEnd = dtEnd;

            view.ViewData(data, bMergeByPartNumber);

            if (eCurrentView == eSelectDataView.DataDocumentViewC1)
            {
                if (DicViewFirstMgr.ContainsKey(eContents.DetailOverview.ToString() + eDataView.C1.ToString()))
                    view.OnSelect -= SetDetailDataView;
            }
            else if (eCurrentView == eSelectDataView.DataDocumentViewC2)
            {
                if (DicViewSecondMgr.ContainsKey(eContents.DetailOverview.ToString() + eDataView.C2.ToString()))
                    view.OnSelect -= SetDetailDataView;
            }

            view.OnSelect += SetDetailDataView;

            barEditItemQuryTest.EditValue = view.GetUseQuery();
        }

        private void SelectOverviewTab()
        {
            UcTRAOverview view = null;

            if (CheckDatabaseConnState() == false)
                return;

            if (eCurrentView == eSelectDataView.DataDocumentViewC1)
            {
                if (DicViewFirstMgr.ContainsKey(eContents.Overview.ToString() + eDataView.C1.ToString()))
                {
                    view = DicViewFirstMgr[eContents.Overview.ToString() + eDataView.C1.ToString()] as UcTRAOverview;

                    SelectAccordianElement(view.ViewID);
                }
            }
            else if (eCurrentView == eSelectDataView.DataDocumentViewC2)
            {
                if (DicViewSecondMgr.ContainsKey(eContents.Overview.ToString() + eDataView.C2.ToString()))
                {
                    view = DicViewSecondMgr[eContents.Overview.ToString() + eDataView.C2.ToString()] as UcTRAOverview;

                    SelectAccordianElement(view.ViewID);
                }
            }
        }

        private void SelectDetailOverviewTab()
        {
            UcTRADetailOverview view = null;

            if (CheckDatabaseConnState() == false)
                return;

            if (eCurrentView == eSelectDataView.DataDocumentViewC1)
            {
                if (DicViewFirstMgr.ContainsKey(eContents.DetailOverview.ToString() + eDataView.C1.ToString()))
                {
                    view = DicViewFirstMgr[eContents.DetailOverview.ToString() + eDataView.C1.ToString()] as UcTRADetailOverview;

                    SelectAccordianElement(view.ViewID);
                }
            }
            else if (eCurrentView == eSelectDataView.DataDocumentViewC2)
            {
                if (DicViewSecondMgr.ContainsKey(eContents.DetailOverview.ToString() + eDataView.C2.ToString()))
                {
                    view = DicViewSecondMgr[eContents.DetailOverview.ToString() + eDataView.C2.ToString()] as UcTRADetailOverview;

                    SelectAccordianElement(view.ViewID);
                }
            }
        }

        private UcTRAOverview CheckOverview()
        {
            UcTRAOverview view = null;

            if (CheckDatabaseConnState() == false)
                return null;

            bool bViewExist = false;

            if (eCurrentView == eSelectDataView.DataDocumentViewC1)
            {
                if (DicViewFirstMgr.ContainsKey(eContents.Overview.ToString() + eDataView.C1.ToString()))
                {
                    view = DicViewFirstMgr[eContents.Overview.ToString() + eDataView.C1.ToString()] as UcTRAOverview;

                    bViewExist = true;
                }
            }
            else if (eCurrentView == eSelectDataView.DataDocumentViewC2)
            {
                if (DicViewSecondMgr.ContainsKey(eContents.Overview.ToString() + eDataView.C2.ToString()))
                {
                    view = DicViewSecondMgr[eContents.Overview.ToString() + eDataView.C2.ToString()] as UcTRAOverview;

                    bViewExist = true;
                }
            }

            if (bViewExist)
            {
                view.SearchStart = DateTime.Parse(barEditItemDateStart.EditValue.ToString());
                view.SearchEnd = DateTime.Parse(barEditItemDateEnd.EditValue.ToString());

                view.SearchEnd = view.SearchEnd.AddHours(23.99);
            }
            else
            {
                view = new UcTRAOverview(this, eContents.Overview, barToggleSwitchItemOverviewMerge.Checked, barToggleSwitchItemOverviewFilter.Checked);

                view.SearchStart = DateTime.Parse(barEditItemDateStart.EditValue.ToString());
                view.SearchEnd = DateTime.Parse(barEditItemDateEnd.EditValue.ToString());

                view.SearchEnd = view.SearchEnd.AddHours(23.99999);

                string strSetID = string.Empty;
                if (eCurrentView == eSelectDataView.DataDocumentViewC1)
                {
                    view.SetSQLConnection(eCurrentView, SetOverviewInfoC1, this);

                    strSetID = eContents.Overview.ToString() + eDataView.C1.ToString();
                    view.ViewID = strSetID;
                    DicViewFirstMgr.Add(strSetID, view);
                }
                else if (eCurrentView == eSelectDataView.DataDocumentViewC2)
                {
                    view.SetSQLConnection(eCurrentView, SetOverviewInfoC2, this);

                    strSetID = eContents.Overview.ToString() + eDataView.C2.ToString();
                    view.ViewID = strSetID;
                    DicViewSecondMgr.Add(strSetID, view);
                }

                tabbedView.AddDocument(view, view.ViewID);
                //tabbedView.AddDocument(view, eContents.Overview.ToString());

                CreateAccordianElement(view);
            }

            SelectAccordianElement(view.ViewID);

            return view;
        }

        private async Task<UcTRAOverview> SetOerviewFindData(UcTRAOverview view, OverviewSearchOption OvOp, bool bMergeByPartNumber = false, string strTestQuery = "")
        {
            if (CheckDatabaseConnState() == false)
                return null;

            //bool bViewExist = false;

            barButtonItemView.Caption = "Search Data(F1)[Cancel]";

            /*
            if (eCurrentView == eSelectDataView.DataDocumentViewC1)
            {
                if (DicViewFirstMgr.ContainsKey(eContents.Overview.ToString() + eDataView.C1.ToString()))
                {
                    view = DicViewFirstMgr[eContents.Overview.ToString() + eDataView.C1.ToString()] as UcTRAOverview;

                    bViewExist = true;
                }
            }
            else if (eCurrentView == eSelectDataView.DataDocumentViewC2)
            {
                if (DicViewSecondMgr.ContainsKey(eContents.Overview.ToString() + eDataView.C2.ToString()))
                {
                    view = DicViewSecondMgr[eContents.Overview.ToString() + eDataView.C2.ToString()] as UcTRAOverview;

                    bViewExist = true;
                }
            }

            if (bViewExist)
            {
                view.SearchStart = DateTime.Parse(barEditItemDateStart.EditValue.ToString());
                view.SearchEnd = DateTime.Parse(barEditItemDateEnd.EditValue.ToString());

                view.SearchEnd = view.SearchEnd.AddHours(23.99);
            }
            else
            {
                view = new UcTRAOverview(this, eContents.Overview, barToggleSwitchItemOverviewMerge.Checked, barToggleSwitchItemOverviewFilter.Checked);

                view.SearchStart = DateTime.Parse(barEditItemDateStart.EditValue.ToString());
                view.SearchEnd = DateTime.Parse(barEditItemDateEnd.EditValue.ToString());

                view.SearchEnd = view.SearchEnd.AddHours(23.99999);

                string strSetID = string.Empty;
                if (eCurrentView == eSelectDataView.DataDocumentViewC1)
                {
                    view.SetSQLConnection(eCurrentView, SetOverviewInfoC1, this);

                    strSetID = eContents.Overview.ToString() + eDataView.C1.ToString();
                    view.ViewID = strSetID;
                    DicViewFirstMgr.Add(strSetID, view);
                }
                else if (eCurrentView == eSelectDataView.DataDocumentViewC2)
                {
                    view.SetSQLConnection(eCurrentView, SetOverviewInfoC2, this);

                    strSetID = eContents.Overview.ToString() + eDataView.C2.ToString();
                    view.ViewID = strSetID;
                    DicViewSecondMgr.Add(strSetID, view);
                }

                tabbedView.AddDocument(view, view.ViewID);
                //tabbedView.AddDocument(view, eContents.Overview.ToString());

                CreateAccordianElement(view);
            }

            SelectAccordianElement(view.ViewID);
            */

            await OpenOverallDataView(view, OvOp, bMergeByPartNumber, strTestQuery);

            if (barCheckItemFullScan.Checked)
                barCheckItemFullScan.Checked = false;

            barButtonItemView.Caption = "Search Data(F1)";

            return view;
        }

        private void SetDetailOerviewFindData(SelectedDataCollection data, bool bMergeByPartNumber = false)
        {
            UcTRADetailOverview view = null;

            if (CheckDatabaseConnState() == false)
                return;

            bool bViewExist = false;

            if (eCurrentView == eSelectDataView.DataDocumentViewC1)
            {
                if (DicViewFirstMgr.ContainsKey(eContents.DetailOverview.ToString() + eDataView.C1.ToString()))
                {
                    view = DicViewFirstMgr[eContents.DetailOverview.ToString() + eDataView.C1.ToString()] as UcTRADetailOverview;

                    bViewExist = true;
                }
            }
            else if (eCurrentView == eSelectDataView.DataDocumentViewC2)
            {
                if (DicViewSecondMgr.ContainsKey(eContents.DetailOverview.ToString() + eDataView.C2.ToString()))
                {
                    view = DicViewSecondMgr[eContents.DetailOverview.ToString() + eDataView.C2.ToString()] as UcTRADetailOverview;

                    bViewExist = true;
                }
            }

            if (bViewExist)
            {
                view.SearchStart = DateTime.Parse(barEditItemDateStart.EditValue.ToString());
                view.SearchEnd = DateTime.Parse(barEditItemDateEnd.EditValue.ToString());

                view.SearchEnd = view.SearchEnd.AddHours(23.99);
            }
            else
            {
                view = new UcTRADetailOverview(this, barToggleSwitchItemOverviewMerge.Checked, barToggleSwitchItemOverviewFilter.Checked);

                view.SearchStart = DateTime.Parse(barEditItemDateStart.EditValue.ToString());
                view.SearchEnd = DateTime.Parse(barEditItemDateEnd.EditValue.ToString());

                view.SearchEnd = view.SearchEnd.AddHours(23.99999);

                string strSetID = string.Empty;
                if (eCurrentView == eSelectDataView.DataDocumentViewC1)
                {
                    view.SetSQLConnection(eCurrentView, SetOverviewInfoC1, this);

                    strSetID = eContents.DetailOverview.ToString() + eDataView.C1.ToString();
                    view.ViewID = strSetID;
                    DicViewFirstMgr.Add(strSetID, view);
                }
                else if (eCurrentView == eSelectDataView.DataDocumentViewC2)
                {
                    view.SetSQLConnection(eCurrentView, SetOverviewInfoC2, this);

                    strSetID = eContents.DetailOverview.ToString() + eDataView.C2.ToString();
                    view.ViewID = strSetID;
                    DicViewSecondMgr.Add(strSetID, view);
                }

                tabbedView.AddDocument(view, view.ViewID);
                //tabbedView.AddDocument(view, eContents.DetailOverview.ToString());

                CreateAccordianElement(view);
            }

            SelectAccordianElement(view.ViewID);

            OpenOverallDetailDataView(view, data, bMergeByPartNumber);
        }

        private async Task<UcTRAOverview> SetOverviewMerge()
        {
            UcTRAOverview view = null;

            if (eCurrentView == eSelectDataView.DataDocumentViewC1)
            {
                if (DicViewFirstMgr.ContainsKey(eContents.Overview.ToString() + eDataView.C1.ToString()))
                    view = DicViewFirstMgr[eContents.Overview.ToString() + eDataView.C1.ToString()] as UcTRAOverview;
            }
            else if (eCurrentView == eSelectDataView.DataDocumentViewC2)
            {
                if (DicViewSecondMgr.ContainsKey(eContents.Overview.ToString() + eDataView.C2.ToString()))
                    view = DicViewSecondMgr[eContents.Overview.ToString() + eDataView.C2.ToString()] as UcTRAOverview;
            }

            if (view == null)
                return null;

            view.bAllowCheckedState = barToggleSwitchItemOverviewMerge.Checked;

            OverviewSearchOption OvOp = new OverviewSearchOption(false, false, string.Empty);

            view = CheckOverview();

            await SetOerviewFindData (view, OvOp, barToggleSwitchItemOverviewMerge.Checked);

            view.SetGridViewStyle();

            return view;
        }

        private void DisplaySelectInformation()
        {
            this.Do(() =>
            {
                if (SelectedContents == eContents.Overview)
                {
                    barEditItemDTBegin.EditValue = SelectedData.StartTime.ToShortDateString() + " " + SelectedData.StartTime.ToShortTimeString();
                    barEditItemDTEnd.EditValue = SelectedData.EndTime.ToShortDateString() + " " + SelectedData.EndTime.ToShortTimeString();
                    barEditItemStation.EditValue = $"{SelectedData.StationName} ({SelectedData.HostID}, {SelectedData.SectionID})";
                    barEditItemProductNo.EditValue = $"{SelectedData.ProductNo} ({SelectedData.TestCode})";
                    barEditItemParentInfo.EditValue = $"{SelectedData.ParentNo} ({SelectedData.FileVersion}, {SelectedData.ProductionCode})";
                }
                else if (SelectedContents == eContents.DetailOverview)
                {
                    barEditItemDTBegin.EditValue = SelectedDetailData.StartTime.ToShortDateString() + " " + SelectedDetailData.StartTime.ToShortTimeString();
                    barEditItemDTEnd.EditValue = SelectedDetailData.EndTime.ToShortDateString() + " " + SelectedDetailData.EndTime.ToShortTimeString();
                    barEditItemStation.EditValue = $"{SelectedDetailData.StationName} ({SelectedDetailData.HostID}, {SelectedDetailData.SectionID})";
                    barEditItemProductNo.EditValue = $"{SelectedDetailData.ProductNo} ({SelectedDetailData.TestCode})";
                    barEditItemParentInfo.EditValue = $"{SelectedDetailData.ParentNo} ({SelectedDetailData.FileVersion}, {SelectedDetailData.ProductionCode})";
                }
            });
        }

        private void SetDataView(SelectedDataCollection data)
        {
            SelectedData = data;

            DisplaySelectInformation();
        }

        private void SetDetailDataView(SelectedDataCollection data)
        {
            SelectedDetailData = data;

            DisplaySelectInformation();
        }

        /*
        private void AccordionSelectedElementChangedEvt(object sender, SelectedElementChangedEventArgs e)
        {
        }
        */

        private bool SetDBConn()
        {
            accordionControl.Elements.Clear();

            barEditItemDateStart.EditValue = DateTime.Now.ToShortDateString();
            barEditItemDateEnd.EditValue = DateTime.Now.ToShortDateString();

            barEditItemHostHistStart.EditValue = DateTime.Now.ToShortDateString();
            barEditItemHostHistEnd.EditValue = DateTime.Now.ToShortDateString();

            strConnIPAddressTL = string.Empty;

            nConnPortTL = DatabaseConnControl.CatalogConnPort;
            //
            strConnIPAddressDT1 = string.Empty;

            nConnPortDT1 = DatabaseConnControl.CatalogConnPort;
            //
            strConnIPAddressDT2 = string.Empty;

            nConnPortDT2 = DatabaseConnControl.CatalogConnPort;

            this.BringToFront();
            this.Focus();

            ConnectForm connFrm = new ConnectForm(null);
            DialogResult dr = connFrm.ShowDialog();

            if (dr == DialogResult.OK || dr == DialogResult.Ignore)
            {
                //Test List Server
                strUserInputConnectInfo1 = connFrm.strInputTextTL;

                strConnIPAddressTL = connFrm.strGetIPAddressTL;

                nConnPortTL = connFrm.nGetConnPortTL;
                //Data Server 1
                strUserInputConnectInfo2 = connFrm.strInputTextDT1;

                strConnIPAddressDT1 = connFrm.strGetIPAddressDT1;

                nConnPortDT1 = connFrm.nGetConnPortDT1;
                //Data Server 2
                bUseDataServer2 = connFrm.bSelectUseDataServer2;

                strUserInputConnectInfo3 = connFrm.strInputTextDT2;

                strConnIPAddressDT2 = connFrm.strGetIPAddressDT2;

                nConnPortDT2 = connFrm.nGetConnPortDT2;
                //
                nSelectOverC1 = connFrm.nOverviewModelC1;
                nSelectOverC2 = connFrm.nOverviewModelC2;

                switch(nSelectOverC1)
                {
                    case 0: SetOverviewInfoC1 = eOverviewModelNameInfo.L; break;
                    case 1: SetOverviewInfoC1 = eOverviewModelNameInfo.P1; break;
                    case 2: SetOverviewInfoC1 = eOverviewModelNameInfo.P2; break;
                }
                switch (nSelectOverC2)
                {
                    case 0: SetOverviewInfoC2 = eOverviewModelNameInfo.L; break;
                    case 1: SetOverviewInfoC2 = eOverviewModelNameInfo.P1; break;
                    case 2: SetOverviewInfoC2 = eOverviewModelNameInfo.P2; break;
                }
                //

                loadForm = new WaitProgressForm();
                loadForm.setDescription("Connecting ...");
                loadForm.Location = new Point(this.Width / 2, this.Height / 2);

                //loadForm.ShowOnTopMode = DevExpress.XtraWaitForm.ShowFormOnTopMode.AboveAll;

                stLoadFormWait.Restart();

                worker.RunWorkerAsync(null);

                loadForm.ShowDialog();

                return true;
            }
            else
            {
                this.Close();

                return false;
            }
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            SetDBConn();
        }
        
        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (DBConnMain != null) // && bDatabaseConnState)
            {
                if (MessageBox.Show("You want to program exit?", "[CP-Server X : TRA]", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
                    e.Cancel = true;
                else
                {
                    e.Cancel = false;

                    ConnectInfoINICtrl CCtrl = new ConnectInfoINICtrl();
                    CCtrl.SetUserTheme(UserLookAndFeel.Default.SkinName);

                    /*SystemX.Product.TRA.Properties.Settings.Default["ApplicationThemeName"] = UserLookAndFeel.Default.SkinName;
                    SystemX.Product.TRA.Properties.Settings.Default.Save();*/

                    DatabaseConnControl.DisconnectDB();
                }
            }
        }

        #region Accordian Type

        AccordionControlElement GetAccordianElement(string strViewID)
        {
            AccordionControlElement elemAccord = accordionControl.Elements.Where(x => x.Name == strViewID).FirstOrDefault();

            return elemAccord;
        }

        void SelectAccordianElement(string strViewID)
        {
            AccordionControlElement elemAccord = GetAccordianElement(strViewID);

            if (elemAccord == null)
                return;

            accordionControl.SelectedElement = null;
            accordionControl.SelectedElement = elemAccord;
        }

        void CreateAccordianElement(UcTRABaseView view)
        {
            AccordionControlElement accelem = new AccordionControlElement();

            accelem.Style = ElementStyle.Item;
            accelem.Name = view.ViewID;
            accelem.Text = view.ContentsType.ToString() + ":" + view.ViewID;

            accordionControl.Elements.Add(accelem);
        }

        #endregion

        void barButtonNavigation_ItemClick(object sender, ItemClickEventArgs e)
        {
            //int barItemIndex = barSubItemNavigation.ItemLinks.IndexOf(e.Link);

            //accordionControl.SelectedElement = mainAccordionGroup.Elements[barItemIndex];

            dockPanel.ShowSliding();
        }

        /*
        private void AccordionElementClickEvt(object sender, MouseEventArgs e)
        {
        }
        */

        void accordionControl_SelectedElementChanged(object sender, SelectedElementChangedEventArgs e)
        {
            if (e.Element == null)
                return;

            AccordionControlElement elemAccord = e.Element;

            eSelectDataView eSelectViewItem = eSelectDataView.DataDocumentViewC1;

            if (elemAccord.Name.IndexOf("C1") >= 0)
                eSelectViewItem = eSelectDataView.DataDocumentViewC1;
            else if (elemAccord.Name.IndexOf("C2") >= 0)
                eSelectViewItem = eSelectDataView.DataDocumentViewC2;

            ChangeDatabaseView(eSelectViewItem);

            UcTRABaseView view = null;
            if (eCurrentView == eSelectDataView.DataDocumentViewC1)
                view = DicViewFirstMgr[elemAccord.Name];
            else if (eCurrentView == eSelectDataView.DataDocumentViewC2)
                view = DicViewSecondMgr[elemAccord.Name];

            SelectedContents = view.ContentsType;

            tabbedView.ActivateDocument(view);
        }

        void tabbedView_DocumentClosed(object sender, DocumentEventArgs e)
        {
            if (ViewDocMgrLock == false)
            {
                string strViewID = e.Document.Caption;

                accordionControl.Elements.Remove(GetAccordianElement(strViewID));

                if (eCurrentView == eSelectDataView.DataDocumentViewC1)
                    DicViewFirstMgr.Remove(strViewID);
                else if (eCurrentView == eSelectDataView.DataDocumentViewC2)
                    DicViewSecondMgr.Remove(strViewID);
            }
        } 

        private bool CheckDatabaseConnState()
        {
            if(bDatabaseConnState == false)
                MessageBox.Show("No database connected. Connect first.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

            return bDatabaseConnState;
        }
        private async Task<UcTRAOverview> CallOverview()
        {
            if (bOverviewCallState)
                return null;

            bOverviewCallState = true;

            if (bOverviewRunState == false)
            {
                barEditItemProgress.EditValue = 0;

                nProgressProcValue = 0;

                OverviewSearchOption OvOp = new OverviewSearchOption(barToggleSwitchItemShowOption.Checked,
                    barCheckItemFullScan.Checked,
                    barEditItemProductID.EditValue.ToString());

                if (OvOp.ProductID.Length > 0 && OvOp.FullScanData)
                {
                    if (MessageBox.Show("A full scan may take a considerable amount of time. Do you want to run it?", "Check before query ...", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
                    {
                        bOverviewCallState = false;

                        return null;
                    }
                }

                bOverviewRunState = true;
                //
                refRunOverview = CheckOverview();

                await SetOerviewFindData(refRunOverview, OvOp, barToggleSwitchItemOverviewMerge.Checked);

                bOverviewRunState = false;

                if(refRunOverview.GetSqlCommandCancelState())
                    barEditItemProgress.EditValue = 0;
                else
                    barEditItemProgress.EditValue = 100;
            }
            else
            {
                if (refRunOverview != null)
                    refRunOverview.SetSqlCommandCancel();
            }

            bOverviewCallState = false;

            return refRunOverview;
        }
        private async void barButtonItemView_ItemClick(object sender, ItemClickEventArgs e)
        {
            await CallOverview();
        }

        private void SetHostHistoryView(bool bVisibleOption = false)
        {
            UcTRATestHistHost view = null;

            if (CheckDatabaseConnState() == false)
                return;

            bool bViewExist = true;

            if (eCurrentView == eSelectDataView.DataDocumentViewC1)
            {
                if (DicViewFirstMgr.ContainsKey(eContents.Overview.ToString() + eDataView.C1.ToString()) == false)
                    bViewExist = false;
            }
            else if (eCurrentView == eSelectDataView.DataDocumentViewC2)
            {
                if (DicViewSecondMgr.ContainsKey(eContents.Overview.ToString() + eDataView.C2.ToString()) == false)
                    bViewExist = false;
            }

            if (bViewExist == false)
                return;

            view = new UcTRATestHistHost(this, bVisibleOption, barToggleSwitchItemOverviewMerge.Checked);

            view.SetSQLConnection(eCurrentView, this);

            string strSetViewID = string.Empty;
            if (eCurrentView == eSelectDataView.DataDocumentViewC1)
            {
                nFirstViewCount++;

                strSetViewID = eContents.TestHistory.ToString() + eDataView.C1.ToString() + $"({nFirstViewCount})";
                view.ViewID = strSetViewID;
                DicViewFirstMgr.Add(strSetViewID, view);
            }
            else if (eCurrentView == eSelectDataView.DataDocumentViewC2)
            {
                nSecondViewCount++;

                strSetViewID = eContents.TestHistory.ToString() + eDataView.C2.ToString() + $"({nSecondViewCount})";
                view.ViewID = strSetViewID;
                DicViewSecondMgr.Add(strSetViewID, view);
            }

            tabbedView.AddDocument(view, view.ViewID);
            //tabbedView.AddDocument(view, eContents.TestHistory.ToString());

            CreateAccordianElement(view);

            SelectAccordianElement(view.ViewID);

            view.ViewData(SelectedDetailData);

            view.OnDetailSelect -= SetDetailTestDataView;
            view.OnDetailSelect += SetDetailTestDataView;
        }

        private void barButtonItemHostHistory_ItemClick(object sender, ItemClickEventArgs e)
        {
            SetHostHistoryView(GetSearchOption);
        }

        void SetDetailTestDataView(DetailTestDataCollection data)
        {
            UcTRADetailTestResult view = null;

            if (CheckDatabaseConnState() == false)
                return;

            this.Do(() =>
            {
                view = new UcTRADetailTestResult();

                view.SetSQLConnection(eCurrentView, this);

                string strSetViewID = string.Empty;
                if (eCurrentView == eSelectDataView.DataDocumentViewC1)
                {
                    nFirstViewCount++;

                    strSetViewID = eContents.TestResult.ToString() + eDataView.C1.ToString() + $"({nFirstViewCount})";
                    view.ViewID = strSetViewID;
                    DicViewFirstMgr.Add(strSetViewID, view);
                }
                else if (eCurrentView == eSelectDataView.DataDocumentViewC2)
                {
                    nSecondViewCount++;

                    strSetViewID = eContents.TestResult.ToString() + eDataView.C2.ToString() + $"({nSecondViewCount})";
                    view.ViewID = strSetViewID;
                    DicViewSecondMgr.Add(strSetViewID, view);
                }

                tabbedView.AddDocument(view, view.ViewID);
                //tabbedView.AddDocument(view, eContents.TestResult.ToString());

                CreateAccordianElement(view);
                SelectAccordianElement(view.ViewID);

                view.ViewData(data);
            });
        }

        void SetTestTrendDataView(TestTrendDataCollection data)
        {
            UcTRAStepTrend view = null;

            if (CheckDatabaseConnState() == false)
                return;

            this.Do(() =>
            {
                view = new UcTRAStepTrend();

                view.SetSQLConnection(eCurrentView, this);

                string strSetViewID = string.Empty;
                if (eCurrentView == eSelectDataView.DataDocumentViewC1)
                {
                    nFirstViewCount++;

                    strSetViewID = eContents.TestTrend.ToString() + eDataView.C1.ToString() + $"({nFirstViewCount})";
                    view.ViewID = strSetViewID;
                    DicViewFirstMgr.Add(strSetViewID, view);
                }
                else if (eCurrentView == eSelectDataView.DataDocumentViewC2)
                {
                    nSecondViewCount++;

                    strSetViewID = eContents.TestTrend.ToString() + eDataView.C2.ToString() + $"({nSecondViewCount})";
                    view.ViewID = strSetViewID;
                    DicViewSecondMgr.Add(strSetViewID, view);
                }

                tabbedView.AddDocument(view, view.ViewID);
                //tabbedView.AddDocument(view, eContents.TestTrend.ToString());

                CreateAccordianElement(view);
                SelectAccordianElement(view.ViewID);

                view.ViewData(data);
            });
        }

        private void SetHostTrendView()
        {
            BaseDocument baseDoc = tabbedView.ActiveDocument;

            if (baseDoc == null)
                return;

            UcTRABaseView baseView = baseDoc.Control as UcTRABaseView;

            if (baseView == null || baseView.ContentsType != eContents.TestHistory)
            {
                MessageBox.Show("Select a search result for test history.");

                return;
            }

            UcTRASummaryTestResult view = null;

            if (CheckDatabaseConnState() == false)
                return;

            this.Do(() =>
            {
                view = new UcTRASummaryTestResult();

                view.SetSQLConnection(eCurrentView, this);

                string strSetViewID = string.Empty;
                if (eCurrentView == eSelectDataView.DataDocumentViewC1)
                {
                    nFirstViewCount++;

                    strSetViewID = eContents.TestSumamry.ToString() + eDataView.C1.ToString() + $"({nFirstViewCount})";
                    view.ViewID = strSetViewID;
                    DicViewFirstMgr.Add(strSetViewID, view);
                }
                else if (eCurrentView == eSelectDataView.DataDocumentViewC2)
                {
                    nSecondViewCount++;

                    strSetViewID = eContents.TestSumamry.ToString() + eDataView.C2.ToString() + $"({nSecondViewCount})";
                    view.ViewID = strSetViewID;
                    DicViewSecondMgr.Add(strSetViewID, view);
                }

                tabbedView.AddDocument(view, view.ViewID);
                //tabbedView.AddDocument(view, eContents.TestSumamry.ToString());

                CreateAccordianElement(view);
                SelectAccordianElement(view.ViewID);

                view.OnStepSelect -= SetTestTrendDataView;
                view.OnStepSelect += SetTestTrendDataView;

                if (baseView.ContentsType == eContents.TestHistory)
                    view.ViewData(SelectedDetailData, (baseView as UcTRATestHistHost).DataResult);
            });
        }

        private void barButtonItemHostTrend_ItemClick(object sender, ItemClickEventArgs e)
        {
            SetHostTrendView();
        }

        private void barButtonItemExportExcel_ItemClick(object sender, ItemClickEventArgs e)
        {
            BaseDocument baseDoc = tabbedView.ActiveDocument;

            if (baseDoc == null)
                return;

            UcTRABaseView baseView = baseDoc.Control as UcTRABaseView;

            if (baseView != null)
                baseView.ExportData();
        }


        private void SetProductHistoryView(bool bVisibleOption = false)
        {
            UcTRATestHistHost view = null;

            if (CheckDatabaseConnState() == false)
                return;

            bool bViewExist = true;

            if (eCurrentView == eSelectDataView.DataDocumentViewC1)
            {
                if (DicViewFirstMgr.ContainsKey(eContents.Overview.ToString() + eDataView.C1.ToString()) == false)
                    bViewExist = false;
            }
            else if (eCurrentView == eSelectDataView.DataDocumentViewC2)
            {
                if (DicViewSecondMgr.ContainsKey(eContents.Overview.ToString() + eDataView.C2.ToString()) == false)
                    bViewExist = false;
            }

            if (bViewExist == false)
                return;

            view = new UcTRATestHistHost(this, bVisibleOption, barToggleSwitchItemOverviewMerge.Checked);

            view.SetSQLConnection(eCurrentView, this);

            string strSetViewID = string.Empty;
            if (eCurrentView == eSelectDataView.DataDocumentViewC1)
            {
                nFirstViewCount++;

                strSetViewID = eContents.TestHistory.ToString() + eDataView.C1.ToString() + $"({nFirstViewCount})";
                view.ViewID = strSetViewID;
                DicViewFirstMgr.Add(strSetViewID, view);
            }
            else if (eCurrentView == eSelectDataView.DataDocumentViewC2)
            {
                nSecondViewCount++;

                strSetViewID = eContents.TestHistory.ToString() + eDataView.C2.ToString() + $"({nSecondViewCount})";
                view.ViewID = strSetViewID;
                DicViewSecondMgr.Add(strSetViewID, view);
            }

            tabbedView.AddDocument(view, view.ViewID);
            //tabbedView.AddDocument(view, eContents.TestHistory.ToString());

            CreateAccordianElement(view);

            SelectAccordianElement(view.ViewID);
            view.ViewData(SelectedDetailData);

            view.OnDetailSelect -= SetDetailTestDataView;
            view.OnDetailSelect += SetDetailTestDataView;
        }

        private void SetNgHistoryView(eContents GetCallType, bool bVisibleOption = false)
        {
            UcTRATestNgHist view = null;

            if (CheckDatabaseConnState() == false)
                return;

            bool bViewExist = true;

            if (eCurrentView == eSelectDataView.DataDocumentViewC1)
            {
                if (DicViewFirstMgr.ContainsKey(eContents.Overview.ToString() + eDataView.C1.ToString()) == false)
                    bViewExist = false;
            }
            else if (eCurrentView == eSelectDataView.DataDocumentViewC2)
            {
                if (DicViewSecondMgr.ContainsKey(eContents.Overview.ToString() + eDataView.C2.ToString()) == false)
                    bViewExist = false;
            }

            if (bViewExist == false)
                return;

            view = new UcTRATestNgHist(this, bVisibleOption, barToggleSwitchItemOverviewMerge.Checked);

            view.SetSQLConnection(eCurrentView, this);

            string strSetViewID = string.Empty;
            if (eCurrentView == eSelectDataView.DataDocumentViewC1)
            {
                nFirstViewCount++;

                strSetViewID = eContents.NgHistory.ToString() + eDataView.C1.ToString() + $"({nFirstViewCount})";
                view.ViewID = strSetViewID;
                DicViewFirstMgr.Add(strSetViewID, view);
            }
            else if (eCurrentView == eSelectDataView.DataDocumentViewC2)
            {
                nSecondViewCount++;

                strSetViewID = eContents.NgHistory.ToString() + eDataView.C2.ToString() + $"({nSecondViewCount})";
                view.ViewID = strSetViewID;
                DicViewSecondMgr.Add(strSetViewID, view);
            }

            tabbedView.AddDocument(view, view.ViewID);
            //tabbedView.AddDocument(view, eContents.NgHistory.ToString());

            CreateAccordianElement(view);

            SelectAccordianElement(view.ViewID);

            switch (GetCallType)
            {
                case eContents.Overview:
                    view.ViewData(SelectedData);
                    break;
                case eContents.DetailOverview:
                    view.ViewData(SelectedDetailData);
                    break;
            }

            view.OnDetailSelect -= SetDetailTestDataView;
            view.OnDetailSelect += SetDetailTestDataView;
        }

        private void barButtonItemProductHistory_ItemClick(object sender, ItemClickEventArgs e)
        {
            SetProductHistoryView(GetSearchOption);
        }
        
        void SetTestHistoryDataView(TestTrendDataCollection data)
        {
            UcTRAStepTrend view = null;

            if (CheckDatabaseConnState() == false)
                return;

            this.Do(() =>
            {
                view = new UcTRAStepTrend();

                view.SetSQLConnection(eCurrentView, this);

                string strSetViewID = string.Empty;
                if (eCurrentView == eSelectDataView.DataDocumentViewC1)
                {
                    nFirstViewCount++;

                    strSetViewID = eContents.TestTrend.ToString() + eDataView.C1.ToString() + $"({nFirstViewCount})";
                    view.ViewID = strSetViewID;
                    DicViewFirstMgr.Add(strSetViewID, view);
                }
                else if (eCurrentView == eSelectDataView.DataDocumentViewC2)
                {
                    nSecondViewCount++;

                    strSetViewID = eContents.TestTrend.ToString() + eDataView.C2.ToString() + $"({nSecondViewCount})";
                    view.ViewID = strSetViewID;
                    DicViewSecondMgr.Add(strSetViewID, view);
                }

                tabbedView.AddDocument(view, view.ViewID);
                //tabbedView.AddDocument(view, eContents.TestTrend.ToString());

                CreateAccordianElement(view);
                SelectAccordianElement(view.ViewID);

                view.ViewData(data);
            });
        }

        private void CloseAllView()
        {
            while (DicViewFirstMgr.Count != 0)
            {
                for (int i = 0; i < DicViewFirstMgr.Count; i++)
                {
                    string strViewID = DicViewFirstMgr.ElementAt(i).Key;

                    accordionControl.Elements.Remove(GetAccordianElement(strViewID));

                    UserControl uc = (UserControl)DicViewFirstMgr.ElementAt(i).Value;
                    uc.Dispose();

                    DicViewFirstMgr.Remove(strViewID);
                }
            }
        }

        private void barButtonItemConnect_ItemClick(object sender, ItemClickEventArgs e)
        {
            using (GetOnOperationDBConnMarker(true))
            {
                if (bDatabaseConnState)
                {
                    ;//
                }

                if (SetDBConn() == false)
                {
                    using (GetOnOperationDBConnMarker(false))
                    {
                        CloseAllView();

                        bDatabaseConnState = false;
                    }
                }

            }
        }

        private void barButtonItemLogout_ItemClick(object sender, ItemClickEventArgs e)
        {
            using (GetOnOperationDBConnMarker(false))
            {
                CloseAllView();

                DatabaseConnControl.DisconnectDB();

                bDatabaseConnState = false;
            }
        }

        private async void barToggleSwitchItemOverviewMerge_CheckedChanged(object sender, ItemClickEventArgs e)
        {
            if (bMergeByPartNumberLocker)
            {
                bMergeByPartNumberLocker = false;

                return;
            }
            //
            await SetOverviewMerge();
        }

        private void barToggleSwitchItemOverviewFilter_CheckedChanged(object sender, ItemClickEventArgs e)
        {
            if (eCurrentView == eSelectDataView.DataDocumentViewC1)
            {
                if (DicViewFirstMgr.ContainsKey(eContents.Overview.ToString() + eDataView.C1.ToString()))
                {
                    UcTRAOverview view = DicViewFirstMgr[eContents.Overview.ToString() + eDataView.C1.ToString()] as UcTRAOverview;

                    view.gridViewMain.OptionsView.ShowAutoFilterRow = barToggleSwitchItemOverviewFilter.Checked;
                }
            }
            else if (eCurrentView == eSelectDataView.DataDocumentViewC2)
            {
                if (DicViewSecondMgr.ContainsKey(eContents.Overview.ToString() + eDataView.C2.ToString()))
                {
                    UcTRAOverview view = DicViewSecondMgr[eContents.Overview.ToString() + eDataView.C2.ToString()] as UcTRAOverview;

                    view.gridViewMain.OptionsView.ShowAutoFilterRow = barToggleSwitchItemOverviewFilter.Checked;
                }
            }
        }

        void View_ControlReleasing(object sender, DevExpress.XtraBars.Docking2010.Views.ControlReleasingEventArgs e)
        {
            e.Cancel = false;
        }

        void View_QueryControl(object sender, DevExpress.XtraBars.Docking2010.Views.QueryControlEventArgs e)
        {
        }

        private void RemoveViewDocument(eSelectDataView GetCurrentView)
        {
            if (GetCurrentView == eSelectDataView.DataDocumentViewC1)
            {
                foreach (var val in DicViewFirstMgr)
                    tabbedView.RemoveDocument(val.Value);
            }
            else if (GetCurrentView == eSelectDataView.DataDocumentViewC2)
            {
                foreach (var val in DicViewSecondMgr)
                    tabbedView.RemoveDocument(val.Value);
            }
        }

        private void ChangeDatabaseView(eSelectDataView SelectView)
        {
            try
            {
                ViewDocMgrLock = true;

                documentManager.BeginUpdate();

                switch (SelectView)
                {
                    case eSelectDataView.DataDocumentViewC1:
                        if (eCurrentView != eSelectDataView.DataDocumentViewC1)
                        {
                            RemoveViewDocument(eCurrentView);

                            //Dictionary<string, UcTRABaseView>
                            foreach (var val in DicViewFirstMgr)
                                tabbedView.AddDocument(val.Value, val.Key);
                        }

                        eCurrentView = eSelectDataView.DataDocumentViewC1;

                        barButtonItemConnSelect.Caption = "Current : Connect [1]";
                        break;
                    case eSelectDataView.DataDocumentViewC2:
                        if (bUseDataServer2 == false)
                            break;

                        if (eCurrentView != eSelectDataView.DataDocumentViewC2)
                        {
                            RemoveViewDocument(eCurrentView);

                            //Dictionary<string, UcTRABaseView>
                            foreach (var val in DicViewSecondMgr)
                                tabbedView.AddDocument(val.Value, val.Key);
                        }

                        eCurrentView = eSelectDataView.DataDocumentViewC2;

                        barButtonItemConnSelect.Caption = "Current : Connect [2]";
                        break;
                }
                //
                barStaticItemConn.Caption = strConnTLLabel;

                switch (eCurrentView)
                {
                    case eSelectDataView.DataDocumentViewC1:
                        barStaticItemConn.Caption += (" " + strConnDT1Label);
                        break;
                    case eSelectDataView.DataDocumentViewC2:
                        barStaticItemConn.Caption += (" " + strConnDT2Label);
                        break;
                }
            }
            catch (Exception ex)
            {
                string strGetErrMsg = ex.Message;
            }
            finally
            {
                documentManager.EndUpdate();

                ViewDocMgrLock = false;

                this.Focus();
            }
        }

        private void barButtonItemConnSelect_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (ViewDocMgrLock)
                return;

            switch (eCurrentView)
            {
                case eSelectDataView.DataDocumentViewC1:
                    ChangeDatabaseView(eSelectDataView.DataDocumentViewC2);
                    break;
                case eSelectDataView.DataDocumentViewC2:
                    ChangeDatabaseView(eSelectDataView.DataDocumentViewC1);
                    break;
            }
        }

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            if (bDatabaseConnState == false)
                return base.ProcessCmdKey(ref msg, keyData);

            if (ViewDocMgrLock)
                return base.ProcessCmdKey(ref msg, keyData);

            switch (keyData)
            {
                case Keys.Control | Keys.D1:
                    ChangeDatabaseView(eSelectDataView.DataDocumentViewC1);
                    break;
                case Keys.Control | Keys.D2:
                    ChangeDatabaseView(eSelectDataView.DataDocumentViewC2);
                    break;
            }

            return base.ProcessCmdKey(ref msg, keyData);
        }

        private async void MainForm_KeyDown(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.F1:
                    {
                        await CallOverview();
                    }
                    break;
                case Keys.F5: SelectOverviewTab(); break;
                case Keys.F6: SetHostHistoryView(); break;
                case Keys.F7: SetProductHistoryView(); break;
                case Keys.F8: SetHostTrendView(); break;
            }
        }

        private void barButtonItemOverview_ItemClick(object sender, ItemClickEventArgs e)
        {
            SelectOverviewTab();
        }


        private void barButtonItemQueryTestOn_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (ribbonPageGroupQueryTest.Visible)
                ribbonPageGroupQueryTest.Visible = false;
            else
                ribbonPageGroupQueryTest.Visible = true;
        }

        private async void barButtonItemQueryTest_ItemClick(object sender, ItemClickEventArgs e)
        {
            bool bViewExist = false;

            if (eCurrentView == eSelectDataView.DataDocumentViewC1)
            {
                if (DicViewFirstMgr.ContainsKey(eContents.Overview.ToString() + eDataView.C1.ToString()))
                    bViewExist = true;
            }
            else if (eCurrentView == eSelectDataView.DataDocumentViewC2)
            {
                if (DicViewSecondMgr.ContainsKey(eContents.Overview.ToString() + eDataView.C2.ToString()))
                    bViewExist = true;
            }

            if (bViewExist)
            {
                //UcTRAOverview view = DicViewFirstMgr[eContents.Overview.ToString()] as UcTRAOverview;

                OverviewSearchOption OvOp = new OverviewSearchOption(false,
                    false,
                    string.Empty);

                UcTRAOverview view = CheckOverview();

                await SetOerviewFindData(view, OvOp, barToggleSwitchItemOverviewMerge.Checked, barEditItemQuryTest.EditValue.ToString());
            }
        }

        private async void barButtonItemHostUseHist_ItemClick(object sender, ItemClickEventArgs e)
        {
            UcTRAOverview view = null;

            if (CheckDatabaseConnState() == false)
                return;

            bool bViewExist = false;

            if (eCurrentView == eSelectDataView.DataDocumentViewC1)
            {
                if (DicViewFirstMgr.ContainsKey(eContents.HostUseHistory.ToString() + eDataView.C1.ToString()))
                {
                    view = DicViewFirstMgr[eContents.HostUseHistory.ToString() + eDataView.C1.ToString()] as UcTRAOverview;

                    bViewExist = true;
                }
            }
            else if (eCurrentView == eSelectDataView.DataDocumentViewC2)
            {
                if (DicViewSecondMgr.ContainsKey(eContents.HostUseHistory.ToString() + eDataView.C2.ToString()))
                {
                    view = DicViewSecondMgr[eContents.HostUseHistory.ToString() + eDataView.C2.ToString()] as UcTRAOverview;

                    bViewExist = true;
                }
            }

            if (bViewExist)
            {
                view.SearchStart = DateTime.Parse(barEditItemHostHistStart.EditValue.ToString());
                view.SearchEnd = DateTime.Parse(barEditItemHostHistEnd.EditValue.ToString());

                view.SearchEnd = view.SearchEnd.AddHours(23.99);
            }
            else
            {
                view = new UcTRAOverview(this, eContents.HostUseHistory, false, true);

                view.SearchStart = DateTime.Parse(barEditItemHostHistStart.EditValue.ToString());
                view.SearchEnd = DateTime.Parse(barEditItemHostHistEnd.EditValue.ToString());

                view.SearchEnd = view.SearchEnd.AddHours(23.99999);
         
                string strSetID = string.Empty;
                if (eCurrentView == eSelectDataView.DataDocumentViewC1)
                {
                    view.SetSQLConnection(eCurrentView, SetOverviewInfoC1, this);

                    strSetID = eContents.HostUseHistory.ToString() + eDataView.C1.ToString();
                    view.ViewID = strSetID;
                    DicViewFirstMgr.Add(strSetID, view);
                }
                else if (eCurrentView == eSelectDataView.DataDocumentViewC2)
                {
                    view.SetSQLConnection(eCurrentView, SetOverviewInfoC2, this);

                    strSetID = eContents.HostUseHistory.ToString() + eDataView.C2.ToString();
                    view.ViewID = strSetID;
                    DicViewSecondMgr.Add(strSetID, view);
                }

                tabbedView.AddDocument(view, view.ViewID);
                //tabbedView.AddDocument(view, eContents.HostUseHistory.ToString());

                CreateAccordianElement(view);
            }

            SelectAccordianElement(view.ViewID);

            DateTime dtStart = DateTime.Parse(barEditItemHostHistStart.EditValue.ToString());
            DateTime dtEnd = DateTime.Parse(barEditItemHostHistEnd.EditValue.ToString());

            dtEnd = dtEnd.AddHours(23.99999);

            /*
            SELECT * FROM (SELECT 
            CAST(HIST_Summary.[TestDT] AS SMALLDATETIME) AS TestDate,
            HIST_Summary.[StationName] AS StationName,
            HIST_Summary.[HostID] AS Host,
            HIST_Summary.[Section] AS Section,
            Y.ModelName,
            HIST_Summary.[ProdNo_P] AS ParentNo,
            HIST_Summary.[ProdNo_C] AS ProductNo,
            HIST_Summary.[TestType] AS TestType,
            HIST_Summary.[Testcode] AS TestCode,
            HIST_Summary.[ProdCode] AS FileCode,
            HIST_Summary.[Version] AS FileVersion,
            HIST_Summary.[TestlistNo] AS TestlistNo,
            HIST_Summary.[ProductID],
            HIST_Summary.[Result]
            FROM HIST_Summary WITH(NOLOCK) 
            LEFT JOIN [CPX].[dbo].[PROD_TestList] AS X WITH(NOLOCK) ON X.No = CONVERT(NVARCHAR, HIST_Summary.[TestListNo]) 
            LEFT JOIN [CPX].[dbo].[PROD_Group] AS Y WITH(NOLOCK) ON Y.No = X.GroupNo 
            WHERE 
            TestDT >= '2022-06-01 00:00:00' AND 
            TestDT <= '2023-06-14 23:59:59' AND 
            ProductID IN('PowerON', 'PowerOFF', 'QUERY') 
            --EXISTS(SELECT 1 FROM HIST_Summary WHERE ProductID = 'PowerON' OR ProductID = 'PowerOFF' OR ProductID = 'QUERY') 
            GROUP BY 
            CAST(HIST_Summary.TestDT AS SMALLDATETIME),
            HIST_Summary.[StationName],
            HIST_Summary.[HostID],
            HIST_Summary.[Section],
            Y.ModelName,
            HIST_Summary.[ProdNo_P],
            HIST_Summary.[ProdNo_C],
            HIST_Summary.[TestType],
            HIST_Summary.[Testcode],
            HIST_Summary.[ProdCode],
            HIST_Summary.[Version],
            HIST_Summary.[TestlistNo],
            HIST_Summary.[ProductID],
            HIST_Summary.[Result]
            ) AS X
            ORDER BY [TestDate] DESC;

            SELECT * FROM (SELECT 
            CAST(HIST_Summary.[TestDT] AS SMALLDATETIME) AS TestDate,
            HIST_Summary.[StationName] AS StationName,
            HIST_Summary.[HostID] AS Host,
            HIST_Summary.[Section] AS Section,
            Y.ModelName,
            HIST_Summary.[ProdNo_P] AS ParentNo,
            HIST_Summary.[ProdNo_C] AS ProductNo,
            HIST_Summary.[TestType] AS TestType,
            HIST_Summary.[Testcode] AS TestCode,
            HIST_Summary.[ProdCode] AS FileCode,
            HIST_Summary.[Version] AS FileVersion,
            HIST_Summary.[TestlistNo] AS TestlistNo,
            HIST_Summary.[ProductID],
            HIST_Summary.[Result]
            FROM HIST_Summary WITH(NOLOCK) 
            LEFT JOIN [CPX].[dbo].[PROD_TestList] AS X WITH(NOLOCK) ON X.No = CONVERT(NVARCHAR, HIST_Summary.[TestListNo]) 
            LEFT JOIN [CPX].[dbo].[PROD_Group] AS Y WITH(NOLOCK) ON Y.No = X.GroupNo 
            WHERE 
            TestDT >= '2022-06-01 00:00:00' AND 
            TestDT <= '2023-06-14 23:59:59' AND 
            --ProductID IN('PowerON', 'PowerOFF', 'QUERY') 
            EXISTS(SELECT 1 FROM HIST_Summary WHERE ProductID = 'PowerON' OR ProductID = 'PowerOFF' OR ProductID = 'QUERY') 
            GROUP BY 
            CAST(HIST_Summary.TestDT AS SMALLDATETIME),
            HIST_Summary.[StationName],
            HIST_Summary.[HostID],
            HIST_Summary.[Section],
            Y.ModelName,
            HIST_Summary.[ProdNo_P],
            HIST_Summary.[ProdNo_C],
            HIST_Summary.[TestType],
            HIST_Summary.[Testcode],
            HIST_Summary.[ProdCode],
            HIST_Summary.[Version],
            HIST_Summary.[TestlistNo],
            HIST_Summary.[ProductID],
            HIST_Summary.[Result]
            ) AS X
            ORDER BY [TestDate] DESC;
            */

            string strTestQuery = $"SELECT TOP(10000) * FROM (SELECT " +
            $"CAST({DMCommon.SummaryHistTable}.[TestDT] AS DATETIME2) AS TestDate, " +
            $"{DMCommon.SummaryHistTable}.[StationName] AS StationName, " +
            $"{DMCommon.SummaryHistTable}.[HostID] AS Host, " +
            $"{DMCommon.SummaryHistTable}.[Section] AS Section, " +
            $"Y.ModelName, " +
            $"{DMCommon.SummaryHistTable}.[ProdNo_P] AS ParentNo, " +
            $"{DMCommon.SummaryHistTable}.[ProdNo_C] AS ProductNo, " +
            $"{DMCommon.SummaryHistTable}.[TestType] AS TestType, " +
            $"{DMCommon.SummaryHistTable}.[Testcode] AS TestCode, " +
            $"{DMCommon.SummaryHistTable}.[ProdCode] AS FileCode, " +
            $"{DMCommon.SummaryHistTable}.[Version] AS FileVersion, " +
            $"{DMCommon.SummaryHistTable}.[TestListFileNo] AS TestListFileNo, " +
            $"{DMCommon.SummaryHistTable}.[TestListVariantNo] AS TestListVariantNo, " +
            $"{DMCommon.SummaryHistTable}.[ProductID], " +
            $"{DMCommon.SummaryHistTable}.[Result] " +
            $"FROM {DMCommon.SummaryHistTable} WITH(NOLOCK) " +
            $"LEFT JOIN [CPXV2].[dbo].[PROD_Variant] AS X WITH(NOLOCK) ON X.No = CONVERT(NVARCHAR, {DMCommon.SummaryHistTable}.[TestListVariantNo]) " +
            $"LEFT JOIN [CPXV2].[dbo].[PROD_Group] AS Y WITH(NOLOCK) ON Y.No = X.GroupNo " +
            $"WHERE " +
            $"TestDT >= '{dtStart.ToString("yyyy-MM-dd HH:mm:ss")}' AND " +
            $"TestDT <= '{dtEnd.ToString("yyyy-MM-dd HH:mm:ss")}' AND " +
            $"ProductID IN('PowerON', 'PowerOFF', 'QUERY') " +
            $"GROUP BY " +
            $"CAST({DMCommon.SummaryHistTable}.TestDT AS DATETIME2), " +
            $"{DMCommon.SummaryHistTable}.[StationName], " +
            $"{DMCommon.SummaryHistTable}.[HostID], " +
            $"{DMCommon.SummaryHistTable}.[Section], " +
            $"Y.ModelName, " +
            $"{DMCommon.SummaryHistTable}.[ProdNo_P], " +
            $"{DMCommon.SummaryHistTable}.[ProdNo_C], " +
            $"{DMCommon.SummaryHistTable}.[TestType], " +
            $"{DMCommon.SummaryHistTable}.[Testcode], " +
            $"{DMCommon.SummaryHistTable}.[ProdCode], " +
            $"{DMCommon.SummaryHistTable}.[Version], " +
            $"{DMCommon.SummaryHistTable}.[TestListFileNo], " +
            $"{DMCommon.SummaryHistTable}.[TestListVariantNo], " +
            $"{DMCommon.SummaryHistTable}.[ProductID], " +
            $"{DMCommon.SummaryHistTable}.[Result] " +
            $") AS X " +
            $"ORDER BY[TestDate] DESC;";

            OverviewSearchOption OvOp = new OverviewSearchOption(barToggleSwitchItemShowOption.Checked,
                false,
                string.Empty);

            OverviewSearchOption oso = await view.ViewData(dtStart, dtEnd, OvOp, false, true, strTestQuery);

            barEditItemQuryTest.EditValue = view.GetUseQuery();
        }

        private void timerProc_Tick(object sender, EventArgs e)
        {
            if (bOverviewRunState)
            {
                if (nProgressProcValue < 99)
                {
                    barEditItemProgress.EditValue = nProgressProcValue;

                    nProgressProcValue += 1;
                }
            }
        }
    }
}