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 System.Reflection;
using System.IO;
using System.Diagnostics;
using System.Threading;
using System.Xml.Linq;

using SystemX.Common.Archive;
using SystemX.Product.ALIS.UI.Subs;
using SystemX.Product.ALIS.UI.View.InfoList;
using SystemX.Product.ALIS.Interface;

using static SystemX.Product.ALIS.UI.View.ViewCfg;
using static SystemX.Product.ALIS.UI.Commons;
using static SystemX.Net.Platform.Common.Util.LogMessage;

using CpTesterPlatform.CpLogUtil;
using CpApplication;
using CpApplication.Manager;
using CpCommon;

using PsKGaudi.Parser.PsCCSArea;
using PsKGaudi;
using PsKGaudi.Parser.MacroModuleSkel;
using PsKGaudi.Parser.PsCCSSTDFn.Parameters;
using PsKGaudi.Parser.PsCCSSTDFn;

using static PsCommon.PsCommon;
using static CpCommon.ExceptionHandler;
using static PsKGaudi.Parser.PsCCS;

using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.Base;
using DevExpress.Utils;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using SystemX.Common;

namespace SystemX.Product.ALIS.UI.View.InfoList
{
    public partial class UcTestListView : UserControl, IUserControlSubscribe
    {
        /// <summary>
        /// IUserControlSubscribe - SetLoginStateNotice
        /// </summary>
        /// <param name="CurrentAccessLevel"></param>
        /// <param name="bLoginState"></param>
        public void SetLoginStateNotice(LoginAccessLevel CurrentAccessLevel, bool bLoginState)
        {
            bool bSetState = ((CurrentAccessLevel == ThisAccessLevel) && (bLoginState == true)) ? true : false;

            stRefreshTimer.Restart();

            ViewLoginState = bSetState;

            WizardCancelEvent?.Invoke(bSetState, null);

            this.Invoke((MethodInvoker)delegate ()
            {
                if (bSetState)
                {
                    layoutControlItemDataMod.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Always;
                    layoutControlItemModelMod.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Always;
                }
                else
                {
                    layoutControlItemDataMod.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
                    layoutControlItemModelMod.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
                }

                ChangeViewType(eSetViewMode.MainView, false);
            });
        }

        /// <summary>
        /// IUserControlSubscribe - GoToFindTestListFileFocus
        /// </summary>
        /// <param name="nTestListFileNo"></param>
        public void GoToFindTestListFileFocus(int nTestListFileNo)
        {
            this.Focus();

            gridHistView.Focus();

            gridHistView.FocusedRowHandle = gridHistView.LocateByDisplayText(0, gridHistView.Columns["No"], nTestListFileNo.ToString());
        }

        /// <summary>
        /// IUserControlSubscribe - GoToFindParentFocus
        /// </summary>
        /// <param name="nParentNo"></param>
        public void GoToFindVariantFocus(int nVariantNo)
        {
            this.Focus();

            gridHistView.Focus();

            gridHistView.FocusedRowHandle = gridHistView.LocateByDisplayText(0, gridHistView.Columns["No"], nVariantNo.ToString());
        }

        /// <summary>
        /// IUserControlSubscribe
        /// </summary>
        public void RefreshDataView()
        {
            eNowViewMode = eSetViewMode.MainView;

            ViewRefresh();
        }

        private void GoToBeforeFocus(int nAbsoluteIndex)
        {
            gridHistView.Focus();

            gridHistView.FocusedRowHandle = nAbsoluteIndex;
        }

        private void EventClear(object obj)
        {
            if (WizardCancelEvent != null)
            {
                foreach (Delegate d in WizardCancelEvent?.GetInvocationList())
                {
                    if (d.Target.GetType() == obj.GetType())
                        WizardCancelEvent -= (EventHandler)d;
                }
            }
        }

        private Dictionary<string, Tuple<SqlDbType, int>> dicTestListFileField;
        private Dictionary<string, Tuple<SqlDbType, int>> dicTestListVariantField;
        private Dictionary<string, Tuple<SqlDbType, int>> dicTestListReleaseField;
        private Dictionary<string, Tuple<SqlDbType, int>> dicVRFYReleaseField;

        public event EventHandler WizardCancelEvent;
        public int AbsoluteIndexRow { get; set; }
        public string AbsoluteUniqueNo { get; set; }
        public string AbsoluteHostName { get; set; }
        //public int AbsoluteIndexCol { get; set; }

        private IChildController ctrlChild;

        private IDataController ctrlDB;

        private DataSet ds = new DataSet();
        private DataTable dt = new DataTable();

        private DataTable dtBeforeReleaseVRFY;
        private DataTable dtBeforeTestList;

        private eSelectType SelectOpenType { get; set; }

        private eEditType eEdtType { get; set; }

        private eSetViewMode eNowViewMode { get; set; } = eSetViewMode.MainView;

        private string strSelectTable;

        private int nVRFYParameter;
        
        //TestList File
        private BackgroundWorker workerTestListFile = new BackgroundWorker();

        //TestList Variant
        private BackgroundWorker workerTestListVariant = new BackgroundWorker();
        //private BackgroundWorker workerTestListVariantFullUpdate = new BackgroundWorker();

        private WaitProgressForm loadForm = null;
        private Stopwatch stLoadFormWait = new Stopwatch();

        public LoginAccessLevel ThisAccessLevel { get; private set; }

        public bool ViewLoginState { private set; get; }

        /// <summary>
        /// Key Event Vars - Release Copy
        /// </summary>
        private bool bCtrlKeyOn = false;
        private bool bHasCopyData = false;

        //Release
        private CReleaseInformation SelectTestListReleaseInfo = new CReleaseInformation();

        private List<CReleaseInformation> lstSetCopyRelease;

        private string strSetCopyProductNoData;
        //Variant
        private CVariantInformation SelectTestListVariantInfo = new CVariantInformation();

        //private List<CReleaseInformation> lstSetUpdateTestList;
        //
        //TestList - File
        private CTestListFileInformation SelectTestListFileInfo = new CTestListFileInformation();

        private Stopwatch stClickTimer;
        
        private long lClickTimerValue;

        private int nPopupMenuHitRow;

        private Stopwatch stRefreshTimer;

        private void SetObjectPosition(Control ct)
        {
            ct.Location = Control.MousePosition;

            int nYSize = ct.Location.Y + ct.Height;
            int nXSize = ct.Location.X + ct.Width;

            int nPYSize = this.Parent.Location.Y + this.Parent.Height;
            int nPXSize = this.Parent.Location.X + this.Parent.Width;

            int nYPos = ct.Location.Y;
            int nXPos = ct.Location.X;

            int nYValue = 0;
            int nXValue = 0;

            if (nPYSize < nYSize)
                nYValue = nYSize - nPYSize;
            if (nPXSize < nXSize)
                nXValue = nXSize - nPXSize;

            ct.Location = new Point(nXPos - nXValue, nYPos - nYValue);
        }

        public UcTestListView(eSelectType SelType, IChildController ctrlChild, IDataController ctrlDB, LoginAccessLevel MakeAccessLevel, bool bLoginState = false)
        {
            InitializeComponent();

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

            ThisAccessLevel = MakeAccessLevel;

            //TestList File
            workerTestListFile.DoWork += (sender, args) => PerformTestListFileReading(sender, args);
            workerTestListFile.RunWorkerCompleted += (sender, args) => ReadingFileCompleted(sender, args);

            //TestList Variant
            workerTestListVariant.DoWork += (sender, args) => PerformTestListVariantReading(sender, args);
            workerTestListVariant.RunWorkerCompleted += (sender, args) => ReadingVariantCompleted(sender, args);

            /*
            workerTestListVariantFullUpdate.DoWork += (sender, args) => PerformTestListVariantFullUpdate(sender, args);
            workerTestListVariantFullUpdate.RunWorkerCompleted += (sender, args) => ReadingVariantFullUpdateCompleted(sender, args);
            */

            stLoadFormWait.Start();

            ViewLoginState = bLoginState;

            if (ViewLoginState)
            {
                layoutControlItemModelMod.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Always;
                layoutControlItemDataMod.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Always;
            }

            // This line of code is generated by Data Source Configuration Wizard
            // Fill a SqlDataSource

            this.ctrlChild = ctrlChild;

            this.ctrlDB = ctrlDB;

            SelectOpenType = SelType;

            layoutControlItemFile.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
            layoutControlItemVariant.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
            layoutControlItemRelease.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;

            layoutControlItemFilter.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Always;
            layoutControlItemGroup.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Always;

            switch (SelectOpenType)
            {
                case eSelectType.TestListFile:
                    layoutControlItemFilter.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
                    layoutControlItemGroup.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;

                    layoutControlItemFile.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Always;
                    layoutControlItemExportTestList.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Always;
                    layoutControlItemVRFY.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Always;

                    strSelectTable = "STOR_TestListFile";

                    layoutControlItemQuery1.Text = "Name";
                    layoutControlItemQuery2.Text = "TestType";
                    layoutControlItemQuery3.Text = "FileVersion";
                    layoutControlItemQuery4.Text = "ProdCode";
                    layoutControlItemQuery5.Text = "FileName";

                    layoutControlItemQuery5.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Always;
                    break;
                case eSelectType.TestListVariant:
                    layoutControlItemVariant.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Always;

                    //layoutControlItemExportTestList.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Always;
                    //layoutControlItemVRFY.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Always;
                    layoutControlItemSelectTL.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Always;
                    //layoutControlItemSelectParentFullUpdate.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Always;

                    strSelectTable = "PROD_Variant";

                    layoutControlItemQuery1.Text = "P_ProdNo";
                    layoutControlItemQuery2.Text = "TestType";
                    layoutControlItemQuery3.Text = "FileVersion";
                    layoutControlItemQuery4.Text = "ProdCode";

                    break;
                case eSelectType.TestListRelease:
                    layoutControlItemRelease.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Always;

                    gridHistView.OptionsSelection.MultiSelect = true;

                    strSelectTable = "PROD_Release";

                    layoutControlItemQuery1.Text = "C_ProdNo";
                    layoutControlItemQuery2.Text = "TestCode";
                    layoutControlItemQuery3.Text = "TestType";
                    layoutControlItemQuery4.Text = "FileVersion";
                    layoutControlItemQuery5.Text = "ProdCode";
                    layoutControlItemQuery6.Text = "P_ProdNo";

                    layoutControlItemQuery5.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Always;
                    layoutControlItemQuery6.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Always;

                    break;
            }

            AbsoluteIndexRow = -1;
            //AbsoluteIndexCol = -1;

            AbsoluteUniqueNo = "";

            simpleButtonRegister1.Text = "Register " + SelectOpenType.ToString() + "(Ctrl+N)";

            lstSetCopyRelease = new List<CReleaseInformation>();
            lstSetCopyRelease.Clear();

            stClickTimer = new Stopwatch();
            stClickTimer.Start();
        }

        private void ViewRefresh(string strSetTableName = "", string strColName = "", string strParameter = "")
        {
            string strGetFilterSet = gridHistView.ActiveFilterString;

            eDbTableList selTable = eDbTableList.NONE;

            string vTblName = string.Empty;

            if (strSetTableName.Length > 0)
                vTblName = strSetTableName;
            else
                vTblName = strSelectTable;

            if (Enum.TryParse<eDbTableList>(vTblName, out selTable))
            {
                //ViewgridControl.BeginUpdate();
                ViewgridControl.BeginInit();

                GridView targetView = null;

                if (eNowViewMode == eSetViewMode.MainView)
                    targetView = gridHistView;
                else if (eNowViewMode == eSetViewMode.SubView)
                    targetView = gridViewTestList;

                ViewgridControl.DataSource = null;

                gridHistView.RefreshData();
                gridViewTestList.RefreshData();

                bool bHasInfo = false;

                if (strColName.Length > 0 && strParameter.Length > 0)
                    bHasInfo = true;

                if (eNowViewMode == eSetViewMode.MainView)
                {
                    if (bHasInfo)
                        dtBeforeTestList = ctrlDB.GetTable(selTable, strColName, strParameter);
                    else
                        dtBeforeTestList = ctrlDB.GetTable(selTable);

                    ViewgridControl.DataSource = dtBeforeTestList;
                }
                else if (eNowViewMode == eSetViewMode.SubView)
                {
                    if (bHasInfo)
                        dtBeforeReleaseVRFY = ctrlDB.GetTable(selTable, strColName, strParameter);
                    else
                        dtBeforeReleaseVRFY = ctrlDB.GetTable(selTable);

                    ViewgridControl.DataSource = dtBeforeReleaseVRFY;
                }

                ViewgridControl.MainView = targetView;

                //ViewgridControl.DataMember = vTblName;
                ViewgridControl.Views[0].PopulateColumns();

                ViewgridControl.EndInit();
                ViewgridControl.BeginInit();

                for (int i = 0; i < targetView.Columns.Count; i++)
                    targetView.Columns[i].OptionsColumn.AllowMerge = DevExpress.Utils.DefaultBoolean.False;

                ColumnStyleSet();

                targetView.BestFitColumns();

                ColumnSizeSet();

                gridHistView.ActiveFilterString = strGetFilterSet;

                ViewgridControl.EndInit();
                //ViewgridControl.EndUpdate();

                if (AbsoluteIndexRow != -1)
                {
                    GoToBeforeFocus(AbsoluteIndexRow);

                    //AbsoluteIndexRow = -1;
                }
            }
        }

        private void ViewChange(DataTable dtSource = null)
        {
            ViewgridControl.BeginInit();

            GridView targetView = null;

            if (eNowViewMode == eSetViewMode.MainView)
                targetView = gridHistView;
            else if (eNowViewMode == eSetViewMode.SubView)
                targetView = gridViewTestList;

            ViewgridControl.DataSource = null;

            gridHistView.RefreshData();
            gridViewTestList.RefreshData();

            if (dtSource != null)
            {
                if (eNowViewMode == eSetViewMode.MainView)
                    ViewgridControl.DataSource = dtSource;
                else if (eNowViewMode == eSetViewMode.SubView)
                    ViewgridControl.DataSource = dtSource;
            }
            else
            {
                if (eNowViewMode == eSetViewMode.MainView)
                    ViewgridControl.DataSource = dtBeforeTestList;
                else if (eNowViewMode == eSetViewMode.SubView)
                    ViewgridControl.DataSource = dtBeforeReleaseVRFY;
            }

            ViewgridControl.MainView = targetView;

            ViewgridControl.MainView.RefreshData();

            //ViewgridControl.DataMember = vTblName;
            ViewgridControl.Views[0].PopulateColumns();

            ViewgridControl.EndInit();
            ViewgridControl.BeginInit();

            for (int i = 0; i < targetView.Columns.Count; i++)
                targetView.Columns[i].OptionsColumn.AllowMerge = DevExpress.Utils.DefaultBoolean.False;

            ColumnStyleSet();

            targetView.BestFitColumns();

            ColumnSizeSet();

            ViewgridControl.EndInit();

            if (dtSource == null)
            {
                if (AbsoluteIndexRow != -1)
                {
                    GoToBeforeFocus(AbsoluteIndexRow);

                    //AbsoluteIndexRow = -1;
                }
            }
        }

        private void ColumnStyleSet()
        {
            GridView targetView = null;

            if (eNowViewMode == eSetViewMode.MainView)
                targetView = gridHistView;
            else if (eNowViewMode == eSetViewMode.SubView)
                targetView = gridViewTestList;

            if (targetView.Columns.Any(x => x.FieldName == "RegDT"))
            {
                if (targetView.Columns["RegDT"].DisplayFormat.FormatString.CompareTo("yyyy-MM-dd HH:mm:ss.fff") != 0)
                {
                    targetView.Columns["RegDT"].DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime;
                    targetView.Columns["RegDT"].DisplayFormat.FormatString = "yyyy-MM-dd HH:mm:ss.fff";
                }
            }
            if (targetView.Columns.Any(x => x.FieldName == "UpdateDT"))
            {
                if (targetView.Columns["UpdateDT"].DisplayFormat.FormatString.CompareTo("yyyy-MM-dd HH:mm:ss.fff") != 0)
                {
                    targetView.Columns["UpdateDT"].DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime;
                    targetView.Columns["UpdateDT"].DisplayFormat.FormatString = "yyyy-MM-dd HH:mm:ss.fff";
                }
            }

            string[] strCtrlFieldName = new string[8];
            strCtrlFieldName[0] = "TestListData";
            strCtrlFieldName[1] = "TestCodeNo";
            strCtrlFieldName[2] = "VariantNo";
            strCtrlFieldName[3] = "GroupNo";
            strCtrlFieldName[4] = "Config";
            strCtrlFieldName[5] = "TestListFileNo";
            strCtrlFieldName[6] = "TestListName";
            strCtrlFieldName[7] = "Name";

            for (int i = 0; i < strCtrlFieldName.Count(); i++)
            {
                IEnumerable<bool> getIndexResult = targetView.Columns.Select(x => x.FieldName == strCtrlFieldName[i]);

                if (getIndexResult == null)
                    continue;

                if (getIndexResult.Any())
                {
                    if (targetView.Columns.Any(x => x.FieldName == strCtrlFieldName[i]))
                    {
                        GridColumn gc = targetView.Columns.First(x => x.FieldName == strCtrlFieldName[i]);
                        int igetIdx = targetView.Columns.IndexOf(gc);

                        if (targetView.Columns[igetIdx].Visible)
                            targetView.Columns[igetIdx].Visible = false;
                    }
                }
            }
        }

        private void ColumnSizeSet()
        {
            GridView targetView = null;

            if (eNowViewMode == eSetViewMode.MainView)
                targetView = gridHistView;
            else if (eNowViewMode == eSetViewMode.SubView)
                targetView = gridViewTestList;

            string[] strChangeSizeFieldName = new string[3];
            strChangeSizeFieldName[0] = "FileName";
            strChangeSizeFieldName[1] = "P_ProdNo";
            strChangeSizeFieldName[2] = "C_ProdNo";

            for (int i = 0; i < strChangeSizeFieldName.Count(); i++)
            {
                IEnumerable<bool> getIndexResult = targetView.Columns.Select(x => x.FieldName == strChangeSizeFieldName[i]);

                if (getIndexResult == null)
                    continue;

                if (getIndexResult.Any())
                {
                    if (targetView.Columns.Any(x => x.FieldName == strChangeSizeFieldName[i]))
                    {
                        GridColumn gc = targetView.Columns.First(x => x.FieldName == strChangeSizeFieldName[i]);
                        int igetIdx = targetView.Columns.IndexOf(gc);

                        int nGetWidth = targetView.Columns[igetIdx].Width;
                        targetView.Columns[igetIdx].Width = nGetWidth + 75;
                    }
                }
            }
        }

        private bool getStatusLoadForm()
        {
            return ((Control)loadForm).Visible;
        }

        private void InsertProdTestListFileInformation(CTestListFileInformation item)
        {
            SqlCommand cmd = new SqlCommand(); 

            string sqlCommandText = "";
            string columns = string.Empty;

            columns = "Name,TestType,Version,ProdCode,FileName,RegDT,RegUser,UpdateDT,UpdateUser,Comment,Description,TestListData";
            string values = string.Join(",", columns.Split(',').Select(c => string.Format("@{0}", c)));
            sqlCommandText = string.Format("INSERT INTO [" + strSelectTable + "] ({0}) VALUES ({1})", columns, values);

            cmd = new SqlCommand(sqlCommandText, ctrlDB.GetConnSqlCmd().Connection);
            SqlParameter[] setParams = new SqlParameter[columns.Split(',').Count()];

            string strGetUpdateDateTime = ctrlDB.SetConvertDateTime(item.UpdateDT.ToString());
            string strGetRegDateTime = ctrlDB.SetConvertDateTime(item.RegDT.ToString());

            //setParams[0] = GetMakeSqlParameterInfo(dicTestListFileField, "Name", item.Name);

            setParams[0] = GetMakeSqlParameterInfo(dicTestListFileField, "Name", "-");
            setParams[1] = GetMakeSqlParameterInfo(dicTestListFileField, "TestType", item.TestType);
            setParams[2] = GetMakeSqlParameterInfo(dicTestListFileField, "Version", item.Version);
            setParams[3] = GetMakeSqlParameterInfo(dicTestListFileField, "ProdCode", item.ProdCode);
            setParams[4] = GetMakeSqlParameterInfo(dicTestListFileField, "FileName", item.FileName);
            setParams[5] = GetMakeSqlParameterInfo(dicTestListFileField, "RegDT", strGetRegDateTime);
            setParams[6] = GetMakeSqlParameterInfo(dicTestListFileField, "RegUser", item.RegUser);
            setParams[7] = GetMakeSqlParameterInfo(dicTestListFileField, "UpdateDT", strGetUpdateDateTime);
            setParams[8] = GetMakeSqlParameterInfo(dicTestListFileField, "UpdateUser", item.UpdateUser);
            setParams[9] = GetMakeSqlParameterInfo(dicTestListFileField, "Comment", item.Comment);
            setParams[10] = GetMakeSqlParameterInfo(dicTestListFileField, "Description", item.Description);

            byte[] ucWriteTestList = XDataArchive.CompressGZipByteToByte(item.TestListFileSelectRawData);
            setParams[11] = GetMakeSqlParameterInfo(dicTestListFileField, "TestListData", ucWriteTestList);

            cmd.Parameters.AddRange(setParams);

            try
            {
                int EffectRows = cmd.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "SqlInsertProdTestListFile - Insert - Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

                return;
            }
        }

        private void InsertProdTestListVariantInformation(CVariantInformation item)
        {
            SqlCommand cmd = new SqlCommand();

            string sqlCommandText = "";
            string columns = string.Empty;

            //TestType,Version,ProdCode,FileName
            columns = "ProdNo_P,RegDT,RegUser,UpdateDT,UpdateUser,GroupNo,Comment,Description,TestListFileNo";
            string values = string.Join(",", columns.Split(',').Select(c => string.Format("@{0}", c)));
            sqlCommandText = string.Format("INSERT INTO [" + strSelectTable + "] ({0}) VALUES ({1})", columns, values);

            cmd = new SqlCommand(sqlCommandText, ctrlDB.GetConnSqlCmd().Connection);
            SqlParameter[] setParams = new SqlParameter[columns.Split(',').Count()];

            string strGetUpdateDateTime = ctrlDB.SetConvertDateTime(item.UpdateDT.ToString());
            string strGetRegDateTime = ctrlDB.SetConvertDateTime(item.RegDT.ToString());

            setParams[0] = GetMakeSqlParameterInfo(dicTestListVariantField, "ProdNo_P", item.ProdNo_P);
            /*
            setParams[1] = GetMakeSqlParameterInfo(dicTestListVariantField, "TestType", item.TestType);
            setParams[2] = GetMakeSqlParameterInfo(dicTestListVariantField, "Version", item.Version);
            setParams[3] = GetMakeSqlParameterInfo(dicTestListVariantField, "ProdCode", item.ProdCode);
            setParams[4] = GetMakeSqlParameterInfo(dicTestListVariantField, "FileName", item.FileName);
            */
            setParams[1] = GetMakeSqlParameterInfo(dicTestListVariantField, "RegDT", strGetRegDateTime);
            setParams[2] = GetMakeSqlParameterInfo(dicTestListVariantField, "RegUser", item.RegUser);
            setParams[3] = GetMakeSqlParameterInfo(dicTestListVariantField, "UpdateDT", strGetUpdateDateTime);
            setParams[4] = GetMakeSqlParameterInfo(dicTestListVariantField, "UpdateUser", item.UpdateUser);
            setParams[5] = GetMakeSqlParameterInfo(dicTestListVariantField, "GroupNo", item.GroupNo);
            setParams[6] = GetMakeSqlParameterInfo(dicTestListVariantField, "Comment", item.Comment);
            setParams[7] = GetMakeSqlParameterInfo(dicTestListVariantField, "Description", item.Description);
            setParams[8] = GetMakeSqlParameterInfo(dicTestListVariantField, "TestListFileNo", item.TestListFileNo);
            
            cmd.Parameters.AddRange(setParams);

            try
            {
                int EffectRows = cmd.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "SqlInsertProdTestListVariant - Insert - Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

                return;
            }
        }

        private void InsertReleaseListInformation(CReleaseInformation item)
        {
            SqlCommand cmd = new SqlCommand();

            string sqlCommandInsert = "";
            string columns = string.Empty;

            SetTestListRelFieldInfo();

            columns = "ProdNo_C,TestCodeNo,VariantNo,Config,RegDT,RegUser,RegUserComment";
            string values = string.Join(",", columns.Split(',').Select(c => string.Format("@{0}", c)));
            sqlCommandInsert = string.Format("INSERT INTO [PROD_Release] ({0}) VALUES ({1})", columns, values);

            cmd = new SqlCommand(sqlCommandInsert, ctrlDB.GetConnSqlCmd().Connection);
            SqlParameter[] setParams = new SqlParameter[columns.Split(',').Count()];

            string strGetRegDateTime = ctrlDB.SetConvertDateTime(item.RegDT.ToString());

            setParams[0] = GetMakeSqlParameterInfo(dicTestListReleaseField, "ProdNo_C", item.ProdNo_C);
            setParams[1] = GetMakeSqlParameterInfo(dicTestListReleaseField, "TestCodeNo", item.TestCodeNo);
            setParams[2] = GetMakeSqlParameterInfo(dicTestListReleaseField, "VariantNo", item.VariantNo);
            setParams[3] = GetMakeSqlParameterInfo(dicTestListReleaseField, "Config", item.Config);
            setParams[4] = GetMakeSqlParameterInfo(dicTestListReleaseField, "RegDT", strGetRegDateTime);
            setParams[5] = GetMakeSqlParameterInfo(dicTestListReleaseField, "RegUser", item.RegUser);
            setParams[6] = GetMakeSqlParameterInfo(dicTestListReleaseField, "RegUserComment", item.RegUserComment);

            cmd.Parameters.AddRange(setParams);

            int EffectRows = cmd.ExecuteNonQuery();
        }

        private void simpleButtonPrint_Click(object sender, EventArgs e)
        {
            ViewgridControl.ShowPrintPreview();
        }

        private void simpleButtonRegister1_Click(object sender, EventArgs e)
        {
            NewItem();
        }

        private void UcTestListView_WizardCancelEvent(string userName)
        {
            throw new NotImplementedException();
        }

        private void simpleButtonModify1_Click(object sender, EventArgs e)
        {
            ModifyItem();
        }

        private void GridViewSelectedProc(int nRow)
        {
            lClickTimerValue = stClickTimer.ElapsedMilliseconds;

            if (eNowViewMode == eSetViewMode.SubView)
                return;

            AbsoluteIndexRow = nRow;

            simpleLabelItemSelectRow.Text = "Select Row : " + (nRow + 1).ToString();

            if (CheckRowSelectInfo())
            {
                try
                {
                    string strNumber = gridHistView.GetFocusedRowCellValue("No").ToString();

                    AbsoluteUniqueNo = strNumber;

                    nVRFYParameter = Convert.ToInt32(AbsoluteUniqueNo);

                    if (CreateInfo(SelectOpenType, lClickTimerValue))
                        stClickTimer.Restart();
                }
                catch
                {
                    ClearListSelect();
                }
            }
            else
            {
                ClearListSelect();
            }
        }

        private void gridHistView_RowClick(object sender, RowClickEventArgs e)
        {
            int nRow = e.RowHandle;

            if (e.Button != MouseButtons.Left)
            {
                gridHistView.OptionsSelection.EnableAppearanceFocusedCell = false;
                gridHistView.OptionsSelection.EnableAppearanceFocusedRow = false;
                gridHistView.OptionsSelection.EnableAppearanceHideSelection = false;

                ClearListSelect();

                return;
            }
            else
            {
                gridHistView.OptionsSelection.EnableAppearanceFocusedCell = true;
                gridHistView.OptionsSelection.EnableAppearanceFocusedRow = true;
                gridHistView.OptionsSelection.EnableAppearanceHideSelection = true;
            }

            GridViewSelectedProc(nRow);
        }

        private void gridHistView_RowCellClick(object sender, RowCellClickEventArgs e)
        {
            /*if (e.Column.FieldName.Equals("No"))
            {
                simpleLabelItemSelectRow.Text = "Select Row : " + (e.RowHandle + 1).ToString();
                simpleLabelItemSelectCol.Text = "Select Col : " + (e.Column.AbsoluteIndex + 1).ToString();

                AbsoluteIndexRow = e.RowHandle;
                AbsoluteIndexCol = e.Column.AbsoluteIndex;

                string strNumber = gridHistView.GetFocusedRowCellValue("No").ToString();

                AbsoluteUniqueNo = strNumber;

                nVRFYParameter = Convert.ToInt32(AbsoluteUniqueNo);

                CreateInfo(SelectOpenType);
            }
            else
            {
                ClearListSelect();
            }*/
        }

        private void simpleButtonViewList_Click(object sender, EventArgs e)
        {
            eNowViewMode = eSetViewMode.MainView;

            ViewRefresh();
        }

        private void simpleButtonDataMod_Click(object sender, EventArgs e)
        {
            if (layoutControlItemModelMod.Visibility == DevExpress.XtraLayout.Utils.LayoutVisibility.Never)
            {
                layoutControlItemModelMod.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Always;
            }
            else
                layoutControlItemModelMod.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
        }

        private GridCellInfo GetMergedCell(GridViewInfo viewInfo, int rowHandle, GridColumn gc)
        {
            GridCellInfo cell = viewInfo.GetGridCellInfo(rowHandle, gc);
            if ((cell == null) || (!cell.IsMerged)) return null;
            else return cell;
        }

        private bool MergedCellIsFocused(GridView view, GridCellInfo cell)
        {
            if (cell == null) return false;

            foreach (GridCellInfo ci in cell.MergedCell.MergedCells)
                if (ci.RowHandle == view.FocusedRowHandle) return true;

            return false;
        }

        private void RefreshMergedCell(GridView view, GridCellInfo cell)
        {
            if (cell == null) return;

            foreach (GridCellInfo ci in cell.MergedCell.MergedCells) 
                view.RefreshRow(ci.RowHandle);
        }

        private void gridHistView_RowCellStyle(object sender, RowCellStyleEventArgs e)
        {
            if (false)
            {
                GridView view = (GridView)sender;
                GridViewInfo viewInfo = (GridViewInfo)view.GetViewInfo();

                if (MergedCellIsFocused(view, GetMergedCell(viewInfo, e.RowHandle, gridHistView.Columns[1])))
                {
                    e.Appearance.Assign(viewInfo.PaintAppearance.FocusedRow);
                    e.Appearance.TextOptions.HAlignment = e.Column.AppearanceCell.HAlignment;
                }
                else
                {
                    if (e.RowHandle == view.FocusedRowHandle)
                    {
                        e.Appearance.Assign(viewInfo.PaintAppearance.FocusedRow);
                        e.Appearance.TextOptions.HAlignment = e.Column.AppearanceCell.HAlignment;
                    }
                }
            }
        }

        private void gridHistView_FocusedRowChanged(object sender, FocusedRowChangedEventArgs e)
        {
            if (false)
            {
                GridView view = (GridView)sender;
                GridViewInfo viewInfo = (GridViewInfo)view.GetViewInfo();

                /*
                int[] nFilterIdx = null;

                if (SelectOpenType == eSelectType.TestList)
                    nFilterIdx = new int[2] { 1, 3 };
                else if (SelectOpenType == eSelectType.TestListRel)
                    nFilterIdx = new int[2] { 1, 5 };

                for (int i = 0; i < nFilterIdx.Count(); i++)
                {
                    RefreshMergedCell(view, GetMergedCell(viewInfo, e.PrevFocusedRowHandle, gridHistView.Columns[nFilterIdx[i]]));
                    RefreshMergedCell(view, GetMergedCell(viewInfo, e.FocusedRowHandle, gridHistView.Columns[nFilterIdx[i]]));
                }
                */

                RefreshMergedCell(view, GetMergedCell(viewInfo, e.PrevFocusedRowHandle, gridHistView.Columns[1]));
                RefreshMergedCell(view, GetMergedCell(viewInfo, e.FocusedRowHandle, gridHistView.Columns[1]));
            }
        }

        private void simpleButtonFilter_Click(object sender, EventArgs e)
        {
            FilterMode();
        }

        private void UcTestListView_Enter(object sender, EventArgs e)
        {
            ViewRefresh();

            gridHistView.Focus();

            FilterMode(true);

            GroupMode(false);
        }

        private void simpleButtonExportTestList_Click(object sender, EventArgs e)
        {
            if (SelectOpenType != eSelectType.TestListFile)
                return;

            ExportTestList();
        }

        private void simpleButtonViewVRFY_Click(object sender, EventArgs e)
        {
            if (SelectOpenType != eSelectType.TestListFile)
                return;

            ChangeViewType(eSetViewMode.None);
        }

        private void gridHistView_KeyPress(object sender, KeyPressEventArgs e)
        {
            byte ucGetChar = Convert.ToByte(e.KeyChar);
        
            switch(ucGetChar)
            {
                case 13:
                    if (gridHistView.SelectedRowsCount > 0)
                    {
                        int[] nRows = gridHistView.GetSelectedRows();

                        GridViewSelectedProc(nRows[0]);
                    }
                    break;
                case 27:
                    simpleButtonModify1.Focus();
                    break;
            }
        }

        private void gridHistView_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.ControlKey)
                bCtrlKeyOn = true;
        }

        private void gridHistView_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.ControlKey)
                bCtrlKeyOn = false;
        }

        private void toolTipController_GetActiveObjectInfo(object sender, DevExpress.Utils.ToolTipControllerGetActiveObjectInfoEventArgs e)
        {
            if (e.SelectedControl != ViewgridControl) return;

            if (SelectOpenType != eSelectType.TestListRelease) return;

            ToolTipControlInfo info = null;

            //Get the view at the current mouse position
            GridView view = ViewgridControl.GetViewAt(e.ControlMousePosition) as GridView;

            if (view == null) return;

            //Get the view's element information that resides at the current position
            GridHitInfo hi = view.CalcHitInfo(e.ControlMousePosition);

            //Display a hint for row indicator cells
            if (hi.HitTest == GridHitTest.RowCell)
            {
                if (hi.Column.FieldName == "P_ProdNo")
                {
                    string strNumber = string.Empty;

                    try
                    {
                        strNumber = view.GetRowCellValue(hi.RowHandle, "No").ToString();
                    }
                    catch
                    {
                        strNumber = string.Empty;
                    }

                    if (strNumber == string.Empty)
                        return;

                    string strMakeSQLText = $"SELECT X.No AS 'VariantNo', " +
                    $"X.ProdNo_P AS 'P_ProdNo', " +
                    $"I.TestType, " +
                    $"I.FileName, " +
                    $"I.Version AS 'FileVersion', " +
                    $"I.ProdCode, " +
                    $"Y.No AS 'GroupNo', " +
                    $"Y.GroupName, " +
                    $"Y.ModelName, " +
                    //$"Y.Comment AS 'Model-Comment', " +
                    $"X.Comment, " +
                    $"X.Description, " +
                    $"X.UseTLPosition AS 'Test-List Position', " +
                    $"K.LatestStepVersion AS 'Step Version' " +
                    $"FROM PROD_Variant AS X " +
                    //INNER LEFT
                    $"INNER JOIN [PROD_Group] AS Y WITH(NOLOCK) ON X.GroupNo = Y.No " +
                    $"INNER JOIN [PROD_Release] AS Z WITH(NOLOCK) ON Z.No = " + strNumber + " " +
                    $"INNER JOIN [STOR_TestListFile] AS I WITH(NOLOCK) ON X.TestListFileNo = I.No " +
                    $"INNER JOIN [HIST_TestListFileLatestStepVersion] AS K WITH(NOLOCK) ON K.TestListFileNo = X.TestListFileNo " +
                    $"WHERE X.No = Z.VariantNo;";

                    try
                    {
                        DataTable dtQuery = ctrlDB.GetTable(strMakeSQLText);

                        if (XCommons.isHasRow(dtQuery))
                        {
                            var SelectedValues = dtQuery.AsEnumerable().Select(x => x.ItemArray);

                            string[] strSplitValue = Array.ConvertAll(SelectedValues.ToArray()[0], x => x.ToString());

                            StringBuilder sbDataMake = new StringBuilder();

                            for (int i = 0; i < dtQuery.Columns.Count; i++)
                                sbDataMake.AppendLine(dtQuery.Columns[i].ColumnName + " : " + strSplitValue[i]);

                            //An object that uniquely identifies a row indicator cell
                            object o = hi.HitTest.ToString() + hi.RowHandle.ToString();
                            info = new ToolTipControlInfo(o, sbDataMake.ToString());
                        }
                    }
                    catch
                    {
                        ;//
                    }
                }
            }
            /*else
            {
                GridHitTest dd = hi.HitTest;

                object o = hi.HitTest.ToString() + hi.RowHandle.ToString();
                string text = dd.ToString();
                info = new ToolTipControlInfo(o, text);
            }*/

            //Supply tooltip information if applicable, otherwise preserve default tooltip (if any)
            if (info != null)
                e.Info = info;
        }

        private void simpleButtonQuery_Click(object sender, EventArgs e)
        {
            if (MainViewModeCheckErr()) return;

            string strGetQueryText = string.Empty;

            if (SelectOpenType == eSelectType.TestListFile)
            {
                strGetQueryText = $"SELECT X.No, " +
                $"X.Name, " +
                $"X.TestType, " +
                $"X.FileName, " +
                $"X.Version AS 'FileVersion', " +
                $"X.ProdCode, " +
                $"X.RegDT, " +
                $"X.RegUser, " +
                $"X.UpdateDT, " +
                $"X.UpdateUser, " +
                $"X.Comment, " +
                $"X.Description, " +
                $"Z.LatestStepVersion AS 'Step Version' " +
                $"FROM [{strSelectTable.ToString()}] AS X WITH(NOLOCK) " +
                $"LEFT JOIN [HIST_TestListFileLatestStepVersion] AS Z WITH(NOLOCK) ON Z.TestListFileNo = X.No ";

                int nWhereCnt = 0;
                string[] strGetAddText = new string[5];
                strGetAddText[0] = textEditQueryText1.Text;
                strGetAddText[1] = textEditQueryText2.Text;
                strGetAddText[2] = textEditQueryText3.Text;
                strGetAddText[3] = textEditQueryText4.Text;
                strGetAddText[4] = textEditQueryText5.Text;

                string[] strItemName = new string[5];
                strItemName[0] = "X.Name";
                strItemName[1] = "X.TestType";
                strItemName[2] = "X.Version";
                strItemName[3] = "X.ProdCode";
                strItemName[4] = "X.FileName";

                for (int i = 0; i < strGetAddText.Length; i++)
                {
                    if (strGetAddText[i].Length > 0)
                    {
                        if (nWhereCnt == 0)
                            strGetQueryText += "WHERE ";
                        else
                            strGetQueryText += "AND ";

                        if (strGetAddText[i].IndexOf("%") < 0)
                            strGetQueryText += strItemName[i] + " = '" + strGetAddText[i] + "' ";
                        else
                            strGetQueryText += strItemName[i] + " LIKE '" + strGetAddText[i] + "' ";

                        nWhereCnt++;
                    }
                }

                strGetQueryText += $"ORDER BY No ASC;";
            }
            else if (SelectOpenType == eSelectType.TestListVariant)
            {
                strGetQueryText = $"SELECT X.No, " +
                    $"X.ProdNo_P AS 'P_ProdNo', " +
                    $"I.TestType, " +
                    $"I.FileName, " +
                    $"I.Version AS 'FileVersion', " +
                    $"I.ProdCode, " +
                    $"I.No AS 'TestListFileNo', " +
                    $"I.Name AS 'TestListName', " +
                    $"X.RegDT, " +
                    $"X.RegUser, " +
                    $"X.UpdateDT, " +
                    $"X.UpdateUser, " +
                    $"Y.No AS 'GroupNo', " +
                    $"Y.GroupName, " +
                    $"Y.ModelName, " +
                    //$"Y.Comment AS 'Model-Comment', " +
                    $"X.Comment, " +
                    $"X.Description, " +
                    $"X.UseTLPosition AS 'Test-List Position', " +
                    $"Z.LatestStepVersion AS 'Step Version' " +
                    //$"X.TestListData " +
                    $"FROM {strSelectTable.ToString()} AS X WITH(NOLOCK) " +
                    $"LEFT JOIN [PROD_Group] AS Y WITH(NOLOCK) ON X.GroupNo = Y.No " +
                    $"LEFT JOIN [STOR_TestListFile] AS I WITH(NOLOCK) ON X.TestListFileNo = I.No " +
                    $"LEFT JOIN [HIST_TestListFileLatestStepVersion] AS Z WITH(NOLOCK) ON X.TestListFileNo = Z.TestListFileNo ";

                int nWhereCnt = 0;
                string[] strGetAddText = new string[4];
                strGetAddText[0] = textEditQueryText1.Text;
                strGetAddText[1] = textEditQueryText2.Text;
                strGetAddText[2] = textEditQueryText3.Text;
                strGetAddText[3] = textEditQueryText4.Text;

                string[] strItemName = new string[4];
                strItemName[0] = "X.ProdNo_P";
                strItemName[1] = "I.TestType";
                strItemName[2] = "I.Version";
                strItemName[3] = "I.ProdCode";

                for (int i = 0; i < strGetAddText.Length; i++)
                {
                    if (strGetAddText[i].Length > 0)
                    {
                        if (nWhereCnt == 0)
                            strGetQueryText += "WHERE ";
                        else
                            strGetQueryText += "AND ";

                        if (strGetAddText[i].IndexOf("%") < 0)
                            strGetQueryText += strItemName[i] + " = '" + strGetAddText[i] + "' ";
                        else
                            strGetQueryText += strItemName[i] + " LIKE '" + strGetAddText[i] + "' ";

                        nWhereCnt++;
                    }
                }

                strGetQueryText += $"ORDER BY No ASC;";
            }
            else if (SelectOpenType == eSelectType.TestListRelease)
            {
                strGetQueryText = $"SELECT X.No, " +
                    $"K.ModelName, " +
                    $"X.ProdNo_C AS 'C_ProdNo', " +
                    $"Y.No AS 'TestCodeNo', " +
                    $"Y.TestCode, " +
                    $"Z.No AS 'VariantNo', " +
                    $"Z.ProdNo_P AS 'P_ProdNo', " +
                    $"J.TestType, " +
                    $"J.Version AS 'FileVersion', " +
                    $"J.ProdCode, " +
                    $"X.Config, " +
                    $"X.RegDT, " +
                    $"X.RegUser, " +
                    $"X.RegUserComment " +
                    $"FROM {strSelectTable.ToString()} AS X WITH(NOLOCK) " +
                    $"LEFT JOIN [STAT_TestCode] AS Y WITH(NOLOCK) ON X.TestCodeNo = Y.No " +
                    $"LEFT JOIN [PROD_Variant] AS Z WITH(NOLOCK) ON X.VariantNo = Z.No " +
                    $"LEFT JOIN [PROD_Group] AS K WITH(NOLOCK) ON K.No = Z.GroupNo " +
                    $"LEFT JOIN [STOR_TestListFile] AS J WITH(NOLOCK) ON Z.TestListFileNo = J.No ";

                int nWhereCnt = 0;
                string[] strGetAddText = new string[6];
                strGetAddText[0] = textEditQueryText1.Text;
                strGetAddText[1] = textEditQueryText2.Text;
                strGetAddText[2] = textEditQueryText3.Text;
                strGetAddText[3] = textEditQueryText4.Text;
                strGetAddText[4] = textEditQueryText5.Text;
                strGetAddText[5] = textEditQueryText6.Text;

                string[] strItemName = new string[6];
                strItemName[0] = "X.ProdNo_C";
                strItemName[1] = "Y.TestCode";
                strItemName[2] = "J.TestType";
                strItemName[3] = "J.Version";
                strItemName[4] = "J.ProdCode";
                strItemName[5] = "Z.ProdNo_P";

                for (int i = 0; i < strGetAddText.Length; i++)
                {
                    if (strGetAddText[i].Length > 0)
                    {
                        if (nWhereCnt == 0)
                            strGetQueryText += "WHERE ";
                        else
                            strGetQueryText += "AND ";

                        if (strGetAddText[i].IndexOf("%") < 0)
                            strGetQueryText += strItemName[i] + " = '" + strGetAddText[i] + "' ";
                        else
                            strGetQueryText += strItemName[i] + " LIKE '" + strGetAddText[i] + "' ";

                        nWhereCnt++;
                    }
                }

                strGetQueryText += $"OR X.No IS NULL ORDER BY No ASC;";
            }
            else
                return;

            string[] strCheck = strGetQueryText.Split(' ');
            string strUpperText = string.Empty;

            foreach (string strItem in strCheck)
            {
                strUpperText = strItem.ToUpper();

                if (strUpperText.CompareTo("INSERT") == 0 ||
                strUpperText.CompareTo("UPDATE") == 0 ||
                strUpperText.CompareTo("DELETE") == 0)
                {
                    MessageBox.Show("SQL control syntax other than SELECT syntax is not supported.", strSelectTable, MessageBoxButtons.OK, MessageBoxIcon.Error);

                    return;
                }
            }

            if (strGetQueryText.IndexOf("TOP(", StringComparison.OrdinalIgnoreCase) < 0)
            {
                int n = strGetQueryText.IndexOf("SELECT", StringComparison.OrdinalIgnoreCase);
                strGetQueryText = strGetQueryText.Insert(n + 7, "TOP(10000) ");
            }

            DataTable dtResult = ctrlDB.GetTable(strGetQueryText);

            if (XCommons.isHasRow(dtResult))
                SetViewCustomTable(dtResult);
            else
                MessageBox.Show("No result set or incorrect syntax.", strSelectTable, MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        private void simpleButtonSelectTL_Click(object sender, EventArgs e)
        {
            if (MainViewModeCheckErr()) return;
            if (SelectedRowCheckErr()) return;

            int nCurrentUsePosition = Convert.ToInt32(gridHistView.GetFocusedRowCellValue("Test-List Position").ToString());
            int nMaxStepVersion = Convert.ToInt32(gridHistView.GetFocusedRowCellValue("Step Version").ToString());

            if (nMaxStepVersion == 0)
                return;

            string strNo = gridHistView.GetFocusedRowCellValue("No").ToString();
            string strProdNo = gridHistView.GetFocusedRowCellValue("P_ProdNo").ToString();
            string strTestType = gridHistView.GetFocusedRowCellValue("TestType").ToString();
            string strVersion = gridHistView.GetFocusedRowCellValue("FileVersion").ToString();
            string strProdCode = gridHistView.GetFocusedRowCellValue("ProdCode").ToString();

            int nDataLoadPosition = 0;
            int nSelectVersion = nMaxStepVersion;

            SelectTestListForm SelectTLForm = new SelectTestListForm(eSelectType.TestListVariant, ctrlDB, nMaxStepVersion);
            SelectTLForm.Location = Control.MousePosition;

            SelectTLForm.strNo = strNo;
            SelectTLForm.strProdNo = strProdNo;
            SelectTLForm.strTestType = strTestType;
            SelectTLForm.strVersion = strVersion;
            SelectTLForm.strProdCode = strProdCode;

            SelectTLForm.ShowDialog();

            if (SelectTLForm.DialogResult != DialogResult.OK)
                return;

            nSelectVersion = Convert.ToInt32(SelectTLForm.nSelectedVersion);
            nDataLoadPosition = nMaxStepVersion - nSelectVersion;

            int nBeforeVersion = nMaxStepVersion - nCurrentUsePosition;
            int nChangeVersion = nSelectVersion;

            if (nBeforeVersion == nChangeVersion)
                return;

            if (MessageBox.Show("[" + strNo + "/" + strProdNo + "/" + strTestType + "/" + strVersion + "/" + strProdCode + "] " +
                "Change Test-List Version. Before Version [" + nBeforeVersion + "] > [" + nChangeVersion + "] Do you want to change the version for the Test-List?", strSelectTable, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                SqlCommand cmd = new SqlCommand();

                string columns = string.Empty;

                columns = "UpdateDT,UpdateUser,UseTLPosition";

                DateTime dtUpdate = ctrlDB.GetServerDateTime(); 
                string strUpdateUser = ctrlDB.GetLoginInfo().UserID;

                StringBuilder sb = new StringBuilder();
                sb.Append($"UPDATE [PROD_Variant] SET ");

                string strGetDateTime = ctrlDB.SetConvertDateTime(dtUpdate.ToString());

                sb.Append("UpdateDT = '" + strGetDateTime + "', ");
                sb.Append("UpdateUser = '" + strUpdateUser + "', ");
                sb.Append("UseTLPosition = " + nDataLoadPosition + " ");
                sb.Append("WHERE No = " + strNo + ";");

                cmd = new SqlCommand(sb.ToString(), ctrlDB.GetConnSqlCmd().Connection);

                try
                {
                    int EffectRows = cmd.ExecuteNonQuery();

                    ViewRefresh();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Test-List Change Version [PROD_Variant] - Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private void simpleButtonSelVRFYVersion_Click(object sender, EventArgs e)
        {
            if (SubViewModeCheckErr()) return;

            int iSetTestListNo = TestListNoCheckErr();

            if (iSetTestListNo < 0)
                return;

            string strQueryText = $"SELECT A.Name, " +
            $"A.TestType, " +
            $"A.Version AS 'FileVersion', " +
            $"A.ProdCode, " +
            $"A.FileName, " +
            $"B.LatestStepVersion AS 'Step Version' FROM [STOR_TestListFile] AS A " +
            $"INNER JOIN [HIST_TestListFileLatestStepVersion] AS B ON B.TestListFileNo = A.No WHERE A.No = {iSetTestListNo};";

            DataTable dtQuery = ctrlDB.GetTable(strQueryText);

            if (XCommons.isHasRow(dtQuery) == false)
                return;

            //int nCurrentUsePosition = Convert.ToInt32(dtQuery.Rows[0]["Test-List Position"].ToString());
            int nMaxStepVersion = Convert.ToInt32(dtQuery.Rows[0]["Step Version"].ToString());

            if (nMaxStepVersion == 0)
                return;

            string strNo = iSetTestListNo.ToString();
            string strName = dtQuery.Rows[0]["Name"].ToString();
            string strTestType = dtQuery.Rows[0]["TestType"].ToString();
            string strVersion = dtQuery.Rows[0]["FileVersion"].ToString();
            string strProdCode = dtQuery.Rows[0]["ProdCode"].ToString();
            string strFileName = dtQuery.Rows[0]["FileName"].ToString();

            int nSelectVersion = nMaxStepVersion;

            SelectTestListForm SelectTLForm = new SelectTestListForm(eSelectType.TestListFile, ctrlDB, nMaxStepVersion, true);
            SelectTLForm.Location = Control.MousePosition;

            SelectTLForm.strNo = strNo;
            SelectTLForm.strName = strName;
            SelectTLForm.strTestType = strTestType;
            SelectTLForm.strVersion = strVersion;
            SelectTLForm.strProdCode = strProdCode;
            SelectTLForm.strFileName = strFileName;

            SelectTLForm.ShowDialog();

            if (SelectTLForm.DialogResult != DialogResult.OK)
                return;

            if (int.TryParse(SelectTLForm.nSelectedVersion, out nSelectVersion) == false)
                DoChangeSubView();
            else
            {
                strQueryText = $"SELECT * FROM(SELECT*, ROW_NUMBER() OVER(PARTITION BY StepID ORDER BY StepVersion DESC) AS RN " +
                    $"FROM VRFY_TestListFileRelease WITH(INDEX=[CSK_VRFY_Release_2]) " +
                    $"WHERE TestlistFileNo = {iSetTestListNo} " +
                    $"AND StepVersion <= {nSelectVersion}) X " +
                    $"WHERE RN = 1 ORDER BY X.StepID ASC;";

                dtQuery = ctrlDB.GetTable(strQueryText);

                if (XCommons.isHasRow(dtQuery))
                    ViewChange(dtQuery);
            }
        }

        private void contextMenuStrip_Opening(object sender, CancelEventArgs e)
        {
            if (LoginStateCheck() == false)
                e.Cancel = true;

            else if (SelectOpenType == eSelectType.TestListFile)
            {
                /*ToolStripMenuItemGoToTestListFile.Enabled = false;
                ToolStripMenuItemGoToVariant.Enabled = false;
                exportToolStripMenuItem.Enabled = true;
                allUpdateToolStripMenuItem.Enabled = false;*/

                ToolStripMenuItemGoToTestListFile.Visible = false;
                ToolStripMenuItemGoToVariant.Visible = false;
                exportToolStripMenuItem.Visible = true;
                allUpdateToolStripMenuItem.Visible = false;

                if (eNowViewMode == eSetViewMode.SubView)
                    e.Cancel = true;
            }
            else if (SelectOpenType == eSelectType.TestListVariant)
            {
                /*ToolStripMenuItemGoToTestListFile.Enabled = true;
                ToolStripMenuItemGoToVariant.Enabled = false;
                exportToolStripMenuItem.Enabled = false;
                allUpdateToolStripMenuItem.Enabled = false;*/

                ToolStripMenuItemGoToTestListFile.Visible = true;
                ToolStripMenuItemGoToVariant.Visible = false;
                exportToolStripMenuItem.Visible = false;
                allUpdateToolStripMenuItem.Visible = false;

                if (eNowViewMode == eSetViewMode.SubView)
                    e.Cancel = true;
            }
            else if (SelectOpenType == eSelectType.TestListRelease)
            {
                /*ToolStripMenuItemGoToTestListFile.Enabled = false;
                ToolStripMenuItemGoToVariant.Enabled = true;
                exportToolStripMenuItem.Enabled = false;
                allUpdateToolStripMenuItem.Enabled = false;*/

                ToolStripMenuItemGoToTestListFile.Visible = false;
                ToolStripMenuItemGoToVariant.Visible = true;
                exportToolStripMenuItem.Visible = false;
                allUpdateToolStripMenuItem.Visible = false;
            }
            else
            {
                ;//
            }

            if (AbsoluteIndexRow < 0 || AbsoluteUniqueNo.Length < 0)
                e.Cancel = true;

            if (CheckRowSelectInfo())
            {
                try
                {
                    string strNumber = gridHistView.GetFocusedRowCellValue("No").ToString();

                    if (AbsoluteUniqueNo != strNumber)
                        e.Cancel = true;

                    GridHitInfo hInfo = gridHistView.CalcHitInfo(ViewgridControl.PointToClient(Cursor.Position));

                    if (hInfo.RowInfo != null)
                        nPopupMenuHitRow = hInfo.RowInfo.RowHandle;
                    else
                        e.Cancel = true;
                }
                catch
                {
                    e.Cancel = true;
                }
            }
        }

        private void contextMenuStrip_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            if (MainViewModeCheckErr()) return;

            ToolStripItem tsp = e.ClickedItem;

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

            if (LoginStateCheck() == false)
                return;

            switch (nTag)
            {
                case 11:
                    GoToTestListFile();
                    break;
                case 0:
                    GoToVariant();
                    break;
                case 1:
                    CopyData();
                    break;
                case 2:
                    PasteData();
                    break;
                case 3:
                    NewItem();
                    break;
                case 4:
                    ModifyItem();
                    break;
                case 5:
                    if (LoginStateCheck() == false) return;
                    ViewgridControl.ShowPrintPreview();
                    break;
                case 6:
                    ExportTestList();
                    break;
                case 7:
                    DeleteItem();
                    break;
                case 8:
                    FilterMode();
                    break;
                case 9:
                    if (gridHistView.GroupCount > 0)
                        GroupMode(false);
                    else
                        GroupMode(true);
                    break;
                case 10: //Full Update
                    ;// SelectParentFullUpdate();
                    break;
            }
        }

        private void simpleButtonSelectParentFullUpdate_Click(object sender, EventArgs e)
        {
            ;// SelectParentFullUpdate();
        }

        private void timerUI_Tick(object sender, EventArgs e)
        {
            /*
            if(loadForm != null)
                stRefreshTimer.Restart();

            if (stRefreshTimer.ElapsedMilliseconds >= 60000)
            {
                if (eNowViewMode == eSetViewMode.MainView && ViewLoginState)
                {
                    stRefreshTimer.Restart();

                    ViewRefresh();
                }
            }
            */

            if (ViewgridControl.ClientRectangle.Contains(ViewgridControl.PointToClient(Control.MousePosition)))
            {
                GridHitInfo hInfo = gridHistView.CalcHitInfo(ViewgridControl.PointToClient(Cursor.Position));

                if (hInfo.RowInfo != null)
                {
                    if(contextMenuStrip.ClientRectangle.Contains(contextMenuStrip.PointToClient(Control.MousePosition)))
                        return;

                    if (nPopupMenuHitRow != hInfo.RowInfo.RowHandle)
                    {
                        if (contextMenuStrip.Visible)
                            contextMenuStrip.Close();
                    }
                }
            }
            else
            {
                if (contextMenuStrip.Visible)
                    contextMenuStrip.Close();
            }


        }

        private void GroupMode(bool bOnOff = false)
        {
            if (gridHistView.Columns.Count <= 0)
                return;

            int[] nGroupIdx = null;

            try
            {
                gridHistView.BeginUpdate();

                if (SelectOpenType == eSelectType.TestListFile)
                    nGroupIdx = null;
                else if (SelectOpenType == eSelectType.TestListVariant)
                    nGroupIdx = new int[1] { 3 };
                else if (SelectOpenType == eSelectType.TestListRelease)
                    nGroupIdx = new int[1] { 6 };

                if (nGroupIdx == null)
                    return;

                if (bOnOff)
                {
                    gridHistView.Columns[nGroupIdx[0]].Group();
                    gridHistView.ExpandAllGroups();
                }
                else
                    gridHistView.Columns[nGroupIdx[0]].UnGroup();
            }
            catch
            {
                ;//Table Null Data
            }
            finally
            {
                gridHistView.EndUpdate();
            }
        }

        private void simpleButtonGroup_Click(object sender, EventArgs e)
        {
            if (gridHistView.GroupCount > 0)
                GroupMode(false);
            else
                GroupMode(true);
        }
    }
}
