using DataBaseConnection.Control;
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.TRA.UIControl;

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

namespace SystemX.Product.TRA.DataManager
{
    public class DMDetailOverview
    {
        public enum eCommand
        {
            PowerON,
            PowerOFF,
            QUERY
        }

        public enum eColList
        {
            TestDate,
            StationName,
            Host,
            Section,
            Start,
            Final,
            ProductNo,
            TestType,
            ParentNo,
            ProductID,
            TestListFileNo,
            TestListVariantNo,
            TestCode,
            FileVersion,
            FileCode,
            StepVersion,
            FirstTestTime,
            FinalTestTime,
            Total,
            OK,
            NG, //NOK,
            TestListCntID
        }

        public enum eColListHide
        {
            TestListCntID,
            RN
        }

        private SqlConnection DBConn { get; set; }

        private SqlConnection ShortTermDBConn { get; set; }

        private SqlConnection LongTermDBConn { get; set; }

        private SqlCommand SQLCmd { get; set; }

        private SelectedDataCollection SelectedOverViewItemData;

        public string strDetailOverviewUseQuery;

        public DataTable dtRaw;

        public DataTable dtSubRaw;

        eOverviewModelNameInfo GetSelectInfo;

        IDataBaseController GetDBController;

        public DMDetailOverview(eSelectDataView SelectView, eOverviewModelNameInfo SelectInfo, IDataBaseController getDBController)
        {
            GetSelectInfo = SelectInfo;

            DBConn = getDBController.GetMainConn();

            GetDBController = getDBController;

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

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

                LongTermDBConn = getDBController.GetLongTermConn2().First().Value;
            }

            strDetailOverviewUseQuery = string.Empty;
        }

        public DataTable GetDataView(eSelectDataView SelectView, SelectedDataCollection data, OverviewSearchOption inputOption)
        {
            if (SelectView == eSelectDataView.DataDocumentViewC1)
            {
                LongTermDBConn = GetDBController.GetLongTermConn1().Where(x => x.Key.Contains(data.StartTime.Year.ToString()))?.FirstOrDefault().Value;
                if (LongTermDBConn == null)
                {
                    LongTermDBConn = GetDBController.GetLongTermConn1().FirstOrDefault().Value;
                }
            }
            else if (SelectView == eSelectDataView.DataDocumentViewC2)
            {
                LongTermDBConn = GetDBController.GetLongTermConn2().Where(x => x.Key.Contains(data.StartTime.Year.ToString()))?.FirstOrDefault().Value;
                if (LongTermDBConn == null)
                {
                    LongTermDBConn = GetDBController.GetLongTermConn2().FirstOrDefault().Value;
                }
            }

            DataTable dtResult = new DataTable();

            SelectedOverViewItemData = data;

            string strGetUseQuery = string.Empty;

            dtRaw = GetRawResult(inputOption, out strGetUseQuery);

            if (inputOption.DisplayByStation == false)
                dtSubRaw = GetSubRawResult();
            else
                dtSubRaw = null;

            strDetailOverviewUseQuery = strGetUseQuery;

            return dtRaw;
        }

        DataTable GetRawResult(OverviewSearchOption inputOption, out string strGetSendQuery)
        {
            DataTable dtResult = new DataTable();
            string strQuery = string.Empty;

            DateTime dtNow = DateTime.Now;
           
            strGetSendQuery = string.Empty;

            strQuery += $"SELECT * FROM (";
            strQuery += $"SELECT ";
            strQuery += $"CAST({DMCommon.SummaryLogTable}.[TestDT] AS DATE) AS {eColList.TestDate.ToString()},";

            if (inputOption.DisplayByStation)
            {
                strQuery += $"{DMCommon.SummaryLogTable}.[StationName] AS {eColList.StationName.ToString()},";
                strQuery += $"{DMCommon.SummaryLogTable}.[HostID] AS {eColList.Host.ToString()},";
                strQuery += $"{DMCommon.SummaryLogTable}.[Section] AS {eColList.Section.ToString()},";
            }
            //
            strQuery += $"Y.ModelName,";

            strQuery += $"{DMCommon.SummaryLogTable}.[TestType] AS {eColList.TestType.ToString()},";
            strQuery += $"{DMCommon.SummaryLogTable}.[ProdNo_C] AS {eColList.ProductNo.ToString()},";
            strQuery += $"{DMCommon.SummaryLogTable}.[Testcode] AS {eColList.TestCode.ToString()},";
            strQuery += $"{DMCommon.SummaryLogTable}.[ProdNo_P] AS {eColList.ParentNo.ToString()},";

            if (SelectedOverViewItemData.ProductID.Length > 0)
                strQuery += $"{DMCommon.SummaryLogTable}.[ProductID] as {eColList.ProductID.ToString()},";

            strQuery += $"{DMCommon.SummaryLogTable}.[TestListFileNo] AS {eColList.TestListFileNo.ToString()},";
            strQuery += $"{DMCommon.SummaryLogTable}.[TestListVariantNo] AS {eColList.TestListVariantNo.ToString()},";
            strQuery += $"{DMCommon.SummaryLogTable}.[ProdCode] AS {eColList.FileCode.ToString()},";
            strQuery += $"{DMCommon.SummaryLogTable}.[Version] AS {eColList.FileVersion.ToString()},";
            strQuery += $"{DMCommon.SummaryLogTable}.[StepVersion] AS {eColList.StepVersion.ToString()},";
            strQuery += $"CONVERT(CHAR(8), MIN({DMCommon.SummaryLogTable}.[TestDT]), 108) AS {eColList.FirstTestTime.ToString()},";
            strQuery += $"CONVERT(CHAR(8), MAX({DMCommon.SummaryLogTable}.[TestDT]), 108) AS {eColList.FinalTestTime.ToString()},";
            strQuery += $"COUNT({DMCommon.SummaryLogTable}.[Result]) AS {eColList.Total.ToString()},";
            strQuery += $"COUNT(CASE WHEN {DMCommon.SummaryLogTable}.[Result] = 'OK' THEN 1 END) AS {eColList.OK.ToString()},";
            strQuery += $"COUNT(CASE WHEN {DMCommon.SummaryLogTable}.[Result] != 'OK' THEN 1 END) AS {eColList.NG.ToString()},";

            if (inputOption.DisplayByStation)
            {
                strQuery += $"ROW_NUMBER() OVER(PARTITION BY {DMCommon.SummaryLogTable}.[ProdNo_C], {DMCommon.SummaryLogTable}.[ProdNo_P] ORDER BY CONVERT(CHAR(23), MAX({DMCommon.SummaryLogTable}.[TestDT]), 121) DESC) AS RN,";

                strQuery += $"{DMCommon.SummaryLogTable}.[TestListCntID] ";
            }
            else
            {
                strQuery += $"ROW_NUMBER() OVER(PARTITION BY {DMCommon.SummaryLogTable}.[ProdNo_C], {DMCommon.SummaryLogTable}.[ProdNo_P] ORDER BY CONVERT(CHAR(23), MAX({DMCommon.SummaryLogTable}.[TestDT]), 121) DESC) AS RN ";
                //strQuery += $"ROW_NUMBER() OVER(PARTITION BY {DMCommon.SummaryLogTable}.[ProdNo_C], {DMCommon.SummaryLogTable}.[Testcode] ORDER BY CONVERT(CHAR(23), MAX({DMCommon.SummaryLogTable}.[TestDT]), 121) DESC) AS RN ";
            }

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

            switch (GetSelectInfo)
            {
                case eOverviewModelNameInfo.L:
                    strQuery += $"LEFT JOIN [CPXV2].[dbo].[PROD_Variant] AS X WITH(NOLOCK) ON X.No = {DMCommon.SummaryLogTable}.[TestListVariantNo] ";
                    strQuery += $"LEFT JOIN [CPXV2].[dbo].[PROD_Group] AS Y WITH(NOLOCK) ON Y.No = X.GroupNo ";
                    break;
                case eOverviewModelNameInfo.P1:
                    strQuery += $"LEFT JOIN [P1].[CPXV2].[dbo].[PROD_Variant] AS X WITH(NOLOCK) ON X.No = {DMCommon.SummaryLogTable}.[TestListVariantNo] ";
                    strQuery += $"LEFT JOIN [P1].[CPXV2].[dbo].[PROD_Group] AS Y WITH(NOLOCK) ON Y.No = X.GroupNo ";
                    break;
                case eOverviewModelNameInfo.P2:
                    strQuery += $"LEFT JOIN [P2].[CPXV2].[dbo].[PROD_Variant] AS X WITH(NOLOCK) ON X.No = {DMCommon.SummaryLogTable}.[TestListVariantNo] ";
                    strQuery += $"LEFT JOIN [P2].[CPXV2].[dbo].[PROD_Group] AS Y WITH(NOLOCK) ON Y.No = X.GroupNo ";
                    break;
            }
            /*
            strQuery += $"LEFT JOIN [CPXV2].[dbo].[PROD_Variant] AS X WITH(NOLOCK) ON X.No = CONVERT(NVARCHAR, {DMCommon.SummaryLogTable}.[TestListVariantNo]) ";
            strQuery += $"LEFT JOIN [CPXV2].[dbo].[PROD_Group] AS Y WITH(NOLOCK) ON Y.No = X.GroupNo ";
            */

            strQuery += $"WHERE TestDT >= '{SelectedOverViewItemData.SearchRangeStart.ToString("yyyy-MM-dd HH:mm:ss")}' AND TestDT <= '{SelectedOverViewItemData.SearchRangeEnd.ToString("yyyy-MM-dd HH:mm:ss")}' AND ";

            strQuery += $"ProdNo_C NOT IN('PowerON', 'PowerOFF', 'QUERY') AND ";
            strQuery += $"ProductID NOT IN('PowerON', 'PowerOFF', 'QUERY') ";

            if (SelectedOverViewItemData.ProductID.Length > 0)
            {
                strQuery += $"AND ProductID = '{SelectedOverViewItemData.ProductID}' ";
            }

            strQuery += $"GROUP BY ";

            strQuery += $"CAST({DMCommon.SummaryLogTable}.[TestDT] AS DATE),";
            //
            strQuery += $"Y.ModelName,";

            if (inputOption.DisplayByStation)
            {
                strQuery += $"{DMCommon.SummaryLogTable}.[StationName],";
                strQuery += $"{DMCommon.SummaryLogTable}.[HostID],";
                strQuery += $"{DMCommon.SummaryLogTable}.[Section],";
                strQuery += $"{DMCommon.SummaryLogTable}.[TestListCntID],";
            }

            if (SelectedOverViewItemData.ProductID.Length > 0)
                strQuery += $"{DMCommon.SummaryLogTable}.ProductID,";

            //strQuery += $"{DMCommon.SummaryLogTable}.[TestListCntID],";

            strQuery += $"{DMCommon.SummaryLogTable}.[TestType],";
            strQuery += $"{DMCommon.SummaryLogTable}.[ProdNo_C],";
            strQuery += $"{DMCommon.SummaryLogTable}.[Testcode],";
            strQuery += $"{DMCommon.SummaryLogTable}.[TestListFileNo],";
            strQuery += $"{DMCommon.SummaryLogTable}.[TestListVariantNo],";
            strQuery += $"{DMCommon.SummaryLogTable}.[ProdNo_P],";
            strQuery += $"{DMCommon.SummaryLogTable}.[ProdCode],";
            strQuery += $"{DMCommon.SummaryLogTable}.[Version],";
            strQuery += $"{DMCommon.SummaryLogTable}.[StepVersion]";
            strQuery += " ";
            strQuery += ") AS X ";

            if (inputOption.DisplayByStation)
            {
                strQuery += "WHERE X.Host = '" + SelectedOverViewItemData.HostID + "' AND X.Section = '" + SelectedOverViewItemData.SectionID + "' ";
                //strQuery += "ORDER BY X.TestDate, X.Host, X.Section ASC;";
                strQuery += "ORDER BY  X.TestDate ASC, X.FirstTestTime ASC;";
            }
            else
            {
                strQuery += "WHERE X.ProductNo = '" + SelectedOverViewItemData.ProductNo + "' AND X.TestType = '" + SelectedOverViewItemData.TestType + "' AND X.TestCode = '" + SelectedOverViewItemData.TestCode + "' AND X.ParentNo = '" + SelectedOverViewItemData.ParentNo + "' ";
                //strQuery += "ORDER BY X.TestDate, X.ProductNo, X.ParentNo ASC;";
                strQuery += "ORDER BY  X.TestDate ASC, X.FirstTestTime ASC;";
            }
            //
            strGetSendQuery = 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();

            return dtResult;
        }

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

            DateTime dtNow = DateTime.Now;
                       
            strQuery += $"SELECT * FROM (";
            strQuery += $"SELECT ";
            strQuery += $"CAST({DMCommon.SummaryLogTable}.[TestDT] AS DATE) AS {eColList.TestDate.ToString()},";

            strQuery += $"Y.ModelName,";

            strQuery += $"{DMCommon.SummaryLogTable}.[TestType] AS {eColList.TestType.ToString()},";
            strQuery += $"{DMCommon.SummaryLogTable}.[ProdNo_C] AS {eColList.ProductNo.ToString()},";
            strQuery += $"{DMCommon.SummaryLogTable}.[Testcode] AS {eColList.TestCode.ToString()},";
            strQuery += $"{DMCommon.SummaryLogTable}.[ProdNo_P] AS {eColList.ParentNo.ToString()},";

            if (SelectedOverViewItemData.ProductID.Length > 0)
                strQuery += $"{DMCommon.SummaryLogTable}.[ProductID] as {eColList.ProductID.ToString()},";

            strQuery += $"{DMCommon.SummaryLogTable}.[TestListFileNo] AS {eColList.TestListFileNo.ToString()},";
            strQuery += $"{DMCommon.SummaryLogTable}.[TestListVariantNo] AS {eColList.TestListVariantNo.ToString()},";
            strQuery += $"{DMCommon.SummaryLogTable}.[ProdCode] AS {eColList.FileCode.ToString()},";
            strQuery += $"{DMCommon.SummaryLogTable}.[Version] AS {eColList.FileVersion.ToString()},";
            strQuery += $"{DMCommon.SummaryLogTable}.[StepVersion] AS {eColList.StepVersion.ToString()},";
            strQuery += $"CONVERT(CHAR(8), MIN({DMCommon.SummaryLogTable}.[TestDT]), 108) AS {eColList.FirstTestTime.ToString()},";
            strQuery += $"CONVERT(CHAR(8), MAX({DMCommon.SummaryLogTable}.[TestDT]), 108) AS {eColList.FinalTestTime.ToString()},";
            strQuery += $"COUNT({DMCommon.SummaryLogTable}.[Result]) AS {eColList.Total.ToString()},";
            strQuery += $"COUNT(CASE WHEN {DMCommon.SummaryLogTable}.[Result] = 'OK' THEN 1 END) AS {eColList.OK.ToString()},";
            strQuery += $"COUNT(CASE WHEN {DMCommon.SummaryLogTable}.[Result] != 'OK' THEN 1 END) AS {eColList.NG.ToString()},";

            strQuery += $"ROW_NUMBER() OVER(PARTITION BY {DMCommon.SummaryLogTable}.[ProdNo_C], {DMCommon.SummaryLogTable}.[ProdNo_P] ORDER BY CONVERT(CHAR(23), MAX({DMCommon.SummaryLogTable}.[TestDT]), 121) DESC) AS RN,";
            //strQuery += $"ROW_NUMBER() OVER(PARTITION BY {DMCommon.SummaryLogTable}.[ProdNo_C], {DMCommon.SummaryLogTable}.[Testcode] ORDER BY CONVERT(CHAR(23), MAX({DMCommon.SummaryLogTable}.[TestDT]), 121) DESC) AS RN,";
            //strQuery += $"ROW_NUMBER() OVER(PARTITION BY {DMCommon.SummaryLogTable}.[ProdNo_C] ORDER BY CONVERT(CHAR(23), MAX({DMCommon.SummaryLogTable}.[TestDT]), 121) DESC) AS RN,";

            strQuery += $"{DMCommon.SummaryLogTable}.[TestListCntID] ";

            strQuery += $"FROM {DMCommon.SummaryLogTable} ";
            strQuery += $"WITH(NOLOCK) ";
            //strQuery += $"LEFT JOIN [CPXV2].[dbo].[PROD_Variant] AS X WITH(NOLOCK) ON X.No = CONVERT(NVARCHAR, {DMCommon.SummaryLogTable}.[TestListVariantNo]) ";

            switch (GetSelectInfo)
            {
                case eOverviewModelNameInfo.L:
                    strQuery += $"LEFT JOIN [CPXV2].[dbo].[PROD_Variant] AS X WITH(NOLOCK) ON X.No = {DMCommon.SummaryLogTable}.[TestListVariantNo] ";
                    strQuery += $"LEFT JOIN [CPXV2].[dbo].[PROD_Group] AS Y WITH(NOLOCK) ON Y.No = X.GroupNo ";
                    break;
                case eOverviewModelNameInfo.P1:
                    strQuery += $"LEFT JOIN [P1].[CPXV2].[dbo].[PROD_Variant] AS X WITH(NOLOCK) ON X.No = {DMCommon.SummaryLogTable}.[TestListVariantNo] ";
                    strQuery += $"LEFT JOIN [P1].[CPXV2].[dbo].[PROD_Group] AS Y WITH(NOLOCK) ON Y.No = X.GroupNo ";
                    break;
                case eOverviewModelNameInfo.P2:
                    strQuery += $"LEFT JOIN [P2].[CPXV2].[dbo].[PROD_Variant] AS X WITH(NOLOCK) ON X.No = {DMCommon.SummaryLogTable}.[TestListVariantNo] ";
                    strQuery += $"LEFT JOIN [P2].[CPXV2].[dbo].[PROD_Group] AS Y WITH(NOLOCK) ON Y.No = X.GroupNo ";
                    break;
            }

            /*
            strQuery += $"LEFT JOIN [CPXV2].[dbo].[PROD_Variant] AS X WITH(NOLOCK) ON X.No = {DMCommon.SummaryLogTable}.[TestListVariantNo] ";
            strQuery += $"LEFT JOIN [CPXV2].[dbo].[PROD_Group] AS Y WITH(NOLOCK) ON Y.No = X.GroupNo ";
            */

            strQuery += $"WHERE TestDT >= '{SelectedOverViewItemData.SearchRangeStart.ToString("yyyy-MM-dd HH:mm:ss")}' AND TestDT <= '{SelectedOverViewItemData.SearchRangeEnd.ToString("yyyy-MM-dd HH:mm:ss")}' AND ";

            strQuery += $"ProdNo_C NOT IN('PowerON', 'PowerOFF', 'QUERY') AND ";
            strQuery += $"ProductID NOT IN('PowerON', 'PowerOFF', 'QUERY') ";

            if (SelectedOverViewItemData.ProductID.Length > 0)
            {
                strQuery += $"AND ProductID = '{SelectedOverViewItemData.ProductID}' ";
            }

            strQuery += $"GROUP BY ";

            strQuery += $"CAST({DMCommon.SummaryLogTable}.[TestDT] AS DATE),";
            //
            strQuery += $"Y.ModelName,";

            if (SelectedOverViewItemData.ProductID.Length > 0)
                strQuery += $"{DMCommon.SummaryLogTable}.ProductID,";

            strQuery += $"{DMCommon.SummaryLogTable}.[TestListCntID],";

            strQuery += $"{DMCommon.SummaryLogTable}.[TestType],";
            strQuery += $"{DMCommon.SummaryLogTable}.[ProdNo_C],";
            strQuery += $"{DMCommon.SummaryLogTable}.[Testcode],";
            strQuery += $"{DMCommon.SummaryLogTable}.[TestListFileNo],";
            strQuery += $"{DMCommon.SummaryLogTable}.[TestListVariantNo],";
            strQuery += $"{DMCommon.SummaryLogTable}.[ProdNo_P],";
            strQuery += $"{DMCommon.SummaryLogTable}.[ProdCode],";
            strQuery += $"{DMCommon.SummaryLogTable}.[Version],";
            strQuery += $"{DMCommon.SummaryLogTable}.[StepVersion]";
            strQuery += " ";
            strQuery += ") AS X ";

            strQuery += "WHERE X.ProductNo = '" + SelectedOverViewItemData.ProductNo + "' AND X.TestType = '" + SelectedOverViewItemData.TestType + "' AND X.TestCode = '" + SelectedOverViewItemData.TestCode + "' AND X.ParentNo = '" + SelectedOverViewItemData.ParentNo + "' ";
            //strQuery += "ORDER BY X.TestDate, X.ProductNo, X.ParentNo ASC;";
            strQuery += "ORDER BY  X.TestDate ASC, X.FirstTestTime ASC;";

            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();

            return dtResult;
        }
    }
}
