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;
using DataBaseConnection.Control;
using Newtonsoft.Json;
using SystemX.Common.Util;

using CPXV2Log = SystemX.Net.Platform.SystemX.Net.XEFCore.DBContext.CPXV2Log;

namespace SystemX.Product.TRA.DataManager
{
    public class DMTestSummary
    {
        public enum eColHideListLog
        {
            No,          
            //TestID
        }

        public enum eColTestLog
        {
            No,           
            //TestID,
            StepID,
            MeasVal,
            MeasValStr,
            Message,
            GlobalMin,
            GlobalMax,
            Result
            //Duration
        }

        public enum eColHideListTL
        {
            No,
            TestlistNo,
            StepVersion,
            Enable,
            IsGlobal,
            UpdateDT
        }

        public enum eColTestlist
        {
            No,
            TestlistNo,
            StepID,
            Variant,
            Gate,
            Activate,
            StepVersion,
            Enable,
            Position,
            StepDesc,
            UseFunction,
            SpecMin,
            SpecMax,
            Dim,
            IsGlobal,
            UpdateDT
        }

        public enum eColTestSummary
        {
            StepID,
            Average,
            Total,
            OK,
            NG //NOK
        }

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

        private SqlCommand SQLCmd { get; set; }

        public DataTable dtHistVersionTL;

        eSelectDataView TestSummarySelectView { get; set; }

        IDataBaseController GetDBController;

        public int nCurrentTLMaxStepVersion { get; set; }

        //public DataTable this[int i] => dtEachVersionTL[i];

        public DMTestSummary(eSelectDataView SelectView, IDataBaseController getDBController, DateTime dtStart)
        {
            GetDBController = getDBController;
            DBConn = getDBController.GetMainConn();

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

                LongTermDBConn = getDBController.GetLongTermConn1().Where(x=>x.Key.Contains(dtStart.Year.ToString())).First().Value;
            }
            else if (SelectView == eSelectDataView.DataDocumentViewC2)
            {
                TestSummarySelectView = eSelectDataView.DataDocumentViewC2;
                ShortTermDBConn = getDBController.GetShortTermConn2();

                LongTermDBConn = getDBController.GetLongTermConn2().Where(x => x.Key.Contains(dtStart.Year.ToString())).First().Value;
            }
        }

        public DataTable SearchTestlist(SelectedDataCollection data, int nHistChkStepVer = int.MinValue, bool bOnlyNewStepVersion = true)
        {
            DataTable dtResult = new DataTable();
            DataTable dtResultChk = new DataTable();

            string strQuery = string.Empty;

            if (data == null)
                return dtResult;

            strQuery = $"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 = '{data.ProductNo}' AND D.TestCode = '{data.TestCode}' AND E.TestType = '{data.TestType}' AND E.Version = '{data.FileVersion}' AND E.ProdCode = '{data.ProductionCode}';";

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

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

            dtCompResult.Load(dtCompReader);

            if (Commons.isHasRow(dtCompResult) == false)
                return dtResult;

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

            dtCompReader.Close();

            string strGetTestListFileNo = string.Empty;

            if (strCompVariNo.CompareTo(data.TestListVariantNo) == 0 &&
            strCompFileNo.CompareTo(data.TestListFileNo) == 0)
                strGetTestListFileNo = data.TestListFileNo;
            else
                strGetTestListFileNo = strCompFileNo;

            strQuery = $"SELECT LatestStepVersion FROM [HIST_TestListFileLatestStepVersion] WITH(NOLOCK) WHERE TestListFileNo = {strGetTestListFileNo};";

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

            DbDataReader dtReaderChk = SQLCmd.ExecuteReader();

            dtResultChk.Clear();
            dtResultChk.Load(dtReaderChk);

            int nMaxStepVersion = Convert.ToInt32(dtResultChk.Rows[0]["LatestStepVersion"].ToString());

            nCurrentTLMaxStepVersion = nMaxStepVersion;

            dtReaderChk.Close();

            //항상 최신 스텝 버전을 체크
            strQuery = $"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 = {strGetTestListFileNo}) AS X " +
                $"WHERE X.RN = 1 ORDER BY X.StepID ASC;";

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

            DbDataReader dtReader = SQLCmd.ExecuteReader();

            dtResult.Clear();
            dtResult.Load(dtReader);

            dtReader.Close();

            if (bOnlyNewStepVersion)
            {
                dtHistVersionTL = null;
            }
            else
            {
                //Hist 목록 검색 스텝 버전 리스트만 검색하여 사용
                dtHistVersionTL = new DataTable();

                strQuery = $"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 = {strGetTestListFileNo} AND StepVersion <= {nHistChkStepVer}) AS X " +
                    $"WHERE X.RN = 1 ORDER BY X.StepID ASC, StepVersion DESC;";

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

                DbDataReader dtHistReader = SQLCmd.ExecuteReader();

                dtHistVersionTL.Clear();
                dtHistVersionTL.Load(dtHistReader);

                dtHistReader.Close();

                //PK 키 지정 >
                //TODO : Primary Key Access Error > 업데이트 된 동일 스텝이 존재시 PK 지정 실패
                DataColumn[] keysHistStepVer = new DataColumn[1];
                keysHistStepVer[0] = new DataColumn();
                keysHistStepVer[0] = dtHistVersionTL.Columns["StepID"];

                dtHistVersionTL.PrimaryKey = keysHistStepVer;

                /*
                dtEachVersionTL = new DataTable[nMaxStepVersion + 1];

                int nStartStepVer = nMaxStepVersion - 5;

                if (nStartStepVer < 0)
                    nStartStepVer = 0;

                for (int i = nStartStepVer; i <= nMaxStepVersion; i++)
                {
                    dtEachVersionTL[i] = new DataTable();

                    strQuery = $"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 = {strGetTestListFileNo} AND StepVersion <= {i}) AS X " +
                    $"WHERE X.RN = 1 ORDER BY X.StepID ASC, StepVersion DESC;";

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

                    DbDataReader dtReader = SQLCmd.ExecuteReader();

                    dtEachVersionTL[i].Clear();
                    dtEachVersionTL[i].Load(dtReader);

                    dtReader.Close();

                    //PK 키 지정 >
                    //TODO : Primary Key Access Error > 업데이트 된 동일 스텝이 존재시 PK 지정 실패
                    DataColumn[] keysEachStepVer = new DataColumn[1];
                    keysEachStepVer[0] = new DataColumn();
                    keysEachStepVer[0] = dtEachVersionTL[i].Columns["StepID"];

                    dtEachVersionTL[i].PrimaryKey = keysEachStepVer;
                }
                */
            }

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

            dtResult.PrimaryKey = keys1;

            return dtResult;
        }

        public DataTable RefineStepVersion(DataTable dtTestlist, SelectedDataCollection data)
        {
            var DuplicatedSteps = dtTestlist.AsEnumerable().GroupBy(x => x[eColTestlist.StepID.ToString()]).
                Select(x => new { StepID = x.Key, Count = x.Count() }).Where(x => x.Count > 1);
            
            foreach(var value in DuplicatedSteps)
            {
                List<DataRow> vdtRow = dtTestlist.AsEnumerable().Where(x => x[eColTestlist.StepID.ToString()].ToString() == value.StepID.ToString()).ToList();
                DataRow vExcRow = vdtRow.Where(x => x[eColTestlist.StepVersion.ToString()].ToString() == data.StepVersion).FirstOrDefault();

                if(vExcRow == null)
                {
                    int nMaxVer = vdtRow.Max(x => Convert.ToInt32(x[eColTestlist.StepVersion.ToString()]));

                    vExcRow = vdtRow.Where(x => Convert.ToInt32(x[eColTestlist.StepVersion.ToString()]) == nMaxVer).FirstOrDefault();
                }

                vdtRow.Remove(vExcRow);

                foreach (DataRow dtRow in vdtRow)
                    dtTestlist.Rows.Remove(dtRow);
            }

            return dtTestlist;
        }

        public DataTable SearchTestSummary(string[] testReqID, List<Int64> vnpSummaryNo)
        {
            DateTime start = DateTime.Now;
            try
            {
                string requId = testReqID?.First();
                if (string.IsNullOrEmpty(requId) == false && requId.Contains(";") == true)
                {
                    start = Convert.ToDateTime(requId.Split(';')[0]);
                }
            }
            catch (Exception e)
            {
                //start = DateTime
            }

            if (TestSummarySelectView == eSelectDataView.DataDocumentViewC1)
            {
                ShortTermDBConn = GetDBController.GetShortTermConn1();

                LongTermDBConn = GetDBController.GetLongTermConn1().Where(x => x.Key.Contains(start.Year.ToString())).First().Value;
            }
            else if (TestSummarySelectView == eSelectDataView.DataDocumentViewC2)
            {
                ShortTermDBConn = GetDBController.GetShortTermConn2();

                LongTermDBConn = GetDBController.GetLongTermConn2().Where(x => x.Key.Contains(start.Year.ToString())).First().Value;
            }

            DataTable dtResult = new DataTable();
            string strQuery = string.Empty;                           

            strQuery += $"SELECT * ";
            strQuery += $"FROM {DMCommon.SummaryLogTable} AS X ";
            strQuery += $"INNER JOIN {DMCommon.ResultLogTable} AS Y ON X.No = Y.No ";
            strQuery += $"WHERE ";

            for (int i = 0; i < vnpSummaryNo.Count; i++)
            {
                strQuery += $"X.[No]=N'{vnpSummaryNo[i]}' ";

                if (i != vnpSummaryNo.Count - 1)
                    strQuery += "OR ";
            }

            //for(int i=0 ; i<testReqID.Length ; i++)
            //{
            //    strQuery += $"TestListCntID=N'{testReqID[i]}' ";

            //    if (i != testReqID.Length - 1)
            //        strQuery += "OR ";
            //}

            strQuery += $";";          

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

            DbDataReader dtReader = SQLCmd.ExecuteReader();

            dtResult.Load(dtReader);
            dtReader.Close();

            List<CPXV2Log.Tables.HIST_TestResult> list = new List<CPXV2Log.Tables.HIST_TestResult>();
            for (int i=0; i<dtResult.Rows.Count; i++)
            {
                list.AddRange(JsonConvert.DeserializeObject<List<CPXV2Log.Tables.HIST_TestResult>>(dtResult.Rows[i]["LogData"].ToString().GzipDecompress()));    
            }

            dtResult = list.GroupBy(x => x.StepID).Select(y => new
            {
                StepID = y.First().StepID,
                Average = GetAvg(y.Average(z => z.MeasVal)),
                Total = y.Count(),
                OK = y.Count(z=>z.Result.Contains("OK")),
                NG = y.Count(z=>!z.Result.Contains("OK"))
            }).OrderBy(y=>y.StepID).ToDataTable();

            return dtResult;
        }

        string GetAvg(decimal avg)
        {
            if (avg > 0)
                return avg.ToString();
            else
                return string.Empty;
        }

        DataTable GetRawResult(DetailTestDataCollection data)
        {
            DataTable dtResult = new DataTable();
            string strQuery = string.Empty;

            if (data == null)
                return dtResult;
                        

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

            DbDataReader dtReader = SQLCmd.ExecuteReader();

            dtResult.Load(dtReader);

            dtReader.Close();

            return dtResult;
        }
    }
}
