using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Runtime.InteropServices;
using kcENT;
using kcMTL;
using kcPRD;
using Microsoft.VisualBasic;
using Microsoft.VisualBasic.CompilerServices;
using iMESCore.Settings;
using static iMESCore.Base.iMESComSubroutine;
using static iMESCore.Base.iMESConst;
using static iMESCore.DataBase.iMESSql;
using static iMESCore.Base.iMESComXML;
using iMESCore.DataBase;
using System.Linq;
using System.Collections.ObjectModel;
using kcSYS;
using kcOE;
using kcOP;
using kcSMD;
using System.Xml;
using kcQC;

namespace tcEAI_C
{

    public class clsOE
    {


        public clsOE()
        {


        }

        #region MO


        /// <summary>
        /// 新增工單
        /// </summary>
        /// <param name="MONo"></param>
        /// <param name="MOUnitNo"></param>
        /// <param name="ProductNo"></param>
        /// <param name="MOQty"></param>
        /// <param name="FactoryNo"></param>
        /// <param name="RONo"></param>
        /// <param name="ItemNo"></param>
        /// <param name="CustomerNo"></param>
        /// <param name="MOTypeNo"></param>
        /// <param name="Priority"></param>
        /// <param name="PlanFinishDate"></param>
        /// <param name="Creator"></param>
        /// <param name="CreateDate"></param>
        /// <param name="Description"></param>
        /// <param name="dtMTL"></param>
        /// <param name="MOProperty"></param>
        /// <param name="aryMessage"></param>
        /// <param name="aryException"></param>
        /// <param name="aryAlert"></param>
        /// <param name="dtMOProperty"></param>
        /// <returns></returns>
        /// <remarks></remarks>
        public static bool addMO(string Orgcode,string OrgMono, string MONo, string MOUnitNo, string ProductNo, decimal MOQty, string FactoryNo, string RONo = null, string ItemNo = null, string CustomerNo = null,
            int MOTypeNo = defInteger, int Priority = defInteger, DateTime PlanFinishDate = default(DateTime), string Creator = null,
            DateTime CreateDate = default(DateTime), string Description = null, DataTable dtMTL = null, List<ArrayList> MOProperty = null, List<ArrayList> aryMessage = null, List<ArrayList> aryException = null,
            List<ArrayList> aryAlert = null, DataTable dtMOProperty = null, string ERPMOLineNo = defString, string CustomerLotNo = null, DateTime PlanStartDate = default(DateTime), int wipEntityId = defInteger, string bomVersion = null, string lcPlantype = null, string faiFlag = null)
        {
            bool addMORet = default(bool);

            bool r = false;
            string strSQLTemp, strSQL = default(string), strSQLAddField, strSQLAddValue;
            IDbConnection cnnTemp1 = null;
            //OleDbCommand cmmTemp;
            DbDataReader drTemp2;
            DbDataReader drTemp3;
            // Dim daTemp As OleDb.OleDbDataAdapter
            // Dim drSel() As DataRow
            // Dim strDataBaseType, strConnectionString As String             'Connection string
            // Dim i As Integer
            // Dim dsTemp As DataSet
            AppSettings objSetting = new AppSettings();
            var CollectionSQL = new Collection();

            try
            {
                string strDataBaseType = objSetting.GetDataBaseType();
                string strConnectionString = objSetting.GetConnectionString(strDataBaseType);
                cnnTemp1 = CreateConnection(strConnectionString);

                // ----- Default Value -----
                int MOSource = 0;                     // 0: RO, 1: RMA, 2: None 
                int MOState = 0;                      // 0: Unconfirm, 1: Pending, 2: Confirm, 3: Release(允許開立生產批), 6: 已在客託倉或退貨倉的工單(允許開立生產批), 99:Close
                int IssueState = 0;
                string BelongToMONo = "N/A";
                string ENGNo = "N/A";
                string ENGVersion = "N/A";
                //string CustomerLotNo = string.Empty;
                // Dim OPNo As String = "LOTCREATE"

                // ---- Get Value -----
                string CustomerName = string.Empty;
                string ProductVersion = string.Empty;
                string ProcessNo = string.Empty;
                string ProcessVersion = string.Empty;

                bool isROExist = false;
                bool isRODetailExist = false;

                string ItemProperty = defString;   // 2016-10-17, Joe, 新增料件屬性，P：採購件，M：自製件，S：外包件
                int OutSourcingFlag = defInteger;     // 2016-10-17, Joe, 0:off，1:on

                // Kevin 15/06/09 ,調整產品編號轉大寫,後續的程式處理並未全部都有轉大寫
                ProductNo = ProductNo.ToUpper();

                // ----- 1. 檢查MO是否存在 -----

                MONo = MONo.ToUpper();

                using (var objOE = new clsOEBasis())
                {
                    if (objOE.GetMOBasis(MONo.ToUpper())["MONo"] is DBNull == false)
                        clsERP.combineException(ref aryException, mesmsg: "[%MONoExist%]");
                }

                // ----- 2. 檢查MOSource-----
                if (string.IsNullOrEmpty(RONo))
                    MOSource = 2; // MO來源為其他(暫不考慮RMA)

                // ----- 3. 檢查CustomerNo是否存在 -----
                if (MOSource == 0)
                {
                    if (string.IsNullOrEmpty(CustomerNo))
                    {
                        // 未傳入
                        clsERP.combineException(ref aryException, mesmsg: "[%ROWithOutCustomer%]");
                    }
                    else
                    {
                        // 有傳入=>檢查Customer主檔
                        using (var objENT = new clsCustomerBasis())
                        {
                            var dr = objENT.GetCustomerBasis(CustomerNo.ToUpper());
                            if (dr["CustomerNo"] is DBNull == true)
                            {
                                // Customer主檔未建立
                                // clsERP.combineException(aryException, , , "[%CustomerNoNotExist%]")

                                // 5.3	若拋入訂單號碼，則必須拋入客戶編號，系統應檢查tblENTCustomerBasis之中是否存在此客戶，若無則自動新增
                                objENT.AddCustomerBasis(CustomerNo.ToUpper(), CustomerNo, CustomerNo, "NULL", "NULL", "NULL", "NULL", "NULL", "NULL");
                                objENT.SetCustomerBasisIssueState(CustomerNo.ToUpper(), 2);
                            }
                            else
                            {
                                CustomerName = dr["CustomerName"].ToString();
                            }
                        }
                    }
                }

                // ----- 4. 檢查Product -----
                using (var objPRD = new clsProduct())
                {
                    var dr = objPRD.GetProduct(ProductNo.ToUpper());
                    if (dr["ProductNo"] is DBNull == true)
                        clsERP.combineException(ref aryException, mesmsg: "[%ProductNoNotExist%]");
                    if (dr["ProductNo"] is DBNull == false && Convert.ToBoolean(Operators.ConditionalCompareObjectNotEqual(dr["IssueState"], 2, false)))
                        clsERP.combineException(ref aryException, mesmsg: "[%ProductNoNotApproved%]");

                    // ----- 5. 檢查MOUnitNo -----
                    if (dr["ProductNo"] is DBNull == false && dr["UnitNo"].ToString().ToLower() != MOUnitNo.ToLower())
                        clsERP.combineException(ref aryException, mesmsg: "[%ProductMOWithDifferentUnitNo%]");
                    dr.Delete();

                    try
                    {
                        ProductVersion = objPRD.GetProductCurVersion(ProductNo.ToUpper());
                    }
                    catch (Exception ex)
                    {
                        clsERP.combineException(ref aryException, mesmsg: "[%GetProductVersionFail%]");
                    }

                    // 2016-10-17, Joe, 取得ItemProperty
                    var drItemProperty = objPRD.GetProductProperty(ProductNo, ProductVersion, "ItemProperty");
                    if (drItemProperty == null == false && drItemProperty["DefaultValue"] is DBNull == false)
                    {
                        ItemProperty = drItemProperty["DefaultValue"].ToString();
                    }
                    // 2016-10-17, Joe, 取得外包控制
                    using (var objSYS = new clsSYSParameter())
                    {
                        OutSourcingFlag = Conversions.ToInteger(objSYS.GetParameterValue("OutSourcingFlag"));
                    }
                    // 2016-10-17, Joe, 若該產品品號屬性屬於S且外包控管參數為Off時，MES不做工單新增/修改，直接回應OK，但訊息應回傳『MES系統不支持外包工單』
                    if (ItemProperty == "S" & OutSourcingFlag == 0)
                    {
                        // 2018/06/26 Lena, 修正訊息語系未譯的問題.
                        clsERP.combineException(ref aryException, mesmsg: "[%ProductNo%]:" + ProductNo + ",[%ProductVersion%]:" + ProductVersion + ",[%IsOutSourcingProduct%], MES [%IsNotSupported%] !");
                        if (aryException.Count > 0)
                            goto exitfun;
                    }

                    // ----- 6. 檢查ProductProcess是否存在 -----
                    // 2012/07/26, Aaron, 如果傳入的MOTypeNo找不到就用-1(*)找尋預設值，再找不到彈出錯誤
                    dr = objPRD.GetProductProcess(ProductNo.ToUpper(), ProductVersion, MOTypeNo, DefaultProcess: 1);
                    if (dr["ProductNo"] is DBNull == true)
                    {
                        dr = objPRD.GetProductProcess(ProductNo.ToUpper(), ProductVersion, -1, DefaultProcess: 1);
                        if (dr["ProductNo"] is DBNull == true)
                            clsERP.combineException(ref aryException, mesmsg: "[%ProductProcessNoNotExist%]");
                    }
                }

                // ----- 7. 檢查用料清單資料 -----
                var objPRD_M = new kcPRD.clsProduct();
                DataView dvTemp;
                var objMTL = new kcMTL.clsMTLBasis();
                var dsBOM = new DataSet();
                DataRow drData;

                System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();            // 用以讀取Xml字串

                // 工單用料表
                var dtMOBom = new DataTable("MOBom");
                dtMOBom.Columns.Add("MONo", Type.GetType("System.String"));
                dtMOBom.Columns.Add("MaterialLevel", Type.GetType("System.Int32"));    // 0:Material,1:Product
                dtMOBom.Columns.Add("MaterialNo", Type.GetType("System.String"));
                dtMOBom.Columns.Add("MaterialVersion", Type.GetType("System.String"));
                dtMOBom.Columns.Add("StdQty", Type.GetType("System.Double"));
                dtMOBom.Columns.Add("DecreaseRate", Type.GetType("System.Double"));
                dtMOBom.Columns.Add("UnitNo", Type.GetType("System.String"));
                dtMOBom.Columns.Add("OPNo", Type.GetType("System.String"));
                dtMOBom.Columns.Add("PutInPlaceType", Type.GetType("System.Int32"));
                dtMOBom.Columns.Add("Specified", Type.GetType("System.Int32"));   // 0:No,1:Yes
                dtMOBom.Columns.Add("MOFlag", Type.GetType("System.Int32"));   // 0:Create MO,1:來自半成品庫,不用開立工單
                dtMOBom.Columns.Add("MaterialMONo", Type.GetType("System.String")); // 半成品的工單編號
                dtMOBom.Columns.Add("Description", Type.GetType("System.String"));  // Bom Material Description
                dtMOBom.Columns.Add("SubstituteMaterialNo", Type.GetType("System.String")); // 替代料,預設值同MaterialNo
                dtMOBom.Columns.Add("SubstituteMaterialLevel", Type.GetType("System.Int32")); // 替代料等級,預設值同物料等級(materialLevel)
                dtMOBom.Columns.Add("SubstituteStdQty", Type.GetType("System.Decimal")); // 替代料標準數量，預設值=標準數量StdQty
                dtMOBom.Columns.Add("RequireQty", Type.GetType("System.Decimal")); // 需求數,預設值=工單數量MoQty * 標準數StdQty
                dtMOBom.Columns.Add("AB", Type.GetType("System.String")); // 需求數,預設值=工單數量MoQty * 標準數StdQty
                dtMOBom.Columns.Add("PositionCode", Type.GetType("System.String")); // 需求數,預設值=工單數量MoQty * 標準數StdQty


                // 1.工單的單位可能與用料表(tblOEMOMaterialList)的標準單位(產品的單位)不同----------------------------------------------------
                // 故須以工單數量,單位換算出產品的標準量
                DataRow drTemp;
                string strStdUnitNo;
                double dblStdQty;

                // 工單開立,產品不一定是CurVersion.
                drTemp = objPRD_M.GetProduct(ProductNo, ProductVersion, CurVersion: defInteger);
                if (drTemp["ProductNo"] is DBNull)
                {
                    throw new iMESException.MESException("0000-200002", "Get product data of ProductNo:" + ProductNo + ", Version:" + ProductVersion + " fail !");
                }

                strStdUnitNo = Conversions.ToString(drTemp["UnitNo"]); // 標準單位
                if ((strStdUnitNo.ToUpper() ?? "") == (MOUnitNo.ToUpper() ?? "")) // 單位相同
                {
                    dblStdQty = Conversions.ToDouble(MOQty);
                }
                else
                {
                    // 將CurQty轉換為產品標準單位之數量
                    udUnitTransferFunction.clsUnitTransferFunction objUnit;
                    var colParameters = new Collection();
                    colParameters.Add(ProductNo, "ProductNo");
                    colParameters.Add(ProductVersion, "ProductVersion");
                    colParameters.Add(ENGNo, "ENGNo");
                    colParameters.Add(ENGVersion, "ENGVersion");
                    objUnit = new udUnitTransferFunction.clsUnitTransferFunction();
                    dblStdQty = Conversions.ToDouble(objUnit.EXETransferQty(MOUnitNo, strStdUnitNo, Conversions.ToDouble(MOQty), colParameters));
                    objUnit = null;
                }
                decimal DecreaseRate = 0m;

                dsBOM = objPRD_M.ShowBOM(ProductNo, ProductVersion);
                var loopTo2 = dsBOM.Tables[0].Rows.Count - 1;
                for (int i = 0; i <= loopTo2; i++)
                {
                    drData = dtMOBom.NewRow();
                    drData["MONo"] = MONo;
                    drData["MaterialLevel"] = dsBOM.Tables[0].Rows[i]["NodeType"];
                    DecreaseRate = Conversions.ToDecimal(dsBOM.Tables[0].Rows[i]["DecreaseRate"]); // 取得耗損率

                    // 2008/06/17,sammi,投料點來自BOM表的設定.
                    drData["PutInPlaceType"] = dsBOM.Tables[0].Rows[i]["PutInPlaceType"];
                    if (Conversions.ToBoolean(Operators.ConditionalCompareObjectEqual(dsBOM.Tables[0].Rows[i]["NodeType"], 1, false))) // Product
                    {
                        drData["MOFlag"] = 0;
                        drData["MaterialMONo"] = MONo;
                        // NodeVersion,取出已轉換的產品版本.
                        drData["MaterialVersion"] = ProductVersion;
                    }
                    else // Material (NodeType = 0)
                    {
                        drData["MOFlag"] = 1;
                        drData["MaterialMONo"] = "N/A";
                        drData["MaterialVersion"] = dsBOM.Tables[0].Rows[i]["NodeVersion"];
                    }
                    drData["MaterialNo"] = dsBOM.Tables[0].Rows[i]["NodeNo"];
                    drData["SubstituteMaterialNo"] = dsBOM.Tables[0].Rows[i]["NodeNo"];  // 替代料,預設值同MaterialNo
                    drData["StdQty"] = dsBOM.Tables[0].Rows[i]["StdQty"];
                    drData["DecreaseRate"] = dsBOM.Tables[0].Rows[i]["DecreaseRate"];
                    drData["UnitNo"] = dsBOM.Tables[0].Rows[i]["UnitNo"];
                    drData["OPNo"] = dsBOM.Tables[0].Rows[i]["OPNo"];
                    drData["Specified"] = dsBOM.Tables[0].Rows[i]["Specified"];
                    drData["Description"] = Strings.Replace(dsBOM.Tables[0].Rows[i]["Description"].ToString(), "'", "''");
                    drData["SubstituteMaterialLevel"] = dsBOM.Tables[0].Rows[i]["NodeType"];  // 2012/12/27,Even,替代料等級，預設值為物料等級
                    drData["SubstituteStdQty"] = dsBOM.Tables[0].Rows[i]["StdQty"]; // 2012/12/28,Even,替代料標準數，預設值為 標準數
                    drData["RequireQty"] = Operators.MultiplyObject(Operators.MultiplyObject(MOQty, dsBOM.Tables[0].Rows[i]["StdQty"]), 1m + DecreaseRate);   // 2012/12/27,Even,需求數，預設值為工單數 * 標準數
                    drData["AB"] = dsBOM.Tables[0].Rows[i]["AB"].ToString();
                    drData["PositionCode"] = dsBOM.Tables[0].Rows[i]["PositionCode"].ToString();
                    dtMOBom.Rows.Add(drData);
                }

                dsBOM.Dispose();
                // Add MO之用料表
                dvTemp = new DataView(dtMOBom);
                dvTemp.RowFilter = Conversions.ToString("MONo='" + MONo + "'");

                var loopTo8 = dvTemp.Count - 1;
                for (int j = 0; j <= loopTo8; j++)
                {
                    DecreaseRate = Conversions.ToDecimal(dvTemp[j]["DecreaseRate"]);
                    decimal decRequireQty = Conversions.ToDecimal(Operators.MultiplyObject(Operators.MultiplyObject(MOQty, dvTemp[j]["StdQty"]), 1m + DecreaseRate));

                    // '2012/12/27,Even,改變需求數
                    dvTemp[j].BeginEdit();
                    // dvTemp.Table.Rows(j)("RequireQty") = dtMO.Rows(i)("MOQty") * dvTemp.Table.Rows(j)("StdQty") * (1 + DecreaseRate)
                    dvTemp[j]["RequireQty"] = decRequireQty;
                    dvTemp[j].EndEdit();

                    AddMOMaterialList(Conversions.ToString(MONo), Conversions.ToString(dvTemp[j]["MaterialNo"]), Conversions.ToInteger(dvTemp[j]["MaterialLevel"]), Conversions.ToDouble(dvTemp[j]["StdQty"]), Conversions.ToDouble(dvTemp[j]["DecreaseRate"]), Conversions.ToString(dvTemp[j]["OPNo"]), Conversions.ToInteger(dvTemp[j]["Specified"]), Conversions.ToInteger(dvTemp[j]["PutInPlaceType"]), Conversions.ToString(dvTemp[j]["UnitNo"]), Conversions.ToInteger(dvTemp[j]["MOFlag"]), Conversions.ToString(dvTemp[j]["MaterialMONo"]), dvTemp[j]["Description"].ToString(), CollectionSQL, MaterialVersion: Conversions.ToString(dvTemp[j]["MaterialVersion"]), SubstituteMaterialNo: Conversions.ToString(dvTemp[j]["MaterialNo"]), SubstituteMaterialLevel: Conversions.ToInteger(dvTemp[j]["SubstituteMaterialLevel"]), RequireQty: Conversions.ToDecimal(dvTemp[j]["RequireQty"]), SubstituteStdQty: Conversions.ToDecimal(dvTemp[j]["SubstituteStdQty"]), Creator: Creator, CreateDate: DateTime.Now, AB:Conversions.ToString(dvTemp[j]["AB"]), PositionCode:Conversions.ToString(dvTemp[j]["PositionCode"]));

                    // R1203001 不是指定用料及半成品時才處理替代料 By Acer 2012/03/06
                    if (Conversions.ToBoolean(Operators.ConditionalCompareObjectEqual(dvTemp[j]["Specified"], 0, false)) && Conversions.ToBoolean(Operators.ConditionalCompareObjectEqual(dvTemp[j]["MaterialLevel"], 0, false)))
                    {
                        var dsSubstitute = new DataSet();
                        if (objPRD_M.ShowBOMMaterialGroup(Conversions.ToString(ProductNo), Conversions.ToString(ProductVersion), Conversions.ToString(dvTemp[j]["MaterialNo"]), Conversions.ToString(dvTemp[j]["OPNo"])).Tables[0].Rows.Count > 0)
                        {
                            // 處理BOM表中指定的替代料
                            dsSubstitute = objPRD_M.ShowBOMMaterialGroup(Conversions.ToString(ProductNo), Conversions.ToString(ProductVersion), Conversions.ToString(dvTemp[j]["MaterialNo"]), Conversions.ToString(dvTemp[j]["OPNo"]));
                        }
                        else
                        {
                            // 處理物料群組中指定的替代料
                            dsSubstitute = objMTL.ShowMaterialSubstitute(Conversions.ToString(dvTemp[j]["MaterialNo"]));
                        }

                        var loopTo9 = dsSubstitute.Tables[0].Rows.Count - 1;
                        for (int k = 0; k <= loopTo9; k++)
                        {
                            // 2012/12/27,Even,處裡替代用料的需求數量，有替代用料，用料清單會除原先清單外再加上替代用料清單
                            decimal dblRequireQty = 0m * (1m + DecreaseRate);

                            AddMOMaterialList(Conversions.ToString(MONo), Conversions.ToString(dvTemp[j]["MaterialNo"]), Conversions.ToInteger(dvTemp[j]["MaterialLevel"]), Conversions.ToDouble(dvTemp[j]["StdQty"]), Conversions.ToDouble(dvTemp[j]["DecreaseRate"]), Conversions.ToString(dvTemp[j]["OPNo"]), Conversions.ToInteger(dvTemp[j]["Specified"]), Conversions.ToInteger(dvTemp[j]["PutInPlaceType"]), Conversions.ToString(dvTemp[j]["UnitNo"]), Conversions.ToInteger(dvTemp[j]["MOFlag"]), Conversions.ToString(dvTemp[j]["MaterialMONo"]), dvTemp[j]["Description"].ToString(), CollectionSQL, MaterialVersion: Conversions.ToString(dvTemp[j]["MaterialVersion"]), SubstituteMaterialNo: dsSubstitute.Tables[0].Rows[k]["MaterialNo"].ToString(), SubstituteMaterialLevel: Conversions.ToInteger(dvTemp[j]["SubstituteMaterialLevel"]), RequireQty: dblRequireQty, SubstituteStdQty: Conversions.ToDecimal(dvTemp[j]["SubstituteStdQty"]), Creator: Creator, CreateDate: DateTime.Now, AB: Conversions.ToString(dvTemp[j]["AB"]), PositionCode: Conversions.ToString(dvTemp[j]["PositionCode"]));

                        }
                        dsSubstitute = null;
                    }

                }
                #region"注释原收用料清单逻辑 继承 PRDBOM"

                //if (dtMTL.Rows.Count > 0)
                //{
                //    bool blnWF = false;
                //    //2023/12/07,Ning,151196: [6.0.7] SDD231107_01-01_WF 工單整合接口調整
                //    //取得目前ERP是否為WF
                //    using (var objSYSPar = new kcSYS.clsSYSParameter())
                //    {
                //        var dsTemp = new DataSet();
                //        dsTemp = objSYSPar.ShowERPSetting(ActiveERP: 1);
                //        if (dsTemp != null && dsTemp.Tables[0].Rows.Count > 0)
                //        {
                //            if (dsTemp.Tables[0].Rows[0]["ERP_Name"].ToString().ToUpper() == "WORKFLOW")
                //            {
                //                blnWF = true;
                //            }
                //        }
                //    }

                //    dtMTL.Columns.Add("MaterialMONo", Type.GetType("System.String"));
                //    // dtMTL: MONo, MaterialNo, MaterialLevel, StdQty, UnitNo, OPNo, PutInPlaceType, DecreaseRate, Specified, *MaterialType, CountWay, *CheckLotNo, *MaterialVersion, +MaterialMONo, +*SubstituteMaterialNo

                //    foreach (DataRow dr in dtMTL.Rows)
                //    {
                //        string strMaterialUnit = dr["UnitNo"].ToString();
                //        decimal decTemp = 0m;
                //        try
                //        {
                //            if (string.IsNullOrEmpty(dr["MainItem"].ToString()))
                //            {
                //                // 未傳入
                //                clsERP.combineException(ref aryException, mesmsg: "[%MainItem%]");
                //            }

                //            //if (string.IsNullOrEmpty(dr["PhantomItem"].ToString()))
                //            //{
                //            //    // 未傳入
                //            //    clsERP.combineException(ref aryException, mesmsg: "[%PhantomItem%]");
                //            //}

                //            if (string.IsNullOrEmpty(dr["LockRequirement"].ToString()))
                //            {
                //                // 未傳入
                //                clsERP.combineException(ref aryException, mesmsg: "[%LockRequirement%]");
                //            }

                //            if (string.IsNullOrEmpty(dr["OperationSeqnum"].ToString()))
                //            {
                //                // 未傳入
                //                clsERP.combineException(ref aryException, mesmsg: "[%OperationSeqnum%]");
                //            }

                //            if (blnWF == true)
                //            {
                //                if (Conversions.ToInteger(dr["StdQty"]) != Convert.ToDecimal(dr["StdQty"]))           //若標準用量有小數, 需以ERP所傳入的該物料的需領用量(RequireQty)/預計產量(MOQty)，並以無條件捨去取到小數六位數的值，做為該物料的標準用量
                //                {
                //                    decTemp = (Convert.ToDecimal(dr["RequireQty"]) / MOQty) * 1000000;
                //                    decTemp = Math.Floor(decTemp);
                //                    decTemp = decTemp / 1000000;
                //                    dr["StdQty"] = decTemp;
                //                }
                //                if (Conversions.ToInteger(dr["SubstituteStdQty"]) != Convert.ToDecimal(dr["SubstituteStdQty"]))           //若替代料標準用量有小數同標準用量處理
                //                {
                //                    decTemp = (Convert.ToDecimal(dr["RequireQty"]) / MOQty) * 1000000;
                //                    decTemp = Math.Floor(decTemp);
                //                    decTemp = decTemp / 1000000;
                //                    dr["SubstituteStdQty"] = decTemp;
                //                }
                //            }
                //            if (dr["MaterialLevel"].ToString() == "0")
                //            {
                //                // 用料清單為物料
                //                using (var objMTL = new clsMTLBasis())
                //                {
                //                    DataRow drMTL = null;
                //                    bool errorFlag = false;

                //                    dr["MONo"] = dr["MONo"].ToString().ToUpper();

                //                    drMTL = objMTL.GetMaterialBasis(dr["MaterialNo"].ToString().ToUpper());
                //                    // (skip) MONo, MaterialLevel, STDQty, DecreaseRate, OPNo, Specified, PutinPlaceType, MOFlag, CountWay, Description, OrgMaterialNo, EX_MTLList1, EX_MTLList2, MaterialVersion

                //                    // MaterialNo
                //                    if (drMTL["MaterialNo"] is DBNull == true)
                //                    {
                //                        errorFlag = true;
                //                        clsERP.combineException(ref aryException, mesmsg: " [%MaterialNo%]:" +
                //                            dr["MaterialNo"] + " [%MaterialNoNotExist%][%InMESSystem%]! [%MaterialLevel%][%IsMaterial%].");
                //                        goto SkipMaterialList;
                //                    }
                //                    else
                //                    {
                //                        dr["MaterialNo"] = dr["MaterialNo"].ToString().ToUpper();
                //                    }

                //                    // UnitNo
                //                    if (drMTL["UnitNo"].ToString().ToLower() != strMaterialUnit.ToLower())
                //                    {
                //                        // 當用料清單和物料主檔的單位不同時
                //                        // 單位轉換
                //                        using (var objUnit = new udUnitTransferFunction.clsUnitTransferFunction())
                //                        {
                //                            var colParameters = new Collection();
                //                            colParameters.Add(dr["MaterialNo"].ToString().ToUpper(), "ProductNo");
                //                            colParameters.Add("*", "ProductVersion");

                //                            try
                //                            {
                //                                dr["StdQty"] = Convert.ToDouble(objUnit.EXETransferQty(strMaterialUnit.ToLower(), drMTL["UnitNo"].ToString().ToLower(), Convert.ToDouble(dr["StdQty"]), colParameters));
                //                                dr["SubstituteStdQty"] = Convert.ToDouble(objUnit.EXETransferQty(strMaterialUnit.ToLower(), drMTL["UnitNo"].ToString().ToLower(), Convert.ToDouble(dr["SubstituteStdQty"]), colParameters));

                //                                dr["UnitNo"] = drMTL["UnitNo"].ToString().ToLower();
                //                            }
                //                            catch (Exception ex)
                //                            {
                //                                errorFlag = true;
                //                                clsERP.combineException(ref aryException, mesmsg: "[%MaterialListUnitNoDifferent%]" + " [%MaterialNo%]:" +
                //                                    dr["MaterialNo"]);
                //                                clsERP.combineException(ref aryException, mesmsg: "[%MaterialListUnitTransferFail%]" + " " + ex.Message);
                //                            }
                //                        }
                //                    }
                //                    else
                //                    {
                //                        dr["UnitNo"] = dr["UnitNo"].ToString().ToLower();
                //                    }

                //                    // MaterialMONo (Default)
                //                    dr["MaterialMONo"] = "N/A";

                //                    // MaterialType
                //                    if (dr["MaterialType"] is DBNull == true)
                //                    {
                //                        dr["MaterialType"] = drMTL["MaterialType"];
                //                    }
                //                    else if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(dr["MaterialType"].ToString().ToUpper(), drMTL["MaterialType"], false)))
                //                    {
                //                        dr["MaterialType"] = dr["MaterialType"].ToString().ToUpper();
                //                    }
                //                    else
                //                    {
                //                        clsERP.combineException(ref aryException, mesmsg: "[%MaterialListMaterialTypeDifferent%]" + " [%MaterialNo%]:" +
                //                            dr["MaterialNo"]);
                //                    }

                //                    // CheckLotNo
                //                    if (dr["CheckLotNo"] is DBNull == true)
                //                    {
                //                        dr["CheckLotNo"] = drMTL["CheckLotNo"];
                //                    }
                //                    else if (Convert.ToBoolean(Operators.ConditionalCompareObjectNotEqual(dr["CheckLotNo"], drMTL["CheckLotNo"], false)))
                //                    {
                //                        clsERP.combineException(ref aryException, mesmsg: "[%MaterialListCheckLotNoDifferent%]" + " [%MaterialNo%]:" +
                //                            dr["MaterialNo"]);
                //                    }

                //                    // 2013/02/20,Even,修改替代料檢查
                //                    if (dr["SubstituteMaterialNo"] is DBNull == true)
                //                    {
                //                        dr["SubstituteMaterialNo"] = dr["MaterialNo"];
                //                        dr["SubstituteMaterialLevel"] = dr["MaterialLevel"];
                //                    }
                //                    // 2013/02/25,Even,判斷替代料，替代料可為半成品或是物料
                //                    else if (dr["SubstituteMaterialLevel"].ToString() == "0") // 為物料
                //                    {
                //                        // 查詢替代料是否在物料主檔內，若無，則出現錯誤訊息
                //                        drMTL = objMTL.GetMaterialBasis(dr["SubstituteMaterialNo"].ToString().ToUpper());
                //                        if (drMTL["MaterialNo"] is DBNull == true)
                //                        {
                //                            errorFlag = true;
                //                            clsERP.combineException(ref aryException, mesmsg: " [%SubstituteMaterialNo%]:" +
                //                                dr["SubstituteMaterialNo"] + " [%MaterialNoNotExist%][%InMESSystem%]! [%SubstituteMaterialLevel%][%IsMaterial%].");
                //                            goto SkipMaterialList;
                //                        }
                //                        else
                //                        {
                //                            dr["SubstituteMaterialNo"] = dr["SubstituteMaterialNo"].ToString().ToUpper();
                //                        }
                //                    }
                //                    else // 為半成品 (SubstituteMaterialLevel = 1)
                //                    {
                //                        DataRow drPRD = null;
                //                        // 檢查物料是否存在於產品主檔
                //                        using (var objPRD = new clsProduct())
                //                        {
                //                            drPRD = objPRD.GetProduct(dr["SubstituteMaterialNo"].ToString().ToUpper());
                //                        }
                //                        if (drPRD["ProductNo"] is DBNull == true)
                //                        {
                //                            errorFlag = true;
                //                            clsERP.combineException(ref aryException, mesmsg: " [%SubstituteMaterialNo%]:" +
                //                                dr["SubstituteMaterialNo"] + " [%ProductNoNotExist%][%InMESSystem%]! [%SubstituteMaterialLevel%][%IsProduct%].");
                //                            goto SkipMaterialList;
                //                        }
                //                        else
                //                        {
                //                            dr["SubstituteMaterialNo"] = dr["SubstituteMaterialNo"].ToString().ToUpper();
                //                        }
                //                    }

                //                    if (dr["SubstituteStdQty"] is DBNull == true)
                //                    {
                //                        dr["SubstituteStdQty"] = dr["StdQty"];
                //                    }

                //                    // 2019/12/16 OwenLiu, Mantis:0065576 , 工單整合(新增)時用料需求數支援單位轉換
                //                    decimal decRequireQty = 0m;
                //                    if (dr["RequireQty"] is DBNull == true)
                //                    {
                //                        // ERP未傳入需求數(RequireQty)
                //                        // 2019/12/23 OwenLiu, Mantis:0065953 修正工單整合 用料清單單位轉換的問題
                //                        dr["RequireQty"] = Operators.MultiplyObject(Operators.MultiplyObject(MOQty, dr["StdQty"]), Operators.AddObject(1, dr["DecreaseRate"]));
                //                    }
                //                    else
                //                    {
                //                        decRequireQty = Convert.ToDecimal(dr["RequireQty"]);
                //                        // 2019/12/23 OwenLiu, Mantis:0065953 修正工單整合 用料清單單位轉換的問題
                //                        if (drMTL["UnitNo"].ToString().ToLower() != strMaterialUnit.ToLower())
                //                        {
                //                            // 當用料清單和物料主檔的單位不同時
                //                            using (var objUnit = new udUnitTransferFunction.clsUnitTransferFunction())
                //                            {
                //                                var colParameters = new Collection();
                //                                colParameters.Add(dr["MaterialNo"].ToString().ToUpper(), "ProductNo");
                //                                colParameters.Add("*", "ProductVersion");
                //                                try
                //                                {
                //                                    dr["RequireQty"] = Convert.ToDouble(objUnit.EXETransferQty(strMaterialUnit.ToLower(), drMTL["UnitNo"].ToString().ToLower(), (double)decRequireQty, colParameters));
                //                                }
                //                                catch (Exception ex)
                //                                {
                //                                    errorFlag = true;
                //                                    clsERP.combineException(ref aryException, mesmsg: "[%MaterialListUnitNoDifferent%]" + " [%MaterialNo%]:" +
                //                                        dr["MaterialNo"]);
                //                                    clsERP.combineException(ref aryException, mesmsg: "[%MaterialListUnitTransferFail%]" + " " + ex.Message);
                //                                }
                //                            }
                //                        }
                //                        else
                //                        {
                //                            dr["RequireQty"] = decRequireQty;
                //                        }
                //                    }

                //                    // 檢查OPNo(用料作業站)是否存在 -----
                //                    if (dr["OPNo"].ToString().ToUpper() != "LOTCREATE")
                //                    {
                //                        // 有傳入=>檢查OP主檔
                //                        using (var objOP = new clsOpBasis())
                //                        {
                //                            var drOP = objOP.GetOPBasis(dr["OPNo"].ToString().ToUpper());
                //                            if (drOP["OPNo"] is DBNull == true)
                //                            {
                //                                // OP主檔未建立
                //                                clsERP.combineException(ref aryException, mesmsg: "[%MaterialNo%]:" +
                //                                    dr["MaterialNo"] + " [%OPNoNotExist%](" + dr["OPNo"] + ")");
                //                            }
                //                        }
                //                    }

                //                }
                //            }
                //            else
                //            {
                //                // 用料清單為半成品
                //                using (var objPRD = new clsProduct())
                //                {
                //                    DataRow drPRD = null;
                //                    bool errorFlag = false;

                //                    dr["MONo"] = dr["MONo"].ToString().ToUpper();

                //                    drPRD = objPRD.GetProduct(dr["MaterialNo"].ToString().ToUpper());
                //                    // (skip) MONo, MaterialLevel, STDQty, DecreaseRate, OPNo, Specified, PutinPlaceType, MOFlag, CountWay, Description, OrgMaterialNo, EX_MTLList1, EX_MTLList2, MaterialVersion

                //                    // MaterialNo
                //                    if (drPRD["ProductNo"] is DBNull == true)
                //                    {
                //                        errorFlag = true;
                //                        clsERP.combineException(ref aryException, mesmsg: " [%MaterialNo%]:" +
                //                            dr["MaterialNo"] + " [%ProductNoNotExist%][%InMESSystem%]! [%MaterialLevel%][%IsProduct%].");
                //                        goto SkipMaterialList;
                //                    }
                //                    else
                //                    {
                //                        dr["MaterialNo"] = dr["MaterialNo"].ToString().ToUpper();
                //                    }

                //                    // UnitNo
                //                    if (drPRD["UnitNo"].ToString().ToLower() != strMaterialUnit.ToLower())
                //                    {
                //                        // 當用料清單和物料主檔的單位不同時
                //                        // 單位轉換
                //                        using (var objUnit = new udUnitTransferFunction.clsUnitTransferFunction())
                //                        {
                //                            var colParameters = new Collection();
                //                            colParameters.Add(dr["MaterialNo"].ToString().ToUpper(), "ProductNo");
                //                            colParameters.Add("*", "ProductVersion");

                //                            try
                //                            {

                //                                dr["StdQty"] = Convert.ToDouble(objUnit.EXETransferQty(strMaterialUnit.ToLower(), drPRD["UnitNo"].ToString().ToLower(), Convert.ToDouble(dr["StdQty"]), colParameters));
                //                                dr["SubstituteStdQty"] = Convert.ToDouble(objUnit.EXETransferQty(strMaterialUnit.ToLower(), drPRD["UnitNo"].ToString().ToLower(), Convert.ToDouble(dr["SubstituteStdQty"]), colParameters));

                //                                dr["UnitNo"] = drPRD["UnitNo"].ToString().ToLower();
                //                            }
                //                            catch (Exception ex)
                //                            {
                //                                errorFlag = true;
                //                                clsERP.combineException(ref aryException, mesmsg: "[%MaterialListUnitNoDifferent%]" + " [%MaterialNo%]:" +
                //                                    dr["MaterialNo"]);
                //                                clsERP.combineException(ref aryException, mesmsg: "[%MaterialListUnitTransferFail%]" + " " + ex.Message);
                //                            }
                //                        }
                //                    }
                //                    else
                //                    {
                //                        dr["UnitNo"] = dr["UnitNo"].ToString().ToLower();
                //                    }

                //                    // MaterialMONo (Default)
                //                    dr["MaterialMONo"] = "N/A";

                //                    // MaterialType
                //                    if (dr["MaterialType"] is DBNull == true)
                //                    {
                //                        dr["MaterialType"] = drPRD["ProductType"];
                //                    }
                //                    else if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(dr["MaterialType"].ToString().ToUpper(), drPRD["ProductType"], false)))
                //                    {
                //                        dr["MaterialType"] = dr["MaterialType"].ToString().ToUpper();
                //                    }
                //                    else
                //                    {
                //                        clsERP.combineException(ref aryException, mesmsg: "[%MaterialListMaterialTypeDifferent%]" + " [%MaterialNo%]:" +
                //                            dr["MaterialNo"]);
                //                    }

                //                    // CheckLotNo
                //                    dr["CheckLotNo"] = 1;    // 半成品固定為1

                //                    // SubstituteMaterialNo
                //                    // ---2013/02/20,Even,替代料是否存在的檢查----
                //                    if (dr["SubstituteMaterialNo"] is DBNull == true)
                //                    {
                //                        dr["SubstituteMaterialNo"] = dr["MaterialNo"];
                //                        dr["SubstituteMaterialLevel"] = dr["MaterialLevel"];
                //                    }
                //                    else
                //                    {
                //                        DataRow drMTL = null;
                //                        // 2013/02/25,Even,判斷替代料，替代料可為半成品或是物料
                //                        if (dr["SubstituteMaterialLevel"].ToString() == "0") // 為物料
                //                        {
                //                            // 查詢替代料是否在物料主檔內，若無，則出現錯誤訊息
                //                            using (var objMTL = new clsMTLBasis())
                //                            {
                //                                drMTL = objMTL.GetMaterialBasis(dr["SubstituteMaterialNo"].ToString().ToUpper());
                //                            }

                //                            if (drMTL["MaterialNo"] is DBNull == true)
                //                            {
                //                                errorFlag = true;
                //                                clsERP.combineException(ref aryException, mesmsg: " [%SubstituteMaterialNo%]:" +
                //                                    dr["SubstituteMaterialNo"] + " [%MaterialNoNotExist%][%InMESSystem%]! [%SubstituteMaterialLevel%][%IsMaterial%].");
                //                                goto SkipMaterialList;
                //                            }
                //                            else
                //                            {
                //                                dr["SubstituteMaterialNo"] = dr["SubstituteMaterialNo"].ToString().ToUpper();
                //                            }
                //                        }
                //                        else // 為半成品 (SubstituteMaterialLevel = 1)
                //                        {
                //                            // 檢查物料是否存在於產品主檔
                //                            drPRD = objPRD.GetProduct(dr["SubstituteMaterialNo"].ToString().ToUpper());
                //                            if (drPRD["ProductNo"] is DBNull == true)
                //                            {
                //                                errorFlag = true;
                //                                clsERP.combineException(ref aryException, mesmsg: " [%SubstituteMaterialNo%]:" +
                //                                    dr["SubstituteMaterialNo"] + " [%ProductNoNotExist%][%InMESSystem%]! [%SubstituteMaterialLevel%][%IsProduct%].");
                //                                goto SkipMaterialList;
                //                            }
                //                            else
                //                            {
                //                                dr["SubstituteMaterialNo"] = dr["SubstituteMaterialNo"].ToString().ToUpper();
                //                            }
                //                        }
                //                    }

                //                    if (dr["SubstituteStdQty"] is DBNull == true)
                //                    {
                //                        dr["SubstituteStdQty"] = dr["StdQty"];
                //                    }


                //                    // 2019/12/16 OwenLiu, Mantis:0065576 , 工單整合(新增)時用料需求數支援單位轉換
                //                    decimal decRequireQty = 0m;
                //                    if (dr["RequireQty"] is DBNull == true)
                //                    {
                //                        // ERP未傳入需求數(RequireQty)
                //                        // 2019/12/23 OwenLiu, Mantis:0065953 修正工單整合 用料清單單位轉換的問題
                //                        dr["RequireQty"] = Operators.MultiplyObject(Operators.MultiplyObject(MOQty, dr["StdQty"]), Operators.AddObject(1, dr["DecreaseRate"]));
                //                    }
                //                    else
                //                    {
                //                        decRequireQty = Convert.ToDecimal(dr["RequireQty"]);
                //                        // 2019/12/23 OwenLiu, Mantis:0065953 修正工單整合 用料清單單位轉換的問題
                //                        if (drPRD["UnitNo"].ToString().ToLower() != strMaterialUnit.ToLower())
                //                        {
                //                            // 當用料清單和產品主檔的單位不同時
                //                            using (var objUnit = new udUnitTransferFunction.clsUnitTransferFunction())
                //                            {
                //                                var colParameters = new Collection();
                //                                colParameters.Add(dr["MaterialNo"].ToString().ToUpper(), "ProductNo");
                //                                colParameters.Add("*", "ProductVersion");
                //                                try
                //                                {
                //                                    dr["RequireQty"] = Convert.ToDouble(objUnit.EXETransferQty(strMaterialUnit.ToLower(), drPRD["UnitNo"].ToString().ToLower(), (double)decRequireQty, colParameters));
                //                                }
                //                                catch (Exception ex)
                //                                {
                //                                    errorFlag = true;
                //                                    clsERP.combineException(ref aryException, mesmsg: "[%MaterialListUnitNoDifferent%]" + " [%MaterialNo%]:" +
                //                                        dr["MaterialNo"]);
                //                                    clsERP.combineException(ref aryException, mesmsg: "[%MaterialListUnitTransferFail%]" + " " + ex.Message);
                //                                }
                //                            }
                //                        }
                //                        else
                //                        {
                //                            dr["RequireQty"] = decRequireQty;
                //                        }
                //                    }

                //                    // 檢查OPNo(用料作業站)是否存在 -----
                //                    if (dr["OPNo"].ToString().ToUpper() != "LOTCREATE")
                //                    {
                //                        // 有傳入=>檢查OP主檔
                //                        using (var objOP = new clsOpBasis())
                //                        {
                //                            var drOP = objOP.GetOPBasis(dr["OPNo"].ToString().ToUpper());
                //                            if (drOP["OPNo"] is DBNull == true)
                //                            {
                //                                // OP主檔未建立
                //                                clsERP.combineException(ref aryException, mesmsg: "[%MaterialNo%]:" +
                //                                    dr["MaterialNo"] + " [%OPNoNotExist%](" + dr["OPNo"] + ")");
                //                            }
                //                        }
                //                    }
                //                }
                //            }

                //            SkipMaterialList:
                //            ;
                //        }

                //        catch (Exception ex)
                //        {
                //            clsERP.combineException(ref aryException, sysmsg: ex.Message, mesmsg: "[%doMaterialListFail%]", stack: iMESCore.Base.iMESComXML.CInput(ex.StackTrace));
                //        }
                //    }
                //}
                #endregion

                // ----- 8. 檢查FactoryNo -----
                // FactoryNo = "N/A"
                List<ArrayList> argstrMessage = null;
                List<ArrayList> argstrException = null;
                doFactoryNo(FactoryNo, Creator, CreateDate, strMessage: argstrMessage, strException: argstrException);

                // ----- 9. 檢查MO Property ---
                if (!(dtMOProperty == null) && dtMOProperty.Rows.Count > 0)
                {
                    foreach (DataRow dr in dtMOProperty.Rows)
                    {
                        List<ArrayList> argaryMessage = null;
                        List<ArrayList> argaryException = null;
                        doSYSMOProperty(Convert.ToString(dr["PropertyNo"]), Convert.ToString(dr["DataType"]), aryMessage: argaryMessage, aryException: argaryException);
                    }
                }

                // ----- Exception => Fail -----
                if (aryException.Count > 0)
                    goto exitfun;

                // ----- Add MO -----
                // Dim objLic As New iMESLicxManager.clsDBCom
                // Using cn As New OleDbConnection(objSetting.GetConnectionString)
                // Using cmd As New OleDbCommand("", cn)
                // cn.Open()
                // Using trans As OleDbTransaction = cn.BeginTransaction
                // cmd.Transaction = trans
                try
                {

                    if (string.IsNullOrEmpty(RONo) == false)
                    {
                        var objOE = new clsOEBasis();
                        // 檢查訂單是否已存在
                        var dr = objOE.GetROBasis(RONo.ToUpper());
                        if (dr["RONo"] is DBNull == false)
                            isROExist = true;

                        // 檢查訂單明細是否已存在
                        // 若訂單號碼有傳入，此項目應一併傳入，若未傳入則預設為1
                        if (string.IsNullOrEmpty(ItemNo))
                            ItemNo = "1";
                        dr = objOE.GetRODetail(RONo.ToUpper(), Convert.ToDecimal(ItemNo.ToUpper()));
                        if (dr["ItemNo"] is DBNull == false)
                        {
                            isRODetailExist = true;
                        }

                        // ----- RO -----
                        if (isROExist == false)
                        {
                            // add ROBasis
                            strSQL = "insert into tbloerobasis(rono,customerno,creator,createdate,issuestate,rostate) values('" + RONo.ToUpper() + "','" + CustomerNo.ToUpper() + "','" + Creator + "',To_Date('" + Strings.Format(CreateDate, "yyyy/MM/dd H:mm:ss") + "','YYYY/MM/DD HH24:MI:SS'),2,2)";
                            CollectionSQL.Add(strSQL);
                            // cmd.CommandText = _
                            // "insert into tbloerobasis(rono,customerno,description,creator,createdate,issuestate,lotserial,rostate) values(?,?,?,?,?,?,?,?)"
                            // cmd.Parameters.AddWithValue(":RONo", RONo.ToUpper)
                            // cmd.Parameters.AddWithValue(":CustomerNo", CustomerNo.ToUpper)
                            // cmd.Parameters.AddWithValue(":Description", DBNull.Value)
                            // cmd.Parameters.AddWithValue(":Creator", Creator)
                            // cmd.Parameters.AddWithValue(":CreateDate", CreateDate)
                            // cmd.Parameters.AddWithValue(":IssueState", 2)
                            // cmd.Parameters.AddWithValue(":LotSerial", DBNull.Value)
                            // cmd.Parameters.AddWithValue(":ROState", 2)
                            // cmd.ExecuteNonQuery()
                            // cmd.Parameters.Clear()
                        }

                        switch (isRODetailExist)
                        {
                            case true:
                                {
                                    // update RODetail
                                    strSQL = "update tbloerodetail set orderqty=orderqty+" + MOQty + ", unreleaseqty=unreleaseqty+" + MOQty;
                                    strSQL += "where RONO='" + RONo.ToUpper() + "' and ItemNo=" + ItemNo.ToUpper();
                                    break;
                                }
                            // Gary Lu 20130307:原本無Where條件，不修正會使得TBLOERODETAIL內其他訂單明細也受到影響
                            // cmd.CommandText = _
                            // "update tbloerodetail set orderqty=orderqty+?, unreleaseqty=unreleaseqty+?"
                            // cmd.Parameters.AddWithValue(":OrderQty", MOQty)
                            // cmd.Parameters.AddWithValue(":UnReleaseQty", MOQty)
                            case false:
                                {
                                    // add RODetail
                                    strSQL = "insert into tbloerodetail(rono,itemno,productno,orderqty,unreleaseqty,creator,createdate,rounitno,customerno,customername) " + "values('" + RONo.ToUpper() + "'," + ItemNo + ",'" + ProductNo.ToUpper() + "'," + MOQty + "," + MOQty + ",'" + Creator + "',To_Date('" + Strings.Format(CreateDate, "yyyy/MM/dd H:mm:ss") + "','YYYY/MM/DD HH24:MI:SS'),'" + MOUnitNo.ToLower() + "','" + CustomerNo.ToUpper() + "','" + ChkSingleQuation(CustomerName) + "')";
                                    break;
                                }
                                // cmd.CommandText = _
                                // "insert into tbloerodetail(rono,itemno,productno,orderqty,unreleaseqty,description,creator,createdate,rounitno,customerno,customername) " & _
                                // "values(?,?,?,?,?,?,?,?,?,?,?)"
                                // cmd.Parameters.AddWithValue(":RONo", RONo.ToUpper)
                                // cmd.Parameters.AddWithValue(":ItemNo", ItemNo)
                                // cmd.Parameters.AddWithValue(":ProductNo", ProductNo.ToUpper)
                                // cmd.Parameters.AddWithValue(":OrderQty", MOQty)
                                // cmd.Parameters.AddWithValue(":UnReleaseQty", MOQty)
                                // cmd.Parameters.AddWithValue(":Description", DBNull.Value)
                                // cmd.Parameters.AddWithValue(":Creator", Creator)
                                // cmd.Parameters.AddWithValue(":CreateDate", CreateDate)
                                // cmd.Parameters.AddWithValue(":ROUnitNo", MOUnitNo.ToLower)
                                // cmd.Parameters.AddWithValue(":CustomerNo", CustomerNo.ToUpper)
                                // cmd.Parameters.AddWithValue(":CustomerName", CustomerName)
                        }
                        CollectionSQL.Add(strSQL);
                        // cmd.ExecuteNonQuery()
                        // cmd.Parameters.Clear()
                    }

                    // ----- MO -----

                    // 2019/08/16 Mantis60378: 新增FromERP欄位, 若來自EAI整合(TT、WF、T100),需填入1
                    // add MO Basis
                    strSQLAddField = "insert into tblOEMOBasis(mono,mostate,moqty,productno,productversion,priority,planfinishdate," + "belongtomono,description,creator,createdate,issuestate,unreleaselotqty,mounitno,motypeno,mosource,engno,engversion,customerno,factoryno" + ", FromERP,wipEntityId,bomVersion,lcPlantype,faiFlag";
                    strSQLAddValue = "values('" + MONo.ToUpper() + "'," + MOState + "," + MOQty + ",'" + ProductNo.ToUpper() + "','" + ProductVersion.ToUpper() + "'," + Priority + ",To_Date('" + Strings.Format(PlanFinishDate, "yyyy/MM/dd H:mm:ss") + "','YYYY/MM/DD HH24:MI:SS'),'" + BelongToMONo + "','" + Description + "','" + Creator + "',To_Date('" + Strings.Format(CreateDate, "yyyy/MM/dd H:mm:ss") + "','YYYY/MM/DD HH24:MI:SS')," + IssueState + "," + MOQty + ",'" + MOUnitNo.ToLower() + "'," + MOTypeNo + "," + MOSource + ",'" + ENGNo + "','" + ENGVersion + "','" + CustomerNo.ToUpper() + "','" + FactoryNo + "'," + "1," + wipEntityId + ",'" + bomVersion + "','" + lcPlantype + "','" + faiFlag + "'";
                    if (string.IsNullOrEmpty(RONo) == true)
                    {
                        strSQLAddField += ",rono";
                        strSQLAddValue += ",'N/A'";
                    }
                    else
                    {
                        strSQLAddField += ",rono";
                        strSQLAddValue += ",'" + RONo.ToUpper() + "'";
                    }
                    if (string.IsNullOrEmpty(Orgcode) == true)
                    {
                        strSQLAddField += ",Orgcode";
                        strSQLAddValue += ",'N/A'";
                    }
                    else
                    {
                        strSQLAddField += ",Orgcode";
                        strSQLAddValue += ",'" + Orgcode + "'";
                    }
                    if (string.IsNullOrEmpty(OrgMono) == true)
                    {
                        strSQLAddField += ",OrgMono";
                        strSQLAddValue += ",'N/A'";
                    }
                    else
                    {
                        strSQLAddField += ",OrgMono";
                        strSQLAddValue += ",'" + OrgMono + "'";
                    }
                    
                    if (string.IsNullOrEmpty(ItemNo) == true)
                    {
                        strSQLAddField += ",itemno";
                        strSQLAddValue += ",-1";
                    }
                    else
                    {
                        strSQLAddField += ",itemno";
                        strSQLAddValue += "," + ItemNo;
                    }
                    if (!string.IsNullOrEmpty(CustomerLotNo))
                    {
                        strSQLAddField += ",customerlotno";
                        strSQLAddValue += ",'" + CustomerLotNo + "'";
                    }

                    // 2018/3/19 Vick 新增欄位 ERPMOLineNo
                    if (ERPMOLineNo != defString)
                    {
                        strSQLAddField += ",ERPMOLineNo";
                        strSQLAddValue += ",'" + ERPMOLineNo + "'";
                    }

                    if (PlanStartDate != default(DateTime))
                    {
                        strSQLAddField += ",PlanStartDate";
                        strSQLAddValue += ", To_Date('" + Strings.Format(PlanStartDate, "yyyy/MM/dd H:mm:ss") + "','YYYY/MM/DD HH24:MI:SS')";
                    }

                    strSQL = strSQLAddField + ")" + strSQLAddValue + ")";
                    CollectionSQL.Add(strSQL);
                    // cmd.CommandText = _
                    // "insert into tbloemobasis(mono,rono,itemno,mostate,moqty,productno,productversion,priority,planfinishdate,belongtomono,description,creator,createdate," & _
                    // "issuestate,unreleaselotqty,mounitno,lotserial,motypeno,mosource,engno,engversion,customerno,incomingkey,customerlotno,factoryno) " & _
                    // "values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
                    // cmd.Parameters.AddWithValue(":MONo", MONo.ToUpper)
                    // If String.IsNullOrEmpty(RONo) = True)
                    // cmd.Parameters.AddWithValue(":RONo", "N/A")
                    // Else
                    // cmd.Parameters.AddWithValue(":RONo", RONo.ToUpper)
                    // End If
                    // If String.IsNullOrEmpty(ItemNo) = True)
                    // cmd.Parameters.AddWithValue(":ItemNo", -1)
                    // Else
                    // cmd.Parameters.AddWithValue(":ItemNo", ItemNo)
                    // End If
                    // cmd.Parameters.AddWithValue(":MOState", MOState)
                    // cmd.Parameters.AddWithValue(":MOQty", MOQty)
                    // cmd.Parameters.AddWithValue(":ProductNo", ProductNo.ToUpper)
                    // cmd.Parameters.AddWithValue(":ProductVersion", ProductVersion.ToUpper)
                    // cmd.Parameters.AddWithValue(":Priority", Priority)
                    // cmd.Parameters.AddWithValue(":PlanFinishDate", PlanFinishDate)
                    // cmd.Parameters.AddWithValue(":BelongToMONo", BelongToMONo)
                    // cmd.Parameters.AddWithValue(":Description", Description)
                    // cmd.Parameters.AddWithValue(":Creator", Creator)
                    // cmd.Parameters.AddWithValue(":CreateDate", CreateDate)
                    // cmd.Parameters.AddWithValue(":IssueState", IssueState)
                    // cmd.Parameters.AddWithValue(":UnReleaseLotQty", MOQty)
                    // cmd.Parameters.AddWithValue(":MOUnitNo", MOUnitNo.ToLower)
                    // cmd.Parameters.AddWithValue(":LotSerial", DBNull.Value)
                    // cmd.Parameters.AddWithValue(":MOTypeNo", MOTypeNo)
                    // cmd.Parameters.AddWithValue(":MOSource", MOSource)
                    // cmd.Parameters.AddWithValue(":EngNo", ENGNo)
                    // cmd.Parameters.AddWithValue(":EngVersion", ENGVersion)
                    // cmd.Parameters.AddWithValue(":CustomerNo", CustomerNo.ToUpper)
                    // cmd.Parameters.AddWithValue(":IncomingKey", DBNull.Value)
                    // If CustomerLotNo = String.Empty)
                    // cmd.Parameters.AddWithValue(":CustomerLotNo", DBNull.Value)
                    // Else
                    // cmd.Parameters.AddWithValue(":CustomerLotNo", CustomerLotNo)
                    // End If
                    // cmd.Parameters.AddWithValue(":FactoryNo", FactoryNo)
                    // cmd.ExecuteNonQuery()
                    // cmd.Parameters.Clear()

                    // add MO Component
                    // 


                    // add MO Material List
                    // dtMTL: MONo, MaterialNo, MaterialLevel, StdQty, UnitNo, OPNo, PutInPlaceType, DecreaseRate, Specified, *MaterialType, CountWay, *CheckLotNo, *MaterialVersion, +*MaterialMONo, +SubstituteMaterialNo                
                    //if (dtMTL.Rows.Count > 0)
                    //{
                    //    if (!dtMTL.Columns.Contains("MaterialMONo"))
                    //        dtMTL.Columns.Add("MaterialMONo", Type.GetType("System.String"));

                    //    foreach (DataRow dr in dtMTL.Rows)
                    //    {
                    //        if (dr["MaterialMONo"] is DBNull || string.IsNullOrEmpty(dr["MaterialMONo"].ToString()))
                    //            dr["MaterialMONo"] = "N/A";

                    //        bool blnAddMaterial = true; // 是否將工單用料加入tblOEMOMaterialList, True:是 False:否

                    //        // 2019/09/25 Grace 增加檢查, 若有傳入DeliveryMethod且值=4, 這筆工單用料清單, 不加入至tblOEMOMaterialList;否或非4則不做任何處理
                    //        // 材料型態tagname：DeliveryMethod (Optional參數,非必傳)
                    //        if (!(dr["DeliveryMethod"] is DBNull))
                    //        {
                    //            if (dr["DeliveryMethod"].ToString() == "4")
                    //            {
                    //                blnAddMaterial = false;
                    //            }
                    //        }

                    //        if (blnAddMaterial)
                    //        {
                    //            // 2019/01/30 OwenLiu, Mantis: 0054631 工單拋轉時，避免oracle與SQLServer對於空字串('')處理不同
                    //            // Oracle會將欄位值存成Null, SQLServer會將欄位值成空字串，造成後續功能判斷上的問題
                    //            string strSQLAddMTLField, strSQLAddMTLValue;
                    //            // 先設定Not Null欄位
                    //            strSQLAddMTLField = "INSERT INTO tblOEMOMaterialList(MONo,MaterialNo,MaterialLevel,StdQty,UnitNo";
                    //            strSQLAddMTLValue = " VALUES('" + dr["MONo"].ToString().ToUpper() + "'" + ",'" + dr["MaterialNo"].ToString().ToUpper() + "'," +
                    //                dr["MaterialLevel"] + "," + dr["StdQty"] + ",'" + dr["UnitNo"].ToString().ToLower() + "'";

                    //            strSQLAddMTLField += ",DecreaseRate,OPNo,Specified,PutinplaceType,MaterialMONo,MaterialType" + ",CountWay,CheckLotNo,SubstituteMaterialNo,mainItem,phantomItem,lockRequirement,operationSeqnum";
                    //            strSQLAddMTLValue = strSQLAddMTLValue + "," +
                    //                dr["DecreaseRate"] + ",'" + dr["OPNo"].ToString().ToUpper() + "'," + dr["Specified"] + "," + dr["PutInPlaceType"] + ",'" + dr["MaterialMONo"] +
                    //                "'" + ",'" + dr["MaterialType"].ToString().ToUpper() + "'," + dr["CountWay"] + "," + dr["CheckLotNo"] + ",'" + dr["SubstituteMaterialNo"].ToString().ToUpper() +
                    //                "','" + dr["mainItem"] + "','" + dr["phantomItem"] + "','" + dr["lockRequirement"] + "','" + dr["operationSeqnum"] + "'";

                    //            // RequireQty
                    //            if (!dr.IsNull("RequireQty") && !string.IsNullOrEmpty(dr["RequireQty"].ToString()))
                    //            {
                    //                strSQLAddMTLField += ",RequireQty";
                    //                strSQLAddMTLValue = strSQLAddMTLValue + "," + dr["RequireQty"].ToString();
                    //            }
                    //            // SubstituteStdQty
                    //            if (!dr.IsNull("SubstituteStdQty") && !string.IsNullOrEmpty(dr["SubstituteStdQty"].ToString()))
                    //            {
                    //                strSQLAddMTLField += ",SubstituteStdQty";
                    //                strSQLAddMTLValue = strSQLAddMTLValue + "," + dr["SubstituteStdQty"].ToString();
                    //            }
                    //            // MaterialVersion
                    //            if (!dr.IsNull("MaterialVersion") && !string.IsNullOrEmpty(dr["MaterialVersion"].ToString()))
                    //            {
                    //                strSQLAddMTLField += ",MaterialVersion";
                    //                strSQLAddMTLValue = strSQLAddMTLValue + ",'" + dr["MaterialVersion"] + "'".ToString();
                    //            }
                    //            // SubstituteMaterialLevel
                    //            if (!dr.IsNull("SubstituteMaterialLevel") && !string.IsNullOrEmpty(dr["SubstituteMaterialLevel"].ToString()))
                    //            {
                    //                strSQLAddMTLField += ",SubstituteMaterialLevel";
                    //                strSQLAddMTLValue = strSQLAddMTLValue + "," + dr["SubstituteMaterialLevel"].ToString();
                    //            }

                    //            strSQL = strSQLAddMTLField + ")" + strSQLAddMTLValue + ")";

                    //            CollectionSQL.Add(strSQL);
                    //        }

                    //        // cmd.CommandText = _
                    //        // "insert into tbloemomateriallist(mono,materialno,materiallevel,stdqty,unitno,opno,putinplacetype," & _
                    //        // "decreaserate,specified,materialtype,countway,checklotno,materialversion,materialmono,substitutematerialno,SubstituteMaterialLevel,SubstituteStdQty,RequireQty) " & _
                    //        // "values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
                    //        // cmd.Parameters.AddWithValue(":MONo", dr("MONo").ToString.ToUpper)
                    //        // cmd.Parameters.AddWithValue(":MaterialNo", dr("MaterialNo").ToString.ToUpper)
                    //        // cmd.Parameters.AddWithValue(":MaterialLevel", dr("MaterialLevel"))
                    //        // cmd.Parameters.AddWithValue(":StdQty", dr("StdQty"))
                    //        // cmd.Parameters.AddWithValue(":UnitNo", dr("UnitNo").ToString.ToLower)
                    //        // cmd.Parameters.AddWithValue(":OPNo", dr("OPNo").ToString.ToUpper)
                    //        // cmd.Parameters.AddWithValue(":PutInPlaceType", dr("PutInPlaceType"))
                    //        // cmd.Parameters.AddWithValue(":DecreaseRate", dr("DecreaseRate"))
                    //        // cmd.Parameters.AddWithValue(":Specified", dr("Specified"))
                    //        // cmd.Parameters.AddWithValue(":MaterialType", dr("MaterialType").ToString.ToUpper)
                    //        // cmd.Parameters.AddWithValue(":CountWay", dr("CountWay"))
                    //        // cmd.Parameters.AddWithValue(":CheckLotNo", dr("CheckLotNo"))
                    //        // cmd.Parameters.AddWithValue(":MaterialVersion", dr("MaterialVersion"))
                    //        // cmd.Parameters.AddWithValue(":MaterialMONo", dr("MaterialMONo"))
                    //        // cmd.Parameters.AddWithValue(":SubstituteMaterialNo", dr("SubstituteMaterialNo").ToString.ToUpper)
                    //        // cmd.Parameters.AddWithValue(":SubstituteMaterialLevel", dr("SubstituteMaterialLevel")) '2012/12/26,Even,新增替代物料階 &數量
                    //        // cmd.Parameters.AddWithValue(":SubstituteStdQty", dr("SubstituteStdQty")) '2012/12/28,Even,新增替代物標準數
                    //        // cmd.Parameters.AddWithValue(":RequireQty", dr("RequireQty"))
                    //        // cmd.ExecuteNonQuery()
                    //        // cmd.Parameters.Clear()
                    //    }
                    //}


                    // add MO Process 
                    // 依產品、產品版本、工單類別找出工單流程
                    // 參考kcOE.ShowProductProcess、kcOE.UpdMOProcessbyProduct、MEStc_WellDown.addMO
                    // 2012/07/26, Aaron, 修正取流程時無法取得多區段的流程

                    // 2018/11/19 OwenLiu, 透過共用Function 統一處理 MOProcess資料
                    ExamineMOProcess(MONo, ProductNo, ProductVersion, MOTypeNo, ref CollectionSQL, ref aryException, CustomerLotNo);

                    if (aryException.Count > 0)
                        goto exitfun;

                    // add MO Property
                    if (dtMOProperty.Rows.Count > 0)
                    {
                        foreach (DataRow dr in dtMOProperty.Rows)
                        {
                            strSQL = "insert into tbloemoproperty(mono,propertyno,propertyvalue) values('" + dr["MONo"].ToString().ToUpper() + "','" +
                                dr["PropertyNo"] + "','" + dr["PropertyValue"] + "')";
                            CollectionSQL.Add(strSQL);
                            // cmd.Parameters.AddWithValue(":MONo", dr("MONo").ToString.ToUpper)
                            // cmd.Parameters.AddWithValue(":PropertyNo", dr("PropertyNo"))
                            // cmd.Parameters.AddWithValue(":PropertyValue", dr("PropertyValue"))
                            // cmd.CommandText = "insert into tbloemoproperty(mono,propertyno,propertyvalue) values(?,?,?)"
                            // cmd.ExecuteNonQuery()
                            // cmd.Parameters.Clear()
                            strSQL = "insert into tbloemoproperty_recive(mono,propertyno,propertyvalue) values('" + dr["MONo"].ToString().ToUpper() + "','" +
                                dr["PropertyNo"] + "','" + dr["PropertyValue"] + "')";
                            CollectionSQL.Add(strSQL);
                            // cmd.Parameters.AddWithValue(":MONo", dr("MONo").ToString.ToUpper)
                            // cmd.Parameters.AddWithValue(":PropertyNo", dr("PropertyNo"))
                            // cmd.Parameters.AddWithValue(":PropertyValue", dr("PropertyValue"))
                            // cmd.CommandText = "insert into tbloemoproperty_recive(mono,propertyno,propertyvalue) values(?,?,?)"
                            // cmd.ExecuteNonQuery()
                            // cmd.Parameters.Clear()
                        }
                    }


                    // add MO SEMI Out
                    // 


                    // trans.Commit()
                    //string argstrDataBaseType = "Null";
                    ExecuteSQLNoneQuery_UPD(objSetting.GetDataBaseType(), objSetting.GetConnectionString(), CollectionSQL);
                    r = true;
                    clsERP.combineMessage(ref aryMessage, mmsg: "[%AddMOSuccess%]");
                }

                catch (Exception ex)
                {
                    // trans.Rollback()
                    clsERP.combineException(ref aryException, sysmsg: ex.Message, mesmsg: "[%AddMOFail%]", stack: iMESCore.Base.iMESComXML.CInput(ex.StackTrace));

                }
                // End Using
                // End Using
                // End Using

                exitfun:
                ;
            }


            catch (Exception ex)
            {
                clsERP.combineException(ref aryException, sysmsg: ex.Message, mesmsg: "[%AddMOFail%]", stack: iMESCore.Base.iMESComXML.CInput(ex.StackTrace));
            }
            finally
            {
                CloseConnection(cnnTemp1);
                addMORet = r;
            }

            return addMORet;

        }
        public static string AddMOMaterialList(string MONo, string MaterialNo, int MaterialLevel, double StdQty, double DecreaseRate, string OPNo, int Specified, int PutInPlaceType, string UnitNo, int MOFlag, string MaterialMONo, string Description = defString, Collection colReturnSQL = null, string AdditionalXml = "", string MaterialVersion = defString, string SubstituteMaterialNo = defString, int SubstituteMaterialLevel = defInteger, decimal RequireQty = defInteger, decimal SubstituteStdQty = defInteger, string Creator = defString, DateTime CreateDate = default(DateTime),string AB=defString,string PositionCode=defString)
        {
            string AddMOMaterialListRet = default(string);
            // 此 Function 將新增一筆資料
            // 傳入值: 各欄位新增值
            // 傳回值: success(成功), fail(失敗)

            DbDataReader drTemp = null;
            string MaterialType = "N/A";
            int CountWay = -1;
            int CheckLotNo = -1;
            IDbConnection cnnTemp = null;

            string strSQL = "";
            string strSQLAddField = "";
            string strSQLAddValue = "";


            AppSettings objSetting = new AppSettings();

            string strDataBaseType = objSetting.GetDataBaseType();
            string strConnectionString = objSetting.GetConnectionString(strDataBaseType);

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

                if (MaterialLevel == 0)   // Material
                {
                    strSQL = "Select MaterialType,CountWay,CheckLotNo From tblMTLMaterialBasis" + " Where MaterialNo ='" + MaterialNo + "'";
                    // cmmTemp = New OleDb.OleDbCommand(strSQL, cnnTemp) 
                    drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp);
                    if (drTemp.Read())
                    {
                        MaterialType = Conversions.ToString(drTemp["MaterialType"]);
                        CountWay = Conversions.ToInteger(drTemp["CountWay"]);
                        CheckLotNo = Conversions.ToInteger(drTemp["CheckLotNo"]);
                    }
                    else
                    {
                        throw new iMESException.MESException("0000-200003", "MaterialNo:" + MaterialNo + " is not exist!");
                    }
                    drTemp.Close();
                }
                // cmmTemp.Dispose()

                else if (MaterialLevel == 1) // Product
                {
                    strSQL = "Select ProductType From tblPRDProductBasis Where ProductNo ='" + MaterialNo + "'";
                    // cmmTemp = New OleDb.OleDbCommand(strSQL, cnnTemp) 
                    drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp);
                    if (drTemp.Read())
                    {
                        MaterialType = Conversions.ToString(drTemp["ProductType"]);
                    }
                    else
                    {
                        throw new iMESException.MESException("0000-200003", "ProductNo:" + MaterialNo + " is not exist!");
                    }
                    drTemp.Close();

                    CheckLotNo = 1; // 一律要Check Lot
                }

                // Combine SQL
                strSQLAddField = "Insert into tblOEMOMaterialList (MONo, MaterialNo, OrgMaterialNo, MaterialLevel, StdQty, UnitNo," + "DecreaseRate, OPNo, Specified, PutInPlaceType, MOFlag, MaterialType, CountWay, CheckLotNo ";
                strSQLAddValue = " Values ('" + MONo + "', '" + MaterialNo + "','" + MaterialNo + "'," + MaterialLevel + "," + StdQty + ",'" + UnitNo + "'," + DecreaseRate + ",'" + OPNo + "'," + Specified + "," + PutInPlaceType + "," + MOFlag + ",'" + MaterialType + "'," + CountWay + "," + CheckLotNo;


                if (MOFlag == 0)  // Create MO,紀錄半成品的工單編號
                {
                    strSQLAddField = strSQLAddField + ",MaterialMONo";
                    strSQLAddValue = strSQLAddValue + ",'" + MaterialMONo + "'";
                }
                else
                {
                    strSQLAddField = strSQLAddField + ",MaterialMONo";
                    strSQLAddValue = strSQLAddValue + ",'N/A'";
                }
                if (Description != defString)
                {
                    strSQLAddField = strSQLAddField + ",Description";
                    strSQLAddValue = strSQLAddValue + ",'" + Description + "'";
                }
                if (MaterialVersion != defString)
                {
                    strSQLAddField = strSQLAddField + ",MaterialVersion";
                    strSQLAddValue = strSQLAddValue + ",'" + MaterialVersion + "'";
                }
                if (SubstituteMaterialNo != defString)
                {
                    strSQLAddField = strSQLAddField + ",SubstituteMaterialNo";
                    strSQLAddValue = strSQLAddValue + ",'" + SubstituteMaterialNo + "'";
                }

                // 2012/12/27,Even,新增替代料等級及需求數量
                if (SubstituteMaterialLevel != defInteger)
                {
                    strSQLAddField = strSQLAddField + ",SubstituteMaterialLevel";
                    strSQLAddValue = strSQLAddValue + ",'" + SubstituteMaterialLevel + "'";
                }
                if (SubstituteStdQty != defInteger)
                {
                    strSQLAddField = strSQLAddField + ",SubstituteStdQty";
                    strSQLAddValue = strSQLAddValue + ",'" + SubstituteStdQty + "'";
                }
                if (RequireQty != defInteger)
                {
                    strSQLAddField = strSQLAddField + ",RequireQty";
                    strSQLAddValue = strSQLAddValue + ",'" + RequireQty + "'";
                }
                if (Creator != defString)
                {
                    strSQLAddField = strSQLAddField + ",Creator";
                    strSQLAddValue = strSQLAddValue + ",'" + Creator + "'";
                }
                if (CreateDate != defDateTime)
                {
                    strSQLAddField = strSQLAddField + ",CreateDate";
                    strSQLAddValue = strSQLAddValue + ",To_Date('" + Strings.Format(CreateDate, "yyyy/MM/dd H:mm:ss") + "','YYYY/MM/DD HH24:MI:SS')";
                }

                if (string.IsNullOrEmpty(AdditionalXml))
                {
                    // 當沒有額外的欄位時,直接給定strSQL
                    strSQL = strSQLAddField + ")" + strSQLAddValue + ")";
                }
                else
                {
                    // 加上additional的field & value 後傳回
                    strSQL = SeparateAddXML_Add(ref strSQLAddField, ref strSQLAddValue, AdditionalXml);
                }

                // 呼叫執行SQL指令
                if (colReturnSQL == null)
                {
                    ExecuteSQLNoneQuery(Conversions.ToString(strDataBaseType), strConnectionString, ref strSQL);
                }
                else
                {
                    // 不執行指令,將指令傳出
                    colReturnSQL.Add(strSQL);
                }

                // Return success
                AddMOMaterialListRet = "success";
            }

            catch (Exception e1)
            {
                AddMOMaterialListRet = "fail";
                // 發生錯誤時丟回本身的Function Name及系統錯誤訊息
                throw;
            } // New Exception("kcOE.AddMOMaterialList: " & e1.Message)

            finally
            {
                CloseConnection(cnnTemp);

            }

            return AddMOMaterialListRet;

        }

        /// <summary>
        /// 編輯工單(工單變更)
        /// </summary>
        /// <param name="MONo"></param>
        /// <param name="MOQty"></param>
        /// <param name="RONo"></param>
        /// <param name="ItemNo"></param>
        /// <param name="CustomerNo"></param>
        /// <param name="MOTypeNo"></param>
        /// <param name="Priority"></param>
        /// <param name="PlanFinishDate"></param>
        /// <param name="Creator"></param>
        /// <param name="CreateDate"></param>
        /// <param name="Description"></param>
        /// <param name="dtMTL"></param>
        /// <param name="aryMessage"></param>
        /// <param name="aryException"></param>
        /// <param name="aryAlert"></param>
        /// <param name="dtMOProperty"></param>
        /// <returns></returns>
        /// <remarks></remarks>
        public static bool editMO(string MONo, decimal MOQty, string RONo = null, string ItemNo = null, string CustomerNo = null, int MOTypeNo = defInteger, int Priority = defInteger, DateTime PlanFinishDate = default(DateTime), string Creator = null, DateTime CreateDate = default(DateTime), string Description = null, DataTable dtMTL = null, List<ArrayList> aryMessage = null, List<ArrayList> aryException = null, List<ArrayList> aryAlert = null, DataTable dtMOProperty = null, string ERPMOLineNo = defString, bool PropertyFlag = false, string CustomerLotNo = null, DateTime PlanStartDate = default(DateTime), int wipEntityId = defInteger, string bomVersion = null, string lcPlantype = null, string faiFlag = null)    // haoqian 221025
        {
            bool editMORet = default(bool);

            bool r = false;
            var CollectionSQL = new Collection();
            string strSQL = "";

            try
            {

                // ----- Default Value -----
                int MOSource = 0;                 // 0: RO, 1: RMA, 2: None 
                int MOState = 0;                   // 0: Unconfirm, 1: Pending, 2: Confirm, 3: Release(允許開立生產批), 6: 已在客託倉或退貨倉的工單(允許開立生產批), 99:Close
                int IssueState = 0;
                string BelongToMONo = "N/A";
                string ENGNo = "N/A";
                string ENGVersion = "N/A";
                //string CustomerLotNo = string.Empty;
                string FactoryNo = "N/A";
                decimal AdjustQty = 0m;
                string OPNo = "LOTCREATE";

                // ---- Get Value -----
                string CustomerName = string.Empty;
                string ProductVersion = string.Empty;
                string ProcessNo = string.Empty;
                string ProcessVersion = string.Empty;

                bool isROExist = false;
                bool isRODetailExist = false;

                string ItemProperty = defString;   // 2016-10-17, Joe, 新增料件屬性，P：採購件，M：自製件，S：外包件
                int OutSourcingFlag = defInteger;     // 2016-10-17, Joe, 0:off，1:on
                string ProductNo = defString;

                var ReleaseQty = default(decimal);

                // ----- 1. 檢查MO是否存在 -----
                MONo = MONo.ToUpper();

                using (var objOE = new clsOEBasis())
                {

                    var drOE = objOE.GetMOBasis(MONo.ToUpper());
                    if (drOE["MONo"] is DBNull == true)
                        clsERP.combineException(ref aryException, mesmsg: "[%MONoNotExist%]");
                    // If drOE.Item("IssueState") < 0 Or drOE.Item("IssueState") > 2) clsERP.combineException(aryException, , , "[%MONoIssueStateCanNotEdit%]")


                    if (!(drOE["MOState"] is DBNull))
                    {
                        if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(drOE["MOState"], 99, false)))
                            clsERP.combineException(ref aryException, mesmsg: "[%MONoClosed%]");
                    }

                    // 2020/08/11 Grace Mantis 76332 依據規格書說明調整：若訂單號碼有傳入，此項目應一併傳入，若未傳入則預設為1
                    if (string.IsNullOrEmpty(ItemNo) == true)
                        ItemNo = "1";

                    // ----- 2. 檢查訂單資料 -----
                    if (string.IsNullOrEmpty(RONo) == false)
                    {
                        if (RONo.ToUpper() != drOE["RONo"].ToString())
                            clsERP.combineException(ref aryException, mesmsg: "[%RONoCanNotChange%]");
                        if (ItemNo != drOE["ItemNo"].ToString())
                            clsERP.combineException(ref aryException, mesmsg: "[%ROItemNoCanNotChange%]");
                    }

                    // ----- 3. 檢查MO剩餘數量 -----
                    // If MOQty < drOE.Item("UnReleaseLotQty")) clsERP.combineException(aryException, , , "[%MOQtyLassThenUnReleaseLotQty%]")

                    // 要修改的MOQty不可小於已下線數量:MOQtyLessThenReleaseLotQty, 2009/05/05,by yumei
                    if (!(drOE["MOQty"] is DBNull))
                    {
                        ReleaseQty = Convert.ToDecimal(Operators.SubtractObject(drOE["MOQty"], drOE["UnReleaseLotQty"]));
                        if (MOQty < ReleaseQty)
                            clsERP.combineException(ref aryException, mesmsg: "[%MOQtyLessThenReleaseLotQty%]");
                    }

                    if (!(drOE["IssueState"] is DBNull))
                    {
                        //檢查工單數量的變更是否合理
                        if (Conversions.ToInteger(drOE["IssueState"]) == 2)
                        {
                            var dsOEMOC = objOE.ShowMOComponent(MONo.ToUpper());
                            if (dsOEMOC.Tables[0].Rows.Count > 0)
                            {
                                //tblOEMOComponent.InventoryNo多筆相同
                                if (!(dsOEMOC.Tables[0].Rows[0]["InventoryNo"] is DBNull))
                                {
                                    clsERP.combineException(ref aryException, mesmsg: "[%EditMOQtyIsNotAllowed_InventoryNo%]");
                                }
                                else
                                {
                                    if (!(drOE["MOQty"] is DBNull))
                                    {
                                        if (MOQty < Convert.ToDecimal(drOE["MOQty"]))
                                        {
                                            if (dsOEMOC.Tables[0].Rows.Count > MOQty)
                                            {
                                                clsERP.combineException(ref aryException, mesmsg: "[%EditMOQtyIsNotAllowed_WaferSouceType%]");
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                    ProductNo = drOE["ProductNo"].ToString();

                }

                if (aryException.Count > 0)
                    goto exitfun;

                // ----- 3. 檢查MOSource-----
                if (string.IsNullOrEmpty(RONo))
                    MOSource = 2; // MO來源為其他(暫不考慮RMA)

                // ----- 4. 檢查CustomerNo是否存在 -----
                if (MOSource == 0)
                {
                    if (string.IsNullOrEmpty(CustomerNo))
                    {
                        // 未傳入
                        clsERP.combineException(ref aryException, mesmsg: "[%ROWithoutCustomerNo%]");
                    }
                    else
                    {
                        // 有傳入=>檢查Customer主檔
                        using (var objENT = new clsCustomerBasis())
                        {
                            var dr = objENT.GetCustomerBasis(CustomerNo.ToUpper());
                            if (dr["CustomerNo"] is DBNull == true)
                            {
                                // Customer主檔未建立
                                // clsERP.combineException(aryException, , , "[%CustomerNoNotExist%]")

                                // 5.3	若拋入訂單號碼，則必須拋入客戶編號，系統應檢查tblENTCustomerBasis之中是否存在此客戶，若無則自動新增
                                objENT.AddCustomerBasis(CustomerNo.ToUpper(), CustomerNo, CustomerNo, "NULL", "NULL", "NULL", "NULL", "NULL", "NULL");
                                objENT.SetCustomerBasisIssueState(CustomerNo.ToUpper(), 2);
                            }
                            else
                            {
                                CustomerName = dr["CustomerName"].ToString();
                            }
                        }
                    }
                }

                // ----- 5. 檢查Product -----
                // Using objPRD As New kcPRD.clsProduct
                // Dim dr As DataRow = objPRD.GetProduct(ProductNo.ToUpper)
                // If IsDBNull(dr("ProductNo")) = True) clsERP.combineException(aryException, , , "[%ProductNoNotExist%]")
                // If IsDBNull(dr("ProductNo")) = False AndAlso dr("IssueState") <> 2) clsERP.combineException(aryException, , , "[%ProductNotApproved%]")

                // '----- 6. 檢查MOUnitNo -----
                // If IsDBNull(dr("ProductNo")) = False AndAlso dr("UnitNo").ToString.ToLower <> MOUnitNo.ToLower) clsERP.combineException(aryException, , , "[%ProductandMOwithdifferentUnitNo%]")
                // dr.Delete()

                // Try
                // ProductVersion = objPRD.GetProductCurVersion(ProductNo.ToUpper)
                // Catch ex As Exception
                // clsERP.combineException(aryException, , , "[%GetProductVersionFail%]")
                // End Try
                // End Using

                using (var objPRD = new clsProduct())
                {
                    try
                    {
                        ProductVersion = objPRD.GetProductCurVersion(ProductNo.ToUpper());
                    }
                    catch (Exception ex)
                    {
                        clsERP.combineException(ref aryException, mesmsg: "[%GetProductVersionFail%]");
                    }
                    // 2016-10-17, Joe, 取得ItemProperty
                    var drItemProperty = objPRD.GetProductProperty(ProductNo, ProductVersion, "ItemProperty");
                    if (drItemProperty == null == false && drItemProperty["DefaultValue"] is DBNull == false)
                    {
                        ItemProperty = drItemProperty["DefaultValue"].ToString();
                    }
                }
                // 2016-10-17, Joe, 取得外包控制
                using (var objSYS = new clsSYSParameter())
                {
                    OutSourcingFlag = Conversions.ToInteger(objSYS.GetParameterValue("OutSourcingFlag"));
                }
                // 2016-10-17, Joe, 若該產品品號屬性屬於S且外包控管參數為Off時，MES不做工單新增/修改，直接回應OK，但訊息應回傳『MES系統不支持外包工單』
                if (ItemProperty == "S" & OutSourcingFlag == 0)
                {
                    clsERP.combineMessage(ref aryMessage, mmsg: "[%ProductNo%]:" + ProductNo + ",[%ProductVersion%]:" + ProductVersion + ",[%Is%] [%OutSourcing%] [%Product%], MES [%IsNotSupported%] !");
                    if (aryMessage.Count > 0)
                        goto exitfun;
                }

                // ----- 7. 檢查用料清單資料 -----
                if (dtMTL.Rows.Count > 0)
                {
                    bool blnWF = false;
                    //2023/12/07,Ning,151196: [6.0.7] SDD231107_01-01_WF 工單整合接口調整
                    //取得目前ERP是否為WF
                    using (var objSYSPar = new kcSYS.clsSYSParameter())
                    {
                        var dsTemp = new DataSet();
                        dsTemp = objSYSPar.ShowERPSetting(ActiveERP: 1);
                        if (dsTemp != null && dsTemp.Tables[0].Rows.Count > 0)
                        {
                            if (dsTemp.Tables[0].Rows[0]["ERP_Name"].ToString().ToUpper() == "WORKFLOW")
                            {
                                blnWF = true;
                            }
                        }
                    }

                    if (!dtMTL.Columns.Contains("MaterialMONo"))
                        dtMTL.Columns.Add("MaterialMONo", Type.GetType("System.String"));

                    // dtMTL: MONo, MaterialNo, MaterialLevel, StdQty, UnitNo, OPNo, PutInPlaceType, DecreaseRate, Specified, *MaterialType, CountWay, *CheckLotNo, *MaterialVersion, +MaterialMONo, +*SubstituteMaterialNo

                    foreach (DataRow dr in dtMTL.Rows)
                    {
                        string strMaterialUnit = dr["UnitNo"].ToString();
                        decimal decTemp = 0m;
                        try
                        {
                            if (string.IsNullOrEmpty(dr["MainItem"].ToString()))
                            {
                                // 未傳入
                                clsERP.combineException(ref aryException, mesmsg: "[%MainItem%]");
                            }

                            //if (string.IsNullOrEmpty(dr["PhantomItem"].ToString()))
                            //{
                            //    // 未傳入
                            //    clsERP.combineException(ref aryException, mesmsg: "[%PhantomItem%]");
                            //}

                            if (string.IsNullOrEmpty(dr["LockRequirement"].ToString()))
                            {
                                // 未傳入
                                clsERP.combineException(ref aryException, mesmsg: "[%LockRequirement%]");
                            }

                            if (string.IsNullOrEmpty(dr["OperationSeqnum"].ToString()))
                            {
                                // 未傳入
                                clsERP.combineException(ref aryException, mesmsg: "[%OperationSeqnum%]");
                            }

                            if (blnWF == true)
                            {
                                if (Conversions.ToInteger(dr["StdQty"]) != Convert.ToDecimal(dr["StdQty"]))           //若標準用量有小數, 需以ERP所傳入的該物料的需領用量(RequireQty)/預計產量(MOQty)，並以無條件捨去取到小數六位數的值，做為該物料的標準用量
                                {
                                    decTemp = (Convert.ToDecimal(dr["RequireQty"]) / MOQty) * 1000000;
                                    decTemp = Math.Floor(decTemp);
                                    decTemp = decTemp / 1000000;
                                    dr["StdQty"] = decTemp;
                                }
                                if (Conversions.ToInteger(dr["SubstituteStdQty"]) != Convert.ToDecimal(dr["SubstituteStdQty"]))           //若替代料標準用量有小數同標準用量處理
                                {
                                    decTemp = (Convert.ToDecimal(dr["RequireQty"]) / MOQty) * 1000000;
                                    decTemp = Math.Floor(decTemp);
                                    decTemp = decTemp / 1000000;
                                    dr["SubstituteStdQty"] = decTemp;
                                }
                            }
                            if (dr["MaterialLevel"].ToString() == "0")
                            {
                                // 用料清單為物料
                                using (var objMTL = new clsMTLBasis())
                                {
                                    DataRow drMTL = null;
                                    bool errorFlag = false;
                                    dr["MONo"] = dr["MONo"].ToString().ToUpper();

                                    drMTL = objMTL.GetMaterialBasis(dr["MaterialNo"].ToString().ToUpper());
                                    // (skip) MONo, MaterialLevel, STDQty, DecreaseRate, OPNo, Specified, PutinPlaceType, MOFlag, CountWay, Description, OrgMaterialNo, EX_MTLList1, EX_MTLList2, MaterialVersion

                                    // MaterialNo
                                    if (drMTL["MaterialNo"] is DBNull == true) // 2013/02/19,Even，以物料編號在物料主檔中查詢，查不到表示該項為半成品，因為TIPTOP系統中，物料和產品在同一個table內，使用者可能挑選到產品卻以為是物料
                                    {
                                        errorFlag = true;
                                        clsERP.combineException(ref aryException, mesmsg: " [%MaterialNo%]:" +
                                            dr["MaterialNo"] + " [%MaterialNoNotExist%][%InMESSystem%]! [%MaterialLevel%][%IsMaterial%].");
                                        goto SkipMaterialList;
                                    }
                                    else
                                    {
                                        dr["MaterialNo"] = dr["MaterialNo"].ToString().ToUpper();
                                    }

                                    // UnitNo
                                    if (drMTL["UnitNo"].ToString().ToLower() != strMaterialUnit.ToLower())
                                    {
                                        // 當用料清單和物料主檔的單位不同時
                                        // 單位轉換
                                        using (var objUnit = new udUnitTransferFunction.clsUnitTransferFunction())
                                        {
                                            var colParameters = new Collection();
                                            colParameters.Add(dr["MaterialNo"].ToString().ToUpper(), "ProductNo");
                                            colParameters.Add("*", "ProductVersion");

                                            try
                                            {
                                                dr["StdQty"] = Convert.ToDouble(objUnit.EXETransferQty(strMaterialUnit.ToLower(), drMTL["UnitNo"].ToString().ToLower(), Convert.ToDouble(dr["StdQty"]), colParameters));
                                                dr["SubstituteStdQty"] = Convert.ToDouble(objUnit.EXETransferQty(strMaterialUnit.ToLower(), drMTL["UnitNo"].ToString().ToLower(), Convert.ToDouble(dr["SubstituteStdQty"]), colParameters));
                                                dr["UnitNo"] = drMTL["UnitNo"].ToString().ToLower();
                                            }
                                            catch (Exception ex)
                                            {
                                                errorFlag = true;
                                                clsERP.combineException(ref aryException, mesmsg: "[%MaterialListUnitNoDifferent%]" + " [%MaterialNo%]:" +
                                                    dr["MaterialNo"]);
                                                clsERP.combineException(ref aryException, mesmsg: "[%MaterialListUnitTransferFail%]" + " " + ex.Message);
                                            }
                                        }
                                    }
                                    else
                                    {
                                        dr["UnitNo"] = dr["UnitNo"].ToString().ToLower();
                                    }

                                    // MaterialMONo (Default)
                                    dr["MaterialMONo"] = "N/A";

                                    // MaterialType
                                    if (dr["MaterialType"] is DBNull == true)
                                    {
                                        dr["MaterialType"] = drMTL["MaterialType"];
                                    }
                                    else if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(dr["MaterialType"].ToString().ToUpper(), drMTL["MaterialType"], false)))
                                    {
                                        dr["MaterialType"] = dr["MaterialType"].ToString().ToUpper();
                                    }
                                    else
                                    {
                                        clsERP.combineException(ref aryException, mesmsg: "[%MaterialListMaterialTypeDifferent%]" + " [%MaterialNo%]:" +
                                            dr["MaterialNo"]);
                                    }

                                    // CheckLotNo
                                    if (dr["CheckLotNo"] is DBNull == true)
                                    {
                                        dr["CheckLotNo"] = drMTL["CheckLotNo"];
                                    }
                                    else if (Convert.ToBoolean(Operators.ConditionalCompareObjectNotEqual(dr["CheckLotNo"], drMTL["CheckLotNo"], false)))
                                    {
                                        clsERP.combineException(ref aryException, mesmsg: "[%MaterialListCheckLotNoDifferent%]" + " [%MaterialNo%]:" +
                                            dr["MaterialNo"]);
                                    }

                                    // 2013/02/20,Even,修改替代料檢查
                                    if (dr["SubstituteMaterialNo"] is DBNull == true)
                                    {
                                        dr["SubstituteMaterialNo"] = dr["MaterialNo"];
                                        dr["SubstituteMaterialLevel"] = dr["MaterialLevel"];
                                    }
                                    // 2013/02/25,Even,判斷替代料，替代料可為半成品或是物料
                                    else if (dr["SubstituteMaterialLevel"].ToString() == "0") // 為物料
                                    {
                                        // 查詢替代料是否在物料主檔內，若無，則出現錯誤訊息
                                        drMTL = objMTL.GetMaterialBasis(dr["SubstituteMaterialNo"].ToString().ToUpper());
                                        if (drMTL["MaterialNo"] is DBNull == true)
                                        {
                                            errorFlag = true;
                                            clsERP.combineException(ref aryException, mesmsg: " [%SubstituteMaterialNo%]:" +
                                                dr["SubstituteMaterialNo"] + " [%MaterialNoNotExist%][%InMESSystem%]! [%SubstituteMaterialLevel%][%IsMaterial%].");
                                            goto SkipMaterialList;
                                        }
                                        else
                                        {
                                            dr["SubstituteMaterialNo"] = dr["SubstituteMaterialNo"].ToString().ToUpper();
                                        }
                                    }
                                    else // 為半成品 (SubstituteMaterialLevel = 1)
                                    {
                                        DataRow drPRD = null;
                                        // 檢查物料是否存在於產品主檔
                                        using (var objPRD = new clsProduct())
                                        {
                                            drPRD = objPRD.GetProduct(dr["SubstituteMaterialNo"].ToString().ToUpper());
                                        }
                                        if (drPRD["ProductNo"] is DBNull == true)
                                        {
                                            errorFlag = true;
                                            clsERP.combineException(ref aryException, mesmsg: " [%SubstituteMaterialNo%]:" +
                                                dr["SubstituteMaterialNo"] + " [%ProductNoNotExist%][%InMESSystem%]! [%SubstituteMaterialLevel%][%IsProduct%].");
                                            goto SkipMaterialList;
                                        }
                                        else
                                        {
                                            dr["SubstituteMaterialNo"] = dr["SubstituteMaterialNo"].ToString().ToUpper();
                                        }
                                    }

                                    if (dr["SubstituteStdQty"] is DBNull == true)
                                    {
                                        dr["SubstituteStdQty"] = dr["StdQty"];
                                    }
                                    // 2019/12/16 OwenLiu, Mantis:0065576 , 工單整合(新增)時用料需求數支援單位轉換
                                    decimal decRequireQty = 0m;
                                    if (dr["RequireQty"] is DBNull == true)
                                    {
                                        // ERP未傳入需求數(RequireQty)
                                        // 2019/12/23 OwenLiu, Mantis:0065953 修正工單整合 用料清單單位轉換的問題
                                        dr["RequireQty"] = Operators.MultiplyObject(Operators.MultiplyObject(MOQty, dr["StdQty"]), Operators.AddObject(1, dr["DecreaseRate"]));
                                    }
                                    else
                                    {
                                        decRequireQty = Convert.ToDecimal(dr["RequireQty"]);
                                        // 2019/12/23 OwenLiu, Mantis:0065953 修正工單整合 用料清單單位轉換的問題
                                        if (drMTL["UnitNo"].ToString().ToLower() != strMaterialUnit.ToLower())
                                        {
                                            // 當用料清單和物料主檔的單位不同時
                                            using (var objUnit = new udUnitTransferFunction.clsUnitTransferFunction())
                                            {
                                                var colParameters = new Collection();
                                                colParameters.Add(dr["MaterialNo"].ToString().ToUpper(), "ProductNo");
                                                colParameters.Add("*", "ProductVersion");
                                                try
                                                {
                                                    dr["RequireQty"] = Convert.ToDouble(objUnit.EXETransferQty(strMaterialUnit.ToLower(), drMTL["UnitNo"].ToString().ToLower(), (double)decRequireQty, colParameters));
                                                }
                                                catch (Exception ex)
                                                {
                                                    errorFlag = true;
                                                    clsERP.combineException(ref aryException, mesmsg: "[%MaterialListUnitNoDifferent%]" + " [%MaterialNo%]:" +
                                                        dr["MaterialNo"]);
                                                    clsERP.combineException(ref aryException, mesmsg: "[%MaterialListUnitTransferFail%]" + " " + ex.Message);
                                                }
                                            }
                                        }
                                        else
                                        {
                                            dr["RequireQty"] = decRequireQty;
                                        }
                                    }

                                    // 檢查OPNo(用料作業站)是否存在 -----
                                    if (dr["OPNo"].ToString().ToUpper() != "LOTCREATE")
                                    {
                                        // 有傳入=>檢查OP主檔
                                        using (var objOP = new clsOpBasis())
                                        {
                                            var drOP = objOP.GetOPBasis(dr["OPNo"].ToString().ToUpper());
                                            if (drOP["OPNo"] is DBNull == true)
                                            {
                                                // OP主檔未建立
                                                clsERP.combineException(ref aryException, mesmsg: "[%OPNoNotExist%]");
                                            }
                                        }
                                    }
                                }
                            }
                            else
                            {
                                // 用料清單為半成品
                                using (var objPRD = new clsProduct())
                                {
                                    DataRow drPRD = null;
                                    bool errorFlag = false;
                                    dr["MONo"] = dr["MONo"].ToString().ToUpper();

                                    drPRD = objPRD.GetProduct(dr["MaterialNo"].ToString().ToUpper());
                                    // (skip) MONo, MaterialLevel, STDQty, DecreaseRate, OPNo, Specified, PutinPlaceType, MOFlag, CountWay, Description, OrgMaterialNo, EX_MTLList1, EX_MTLList2, MaterialVersion

                                    // MaterialNo
                                    if (drPRD["ProductNo"] is DBNull == true)
                                    {
                                        errorFlag = true;
                                        clsERP.combineException(ref aryException, mesmsg: " [%MaterialNo%]:" +
                                            dr["MaterialNo"] + " [%ProductNoNotExist%][%InMESSystem%]! [%MaterialLevel%][%IsProduct%].");
                                        goto SkipMaterialList;
                                    }
                                    else
                                    {
                                        dr["MaterialNo"] = dr["MaterialNo"].ToString().ToUpper();
                                    }

                                    // UnitNo
                                    if (drPRD["UnitNo"].ToString().ToLower() != dr["UnitNo"].ToString().ToLower())
                                    {
                                        // 當用料清單和物料主檔的單位不同時
                                        // 單位轉換
                                        using (var objUnit = new udUnitTransferFunction.clsUnitTransferFunction())
                                        {
                                            var colParameters = new Collection();
                                            colParameters.Add(dr["MaterialNo"].ToString().ToUpper(), "ProductNo");
                                            colParameters.Add("*", "ProductVersion");

                                            try
                                            {
                                                dr["StdQty"] = Convert.ToDouble(objUnit.EXETransferQty(strMaterialUnit.ToLower(), drPRD["UnitNo"].ToString().ToLower(), Convert.ToDouble(dr["StdQty"]), colParameters));

                                                dr["SubstituteStdQty"] = Convert.ToDouble(objUnit.EXETransferQty(strMaterialUnit.ToLower(), drPRD["UnitNo"].ToString().ToLower(), Convert.ToDouble(dr["SubstituteStdQty"]), colParameters));

                                                dr["UnitNo"] = drPRD["UnitNo"].ToString().ToLower();
                                            }
                                            catch (Exception ex)
                                            {
                                                errorFlag = true;
                                                clsERP.combineException(ref aryException, mesmsg: "[%MaterialListUnitNoDifferent%]" + " [%MaterialNo%]:" +
                                                    dr["MaterialNo"]);
                                                clsERP.combineException(ref aryException, mesmsg: "[%MaterialListUnitTransferFail%]" + " " + ex.Message);
                                            }
                                        }
                                    }
                                    else
                                    {
                                        dr["UnitNo"] = dr["UnitNo"].ToString().ToLower();
                                    }

                                    // MaterialMONo (Default)
                                    dr["MaterialMONo"] = "N/A";

                                    // MaterialType
                                    if (dr["MaterialType"] is DBNull == true)
                                    {
                                        dr["MaterialType"] = drPRD["ProductType"];
                                    }
                                    else if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(dr["MaterialType"].ToString().ToUpper(), drPRD["ProductType"], false)))
                                    {
                                        dr["MaterialType"] = dr["MaterialType"].ToString().ToUpper();
                                    }
                                    else
                                    {
                                        clsERP.combineException(ref aryException, mesmsg: "[%MaterialListMaterialTypeDifferent%]" + " [%MaterialNo%]:" +
                                            dr["MaterialNo"]);
                                    }

                                    // CheckLotNo
                                    dr["CheckLotNo"] = 1;   // 半成品固定為1

                                    // SubstituteMaterialNo
                                    // ---2013/02/20,Even,替代料是否存在的檢查----
                                    if (dr["SubstituteMaterialNo"] is DBNull == true)
                                    {
                                        dr["SubstituteMaterialNo"] = dr["MaterialNo"];
                                        dr["SubstituteMaterialLevel"] = dr["MaterialLevel"];
                                    }
                                    else
                                    {
                                        DataRow drMTL = null;
                                        // 2013/02/25,Even,判斷替代料，替代料可為半成品或是物料
                                        if (dr["SubstituteMaterialLevel"].ToString() == "0") // 為物料
                                        {
                                            // 查詢替代料是否在物料主檔內，若無，則出現錯誤訊息
                                            using (var objMTL = new clsMTLBasis())
                                            {
                                                drMTL = objMTL.GetMaterialBasis(dr["SubstituteMaterialNo"].ToString().ToUpper());
                                            }

                                            if (drMTL["MaterialNo"] is DBNull == true)
                                            {
                                                errorFlag = true;
                                                clsERP.combineException(ref aryException, mesmsg: " [%SubstituteMaterialNo%]:" +
                                                    dr["SubstituteMaterialNo"] + " [%MaterialNoNotExist%][%InMESSystem%]! [%SubstituteMaterialLevel%][%IsMaterial%].");
                                                goto SkipMaterialList;
                                            }
                                            else
                                            {
                                                dr["SubstituteMaterialNo"] = dr["SubstituteMaterialNo"].ToString().ToUpper();
                                            }
                                        }
                                        else // 為半成品 (SubstituteMaterialLevel = 1)
                                        {
                                            // 檢查物料是否存在於產品主檔
                                            drPRD = objPRD.GetProduct(dr["SubstituteMaterialNo"].ToString().ToUpper());
                                            if (drPRD["ProductNo"] is DBNull == true)
                                            {
                                                errorFlag = true;
                                                clsERP.combineException(ref aryException, mesmsg: " [%SubstituteMaterialNo%]:" +
                                                    dr["SubstituteMaterialNo"] + " [%ProductNoNotExist%][%InMESSystem%]! [%SubstituteMaterialLevel%][%IsProduct%].");
                                                goto SkipMaterialList;
                                            }
                                            else
                                            {
                                                dr["SubstituteMaterialNo"] = dr["SubstituteMaterialNo"].ToString().ToUpper();
                                            }
                                        }
                                    }

                                    if (dr["SubstituteStdQty"] is DBNull == true)
                                    {
                                        dr["SubstituteStdQty"] = dr["StdQty"];
                                    }

                                    // 2019/12/16 OwenLiu, Mantis:0065576 , 工單整合(新增)時用料需求數支援單位轉換
                                    decimal decRequireQty = 0m;
                                    if (dr["RequireQty"] is DBNull == true)
                                    {
                                        // ERP未傳入需求數(RequireQty)
                                        // 2019/12/23 OwenLiu, Mantis:0065953 修正工單整合 用料清單單位轉換的問題
                                        dr["RequireQty"] = Operators.MultiplyObject(Operators.MultiplyObject(MOQty, dr["StdQty"]), Operators.AddObject(1, dr["DecreaseRate"]));
                                    }
                                    else
                                    {
                                        decRequireQty = Convert.ToDecimal(dr["RequireQty"]);
                                        // 2019/12/23 OwenLiu, Mantis:0065953 修正工單整合 用料清單單位轉換的問題
                                        if (drPRD["UnitNo"].ToString().ToLower() != strMaterialUnit.ToLower())
                                        {
                                            // 當用料清單和產品主檔的單位不同時
                                            using (var objUnit = new udUnitTransferFunction.clsUnitTransferFunction())
                                            {
                                                var colParameters = new Collection();
                                                colParameters.Add(dr["MaterialNo"].ToString().ToUpper(), "ProductNo");
                                                colParameters.Add("*", "ProductVersion");
                                                try
                                                {
                                                    dr["RequireQty"] = Convert.ToDouble(objUnit.EXETransferQty(strMaterialUnit.ToLower(), drPRD["UnitNo"].ToString().ToLower(), (double)decRequireQty, colParameters));
                                                }
                                                catch (Exception ex)
                                                {
                                                    errorFlag = true;
                                                    clsERP.combineException(ref aryException, mesmsg: "[%MaterialListUnitNoDifferent%]" + " [%MaterialNo%]:" +
                                                        dr["MaterialNo"]);
                                                    clsERP.combineException(ref aryException, mesmsg: "[%MaterialListUnitTransferFail%]" + " " + ex.Message);
                                                }
                                            }
                                        }
                                        else
                                        {
                                            dr["RequireQty"] = decRequireQty;
                                        }
                                    }

                                    // 檢查OPNo(用料作業站)是否存在 -----
                                    if (dr["OPNo"].ToString().ToUpper() != "LOTCREATE")
                                    {
                                        // 有傳入=>檢查OP主檔
                                        using (var objOP = new clsOpBasis())
                                        {
                                            var drOP = objOP.GetOPBasis(dr["OPNo"].ToString().ToUpper());
                                            if (drOP["OPNo"] is DBNull == true)
                                            {
                                                // OP主檔未建立
                                                clsERP.combineException(ref aryException, mesmsg: "[%OPNoNotExist%]");
                                            }
                                        }
                                    }
                                }
                            }

                            SkipMaterialList:
                            ;
                        }

                        catch (Exception ex)
                        {
                            clsERP.combineException(ref aryException, sysmsg: ex.Message, mesmsg: "[%doMaterialListFail%]", stack: iMESCore.Base.iMESComXML.CInput(ex.StackTrace));
                        }
                    }

                }

                // ----- 8. 取得FactoryNo -----
                // FactoryNo = "N/A"

                // ----- 檢查MO Property ---
                if (!(dtMOProperty == null) && dtMOProperty.Rows.Count > 0)
                {
                    foreach (DataRow dr in dtMOProperty.Rows)
                    {
                        List<ArrayList> argaryMessage = null;
                        List<ArrayList> argaryException = null;
                        doSYSMOProperty(Convert.ToString(dr["PropertyNo"]), Convert.ToString(dr["DataType"]), aryMessage: argaryMessage, aryException: argaryException);
                    }
                }

                // ----- 9. 檢查OPNo(用料作業站)是否存在 -----
                if (dtMTL.Rows.Count > 0)
                {

                    // dtMTL.Columns.Add("MaterialMONo", System.Type.GetType("System.String"))

                    // dtMTL: MONo, MaterialNo, MaterialLevel, StdQty, UnitNo, OPNo, PutInPlaceType, DecreaseRate, Specified, *MaterialType, CountWay, *CheckLotNo, *MaterialVersion, +MaterialMONo

                    foreach (DataRow dr in dtMTL.Rows)
                    {
                        try
                        {
                            // OPyNo <> "LOTCREATE"
                            if (dr["OPNo"].ToString() != OPNo.ToString())
                            {
                                // 有傳入=>檢查OP主檔
                                using (var objOP = new clsOpBasis())
                                {
                                    var drOP = objOP.GetOPBasis(dr["OPNo"].ToString());
                                    if (drOP["OPNo"] is DBNull == true)
                                    {
                                        // OP主檔未建立
                                        clsERP.combineException(ref aryException, mesmsg: "[%OPNoNotExist%]");
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            clsERP.combineException(ref aryException, sysmsg: ex.Message, mesmsg: "[%doMaterialListFail%]", stack: iMESCore.Base.iMESComXML.CInput(ex.StackTrace));
                        }
                    }
                }


                // ----- Exception => Fail -----
                if (aryException.Count > 0)
                    goto exitfun;

                // ----- Edit MO -----
                AppSettings objSetting = new AppSettings();
                // Using cn As New OleDbConnection(objSetting.GetConnectionString)
                // Using cmd As New OleDbCommand("", cn)
                // cn.Open()
                // Using trans As OleDbTransaction = cn.BeginTransaction
                // cmd.Transaction = trans
                try
                {
                    // ----- MO -----
                    // edit MO Basis
                    strSQL = "update tbloemobasis set " + "moqty=" + MOQty + ", " + "unreleaselotqty=" + (MOQty - ReleaseQty) + ", " + "priority=" + Priority + ", " + "planfinishdate=To_Date('" + Strings.Format(PlanFinishDate, "yyyy/MM/dd H:mm:ss") + "','YYYY/MM/DD HH24:MI:SS'), " + "description=N'" + Description + "' ";

                    // 2018/3/19 Vick 新增欄位 ERPMOLineNo
                    if (ERPMOLineNo != defString)
                    {
                        strSQL += ",ERPMOLineNo ='" + ERPMOLineNo + "' ";
                    }
                    if (PlanStartDate != defDateTime)
                    {
                        strSQL += ",PlanStartDate = To_Date('" + Strings.Format(PlanStartDate, "yyyy/MM/dd H:mm:ss") + "','YYYY/MM/DD HH24:MI:SS') ";
                    }
                    strSQL += "where mono='" + MONo.ToUpper() + "'";

                    CollectionSQL.Add(strSQL);
                    // cmd.CommandText = _
                    // "update tbloemobasis set " & _
                    // "moqty=?, " & _
                    // "unreleaselotqty=?, " & _
                    // "priority=?, " & _
                    // "planfinishdate=?, " & _
                    // "description=? " & _
                    // "where mono=?"
                    // cmd.Parameters.AddWithValue(":MOQty", MOQty)
                    // cmd.Parameters.AddWithValue(":UnReleaseLotQty", MOQty - ReleaseQty) 'UNRELEASELOTQTY
                    // cmd.Parameters.AddWithValue(":Priority", Priority)
                    // cmd.Parameters.AddWithValue(":PlanFinishDate", PlanFinishDate)
                    // cmd.Parameters.AddWithValue(":Description", Description)
                    // cmd.Parameters.AddWithValue(":MONo", MONo.ToUpper) 
                    // cmd.ExecuteNonQuery()
                    // cmd.Parameters.Clear()

                    // add MO Component


                    // add MO Material List
                    // dtMTL: MONo, MaterialNo, MaterialLevel, StdQty, UnitNo, OPNo, PutInPlaceType, DecreaseRate, Specified, *MaterialType, CountWay, *CheckLotNo, *MaterialVersion, +MaterialMONo, +*SubstituteMaterialNo
                    if (dtMTL.Rows.Count > 0)
                    {

                        using (var objOE = new clsOEBasis())
                        {

                            var dtTemp = objOE.ShowMOMaterialList(MONo.ToUpper()).Tables["MOMaterialList"];

                            strSQL = "delete from tbloemomateriallist where mono='" + MONo.ToUpper() + "'";
                            CollectionSQL.Add(strSQL);
                            // cmd.CommandText = _
                            // "delete from tbloemomateriallist where mono=?"
                            // cmd.Parameters.AddWithValue(":MONo", MONo.ToUpper)
                            // cmd.ExecuteNonQuery()
                            // cmd.Parameters.Clear()

                            foreach (DataRow dr in dtMTL.Rows)
                            {

                                bool blnAddMaterial = true; // 是否將工單用料加入tblOEMOMaterialList, True:是 False:否

                                // 2019/09/25 Grace 增加檢查, 若有傳入DeliveryMethod且值=4, 這筆工單用料清單, 不加入至tblOEMOMaterialList;否或非4則不做任何處理
                                // 材料型態tagname：DeliveryMethod (Optional參數,非必傳)
                                if (!(dr["DeliveryMethod"] is DBNull))
                                {
                                    if (dr["DeliveryMethod"].ToString() == "4")
                                    {
                                        blnAddMaterial = false;
                                    }
                                }

                                if (blnAddMaterial)
                                {
                                    strSQL = "insert into tbloemomateriallist(mono,materialno,materiallevel,stdqty,unitno,opno,putinplacetype," +
                                    "decreaserate,specified,materialtype,countway,checklotno,materialversion,materialmono,substitutematerialno,SubstituteMaterialLevel,SubstituteStdQty,RequireQty,mainItem,phantomItem,lockRequirement,operationSeqnum) " +
                                    "values('" + dr["MONo"].ToString().ToUpper() + "','" + dr["MaterialNo"].ToString().ToUpper() + "'," + dr["MaterialLevel"] + "," + dr["StdQty"] + ",'" + dr["UnitNo"].ToString().ToLower() +
                                    "','" + dr["OPNo"].ToString().ToUpper() + "'," + dr["PutInPlaceType"] + "," + dr["DecreaseRate"] + "," + dr["Specified"] + ",'" + dr["MaterialType"].ToString().ToUpper() + "'," + dr["CountWay"] +
                                    "," + dr["CheckLotNo"] + ",'" + dr["MaterialVersion"] + "','" + dr["MaterialMONo"] + "','" + dr["SubstituteMaterialNo"].ToString().ToUpper() + "'," + dr["SubstituteMaterialLevel"] + "," + dr["SubstituteStdQty"] + "," + dr["RequireQty"] + ",'" + dr["mainItem"] + "','" + dr["phantomItem"] + "','" + dr["lockRequirement"] + "','" + dr["operationSeqnum"] + "')";
                                    CollectionSQL.Add(strSQL);
                                    // cmd.CommandText = _
                                    // "insert into tbloemomateriallist(mono,materialno,materiallevel,stdqty,unitno,opno,putinplacetype," & _
                                    // "decreaserate,specified,materialtype,countway,checklotno,materialversion,materialmono,substitutematerialno,SubstituteMaterialLevel,SubstituteStdQty,RequireQty) " & _
                                    // "values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
                                    // cmd.Parameters.AddWithValue(":MONo", dr["MONo").ToString.ToUpper)
                                    // cmd.Parameters.AddWithValue(":MaterialNo", dr["MaterialNo").ToString.ToUpper)
                                    // cmd.Parameters.AddWithValue(":MaterialLevel", dr["MaterialLevel"))
                                    // cmd.Parameters.AddWithValue(":StdQty", dr["StdQty"))
                                    // cmd.Parameters.AddWithValue(":UnitNo", dr["UnitNo").ToString.ToLower)
                                    // cmd.Parameters.AddWithValue(":OPNo", dr["OPNo").ToString.ToUpper)
                                    // cmd.Parameters.AddWithValue(":PutInPlaceType", dr["PutInPlaceType"))
                                    // cmd.Parameters.AddWithValue(":DecreaseRate", dr["DecreaseRate"))
                                    // cmd.Parameters.AddWithValue(":Specified", dr["Specified"))
                                    // cmd.Parameters.AddWithValue(":MaterialType", dr["MaterialType").ToString.ToUpper)
                                    // cmd.Parameters.AddWithValue(":CountWay", dr["CountWay"))
                                    // cmd.Parameters.AddWithValue(":CheckLotNo", dr["CheckLotNo"))
                                    // cmd.Parameters.AddWithValue(":MaterialVersion", dr["MaterialVersion"))
                                    // cmd.Parameters.AddWithValue(":MaterialMONo", dr["MaterialMONo"))
                                    // cmd.Parameters.AddWithValue(":SubstituteMaterialNo", dr["SubstituteMaterialNo").ToString.ToUpper)
                                    // cmd.Parameters.AddWithValue(":SubstituteMaterialLevel", dr["SubstituteMaterialLevel")) '2012/12/26,Even,新增替代物料階 &數量
                                    // cmd.Parameters.AddWithValue(":SubstituteStdQty", dr["SubstituteStdQty")) '2012/12/28,Even,新增替代物標準數
                                    // cmd.Parameters.AddWithValue(":RequireQty", dr["RequireQty"))
                                    // cmd.ExecuteNonQuery()
                                    // cmd.Parameters.Clear()

                                }
                                // 將舊的OrgMaterialQty資料更新到tbloemomateriallist
                                DataRow[] drTemp = dtTemp.Select("MONo='" + dr["MONo"].ToString().ToUpper() + "'" + " And MaterialNo='" + dr["MaterialNo"].ToString().ToUpper() + "'" + " And OPNo='" +
                                    dr["OPNo"] + "'" + " And SubstituteMaterialNo='" + dr["SubstituteMaterialNo"].ToString().ToUpper() + "'");

                                foreach (DataRow drOrgMaterialQty in drTemp)
                                {
                                    strSQL = "update tbloemomateriallist set orgmaterialqty=" + drOrgMaterialQty["OrgMaterialQty"] +
                                             " where mono='" + dr["MONo"].ToString().ToUpper() + "' and materialno='" + dr["MaterialNo"].ToString().ToUpper() +
                                             "' and opno='" + dr["OPNo"].ToString().ToUpper() + "' and substitutematerialno='" + dr["SubstituteMaterialNo"].ToString().ToUpper() + "'";
                                    CollectionSQL.Add(strSQL);
                                    // cmd.CommandText = _
                                    // "update tbloemomateriallist set orgmaterialqty=?" & _
                                    // " where mono=? and materialno=? and opno=? and substitutematerialno=?"
                                    // cmd.Parameters.AddWithValue(":OrgMaterialQty", drOrgMaterialQty("OrgMaterialQty"))
                                    // cmd.Parameters.AddWithValue(":MONo", dr["MONo").ToString.ToUpper)
                                    // cmd.Parameters.AddWithValue(":MaterialNo", dr["MaterialNo").ToString.ToUpper)
                                    // cmd.Parameters.AddWithValue(":OPNo", dr["OPNo").ToString.ToUpper)
                                    // cmd.Parameters.AddWithValue(":SubstituteMaterialNo", dr["SubstituteMaterialNo").ToString.ToUpper)
                                    // cmd.ExecuteNonQuery()
                                    // cmd.Parameters.Clear()
                                }

                            }
                        }
                    }


                    // add MO Process
                    // 依目前規格書之「工單變更」:
                    // 「4.1	單頭只能修改數量(MOQty)與預定完工日(PlanFinishDate)兩個欄位」,
                    // 故工單流程暫不做修改


                    // add MO Property
                    if (dtMOProperty.Rows.Count > 0)
                    {
                        if (PropertyFlag)  // haoqian 221025
                        {
                            strSQL = "delete from tbloemoproperty where mono='" + MONo.ToUpper() + "'";
                            CollectionSQL.Add(strSQL);
                            // cmd.CommandText = "delete from tbloemoproperty where mono=?"
                            // cmd.Parameters.AddWithValue(":MONo", MONo.ToUpper)
                            // cmd.ExecuteNonQuery()
                            // cmd.Parameters.Clear()

                            strSQL = "delete from tbloemoproperty_recive where mono='" + MONo.ToUpper() + "'";
                            CollectionSQL.Add(strSQL);
                            // cmd.CommandText = "delete from tbloemoproperty_recive where mono=?"
                            // cmd.Parameters.AddWithValue(":MONo", MONo.ToUpper)
                            // cmd.ExecuteNonQuery()
                            // cmd.Parameters.Clear()

                            foreach (DataRow dr in dtMOProperty.Rows)
                            {
                                strSQL = "insert into tbloemoproperty(mono,propertyno,propertyvalue) values('" + dr["MONo"].ToString().ToUpper() + "','" + dr["PropertyNo"] + "','" + dr["PropertyValue"] + "')";
                                CollectionSQL.Add(strSQL);
                                // cmd.Parameters.AddWithValue(":MONo", dr["MONo").ToString.ToUpper)
                                // cmd.Parameters.AddWithValue(":PropertyNo", dr["PropertyNo"))
                                // cmd.Parameters.AddWithValue(":PropertyValue", dr["PropertyValue"))
                                // cmd.CommandText = "insert into tbloemoproperty(mono,propertyno,propertyvalue) values(?,?,?)"
                                // cmd.ExecuteNonQuery()
                                // cmd.Parameters.Clear()
                                strSQL = "insert into tbloemoproperty_recive(mono,propertyno,propertyvalue) values('" + dr["MONo"].ToString().ToUpper() + "','" + dr["PropertyNo"] + "','" + dr["PropertyValue"] + "')";
                                CollectionSQL.Add(strSQL);
                                // cmd.Parameters.AddWithValue(":MONo", dr["MONo").ToString.ToUpper)
                                // cmd.Parameters.AddWithValue(":PropertyNo", dr["PropertyNo"))
                                // cmd.Parameters.AddWithValue(":PropertyValue", dr["PropertyValue"))
                                // cmd.CommandText = "insert into tbloemoproperty_recive(mono,propertyno,propertyvalue) values(?,?,?)"
                                // cmd.ExecuteNonQuery()
                                // cmd.Parameters.Clear()
                            }
                        }
                        else   // haoqian 221025
                        {
                            foreach (DataRow dr in dtMOProperty.Rows)
                            {
                                strSQL = "update tbloemoproperty set propertyvalue = '" + dr["PropertyValue"] + "' where mono = '" + dr["MONo"].ToString().ToUpper() + "' and propertyno = '" + dr["PropertyNo"] + "'";
                                CollectionSQL.Add(strSQL);

                                strSQL = "update tbloemoproperty_recive set propertyvalue = '" + dr["PropertyValue"] + "' where mono = '" + dr["MONo"].ToString().ToUpper() + "' and propertyno = '" + dr["PropertyNo"] + "'";
                                CollectionSQL.Add(strSQL);

                            }

                        }
                    }

                    // 78079
                    // ----- MOComponent -----
                    // edit MO Component
                    using (var objOE = new clsOEBasis())
                    {
                        using (var objSYS = new clsSYSEng())
                        {
                            // Dim drOE As DataRow = objOE.GetMOBasis(MONo.ToUpper)
                            var dsOEMOC = objOE.ShowMOComponent(MONo.ToUpper());
                            if (dsOEMOC.Tables[0].Rows.Count > 0)
                            {
                                if (MOQty > dsOEMOC.Tables[0].Rows.Count)
                                {
                                    var dsCreateComponentNo = new DataSet();
                                    dsCreateComponentNo = objSYS.InitComponentNo(true, (int)Math.Round(MOQty - dsOEMOC.Tables[0].Rows.Count), MONo.ToUpper(), FactoryNo, CustomerNo, ProductNo, ProductVersion);
                                    if (!(dsCreateComponentNo.Tables == null) && dsCreateComponentNo.Tables[0].Rows.Count > 0)
                                    {
                                        for (int i = 1, loopTo = dsCreateComponentNo.Tables[0].Rows.Count; i <= loopTo; i++) // MOQty - dsOEMOC.Tables[0].Rows.Count
                                        {
                                            strSQL = "Insert into tblOEMOComponent (MoNo, ComponentNo, GoodQty, UnitNo, ReleaseState)" +
                                                    " Values ('" + MONo.ToUpper() + "', '" + dsCreateComponentNo.Tables[0].Rows[i - 1]["ComponentNo"].ToString() + "'," +
                                                    dsOEMOC.Tables[0].Rows[0]["GoodQty"] + ",'" + dsOEMOC.Tables[0].Rows[0]["UnitNo"] + "', 0)";
                                            CollectionSQL.Add(strSQL);
                                        }
                                    }
                                    if (dsCreateComponentNo != null)
                                        dsCreateComponentNo = null;
                                }
                            }
                            if (dsOEMOC != null)
                                dsOEMOC = null;
                        }
                    }

                    // add MO SEMI Out

                    // trans.Commit()
                    //string argstrDataBaseType = "Null";
                    ExecuteSQLNoneQuery_UPD(objSetting.GetDataBaseType(), objSetting.GetConnectionString(), CollectionSQL);
                    r = true;
                    clsERP.combineMessage(ref aryMessage, mmsg: "[%EditMOSuccess%]");
                }
                catch (Exception ex)
                {
                    // trans.Rollback()
                    clsERP.combineException(ref aryException, sysmsg: ex.Message, mesmsg: "[%EditMOFail%]", stack: iMESCore.Base.iMESComXML.CInput(ex.StackTrace));

                }
                // End Using
                // End Using
                // End Using

                exitfun:
                ;
            }


            catch (Exception ex)
            {
                clsERP.combineException(ref aryException, sysmsg: ex.Message, mesmsg: "[%EditMOFail%]", stack: iMESCore.Base.iMESComXML.CInput(ex.StackTrace));
            }
            finally
            {
                editMORet = r;
            }

            return editMORet;

        }

        /// <summary>
        /// 檢查SYS模組裡的工單屬性
        /// </summary>
        /// <param name="PropertyNo"></param>
        /// <param name="DataType"></param>
        /// <param name="IssueState"></param>
        /// <param name="aryMessage"></param>
        /// <param name="aryException"></param>
        /// <returns></returns>
        /// <remarks></remarks>
        public static object doSYSMOProperty(string PropertyNo, string DataType, int IssueState = 2, List<ArrayList> aryMessage = null, List<ArrayList> aryException = null)
        {
            object doSYSMOPropertyRet = default(object);
            bool r = false;
            try
            {

                // ----- 檢查MOProperty是否存在 -----
                using (var objSYS = new clsSYSEng())
                {

                    var dr = objSYS.GetMOProperty(PropertyNo);

                    // ----- MOProperty已存在 -----
                    if (dr["PropertyNo"] is DBNull == false)
                    {
                        r = true;
                        goto exitfun;
                    }

                    // ----- MOProperty不存在=>新增MOProperty -----
                    // DataType: 0:Numeric, 1:String, 2:Percent, 3:DateTime, 4:Boolean
                    int intType = 1;
                    switch (DataType.ToUpper())
                    {
                        case "NUMERIC":
                            {
                                intType = 0;
                                break;
                            }
                        case "STRING":
                            {
                                intType = 1;
                                break;
                            }
                        case "PERCENT":
                            {
                                intType = 2;
                                break;
                            }
                        case "DATETIME":
                            {
                                intType = 3;
                                break;
                            }
                        case "BOOLEAN":
                            {
                                intType = 4;
                                break;
                            }

                        default:
                            {
                                intType = 1;  // 預設為String
                                break;
                            }
                    }

                    try
                    {
                        objSYS.AddMOProperty(PropertyNo, PropertyNo, intType, 0);
                        objSYS.SetMOPropertyIssueState(PropertyNo, IssueState);
                        clsERP.combineMessage(ref aryMessage, mmsg: "[%AddSYSMOPropertySuccess%]");
                    }
                    catch (Exception ex)
                    {
                        clsERP.combineException(ref aryException, sysmsg: ex.Message, mesmsg: "[%AddSYSMOPropertyFail%]");
                        goto exitfun;
                    }

                    r = true;

                }

                exitfun:
                ;
            }


            catch (Exception ex)
            {
                clsERP.combineException(ref aryException, sysmsg: ex.Message, mesmsg: "[%doSYSMOPropertyFail%]", stack: iMESCore.Base.iMESComXML.CInput(ex.StackTrace));
            }
            finally
            {
                doSYSMOPropertyRet = r;
            }

            return doSYSMOPropertyRet;
        }
        /// <summary>
        /// 檢查工廠編號是否存在；不存在=>新增
        /// </summary>
        /// <param name="FactoryNo"></param>
        /// <param name="Creator"></param>
        /// <param name="CreateDate"></param>
        /// <param name="IssueState"></param>
        /// <param name="strMessage"></param>
        /// <param name="strException"></param>
        /// <returns></returns>
        /// <remarks></remarks>
        public static object doFactoryNo(string FactoryNo, string Creator, DateTime CreateDate, int IssueState = 2, List<ArrayList> strMessage = null, List<ArrayList> strException = null)
        {
            object doFactoryNoRet = default(object);
            bool r = false;
            try
            {

                // ----- 檢查工廠編號是否存在 -----
                using (var objSMD = new clsSMDBasis())
                {

                    var dr = objSMD.GetFactoryBasis(FactoryNo.ToUpper());

                    // ----- 工廠編號已存在 -----
                    if (dr["FactoryNo"] is DBNull == false)
                        goto exitfun;

                    // ----- 工廠編號不存在=>新增工廠編號 -----
                    try
                    {
                        objSMD.AddFactoryBasis(FactoryNo.ToUpper(), "(from ERP)", Creator: Creator, CreateDate: CreateDate);
                        objSMD.SetFactoryBasisIssueState(FactoryNo.ToUpper(), IssueState);
                        clsERP.combineMessage(ref strMessage, mmsg: "[%AddFactoryNoSuccess%]");
                    }
                    catch (Exception ex)
                    {
                        clsERP.combineException(ref strException, sysmsg: ex.Message, mesmsg: "[%AddFactoryNoFail%]", stack: iMESCore.Base.iMESComXML.CInput(ex.StackTrace));
                        goto exitfun;
                    }
                }
                r = true;
                exitfun:
                ;
            }


            catch (Exception ex)
            {
                clsERP.combineException(ref strException, sysmsg: ex.Message, mesmsg: "[%doFactoryFail%]", stack: iMESCore.Base.iMESComXML.CInput(ex.StackTrace));
            }
            finally
            {
                doFactoryNoRet = r;
            }

            return doFactoryNoRet;
        }
        private static bool ExamineMOProcess(string MONo, string ProductNo, string ProductVersion, int MOTypeNo, ref Collection colSQL, ref List<ArrayList> aryException, string CustomerLotNo = null)
        {

            bool blnExecResult = false;
            AppSettings objSetting = new AppSettings();
            IDbConnection cnnTemp = null;
            string strSQL = "", strSQLAddField = "", strSQLAddValue = "";
            var CollectionSQL = new Collection();
            string CustomerNo = "", DeviceNo = "";

            try
            {
                string strDataBaseType = objSetting.GetDataBaseType();
                string strConnectionString = objSetting.GetConnectionString(strDataBaseType);
                cnnTemp = CreateConnection(strConnectionString);
                DbDataReader drTemp;

                // 1.依據工單類型(MOTypeNo)找出預設的流程編號
                // 先查詢指定的工單類型，找不到再用MOType=*的資料(MOTypeNo =-1)
                var dtPRDPSNoList = new DataTable();
                var dtPorductProcess = new DataTable();
                strSQL = "select CustomerNo,DeviceNo from tblPRDProductBasis where ProductNo = '" + ProductNo + "' And ProductVersion = '" + ProductVersion + "'";
                drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp);
                if (drTemp.Read())
                {
                    CustomerNo = drTemp["CustomerNo"].ToString();
                    DeviceNo = drTemp["DeviceNo"].ToString();
                }
                drTemp.Close();

                strSQL = "SELECT PSNo FROM (" + " SELECT PSNo,Min(PSOrder) AS PSOrder FROM tblPRDProductProcess" + " WHERE ProductNo = '" + ProductNo + "' AND ProductVersion = '" + ProductVersion + "'" + " GROUP BY PSNo )A ORDER BY PSOrder";
                //using (var daTemp = new OleDbDataAdapter(strSQL, cnnTemp))
                //{
                //    daTemp.Fill(dtPRDPSNoList);
                //}
                ExecuteSQLQuery_Adapter(strSQL, dtPRDPSNoList, cnnTemp);

                foreach (DataRow drData in dtPRDPSNoList.Rows)
                {
                    var dtSinglePSNoProcess = new DataTable();
                    strSQL = "SELECT * FROM tblPRDProductProcess" + " WHERE ProductNo = '" + ProductNo + "' AND ProductVersion = '" + ProductVersion + "'" + " AND MOTypeNo = " + MOTypeNo + " AND DefaultProcess = 1" + " AND PSNo = '" +
                        drData["PSNo"] + "' ORDER BY PSOrder";
                    //using (var daTemp = new OleDbDataAdapter(strSQL, cnnTemp))
                    //{
                    //    daTemp.Fill(dtSinglePSNoProcess);
                    //}
                    ExecuteSQLQuery_Adapter(strSQL, dtSinglePSNoProcess, cnnTemp);

                    if (dtSinglePSNoProcess.Rows.Count.Equals(0))
                    {
                        strSQL = "SELECT * FROM tblPRDProductProcess" + " WHERE ProductNo = '" + ProductNo + "' AND ProductVersion = '" + ProductVersion + "'" + " AND MOTypeNo = -1 AND DefaultProcess = 1" + " AND PSNo = '" +
                            drData["PSNo"] + "' ORDER BY PSOrder";
                        //using (var daTemp = new OleDbDataAdapter(strSQL, cnnTemp))
                        //{
                        //    daTemp.Fill(dtSinglePSNoProcess);
                        //}
                        ExecuteSQLQuery_Adapter(strSQL, dtSinglePSNoProcess, cnnTemp);
                    }
                    dtPorductProcess.Merge(dtSinglePSNoProcess);
                }

                dtPRDPSNoList.Dispose();


                if (CustomerNo != "N/A" && DeviceNo != "N/A")
                {
                    string strMOTypeNo = MOTypeNo.ToString();
                    DataSet dsECN = new DataSet();
                    var dtECN = new DataTable();
                    var dtNewPorductProcess = new DataTable();
                    DataRow drECN;

                    dtECN.Columns.Add("MONo", Type.GetType("System.String"));
                    dtECN.Columns.Add("CustomerLotNo", Type.GetType("System.String"));

                    drECN = dtECN.NewRow();
                    drECN["MONo"] = MONo;
                    drECN["CustomerLotNo"] = CustomerLotNo;
                    dtECN.Rows.Add(drECN);

                    dsECN = ShowECNProcessData(ProductNo, ProductVersion, strMOTypeNo, ref aryException, dtECN);

                    if (aryException.Count <= 0)
                    {
                        short intProcessOrder = 1;
                        foreach (DataRow drProcess in dsECN.Tables["tblECNProcessData"].Rows)
                        {
                            string strProcessNo = drProcess["ProcessNo"].ToString();
                            string strProcessVersion = drProcess["ProcessVersion"].ToString();


                            strSQL = "SELECT * FROM tblPRDProductProcess" + " WHERE ProductNo = '" + ProductNo + "' AND ProductVersion = '" + ProductVersion + "'" + " And ProcessNo = '" +
                            strProcessNo + "'" + "   AND ProcessVersion = '" + strProcessVersion + "' AND MOTypeNo = " + MOTypeNo + "";
                            ExecuteSQLQuery_Adapter(strSQL, dtNewPorductProcess, cnnTemp);
                        }
                        foreach (DataRow drNewProcess in dtNewPorductProcess.Rows)
                        {

                            // 以指定流程版本新增工單流程
                            strSQL = "SELECT B.ProcessNo, B.ProcessVersion, B.NodeNo, B.NodeId" + " FROM tblPRSProcessBasis A join tblPRSNodeBasis B ON A.ProcessNo = B.ProcessNo AND A.ProcessVersion = B.ProcessVersion" + " WHERE A.ProcessNo = '" +
                            drNewProcess["ProcessNo"].ToString() + "'" + " AND A.ProcessVersion = '" + drNewProcess["ProcessVersion"].ToString() + "'" + " AND B.NodeId = (" + "   SELECT Min(B.ToNodeId)" +
                            "   FROM tblPRSProcessBasis A join tblPRSNodeRelation B ON A.ProcessNo = B.ProcessNo AND A.ProcessVersion = B.ProcessVersion" + "   WHERE A.ProcessNo = '" +
                            drNewProcess["ProcessNo"].ToString() + "'" + "   AND A.ProcessVersion = '" + drNewProcess["ProcessVersion"].ToString() + "'" + "   And B.FromNodeNo = 'START' GROUP BY A.ProcessNo)";
                            drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp);
                            if (drTemp.Read())
                            {
                                // 應該只有一筆資料，每一個流程也只需要新增一筆資料
                                // 2019/01/23 OwenLiu, 修正工單流程存入ProcessVersion 為 * 的問題
                                strSQLAddField = "INSERT INTO tblOEMOProcess (MONo,PSNo,PSOrder,ProcessOrder,ProcessNo,ProcessVersion";
                                strSQLAddValue = " VALUES ('" + MONo + "','" +
                                    drNewProcess["PSNo"] + "'," + drNewProcess["PSOrder"] + "," + intProcessOrder.ToString() + ",'" + drNewProcess["ProcessNo"].ToString() + "'" + ",'" + drTemp["ProcessVersion"].ToString() +
                                    "'";

                                strSQLAddField += ",OPNo,NodeId,HaveComponent,HaveLevel";
                                strSQLAddValue = strSQLAddValue + ",'" +
                                    drTemp["NodeNo"] + "','" + drTemp["NodeId"] + "'" + "," + drNewProcess["HaveComponent"] + "," + drNewProcess["HaveLevel"];
                                strSQL = strSQLAddField + ")" + strSQLAddValue + ")";
                                CollectionSQL.Add(strSQL);
                                intProcessOrder = (short)(intProcessOrder + 1);
                            }
                            drTemp.Close();
                        }
                    }
                }
                else
                {
                    short intProcessOrder = 1;
                    foreach (DataRow drProcess in dtPorductProcess.Rows)
                    {
                        string strProcessNo = drProcess["ProcessNo"].ToString();
                        string strProcessVersion = drProcess["ProcessVersion"].ToString();
                        if (strProcessVersion == "*")
                        {
                            // 以目前最新流程新增工單流程
                            strSQL = "SELECT B.ProcessNo, B.ProcessVersion, B.NodeNo, B.NodeId" + " FROM tblPRSProcessBasis A join tblPRSNodeBasis B ON A.ProcessNo = B.ProcessNo AND A.ProcessVersion = B.ProcessVersion" + " WHERE A.ProcessNo = '" +
                                drProcess["ProcessNo"] + "' AND A.CurVersion = 1" + " AND B.NodeId = (" + "   SELECT Min(B.ToNodeId)" + "   FROM tblPRSProcessBasis A join tblPRSNodeRelation B ON A.ProcessNo = B.ProcessNo AND A.ProcessVersion = B.ProcessVersion" +
                                "   WHERE A.ProcessNo = '" + drProcess["ProcessNo"] + "' AND A.CurVersion = 1" + "   AND B.FromNodeNo = 'START' GROUP BY A.ProcessNo)";
                        }
                        else
                        {
                            // 以指定流程版本新增工單流程
                            strSQL = "SELECT B.ProcessNo, B.ProcessVersion, B.NodeNo, B.NodeId" + " FROM tblPRSProcessBasis A join tblPRSNodeBasis B ON A.ProcessNo = B.ProcessNo AND A.ProcessVersion = B.ProcessVersion" + " WHERE A.ProcessNo = '" +
                                drProcess["ProcessNo"] + "'" + " AND A.ProcessVersion = '" + strProcessVersion + "'" + " AND B.NodeId = (" + "   SELECT Min(B.ToNodeId)" +
                                "   FROM tblPRSProcessBasis A join tblPRSNodeRelation B ON A.ProcessNo = B.ProcessNo AND A.ProcessVersion = B.ProcessVersion" + "   WHERE A.ProcessNo = '" +
                                drProcess["ProcessNo"] + "'" + "   AND A.ProcessVersion = '" + strProcessVersion + "'" + "   And B.FromNodeNo = 'START' GROUP BY A.ProcessNo)";
                        }

                        //using (var cmdProcess = new OleDbCommand(strSQL, cnnTemp))
                        //{
                        //var drTemp = cmdProcess.ExecuteReader();
                        drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp);
                        if (drTemp.Read())
                        {
                            // 應該只有一筆資料，每一個流程也只需要新增一筆資料
                            // 2019/01/23 OwenLiu, 修正工單流程存入ProcessVersion 為 * 的問題
                            strSQLAddField = "INSERT INTO tblOEMOProcess (MONo,PSNo,PSOrder,ProcessOrder,ProcessNo,ProcessVersion";
                            strSQLAddValue = " VALUES ('" + MONo + "','" +
                                drProcess["PSNo"] + "'," + drProcess["PSOrder"] + "," + intProcessOrder.ToString() + ",'" + strProcessNo + "'" + ",'" + drTemp["ProcessVersion"].ToString() +
                                "'";

                            strSQLAddField += ",OPNo,NodeId,HaveComponent,HaveLevel";
                            strSQLAddValue = strSQLAddValue + ",'" +
                                drTemp["NodeNo"] + "','" + drTemp["NodeId"] + "'" + "," + drProcess["HaveComponent"] + "," + drProcess["HaveLevel"];
                            strSQL = strSQLAddField + ")" + strSQLAddValue + ")";
                            CollectionSQL.Add(strSQL);
                            intProcessOrder = (short)(intProcessOrder + 1);
                        }
                        drTemp.Close();
                        //}
                    }
                }




                // 將收集到的SQL語句加以回傳，由呼叫端統一執行
                if (colSQL != null)
                {
                    for (int i = 1, loopTo = CollectionSQL.Count; i <= loopTo; i++)
                        colSQL.Add(CollectionSQL[i]);
                }

                blnExecResult = true;
            }
            catch (Exception ex)
            {
                clsERP.combineException(ref aryException, sysmsg: ex.Message, mesmsg: "[%ExamineMOProcess%]", stack: iMESCore.Base.iMESComXML.CInput(ex.StackTrace));
            }
            finally
            {
                CloseConnection(cnnTemp);
            }

            return default(bool);

        }
        private static DataSet ShowECNProcessData(string ProductNo, string ProductVersion, string MOTypeNo, ref List<ArrayList> aryException, DataTable dtECN)
        {
            DataSet ShowECNProcessDataRet = default(DataSet);

            // dtECN 傳入LotNo,OrgLotNo,CustomerLotNo,MONo 的資料只會有一筆

            var CollectionSQL = new Collection();
            var CreateDate = DateTime.Now;
            string strSQLAddField, strSQLAddValue;
            string strSQL = "";
            var drTemp = default(DbDataReader);
            DbDataReader drSEN;
            DbDataReader drTECN;
            DbDataReader drECN;
            var dtProcess = new DataTable();
            string tblECNProcessData;
            tblECNProcessData = "tblECNProcessData";
            dtProcess.TableName = tblECNProcessData;
            dtProcess.Columns.Add("ECNNO", Type.GetType("System.String"));
            dtProcess.Columns.Add("PROCESSNO", Type.GetType("System.String"));
            dtProcess.Columns.Add("PROCESSVERSION", Type.GetType("System.String"));
            dtProcess.Columns.Add("ECNTYPE", Type.GetType("System.String"));

            AppSettings objSetting = new AppSettings();
            bool blnAllProcess = false; // 用於判斷ECN是否有多條流程
            var cnnTemp = default(IDbConnection);

            try
            {
                string strDataBaseType = objSetting.GetDataBaseType();
                string strConnectionString = objSetting.GetConnectionString(strDataBaseType);
                cnnTemp = CreateConnection(strConnectionString);

                DataSet dsTemp;
                DataRow[] drSel;

                cnnTemp = CreateConnection(strConnectionString);

                // 檢查SEN
                strSQL = "Select * from TBLPRDECNPROCESS where ProductNo='" + ProductNo + "' and productversion='" + ProductVersion + "' and ECNType='SEN' and ECNState=2 ORDER BY  SENType Desc ";
                dsTemp = new DataSet();
                ExecuteSQLQuery_Adapter(strSQL, dsTemp, "TBLPRDECNPROCESS", cnnTemp);

                drSel = dsTemp.Tables["TBLPRDECNPROCESS"].Select();
                if (drSel.Length > 0)
                {
                    foreach (DataRow r in drSel)
                    {
                        strSQL = "Select * from TBLPRDSENLOTDETAIL where ProductNo='" + ProductNo + "' and productversion='" + ProductVersion + "' and ECNNO='" + r["ECNNO"].ToString() + "'";
                        ////cmmTemp = new IDbCommand(strSQL, cnnTemp); // Select data
                        drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp);
                        while (drTemp.Read()) // 比對有無相符的資料
                        {
                            switch (drTemp["SENTYPE"].ToString())
                            {
                                case "1": //客戶批號
                                    {
                                        dtECN.DefaultView.RowFilter = "CustomerLotNo like '" + drTemp["LOTNO"].ToString() + "'";
                                        if (dtECN.DefaultView.Count == 1)
                                        {
                                            // 以ECNNO跟工單類型尋找
                                            strSQL = "Select * from TBLPRDMOPROCESS where ProductNo='" + ProductNo + "' and productversion='" + ProductVersion + "' and ECNNO='" + r["ECNNO"].ToString() + "' and MOTypeNo='" + MOTypeNo + "' ";
                                            ////cmmTemp = new IDbCommand(strSQL, cnnTemp); // Select data
                                            drSEN = ExecuteSQLQuery_Reader(strSQL, cnnTemp);
                                            while (drSEN.Read())
                                            {
                                                dtProcess.Rows.Add(r["ECNNO"].ToString(), drSEN["PROCESSNO"].ToString(), drSEN["PROCESSVERSION"], "SEN");
                                                blnAllProcess = true;
                                            }

                                            // 若目前工單類型找不到資料以*尋找
                                            strSQL = "Select * from TBLPRDMOPROCESS where ProductNo='" + ProductNo + "' and productversion='" + ProductVersion + "' and ECNNO='" + r["ECNNO"].ToString() + "' and MOTypeNo='-1' ";
                                            ////cmmTemp = new IDbCommand(strSQL, cnnTemp); // Select data
                                            drSEN = ExecuteSQLQuery_Reader(strSQL, cnnTemp);
                                            while (drSEN.Read())
                                            {
                                                dtProcess.Rows.Add(r["ECNNO"].ToString(), drSEN["PROCESSNO"].ToString(), drSEN["PROCESSVERSION"], "SEN");
                                                blnAllProcess = true;
                                            }


                                            goto GoTonext;
                                        }

                                        break;
                                    }
                                case "0": //工單編號
                                    {
                                        dtECN.DefaultView.RowFilter = "MONo like '" + drTemp["LOTNO"].ToString() + "'";
                                        if (dtECN.DefaultView.Count == 1)
                                        {
                                            // 以ECNNO跟工單類型尋找
                                            strSQL = "Select * from TBLPRDMOPROCESS where ProductNo='" + ProductNo + "' and productversion='" + ProductVersion + "' and ECNNO='" + r["ECNNO"].ToString() + "' and MOTypeNo='" + MOTypeNo + "' ";
                                            ////cmmTemp = new IDbCommand(strSQL, cnnTemp); // Select data
                                            drSEN = ExecuteSQLQuery_Reader(strSQL, cnnTemp);
                                            while (drSEN.Read())
                                            {
                                                dtProcess.Rows.Add(r["ECNNO"].ToString(), drSEN["PROCESSNO"].ToString(), drSEN["PROCESSVERSION"], "SEN");
                                                blnAllProcess = true;
                                            }

                                            // 若目前工單類型找不到資料以*尋找
                                            strSQL = "Select * from TBLPRDMOPROCESS where ProductNo='" + ProductNo + "' and productversion='" + ProductVersion + "' and ECNNO='" + r["ECNNO"].ToString() + "' and MOTypeNo='-1' ";
                                            ////cmmTemp = new IDbCommand(strSQL, cnnTemp); // Select data
                                            drSEN = ExecuteSQLQuery_Reader(strSQL, cnnTemp);
                                            while (drSEN.Read())
                                            {
                                                dtProcess.Rows.Add(r["ECNNO"].ToString(), drSEN["PROCESSNO"].ToString(), drSEN["PROCESSVERSION"], "SEN");
                                                blnAllProcess = true;
                                            }

                                            goto GoTonext;
                                        }

                                        break;
                                    }

                            }
                        }
                        drTemp.Close();
                        ////cmmTemp.Dispose();
                    }
                }

                if (dsTemp != null)
                {
                    dsTemp.Dispose();
                }

                // 2020/03/17 Eric
                if (blnAllProcess == true)
                {
                    goto GoTonext;
                }

                // 檢查TECN
                strSQL = "Select * from TBLPRDECNPROCESS where ProductNo='" + ProductNo + "' and productversion='" + ProductVersion + "' and ECNType='TECN' and ECNState=2 " + "And StartTime <=  To_Date('" + Strings.Format(DateTime.Now, "yyyy/MM/dd HH:mm:ss") + "','YYYY/MM/DD HH24:MI:SS') And EndTime >  To_Date('" + Strings.Format(DateTime.Now, "yyyy/MM/dd HH:mm:ss") + "','YYYY/MM/DD HH24:MI:SS')";
                // 2020/02/04 OwenLiu, 修正SQLServer 查詢問題
                strSQL = SQLCommandTuning(strDataBaseType, ref strSQL);
                drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp);
                if (drTemp.Read())
                {
                    // 以ECNNO跟工單類型尋找
                    strSQL = "Select * from TBLPRDMOPROCESS where ProductNo='" + ProductNo + "' and productversion='" + ProductVersion + "' and ECNNO='" + drTemp["ECNNO"].ToString() + "' and MOTypeNo='" + MOTypeNo + "' ";
                    drTECN = ExecuteSQLQuery_Reader(strSQL, cnnTemp);
                    while (drTECN.Read())
                    {
                        dtProcess.Rows.Add(drTemp["ECNNO"].ToString(), drTECN["PROCESSNO"].ToString(), drTECN["PROCESSVERSION"], "TECN");
                        blnAllProcess = true;
                    }

                    // 若目前工單類型找不到資料以*尋找
                    strSQL = "Select * from TBLPRDMOPROCESS where ProductNo='" + ProductNo + "' and productversion='" + ProductVersion + "' and ECNNO='" + drTemp["ECNNO"].ToString() + "' and MOTypeNo='-1' ";
                    ////cmmTemp = new IDbCommand(strSQL, cnnTemp); // Select data
                    drTECN = ExecuteSQLQuery_Reader(strSQL, cnnTemp);
                    while (drTECN.Read())
                    {
                        dtProcess.Rows.Add(drTemp["ECNNO"].ToString(), drTECN["PROCESSNO"].ToString(), drTECN["PROCESSVERSION"], "TECN");
                        blnAllProcess = true;
                    }

                    // 若有ECNNO卻無流程編號及版本回拋錯誤
                    goto GoTonext;
                }
                drTemp.Close();

                // 2020/03/17 Eric
                if (blnAllProcess == true)
                {
                    goto GoTonext;
                }

                // 檢查ECN
                strSQL = "Select * from TBLPRDECNPROCESS where ProductNo='" + ProductNo + "' and productversion='" + ProductVersion + "' and ECNType='ECN' and ECNState=2 ";
                drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp);
                if (drTemp.Read())
                {
                    // 以ECNNO跟工單類型尋找
                    strSQL = "Select * from TBLPRDMOPROCESS where ProductNo='" + ProductNo + "' and productversion='" + ProductVersion + "' and ECNNO='" + drTemp["ECNNO"].ToString() + "' and MOTypeNo='" + MOTypeNo + "' ";
                    drECN = ExecuteSQLQuery_Reader(strSQL, cnnTemp);
                    while (drECN.Read())
                        dtProcess.Rows.Add(drTemp["ECNNO"].ToString(), drECN["PROCESSNO"].ToString(), drECN["PROCESSVERSION"], "ECN");

                    // 若目前工單類型找不到資料以*尋找
                    strSQL = "Select * from TBLPRDMOPROCESS where ProductNo='" + ProductNo + "' and productversion='" + ProductVersion + "' and ECNNO='" + drTemp["ECNNO"].ToString() + "' and MOTypeNo='-1' ";
                    drECN = ExecuteSQLQuery_Reader(strSQL, cnnTemp);
                    while (drECN.Read())
                        dtProcess.Rows.Add(drTemp["ECNNO"].ToString(), drECN["PROCESSNO"].ToString(), drECN["PROCESSVERSION"], "ECN");

                    // 若有ECNNO卻無流程編號及版本回拋錯誤
                    goto GoTonext;
                }

                GoTonext:
                ;

                drTemp.Close();

                if (dtProcess.Rows.Count <= 0) { clsERP.combineException(ref aryException, mesmsg: "[%ProductNo%]:" + ProductNo + "[%CouldNotFindTheCorrespondingProcessData%]"); } //拋出找不到對應流程資料的錯誤，不允許新增工單

                if (dsTemp != null)
                {
                    dsTemp.Dispose();
                }
                dsTemp.Tables.Add(dtProcess);
                ShowECNProcessDataRet = dsTemp;
                //LoadECNProcessDataRet = iMESCore.Base.iMESComXML.CombineXMLReturnValue("loadecnprocessdata", tblECNProcessData, "DataSet", iMESCore.Base.iMESComXML.FormatXMLSchema(dsTemp.GetXmlSchema()), dsTemp.GetXml(), "");                
            }

            catch (Exception e1)
            {

                // 發生錯誤時丟回本身的Function Name及系統錯誤訊息
                throw;

            }
            finally
            {
                if (cnnTemp != null)
                {
                    CloseConnection(cnnTemp);
                }
            }
            return ShowECNProcessDataRet;

        }
        #endregion  
    }
}
