using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Linq;
using SystemX.Net;
using SystemX.Net.BaseProtocol;
using SystemX.Net.DB;

using CpTesterPlatform.CpLogUtil;

using static SystemX.Net.Platform.Common.Util.LogMessage;
using static SystemX.Net.DB.XDBConnManager;

namespace SystemX.Common.Log.LSU
{
    public class AnalysisLog_LSU : IDisposable
    {
        public bool STATE { set; get; }

        //DataBase
        private XDBConnManager MngDBConn;
        //QueryInfo
        public LogProcessInfo_LSU qiLogProcessInfo;
        //Log Scan Process Task 
        private Task taskScanProcess;

        private bool m_bTaskBlock;
        //
        private Stopwatch stProcessTime;

        private long lLastProcessTime;
        private long lLastItemTime;
        private long lLastProcessNum;

        private CancellationTokenSource cts;

        public int SET_LOG_PROC_POS { set; get; }
        public int SET_LOG_DELETE_MANAGE_POS { set; get; }

        public int SET_LOG_SCAN_SHIFT_TIME { set; get; }
        public int SET_LOG_MANAGE_SCAN_TIME { set; get; }
        //
        private string strLogDataFilePath { set; get; }
        private eLogDataType eGetLogDataType { set; get; }
        private eLogAccessType eGetAccessType { set; get; }
        private CpLogHeader getCpLogHeader;
        //
        public bool[] LOG_DATA_CHECK_STATE { set; get; }

        public int[] PROC_NO_LIST; 

        public long GET_LAST_PROCESS_TIME()
        {
            return lLastProcessTime;
        }
        public long GET_LAST_PROCESS_NUM()
        {
            return lLastProcessNum;
        }
        public long GET_LAST_ITEM_TIME()
        {
            return lLastItemTime;
        }

        ~AnalysisLog_LSU()
        {
            Dispose(false);
        }
        public AnalysisLog_LSU()
        {
            STATE = true;

            //Proc Position
            SET_LOG_PROC_POS = 0;
            SET_LOG_DELETE_MANAGE_POS = 0;

            //1초 마다 미 처리 로그 스캔
            SET_LOG_SCAN_SHIFT_TIME = 500;

            //24시간 마다 삭제 대상 데이터 스캔
            SET_LOG_MANAGE_SCAN_TIME = 86400000;

            //PROC NO LIST
            PROC_NO_LIST = new int[10];
            PROC_NO_LIST[0] = 180; //PL, CDA
            PROC_NO_LIST[1] = 190; //PH, PM
            PROC_NO_LIST[2] = 200; //LK,
            PROC_NO_LIST[3] = 210; //LT
            PROC_NO_LIST[4] = 220; //LTV, IR
            PROC_NO_LIST[5] = 230; //CA
            PROC_NO_LIST[6] = 240; //FT
            PROC_NO_LIST[7] = 250; //OSP
            PROC_NO_LIST[8] = 260; //PV, LVDT
            PROC_NO_LIST[9] = 270; //UL

            //Unused
            //PROC_NO_LIST[10] = 280; //GD 
            //PROC_NO_LIST[11] = 290; //P

            XLogDataControl_.SetLogFieldInfo();

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

            lLastProcessTime = 0;
            lLastItemTime = 0;

            lLastProcessNum = 0;

            MessageOutput.PrintLogLevel = LogMessageLevel.INFO;

            string strExcutePos = Environment.CurrentDirectory;
            string strDBInfoPos = strExcutePos + @"\Configure\DBConnInfo.xml";
            string strQueryInfoPos = strExcutePos + @"\Configure\LogProcessInfo.xml";

            qiLogProcessInfo = new LogProcessInfo_LSU(strQueryInfoPos);
            if (qiLogProcessInfo.Load())
            {
                LOG_DATA_CHECK_STATE = new bool[qiLogProcessInfo.GeManageInfo().Count()];
                for (int i = 0; i < qiLogProcessInfo.GeManageInfo().Count(); i++)
                    LOG_DATA_CHECK_STATE[i] = true;

                MngDBConn = new XDBConnManager();
                MngDBConn.ConfigPath = strDBInfoPos;

                if (MngDBConn.OpenConnection())
                {
                    /*
                    taskScanProcess = null;
                    m_bTaskBlock = false;

                    cts = new CancellationTokenSource();
                    taskScanProcess = new Task(new Action<object>(WatchResultTable), cts.Token);
                    taskScanProcess.Start();
                    */

                    MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @" Success to connect to DB. [SystemX.Common.Protocol.Log.LSU_Trimming_4Th : AnalysisLog_.AnalysisLog_]", ConsoleColor.White, LogMessageLevel.DEBUG);
                }
                else
                {
                    STATE = false;

                    MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @" Failed to connect to DB. [SystemX.Common.Protocol.Log.LSU_Trimming_4Th : AnalysisLog_.AnalysisLog_]", ConsoleColor.Yellow, LogMessageLevel.DEBUG);
                }
            }
            else
            {
                STATE = false;

                MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @" Read to configure failed. [SystemX.Common.Protocol.Log.LSU_Trimming_4Th : AnalysisLog_.AnalysisLog_]", ConsoleColor.Yellow, LogMessageLevel.DEBUG);
            }
        }
        public void Dispose()
        {
            Dispose(true);
        }
        protected virtual void Dispose(bool bDisposing)
        {
            if (bDisposing)
            {

            }

            if (taskScanProcess != null)
            {
                cts.Cancel();

                taskScanProcess.Wait();

                m_bTaskBlock = true;
            }

            // do releasing unmanaged resource (종결자가 없는 객체의 자원 해제)
            // i.e. close file handle of operating systems

            // suppress calling of Finalizer
            GC.SuppressFinalize(this);
        }
        private DataSet QueryProcess(string strGetQuery, ref bool bResult)//, out byte[] ucQueryByteArray)
        {
            bResult = false;

            SqlDataReader xSqlReader = null;

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

            int iFieldCnt = 0;
            int iRecordsAffectedCnt = 0;
            bool bHasRow = false;

            //ucQueryByteArray = null;

            try
            {
                try
                {
                    xSqlReader = MngDBConn.QueryDatabase(eConnCategory.Main, strGetQuery);

                    if (xSqlReader != null)
                    {
                        iFieldCnt = xSqlReader.FieldCount;
                        iRecordsAffectedCnt = xSqlReader.RecordsAffected;
                        bHasRow = xSqlReader.HasRows;

                        dt.Load(xSqlReader);
                        ds.Tables.Add(dt);
                    }
                }
                catch (Exception ex)
                {
                    xSqlReader = null;

                    MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"<" + strGetQuery + "> Query process fail![SystemX.Net.Platform.Log : AnalysisLog_.QueryProcess]\r\n" + ex.Message, ConsoleColor.Yellow, LogMessageLevel.DEBUG);
                }
            }
            finally
            {
                if (xSqlReader != null)
                    xSqlReader.Close();
            }

            if (iFieldCnt > 0 || iRecordsAffectedCnt > 0 || bHasRow == true)
                bResult = true;

            return ds;
        }
        private async void WatchResultTable(object objState)
        {
            CancellationToken token = (CancellationToken)objState;

            Stopwatch stLogScanTimer = new Stopwatch();
            stLogScanTimer.Start();
            Stopwatch stLogManageTimer = new Stopwatch();
            stLogManageTimer.Start();

            while (!m_bTaskBlock)
            {
                if (token.IsCancellationRequested)
                    break;

                try
                {
                    if (stLogScanTimer.ElapsedMilliseconds >= SET_LOG_SCAN_SHIFT_TIME)
                    {
                        int[] iGetLogNo = QueryStatusResultTable(PROC_NO_LIST[SET_LOG_PROC_POS], token);

                        if (iGetLogNo != null)
                        {
                            bool bResult = QueryInfoResultTable(PROC_NO_LIST[SET_LOG_PROC_POS], token, iGetLogNo);
                        }

                        SET_LOG_PROC_POS++;

                        if (PROC_NO_LIST.Length <= SET_LOG_PROC_POS)
                            SET_LOG_PROC_POS = 0;

                        stLogScanTimer.Restart();
                    }
                    if ((stLogManageTimer.ElapsedMilliseconds >= SET_LOG_MANAGE_SCAN_TIME))
                    {
                        //LOG_DATA_CHECK_STATE = false;

                        if (qiLogProcessInfo.USE_TABLE_DATA_DELETE_MANAGER)
                        {
                            foreach (KeyValuePair<int, Tuple<bool, string, int>> infoM in qiLogProcessInfo.GeManageInfo())
                            {
                                if (infoM.Value.Item1)
                                {
                                    int[] iGetDeleteNo = QueryManageDateTable(infoM.Value.Item2, infoM.Value.Item3.ToString(), token);

                                    if (iGetDeleteNo != null)
                                    {
                                        ManageTableDataDelete(iGetDeleteNo, infoM.Value.Item2, infoM.Value.Item3.ToString(), token);
                                    }

                                    iGetDeleteNo = QueryManageDateTable(infoM.Value.Item2, infoM.Value.Item3.ToString(), token);

                                    //if (iGetDeleteNo != null)
                                    //    LOG_DATA_CHECK_STATE = true;
                                }
                            }
                        }

                        stLogManageTimer.Restart();
                    }
                }
                catch (Exception ex)
                {
                    MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"General Queue Process failed.[SystemX.Common.Protocol.Log.LSU_Trimming_4Th : AnalysisLog_LSU.WatchResultTable]\r\n" + ex.Message, ConsoleColor.Yellow, LogMessageLevel.DEBUG);
                }

                await Task.Delay(1);
            }
        }
        public int[] QueryManageDateTable(string strTableName, string strDateDiff, CancellationToken token)
        {
            bool bGetQueryResult = false;

            int[] iQueryNoArr = null;

            DataSet ds = QueryProcess("SELECT TOP(100) * FROM [" + strTableName + "] WHERE No " +
            "IN(SELECT No FROM [" + strTableName + "] WHERE " +
            "CONVERT(VARCHAR(8), UpdateDT, 112) <= CONVERT(VARCHAR(8), GETDATE() - " + strDateDiff + ", 112)) ORDER BY No;", ref bGetQueryResult);

            bool hasRows = XCommons.isHasRow(ds);

            if (hasRows)
            {
                int iRowNum = ds.Tables[0].Rows.Count;

                iQueryNoArr = new int[iRowNum];
                Array.Clear(iQueryNoArr, 0, iQueryNoArr.Length);

                for (int i = 0; i < iRowNum; i++)
                {
                    if (token.IsCancellationRequested)
                        return null;

                    var getValue = ds.Tables[0].Rows[i]["No"];

                    iQueryNoArr[i] = int.Parse(getValue.ToString());
                }
            }

            stProcessTime.Restart();

            return iQueryNoArr;
        }
        public bool ManageTableDataDelete(int[] iGetNoArray, string strTableName, string strDateDiff, CancellationToken token)
        {
            bool bGetQueryResult = false;

            bool bFindItem = false;
            long lDataNum = 0;

            foreach (int iGetNo in iGetNoArray)
            {
                bFindItem = true;

                lDataNum = iGetNoArray.Count();

                if (token.IsCancellationRequested)
                    break;

                /*
                QueryProcess("DELETE [" + strTableName + "] WHERE " +
                "CONVERT(VARCHAR(8), UpdateDT, 112) <= CONVERT(VARCHAR(8), GETDATE() - " + strDateDiff + ", 112);", ref bGetQueryResult);
                */

                QueryProcess("DELETE [" + strTableName + "] WHERE No = " + iGetNo + ";", ref bGetQueryResult);
            }

            if (bFindItem)
            {
                lLastProcessTime = stProcessTime.ElapsedMilliseconds;
                lLastProcessNum = lDataNum;
            }

            return true;
        }
        public int[] QueryStatusResultTable(int iProcNum, CancellationToken token)
        {
            bool bGetQueryResult = false;

            int[] iQueryNoArr = null;

            DataSet ds = QueryProcess("SELECT TOP (50) A.No, A.Status FROM HIST_TestResultData_" + iProcNum.ToString() + " AS A WHERE A.Status = 0 OR A.Status = 10 OR A.Status = 20 OR A.Status = 30 ORDER BY No DESC;", ref bGetQueryResult);

            bool hasRows = XCommons.isHasRow(ds);

            if (hasRows)
            {
                int iRowNum = ds.Tables[0].Rows.Count;

                iQueryNoArr = new int[iRowNum];
                Array.Clear(iQueryNoArr, 0, iQueryNoArr.Length);

                for (int i = 0; i < iRowNum; i++)
                {
                    if (token.IsCancellationRequested)
                        return null;

                    var getValue = ds.Tables[0].Rows[i]["No"];

                    iQueryNoArr[i] = int.Parse(getValue.ToString());
                }
            }

            stProcessTime.Restart();

            return iQueryNoArr;
        }
        private bool SetLogData(int iProcNum, int iGetNo)
        {
            bool bGetQueryResult = false;

            DataSet dsLogData = null;
            DataSet dsModeData = null;
            DataSet dsPalletData = null;

            strLogDataFilePath = "";

            eGetLogDataType = eLogDataType.None;

            try
            {
                dsLogData = QueryProcess("SELECT A.No, A.LogAccessKey, A.ProcNo, A.PalletNumber, A.PalletID, A.PIndex, A.ProdNo, A.ProdID, A.TestID, A.LogDataPath, A.Status, A.UpdateDT " +
                "FROM HIST_TestResultData_" + iProcNum.ToString() + " AS A WHERE A.No =" + iGetNo.ToString() + ";", ref bGetQueryResult);

                bool hasRows = XCommons.isHasRow(dsLogData);

                if (hasRows)
                {
                    var Data = dsLogData.Tables[0].Rows[0]["LogDataPath"].ToString().Trim();
                    strLogDataFilePath = Data;

                    var vStatus = dsLogData.Tables[0].Rows[0]["Status"];

                    if ((short)eLogDataType.Normal == (Convert.ToInt16(vStatus) / 10))
                        eGetLogDataType = eLogDataType.Normal;
                    else if ((short)eLogDataType.CSV_Type0 == (Convert.ToInt16(vStatus) / 10))
                        eGetLogDataType = eLogDataType.CSV_Type0;
                    else if ((short)eLogDataType.CSV_Type1 == (Convert.ToInt16(vStatus) / 10))
                        eGetLogDataType = eLogDataType.CSV_Type1;
                    else if ((short)eLogDataType.CSV_Type2 == (Convert.ToInt16(vStatus) / 10))
                        eGetLogDataType = eLogDataType.CSV_Type2;
                    else
                    {
                        MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"General log processing [Log type select] failed.[SystemX.Common.Protocol.Log.LSU_Trimming_4Th : AnalysisLog_.SetLogData]", ConsoleColor.Yellow, LogMessageLevel.DEBUG);

                        throw new Exception();
                    }

                    var vLogAccessKey = dsLogData.Tables[0].Rows[0]["LogAccessKey"].ToString().Trim();
                    var vProcNo = dsLogData.Tables[0].Rows[0]["ProcNo"].ToString().Trim();

                    var vPalletNum = dsLogData.Tables[0].Rows[0]["PalletNumber"].ToString().Trim();
                    var vPalletID = dsLogData.Tables[0].Rows[0]["PalletID"].ToString().Trim();
                    var vPIndex = dsLogData.Tables[0].Rows[0]["PIndex"].ToString().Trim();
                    var vProdNo = dsLogData.Tables[0].Rows[0]["ProdNo"].ToString().Trim();
                    var vProdID = dsLogData.Tables[0].Rows[0]["ProdID"].ToString().Trim();

                    var vTestID = dsLogData.Tables[0].Rows[0]["TestID"].ToString().Trim();

                    dsModeData = QueryProcess("SELECT ModeID FROM CONST_WorkMode WHERE PalletNumber = '" + vPalletNum + "';", ref bGetQueryResult);
                    dsPalletData = QueryProcess("SELECT * FROM STAT_ProdLoad A WHERE A.PalletNumber = '" + vPalletNum + "' ORDER BY A.No;", ref bGetQueryResult);

                    if (XCommons.isHasRow(dsModeData) == false ||
                       XCommons.isHasRow(dsPalletData) == false)
                    {
                        MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"General log processing [Query mode/pallet information (1)] failed.[SystemX.Common.Protocol.Log.LSU_Trimming_4Th : AnalysisLog_.SetLogData]", ConsoleColor.Yellow, LogMessageLevel.DEBUG);

                        throw new Exception();
                    }
                    var vpModeID = dsModeData.Tables[0].Rows[0]["ModeID"].ToString().Trim();

                    if (eGetLogDataType == eLogDataType.Normal)
                    {
                        CpLogStoreData.vLSaveTableName = qiLogProcessInfo.GetSaveTableName(vTestID.ToString());
                        CpLogStoreData.vLSaveDetailTable = qiLogProcessInfo.GetSaveDetailTable(vTestID.ToString());
                        CpLogStoreData.ExtrctInfo = qiLogProcessInfo.GetExtractInfo(vTestID.ToString());

                        foreach (DataRow dr in dsPalletData.Tables[0].Rows)
                        {
                            int iIndex = dsPalletData.Tables[0].Rows.IndexOf(dr);

                            int iLogIndex = XLogDataControl_.ConvertTextToTryValue<int>(vPIndex.ToString(), -1);
                            if (iLogIndex == -1)
                            {
                                MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"General log processing [Query mode/pallet information (2)] failed.[SystemX.Common.Protocol.Log.LSU_Trimming_4Th : AnalysisLog_.SetLogData]", ConsoleColor.Yellow, LogMessageLevel.DEBUG);

                                throw new Exception();
                            }
                            else
                            {
                                iLogIndex -= 1;

                                CpLogStoreData.vLLogAccessKey = vLogAccessKey;
                                CpLogStoreData.vLProcNo = vProcNo;
                                CpLogStoreData.vLPalletNumber = dsPalletData.Tables[0].Rows[iLogIndex]["PalletNumber"].ToString().Trim();
                                CpLogStoreData.vLPalletID = dsPalletData.Tables[0].Rows[iLogIndex]["PalletID"].ToString().Trim();
                                CpLogStoreData.vLPIndex = dsPalletData.Tables[0].Rows[iLogIndex]["PIndex"].ToString().Trim();
                                CpLogStoreData.vLProdNo = dsPalletData.Tables[0].Rows[iLogIndex]["ProdNo"].ToString().Trim();
                                CpLogStoreData.vLProdID = dsPalletData.Tables[0].Rows[iLogIndex]["ProdID"].ToString().Trim();
                                CpLogStoreData.vLSensorType = dsPalletData.Tables[0].Rows[iLogIndex]["SensorType"].ToString().Trim();

                                CpLogStoreData.vLStatus = "-";
                                CpLogStoreData.vLTestID = vTestID;
                                CpLogStoreData.vLResult = "-";
                                CpLogStoreData.vLTestDuration = "-";

                                break;
                            }
                        }
                    }
                    else
                    {
                        CustomLogStoreData.vLSaveTableName = qiLogProcessInfo.GetSaveTableName(vTestID.ToString());
                        CustomLogStoreData.vLSaveDetailTable = qiLogProcessInfo.GetSaveDetailTable(vTestID.ToString());
                        CustomLogStoreData.ExtrctInfo = qiLogProcessInfo.GetExtractInfo(vTestID.ToString());

                        foreach (DataRow dr in dsPalletData.Tables[0].Rows)
                        {
                            int iIndex = dsPalletData.Tables[0].Rows.IndexOf(dr);
                            CustomLogStoreData.vLLogAccessKey[iIndex] = vLogAccessKey;
                            CustomLogStoreData.vLProcNo[iIndex] = vProcNo;
                            CustomLogStoreData.vLPalletNumber[iIndex] = vPalletNum;

                            //CustomLogStoreData.vLPalletNumber[iIndex] = dsPalletData.Tables[0].Rows[0]["PalletNumber"].ToString().Trim();
                            CustomLogStoreData.vLPalletID[iIndex] = dsPalletData.Tables[0].Rows[iIndex]["PalletID"].ToString().Trim();
                            CustomLogStoreData.vLPIndex[iIndex] = dsPalletData.Tables[0].Rows[iIndex]["PIndex"].ToString().Trim();
                            CustomLogStoreData.vLProdNo[iIndex] = dsPalletData.Tables[0].Rows[iIndex]["ProdNo"].ToString().Trim();
                            CustomLogStoreData.vLProdID[iIndex] = dsPalletData.Tables[0].Rows[iIndex]["ProdID"].ToString().Trim();
                            CustomLogStoreData.vLSensorType[iIndex] = dsPalletData.Tables[0].Rows[iIndex]["SensorType"].ToString().Trim();

                            CustomLogStoreData.SelectProdNo = CustomLogStoreData.vLProdNo[iIndex];

                            if (vpModeID.ToString() == "1")
                                CustomLogStoreData.vLStatus[iIndex] = "NORMAL";
                            else if (vpModeID.ToString() == "2")
                                CustomLogStoreData.vLStatus[iIndex] = "REWORK";
                            else if (vpModeID.ToString() == "3")
                                CustomLogStoreData.vLStatus[iIndex] = "RETEST";
                            else
                                CustomLogStoreData.vLStatus[iIndex] = "-";

                            CustomLogStoreData.vLTestID[iIndex] = vTestID;
                            CustomLogStoreData.vLResult[iIndex] = "-";

                            CustomLogStoreData.vLVal_Min[iIndex] = "-";
                            CustomLogStoreData.vLVal_Max[iIndex] = "-";
                            CustomLogStoreData.vLVal_Meas[iIndex] = "-";
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                bGetQueryResult = false;

                MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"General shift log data failed.[SystemX.Common.Protocol.Log.LSU_Trimming_4Th : AnalysisLog_.SetLogData]\r\n" + ex.Message, ConsoleColor.Yellow, LogMessageLevel.DEBUG);
            }

            return bGetQueryResult;
        }
        private bool FileAccessCheck()
        {
            bool bAccessCheck = true;

            //File Access Check
            FileStream fs = null;
            try
            {
                fs = new FileStream(@strLogDataFilePath, FileMode.Open, FileAccess.ReadWrite, FileShare.None);
            }
            catch (Exception ex)
            {
                //File Access fail next file
                MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"File access check fail. [" + @strLogDataFilePath + "] [SystemX.Common.Protocol.Log.LSU_Trimming_4Th : AnalysisLog_.FileAccessCheck]\r\n" + ex.Message, ConsoleColor.Yellow, LogMessageLevel.DEBUG);

                bAccessCheck = false;
            }
            finally
            {
                //FIle Access ok
                if (fs != null)
                    fs.Close();
            }

            return bAccessCheck;
        }
        private bool GetNoramlDataAccessResult(string strLogDataPath, ref DataSet dsGetSet)
        {
            bool bStatusCheck = true;

            dsGetSet = null;

            try
            {
                //CpLogCompUtil
                //CpLogCompUtil.CopyToMemory()
                DataTable dt = CpLogFileIO.GetLogData(@strLogDataPath, out getCpLogHeader);

                DataSet dsLog = new DataSet();
                dsLog.Tables.Add(dt);

                dsGetSet = dsLog.Copy();

                bStatusCheck = XCommons.isHasRow(dsLog);

                if (bStatusCheck)
                {
                    //추출 정보 존재시
                    if (CpLogStoreData.ExtrctInfo.Count > 0)
                    {
                        CpLogStoreData.SetMeasLength(CpLogStoreData.ExtrctInfo.Count);

                        foreach (KeyValuePair<int, Tuple<string, bool, string, int, string, string, string>> k in CpLogStoreData.ExtrctInfo)
                        {
                            DataRow[] dr = null;

                            if (k.Value.Item2)
                            {
                                foreach (DataRow getDr in dsLog.Tables[0].Rows)
                                {
                                    string strGetMO = getDr.ItemArray[2].ToString().Trim();

                                    if (strGetMO.IndexOf(k.Value.Item3.ToString()) >= 0)
                                    {
                                        dr = new DataRow[1];
                                        dr[0] = getDr;

                                        break;
                                    }
                                }
                                //dsLog.Tables[0].Select("Mo = '" + k.Value.Item3.ToString() + "'");
                            }
                            else
                                dsLog.Tables[0].Select("Step = " + k.Value.Item4.ToString());

                            int iGetCnt = (dr != null) ? dr.Count() : 0;
                            if (iGetCnt > 0)
                            {
                                string strSetValue = XLogDataControl_.ConvertTextToTryValue<double>(dr[0].ItemArray[5].ToString(), 0).ToString();
                                CpLogStoreData.SetMeasValue(k.Key, strSetValue);
                            }
                            else
                                CpLogStoreData.SetMeasValue(k.Key, "0");
                        }
                    }

                    CpLogStoreData.SetCpLogHeaderData(getCpLogHeader);
                }
            }
            catch (Exception ex)
            {
                MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"CpLog file access get header failed. [" + @strLogDataPath + "] [SystemX.Common.Protocol.Log.LSU_Trimming_4Th : AnalysisLog_.GetNoramlDataAccessResult]\r\n" + ex.Message, ConsoleColor.Yellow, LogMessageLevel.DEBUG);

                bStatusCheck = false;
            }

            return bStatusCheck;
        }
        private bool GetCustomDataSubProcess(string strDataPath)
        {
            bool bStatusCheck = true;

            DataSet dsLogData = null;

            try
            {
                if (XLogDataControl_.ReadFileData(eGetLogDataType, @strDataPath))
                {
                    if (eGetLogDataType == eLogDataType.CSV_Type0)
                    {
                        dsLogData = QueryProcess("SELECT " +
                            "PrsFail_LSpec AS Val_Min, " +
                            "PrsFail_USpec AS Val_Max " +
                            "FROM PROD_ModelChar_LK " +
                            "WHERE " +
                            "PrtProdNo = " +
                            "(SELECT PrtProdNo FROM PROD_ModelChild WHERE ProdNo = '" +
                            CustomLogStoreData.SelectProdNo + "');", ref bStatusCheck);

                        for (int i = 0; i < CustomLogStoreData.vLVal_Min.Length; i++)
                            CustomLogStoreData.vLVal_Min[i] = dsLogData.Tables[0].Rows[0]["Val_Min"].ToString().Trim();
                        for (int i = 0; i < CustomLogStoreData.vLVal_Min.Length; i++)
                            CustomLogStoreData.vLVal_Max[i] = dsLogData.Tables[0].Rows[0]["Val_Max"].ToString().Trim();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"Custom file sub process failed. [" + @strDataPath + "] [SystemX.Common.Protocol.Log.LSU_Trimming_4Th : AnalysisLog_.GetCustomDataSubProcess]\r\n" + ex.Message, ConsoleColor.Yellow, LogMessageLevel.DEBUG);

                bStatusCheck = false;
            }

            return bStatusCheck;
        }
        private SqlCommand[] GetCommandList(int iProcNum, int iGetNo, eLogDataType eCurLogType, eLogAccessType eCurAccessType, ref SqlCommand[] getSubCmd)
        {
            bool bGetQueryResult = true;
            bool hasData = false;

            SqlCommand[] getCmd;
            getSubCmd = null;

            DataSet dsLogData = null;
            DataSet dsCpLogRawData = null;

            string strTempFileName = @"D:\TempCreateFolder\";

            try
            {
                if (eCurAccessType == eLogAccessType.FileData)
                {
                    if (FileAccessCheck())
                    {
                        //CP
                        if (eGetLogDataType == eLogDataType.Normal)
                            hasData = GetNoramlDataAccessResult(strLogDataFilePath, ref dsCpLogRawData);
                        //CSV
                        else
                            hasData = GetCustomDataSubProcess(strLogDataFilePath);
                    }
                }
                else if (eCurAccessType == eLogAccessType.VarBinaryData)
                {
                    dsLogData = QueryProcess("SELECT A.No, A.LogAccessKey, A.ProcNo, A.PalletNumber, A.PalletID, A.PIndex, A.ProdNo, A.ProdID, A.TestID, A.LogData, A.Status, A.UpdateDT " +
                    "FROM HIST_TestResultData_" + iProcNum.ToString() + " AS A WHERE A.No =" + iGetNo.ToString() + ";", ref bGetQueryResult);

                    var Data = dsLogData.Tables[0].Rows[0]["LogData"];
                    /*
                    N: cd26ccf675d64521884f1693c62ed303
                    D: cd26ccf6-75d6-4521-884f-1693c62ed303
                    B: {cd26ccf6-75d6-4521-884f-1693c62ed303}
                    P: (cd26ccf6-75d6-4521-884f-1693c62ed303)
                    X: {0xcd26ccf6,0x75d6,0x4521,{0x88,0x4f,0x16,0x93,0xc6,0x2e,0xd3,0x03}}
                    */
                    Guid uguid = Guid.NewGuid();

                    strTempFileName = @"D:\TempCreateFolder\";

                    if (Directory.Exists(strTempFileName) == false)
                        Directory.CreateDirectory(strTempFileName);

                    strTempFileName += uguid.ToString("B") + ".CpLog";

                    File.WriteAllBytes(strTempFileName, (byte[])Data);

                    //CP
                    if (eGetLogDataType == eLogDataType.Normal)
                        hasData = GetNoramlDataAccessResult(strTempFileName, ref dsCpLogRawData);
                    //CSV
                    else
                        hasData = GetCustomDataSubProcess(strTempFileName);
                }
                else
                {
                    MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"General log processing [Unknown access data] failed.[SystemX.Common.Protocol.Log.LSU_Trimming_4Th : AnalysisLog_.GetCommandList]", ConsoleColor.Yellow, LogMessageLevel.DEBUG);

                    throw new Exception();
                }
                //
                if (hasData)
                {
                    getCmd = XLogDataControl_.HISTTableProcess(eGetLogDataType);

                    if (eGetLogDataType == eLogDataType.Normal)
                    {
                        //디테일 테이블 저장
                        if (CpLogStoreData.vLSaveDetailTable)
                        {
                            //STEP,POSITION,MO,FNC_NAME,MIN_VALUE,MEASURE_VALUE,MAX_VALUE,DIM,CHECK_RETURN,SPENT_TIME,INFO
                            string columns = "STEP,POSITION,MO,FNC_NAME,MIN_VALUE,MEASURE_VALUE,MAX_VALUE,DIM,CHECK_RETURN,SPENT_TIME,INFO";
                            //columns = string.Join(",", dsCpLogRawData.Tables[0].Columns.Cast<DataColumn>().Select(c => c.ColumnName));

                            string values = string.Join(",", columns.Split(',').Select(c => string.Format("@{0}", c)));
                            //values = string.Join(",", dsCpLogRawData.Tables[0].Columns.Cast<DataColumn>().Select(c => string.Format("@{0}", c.ColumnName)));
                            
                            String sqlCommandInsert = string.Format("INSERT INTO HIST_TestResultDatail_" + iProcNum.ToString() + " (LogAccessKey, {0}) VALUES (@LogAccessKey, {1})", columns, values);

                            getSubCmd = new SqlCommand[dsCpLogRawData.Tables[0].Rows.Count];
                            foreach (DataRow row in dsCpLogRawData.Tables[0].Rows)
                            {
                                int irIndex = dsCpLogRawData.Tables[0].Rows.IndexOf(row);
                                getSubCmd[irIndex] = new SqlCommand(sqlCommandInsert);

                                getSubCmd[irIndex].Parameters.Clear();

                                getSubCmd[irIndex].Parameters.AddWithValue("@LogAccessKey", CpLogStoreData.vLLogAccessKey);
                                foreach (DataColumn col in dsCpLogRawData.Tables[0].Columns)
                                {
                                    int icIndex = dsCpLogRawData.Tables[0].Columns.IndexOf(col);

                                    string strSetValue = row[col].ToString().Trim();
                                    getSubCmd[irIndex].Parameters.AddWithValue("@" + columns.Split(',')[icIndex], strSetValue);
                                }
                            }
                        }
                    }
                }
                else
                {
                    MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"General log processing [" + eCurAccessType.ToString() + " : file no has data] failed.[SystemX.Common.Protocol.Log.LSU_Trimming_4Th : AnalysisLog_.GetCommandList]", ConsoleColor.Yellow, LogMessageLevel.DEBUG);

                    throw new Exception();
                }
            }
            catch (Exception ex)
            {
                MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"General log processing [" + eGetLogDataType.ToString() + "] [" + eCurAccessType.ToString() + "] failed.[SystemX.Common.Protocol.Log.LSU_Trimming_4Th : AnalysisLog_.GetCommandList]\r\n" + ex.Message, ConsoleColor.Yellow, LogMessageLevel.DEBUG);

                getCmd = null;

                int iSetStatus = GetStatusCode(false);

                QueryProcess("UPDATE HIST_TestResultData_" + iProcNum.ToString() + " SET Status = " + iSetStatus + ", UpdateDT = GETDATE() WHERE No = " + iGetNo.ToString() + ";", ref bGetQueryResult);
            }
            finally
            {
                if (File.Exists(strTempFileName))
                    File.Delete(strTempFileName);
            }

            return getCmd;
        }
        public bool QueryInfoResultTable(int iProcNum, CancellationToken token, int[] iGetNoArray)
        {
            bool bGetQueryResult = false;
            bool bFindItem = false;

            long lDataNum = 0;

            foreach (int iGetNo in iGetNoArray)
            {
                if (token.IsCancellationRequested)
                    break;

                lDataNum = iGetNoArray.Count();
                bFindItem = true;

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

                if (SetLogData(iProcNum, iGetNo) == false)
                {
                    MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"No : " + iGetNo.ToString() + " General log processing [Log data base information] failed. [SystemX.Common.Protocol.Log.LSU_Trimming_4Th : AnalysisLog_.QueryInfoResultTable]", ConsoleColor.Yellow, LogMessageLevel.DEBUG);

                    continue;
                }
                else
                {
                    ;//
                }
                if (File.Exists(strLogDataFilePath))
                    eGetAccessType = eLogAccessType.FileData;
                else
                    eGetAccessType = eLogAccessType.VarBinaryData;

                //Detatil Command List
                SqlCommand[] getSubCmd = null;

                //HIST Command and Extractinfo - Update table Command
                SqlCommand[] getCmd = GetCommandList(iProcNum, iGetNo, eGetLogDataType, eGetAccessType, ref getSubCmd);

                //Command Process        
                bool bCommandProcessResult = true;

                int iSetStatus = GetStatusCode(true);
                int iSetFailStatus = GetStatusCode(false);

                if (getCmd == null)
                {
                    bCommandProcessResult = false;

                    goto FAILED_PROCESS;
                }

                foreach (SqlCommand sc in getCmd)
                {
                    if (sc == null)
                        continue;

                    if (MngDBConn.CurrentConnection(eConnCategory.Main).ExecuteNonQuery(sc) == false)
                        bCommandProcessResult = false;
                }

                if (getSubCmd != null)
                {
                    foreach (SqlCommand sc in getSubCmd)
                    {
                        if (sc == null)
                            continue;

                        if (MngDBConn.CurrentConnection(eConnCategory.Main).ExecuteNonQuery(sc) == false)
                            bCommandProcessResult = false;
                    }
                }

                FAILED_PROCESS:

                if(bCommandProcessResult)
                    QueryProcess("UPDATE HIST_TestResultData_" + iProcNum.ToString() + " SET Status = " + iSetStatus + ", UpdateDT = GETDATE() WHERE No = " + iGetNo.ToString() + ";", ref bGetQueryResult);
                else
                    QueryProcess("UPDATE HIST_TestResultData_" + iProcNum.ToString() + " SET Status = " + iSetFailStatus + ", UpdateDT = GETDATE() WHERE No = " + iGetNo.ToString() + ";", ref bGetQueryResult);

                lLastItemTime = stMeasTime.ElapsedMilliseconds;
            }

            if (bFindItem)
            {
                lLastProcessTime = stProcessTime.ElapsedMilliseconds;
                lLastProcessNum = lDataNum;
            }

            return bGetQueryResult;
        }
        private int GetStatusCode(bool bResult)
        {
            int iSetStatus = 0;

            if (eGetLogDataType == eLogDataType.Normal)
                iSetStatus = 0;
            else if (eGetLogDataType == eLogDataType.CSV_Type0)
                iSetStatus = 10;
            else if (eGetLogDataType == eLogDataType.CSV_Type1)
                iSetStatus = 20;
            else if (eGetLogDataType == eLogDataType.CSV_Type2)
                iSetStatus = 30;
            else
                iSetStatus = 100;

            if (bResult)
                iSetStatus += 1;
            else
                iSetStatus += 2;

            return iSetStatus;
        }
        
    }
}
