using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SystemX.Product.ALIS.Interface;
using SystemX.Product.CP.TRA;
using SystemX.Product.TRA.UIControl;

using static SystemX.Product.TRA.DataManager.DMOverview;
using static SystemX.Product.CP.TRA.Commons;

namespace SystemX.Product.TRA.DataManager
{
    public class DMTestNgHistory
    {
        public enum eColList
        {
            No,
            TestDateTime,
            StationName,
            Host,
            Section,
            ProductID,
            ProductNo,
            TestType,
            TestCode,
            ParentNo,
            FileVersion,
            FileCode,
            StepVersion,
            Duration,
            TestResult,
            //OK,
            //NOK,
            TestListFileNo,
            TestListVariantNo,
            //TestID,
            LogNo,
            LogCount,
            AccessStart,
            AccessEnd,
            TestlistFileName,
            TestlistReqID
        }

        private SqlConnection DBConn { get; set; }
        private SqlConnection ShortTermDBConn { get; set; }
        private SqlConnection LongTermDBConn { get; set; }

        private SqlCommand SQLCmd { get; set; }


        public DMTestNgHistory(eSelectDataView SelectView, IDataBaseController getDBController)
        {
            DBConn = getDBController.GetMainConn();

            if (SelectView == eSelectDataView.DataDocumentViewC1)
            {
                ShortTermDBConn = getDBController.GetShortTermConn1();

                LongTermDBConn = getDBController.GetLongTermConn1();
            }
            else if (SelectView == eSelectDataView.DataDocumentViewC2)
            {
                ShortTermDBConn = getDBController.GetShortTermConn2();

                LongTermDBConn = getDBController.GetLongTermConn2();
            }
        }

        public DataTable SearchTestNgHistory(SelectedDataCollection data, TestHistorySearchOption option, int nReqIdPos = int.MaxValue)
        {
            DataTable dtResult = GetRawResult(data, option, nReqIdPos);
            
            return dtResult;
        }

        public int[] CheckTestListFileNo(string strProductNo, string strTestCode, string strTestType, string strFileVer, string strFileCode)
        {
            DataTable dtResult = new DataTable();
            StringBuilder strQuery = new StringBuilder();
            //string strQuery = string.Empty;

            strQuery.Append($"SELECT A.ProdNo_C, B.ProdNo_P, B.UpdateDT, D.TestCode, D.Gate1, D.Gate2, E.FileName, A.RegUserComment, B.Description, C.GroupName, C.ModelName, A.VariantNo AS 'TestListNo', A.Config, E.TestType, E.Version, E.ProdCode, B.UseTLPosition, B.TestListFileNo, E.UpdateDT AS 'TestListFileUpdateDT', A.VariantNo FROM [PROD_Release] AS A WITH(NOLOCK) " +
               $"INNER JOIN(SELECT * FROM [PROD_Variant] WITH(NOLOCK)) AS B ON A.VariantNo = B.No " +
               $"INNER JOIN(SELECT * FROM [PROD_Group] WITH(NOLOCK)) AS C ON B.GroupNo = C.No " +
               $"INNER JOIN(SELECT * FROM [STAT_TestCode] WITH(NOLOCK)) AS D ON A.TestCodeNo = D.No " +
               $"INNER JOIN(SELECT * FROM [STOR_TestListFile] WITH(NOLOCK)) AS E ON B.TestListFileNo = E.No " +
               $"WHERE A.ProdNo_C = '{strProductNo}' AND D.TestCode = '{strTestCode}' AND E.TestType = '{strTestType}' AND E.Version = '{strFileVer}' AND E.ProdCode = '{strFileCode}';");

            SQLCmd = new SqlCommand(strQuery.ToString(), DBConn);
            SQLCmd.CommandTimeout = DMCommon.nDefaultScanTime;

            DbDataReader dtCompReader = SQLCmd.ExecuteReader();
            DataTable dtCompResult = new DataTable();

            dtCompResult.Load(dtCompReader);

            if (Commons.isHasRow(dtCompResult) == false)
                return new int[] { int.MinValue, int.MinValue };

            string strCompVariNo = dtCompResult.Rows[0]["VariantNo"].ToString();
            string strCompFileNo = dtCompResult.Rows[0]["TestListFileNo"].ToString();

            dtCompReader.Close();

            return new int[] { int.Parse(strCompFileNo), int.Parse(strCompVariNo) };
        }

        public DataTable GetUseTestListInformation(int nTestListNo, int nUseStepVersion)
        {
            DataTable dtResult = new DataTable();
            StringBuilder strQuery = new StringBuilder();
            //string strQuery = string.Empty;

            strQuery.Append($"SELECT * FROM ( " +
                        $"SELECT *, ROW_NUMBER() OVER(PARTITION BY StepID ORDER BY StepVersion DESC) " +
                        $"AS RN FROM VRFY_TestListFileRelease WITH (NOLOCK, INDEX=[CSK_VRFY_Release_2]) WHERE TestListFileNo = {nTestListNo.ToString()} " +
                        $"AND StepVersion <= {nUseStepVersion.ToString()}) X WHERE RN = 1 ORDER BY X.StepID ASC;");

            /*
            strQuery.Append($"SELECT * FROM ( " +
                       $"SELECT *, ROW_NUMBER() OVER(PARTITION BY StepID ORDER BY StepVersion DESC) " +
                       $"AS RN FROM VRFY_TestListFileRelease WITH (NOLOCK, INDEX=[CSK_VRFY_Release_2]) WHERE TestListFileNo = {nTestListNo.ToString()} " +
                       $"AND StepVersion <= {nUseStepVersion.ToString()}) X ORDER BY X.StepID ASC;");
            */

            SQLCmd = new SqlCommand(strQuery.ToString(), DBConn);
            SQLCmd.CommandTimeout = DMCommon.nDefaultScanTime;

            DbDataReader dtReader = SQLCmd.ExecuteReader();

            dtResult.Load(dtReader);

            dtReader.Close();

            //PK 지정
            DataColumn[] keys1 = new DataColumn[1];
            keys1[0] = new DataColumn();
            keys1[0] = dtResult.Columns["StepID"];

            dtResult.PrimaryKey = keys1;

            return dtResult;
        }

        DataTable GetRawResult(SelectedDataCollection data, TestHistorySearchOption option, int nReqIdPos = int.MaxValue)
        {
            DataTable dtResult = new DataTable();
            //string strQuery = string.Empty;
            StringBuilder strQuery = new StringBuilder();

            DateTime dtCheckTime = DateTime.Now;

            //데이터 검색 시작 시간 확인
            if (option.Time_WholeRange)
                dtCheckTime = data.SearchRangeStart;
            else if (option.Time_SelectedTest)
                dtCheckTime = data.StartTime;
            else if (option.Time_Day)
                dtCheckTime = data.StartTime;

            DateTime dtNow = DateTime.Now;

            int nDiffMonth =  12 * (dtNow.Year - dtCheckTime.Year) + (dtNow.Month - dtCheckTime.Month);

            //검색 시작시간이 3개월 전이면 LongTerm Summary 검색
            bool bLongTermTableUse = nDiffMonth > 3 ? true : false;

            if (data == null)
                return dtResult;

            strQuery.Append($"SELECT ");

            strQuery.Append($"{DMCommon.SummaryLogTable}.No,");
            strQuery.Append($"CONVERT(char(20), {DMCommon.SummaryLogTable}.TestDT, 20) as {eColList.TestDateTime.ToString()},");
            strQuery.Append($"{DMCommon.SummaryLogTable}.StationName as {eColList.StationName.ToString()},");
            strQuery.Append($"{DMCommon.SummaryLogTable}.HostID as {eColList.Host.ToString()},");
            strQuery.Append($"{DMCommon.SummaryLogTable}.Section as {eColList.Section.ToString()},");
            strQuery.Append($"{DMCommon.SummaryLogTable}.ProductID as {eColList.ProductID.ToString()},");
            strQuery.Append($"{DMCommon.SummaryLogTable}.TestType as {eColList.TestType.ToString()},");
            strQuery.Append($"{DMCommon.SummaryLogTable}.ProdNo_C as {eColList.ProductNo.ToString()},");
            strQuery.Append($"{DMCommon.SummaryLogTable}.Testcode as {eColList.TestCode.ToString()},");
            strQuery.Append($"{DMCommon.SummaryLogTable}.ProdNo_P as {eColList.ParentNo.ToString()},");
            strQuery.Append($"{DMCommon.SummaryLogTable}.ProdCode as {eColList.FileCode.ToString()},");
            strQuery.Append($"{DMCommon.SummaryLogTable}.Version as {eColList.FileVersion.ToString()},");
            strQuery.Append($"{DMCommon.SummaryLogTable}.StepVersion as {eColList.StepVersion.ToString()},");
            strQuery.Append($"{DMCommon.SummaryLogTable}.Duration as {eColList.Duration.ToString()},");
            strQuery.Append($"{DMCommon.SummaryLogTable}.Result as {eColList.TestResult.ToString()},");

            strQuery.Append($"{DMCommon.SummaryLogTable}.[TestListFileNo],");
            strQuery.Append($"{DMCommon.SummaryLogTable}.[TestListVariantNo],");
            strQuery.Append($"{DMCommon.SummaryLogTable}.[LogNo],");
            strQuery.Append($"{DMCommon.SummaryLogTable}.[LogCount],");
            //strQuery += $"{DMCommon.SummaryLogTable}.[TestID],";
            strQuery.Append($"{DMCommon.SummaryLogTable}.[LogNo],");
            strQuery.Append($"{DMCommon.SummaryLogTable}.[LogCount],");
            strQuery.Append($"{DMCommon.SummaryLogTable}.[AccessStart],");
            strQuery.Append($"{DMCommon.SummaryLogTable}.[AccessEnd],");
            strQuery.Append($"{DMCommon.SummaryLogTable}.[TestListFileName],");
            strQuery.Append($"{DMCommon.SummaryLogTable}.[TestListCntID] as {eColList.TestlistReqID.ToString()}");

            strQuery.Append(" ");
            strQuery.Append($"FROM {DMCommon.SummaryLogTable} ");
            strQuery.Append($"WITH(NOLOCK) ");

            if (option.Time_WholeRange)
                strQuery.Append($"WHERE TestDT >= '{data.SearchRangeStart.ToString("yyyy-MM-dd 00:00:00")}' AND TestDT <= '{data.SearchRangeEnd.ToString("yyyy-MM-dd 23:59:59")}' ");
            else if(option.Time_SelectedTest)
                strQuery.Append($"WHERE TestDT >= '{data.StartTime.ToString("yyyy-MM-dd HH:mm:ss")}' AND TestDT <= '{data.EndTime.ToString("yyyy-MM-dd HH:mm:ss")}' ");
            else if(option.Time_Day)
                strQuery.Append($"WHERE TestDT >= '{data.StartTime.ToShortDateString()} 00:00:00' AND TestDT <= '{data.EndTime.ToShortDateString()} 23:59:59' ");

            if (option.Station && !string.IsNullOrWhiteSpace(data.StationName))
                strQuery.Append($" AND (StationName = '{data.StationName}'  OR StationName = '-') ");
            if (option.Host && !string.IsNullOrWhiteSpace(data.HostID))
                strQuery.Append($" AND (HostID = '{data.HostID}' OR HostID = '-') ");
            if (option.Section && !string.IsNullOrWhiteSpace(data.SectionID))
                strQuery.Append($" AND (Section = '{data.SectionID}'  OR Section = '-') ");
            if (option.TestType)
                strQuery.Append($" AND (TestType = '{data.TestType}'  OR TestType = '-') ");
            if (option.ProductNo)
            {
                strQuery.Append($" AND (ProdNo_C = '{data.ProductNo}' ");

                if(option.Host && !string.IsNullOrWhiteSpace(data.HostID))
                {
                    foreach(string strCmd in Enum.GetNames(typeof(eCommand)))
                        strQuery.Append($"OR ProdNo_C = '{strCmd}'");
                }
                strQuery.Append($" )");
            }
            if (option.TestCode)
                strQuery.Append($" AND (Testcode = '{data.TestCode}'  OR Testcode = '-') ");
            if (option.ParentNo)
                strQuery.Append($" AND (ProdNo_P = '{data.ParentNo}'  OR ProdNo_P = '-') ");
            if (option.ProductionCode)
                strQuery.Append($" AND (ProdCode = '{data.ProductionCode}'  OR ProdCode = '-') ");
            if (option.FileVersion)
                strQuery.Append($" AND (Version = '{data.FileVersion}'  OR Version = '-') ");
            if (option.StepVersion)
                strQuery.Append($" AND (StepVersion = '{data.StepVersion}'  OR StepVersion = '-1') ");
            if (option.Time_SelectedTest)
            {
                if (nReqIdPos == int.MaxValue)
                    strQuery.Append($" AND (TestListCntID = '{data.TestRequestID[0]}'  OR TestListCntID = '-') ");
                else
                    strQuery.Append($" AND (TestListCntID = '{data.TestRequestID[nReqIdPos]}'  OR TestListCntID = '-') ");
            }

            // strQuery.Append($" AND (Result = 'NG' OR Result = 'SYSTEM_ERROR' OR Result = 'STOP') ";
            strQuery.Append($" AND (Result != 'OK') ");

            strQuery.Append(" ");
            strQuery.Append($"ORDER BY ");
            strQuery.Append($"{DMCommon.SummaryLogTable}.TestDT");
            strQuery.Append(";");

            if (bLongTermTableUse) SQLCmd = new SqlCommand(strQuery.ToString(), LongTermDBConn);
            else SQLCmd = new SqlCommand(strQuery.ToString(), ShortTermDBConn);
            SQLCmd.CommandTimeout = DMCommon.nDefaultScanTime;

            DbDataReader dtReader = SQLCmd.ExecuteReader();

            dtResult.Load(dtReader);

            dtReader.Close();

            return dtResult;
        }
    }
}
