using System;
using System.Data;
using System.Data.Common;
using Microsoft.VisualBasic;
using static iMESCore.Base.iMESComSubroutine;
using static iMESCore.Base.iMESComXML;
using static iMESCore.Base.iMESConst;
using static iMESCore.DataBase.iMESSql;
using iMESCore.Settings;

namespace MEStc_SXS
{


    public class clsLot : IDisposable
    {
        /*不使用modXX,不再使用OleDb
         * 資料庫相關(建立連線/讀取資料/異動資料),使用data_access_service.dll
         * 設定檔相關,使用iMESAppSetting
         * Xml相關,使用iMESComXML.dll
         * 常數相關,使用iMESConst.dll
         * 簡易副程式,使用iMESComSubroutine.dll
        */


        private AppSettings objSetting = new AppSettings();
        private string strConnectionString;       // Connection string
        private string strDataBaseType;           // DataBase Type:oracle, mysql, access
        private string strMQType;                 // MessageQueue Type:TIBCO, MQSeries, MSMQ
        private bool disposed = false;        // To detect redundant calls
        private string strSQL = "";

        #region --- Initial Object ---

        public clsLot()
        {
            // Get database type
            strDataBaseType = objSetting.GetDataBaseType();
            // Get connection string    
            strConnectionString = objSetting.GetConnectionString(strDataBaseType);
            // Get Message Queue Type
            strMQType = objSetting.GetMQType();
        }

        #endregion

        #region --- Property ---

        // //Property--------------------------------------------------------------------------------------------------------------------------------
        public string ConnectionString
        {
            get
            {
                return strConnectionString;
            }
        }

        public string DataBaseType
        {
            get
            {
                return strDataBaseType;
            }
        }

        public string MQType
        {
            get
            {
                return strMQType;
            }
        }

        // 2003/03/22,sammi.
        // 因TC可能呼叫KC,在整個Function中,必須要使用同一個Reverse物件,如此在產生AddReverseUpdateContent的資料時,ReverseOrder才不會重覆.
        // 若KC再往下呼叫UD,則必須將Reverse物件傳遞予UD.
        //public object ReverseObj
        //{
        //    get
        //    {
        //        //return objReverse;
        //        // ReverseObj = objReverse
        //    }
        //}


        #endregion

        #region IDisposable Support
        private bool disposedValue; // 偵測多餘的呼叫

        // IDisposable
        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    // TODO: 處置 Managed 狀態 (Managed 物件)。
                }

                // TODO: 釋放 Unmanaged 資源 (Unmanaged 物件) 並覆寫下面的 Finalize()。
                // TODO: 將大型欄位設定為 null。
            }
            disposedValue = true;
        }

        // TODO: 只有當上面的 Dispose(ByVal disposing As Boolean) 有可釋放 Unmanaged 資源的程式碼時，才覆寫 Finalize()。
        // Protected Overrides Sub Finalize()
        // ' 請勿變更此程式碼。在上面的 Dispose(ByVal disposing As Boolean) 中輸入清除程式碼。
        // Dispose(False)
        // MyBase.Finalize()
        // End Sub

        // 由 Visual Basic 新增此程式碼以正確實作可處置的模式。
        public void Dispose()
        {
            // 請勿變更此程式碼。在以上的 Dispose 置入清除程式碼 (ByVal 視為布林值處置)。
            Dispose(true);
            GC.SuppressFinalize(this);
        }
        #endregion


        public string LoadOPType(string OPType = defString, int IssueState = defInteger, string AdditionalXml = "")
        {
            string LoadOPTypeRet = null;
            // 此 Function 將資料以XML方式取出
            // 傳入值: 索引值
            // 傳回值: XML(成功), fail(失敗)


            DataSet dsOP = null;

            try
            {

                dsOP = ShowOPType(OPType, IssueState, AdditionalXml);

                // //Combine return value
                LoadOPTypeRet = CombineXMLReturnValue("loadoptype", "OPType", "DataSet", FormatXMLSchema(dsOP.GetXmlSchema()), dsOP.GetXml(), "");
            }

            catch (Exception e1)
            {
                LoadOPTypeRet = "fail";
                throw;
            } // New Exception("kcOP.LoadOPType: " & e1.Message)

            finally
            {
                if (dsOP != null)
                {
                    dsOP.Dispose();
                }
            }

            return LoadOPTypeRet;

        }

        public DataSet ShowOPType(string OPType = defString, int IssueState = defInteger, string AdditionalXml = "")
        {
            DataSet ShowOPTypeRet = null;

            // 此 Function 將資料以 Dataset 方式取出
            // 傳入值: 索引值
            // 傳回值: Dataset(成功), Nothing(失敗)


            DataSet dsOP = null;
            IDbConnection cnnTemp = null;

            try
            {
                // //Create connection
                cnnTemp = CreateConnection(strConnectionString);

                strSQL = "Select * From tblOPType Where OPType Is Not Null";
                if (OPType != defString)
                {
                    strSQL = strSQL + " And OPType = '" + OPType + "'";
                }
                if (IssueState != defInteger)
                {
                    strSQL = strSQL + " And IssueState = " + IssueState;
                }

                if (!string.IsNullOrEmpty(AdditionalXml))
                {
                    // 加上additional的condition
                    strSQL = strSQL + SeparateAddXML_Condition(AdditionalXml);
                }

                // //Select data
                dsOP = new DataSet();
                ExecuteSQLQuery_Adapter(strSQL, dsOP, "OPType", cnnTemp);

                // //Return data
                ShowOPTypeRet = dsOP;
            }

            catch (Exception e1)
            {
                ShowOPTypeRet = null;
                throw;
            }

            finally
            {
                CloseConnection(cnnTemp);
                if (dsOP != null)
                {
                    dsOP.Dispose();
                }
            }

            return ShowOPTypeRet;
        }

        public DataRow GetOPType(string OPType = defString, int IssueState = defInteger, string AdditionalXml = "")
        {
            DataRow GetOPTypeRet = null;
            // 此 Function 將資料以XML方式取出
            // 傳入值: 索引值
            // 傳回值: XML(成功), fail(失敗)


            DataSet dsOP = null;

            try
            {

                dsOP = ShowOPType(OPType, IssueState, AdditionalXml);

                // //Return data
                if (dsOP.Tables[0].Rows.Count > 0)
                {
                    GetOPTypeRet = dsOP.Tables[0].Rows[0];
                }
                else
                {
                    GetOPTypeRet = dsOP.Tables[0].NewRow();
                }
            }

            catch (Exception e1)
            {
                GetOPTypeRet = null;
                throw;
            } // New Exception("kcOP.LoadOPType: " & e1.Message)

            finally
            {
                if (dsOP != null)
                {
                    dsOP.Dispose();
                }
            }

            return GetOPTypeRet;

        }

        public string BR_CheckIn(long LotStamp, string LotNo, string LinkName, DataTable dtAttrib, DataTable dtEquipment, string UserNo, string ShiftNo,
            string LotRecord = defString, DateTime CheckInTime = default(DateTime), string RuleNo = "", DataTable dtLoginState = null, DataTable dtAccessory = null,
            DataTable dtMTLLot = null, string LanguageMode = defString)
        {
            string BR_CheckInRet = default(string);
            // 此 Function 將更新CheckIn Data
            // 傳入值: LotNo,dtAttrib,dtEquipment
            // 傳回值: success(成功), fail(失敗)

            IDbConnection cnnTemp = null;
            DbDataReader drTemp;
            var CollectionSQL = new Collection();
            var CollectionSQL_Rows = new Collection();
            string strSQL = "";

            string LotSerial, OPNo, BRNo, SerialNo, LogGroupSerial, BaseLotNo, CurQTY;
            int PhaseNo;
            DateTime datEventTime;
            long lngLotStamp;

            try
            {
                // //Create connection
                cnnTemp = CreateConnection(strConnectionString);

                // 1.取出Temp LotState的資料
                strSQL = "Select A.LotSerial,A.OPNo,A.SerialNo,B.BRNo,B.LogGroupSerial,B.LotStamp,B.BaseLotNo,B.CurQTY,B.PhaseNo " +
                    " From tblWIPTemp_LotState A, tblWIPLotState B " + " Where A.LotNo ='" + LotNo + "'" + " And A.LotNo = B.LotNo ";
                // cmmTemp = New OleDb.OleDbCommand(strSQL, cnnTemp) 
                drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp);
                if (drTemp.Read())
                {
                    LotSerial = drTemp["LotSerial"].ToString();
                    OPNo = drTemp["OPNo"].ToString();
                    SerialNo = drTemp["SerialNo"].ToString();
                    BRNo = drTemp["BRNo"].ToString();
                    LogGroupSerial = drTemp["LogGroupSerial"].ToString();
                    lngLotStamp = Convert.ToInt64(drTemp["LotStamp"]);
                    BaseLotNo = drTemp["BaseLotNo"].ToString();
                    CurQTY = drTemp["CurQTY"].ToString();
                    PhaseNo = Convert.ToInt32(drTemp["PhaseNo"]); // 2020/11/20 Steven Mantis:	0082084: [PAD]eRunCard_調整 BR 生產記錄
                }
                else
                {
                    throw new iMESException.MESException("0000-202003", "[%LotNo%] : " + LotNo);
                }
                drTemp.Close();


                // 呼叫執行SQL指令
                ExecuteSQLNoneQuery_ChkRowCount(strDataBaseType, strConnectionString, CollectionSQL, CollectionSQL_Rows);

                // //Return success
                BR_CheckInRet = "success";
            }

            catch (Exception e1)
            {
                BR_CheckInRet = "fail";
                throw;
            }
            finally
            {
                CloseConnection(cnnTemp);

            }
            return BR_CheckInRet;

        }


    }
}