using API_Base;
using iMESCIOC.Request.EAP;
using iMESCIOC.Request.ERP;
using iMESCIOC.Request.WMS_Request;
using iMESCIOC.Response.EAP;
using iMESCIOC.Response.ERP;
using iMESCIOC.Response.WMS_Response;
using iMESCore.Settings;
using Microsoft.VisualBasic;
using Microsoft.VisualBasic.CompilerServices;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data;
using System.Linq;
using System.Net.Http.Headers;
using System.Reflection;
//using System.Web.Services;
using System.Xml;
using System.Xml;
using tcEAI_C;
using static iMESCore.Base.iMESConst;

namespace EAIws_C
{

    static class modERP
    {

        public static string strService = "ERP";
        public static string strDataBaseType;
        public static string strConnectionString;

        //public static string funCreateOperation(string InXml)
        //{
        //    string funCreateOperationRet = default(string);
        //    System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();    // 用以讀取Xml字串
        //    string OutXml = null;

        //    string strIdentity = string.Empty;    // Identity XML字串
        //    string strResult = "fail";            // Result XML字串
        //    List<ArrayList> strException = new List<ArrayList>();  // Exception XML字串
        //    List<ArrayList> strMessage = new List<ArrayList>();    // Message XML字串
        //    string strKeyValue = string.Empty;    // TransactionLot KeyValue
        //    string strMode = string.Empty;        // Mode

        //    try
        //    {
        //        try
        //        {
        //            // 讀取InXml字串
        //            xmlDoc.LoadXml(InXml);
        //        }
        //        catch (Exception ex)
        //        {
        //            clsERP.combineException(ref strException, null, ex.Message, "[%InXmlError%]", ex.StackTrace);
        //            goto exitFun;
        //        }

        //        // 組Identity字串
        //        try
        //        {
        //            strIdentity = modWS.CombineXMLIdentity(xmlDoc);
        //        }
        //        catch (Exception ex)
        //        {
        //            clsERP.combineException(ref strException, null, ex.Message, "[%IndentityError%]", ex.StackTrace);
        //            goto exitFun;
        //        }


        //        // 2019/05/09 OwenLiu, Mantis:0057304 作業站整合若資料已存在，
        //        // 且ERP未傳值的狀況， 不更新OPType, OPClass, OPShortName, OPOrder
        //        string OPNo = string.Empty;
        //        string OPName = string.Empty;
        //        string OPType = defString;
        //        string PSNo = defString;
        //        int OPClass = defInteger;                      // Default 0 : General OP
        //        string OPShortName = defString;
        //        int OPOrder = defInteger;                        // Default 0
        //        string Description = string.Empty;
        //        string Creator = string.Empty;
        //        DateTime CreateDate = DateTime.Now;               // Default Today
        //        int PrintOutOnRunCard = 1;                // Default 1
        //        double StdUnitRunTime = 0;                    // Default 0
        //        long CountOpUnitQty = 1;                      // Default 1
        //        double StdQueueTime = 0;                      // Default 0
        //        decimal decStdUnitRunTime = defInteger;
        //        decimal decCountOpUnitQty = defInteger;
        //        decimal decStdQueueTime = defInteger;
        //        int OSOption = defInteger;
        //        int OSOptionTemp = defInteger;
        //        string ERPPDLineNo = defString;
        //        // Dim OldERPPDLineNo As String = defString '存放作業站修改前的群組資料

        //        // OPNo
        //        if (xmlDoc.DocumentElement.GetElementsByTagName("opno").Count > 0 && xmlDoc.GetElementsByTagName("opno").Item(0).SelectNodes("value").Count > 0)
        //            OPNo = modWS.CInput(xmlDoc.DocumentElement.GetElementsByTagName("opno").Item(0).SelectNodes("value").Item(0).InnerText);

        //        // OPName
        //        if (xmlDoc.DocumentElement.GetElementsByTagName("opname").Count > 0 && xmlDoc.GetElementsByTagName("opname").Item(0).SelectNodes("value").Count > 0)
        //            OPName = modWS.CInput(xmlDoc.DocumentElement.GetElementsByTagName("opname").Item(0).SelectNodes("value").Item(0).InnerText);



        //        // 判斷成功與否
        //        if (strException.Count > 0)
        //            goto exitFun;

        //        strResult = "success";

        //    exitFun:
        //        ;
        //    }

        //    catch (Exception ex)
        //    {
        //        clsERP.combineException(ref strException, null, ex.Message, "[%CreateOPFail%]", ex.StackTrace);
        //    }

        //    finally
        //    {

        //        // 將各部份之XML字串組起來並傳出
        //        OutXml = modWS.CombineXMLResponse(strIdentity, null, strException, strResult, strMessage);

        //        funCreateOperationRet = OutXml;
        //    }

        //    return funCreateOperationRet;
        //}


        #region --- SD_DSC_SI009 MO ---
        public static string funAddMO(string InXml)
        {
            string funAddMORet = default(string);

            var xmlDoc = new XmlDocument();    // 用以讀取Xml字串
            XmlNodeList xmlList;
            string OutXml = null;

            string strIdentity = string.Empty;    // Identity XML字串
            string strResult = "fail";            // Result XML字串
            var strException = new List<ArrayList>();  // Exception XML字串
            var strMessage = new List<ArrayList>();    // Message XML字串
            string strKeyValue = string.Empty;    // TransactionLot KeyValue
            var strAlert = new List<ArrayList>();

            try
            {

                try
                {
                    // 讀取InXml字串
                    xmlDoc.LoadXml(InXml);
                }
                catch (Exception ex)
                {
                    clsERP.combineException(ref strException, sysmsg: ex.Message, mesmsg: "[%InXmlError%]", stack: ex.StackTrace);
                    goto exitFun;
                }

                // 組Identity字串
                try
                {
                    strIdentity = modWS.CombineXMLIdentity(xmlDoc);
                }
                catch (Exception ex)
                {
                    clsERP.combineException(ref strException, sysmsg: ex.Message, mesmsg: "[%IndentityError%]", stack: ex.StackTrace);
                    goto exitFun;
                }

                string MONo = string.Empty;
                string RONo = string.Empty;
                string ItemNo = string.Empty;          // RO ItemNo
                string CustomerNo = string.Empty;
                string CustomerLotNo = string.Empty;
                string MOUnitNo = string.Empty;        // MOUnitNo
                string ProductNo = string.Empty;
                string ProductVersion = string.Empty;
                decimal MOQty = 0m;
                int MOTypeNo = Conversions.ToInteger(ConfigurationManager.AppSettings["defMOTypeNo"]);
                int Priority = Conversions.ToInteger(ConfigurationManager.AppSettings["defMOPriority"]);
                var PlanFinishDate = DateAndTime.DateAdd(DateInterval.Day, Conversions.ToInteger(ConfigurationManager.AppSettings["defMOPlanFinishDate"]), DateTime.Now);
                var PlanStartDate = DateAndTime.DateAdd(DateInterval.Day, Conversions.ToInteger(ConfigurationManager.AppSettings["defMOPlanStartDate"]), Convert.ToDateTime(Strings.Format(DateTime.Now, "yyyy/MM/dd")));
                string Creator = string.Empty;
                var CreateDate = DateTime.Now;        // Default Today
                string Description = string.Empty;
                string FactoryNo = string.Empty;
                var MOProperty = new List<ArrayList>();
                int MaterialLevel = defInteger;
                int wipEntityId = defInteger;
                string bomVersion = string.Empty;
                string lcPlantype = string.Empty;
                string faiFlag = string.Empty;

                string strERPMOLineNo = defString;
                string strDeliveryMethod = defString;

                string SubstituteMaterialNo = string.Empty;
                string MaterialNo = string.Empty;
                string OPNO = string.Empty;
                string Orgcode = string.Empty;
                string OrgMono = string.Empty;

                if (xmlDoc.DocumentElement.GetElementsByTagName("orgcode").Count > 0 && xmlDoc.GetElementsByTagName("orgcode").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("orgcode").Item(0).SelectNodes("value").Item(0).InnerText))


                {
                    string argstrInput = xmlDoc.DocumentElement.GetElementsByTagName("orgcode").Item(0).SelectNodes("value").Item(0).InnerText;
                    Orgcode = modWS.CInput_Singlequotation(argstrInput);
                    xmlDoc.DocumentElement.GetElementsByTagName("orgcode").Item(0).SelectNodes("value").Item(0).InnerText = argstrInput;
                }

                if (xmlDoc.DocumentElement.GetElementsByTagName("orgmono").Count > 0 && xmlDoc.GetElementsByTagName("orgmono").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("orgmono").Item(0).SelectNodes("value").Item(0).InnerText))


                {
                    string argstrInput = xmlDoc.DocumentElement.GetElementsByTagName("orgmono").Item(0).SelectNodes("value").Item(0).InnerText;
                    OrgMono = modWS.CInput_Singlequotation(argstrInput);
                    xmlDoc.DocumentElement.GetElementsByTagName("orgmono").Item(0).SelectNodes("value").Item(0).InnerText = argstrInput;
                }
                // MONo
                if (xmlDoc.DocumentElement.GetElementsByTagName("mono").Count > 0 && xmlDoc.GetElementsByTagName("mono").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("mono").Item(0).SelectNodes("value").Item(0).InnerText))


                {
                    string argstrInput = xmlDoc.DocumentElement.GetElementsByTagName("mono").Item(0).SelectNodes("value").Item(0).InnerText;
                    MONo = modWS.CInput_Singlequotation(argstrInput);
                    xmlDoc.DocumentElement.GetElementsByTagName("mono").Item(0).SelectNodes("value").Item(0).InnerText = argstrInput;
                }

                // RONo
                if (xmlDoc.DocumentElement.GetElementsByTagName("rono").Count > 0 && xmlDoc.GetElementsByTagName("rono").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("rono").Item(0).SelectNodes("value").Item(0).InnerText))


                {
                    string argstrInput1 = xmlDoc.DocumentElement.GetElementsByTagName("rono").Item(0).SelectNodes("value").Item(0).InnerText;
                    RONo = modWS.CInput_Singlequotation(argstrInput1);
                    xmlDoc.DocumentElement.GetElementsByTagName("rono").Item(0).SelectNodes("value").Item(0).InnerText = argstrInput1;
                }

                // ItemNo
                if (xmlDoc.DocumentElement.GetElementsByTagName("itemno").Count > 0 && xmlDoc.GetElementsByTagName("itemno").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("itemno").Item(0).SelectNodes("value").Item(0).InnerText))


                {
                    string argstrInput2 = xmlDoc.DocumentElement.GetElementsByTagName("itemno").Item(0).SelectNodes("value").Item(0).InnerText;
                    ItemNo = modWS.CInput_Singlequotation(argstrInput2);
                    xmlDoc.DocumentElement.GetElementsByTagName("itemno").Item(0).SelectNodes("value").Item(0).InnerText = argstrInput2;
                }

                // 如傳入的值為0001則轉換成1
                if (!string.IsNullOrEmpty(ItemNo))
                {
                    ItemNo = Conversions.ToInteger(ItemNo).ToString();
                }


                // CustomerNo
                if (xmlDoc.DocumentElement.GetElementsByTagName("customerno").Count > 0 && xmlDoc.GetElementsByTagName("customerno").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("customerno").Item(0).SelectNodes("value").Item(0).InnerText))


                {
                    string argstrInput3 = xmlDoc.DocumentElement.GetElementsByTagName("customerno").Item(0).SelectNodes("value").Item(0).InnerText;
                    CustomerNo = modWS.CInput_Singlequotation(argstrInput3);
                    xmlDoc.DocumentElement.GetElementsByTagName("customerno").Item(0).SelectNodes("value").Item(0).InnerText = argstrInput3;
                }

                // CustomerLotNo
                if (xmlDoc.DocumentElement.GetElementsByTagName("customerlotno").Count > 0 && xmlDoc.GetElementsByTagName("customerlotno").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("customerlotno").Item(0).SelectNodes("value").Item(0).InnerText))


                {
                    string argstrInput3 = xmlDoc.DocumentElement.GetElementsByTagName("customerlotno").Item(0).SelectNodes("value").Item(0).InnerText;
                    CustomerLotNo = modWS.CInput_Singlequotation(argstrInput3);
                    xmlDoc.DocumentElement.GetElementsByTagName("customerlotno").Item(0).SelectNodes("value").Item(0).InnerText = argstrInput3;
                }

                // MOUnitNo
                if (xmlDoc.DocumentElement.GetElementsByTagName("mounitno").Count > 0 && xmlDoc.GetElementsByTagName("mounitno").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("mounitno").Item(0).SelectNodes("value").Item(0).InnerText))


                {
                    string argstrInput4 = xmlDoc.DocumentElement.GetElementsByTagName("mounitno").Item(0).SelectNodes("value").Item(0).InnerText;
                    MOUnitNo = modWS.CInput_Singlequotation(argstrInput4);
                    xmlDoc.DocumentElement.GetElementsByTagName("mounitno").Item(0).SelectNodes("value").Item(0).InnerText = argstrInput4;
                }

                // ProductNo
                if (xmlDoc.DocumentElement.GetElementsByTagName("productno").Count > 0 && xmlDoc.GetElementsByTagName("productno").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("productno").Item(0).SelectNodes("value").Item(0).InnerText))


                {
                    string argstrInput5 = xmlDoc.DocumentElement.GetElementsByTagName("productno").Item(0).SelectNodes("value").Item(0).InnerText;
                    ProductNo = modWS.CInput_Singlequotation(argstrInput5);
                    xmlDoc.DocumentElement.GetElementsByTagName("productno").Item(0).SelectNodes("value").Item(0).InnerText = argstrInput5;
                }

                // FactoryNo
                if (xmlDoc.DocumentElement.GetElementsByTagName("factoryno").Count > 0 && xmlDoc.GetElementsByTagName("factoryno").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("factoryno").Item(0).SelectNodes("value").Item(0).InnerText))


                {
                    string argstrInput6 = xmlDoc.DocumentElement.GetElementsByTagName("factoryno").Item(0).SelectNodes("value").Item(0).InnerText;
                    FactoryNo = modWS.CInput_Singlequotation(argstrInput6);
                    xmlDoc.DocumentElement.GetElementsByTagName("factoryno").Item(0).SelectNodes("value").Item(0).InnerText = argstrInput6;
                }

                // MOQty
                if (xmlDoc.DocumentElement.GetElementsByTagName("moqty").Count > 0 && xmlDoc.GetElementsByTagName("moqty").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("moqty").Item(0).SelectNodes("value").Item(0).InnerText) && Information.IsNumeric(xmlDoc.DocumentElement.GetElementsByTagName("moqty").Item(0).SelectNodes("value").Item(0).InnerText) == true)



                    MOQty = Convert.ToDecimal(xmlDoc.DocumentElement.GetElementsByTagName("moqty").Item(0).SelectNodes("value").Item(0).InnerText);

                // MOTypeNo
                if (xmlDoc.DocumentElement.GetElementsByTagName("motypeno").Count > 0 && xmlDoc.GetElementsByTagName("motypeno").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("motypeno").Item(0).SelectNodes("value").Item(0).InnerText) && Information.IsNumeric(xmlDoc.DocumentElement.GetElementsByTagName("motypeno").Item(0).SelectNodes("value").Item(0).InnerText) == true)
                {
                    MOTypeNo = Conversions.ToInteger(xmlDoc.DocumentElement.GetElementsByTagName("motypeno").Item(0).SelectNodes("value").Item(0).InnerText);
                }
                else
                {
                    clsERP.combineException(ref strException, mesmsg: "[%MOTypeError%]");
                }
                // Priority
                if (xmlDoc.DocumentElement.GetElementsByTagName("priority").Count > 0 && xmlDoc.GetElementsByTagName("priority").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("priority").Item(0).SelectNodes("value").Item(0).InnerText) && Information.IsNumeric(xmlDoc.DocumentElement.GetElementsByTagName("priority").Item(0).SelectNodes("value").Item(0).InnerText) == true)



                    Priority = Conversions.ToInteger(xmlDoc.DocumentElement.GetElementsByTagName("priority").Item(0).SelectNodes("value").Item(0).InnerText);

                // PlanFinishDate
                if (xmlDoc.DocumentElement.GetElementsByTagName("planfinishdate").Count > 0 && xmlDoc.GetElementsByTagName("planfinishdate").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("planfinishdate").Item(0).SelectNodes("value").Item(0).InnerText) && Information.IsDate(xmlDoc.DocumentElement.GetElementsByTagName("planfinishdate").Item(0).SelectNodes("value").Item(0).InnerText) == true)



                    PlanFinishDate = Convert.ToDateTime(xmlDoc.DocumentElement.GetElementsByTagName("planfinishdate").Item(0).SelectNodes("value").Item(0).InnerText);

                // PlanStartDate
                if (xmlDoc.DocumentElement.GetElementsByTagName("planstartdate").Count > 0 && xmlDoc.GetElementsByTagName("planstartdate").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("planstartdate").Item(0).SelectNodes("value").Item(0).InnerText) && Information.IsDate(xmlDoc.DocumentElement.GetElementsByTagName("planstartdate").Item(0).SelectNodes("value").Item(0).InnerText) == true)



                    PlanStartDate = Convert.ToDateTime(xmlDoc.DocumentElement.GetElementsByTagName("planstartdate").Item(0).SelectNodes("value").Item(0).InnerText);

                // Creator
                Creator = modWS.GetXMLIdentityNode(xmlDoc, "curuserno");

                // Description
                if (xmlDoc.DocumentElement.GetElementsByTagName("description").Count > 0 && xmlDoc.GetElementsByTagName("description").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("description").Item(0).SelectNodes("value").Item(0).InnerText))


                {
                    string argstrInput7 = xmlDoc.DocumentElement.GetElementsByTagName("description").Item(0).SelectNodes("value").Item(0).InnerText;
                    Description = modWS.CInput_Singlequotation(argstrInput7);
                    xmlDoc.DocumentElement.GetElementsByTagName("description").Item(0).SelectNodes("value").Item(0).InnerText = argstrInput7;
                }

                // 2018/3/19 Vick 新增欄位 ERPMOLineNo
                if (xmlDoc.DocumentElement.GetElementsByTagName("erpmolineno").Count > 0 && xmlDoc.GetElementsByTagName("erpmolineno").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("erpmolineno").Item(0).SelectNodes("value").Item(0).InnerText))


                {
                    string argstrInput8 = xmlDoc.DocumentElement.GetElementsByTagName("erpmolineno").Item(0).SelectNodes("value").Item(0).InnerText;
                    strERPMOLineNo = modWS.CInput_Singlequotation(argstrInput8);
                    xmlDoc.DocumentElement.GetElementsByTagName("erpmolineno").Item(0).SelectNodes("value").Item(0).InnerText = argstrInput8;
                }


                if (xmlDoc.DocumentElement.GetElementsByTagName("wipentityid").Count > 0 && xmlDoc.GetElementsByTagName("wipentityid").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("wipentityid").Item(0).SelectNodes("value").Item(0).InnerText) && Information.IsNumeric(xmlDoc.DocumentElement.GetElementsByTagName("wipentityid").Item(0).SelectNodes("value").Item(0).InnerText) == true)



                    wipEntityId = Conversions.ToInteger(xmlDoc.DocumentElement.GetElementsByTagName("wipentityid").Item(0).SelectNodes("value").Item(0).InnerText);


                if (xmlDoc.DocumentElement.GetElementsByTagName("bomversion").Count > 0 && xmlDoc.GetElementsByTagName("bomversion").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("bomversion").Item(0).SelectNodes("value").Item(0).InnerText))


                {
                    string argstrInput8 = xmlDoc.DocumentElement.GetElementsByTagName("bomversion").Item(0).SelectNodes("value").Item(0).InnerText;
                    bomVersion = modWS.CInput_Singlequotation(argstrInput8);
                    xmlDoc.DocumentElement.GetElementsByTagName("bomversion").Item(0).SelectNodes("value").Item(0).InnerText = argstrInput8;
                }

                if (xmlDoc.DocumentElement.GetElementsByTagName("lcplantype").Count > 0 && xmlDoc.GetElementsByTagName("lcplantype").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("lcplantype").Item(0).SelectNodes("value").Item(0).InnerText))


                {
                    string argstrInput8 = xmlDoc.DocumentElement.GetElementsByTagName("lcplantype").Item(0).SelectNodes("value").Item(0).InnerText;
                    lcPlantype = modWS.CInput_Singlequotation(argstrInput8);
                    xmlDoc.DocumentElement.GetElementsByTagName("lcplantype").Item(0).SelectNodes("value").Item(0).InnerText = argstrInput8;
                }

                if (xmlDoc.DocumentElement.GetElementsByTagName("faiflag").Count > 0 && xmlDoc.GetElementsByTagName("faiflag").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("faiflag").Item(0).SelectNodes("value").Item(0).InnerText))


                {
                    string argstrInput8 = xmlDoc.DocumentElement.GetElementsByTagName("faiflag").Item(0).SelectNodes("value").Item(0).InnerText;
                    faiFlag = modWS.CInput_Singlequotation(argstrInput8);
                    xmlDoc.DocumentElement.GetElementsByTagName("faiflag").Item(0).SelectNodes("value").Item(0).InnerText = argstrInput8;
                }

                // 檢查必要性欄位
                if (string.IsNullOrEmpty(MONo))
                    clsERP.combineException(ref strException, mesmsg: "[%MONoEmpty%]");
                if (string.IsNullOrEmpty(MOUnitNo))
                    clsERP.combineException(ref strException, mesmsg: "[%MOUnitNoEmpty%]");
                if (string.IsNullOrEmpty(ProductNo))
                    clsERP.combineException(ref strException, mesmsg: "[%ProductNoEmpty%]");
                if (string.IsNullOrEmpty(FactoryNo))
                    clsERP.combineException(ref strException, mesmsg: "[%FactoryNoEmpty%]");
                if (MOQty <= 0m)
                    clsERP.combineException(ref strException, mesmsg: "[%MOQtyError%]");
                if (strException.Count > 0)
                    goto exitFun;

                // 2019/08/16 Grace 新增tblOEMOBasis.FromERP=1處理, 不需在Description填入"From ERP"
                // '20180514 KevinChang 0046325: TIPTOP工單整合-工單刪除問題
                // Description = IIf(String.IsNullOrEmpty(Description), "From ERP", "From ERP，" & Description)

                // ----- MO Detail -----
                var dtMTL = new DataTable("MOMaterialList");
                dtMTL.Columns.Add("MONo", Type.GetType("System.String"));
                dtMTL.Columns.Add("MaterialNo", Type.GetType("System.String"));
                dtMTL.Columns.Add("MaterialLevel", Type.GetType("System.Int16"));
                dtMTL.Columns.Add("StdQty", Type.GetType("System.Decimal"));
                dtMTL.Columns.Add("UnitNo", Type.GetType("System.String"));
                dtMTL.Columns.Add("OPNo", Type.GetType("System.String"));
                dtMTL.Columns.Add("PutInPlaceType", Type.GetType("System.Int16"));
                dtMTL.Columns.Add("DecreaseRate", Type.GetType("System.Decimal"));
                dtMTL.Columns.Add("Specified", Type.GetType("System.Int16"));
                dtMTL.Columns.Add("MaterialType", Type.GetType("System.String"));
                dtMTL.Columns.Add("CountWay", Type.GetType("System.Int16"));
                dtMTL.Columns.Add("CheckLotNo", Type.GetType("System.Int16"));
                dtMTL.Columns.Add("MaterialVersion", Type.GetType("System.String"));
                dtMTL.Columns.Add("MaterialMONo", Type.GetType("System.String"));
                dtMTL.Columns.Add("SubstituteMaterialNo", Type.GetType("System.String"));
                dtMTL.Columns.Add("SubstituteMaterialLevel", Type.GetType("System.Int16"));  // 2012/12/26,Even,新增替代物料及物料使用量
                dtMTL.Columns.Add("SubstituteStdQty", Type.GetType("System.Decimal")); // 2012/12/28,Even,新增替代料標準數
                dtMTL.Columns.Add("RequireQty", Type.GetType("System.Decimal"));
                dtMTL.Columns.Add("DeliveryMethod", Type.GetType("System.String")); // 2019/09/26 Grace 新增"材料型態"

                dtMTL.Columns.Add("MainItem", Type.GetType("System.String")); //主料编号
                dtMTL.Columns.Add("PhantomItem", Type.GetType("System.String")); //虚拟件
                dtMTL.Columns.Add("LockRequirement", Type.GetType("System.String")); //是否锁定需求
                dtMTL.Columns.Add("OperationSeqnum", Type.GetType("System.String")); //工序
                if (xmlDoc.DocumentElement.GetElementsByTagName("momateriallist").Count > 0)
                {
                    if (xmlDoc.GetElementsByTagName("momateriallist").Item(0).SelectNodes("value").Count > 0)
                    {
                        xmlList = xmlDoc.GetElementsByTagName("momateriallist").Item(0).SelectNodes("value");
                        if (xmlList.Count == 0)
                        {
                            clsERP.combineException(ref strMessage, mesmsg: "[%MOMaterialListNotExist%]");
                        }
                        else
                        {
                            DataRow dr;
                            bool errorFlag = false;
                            for (int i = 0, loopTo = xmlList.Count - 1; i <= loopTo; i++)
                            {
                                OPNO = string.Empty;
                                errorFlag = false;
                                try
                                {
                                    dr = dtMTL.NewRow();

                                    // ----- MONo -----
                                    dr["MONo"] = MONo;

                                    // ----- MaterialMo -----
                                    if (xmlList[i].SelectNodes("materialno").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("materialno").Item(0).InnerText))
                                    {
                                        dr["MaterialNo"] = modWS.CInput_Singlequotation(xmlList[i].SelectNodes("materialno").Item(0).InnerText).ToString().ToUpper();
                                        MaterialNo = modWS.CInput_Singlequotation(xmlList[i].SelectNodes("materialno").Item(0).InnerText).ToString().ToUpper();
                                    }
                                    else
                                    {
                                        errorFlag = true;
                                        clsERP.combineException(ref strException, mesmsg: "[%MaterialListMaterialNoError%]");
                                    }

                                    // ----- MaterialLevel -----
                                    if (xmlList[i].SelectNodes("materiallevel").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("materiallevel").Item(0).InnerText) && Information.IsNumeric(xmlList[i].SelectNodes("materiallevel").Item(0).InnerText) == true)

                                    {
                                        MaterialLevel = Conversions.ToInteger(xmlList[i].SelectNodes("materiallevel").Item(0).InnerText);
                                    }
                                    else
                                    {
                                        // Default value
                                        MaterialLevel = Conversions.ToInteger(ConfigurationManager.AppSettings["defMOListMaterialLevel"]);
                                    }
                                    dr["MaterialLevel"] = MaterialLevel;

                                    // ----- StdQty -----
                                    decimal dblStdQty = 0m;

                                    if (xmlList[i].SelectNodes("stdqty").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("stdqty").Item(0).InnerText) && Information.IsNumeric(xmlList[i].SelectNodes("stdqty").Item(0).InnerText) == true)

                                    {
                                        dr["StdQty"] = Convert.ToDecimal(xmlList[i].SelectNodes("stdqty").Item(0).InnerText);

                                        dblStdQty = Convert.ToDecimal(dr["StdQty"]);  // 暫存StdQty
                                    }

                                    else
                                    {
                                        errorFlag = true;
                                        clsERP.combineException(ref strException, mesmsg: "[%MaterialListSTDQtyError%]");
                                    }

                                    // ----- UnitNo -----
                                    if (xmlList[i].SelectNodes("unitno").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("unitno").Item(0).InnerText))
                                    {
                                        string argstrInput9 = xmlList[i].SelectNodes("unitno").Item(0).InnerText;
                                        dr["UnitNo"] = modWS.CInput_Singlequotation(argstrInput9);
                                        xmlList[i].SelectNodes("unitno").Item(0).InnerText = argstrInput9;
                                    }
                                    else
                                    {
                                        errorFlag = true;
                                        clsERP.combineException(ref strException, mesmsg: "[%MaterialListUnitNoError%]");
                                    }

                                    // ----- PutInPlaceType -----
                                    if (xmlList[i].SelectNodes("putinplacetype").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("putinplacetype").Item(0).InnerText) && Information.IsNumeric(xmlList[i].SelectNodes("putinplacetype").Item(0).InnerText.ToUpper()) == true)

                                    {
                                        dr["PutInPlaceType"] = Conversions.ToInteger(xmlList[i].SelectNodes("putinplacetype").Item(0).InnerText);
                                    }
                                    else
                                    {
                                        // Default value
                                        dr["PutInPlaceType"] = Conversions.ToInteger(ConfigurationManager.AppSettings["defMOListPutInPlaceType"]);
                                    }

                                    // ----- DecreaseRate -----
                                    if (xmlList[i].SelectNodes("decreaserate").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("decreaserate").Item(0).InnerText) && Information.IsNumeric(xmlList[i].SelectNodes("decreaserate").Item(0).InnerText) == true)

                                    {
                                        dr["DecreaseRate"] = Convert.ToDecimal(xmlList[i].SelectNodes("decreaserate").Item(0).InnerText);
                                    }
                                    else
                                    {
                                        // Default value
                                        dr["DecreaseRate"] = Convert.ToDecimal(ConfigurationManager.AppSettings["defMOListDecreaseRate"]);
                                    }

                                    // ----- Specified -----
                                    if (xmlList[i].SelectNodes("specified").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("specified").Item(0).InnerText) && Information.IsNumeric(xmlList[i].SelectNodes("specified").Item(0).InnerText) == true)

                                    {
                                        dr["Specified"] = Convert.ToDecimal(xmlList[i].SelectNodes("specified").Item(0).InnerText);
                                    }
                                    else
                                    {
                                        // Default value
                                        dr["Specified"] = Convert.ToDecimal(ConfigurationManager.AppSettings["defMOListSpecified"]);
                                    }

                                    // ----- MaterialType-----
                                    if (xmlList[i].SelectNodes("materialtype").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("materialtype").Item(0).InnerText))

                                    {
                                        string argstrInput10 = xmlList[i].SelectNodes("materialtype").Item(0).InnerText;
                                        dr["MaterialType"] = modWS.CInput_Singlequotation(argstrInput10);
                                        xmlList[i].SelectNodes("materialtype").Item(0).InnerText = argstrInput10;
                                    }

                                    // ----- CountWay -----
                                    if (xmlList[i].SelectNodes("countway").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("countway").Item(0).InnerText) && Information.IsNumeric(xmlList[i].SelectNodes("countway").Item(0).InnerText) == true)

                                    {
                                        dr["CountWay"] = Conversions.ToInteger(xmlList[i].SelectNodes("countway").Item(0).InnerText);
                                    }
                                    else
                                    {
                                        // Default value
                                        dr["CountWay"] = Conversions.ToInteger(ConfigurationManager.AppSettings["defMOListCountWay"]);
                                    }

                                    // ----- CheckLotNo -----
                                    if (xmlList[i].SelectNodes("checklotno").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("checklotno").Item(0).InnerText) && Information.IsNumeric(xmlList[i].SelectNodes("checklotno").Item(0).InnerText) == true)


                                        dr["CheckLotNo"] = Conversions.ToInteger(xmlList[i].SelectNodes("checklotno").Item(0).InnerText);

                                    // ----- MaterialVersion -----
                                    if (xmlList[i].SelectNodes("materialversion").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("materialversion").Item(0).InnerText))

                                    {
                                        string argstrInput11 = xmlList[i].SelectNodes("materialversion").Item(0).InnerText;
                                        dr["MaterialVersion"] = modWS.CInput_Singlequotation(argstrInput11);
                                        xmlList[i].SelectNodes("materialversion").Item(0).InnerText = argstrInput11;
                                    }

                                    // ----- SubstituteMaterialNo -----
                                    if (xmlList[i].SelectNodes("substitutematerialno").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("substitutematerialno").Item(0).InnerText))
                                    {
                                        dr["SubstituteMaterialNo"] = modWS.CInput_Singlequotation(xmlList[i].SelectNodes("substitutematerialno").Item(0).InnerText).ToString().ToUpper();
                                        SubstituteMaterialNo = modWS.CInput_Singlequotation(xmlList[i].SelectNodes("substitutematerialno").Item(0).InnerText).ToString().ToUpper();
                                    }
                                    else
                                    {
                                        // Default value
                                        dr["SubstituteMaterialNo"] = dr["materialno"].ToString().ToUpper();
                                        SubstituteMaterialNo = dr["materialno"].ToString().ToUpper();
                                    }

                                    // ----- OPNo -----
                                    // 若有傳入作業站資訊以傳入的資訊為主
                                    // 若沒有傳入作業站資訊，則優先以產品BOM上定義的作業站，若產品BOM無定義，以物料屬性 PutInPlace_OPNo 中的值為主
                                    // 若皆無傳入則以Config中定義的作業站為主
                                    if (xmlList[i].SelectNodes("opno").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("opno").Item(0).InnerText))
                                    {
                                        string argstrInput12 = xmlList[i].SelectNodes("opno").Item(0).InnerText;
                                        dr["OPNo"] = modWS.CInput_Singlequotation(argstrInput12);
                                        xmlList[i].SelectNodes("opno").Item(0).InnerText = argstrInput12;
                                    }
                                    else
                                    {
                                        // 檢查產品BOM是否有定義，若無繼續往下查找對應作業站資訊
                                        using (var objPRD = new kcPRD.clsProduct())
                                        {
                                            try
                                            {
                                                ProductVersion = objPRD.GetProductCurVersion(ProductNo.ToUpper());
                                            }
                                            catch (Exception ex)
                                            {
                                                errorFlag = true;
                                                clsERP.combineException(ref strException, mesmsg: "[%GetProductVersionFail%]");
                                            }

                                            DataSet dsTemp_PRD;
                                            if (SubstituteMaterialNo == MaterialNo)
                                            {
                                                dsTemp_PRD = objPRD.ShowBOM(ProductNo, ProductVersion, MaterialNo);
                                                if (dsTemp_PRD.Tables["PRDBOM"].Rows.Count > 0)
                                                {
                                                    OPNO = dsTemp_PRD.Tables["PRDBOM"].Rows[0]["OPNO"].ToString().ToUpper();
                                                    dsTemp_PRD = null;
                                                }
                                                else
                                                {
                                                    dsTemp_PRD = null;
                                                }
                                            }
                                            else
                                            {
                                                dsTemp_PRD = objPRD.ShowBOMMaterialGroup(ProductNo, ProductVersion, MaterialNo, MaterialNo: SubstituteMaterialNo);
                                                if (dsTemp_PRD.Tables["MaterialGroup"].Rows.Count > 0)
                                                {
                                                    OPNO = dsTemp_PRD.Tables["MaterialGroup"].Rows[0]["OPNO"].ToString().ToUpper();
                                                    dsTemp_PRD = null;
                                                }
                                                else
                                                {
                                                    dsTemp_PRD = null;
                                                }
                                            }

                                        }

                                        if (string.IsNullOrEmpty(OPNO))
                                        {
                                            // 檢查物料屬性是否有定義，若繼續往下查找對應作業站資訊
                                            DataSet dsTemp_MTL;
                                            using (var objMTL = new kcMTL.clsMTLBasis())
                                            {
                                                dsTemp_MTL = objMTL.ShowMaterialProperty(SubstituteMaterialNo, "PutInPlace_OPNo", 2);
                                                if (dsTemp_MTL.Tables["MaterialProperty"].Rows.Count > 0)
                                                {
                                                    OPNO = dsTemp_MTL.Tables["MaterialProperty"].Rows[0]["DEFAULTVALUE"].ToString().ToUpper();
                                                    dsTemp_MTL = null;
                                                }
                                                else
                                                {
                                                    dsTemp_MTL = null;
                                                }
                                            }

                                            if (string.IsNullOrEmpty(OPNO))
                                            {
                                                // Default value
                                                dr["OPNo"] = ConfigurationManager.AppSettings["defMOListOPNo"];
                                            }
                                            else
                                            {
                                                dr["OPNo"] = OPNO;
                                            }
                                        }
                                        else
                                        {
                                            dr["OPNo"] = OPNO;
                                        }

                                    }

                                    // 2012/02/18,Even,新增替代物料等級、替代料標準數及物料使用量-------
                                    // ----- SubstituteMaterialLevel -----
                                    if (xmlList[i].SelectNodes("substitutemateriallevel").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("substitutemateriallevel").Item(0).InnerText) && Information.IsNumeric(xmlList[i].SelectNodes("substitutemateriallevel").Item(0).InnerText) == true)

                                    {
                                        dr["SubstituteMaterialLevel"] = Conversions.ToInteger(xmlList[i].SelectNodes("substitutemateriallevel").Item(0).InnerText);
                                    }
                                    else
                                    {
                                        // Default value,未抓取到，抓取MaterialLevel
                                        dr["SubstituteMaterialLevel"] = MaterialLevel;
                                    }
                                    // ----- SubstituteStdQty --
                                    if (xmlList[i].SelectNodes("substitutestdqty").Count > 0 &&
                                        !string.IsNullOrEmpty(xmlList[i].SelectNodes("substitutestdqty").Item(0).InnerText) &&
                                        Information.IsNumeric(xmlList[i].SelectNodes("substitutestdqty").Item(0).InnerText))
                                    {
                                        dr["SubstituteStdQty"] = Convert.ToDecimal(xmlList[i].SelectNodes("substitutestdqty").Item(0).InnerText);

                                        if (dr["MaterialNo"].ToString() == dr["SubstituteMaterialNo"].ToString())
                                        {
                                            if (Convert.ToDecimal(dr["stdqty"]) != Convert.ToDecimal(dr["substitutestdqty"]))
                                            {
                                                errorFlag = true;
                                                clsERP.combineException(ref strException, mesmsg: dr["MaterialNo"].ToString() + "[%StdQtyAndSubstituteStdQtyMustBeTheSame%]");
                                            }
                                        }
                                    }
                                    else
                                    {
                                        // 2018/09/20 OwenLiu, 因為後端程式會重新計算，這邊取消預設值的指定
                                        // 'Default value,未抓取到，抓取則抓物料之標準數
                                        // dr("SubstituteStdQty") = dr("StdQty")
                                    }
                                    // ----- RequireQty--------若無資料則為工單數 * 標準數*(1+損耗率)
                                    if (xmlList[i].SelectNodes("requireqty").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("requireqty").Item(0).InnerText) && Information.IsNumeric(xmlList[i].SelectNodes("requireqty").Item(0).InnerText) == true)

                                    {
                                        dr["RequireQty"] = Convert.ToDecimal(xmlList[i].SelectNodes("requireqty").Item(0).InnerText);
                                    }
                                    else
                                    {
                                        // 2018/09/20 OwenLiu, 因為後端程式會重新計算，這邊取消預設值的指定
                                        // 'Default value
                                        // dr("RequireQty") = MOQty * dblStdQty * (1 + dr("DecreaseRate"))
                                    }


                                    // ----- DeliveryMethod -----
                                    // 2019/09/26 Grace 新增tagname, 材料型態：DeliveryMethod (Optional參數,非必傳)
                                    if (xmlList[i].SelectNodes("deliverymethod").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("deliverymethod").Item(0).InnerText))

                                    {
                                        string argstrInput13 = xmlList[i].SelectNodes("deliverymethod").Item(0).InnerText;
                                        dr["DeliveryMethod"] = modWS.CInput_Singlequotation(argstrInput13);
                                        xmlList[i].SelectNodes("deliverymethod").Item(0).InnerText = argstrInput13;
                                    }


                                    if (xmlList[i].SelectNodes("mainitem").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("mainitem").Item(0).InnerText))

                                    {
                                        string argstrInput13 = xmlList[i].SelectNodes("mainitem").Item(0).InnerText;
                                        dr["MainItem"] = modWS.CInput_Singlequotation(argstrInput13);
                                        xmlList[i].SelectNodes("mainitem").Item(0).InnerText = argstrInput13;
                                    }

                                    if (xmlList[i].SelectNodes("phantomitem").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("phantomitem").Item(0).InnerText))

                                    {
                                        string argstrInput13 = xmlList[i].SelectNodes("phantomitem").Item(0).InnerText;
                                        dr["PhantomItem"] = modWS.CInput_Singlequotation(argstrInput13);
                                        xmlList[i].SelectNodes("phantomitem").Item(0).InnerText = argstrInput13;
                                    }

                                    if (xmlList[i].SelectNodes("lockrequirement").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("lockrequirement").Item(0).InnerText))

                                    {
                                        string argstrInput13 = xmlList[i].SelectNodes("lockrequirement").Item(0).InnerText;
                                        dr["LockRequirement"] = modWS.CInput_Singlequotation(argstrInput13);
                                        xmlList[i].SelectNodes("lockrequirement").Item(0).InnerText = argstrInput13;
                                    }

                                    if (xmlList[i].SelectNodes("operationseqnum").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("operationseqnum").Item(0).InnerText))

                                    {
                                        string argstrInput13 = xmlList[i].SelectNodes("operationseqnum").Item(0).InnerText;
                                        dr["OperationSeqnum"] = modWS.CInput_Singlequotation(argstrInput13);
                                        xmlList[i].SelectNodes("operationseqnum").Item(0).InnerText = argstrInput13;
                                    }

                                    if (errorFlag == false)
                                    {
                                        dtMTL.Rows.Add(dr);
                                    }
                                }

                                catch (Exception ex)
                                {
                                    clsERP.combineException(ref strException, sysmsg: ex.Message, mesmsg: "[%MOMaterialListError%]", stack: ex.StackTrace);
                                }
                            }
                        }
                    }
                }

                // ----- MO Property -----
                var dtMOProperty = new DataTable("MOProperty");
                dtMOProperty.Columns.Add("MONo", Type.GetType("System.String"));
                dtMOProperty.Columns.Add("PropertyNo", Type.GetType("System.String"));
                dtMOProperty.Columns.Add("PropertyValue", Type.GetType("System.String"));
                dtMOProperty.Columns.Add("DataType", Type.GetType("System.String"));  // DataType: 0:Numeric, 1:String(default), 2:Percent, 3:DateTime, 4:Boolean

                // web.config裡預設的MOProperty (ERPUnitNo)(原本是寫在ArrayList裡,改寫在DataTable裡)
                if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["defERPUnitNoProperty"]))
                {
                    DataRow drP;
                    drP = dtMOProperty.NewRow();
                    drP["MONo"] = MONo;
                    drP["PropertyNo"] = ConfigurationManager.AppSettings["defERPUnitNoProperty"];
                    drP["PropertyValue"] = MOUnitNo;
                    drP["DataType"] = "String";
                    dtMOProperty.Rows.Add(drP);
                }

                // ERP拋過來的工單屬性
                if (xmlDoc.DocumentElement.GetElementsByTagName("property").Count > 0)
                {
                    if (xmlDoc.GetElementsByTagName("property").Item(0).SelectNodes("value").Count > 0)
                    {
                        xmlList = xmlDoc.GetElementsByTagName("property").Item(0).SelectNodes("value");
                        if (xmlList.Count == 0)
                        {
                        }
                        // clsERP.combineMessage(strMessage, , , "[%MOPropertyNotExist%]")
                        else
                        {
                            DataRow dr;
                            bool errorFlag = false;
                            for (int i = 0, loopTo1 = xmlList.Count - 1; i <= loopTo1; i++)
                            {
                                errorFlag = false;
                                try
                                {
                                    dr = dtMOProperty.NewRow();

                                    // ----- MONo -----
                                    dr["MONo"] = MONo;

                                    // ----- PropertyNo -----
                                    if (xmlList[i].SelectNodes("name").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("name").Item(0).InnerText))
                                    {
                                        string argstrInput14 = xmlList[i].SelectNodes("name").Item(0).InnerText;
                                        dr["PropertyNo"] = modWS.CInput_Singlequotation(argstrInput14);
                                        xmlList[i].SelectNodes("name").Item(0).InnerText = argstrInput14;
                                    }
                                    else
                                    {
                                        errorFlag = true;
                                        clsERP.combineException(ref strException, mesmsg: "[%PropertyNoEmpty%]");
                                    }

                                    // ----- PropertyValue -----
                                    if (xmlList[i].SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("value").Item(0).InnerText))
                                    {
                                        string argstrInput15 = xmlList[i].SelectNodes("value").Item(0).InnerText;
                                        dr["PropertyValue"] = modWS.CInput_Singlequotation(argstrInput15);
                                        xmlList[i].SelectNodes("value").Item(0).InnerText = argstrInput15;
                                    }
                                    else
                                    {
                                        errorFlag = true;
                                        clsERP.combineException(ref strException, mesmsg: "[%PropertyValueEmpty%]");
                                    }

                                    // ----- DataType -----
                                    if (xmlList[i].SelectNodes("type").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("type").Item(0).InnerText))
                                    {
                                        string argstrInput16 = xmlList[i].SelectNodes("type").Item(0).InnerText;
                                        dr["DataType"] = modWS.CInput_Singlequotation(argstrInput16);
                                        xmlList[i].SelectNodes("type").Item(0).InnerText = argstrInput16;
                                    }
                                    else
                                    {
                                        errorFlag = true;
                                        clsERP.combineException(ref strException, mesmsg: "[%DataTypeEmpty%]");
                                    }

                                    if (errorFlag == false)
                                    {
                                        dtMOProperty.Rows.Add(dr);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    clsERP.combineException(ref strException, sysmsg: ex.Message, mesmsg: "[%MOPropertyError%]", stack: ex.StackTrace);
                                }
                            }
                        }
                    }
                }

                if (strException.Count > 0)
                    goto exitFun;

                // KeyValue
                strKeyValue = MONo;

                // '呼叫Dll執行 ----- UnitNo=UnitType=SystemUnit -----
                clsOE.addMO(Orgcode, OrgMono, MONo, MOUnitNo, ProductNo, MOQty, FactoryNo, RONo, ItemNo, CustomerNo, MOTypeNo, Priority, PlanFinishDate, Creator, CreateDate, Description, dtMTL, MOProperty, strMessage, strException, strAlert, dtMOProperty, strERPMOLineNo, CustomerLotNo, PlanStartDate, wipEntityId: wipEntityId, bomVersion: bomVersion, lcPlantype: lcPlantype, faiFlag: faiFlag);

                // 判斷成功與否
                if (strException.Count > 0)
                    goto exitFun;

                strResult = "success";

            exitFun:
                ;
            }


            catch (Exception ex)
            {
                clsERP.combineException(ref strException, sysmsg: ex.Message, mesmsg: "[%AddMOFail%]", stack: ex.StackTrace);
            }

            finally
            {

                // 將各部份之XML字串組起來並傳出
                string argReturnValue = null;
                OutXml = modWS.CombineXMLResponse(strIdentity, argReturnValue, strException, strResult, strMessage);

                // 紀錄Transaction Log
                try
                {
                    clsERP.addTransactionLog_ErrorCode(modWS.GetXMLIdentityNode(xmlDoc, "transactionid"), modWS.GetXMLIdentityNode(xmlDoc, "moduleid"), modWS.GetXMLIdentityNode(xmlDoc, "functionid"), modWS.GetXMLIdentityNode(xmlDoc, "computername"), modWS.GetXMLIdentityNode(xmlDoc, "curuserno"), modWS.GetXMLIdentityNode(xmlDoc, "sendtime"), strResult, strKeyValue, strMessage, strException, InXml, OutXml, "AddMO", Conversions.ToInteger(ConfigurationManager.AppSettings["keepLog"]), Conversions.ToInteger(ConfigurationManager.AppSettings["keepXML"]), LogClass: "ERP");
                }
                catch (Exception ex)
                {
                    string strMsg = ex.Message;
                }


                funAddMORet = OutXml;

            }

            return funAddMORet;

        }

        public static string funEditMO(string InXml)
        {
            string funEditMORet = default(string);

            var xmlDoc = new XmlDocument();            // 用以讀取Xml字串
            XmlNodeList xmlList;
            string OutXml = null;

            string strIdentity = string.Empty;                      // Identity XML字串
            string strResult = "fail";                                    // Result XML字串
            var strException = new List<ArrayList>();            // Exception XML字串
            var strMessage = new List<ArrayList>();              // Message XML字串
            var strAlert = new List<ArrayList>();
            string strKeyValue = string.Empty;                    // TransactionLot KeyValue

            try
            {

                try
                {
                    // 讀取InXml字串
                    xmlDoc.LoadXml(InXml);
                }
                catch (Exception ex)
                {
                    clsERP.combineException(ref strException, sysmsg: ex.Message, mesmsg: "[%InXmlError%]", stack: ex.StackTrace);
                    goto exitFun;
                }

                // 組Identity字串
                try
                {
                    strIdentity = modWS.CombineXMLIdentity(xmlDoc);
                }
                catch (Exception ex)
                {
                    clsERP.combineException(ref strException, sysmsg: ex.Message, mesmsg: "[%IndentityError%]", stack: ex.StackTrace);
                    goto exitFun;
                }

                string MONo = string.Empty;
                string RONo = string.Empty;
                string ItemNo = string.Empty;          // RO ItemNo
                string CustomerNo = string.Empty;
                string CustomerLotNo = string.Empty; //CustomerLotNo
                decimal MOQty = 0m;
                int MOTypeNo = Conversions.ToInteger(ConfigurationManager.AppSettings["defMOTypeNo"]);
                int Priority = Conversions.ToInteger(ConfigurationManager.AppSettings["defMOPriority"]);
                var PlanFinishDate = DateAndTime.DateAdd(DateInterval.Day, Conversions.ToInteger(ConfigurationManager.AppSettings["defMOPlanFinishDate"]), DateTime.Now);
                var PlanStartDate = defDateTime;
                string Creator = string.Empty;
                var CreateDate = DateTime.Now;        // Default Today
                string Description = string.Empty;
                string MOUnitNo = string.Empty;
                int MaterialLevel = defInteger;
                int wipEntityId = defInteger;
                string bomVersion = string.Empty;
                string lcPlantype = string.Empty;
                string faiFlag = string.Empty;

                string strERPMOLineNo = defString;

                string ProductNo = string.Empty;
                string ProductVersion = string.Empty;
                string SubstituteMaterialNo = string.Empty;
                string MaterialNo = string.Empty;
                string OPNO = string.Empty;

                // MONo
                if (xmlDoc.DocumentElement.GetElementsByTagName("mono").Count > 0 && xmlDoc.GetElementsByTagName("mono").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("mono").Item(0).SelectNodes("value").Item(0).InnerText))


                {
                    string argstrInput = xmlDoc.DocumentElement.GetElementsByTagName("mono").Item(0).SelectNodes("value").Item(0).InnerText;
                    MONo = modWS.CInput_Singlequotation(argstrInput);
                    xmlDoc.DocumentElement.GetElementsByTagName("mono").Item(0).SelectNodes("value").Item(0).InnerText = argstrInput;
                }

                // RONo
                if (xmlDoc.DocumentElement.GetElementsByTagName("rono").Count > 0 && xmlDoc.GetElementsByTagName("rono").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("rono").Item(0).SelectNodes("value").Item(0).InnerText))


                {
                    string argstrInput1 = xmlDoc.DocumentElement.GetElementsByTagName("rono").Item(0).SelectNodes("value").Item(0).InnerText;
                    RONo = modWS.CInput_Singlequotation(argstrInput1);
                    xmlDoc.DocumentElement.GetElementsByTagName("rono").Item(0).SelectNodes("value").Item(0).InnerText = argstrInput1;
                }

                // ItemNo
                if (xmlDoc.DocumentElement.GetElementsByTagName("itemno").Count > 0 && xmlDoc.GetElementsByTagName("itemno").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("itemno").Item(0).SelectNodes("value").Item(0).InnerText))


                {
                    string argstrInput2 = xmlDoc.DocumentElement.GetElementsByTagName("itemno").Item(0).SelectNodes("value").Item(0).InnerText;
                    ItemNo = modWS.CInput_Singlequotation(argstrInput2);
                    xmlDoc.DocumentElement.GetElementsByTagName("itemno").Item(0).SelectNodes("value").Item(0).InnerText = argstrInput2;
                }

                // 如傳入的值為0001則轉換成1
                if (!string.IsNullOrEmpty(ItemNo))
                {
                    ItemNo = Conversions.ToInteger(ItemNo).ToString();
                }

                // CustomerNo
                if (xmlDoc.DocumentElement.GetElementsByTagName("customerno").Count > 0 && xmlDoc.GetElementsByTagName("customerno").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("customerno").Item(0).SelectNodes("value").Item(0).InnerText))


                {
                    string argstrInput3 = xmlDoc.DocumentElement.GetElementsByTagName("customerno").Item(0).SelectNodes("value").Item(0).InnerText;
                    CustomerNo = modWS.CInput_Singlequotation(argstrInput3);
                    xmlDoc.DocumentElement.GetElementsByTagName("customerno").Item(0).SelectNodes("value").Item(0).InnerText = argstrInput3;
                }

                // CustomerLotNo
                if (xmlDoc.DocumentElement.GetElementsByTagName("customerlotno").Count > 0 && xmlDoc.GetElementsByTagName("customerlotno").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("customerlotno").Item(0).SelectNodes("value").Item(0).InnerText))


                {
                    string argstrInput3 = xmlDoc.DocumentElement.GetElementsByTagName("customerlotno").Item(0).SelectNodes("value").Item(0).InnerText;
                    CustomerLotNo = modWS.CInput_Singlequotation(argstrInput3);
                    xmlDoc.DocumentElement.GetElementsByTagName("customerlotno").Item(0).SelectNodes("value").Item(0).InnerText = argstrInput3;
                }

                // MOQty
                if (xmlDoc.DocumentElement.GetElementsByTagName("moqty").Count > 0 && xmlDoc.GetElementsByTagName("moqty").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("moqty").Item(0).SelectNodes("value").Item(0).InnerText) && Information.IsNumeric(xmlDoc.DocumentElement.GetElementsByTagName("moqty").Item(0).SelectNodes("value").Item(0).InnerText) == true)



                    MOQty = Convert.ToDecimal(xmlDoc.DocumentElement.GetElementsByTagName("moqty").Item(0).SelectNodes("value").Item(0).InnerText);

                // MOTypeNo
                if (xmlDoc.DocumentElement.GetElementsByTagName("motypeno").Count > 0 && xmlDoc.GetElementsByTagName("motypeno").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("motypeno").Item(0).SelectNodes("value").Item(0).InnerText) && Information.IsNumeric(xmlDoc.DocumentElement.GetElementsByTagName("motypeno").Item(0).SelectNodes("value").Item(0).InnerText) == true)



                    MOTypeNo = Conversions.ToInteger(xmlDoc.DocumentElement.GetElementsByTagName("motypeno").Item(0).SelectNodes("value").Item(0).InnerText);

                // Priority
                if (xmlDoc.DocumentElement.GetElementsByTagName("priority").Count > 0 && xmlDoc.GetElementsByTagName("priority").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("priority").Item(0).SelectNodes("value").Item(0).InnerText) && Information.IsNumeric(xmlDoc.DocumentElement.GetElementsByTagName("priority").Item(0).SelectNodes("value").Item(0).InnerText) == true)



                    Priority = Conversions.ToInteger(xmlDoc.DocumentElement.GetElementsByTagName("priority").Item(0).SelectNodes("value").Item(0).InnerText);

                // PlanFinishDate
                if (xmlDoc.DocumentElement.GetElementsByTagName("planfinishdate").Count > 0 && xmlDoc.GetElementsByTagName("planfinishdate").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("planfinishdate").Item(0).SelectNodes("value").Item(0).InnerText) && Information.IsDate(xmlDoc.DocumentElement.GetElementsByTagName("planfinishdate").Item(0).SelectNodes("value").Item(0).InnerText) == true)



                    PlanFinishDate = Convert.ToDateTime(xmlDoc.DocumentElement.GetElementsByTagName("planfinishdate").Item(0).SelectNodes("value").Item(0).InnerText);

                // PlanStartDate
                if (xmlDoc.DocumentElement.GetElementsByTagName("planstartdate").Count > 0 && xmlDoc.GetElementsByTagName("planstartdate").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("planstartdate").Item(0).SelectNodes("value").Item(0).InnerText) && Information.IsDate(xmlDoc.DocumentElement.GetElementsByTagName("planstartdate").Item(0).SelectNodes("value").Item(0).InnerText) == true)



                    PlanStartDate = Convert.ToDateTime(xmlDoc.DocumentElement.GetElementsByTagName("planstartdate").Item(0).SelectNodes("value").Item(0).InnerText);

                // Creator
                Creator = modWS.GetXMLIdentityNode(xmlDoc, "curuserno");

                // Description
                if (xmlDoc.DocumentElement.GetElementsByTagName("description").Count > 0 && xmlDoc.GetElementsByTagName("description").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("description").Item(0).SelectNodes("value").Item(0).InnerText))


                    Description = xmlDoc.DocumentElement.GetElementsByTagName("description").Item(0).SelectNodes("value").Item(0).InnerText;

                // MOUnitNo
                if (xmlDoc.DocumentElement.GetElementsByTagName("mounitno").Count > 0 && xmlDoc.GetElementsByTagName("mounitno").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("mounitno").Item(0).SelectNodes("value").Item(0).InnerText))


                {
                    string argstrInput4 = xmlDoc.DocumentElement.GetElementsByTagName("mounitno").Item(0).SelectNodes("value").Item(0).InnerText;
                    MOUnitNo = modWS.CInput_Singlequotation(argstrInput4);
                    xmlDoc.DocumentElement.GetElementsByTagName("mounitno").Item(0).SelectNodes("value").Item(0).InnerText = argstrInput4;
                }

                // 2018/3/19 Vick 新增欄位 ERPMOLineNo
                if (xmlDoc.DocumentElement.GetElementsByTagName("erpmolineno").Count > 0 && xmlDoc.GetElementsByTagName("erpmolineno").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("erpmolineno").Item(0).SelectNodes("value").Item(0).InnerText))


                {
                    string argstrInput5 = xmlDoc.DocumentElement.GetElementsByTagName("erpmolineno").Item(0).SelectNodes("value").Item(0).InnerText;
                    strERPMOLineNo = modWS.CInput_Singlequotation(argstrInput5);
                    xmlDoc.DocumentElement.GetElementsByTagName("erpmolineno").Item(0).SelectNodes("value").Item(0).InnerText = argstrInput5;
                }

                if (xmlDoc.DocumentElement.GetElementsByTagName("wipentityid").Count > 0 && xmlDoc.GetElementsByTagName("wipentityid").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("wipentityid").Item(0).SelectNodes("value").Item(0).InnerText) && Information.IsNumeric(xmlDoc.DocumentElement.GetElementsByTagName("wipentityid").Item(0).SelectNodes("value").Item(0).InnerText) == true)



                    wipEntityId = Conversions.ToInteger(xmlDoc.DocumentElement.GetElementsByTagName("wipentityid").Item(0).SelectNodes("value").Item(0).InnerText);


                if (xmlDoc.DocumentElement.GetElementsByTagName("bomversion").Count > 0 && xmlDoc.GetElementsByTagName("bomversion").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("bomversion").Item(0).SelectNodes("value").Item(0).InnerText))


                {
                    string argstrInput8 = xmlDoc.DocumentElement.GetElementsByTagName("bomversion").Item(0).SelectNodes("value").Item(0).InnerText;
                    bomVersion = modWS.CInput_Singlequotation(argstrInput8);
                    xmlDoc.DocumentElement.GetElementsByTagName("bomversion").Item(0).SelectNodes("value").Item(0).InnerText = argstrInput8;
                }

                if (xmlDoc.DocumentElement.GetElementsByTagName("lcplantype").Count > 0 && xmlDoc.GetElementsByTagName("lcplantype").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("lcplantype").Item(0).SelectNodes("value").Item(0).InnerText))


                {
                    string argstrInput8 = xmlDoc.DocumentElement.GetElementsByTagName("lcplantype").Item(0).SelectNodes("value").Item(0).InnerText;
                    lcPlantype = modWS.CInput_Singlequotation(argstrInput8);
                    xmlDoc.DocumentElement.GetElementsByTagName("lcplantype").Item(0).SelectNodes("value").Item(0).InnerText = argstrInput8;
                }

                if (xmlDoc.DocumentElement.GetElementsByTagName("faiflag").Count > 0 && xmlDoc.GetElementsByTagName("faiflag").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("faiflag").Item(0).SelectNodes("value").Item(0).InnerText))


                {
                    string argstrInput8 = xmlDoc.DocumentElement.GetElementsByTagName("faiflag").Item(0).SelectNodes("value").Item(0).InnerText;
                    faiFlag = modWS.CInput_Singlequotation(argstrInput8);
                    xmlDoc.DocumentElement.GetElementsByTagName("faiflag").Item(0).SelectNodes("value").Item(0).InnerText = argstrInput8;
                }

                // 檢查必要性欄位
                if (string.IsNullOrEmpty(MONo))
                    clsERP.combineException(ref strException, mesmsg: "[%MONoEmpty%]");
                if (MOQty <= 0m)
                    clsERP.combineException(ref strException, mesmsg: "[%MOQtyError%]");

                // 2022/04/08 Eric 檢查產品資訊，並取得目前產品資訊用於後續判斷投料作業站
                using (var objOE = new kcOE.clsOEBasis())
                {
                    DataSet dsTemp_OE;
                    dsTemp_OE = objOE.ShowMOBasis(MONo);
                    if (dsTemp_OE.Tables["OEMOBasis"].Rows.Count > 0)
                    {
                        ProductNo = dsTemp_OE.Tables["OEMOBasis"].Rows[0]["ProductNo"].ToString().ToUpper();
                        ProductVersion = dsTemp_OE.Tables["OEMOBasis"].Rows[0]["ProductVersion"].ToString().ToUpper();
                        dsTemp_OE = null;
                    }
                    else
                    {
                        // 工單編號不存在
                        clsERP.combineException(ref strException, mesmsg: "[%MONoNotExist%]");
                        dsTemp_OE = null;
                    }
                }

                if (strException.Count > 0)
                    goto exitFun;

                // 2019/02/24 OwenLiu, Mantis:0055248 TIPTOP工單整合-工單刪除問題
                Description = (string.IsNullOrEmpty(Description) ? "From ERP" : "From ERP，" + Description);

                // ----- MO Detail -----
                var dtMTL = new DataTable("MOMaterialList");
                dtMTL.Columns.Add("MONo", Type.GetType("System.String"));
                dtMTL.Columns.Add("MaterialNo", Type.GetType("System.String"));
                dtMTL.Columns.Add("MaterialLevel", Type.GetType("System.Int16"));
                dtMTL.Columns.Add("StdQty", Type.GetType("System.Decimal"));
                dtMTL.Columns.Add("UnitNo", Type.GetType("System.String"));
                dtMTL.Columns.Add("OPNo", Type.GetType("System.String"));
                dtMTL.Columns.Add("PutInPlaceType", Type.GetType("System.Int16"));
                dtMTL.Columns.Add("DecreaseRate", Type.GetType("System.Decimal"));
                dtMTL.Columns.Add("Specified", Type.GetType("System.Int16"));
                dtMTL.Columns.Add("MaterialType", Type.GetType("System.String"));
                dtMTL.Columns.Add("CountWay", Type.GetType("System.Int16"));
                dtMTL.Columns.Add("CheckLotNo", Type.GetType("System.Int16"));
                dtMTL.Columns.Add("MaterialVersion", Type.GetType("System.String"));
                dtMTL.Columns.Add("MaterialMONo", Type.GetType("System.String"));
                dtMTL.Columns.Add("SubstituteMaterialNo", Type.GetType("System.String"));
                dtMTL.Columns.Add("SubstituteMaterialLevel", Type.GetType("System.Int16"));  // 2012/12/26,Even,新增替代物料及物料使用量
                dtMTL.Columns.Add("SubstituteStdQty", Type.GetType("System.Decimal")); // 2012/12/28,Even,新增替代料標準數
                dtMTL.Columns.Add("RequireQty", Type.GetType("System.Decimal"));
                dtMTL.Columns.Add("DeliveryMethod", Type.GetType("System.String")); // 2019/09/26 Grace 新增"材料型態"

                dtMTL.Columns.Add("MainItem", Type.GetType("System.String")); //主料编号
                dtMTL.Columns.Add("PhantomItem", Type.GetType("System.String")); //虚拟件
                dtMTL.Columns.Add("LockRequirement", Type.GetType("System.String")); //是否锁定需求
                dtMTL.Columns.Add("OperationSeqnum", Type.GetType("System.String")); //工序

                if (xmlDoc.DocumentElement.GetElementsByTagName("momateriallist").Count > 0)
                {
                    if (xmlDoc.GetElementsByTagName("momateriallist").Item(0).SelectNodes("value").Count > 0)
                    {
                        xmlList = xmlDoc.GetElementsByTagName("momateriallist").Item(0).SelectNodes("value");
                        if (xmlList.Count == 0)
                        {
                            clsERP.combineException(ref strMessage, mesmsg: "[%MOMaterialListNotExist%]");
                        }
                        else
                        {
                            DataRow dr;
                            bool errorFlag = false;
                            for (int i = 0, loopTo = xmlList.Count - 1; i <= loopTo; i++)
                            {
                                OPNO = string.Empty;
                                errorFlag = false;
                                try
                                {
                                    dr = dtMTL.NewRow();

                                    // ----- MONo -----
                                    dr["MONo"] = MONo;

                                    // ----- MaterialMo -----
                                    if (xmlList[i].SelectNodes("materialno").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("materialno").Item(0).InnerText))
                                    {
                                        dr["MaterialNo"] = modWS.CInput_Singlequotation(xmlList[i].SelectNodes("materialno").Item(0).InnerText).ToString().ToUpper();
                                        MaterialNo = modWS.CInput_Singlequotation(xmlList[i].SelectNodes("materialno").Item(0).InnerText).ToString().ToUpper();
                                    }
                                    else
                                    {
                                        errorFlag = true;
                                        clsERP.combineException(ref strException, mesmsg: "[%MaterialListMaterialNoError%]");
                                    }

                                    // ----- MaterialLevel -----
                                    if (xmlList[i].SelectNodes("materiallevel").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("materiallevel").Item(0).InnerText) && Information.IsNumeric(xmlList[i].SelectNodes("materiallevel").Item(0).InnerText) == true)

                                    {
                                        MaterialLevel = Conversions.ToInteger(xmlList[i].SelectNodes("materiallevel").Item(0).InnerText);
                                    }
                                    else
                                    {
                                        // Default value
                                        MaterialLevel = Conversions.ToInteger(ConfigurationManager.AppSettings["defMOListMaterialLevel"]);
                                    }
                                    dr["MaterialLevel"] = MaterialLevel;

                                    // ----- StdQty -----
                                    decimal dblStdQty = 0m;
                                    if (xmlList[i].SelectNodes("stdqty").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("stdqty").Item(0).InnerText) && Information.IsNumeric(xmlList[i].SelectNodes("stdqty").Item(0).InnerText) == true)

                                    {

                                        dr["StdQty"] = Convert.ToDecimal(xmlList[i].SelectNodes("stdqty").Item(0).InnerText);
                                        dblStdQty = Convert.ToDecimal(dr["StdQty"]);
                                    }

                                    else
                                    {
                                        errorFlag = true;
                                        clsERP.combineException(ref strException, mesmsg: "[%MaterialListSTDQtyError%]");
                                    }

                                    // ----- UnitNo -----
                                    if (xmlList[i].SelectNodes("unitno").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("unitno").Item(0).InnerText))
                                    {
                                        string argstrInput6 = xmlList[i].SelectNodes("unitno").Item(0).InnerText;
                                        dr["UnitNo"] = modWS.CInput_Singlequotation(argstrInput6);
                                        xmlList[i].SelectNodes("unitno").Item(0).InnerText = argstrInput6;
                                    }
                                    else
                                    {
                                        errorFlag = true;
                                        clsERP.combineException(ref strException, mesmsg: "[%MaterialListUnitNoError%]");
                                    }

                                    // ----- PutInPlaceType -----
                                    if (xmlList[i].SelectNodes("putinplacetype").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("putinplacetype").Item(0).InnerText) && Information.IsNumeric(xmlList[i].SelectNodes("putinplacetype").Item(0).InnerText.ToUpper()) == true)

                                    {
                                        dr["PutInPlaceType"] = Conversions.ToInteger(xmlList[i].SelectNodes("putinplacetype").Item(0).InnerText);
                                    }
                                    else
                                    {
                                        // Default value
                                        dr["PutInPlaceType"] = Conversions.ToInteger(ConfigurationManager.AppSettings["defMOListPutInPlaceType"]);
                                    }

                                    // ----- DecreaseRate -----
                                    if (xmlList[i].SelectNodes("decreaserate").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("decreaserate").Item(0).InnerText) && Information.IsNumeric(xmlList[i].SelectNodes("decreaserate").Item(0).InnerText) == true)

                                    {
                                        dr["DecreaseRate"] = Convert.ToDecimal(xmlList[i].SelectNodes("decreaserate").Item(0).InnerText);
                                    }
                                    else
                                    {
                                        // Default value
                                        dr["DecreaseRate"] = Convert.ToDecimal(ConfigurationManager.AppSettings["defMOListDecreaseRate"]);
                                    }

                                    // ----- Specified -----
                                    if (xmlList[i].SelectNodes("specified").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("specified").Item(0).InnerText) && Information.IsNumeric(xmlList[i].SelectNodes("specified").Item(0).InnerText) == true)

                                    {
                                        dr["Specified"] = Convert.ToDecimal(xmlList[i].SelectNodes("specified").Item(0).InnerText);
                                    }
                                    else
                                    {
                                        // Default value
                                        dr["Specified"] = Convert.ToDecimal(ConfigurationManager.AppSettings["defMOListSpecified"]);
                                    }

                                    // ----- MaterialType-----
                                    if (xmlList[i].SelectNodes("materialtype").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("materialtype").Item(0).InnerText))

                                    {
                                        string argstrInput7 = xmlList[i].SelectNodes("materialtype").Item(0).InnerText;
                                        dr["MaterialType"] = modWS.CInput_Singlequotation(argstrInput7);
                                        xmlList[i].SelectNodes("materialtype").Item(0).InnerText = argstrInput7;
                                    }

                                    // ----- CountWay -----
                                    if (xmlList[i].SelectNodes("countway").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("countway").Item(0).InnerText) && Information.IsNumeric(xmlList[i].SelectNodes("countway").Item(0).InnerText) == true)

                                    {
                                        dr["CountWay"] = Conversions.ToInteger(xmlList[i].SelectNodes("countway").Item(0).InnerText);
                                    }
                                    else
                                    {
                                        // Default value
                                        dr["CountWay"] = Conversions.ToInteger(ConfigurationManager.AppSettings["defMOListCountWay"]);
                                    }

                                    // ----- CheckLotNo -----
                                    if (xmlList[i].SelectNodes("checklotno").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("checklotno").Item(0).InnerText) && Information.IsNumeric(xmlList[i].SelectNodes("checklotno").Item(0).InnerText) == true)


                                        dr["CheckLotNo"] = Conversions.ToInteger(xmlList[i].SelectNodes("checklotno").Item(0).InnerText);

                                    // ----- MaterialVersion -----
                                    if (xmlList[i].SelectNodes("materialversion").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("materialversion").Item(0).InnerText))

                                    {
                                        string argstrInput8 = xmlList[i].SelectNodes("materialversion").Item(0).InnerText;
                                        dr["MaterialVersion"] = modWS.CInput_Singlequotation(argstrInput8);
                                        xmlList[i].SelectNodes("materialversion").Item(0).InnerText = argstrInput8;
                                    }

                                    // ----- SubstituteMaterialNo -----
                                    if (xmlList[i].SelectNodes("substitutematerialno").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("substitutematerialno").Item(0).InnerText))
                                    {
                                        dr["SubstituteMaterialNo"] = modWS.CInput_Singlequotation(xmlList[i].SelectNodes("substitutematerialno").Item(0).InnerText).ToString().ToUpper();
                                        SubstituteMaterialNo = modWS.CInput_Singlequotation(xmlList[i].SelectNodes("substitutematerialno").Item(0).InnerText).ToString().ToUpper();
                                    }
                                    else
                                    {
                                        // Default value
                                        dr["SubstituteMaterialNo"] = dr["materialno"].ToString().ToUpper();
                                        SubstituteMaterialNo = dr["materialno"].ToString().ToUpper();
                                    }

                                    // ----- OPNo -----
                                    // 若有傳入作業站資訊以傳入的資訊為主
                                    // 若沒有傳入作業站資訊，則優先以產品BOM上定義的作業站，若產品BOM無定義，以物料屬性 PutInPlace_OPNo 中的值為主
                                    // 若皆無傳入則以Config中定義的作業站為主
                                    if (xmlList[i].SelectNodes("opno").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("opno").Item(0).InnerText))
                                    {
                                        string argstrInput9 = xmlList[i].SelectNodes("opno").Item(0).InnerText;
                                        dr["OPNo"] = modWS.CInput_Singlequotation(argstrInput9);
                                        xmlList[i].SelectNodes("opno").Item(0).InnerText = argstrInput9;
                                    }
                                    else
                                    {
                                        // 檢查產品BOM是否有定義，若無繼續往下查找對應作業站資訊
                                        using (var objPRD = new kcPRD.clsProduct())
                                        {

                                            DataSet dsTemp_PRD;
                                            if (SubstituteMaterialNo == MaterialNo)
                                            {
                                                dsTemp_PRD = objPRD.ShowBOM(ProductNo, ProductVersion, MaterialNo);
                                                if (dsTemp_PRD.Tables["PRDBOM"].Rows.Count > 0)
                                                {
                                                    OPNO = dsTemp_PRD.Tables["PRDBOM"].Rows[0]["OPNO"].ToString().ToUpper();
                                                    dsTemp_PRD = null;
                                                }
                                                else
                                                {
                                                    dsTemp_PRD = null;
                                                }
                                            }
                                            else
                                            {
                                                dsTemp_PRD = objPRD.ShowBOMMaterialGroup(ProductNo, ProductVersion, MaterialNo, MaterialNo: SubstituteMaterialNo);
                                                if (dsTemp_PRD.Tables["MaterialGroup"].Rows.Count > 0)
                                                {
                                                    OPNO = dsTemp_PRD.Tables["MaterialGroup"].Rows[0]["OPNO"].ToString().ToUpper();
                                                    dsTemp_PRD = null;
                                                }
                                                else
                                                {
                                                    dsTemp_PRD = null;
                                                }
                                            }

                                        }

                                        if (string.IsNullOrEmpty(OPNO))
                                        {
                                            // 檢查物料屬性是否有定義，若繼續往下查找對應作業站資訊
                                            DataSet dsTemp_MTL;
                                            using (var objMTL = new kcMTL.clsMTLBasis())
                                            {
                                                dsTemp_MTL = objMTL.ShowMaterialProperty(SubstituteMaterialNo, "PutInPlace_OPNo", 2);
                                                if (dsTemp_MTL.Tables["MaterialProperty"].Rows.Count > 0)
                                                {
                                                    OPNO = dsTemp_MTL.Tables["MaterialProperty"].Rows[0]["DEFAULTVALUE"].ToString().ToUpper();
                                                    dsTemp_MTL = null;
                                                }
                                                else
                                                {
                                                    dsTemp_MTL = null;
                                                }
                                            }

                                            if (string.IsNullOrEmpty(OPNO))
                                            {
                                                // Default value
                                                dr["OPNo"] = ConfigurationManager.AppSettings["defMOListOPNo"];
                                            }
                                            else
                                            {
                                                dr["OPNo"] = OPNO;
                                            }
                                        }
                                        else
                                        {
                                            dr["OPNo"] = OPNO;
                                        }

                                    }

                                    // 2013/02/18,Even,新增替代物料及物料使用量-------
                                    // ----- SubstituteMaterialLevel -----
                                    if (xmlList[i].SelectNodes("substitutemateriallevel").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("substitutemateriallevel").Item(0).InnerText) && Information.IsNumeric(xmlList[i].SelectNodes("substitutemateriallevel").Item(0).InnerText) == true)

                                    {
                                        dr["SubstituteMaterialLevel"] = Conversions.ToInteger(xmlList[i].SelectNodes("substitutemateriallevel").Item(0).InnerText);
                                    }
                                    else
                                    {
                                        // Default value,未抓取到，抓取MaterialLevel
                                        dr["SubstituteMaterialLevel"] = MaterialLevel;
                                    }
                                    // ----- SubstituteStdQty --
                                    if (xmlList[i].SelectNodes("substitutestdqty").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("substitutestdqty").Item(0).InnerText) && Information.IsNumeric(xmlList[i].SelectNodes("substitutestdqty").Item(0).InnerText) == true)

                                    {
                                        dr["SubstituteStdQty"] = Convert.ToDecimal(xmlList[i].SelectNodes("substitutestdqty").Item(0).InnerText);
                                    }
                                    else
                                    {
                                        // 2018/09/20 OwenLiu, 因為後端程式會重新計算，這邊取消預設值的指定
                                        // 'Default value,未抓取到，抓取則抓物料之標準數
                                        // dr("SubstituteStdQty") = dr("StdQty")
                                    }

                                    // ----- RequireQty--------若無資料則為工單數 * 標準數*(1+損耗率)
                                    if (xmlList[i].SelectNodes("requireqty").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("requireqty").Item(0).InnerText) && Information.IsNumeric(xmlList[i].SelectNodes("requireqty").Item(0).InnerText) == true)

                                    {
                                        dr["RequireQty"] = Convert.ToDecimal(xmlList[i].SelectNodes("requireqty").Item(0).InnerText);
                                    }
                                    else
                                    {
                                        // 2018/09/20 OwenLiu, 因為後端程式會重新計算，這邊取消預設值的指定
                                        // 'Default value
                                        // dr("RequireQty") = MOQty * dblStdQty * (1 + dr("DecreaseRate"))
                                    }

                                    // ----- DeliveryMethod -----
                                    // 2019/09/26 Grace 新增tagname, 材料型態：DeliveryMethod (Optional參數,非必傳)
                                    if (xmlList[i].SelectNodes("deliverymethod").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("deliverymethod").Item(0).InnerText))

                                    {
                                        string argstrInput10 = xmlList[i].SelectNodes("deliverymethod").Item(0).InnerText;
                                        dr["DeliveryMethod"] = modWS.CInput_Singlequotation(argstrInput10);
                                        xmlList[i].SelectNodes("deliverymethod").Item(0).InnerText = argstrInput10;
                                    }

                                    if (xmlList[i].SelectNodes("mainitem").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("mainitem").Item(0).InnerText))

                                    {
                                        string argstrInput13 = xmlList[i].SelectNodes("mainitem").Item(0).InnerText;
                                        dr["MainItem"] = modWS.CInput_Singlequotation(argstrInput13);
                                        xmlList[i].SelectNodes("mainitem").Item(0).InnerText = argstrInput13;
                                    }

                                    if (xmlList[i].SelectNodes("phantomitem").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("phantomitem").Item(0).InnerText))

                                    {
                                        string argstrInput13 = xmlList[i].SelectNodes("phantomitem").Item(0).InnerText;
                                        dr["PhantomItem"] = modWS.CInput_Singlequotation(argstrInput13);
                                        xmlList[i].SelectNodes("phantomitem").Item(0).InnerText = argstrInput13;
                                    }

                                    if (xmlList[i].SelectNodes("lockrequirement").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("lockrequirement").Item(0).InnerText))

                                    {
                                        string argstrInput13 = xmlList[i].SelectNodes("lockrequirement").Item(0).InnerText;
                                        dr["LockRequirement"] = modWS.CInput_Singlequotation(argstrInput13);
                                        xmlList[i].SelectNodes("lockrequirement").Item(0).InnerText = argstrInput13;
                                    }

                                    if (xmlList[i].SelectNodes("operationseqnum").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("operationseqnum").Item(0).InnerText))

                                    {
                                        string argstrInput13 = xmlList[i].SelectNodes("operationseqnum").Item(0).InnerText;
                                        dr["OperationSeqnum"] = modWS.CInput_Singlequotation(argstrInput13);
                                        xmlList[i].SelectNodes("operationseqnum").Item(0).InnerText = argstrInput13;
                                    }

                                    if (errorFlag == false)
                                    {
                                        dtMTL.Rows.Add(dr);
                                    }
                                }

                                catch (Exception ex)
                                {
                                    clsERP.combineException(ref strException, sysmsg: ex.Message, mesmsg: "[%MOMaterialListError%]", stack: ex.StackTrace);
                                }
                            }
                        }
                    }
                }

                // MO Property
                var dtMOProperty = new DataTable("MOProperty");
                dtMOProperty.Columns.Add("MONo", Type.GetType("System.String"));
                dtMOProperty.Columns.Add("PropertyNo", Type.GetType("System.String"));
                dtMOProperty.Columns.Add("PropertyValue", Type.GetType("System.String"));
                // dtMOProperty.Columns.Add("LotSerial", System.Type.GetType("System.String"))
                dtMOProperty.Columns.Add("DataType", Type.GetType("System.String"));  // DataType: 0:Numeric, 1:String(default), 2:Percent, 3:DateTime, 4:Boolean

                // web.config裡預設的MOProperty (ERPUnitNo)(原本是寫在ArrayList裡,改寫在DataTable裡)
                if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["defERPUnitNoProperty"]))
                {
                    DataRow drP;
                    drP = dtMOProperty.NewRow();
                    drP["MONo"] = MONo;
                    drP["PropertyNo"] = ConfigurationManager.AppSettings["defERPUnitNoProperty"];
                    drP["PropertyValue"] = MOUnitNo;
                    drP["DataType"] = "String";
                    dtMOProperty.Rows.Add(drP);
                }


                bool PropertyFlag = false;   // haoqian 221025
                                             // ERP拋過來的屬性
                if (xmlDoc.DocumentElement.GetElementsByTagName("property").Count > 0)
                {
                    if (xmlDoc.GetElementsByTagName("property").Item(0).SelectNodes("value").Count > 0)
                    {
                        xmlList = xmlDoc.GetElementsByTagName("property").Item(0).SelectNodes("value");
                        if (xmlList.Count == 0)
                        {
                        }
                        // clsERP.combineMessage(strMessage, , , "[%MOPropertyNotExist%]")
                        else
                        {
                            DataRow dr;
                            bool errorFlag = false;
                            PropertyFlag = true;   // haoqian 221025
                            for (int i = 0, loopTo1 = xmlList.Count - 1; i <= loopTo1; i++)
                            {
                                errorFlag = false;
                                try
                                {
                                    dr = dtMOProperty.NewRow();

                                    // ----- MONo -----
                                    dr["MONo"] = MONo;

                                    // ----- PropertyNo -----
                                    if (xmlList[i].SelectNodes("name").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("name").Item(0).InnerText))
                                    {
                                        string argstrInput11 = xmlList[i].SelectNodes("name").Item(0).InnerText;
                                        dr["PropertyNo"] = modWS.CInput_Singlequotation(argstrInput11);
                                        xmlList[i].SelectNodes("name").Item(0).InnerText = argstrInput11;
                                    }
                                    else
                                    {
                                        errorFlag = true;
                                        clsERP.combineException(ref strException, mesmsg: "[%MOPropertyNoEmpty%]");
                                    }

                                    // ----- PropertyValue -----
                                    if (xmlList[i].SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("value").Item(0).InnerText))
                                    {
                                        string argstrInput12 = xmlList[i].SelectNodes("value").Item(0).InnerText;
                                        dr["PropertyValue"] = modWS.CInput_Singlequotation(argstrInput12);
                                        xmlList[i].SelectNodes("value").Item(0).InnerText = argstrInput12;
                                    }
                                    else
                                    {
                                        errorFlag = true;
                                        clsERP.combineException(ref strException, mesmsg: "[%MOPropertyValueEmpty%]");
                                    }

                                    // ----- DataType -----
                                    if (xmlList[i].SelectNodes("type").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("type").Item(0).InnerText))
                                    {
                                        string argstrInput13 = xmlList[i].SelectNodes("type").Item(0).InnerText;
                                        dr["DataType"] = modWS.CInput_Singlequotation(argstrInput13);
                                        xmlList[i].SelectNodes("type").Item(0).InnerText = argstrInput13;
                                    }
                                    else
                                    {
                                        errorFlag = true;
                                        clsERP.combineException(ref strException, mesmsg: "[%MOPropertyDataTypeEmpty%]");
                                    }

                                    if (errorFlag == false)
                                    {
                                        dtMOProperty.Rows.Add(dr);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    clsERP.combineException(ref strException, sysmsg: ex.Message, mesmsg: "[%MOPropertyError%]", stack: ex.StackTrace);
                                }
                            }
                        }
                    }
                }

                if (strException.Count > 0)
                    goto exitFun;

                // KeyValue
                strKeyValue = MONo;

                // '呼叫Dll執行 ----- UnitNo=UnitType=SystemUnit -----
                clsOE.editMO(MONo, MOQty, RONo, ItemNo, CustomerNo, MOTypeNo, Priority, PlanFinishDate, Creator, CreateDate, Description, dtMTL, strMessage, strException, strAlert, dtMOProperty, strERPMOLineNo, PropertyFlag, CustomerLotNo, PlanStartDate);

                // 判斷成功與否
                if (strException.Count > 0)
                    goto exitFun;

                strResult = "success";

            exitFun:
                ;
            }


            catch (Exception ex)
            {
                clsERP.combineException(ref strException, sysmsg: ex.Message, mesmsg: "[%EditMOFail%]", stack: ex.StackTrace);
            }

            finally
            {

                // 將各部份之XML字串組起來並傳出
                string argReturnValue = null;
                OutXml = modWS.CombineXMLResponse(strIdentity, argReturnValue, strException, strResult, strMessage);

                // 紀錄Transaction Log
                clsERP.addTransactionLog_ErrorCode(modWS.GetXMLIdentityNode(xmlDoc, "transactionid"), modWS.GetXMLIdentityNode(xmlDoc, "moduleid"), modWS.GetXMLIdentityNode(xmlDoc, "functionid"), modWS.GetXMLIdentityNode(xmlDoc, "computername"), modWS.GetXMLIdentityNode(xmlDoc, "curuserno"), modWS.GetXMLIdentityNode(xmlDoc, "sendtime"), strResult, strKeyValue, strMessage, strException, InXml, OutXml, "EditMO", Conversions.ToInteger(ConfigurationManager.AppSettings["keepLog"]), Conversions.ToInteger(ConfigurationManager.AppSettings["keepXML"]), LogClass: "ERP");

                funEditMORet = OutXml;

            }

            return funEditMORet;

        }
        #endregion

        /// <summary>
        /// 匹配你调试结构的API服务入参信息类
        /// </summary>
        public class API_Base_ServiceInfo
        {
            public string ComputerName { get; set; }
            public string CurUserNo { get; set; }
            public string FunctionID { get; set; }
            // 你需要取的目标属性1
            public string InJson { get; set; }
            public string ModuleID { get; set; }
            public string OutJson { get; set; }
            public string PackageName { get; set; }
            public DateTime SendTime { get; set; }
            public int TargetType { get; set; }
            public string TransactionId { get; set; }
            // 你需要取的目标属性2
            public HttpRequestHeaders httpRequest { get; set; }
            public int keepJson { get; set; }
        }
        public static string InvokeSrv_JsonToXml(object parameters)
        {
            string result = "";
            string transactionid = "";
            string moduleid = "";
            string functionid = "";
            string computername = "";
            string curuserno = "";
            string curusrpwd = "";//新增用户密码 SM2加密
            string sendtime = "";
            string languagemode = "";
            string outXml = "";
            string Json = "";



            string ContentType = "";
            string SourceSystem = "";
            string TargetSystem = "";
            string Authorization = "";

            try
            {
                //转换为数组
                if (parameters is object[] paramArray && paramArray.Length >= 2)
                {
                    if (paramArray[1] is API_Base.ServiceInfo serviceInfo)
                    {
                        Json = serviceInfo.InJson;
                        string headerText = serviceInfo.httpRequest.ToString();

                        // 解析逻辑
                        var lines = headerText.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
                        Dictionary<string, string> headers = new Dictionary<string, string>();
                        foreach (var line in lines)
                        {
                            int index = line.IndexOf(':');
                            if (index > 0)
                            {
                                string key = line.Substring(0, index).Trim();
                                string value = line.Substring(index + 1).Trim();
                                headers[key] = value;
                            }
                        }
                        // 结果
                        //curuserno = headers.TryGetValue("curuserno", out var no) ? no : "";
                        //curusrpwd = headers.TryGetValue("curusrpwd", out var pwd) ? pwd : "";


                        ContentType = headers.TryGetValue("Content-Type", out var contp) ? contp : "";
                        SourceSystem = headers.TryGetValue("Source-System", out var sous) ? sous : "";
                        TargetSystem = headers.TryGetValue("Target-System", out var tars) ? tars : "";
                        Authorization = headers.TryGetValue("Authorization", out var auth) ? auth : "";

                        curusrpwd = Authorization;





                    }
                }

                XmlDocument xmlDoc = Newtonsoft.Json.JsonConvert.DeserializeXmlNode(Json);

                if (xmlDoc.GetElementsByTagName("transactionid").Count > 0)
                    transactionid = xmlDoc.GetElementsByTagName("transactionid")[0].InnerText;
                if (xmlDoc.GetElementsByTagName("moduleid").Count > 0)
                    moduleid = xmlDoc.GetElementsByTagName("moduleid")[0].InnerText;
                if (xmlDoc.GetElementsByTagName("computername").Count > 0)
                    computername = xmlDoc.GetElementsByTagName("computername")[0].InnerText;
                if (xmlDoc.GetElementsByTagName("curuserno").Count > 0)
                    curuserno = xmlDoc.GetElementsByTagName("curuserno")[0].InnerText;
                ////解析传入密码
                //if (xmlDoc.GetElementsByTagName("curusrpwd").Count > 0)
                //    curusrpwd = xmlDoc.GetElementsByTagName("curusrpwd")[0].InnerText;


                if (xmlDoc.GetElementsByTagName("sendtime").Count > 0)
                    sendtime = xmlDoc.GetElementsByTagName("sendtime")[0].InnerText;
                if (xmlDoc.GetElementsByTagName("languagemode").Count > 0)
                    languagemode = xmlDoc.GetElementsByTagName("languagemode")[0].InnerText;

                XmlNodeList temp = xmlDoc.GetElementsByTagName("functionid");
                XmlNode nFunctionId = temp.Count > 0 ? temp[0] : null;
                if (nFunctionId == null)
                    throw new iMESException.MESException("0000-003000", "functionid Not Found");

                if (curuserno == "")
                {
                    throw new iMESException.MESException("0000-003000", "curuserno Not Found");
                }

                if (curusrpwd == "")
                {
                    throw new iMESException.MESException("0000-003000", "curusrpwd Not Found");
                }


                //if (ContentType == "")
                //{
                //    throw new iMESException.MESException("0000-003000", "ContentType Not Found");
                //}

                if (SourceSystem == "")
                {
                    throw new iMESException.MESException("0000-003000", "SourceSystem Not Found");
                }

                if (TargetSystem == "")
                {
                    throw new iMESException.MESException("0000-003000", "TargetSystem Not Found");
                }


                functionid = nFunctionId.InnerText;

                //add by 14166 for 新增权限校验
                tcEAI_C.clsERP.funCheckUser(curuserno, curusrpwd);

                //alter by 14166 for 调整调用方式
                //仅支持标准接口客开

                //MethodInfo mi = typeof(EAIws.wsERP).GetMethod(functionid, BindingFlags.Public | BindingFlags.Instance);
                //System.Reflection.ConstructorInfo ctor = typeof(EAIws.wsERP).GetConstructor(Type.EmptyTypes);


                ////调整支持新个案接口
                //MethodInfo mi = null;
                //System.Reflection.ConstructorInfo ctor = null;

                //// 定义要搜索的类型顺序
                //Type[] searchTypes = { typeof(modERP), typeof(EAIws.wsERP) };
                //Type targetType = null;

                //foreach (Type type in searchTypes)
                //{
                //    mi = type.GetMethod(functionid, BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);
                //    if (mi != null)
                //    {
                //        targetType = type;
                //        break;
                //    }
                //}

                //if (targetType == null)
                //{
                //    throw new iMESException.MESException("0000-003000", functionid + " [%INVOKE FAIL%]!");
                //}



                MethodInfo mi = null;
                System.Reflection.ConstructorInfo ctor = null;


                mi = typeof(modERP).GetMethod(functionid, BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);
                if (mi == null)
                {
                    mi = typeof(EAIws.wsERP).GetMethod(functionid, BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);
                    if (mi == null)
                    {
                        throw new iMESException.MESException("0000-003000", functionid + " [%INVOKE FAIL%]!");
                    }
                    else
                    {
                        ctor = typeof(EAIws.wsERP).GetConstructor(Type.EmptyTypes);
                        object instance = ctor.Invoke(null);
                        outXml = mi.Invoke(instance, new object[] { xmlDoc.OuterXml }).ToString();
                    }
                }
                else
                {
                    outXml = mi.Invoke(null, new object[] { xmlDoc.OuterXml }).ToString();
                }


                XmlDocument xmlDoc2 = new XmlDocument();
                xmlDoc2.LoadXml(outXml);
                result = Newtonsoft.Json.JsonConvert.SerializeObject(xmlDoc2);
            }
            catch (Exception ex)
            {
                if (ex is TargetInvocationException && ex.InnerException != null) ex = ex.InnerException;

                Dictionary<string, object> resultObj = new Dictionary<string, object>();
                resultObj["response"] = new Dictionary<string, object>();
                Dictionary<string, object> response = resultObj["response"] as Dictionary<string, object>;
                response["identity"] = new Dictionary<string, object>();
                response["exception"] = new Dictionary<string, object>();
                response["returnvalue"] = "";
                response["result"] = "fail";
                Dictionary<string, object> identity = ((resultObj["response"] as Dictionary<string, object>)["identity"] as Dictionary<string, object>);
                identity["transactionid"] = transactionid;
                identity["moduleid"] = moduleid;
                identity["functionid"] = functionid;
                identity["computername"] = computername;
                identity["curuserno"] = curuserno;
                identity["sendtime"] = sendtime;
                identity["languagemode"] = languagemode;
                Dictionary<string, object> exception = ((resultObj["response"] as Dictionary<string, object>)["exception"] as Dictionary<string, object>);
                exception["code"] = ex is iMESException.MESException ? (ex as iMESException.MESException).ErrorCode : "0000-999999";
                exception["sysmsg"] = ex.Message;
                exception["mesmsg"] = ex.Message;
                exception["stack"] = ex.StackTrace;
                result = Newtonsoft.Json.JsonConvert.SerializeObject(resultObj);
            }

            return result;
        }






        #region-----------add by 14166 for 新增人员接口-----------
        public static string CreateUesr(string InXml)
        {
            string funAddUserRet = default(string);
            System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();    // 用以讀取Xml字串 
            System.Xml.XmlNodeList xmlList;

            string OutXml = null;

            string strIdentity = string.Empty;    // Identity XML字串
            string strResult = "fail";            // Result XML字串
            List<ArrayList> strException = new List<ArrayList>();  // Exception XML字串
            List<ArrayList> strMessage = new List<ArrayList>();    // Message XML字串
            string strKeyValue = string.Empty;    // TransactionLot KeyValue
            string strMode = string.Empty;        // Mode

            try
            {
                try
                {
                    xmlDoc.LoadXml(InXml);
                }
                catch (Exception ex)
                {
                    clsERP.combineException(ref strException, null, ex.Message, "[%InXmlError%]", ex.StackTrace);
                    goto exitFun;
                }

                try
                {
                    strIdentity = modWS.CombineXMLIdentity(xmlDoc);
                }
                catch (Exception ex)
                {
                    clsERP.combineException(ref strException, null, ex.Message, "[%IndentityError%]", ex.StackTrace);
                    goto exitFun;
                }

                string UserNo = string.Empty;//用户编号
                string UserName = string.Empty;//用户名称
                string UserLevel = string.Empty;//用户等级


                string Creator = "ERP";//创建人
                string CreateDate = Conversions.ToString(DateTime.Now);//创建时间

                string Description = string.Empty;//描述
                string IssueState = string.Empty;//签核状态



                string ChangeDate = Conversions.ToString(DateTime.Now);//变更时间
                string ResetPassword = string.Empty;//第一次登录是否重设密码

                string UserType = string.Empty;//用户类别
                string UserDP = string.Empty;//用户部门
                string UserEmail = string.Empty;//电子邮箱


                string Password = string.Empty;//密码

                //DateTime InputDate = DateTime.Now;        // Default Today

                // UserNo  必要輸入 
                if (xmlDoc.DocumentElement.GetElementsByTagName("userno").Count > 0 && xmlDoc.GetElementsByTagName("userno").Item(0).SelectNodes("value").Count > 0)
                    UserNo = modWS.CInput_Singlequotation(xmlDoc.DocumentElement.GetElementsByTagName("userno").Item(0).SelectNodes("value").Item(0).InnerText);

                if (UserNo == string.Empty)
                    clsERP.combineException(ref strException, null, null, "[%UserNoEmpty%%]");

                // UserName  必要輸入 
                if (xmlDoc.DocumentElement.GetElementsByTagName("username").Count > 0 && xmlDoc.GetElementsByTagName("username").Item(0).SelectNodes("value").Count > 0)
                    UserName = modWS.CInput_Singlequotation(xmlDoc.DocumentElement.GetElementsByTagName("username").Item(0).SelectNodes("value").Item(0).InnerText);

                if (UserName == string.Empty)
                    clsERP.combineException(ref strException, null, null, "[%UserNameEmpty%%]");

                // UserLevel  必要輸入 
                if (xmlDoc.DocumentElement.GetElementsByTagName("userlevel").Count > 0 && xmlDoc.GetElementsByTagName("userlevel").Item(0).SelectNodes("value").Count > 0)
                    UserLevel = modWS.CInput_Singlequotation(xmlDoc.DocumentElement.GetElementsByTagName("userlevel").Item(0).SelectNodes("value").Item(0).InnerText);

                if (UserLevel == string.Empty)
                    clsERP.combineException(ref strException, null, null, "[%UserLevelEmpty%%]");



                // Password  必要輸入 
                if (xmlDoc.DocumentElement.GetElementsByTagName("password").Count > 0 && xmlDoc.GetElementsByTagName("password").Item(0).SelectNodes("value").Count > 0)
                    Password = modWS.CInput_Singlequotation(xmlDoc.DocumentElement.GetElementsByTagName("password").Item(0).SelectNodes("value").Item(0).InnerText);

                if (UserLevel == string.Empty)
                    clsERP.combineException(ref strException, null, null, "[%PasswordEmpty%%]");



                // Creator  必要輸入 
                if (xmlDoc.DocumentElement.GetElementsByTagName("creator").Count > 0 && xmlDoc.GetElementsByTagName("creator").Item(0).SelectNodes("value").Count > 0)
                    Creator = modWS.CInput_Singlequotation(xmlDoc.DocumentElement.GetElementsByTagName("creator").Item(0).SelectNodes("value").Item(0).InnerText);

                // CreateDate 非必要輸入 
                if (xmlDoc.DocumentElement.GetElementsByTagName("createdate").Count > 0 && xmlDoc.GetElementsByTagName("createdate").Item(0).SelectNodes("value").Count > 0)
                    CreateDate = modWS.CInput_Singlequotation(xmlDoc.DocumentElement.GetElementsByTagName("createdate").Item(0).SelectNodes("value").Item(0).InnerText);

                // Description  必要輸入 
                if (xmlDoc.DocumentElement.GetElementsByTagName("description").Count > 0 && xmlDoc.GetElementsByTagName("description").Item(0).SelectNodes("value").Count > 0)
                    Description = modWS.CInput_Singlequotation(xmlDoc.DocumentElement.GetElementsByTagName("description").Item(0).SelectNodes("value").Item(0).InnerText);

                // IssueState 非必要輸入 
                if (xmlDoc.DocumentElement.GetElementsByTagName("issuestate").Count > 0 && xmlDoc.GetElementsByTagName("issuestate").Item(0).SelectNodes("value").Count > 0)
                    IssueState = modWS.CInput_Singlequotation(xmlDoc.DocumentElement.GetElementsByTagName("issuestate").Item(0).SelectNodes("value").Item(0).InnerText);

                // ChangeDate  必要輸入 
                if (xmlDoc.DocumentElement.GetElementsByTagName("changedate").Count > 0 && xmlDoc.GetElementsByTagName("changedate").Item(0).SelectNodes("value").Count > 0)
                    ChangeDate = modWS.CInput_Singlequotation(xmlDoc.DocumentElement.GetElementsByTagName("changedate").Item(0).SelectNodes("value").Item(0).InnerText);

                // ResetPassword 非必要輸入 
                if (xmlDoc.DocumentElement.GetElementsByTagName("resetpassword").Count > 0 && xmlDoc.GetElementsByTagName("resetpassword").Item(0).SelectNodes("value").Count > 0)
                    ResetPassword = modWS.CInput_Singlequotation(xmlDoc.DocumentElement.GetElementsByTagName("resetpassword").Item(0).SelectNodes("value").Item(0).InnerText);

                // UserType 非必要輸入 
                if (xmlDoc.DocumentElement.GetElementsByTagName("usertype").Count > 0 && xmlDoc.GetElementsByTagName("usertype").Item(0).SelectNodes("value").Count > 0)
                    UserType = modWS.CInput_Singlequotation(xmlDoc.DocumentElement.GetElementsByTagName("usertype").Item(0).SelectNodes("value").Item(0).InnerText);



                // UserEmail  邮件非必要輸入 
                if (xmlDoc.DocumentElement.GetElementsByTagName("emailaddress").Count > 0 && xmlDoc.GetElementsByTagName("emailaddress").Item(0).SelectNodes("value").Count > 0)
                    UserEmail = modWS.CInput_Singlequotation(xmlDoc.DocumentElement.GetElementsByTagName("emailaddress").Item(0).SelectNodes("value").Item(0).InnerText);

                // UserDP  部门非必要輸入 
                if (xmlDoc.DocumentElement.GetElementsByTagName("departmentno").Count > 0 && xmlDoc.GetElementsByTagName("departmentno").Item(0).SelectNodes("value").Count > 0)
                    UserDP = modWS.CInput_Singlequotation(xmlDoc.DocumentElement.GetElementsByTagName("departmentno").Item(0).SelectNodes("value").Item(0).InnerText);





                // 檢查必要性欄位
                if (strException.Count > 0)
                    goto exitFun;
                //string UserNo = string.Empty;//用户编号
                //string UserName = string.Empty;//用户名称
                //string UserLevel = string.Empty;//用户等级


                //string Creator = "ERP";//创建人
                //string CreateDate = Conversions.ToString(DateTime.Now);//创建时间

                //string Description = string.Empty;//描述
                //string IssueState = string.Empty;//签核状态



                //string ChangeDate = string.Empty;//变更时间
                //string ResetPassword = string.Empty;//第一次登录是否重设密码

                //string UserType = string.Empty;//用户类别
                //string UserDP = string.Empty;//用户部门
                //string UserEmail = string.Empty;//电子邮箱
                // KeyValue
                strKeyValue = UserNo;

                clsERP.funAddUser(ref strMessage, ref strException, UserNo, UserName, UserLevel, Creator, CreateDate, Description, IssueState, ChangeDate, ResetPassword, UserType, UserDP, UserEmail, Password);

                // 判斷成功與否
                if (strException.Count > 0)
                    goto exitFun;

                strResult = "success";


            exitFun:
                ;
            }
            catch (Exception ex)
            {
                clsERP.combineException(ref strException, null, ex.Message, "[%AddUserFail%]", ex.StackTrace);
            }
            finally
            {

                // 將各部份之XML字串組起來並傳出
                OutXml = modWS.CombineXMLResponse(strIdentity, null, strException, strResult, strMessage);

                // 紀錄Transaction Log
                clsERP.addTransactionLog_ErrorCode(modWS.GetXMLIdentityNode(xmlDoc, "transactionid"), modWS.GetXMLIdentityNode(xmlDoc, "moduleid"), modWS.GetXMLIdentityNode(xmlDoc, "functionid"), modWS.GetXMLIdentityNode(xmlDoc, "computername"), modWS.GetXMLIdentityNode(xmlDoc, "curuserno"), modWS.GetXMLIdentityNode(xmlDoc, "sendtime"), strResult, strKeyValue, strMessage, strException, InXml, OutXml, "AddUser(" + strMode + ")", Conversions.ToInteger(1), Conversions.ToInteger(1), LogClass: "ERP");

                funAddUserRet = OutXml;
            }

            return funAddUserRet;
        }

        public static string DelUesr(string InXml)
        {
            string funAddUserRet = default(string);
            System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();    // 用以讀取Xml字串 
            System.Xml.XmlNodeList xmlList;

            string OutXml = null;

            string strIdentity = string.Empty;    // Identity XML字串
            string strResult = "fail";            // Result XML字串
            List<ArrayList> strException = new List<ArrayList>();  // Exception XML字串
            List<ArrayList> strMessage = new List<ArrayList>();    // Message XML字串
            string strKeyValue = string.Empty;    // TransactionLot KeyValue
            string strMode = string.Empty;        // Mode

            try
            {
                try
                {
                    xmlDoc.LoadXml(InXml);
                }
                catch (Exception ex)
                {
                    clsERP.combineException(ref strException, null, ex.Message, "[%InXmlError%]", ex.StackTrace);
                    goto exitFun;
                }

                try
                {
                    strIdentity = modWS.CombineXMLIdentity(xmlDoc);
                }
                catch (Exception ex)
                {
                    clsERP.combineException(ref strException, null, ex.Message, "[%IndentityError%]", ex.StackTrace);
                    goto exitFun;
                }

                string UserNo = string.Empty;//用户编号
                string UserName = string.Empty;//用户名称
                string UserLevel = string.Empty;//用户等级


                string Creator = "ERP";//创建人
                string CreateDate = Conversions.ToString(DateTime.Now);//创建时间

                string Description = string.Empty;//描述
                string IssueState = string.Empty;//签核状态



                string ChangeDate = Conversions.ToString(DateTime.Now);//变更时间
                string ResetPassword = string.Empty;//第一次登录是否重设密码

                string UserType = string.Empty;//用户类别
                string UserDP = string.Empty;//用户部门
                string UserEmail = string.Empty;//电子邮箱


                string Password = string.Empty;//密码

                //DateTime InputDate = DateTime.Now;        // Default Today

                // UserNo  必要輸入 
                if (xmlDoc.DocumentElement.GetElementsByTagName("userno").Count > 0 && xmlDoc.GetElementsByTagName("userno").Item(0).SelectNodes("value").Count > 0)
                    UserNo = modWS.CInput_Singlequotation(xmlDoc.DocumentElement.GetElementsByTagName("userno").Item(0).SelectNodes("value").Item(0).InnerText);

                if (UserNo == string.Empty)
                    clsERP.combineException(ref strException, null, null, "[%UserNoEmpty%%]");

                // UserName  必要輸入 
                if (xmlDoc.DocumentElement.GetElementsByTagName("username").Count > 0 && xmlDoc.GetElementsByTagName("username").Item(0).SelectNodes("value").Count > 0)
                    UserName = modWS.CInput_Singlequotation(xmlDoc.DocumentElement.GetElementsByTagName("username").Item(0).SelectNodes("value").Item(0).InnerText);

                //if (UserName == string.Empty)
                //    clsERP.combineException(ref strException, null, null, "[%UserNameEmpty%%]");

                // UserLevel  必要輸入 
                if (xmlDoc.DocumentElement.GetElementsByTagName("userlevel").Count > 0 && xmlDoc.GetElementsByTagName("userlevel").Item(0).SelectNodes("value").Count > 0)
                    UserLevel = modWS.CInput_Singlequotation(xmlDoc.DocumentElement.GetElementsByTagName("userlevel").Item(0).SelectNodes("value").Item(0).InnerText);

                //if (UserLevel == string.Empty)
                //    clsERP.combineException(ref strException, null, null, "[%UserLevelEmpty%%]");



                // Password  必要輸入 
                if (xmlDoc.DocumentElement.GetElementsByTagName("password").Count > 0 && xmlDoc.GetElementsByTagName("password").Item(0).SelectNodes("value").Count > 0)
                    Password = modWS.CInput_Singlequotation(xmlDoc.DocumentElement.GetElementsByTagName("password").Item(0).SelectNodes("value").Item(0).InnerText);

                if (UserLevel == string.Empty)
                    clsERP.combineException(ref strException, null, null, "[%PasswordEmpty%%]");



                // Creator  必要輸入 
                if (xmlDoc.DocumentElement.GetElementsByTagName("creator").Count > 0 && xmlDoc.GetElementsByTagName("creator").Item(0).SelectNodes("value").Count > 0)
                    Creator = modWS.CInput_Singlequotation(xmlDoc.DocumentElement.GetElementsByTagName("creator").Item(0).SelectNodes("value").Item(0).InnerText);

                // CreateDate 非必要輸入 
                if (xmlDoc.DocumentElement.GetElementsByTagName("createdate").Count > 0 && xmlDoc.GetElementsByTagName("createdate").Item(0).SelectNodes("value").Count > 0)
                    CreateDate = modWS.CInput_Singlequotation(xmlDoc.DocumentElement.GetElementsByTagName("createdate").Item(0).SelectNodes("value").Item(0).InnerText);

                // Description  必要輸入 
                if (xmlDoc.DocumentElement.GetElementsByTagName("description").Count > 0 && xmlDoc.GetElementsByTagName("description").Item(0).SelectNodes("value").Count > 0)
                    Description = modWS.CInput_Singlequotation(xmlDoc.DocumentElement.GetElementsByTagName("description").Item(0).SelectNodes("value").Item(0).InnerText);

                // IssueState 非必要輸入 
                if (xmlDoc.DocumentElement.GetElementsByTagName("issuestate").Count > 0 && xmlDoc.GetElementsByTagName("issuestate").Item(0).SelectNodes("value").Count > 0)
                    IssueState = modWS.CInput_Singlequotation(xmlDoc.DocumentElement.GetElementsByTagName("issuestate").Item(0).SelectNodes("value").Item(0).InnerText);

                // ChangeDate  必要輸入 
                if (xmlDoc.DocumentElement.GetElementsByTagName("changedate").Count > 0 && xmlDoc.GetElementsByTagName("changedate").Item(0).SelectNodes("value").Count > 0)
                    ChangeDate = modWS.CInput_Singlequotation(xmlDoc.DocumentElement.GetElementsByTagName("changedate").Item(0).SelectNodes("value").Item(0).InnerText);

                // ResetPassword 非必要輸入 
                if (xmlDoc.DocumentElement.GetElementsByTagName("resetpassword").Count > 0 && xmlDoc.GetElementsByTagName("resetpassword").Item(0).SelectNodes("value").Count > 0)
                    ResetPassword = modWS.CInput_Singlequotation(xmlDoc.DocumentElement.GetElementsByTagName("resetpassword").Item(0).SelectNodes("value").Item(0).InnerText);

                // UserType 非必要輸入 
                if (xmlDoc.DocumentElement.GetElementsByTagName("usertype").Count > 0 && xmlDoc.GetElementsByTagName("usertype").Item(0).SelectNodes("value").Count > 0)
                    UserType = modWS.CInput_Singlequotation(xmlDoc.DocumentElement.GetElementsByTagName("usertype").Item(0).SelectNodes("value").Item(0).InnerText);



                // UserEmail  邮件非必要輸入 
                if (xmlDoc.DocumentElement.GetElementsByTagName("emailaddress").Count > 0 && xmlDoc.GetElementsByTagName("emailaddress").Item(0).SelectNodes("value").Count > 0)
                    UserEmail = modWS.CInput_Singlequotation(xmlDoc.DocumentElement.GetElementsByTagName("emailaddress").Item(0).SelectNodes("value").Item(0).InnerText);

                // UserDP  部门非必要輸入 
                if (xmlDoc.DocumentElement.GetElementsByTagName("departmentno").Count > 0 && xmlDoc.GetElementsByTagName("departmentno").Item(0).SelectNodes("value").Count > 0)
                    UserDP = modWS.CInput_Singlequotation(xmlDoc.DocumentElement.GetElementsByTagName("departmentno").Item(0).SelectNodes("value").Item(0).InnerText);





                // 檢查必要性欄位
                if (strException.Count > 0)
                    goto exitFun;

                // KeyValue
                strKeyValue = UserNo;

                clsERP.funDelUser(ref strMessage, ref strException, UserNo, UserName, UserLevel, Creator, CreateDate, Description, IssueState, ChangeDate, ResetPassword, UserType, UserDP, UserEmail, Password);

                // 判斷成功與否
                if (strException.Count > 0)
                    goto exitFun;

                strResult = "success";


            exitFun:
                ;
            }
            catch (Exception ex)
            {
                clsERP.combineException(ref strException, null, ex.Message, "[%DelUserFail%]", ex.StackTrace);
            }
            finally
            {

                // 將各部份之XML字串組起來並傳出
                OutXml = modWS.CombineXMLResponse(strIdentity, null, strException, strResult, strMessage);

                // 紀錄Transaction Log
                clsERP.addTransactionLog_ErrorCode(modWS.GetXMLIdentityNode(xmlDoc, "transactionid"), modWS.GetXMLIdentityNode(xmlDoc, "moduleid"), modWS.GetXMLIdentityNode(xmlDoc, "functionid"), modWS.GetXMLIdentityNode(xmlDoc, "computername"), modWS.GetXMLIdentityNode(xmlDoc, "curuserno"), modWS.GetXMLIdentityNode(xmlDoc, "sendtime"), strResult, strKeyValue, strMessage, strException, InXml, OutXml, "AddUser(" + strMode + ")", Conversions.ToInteger(1), Conversions.ToInteger(1), LogClass: "ERP");

                funAddUserRet = OutXml;
            }

            return funAddUserRet;
        }
        #endregion


        #region --- 辅料调拨接口 ---
        public static string AddMaterial_WIP(string InXml)
        {
            string funAddMaterial_WIP = default(string);

            var xmlDoc = new XmlDocument();    // 用以讀取Xml字串
            XmlNodeList xmlList;
            string OutXml = null;

            string strIdentity = string.Empty;    // Identity XML字串
            string strResult = "fail";            // Result XML字串
            var strException = new List<ArrayList>();  // Exception XML字串
            var strMessage = new List<ArrayList>();    // Message XML字串
            string strKeyValue = string.Empty;    // TransactionLot KeyValue
            var strAlert = new List<ArrayList>();

            int Status = 0;//status：0为发料，1为退料

            try
            {

                try
                {
                    // 讀取InXml字串
                    xmlDoc.LoadXml(InXml);
                }
                catch (Exception ex)
                {
                    clsERP.combineException(ref strException, sysmsg: ex.Message, mesmsg: "[%InXmlError%]", stack: ex.StackTrace);
                    goto exitFun;
                }

                // 組Identity字串
                try
                {
                    strIdentity = modWS.CombineXMLIdentity(xmlDoc);
                }
                catch (Exception ex)
                {
                    clsERP.combineException(ref strException, sysmsg: ex.Message, mesmsg: "[%IndentityError%]", stack: ex.StackTrace);
                    goto exitFun;
                }

                // ----- Material In List -----
                var dtMTL = new DataTable("MaterialTransferList");
                dtMTL.Columns.Add("Vendorno", Type.GetType("System.String"));
                dtMTL.Columns.Add("MaterialNo", Type.GetType("System.String"));
                dtMTL.Columns.Add("MaterialLotNo", Type.GetType("System.String"));
                dtMTL.Columns.Add("MaterialUnitNo", Type.GetType("System.String"));
                dtMTL.Columns.Add("TransferQty", Type.GetType("System.Decimal"));
                dtMTL.Columns.Add("FromInventoryNo", Type.GetType("System.String"));
                dtMTL.Columns.Add("FromLocatorNo", Type.GetType("System.String"));
                dtMTL.Columns.Add("ToInventoryNo", Type.GetType("System.String"));
                dtMTL.Columns.Add("ToLocatorNo", Type.GetType("System.String"));

                if (xmlDoc.GetElementsByTagName("materialtransferlist").Count > 0)
                {
                    if (xmlDoc.GetElementsByTagName("materialtransferlist").Item(0).SelectNodes("value").Count > 0)
                    {
                        xmlList = xmlDoc.GetElementsByTagName("materialtransferlist").Item(0).SelectNodes("value");
                        if (xmlList.Count == 0)
                        {
                            clsERP.combineException(ref strException, mesmsg: "[%MaterialListNotExist%]");

                        }
                        else
                        {
                            DataRow dr;
                            bool errorFlag = false;
                            for (int i = 0, loopTo = xmlList.Count - 1; i <= loopTo; i++)
                            {
                                errorFlag = false;

                                try
                                {
                                    dr = dtMTL.NewRow();


                                    // ----- Vendorno -----
                                    if (xmlList[i].SelectNodes("vendorno").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("vendorno").Item(0).InnerText))

                                    {
                                        dr["Vendorno"] = modWS.CInput_Singlequotation(xmlList[i].SelectNodes("vendorno").Item(0).InnerText).ToString();
                                    }

                                    // ----- MaterialNo -----
                                    if (xmlList[i].SelectNodes("materialno").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("materialno").Item(0).InnerText))
                                    {
                                        dr["MaterialNo"] = modWS.CInput_Singlequotation(xmlList[i].SelectNodes("materialno").Item(0).InnerText).ToString().ToUpper();
                                    }
                                    else
                                    {
                                        errorFlag = true;
                                        clsERP.combineException(ref strException, mesmsg: "[%MaterialNoEmpty%]");
                                    }

                                    // ----- MaterialLotNo -----
                                    if (xmlList[i].SelectNodes("materiallotno").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("materiallotno").Item(0).InnerText))

                                    {
                                        dr["MaterialLotNo"] = modWS.CInput_Singlequotation(xmlList[i].SelectNodes("materiallotno").Item(0).InnerText).ToString();
                                    }


                                    // ----- MaterialUnitNo -----
                                    if (xmlList[i].SelectNodes("materialunitno").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("materialunitno").Item(0).InnerText))
                                    {
                                        string argstrInput = xmlList[i].SelectNodes("materialunitno").Item(0).InnerText;
                                        dr["MaterialUnitNo"] = modWS.CInput_Singlequotation(argstrInput);
                                        xmlList[i].SelectNodes("materialunitno").Item(0).InnerText = argstrInput;
                                    }
                                    else
                                    {
                                        errorFlag = true;
                                        clsERP.combineException(ref strException, mesmsg: "[%MaterialUnitNoEmpty%]");
                                    }

                                    // ----- TransferQty -----
                                    if (xmlList[i].SelectNodes("transferqty").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("transferqty").Item(0).InnerText) && Information.IsNumeric(xmlList[i].SelectNodes("transferqty").Item(0).InnerText) == true)

                                    {
                                        dr["TransferQty"] = Convert.ToDecimal(xmlList[i].SelectNodes("transferqty").Item(0).InnerText);
                                        //if (Mode == 2 || Mode == 4)
                                        //{
                                        //    // 還原發料或還原退料時將Qty改為負
                                        //    dr["Qty"] = -Convert.ToDecimal(dr["Qty"]);
                                        //}
                                    }
                                    else
                                    {
                                        errorFlag = true;
                                        clsERP.combineException(ref strException, mesmsg: "[%TransferQtyEmtpy%]");
                                    }

                                    // ----- FromInventoryNo -----
                                    if (xmlList[i].SelectNodes("frominventoryno").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("frominventoryno").Item(0).InnerText))

                                    {
                                        dr["FromInventoryNo"] = modWS.CInput_Singlequotation(xmlList[i].SelectNodes("frominventoryno").Item(0).InnerText).ToString();
                                    }

                                    // ----- FromLocatorNo -----
                                    dr["FromLocatorNo"] = "N/A";

                                    // ----- ToInventoryNo -----
                                    if (xmlList[i].SelectNodes("toinventoryno").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("toinventoryno").Item(0).InnerText))

                                    {
                                        dr["ToInventoryNo"] = modWS.CInput_Singlequotation(xmlList[i].SelectNodes("toinventoryno").Item(0).InnerText).ToString();
                                    }

                                    // ----- ToLocatorNo -----
                                    dr["ToLocatorNo"] = "N/A";

                                    if (errorFlag == false)
                                    {
                                        dtMTL.Rows.Add(dr);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    switch (Status)
                                    {
                                        case 0:
                                            {
                                                clsERP.combineException(ref strException, sysmsg: ex.Message, mesmsg: "[%MaterialTransferListFail%]", stack: ex.StackTrace);          // 发料错误
                                                break;
                                            }
                                        case 1:
                                            {
                                                clsERP.combineException(ref strException, sysmsg: ex.Message, mesmsg: "[%MaterialTransferListFail%]", stack: ex.StackTrace);          // 退料错误
                                                break;
                                            }
                                    }

                                }

                            }

                        }
                    }


                }


                string SubInventoryTransferNo = string.Empty;
                string Description = string.Empty;
                string Creator = string.Empty;
                var Createdate = DateTime.Now;

                // SubInventoryTransferNo
                if (xmlDoc.DocumentElement.GetElementsByTagName("subinventorytransferno").Count > 0 && xmlDoc.GetElementsByTagName("subinventorytransferno").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("subinventorytransferno").Item(0).SelectNodes("value").Item(0).InnerText))
                {
                    string argstrInput = xmlDoc.DocumentElement.GetElementsByTagName("subinventorytransferno").Item(0).SelectNodes("value").Item(0).InnerText;
                    SubInventoryTransferNo = modWS.CInput_Singlequotation(argstrInput);
                    xmlDoc.DocumentElement.GetElementsByTagName("subinventorytransferno").Item(0).SelectNodes("value").Item(0).InnerText = argstrInput;
                }

                // Description
                if (xmlDoc.DocumentElement.GetElementsByTagName("description").Count > 0 && xmlDoc.GetElementsByTagName("description").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("description").Item(0).SelectNodes("value").Item(0).InnerText))
                {
                    Description = xmlDoc.DocumentElement.GetElementsByTagName("description").Item(0).SelectNodes("value").Item(0).InnerText;
                }

                // Creator
                if (xmlDoc.DocumentElement.GetElementsByTagName("creator").Count > 0 && xmlDoc.GetElementsByTagName("creator").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("creator").Item(0).SelectNodes("value").Item(0).InnerText))
                {
                    Creator = xmlDoc.DocumentElement.GetElementsByTagName("creator").Item(0).SelectNodes("value").Item(0).InnerText;
                }

                // ToDateTime
                if (xmlDoc.DocumentElement.GetElementsByTagName("createdate").Count > 0 && xmlDoc.GetElementsByTagName("createdate").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("createdate").Item(0).SelectNodes("value").Item(0).InnerText))
                {
                    Createdate = Convert.ToDateTime(xmlDoc.DocumentElement.GetElementsByTagName("createdate").Item(0).SelectNodes("value").Item(0).InnerText);
                }

                // Status
                if (xmlDoc.DocumentElement.GetElementsByTagName("status").Count > 0 && xmlDoc.GetElementsByTagName("status").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("status").Item(0).SelectNodes("value").Item(0).InnerText))
                {
                    Status = Convert.ToInt32(xmlDoc.DocumentElement.GetElementsByTagName("status").Item(0).SelectNodes("value").Item(0).InnerText);
                }

                // 檢查必要性欄位
                if (string.IsNullOrEmpty(SubInventoryTransferNo))
                    clsERP.combineException(ref strException, mesmsg: "[%SubInventoryTransferNoEmpty%]");
                if (string.IsNullOrEmpty(Status.ToString()))
                    clsERP.combineException(ref strException, mesmsg: "[%StatusEmpty%]");
                if (strException.Count > 0)
                    goto exitFun;

                // KeyValue
                strKeyValue = SubInventoryTransferNo;

                // '呼叫Dll執行 ----- UnitNo=UnitType=SystemUnit -----
                tcEAI_C.clsERP.funAddMaterial_WIP(SubInventoryTransferNo, Description, Creator, Status, Createdate, dtMTL, strMessage, strException, strAlert);

                // 判斷成功與否
                if (strException.Count > 0)
                    goto exitFun;

                strResult = "success";

            exitFun:
                ;
            }
            catch (Exception ex)
            {
                clsERP.combineException(ref strException, sysmsg: ex.Message, mesmsg: "[%AddMaterial_WIPFail%]", stack: ex.StackTrace);
            }
            finally
            {
                // 將各部份之XML字串組起來並傳出
                string argReturnValue = null;
                OutXml = modWS.CombineXMLResponse(strIdentity, argReturnValue, strException, strResult, strMessage);
                // 紀錄Transaction Log
                tcEAI_C.clsERP.addTransactionLog_ErrorCode(modWS.GetXMLIdentityNode(xmlDoc, "transactionid"), modWS.GetXMLIdentityNode(xmlDoc, "moduleid"), modWS.GetXMLIdentityNode(xmlDoc, "functionid"), modWS.GetXMLIdentityNode(xmlDoc, "computername"), modWS.GetXMLIdentityNode(xmlDoc, "curuserno"), modWS.GetXMLIdentityNode(xmlDoc, "sendtime"), strResult, strKeyValue, strMessage, strException, InXml, OutXml, "AddMaterial_WIP", Conversions.ToInteger(System.Configuration.ConfigurationManager.AppSettings["keepLog"]), Conversions.ToInteger(System.Configuration.ConfigurationManager.AppSettings["keepXML"]), LogClass: "ERP");
                funAddMaterial_WIP = OutXml;

            }

            return funAddMaterial_WIP;

        }
        #endregion

        #region 更新MES箱状态接口
        public static string UpdateMESCarrier(string InXml)
        {
            string UpdateMESCarrier = default(string);
            var xmlDoc = new XmlDocument();    // 用以讀取Xml字串
            XmlNodeList xmlList;
            string OutXml = null;
            string strIdentity = string.Empty;    // Identity XML字串
            string strResult = "fail";            // Result XML字串
            var strException = new List<ArrayList>();  // Exception XML字串
            var strMessage = new List<ArrayList>();    // Message XML字串
            string strKeyValue = string.Empty;    // TransactionLot KeyValue
            string dbCode = "";
            string execType = "";
            string Type = "";
            string Barcode = "";
            try
            {

                try
                {
                    // 讀取InXml字串
                    xmlDoc.LoadXml(InXml);
                }
                catch (Exception ex)
                {
                    clsERP.combineException(ref strException, sysmsg: ex.Message, mesmsg: "[%InXmlError%]", stack: ex.StackTrace);
                    goto exitFun;
                }

                // 組Identity字串
                try
                {
                    strIdentity = modWS.CombineXMLIdentity(xmlDoc);
                }
                catch (Exception ex)
                {
                    clsERP.combineException(ref strException, sysmsg: ex.Message, mesmsg: "[%IndentityError%]", stack: ex.StackTrace);
                    goto exitFun;
                }

                if (xmlDoc.DocumentElement.GetElementsByTagName("dbcode").Count > 0 && xmlDoc.GetElementsByTagName("dbcode").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("dbcode").Item(0).SelectNodes("value").Item(0).InnerText))
                {
                    dbCode = xmlDoc.DocumentElement.GetElementsByTagName("dbcode").Item(0).SelectNodes("value").Item(0).InnerText;
                }

                if (xmlDoc.DocumentElement.GetElementsByTagName("exectype").Count > 0 && xmlDoc.GetElementsByTagName("exectype").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("exectype").Item(0).SelectNodes("value").Item(0).InnerText))
                {
                    execType = xmlDoc.DocumentElement.GetElementsByTagName("exectype").Item(0).SelectNodes("value").Item(0).InnerText;
                }

                if (xmlDoc.DocumentElement.GetElementsByTagName("type").Count > 0 && xmlDoc.GetElementsByTagName("type").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("type").Item(0).SelectNodes("value").Item(0).InnerText))
                {
                    Type = xmlDoc.DocumentElement.GetElementsByTagName("type").Item(0).SelectNodes("value").Item(0).InnerText;
                }

                if (xmlDoc.DocumentElement.GetElementsByTagName("barcode").Count > 0 && xmlDoc.GetElementsByTagName("barcode").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("barcode").Item(0).SelectNodes("value").Item(0).InnerText))
                {
                    Barcode = xmlDoc.DocumentElement.GetElementsByTagName("barcode").Item(0).SelectNodes("value").Item(0).InnerText;
                }

                // 檢查必要性欄位
                if (string.IsNullOrEmpty(dbCode))
                    clsERP.combineException(ref strException, mesmsg: "[%dbCodeEmpty%]");
                if (string.IsNullOrEmpty(execType))
                    clsERP.combineException(ref strException, mesmsg: "[%execTypeEmpty%]");
                if (string.IsNullOrEmpty(Type))
                    clsERP.combineException(ref strException, mesmsg: "[%TypeEmpty%]");
                if (string.IsNullOrEmpty(Barcode))
                    clsERP.combineException(ref strException, mesmsg: "[%BarcodeEmpty%]");
                if (strException.Count > 0)
                    goto exitFun;

                // '呼叫Dll執行 ----- UnitNo=UnitType=SystemUnit -----


                // 判斷成功與否
                if (strException.Count > 0)
                    goto exitFun;

                strResult = "success";

            exitFun:
                ;
            }
            catch (Exception ex)
            {
                clsERP.combineException(ref strException, sysmsg: ex.Message, mesmsg: "[%AddMaterial_WIPFail%]", stack: ex.StackTrace);
            }
            finally
            {
                // 將各部份之XML字串組起來並傳出
                string argReturnValue = null;
                OutXml = modWS.CombineXMLResponse(strIdentity, argReturnValue, strException, strResult, strMessage);
                // 紀錄Transaction Log
                tcEAI_C.clsERP.addTransactionLog_ErrorCode(modWS.GetXMLIdentityNode(xmlDoc, "transactionid"), modWS.GetXMLIdentityNode(xmlDoc, "moduleid"), modWS.GetXMLIdentityNode(xmlDoc, "functionid"), modWS.GetXMLIdentityNode(xmlDoc, "computername"), modWS.GetXMLIdentityNode(xmlDoc, "curuserno"), modWS.GetXMLIdentityNode(xmlDoc, "sendtime"), strResult, strKeyValue, strMessage, strException, InXml, OutXml, "AddMaterial_WIP", Conversions.ToInteger(System.Configuration.ConfigurationManager.AppSettings["keepLog"]), Conversions.ToInteger(System.Configuration.ConfigurationManager.AppSettings["keepXML"]), LogClass: "ERP");
                UpdateMESCarrier = OutXml;

            }

            return UpdateMESCarrier;
        }
        #endregion

        #region 湿敏接口
        public static string UpdateMaterialSM(string InXml)
        {
            string UpdateMaterialSM = default(string);

            var xmlDoc = new XmlDocument();    // 用以讀取Xml字串
            XmlNodeList xmlList;
            string OutXml = null;

            string strIdentity = string.Empty;    // Identity XML字串
            string strResult = "fail";            // Result XML字串
            var strException = new List<ArrayList>();  // Exception XML字串
            var strMessage = new List<ArrayList>();    // Message XML字串
            string strKeyValue = string.Empty;    // TransactionLot KeyValue
            DataRow drData;
            string Factory = "";
            DataTable dtData = new DataTable();
            try
            {

                try
                {
                    // 讀取InXml字串
                    xmlDoc.LoadXml(InXml);
                }
                catch (Exception ex)
                {
                    clsERP.combineException(ref strException, sysmsg: ex.Message, mesmsg: "[%InXmlError%]", stack: ex.StackTrace);
                    goto exitFun;
                }

                // 組Identity字串
                try
                {
                    strIdentity = modWS.CombineXMLIdentity(xmlDoc);
                }
                catch (Exception ex)
                {
                    clsERP.combineException(ref strException, sysmsg: ex.Message, mesmsg: "[%IndentityError%]", stack: ex.StackTrace);
                    goto exitFun;
                }

                if (xmlDoc.DocumentElement.GetElementsByTagName("Factory").Count > 0 && xmlDoc.GetElementsByTagName("Factory").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("Factory").Item(0).SelectNodes("value").Item(0).InnerText))
                {
                    Factory = xmlDoc.DocumentElement.GetElementsByTagName("Factory").Item(0).SelectNodes("value").Item(0).InnerText;
                }

                dtData.Columns.Add("REELID", Type.GetType("System.String"));
                dtData.Columns.Add("STATUS", Type.GetType("System.String"));
                dtData.Columns.Add("OPENDATETIME", Type.GetType("System.DateTime"));
                dtData.Columns.Add("CLOSEDATETIME", Type.GetType("System.DateTime"));
                dtData.Columns.Add("OPENUSER", Type.GetType("System.String"));
                dtData.Columns.Add("CLOSEUSER", Type.GetType("System.String"));
                dtData.Columns.Add("INTERVALTIME", Type.GetType("System.String"));
                if (xmlDoc.DocumentElement.GetElementsByTagName("Detail").Count > 0)
                {
                    if (xmlDoc.GetElementsByTagName("Detail").Item(0).SelectNodes("msdinfo").Count > 0)
                    {
                        xmlList = xmlDoc.GetElementsByTagName("Detail").Item(0).SelectNodes("msdinfo");
                        var loopTo = xmlList.Count - 1;
                        for (int i = 0; i <= loopTo; i++)
                        {
                            if (xmlList[i].SelectNodes("REELID").Count == 0 | xmlList[i].SelectNodes("STATUS").Count == 0 | xmlList[i].SelectNodes("OPENDATETIME").Count == 0 | xmlList[i].SelectNodes("CLOSEDATETIME").Count == 0 | xmlList[i].SelectNodes("OPENUSER").Count == 0 | xmlList[i].SelectNodes("CLOSEUSER").Count == 0 | xmlList[i].SelectNodes("INTERVALTIME").Count == 0)
                            {
                                throw new iMESException.MESException("0000-200001", "REELID,STATUS,OPENDATETIME,CLOSEDATETIME,OPENUSER,CLOSEUSER,INTERVALTIME can not empty!");
                            }
                            drData = dtData.NewRow();
                            drData["REELID"] = xmlList[i].SelectNodes("REELID").Item(0).InnerText;
                            drData["STATUS"] = xmlList[i].SelectNodes("STATUS").Item(0).InnerText;
                            drData["OPENDATETIME"] = Convert.ToDateTime(xmlList[i].SelectNodes("OPENDATETIME").Item(0).InnerText);
                            drData["CLOSEDATETIME"] = Convert.ToDateTime(xmlList[i].SelectNodes("CLOSEDATETIME").Item(0).InnerText);
                            drData["OPENUSER"] = xmlList[i].SelectNodes("OPENUSER").Item(0).InnerText;
                            drData["CLOSEUSER"] = xmlList[i].SelectNodes("CLOSEUSER").Item(0).InnerText;
                            drData["INTERVALTIME"] = xmlList[i].SelectNodes("INTERVALTIME").Item(0).InnerText;
                            dtData.Rows.Add(drData);
                        }
                    }
                }

                // 檢查必要性欄位
                if (string.IsNullOrEmpty(Factory))
                    clsERP.combineException(ref strException, mesmsg: "[%FactoryEmpty%]");
                if (strException.Count > 0)
                    goto exitFun;

                // KeyValue
                strKeyValue = Factory;

                // 判斷成功與否
                if (strException.Count > 0)
                    goto exitFun;

                strResult = "success";

            exitFun:
                ;
            }
            catch (Exception ex)
            {
                clsERP.combineException(ref strException, sysmsg: ex.Message, mesmsg: "[%AddMaterial_WIPFail%]", stack: ex.StackTrace);
            }
            finally
            {
                // 將各部份之XML字串組起來並傳出
                string argReturnValue = null;
                OutXml = modWS.CombineXMLResponse(strIdentity, argReturnValue, strException, strResult, strMessage);
                // 紀錄Transaction Log
                tcEAI_C.clsERP.addTransactionLog_ErrorCode(modWS.GetXMLIdentityNode(xmlDoc, "transactionid"), modWS.GetXMLIdentityNode(xmlDoc, "moduleid"), modWS.GetXMLIdentityNode(xmlDoc, "functionid"), modWS.GetXMLIdentityNode(xmlDoc, "computername"), modWS.GetXMLIdentityNode(xmlDoc, "curuserno"), modWS.GetXMLIdentityNode(xmlDoc, "sendtime"), strResult, strKeyValue, strMessage, strException, InXml, OutXml, "AddMaterial_WIP", Conversions.ToInteger(System.Configuration.ConfigurationManager.AppSettings["keepLog"]), Conversions.ToInteger(System.Configuration.ConfigurationManager.AppSettings["keepXML"]), LogClass: "ERP");
                UpdateMaterialSM = OutXml;

            }

            return UpdateMaterialSM;
        }
        #endregion

        #region MES退料接口
        public static string funMaterialReturn(string InXml)
        {
            string funMaterialReturn = default(string);

            var xmlDoc = new XmlDocument();    // 用以讀取Xml字串
            XmlNodeList xmlList;
            string OutXml = null;

            string strIdentity = string.Empty;    // Identity XML字串
            string strResult = "fail";            // Result XML字串
            var strException = new List<ArrayList>();  // Exception XML字串
            var strMessage = new List<ArrayList>();    // Message XML字串
            string strKeyValue = string.Empty;    // TransactionLot KeyValue
            DataRow drData;
            string Factory = "";
            DataTable dtData = new DataTable();
            DataTable dtDataTemp = new DataTable();
            string mocode = "";
            string mvdcode = "";
            string fromstorage = "";
            string tostorage = "";
            string usercode = "";
            string mdate = "";
            string mtime = "";
            try
            {

                try
                {
                    // 讀取InXml字串
                    xmlDoc.LoadXml(InXml);
                }
                catch (Exception ex)
                {
                    clsERP.combineException(ref strException, sysmsg: ex.Message, mesmsg: "[%InXmlError%]", stack: ex.StackTrace);
                    goto exitFun;
                }

                // 組Identity字串
                try
                {
                    strIdentity = modWS.CombineXMLIdentity(xmlDoc);
                }
                catch (Exception ex)
                {
                    clsERP.combineException(ref strException, sysmsg: ex.Message, mesmsg: "[%IndentityError%]", stack: ex.StackTrace);
                    goto exitFun;
                }



                if (xmlDoc.DocumentElement.GetElementsByTagName("Factory").Count > 0 && xmlDoc.GetElementsByTagName("Factory").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("Factory").Item(0).SelectNodes("value").Item(0).InnerText))
                {
                    Factory = xmlDoc.DocumentElement.GetElementsByTagName("Factory").Item(0).SelectNodes("value").Item(0).InnerText;
                }

                if (xmlDoc.DocumentElement.GetElementsByTagName("Detail").Count > 0 && xmlDoc.GetElementsByTagName("Detail").Item(0).SelectNodes("mcode").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("Detail").Item(0).SelectNodes("mcode").Item(0).InnerText))
                {
                    mocode = xmlDoc.DocumentElement.GetElementsByTagName("Detail").Item(0).SelectNodes("mocode").Item(0).InnerText;
                }
                if (xmlDoc.DocumentElement.GetElementsByTagName("Detail").Count > 0 && xmlDoc.GetElementsByTagName("Detail").Item(0).SelectNodes("mcode").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("Detail").Item(0).SelectNodes("mvdcode").Item(0).InnerText))
                {
                    mvdcode = xmlDoc.DocumentElement.GetElementsByTagName("Detail").Item(0).SelectNodes("mvdcode").Item(0).InnerText;
                }
                if (xmlDoc.DocumentElement.GetElementsByTagName("Detail").Count > 0 && xmlDoc.GetElementsByTagName("Detail").Item(0).SelectNodes("mcode").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("Detail").Item(0).SelectNodes("fromstorage").Item(0).InnerText))
                {
                    fromstorage = xmlDoc.DocumentElement.GetElementsByTagName("Detail").Item(0).SelectNodes("fromstorage").Item(0).InnerText;
                }
                if (xmlDoc.DocumentElement.GetElementsByTagName("Detail").Count > 0 && xmlDoc.GetElementsByTagName("Detail").Item(0).SelectNodes("mcode").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("Detail").Item(0).SelectNodes("tostorage").Item(0).InnerText))
                {
                    tostorage = xmlDoc.DocumentElement.GetElementsByTagName("Detail").Item(0).SelectNodes("tostorage").Item(0).InnerText;
                }
                if (xmlDoc.DocumentElement.GetElementsByTagName("Detail").Count > 0 && xmlDoc.GetElementsByTagName("Detail").Item(0).SelectNodes("mcode").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("Detail").Item(0).SelectNodes("usercode").Item(0).InnerText))
                {
                    usercode = xmlDoc.DocumentElement.GetElementsByTagName("Detail").Item(0).SelectNodes("usercode").Item(0).InnerText;
                }
                if (xmlDoc.DocumentElement.GetElementsByTagName("Detail").Count > 0 && xmlDoc.GetElementsByTagName("Detail").Item(0).SelectNodes("mcode").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("Detail").Item(0).SelectNodes("mdate").Item(0).InnerText))
                {
                    mdate = xmlDoc.DocumentElement.GetElementsByTagName("Detail").Item(0).SelectNodes("mdate").Item(0).InnerText;
                }
                if (xmlDoc.DocumentElement.GetElementsByTagName("Detail").Count > 0 && xmlDoc.GetElementsByTagName("Detail").Item(0).SelectNodes("mcode").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("Detail").Item(0).SelectNodes("mtime").Item(0).InnerText))
                {
                    mtime = xmlDoc.DocumentElement.GetElementsByTagName("Detail").Item(0).SelectNodes("mtime").Item(0).InnerText;
                }

                dtData.Columns.Add("MCODE", Type.GetType("System.String"));
                dtData.Columns.Add("QTY", Type.GetType("System.String"));
                if (xmlDoc.DocumentElement.GetElementsByTagName("Detail").Count > 0)
                {
                    if (xmlDoc.GetElementsByTagName("Detail").Item(0).SelectNodes("mlist").Count > 0)
                    {
                        xmlList = xmlDoc.GetElementsByTagName("Detail").Item(0).SelectNodes("mlist");
                        var loopTo = xmlList.Count - 1;
                        for (int i = 0; i <= loopTo; i++)
                        {
                            if (xmlList[i].SelectNodes("MCODE").Count == 0 | xmlList[i].SelectNodes("QTY").Count == 0)
                            {
                                throw new iMESException.MESException("0000-200001", "MCODE,QTY can not empty!");
                            }
                            drData = dtData.NewRow();
                            drData["MCODE"] = xmlList[i].SelectNodes("MCODE").Item(0).InnerText;
                            drData["QTY"] = xmlList[i].SelectNodes("QTY").Item(0).InnerText;
                            dtData.Rows.Add(drData);
                        }
                    }
                }

                dtDataTemp.Columns.Add("REELID", Type.GetType("System.String"));
                dtDataTemp.Columns.Add("MCODE", Type.GetType("System.String"));
                dtDataTemp.Columns.Add("QTY", Type.GetType("System.String"));
                if (xmlDoc.DocumentElement.GetElementsByTagName("Detail").Count > 0)
                {
                    if (xmlDoc.GetElementsByTagName("Detail").Item(0).SelectNodes("reelinfo").Count > 0)
                    {
                        xmlList = xmlDoc.GetElementsByTagName("Detail").Item(0).SelectNodes("reelinfo");
                        var loopTo = xmlList.Count - 1;
                        for (int i = 0; i <= loopTo; i++)
                        {
                            if (xmlList[i].SelectNodes("MCODE").Count == 0 | xmlList[i].SelectNodes("QTY").Count == 0 | xmlList[i].SelectNodes("REELID").Count == 0)
                            {
                                throw new iMESException.MESException("0000-200001", "REELID,MCODE,QTY can not empty!");
                            }
                            drData = dtDataTemp.NewRow();
                            drData["REELID"] = xmlList[i].SelectNodes("REELID").Item(0).InnerText;
                            drData["MCODE"] = xmlList[i].SelectNodes("MCODE").Item(0).InnerText;
                            drData["QTY"] = xmlList[i].SelectNodes("QTY").Item(0).InnerText;
                            dtDataTemp.Rows.Add(drData);
                        }
                    }
                }

                // 檢查必要性欄位
                if (string.IsNullOrEmpty(Factory))
                    clsERP.combineException(ref strException, mesmsg: "[%FactoryEmpty%]");
                if (strException.Count > 0)
                    goto exitFun;

                // KeyValue
                strKeyValue = Factory;

                // '呼叫Dll執行 ----- UnitNo=UnitType=SystemUnit -----


                // 判斷成功與否
                if (strException.Count > 0)
                    goto exitFun;

                strResult = "success";

            exitFun:
                ;
            }
            catch (Exception ex)
            {
                clsERP.combineException(ref strException, sysmsg: ex.Message, mesmsg: "[%AddMaterial_WIPFail%]", stack: ex.StackTrace);
            }
            finally
            {
                // 將各部份之XML字串組起來並傳出
                string argReturnValue = null;
                OutXml = modWS.CombineXMLResponse(strIdentity, argReturnValue, strException, strResult, strMessage);
                // 紀錄Transaction Log
                tcEAI_C.clsERP.addTransactionLog_ErrorCode(modWS.GetXMLIdentityNode(xmlDoc, "transactionid"), modWS.GetXMLIdentityNode(xmlDoc, "moduleid"), modWS.GetXMLIdentityNode(xmlDoc, "functionid"), modWS.GetXMLIdentityNode(xmlDoc, "computername"), modWS.GetXMLIdentityNode(xmlDoc, "curuserno"), modWS.GetXMLIdentityNode(xmlDoc, "sendtime"), strResult, strKeyValue, strMessage, strException, InXml, OutXml, "AddMaterial_WIP", Conversions.ToInteger(System.Configuration.ConfigurationManager.AppSettings["keepLog"]), Conversions.ToInteger(System.Configuration.ConfigurationManager.AppSettings["keepXML"]), LogClass: "ERP");
                funMaterialReturn = OutXml;

            }

            return funMaterialReturn;
        }
        #endregion

        //#region Reel校验接口
        ////public static string CheckReelQty(string jsonInput)
        ////{
        ////    JObject response = new JObject();
        ////    try
        ////    {
        ////        JObject requestJson = JObject.Parse(jsonInput);
        ////        string factory = (string)requestJson["Data"]?["Factory"];
        ////        string reelId = (string)requestJson["Data"]?["Detail"]?["REELID"];
        ////        string qty = (string)requestJson["Data"]?["Detail"]?["QTY"];
        ////        bool isSuccess = true;

        ////        if (isSuccess)
        ////        {
        ////            response["result"] = 1;
        ////            response["qty"] = qty;
        ////            response["mcode"] = "111";
        ////            response["vendorcode"] = "123456";
        ////            response["vendordate"] = "20240512";
        ////            response["manufacturer"] = "龙旗";
        ////            response["vendorlotno"] = "123";
        ////            response["oraFacReel"] = "12";
        ////            response["snscale"] = "09";
        ////            response["mpn"] = "";
        ////            response["produceArea"] = "";
        ////            response["cnum"] = 0;
        ////            response["msg"] = null;
        ////        }
        ////        else
        ////        {
        ////            response["result"] = 0;
        ////            response["msg"] = $"未找到该料卷{reelId}";
        ////            response["qty"] = "";
        ////        }
        ////    }
        ////    catch (Exception ex)
        ////    {
        ////        response["result"] = 0;
        ////        response["msg"] = "解析异常或系统错误: " + ex.Message;
        ////        response["qty"] = "";

        ////        // 此处可以加上你原来的记录 Log 的代码
        ////    }

        ////    return response.ToString(Newtonsoft.Json.Formatting.None );
        ////}

        //public static string CheckReelQty(object input)
        //{
        //    JObject response = new JObject();
        //    string Json = "";
        //    var strException = new List<ArrayList>();  // Exception XML字串
        //    var strMessage = new List<ArrayList>();    // Message XML字串
        //    try
        //    {
        //        if (input is object[] paramArray && paramArray.Length >= 2)
        //        {
        //            if (paramArray[1] is API_Base.ServiceInfo serviceInfo)
        //            {
        //                Json = serviceInfo.InJson;
        //                //JObject requestJson = JObject.FromObject(input);
        //                JObject requestJson = JObject.Parse(Json);
        //                string factory = requestJson["Data"]?["Factory"]?.ToString();
        //                string reelId = requestJson["Data"]?["Detail"]?["REELID"]?.ToString();
        //                string qty = requestJson["Data"]?["Detail"]?["QTY"]?.ToString();
        //                string STORAGECODE = requestJson["Data"]?["Detail"]?["STORAGECODE"]?.ToString();

        //                // 逻辑判断（这里保持你原有的逻辑）
        //                //clsERP.CheckReelQty()
        //                bool isSuccess = true;
        //                string mcode = "";
        //                string qty1 = "";
        //                isSuccess = clsERP.CheckReelQty(ref strException, ref strMessage, reelId,ref mcode,ref qty1);
        //                if (isSuccess)
        //                {
        //                    response["result"] = 1;
        //                    response["qty"] = qty1;
        //                    response["mcode"] = mcode;
        //                    response["vendorcode"] = "123456";
        //                    response["vendordate"] = DateTime.Now.ToString("yyyy-MM-dd");
        //                    response["manufacturer"] = "龙旗";
        //                    response["vendorlotno"] = "123";
        //                    response["oraFacReel"] = reelId;
        //                    response["snscale"] = "09";
        //                    response["mpn"] = "";
        //                    response["produceArea"] = "";
        //                    response["cnum"] = 0;
        //                    response["msg"] = null;
        //                }
        //                else
        //                {
        //                    response["result"] = 0;
        //                    response["msg"] = $"未找到该料卷{reelId}";
        //                    response["qty"] = "";
        //                }
        //            }
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        response["result"] = 0;
        //        response["msg"] = "数据解析异常或系统错误: " + ex.Message;
        //        response["qty"] = "";
        //        // Log.Error(ex); 
        //    }

        //    return response.ToString(Newtonsoft.Json.Formatting.None);
        //}
        //#endregion



        #region 电子料仓发料明细数据回传(按销售订单回传)
        public static string SendMaterial_RAW(string InXml)
        {
            string SendMaterial_RAWs = default(string);

            var xmlDoc = new XmlDocument();    // 用以讀取Xml字串
            XmlNodeList xmlList;
            string OutXml = null;

            string strIdentity = string.Empty;    // Identity XML字串
            string strResult = "fail";            // Result XML字串
            var strException = new List<ArrayList>();  // Exception XML字串
            var strMessage = new List<ArrayList>();    // Message XML字串
            string strKeyValue = string.Empty;    // TransactionLot KeyValue
            DataRow drData;
            string Factory = "";
            DataTable dtData = new DataTable();
            try
            {

                try
                {
                    // 讀取InXml字串
                    xmlDoc.LoadXml(InXml);
                }
                catch (Exception ex)
                {
                    clsERP.combineException(ref strException, sysmsg: ex.Message, mesmsg: "[%InXmlError%]", stack: ex.StackTrace);
                    goto exitFun;
                }

                // 組Identity字串
                try
                {
                    strIdentity = modWS.CombineXMLIdentity(xmlDoc);
                }
                catch (Exception ex)
                {
                    clsERP.combineException(ref strException, sysmsg: ex.Message, mesmsg: "[%IndentityError%]", stack: ex.StackTrace);
                    goto exitFun;
                }

                if (xmlDoc.DocumentElement.GetElementsByTagName("Factory").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("Factory").Item(0).InnerText))
                {
                    Factory = xmlDoc.DocumentElement.GetElementsByTagName("Factory").Item(0).InnerText;
                }

                dtData.Columns.Add("RECEIPTNO", Type.GetType("System.String"));
                dtData.Columns.Add("RECEIPTLINE", Type.GetType("System.String"));
                dtData.Columns.Add("STORAGECODE", Type.GetType("System.String"));
                dtData.Columns.Add("MCODE", Type.GetType("System.String"));
                dtData.Columns.Add("MNAME", Type.GetType("System.String"));
                dtData.Columns.Add("REELID", Type.GetType("System.String"));
                dtData.Columns.Add("DATECODE", Type.GetType("System.String"));

                dtData.Columns.Add("SNSCALE", Type.GetType("System.String"));
                dtData.Columns.Add("VENDERDATE", Type.GetType("System.String"));
                dtData.Columns.Add("VENDORCODE", Type.GetType("System.String"));
                dtData.Columns.Add("VENDORITEMCODE", Type.GetType("System.String"));
                dtData.Columns.Add("VENDERLOTNO", Type.GetType("System.String"));
                dtData.Columns.Add("MANUFACTURER", Type.GetType("System.String"));
                dtData.Columns.Add("EXDATE", Type.GetType("System.String"));
                dtData.Columns.Add("QTY", Type.GetType("System.String"));
                dtData.Columns.Add("USERCODE", Type.GetType("System.String"));

                dtData.Columns.Add("MDATE", Type.GetType("System.String"));
                dtData.Columns.Add("MTIME", Type.GetType("System.String"));


                if (xmlDoc.DocumentElement.GetElementsByTagName("Detail").Count > 0)
                {
                    xmlList = xmlDoc.GetElementsByTagName("Detail");
                    var loopTo = xmlList.Count - 1;
                    for (int i = 0; i <= loopTo; i++)
                    {
                        if (xmlList[i].SelectNodes("RECEIPTNO").Count == 0 | xmlList[i].SelectNodes("RECEIPTLINE").Count == 0 | xmlList[i].SelectNodes("STORAGECODE").Count == 0 | xmlList[i].SelectNodes("REELID").Count == 0 | xmlList[i].SelectNodes("DATECODE").Count == 0 | xmlList[i].SelectNodes("VENDERDATE").Count == 0 | xmlList[i].SelectNodes("VENDERLOTNO").Count == 0 |
                            xmlList[i].SelectNodes("MANUFACTURER").Count == 0 | xmlList[i].SelectNodes("EXDATE").Count == 0 | xmlList[i].SelectNodes("QTY").Count == 0 | xmlList[i].SelectNodes("USERCODE").Count == 0 | xmlList[i].SelectNodes("MDATE").Count == 0 | xmlList[i].SelectNodes("MTIME").Count == 0)
                        {
                            throw new iMESException.MESException("0000-200001", "RECEIPTNO,RECEIPTLINE,STORAGECODE,REELID,VENDERDATE,VENDERLOTNO,MANUFACTURER,EXDATE,QTY,USERCODE,MDATE,MTIME,can not empty!");
                        }
                        drData = dtData.NewRow();

                        drData["RECEIPTNO"] = xmlList[i].SelectNodes("RECEIPTNO").Item(0).InnerText;
                        drData["RECEIPTLINE"] = xmlList[i].SelectNodes("RECEIPTLINE").Item(0).InnerText;
                        drData["STORAGECODE"] = xmlList[i].SelectNodes("STORAGECODE").Item(0).InnerText;
                        drData["MCODE"] = xmlList[i].SelectNodes("MCODE").Item(0).InnerText;
                        drData["MNAME"] = xmlList[i].SelectNodes("MNAME").Item(0).InnerText;
                        drData["REELID"] = xmlList[i].SelectNodes("REELID").Item(0).InnerText;
                        drData["DATECODE"] = xmlList[i].SelectNodes("DATECODE").Item(0).InnerText;
                        drData["SNSCALE"] = xmlList[i].SelectNodes("SNSCALE").Item(0).InnerText;
                        drData["VENDERDATE"] = xmlList[i].SelectNodes("VENDERDATE").Item(0).InnerText;
                        drData["VENDORCODE"] = xmlList[i].SelectNodes("VENDORCODE").Item(0).InnerText;
                        drData["VENDORITEMCODE"] = xmlList[i].SelectNodes("VENDORITEMCODE").Item(0).InnerText;
                        drData["VENDERLOTNO"] = xmlList[i].SelectNodes("VENDERLOTNO").Item(0).InnerText;
                        drData["MANUFACTURER"] = xmlList[i].SelectNodes("MANUFACTURER").Item(0).InnerText;
                        drData["EXDATE"] = xmlList[i].SelectNodes("EXDATE").Item(0).InnerText;

                        drData["QTY"] = xmlList[i].SelectNodes("QTY").Item(0).InnerText;
                        drData["USERCODE"] = xmlList[i].SelectNodes("USERCODE").Item(0).InnerText;
                        drData["MDATE"] = xmlList[i].SelectNodes("MDATE").Item(0).InnerText;
                        drData["MTIME"] = xmlList[i].SelectNodes("MTIME").Item(0).InnerText;

                        dtData.Rows.Add(drData);
                    }
                }

                // 檢查必要性欄位
                if (string.IsNullOrEmpty(Factory))
                    clsERP.combineException(ref strException, mesmsg: "[%FactoryEmpty%]");
                if (strException.Count > 0)
                    goto exitFun;

                // KeyValue
                strKeyValue = Factory;

                // 判斷成功與否
                if (strException.Count > 0)
                    goto exitFun;

                strResult = "success";

            exitFun:
                ;
            }
            catch (Exception ex)
            {
                clsERP.combineException(ref strException, sysmsg: ex.Message, mesmsg: "[%SendMaterial_RAWFail%]", stack: ex.StackTrace);
            }
            finally
            {
                // 將各部份之XML字串組起來並傳出
                string argReturnValue = null;
                OutXml = modWS.CombineXMLResponse(strIdentity, argReturnValue, strException, strResult, strMessage);
                // 紀錄Transaction Log
                tcEAI_C.clsERP.addTransactionLog_ErrorCode(modWS.GetXMLIdentityNode(xmlDoc, "transactionid"), modWS.GetXMLIdentityNode(xmlDoc, "moduleid"), modWS.GetXMLIdentityNode(xmlDoc, "functionid"), modWS.GetXMLIdentityNode(xmlDoc, "computername"), modWS.GetXMLIdentityNode(xmlDoc, "curuserno"), modWS.GetXMLIdentityNode(xmlDoc, "sendtime"), strResult, strKeyValue, strMessage, strException, InXml, OutXml, "AddMaterial_WIP", Conversions.ToInteger(System.Configuration.ConfigurationManager.AppSettings["keepLog"]), Conversions.ToInteger(System.Configuration.ConfigurationManager.AppSettings["keepXML"]), LogClass: "ERP");
                SendMaterial_RAWs = OutXml;

            }

            return SendMaterial_RAWs;
        }
        #endregion


        #region  "WMS发料回传前,先回传发料明细关联reel信息,datahub调用MES服务,推送发料明细数据至MES;"

        /// <summary>
        /// 校验JOSN权限，并解析出JOSN,目前账号只支持DS
        /// </summary>
        /// <returns></returns>
        public static string funCheckJson(object parameters)
        {
            string result = "";
            string transactionid = "";
            string moduleid = "";
            string functionid = "";
            string computername = "";
            string curuserno = "DS";
            string curusrpwd = "";//新增用户密码 SM2加密
            string sendtime = "";
            string languagemode = "";
            string outXml = "";
            string Json = "";



            string ContentType = "";
            string SourceSystem = "";
            string TargetSystem = "";
            string Authorization = "";
            try
            {
                //转换为数组
                if (parameters is object[] paramArray && paramArray.Length >= 2)
                {
                    if (paramArray[1] is API_Base.ServiceInfo serviceInfo)
                    {
                        Json = serviceInfo.InJson;
                        string headerText = serviceInfo.httpRequest.ToString();

                        // 解析逻辑
                        var lines = headerText.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
                        Dictionary<string, string> headers = new Dictionary<string, string>();
                        foreach (var line in lines)
                        {
                            int index = line.IndexOf(':');
                            if (index > 0)
                            {
                                string key = line.Substring(0, index).Trim();
                                string value = line.Substring(index + 1).Trim();
                                headers[key] = value;
                            }
                        }
                        // 结果
                        //curuserno = headers.TryGetValue("curuserno", out var no) ? no : "";
                        //curusrpwd = headers.TryGetValue("curusrpwd", out var pwd) ? pwd : "";


                        ContentType = headers.TryGetValue("Content-Type", out var contp) ? contp : "";
                        SourceSystem = headers.TryGetValue("Source-System", out var sous) ? sous : "";
                        TargetSystem = headers.TryGetValue("Target-System", out var tars) ? tars : "";
                        Authorization = headers.TryGetValue("Authorization", out var auth) ? auth : "";

                        curusrpwd = Authorization;





                    }
                }

                tcEAI_C.clsERP.funCheckUser(curuserno, curusrpwd);

            }
            catch (Exception ex)
            {
                throw ex;
            }
            return Json;
        }

        public static string funReceiveReelMaterialByWMS(object parameters)
        {
            string funSendReelMaterialByWMS = default(string);
            string strResult = ""; //返回结果
            string strMsg = ""; //返回信息
            string strKeyValue = "";
            var strException = new List<ArrayList>();  // Exception XML字串
            var strMessage = new List<ArrayList>();    // Message XML字串
            string strResponseJson = "";//传出JOSN
            string strRequestJson = ""; //传入JOSN

            try
            {

                strRequestJson = funCheckJson(parameters);

                // ======================
                // 1.反序列化 JSON
                // ======================
                var result = JsonConvert.DeserializeObject<ReceiveReelMaterialByWMS_Request>(strRequestJson);

                // 定义最终要组装的DataTable
                DataTable dtReel = new DataTable();

                // 先给DataTable创建所有列
                dtReel.Columns.Add("Factory", typeof(string));
                dtReel.Columns.Add("RECEIPTNO", typeof(string));
                dtReel.Columns.Add("RECEIPTLINE", typeof(int));
                dtReel.Columns.Add("STORAGECODE", typeof(string));
                dtReel.Columns.Add("MCODE", typeof(string));
                dtReel.Columns.Add("MNAME", typeof(string));
                dtReel.Columns.Add("REELID", typeof(string));
                dtReel.Columns.Add("DATECODE", typeof(string));
                dtReel.Columns.Add("SNSCALE", typeof(string));
                dtReel.Columns.Add("VENDERDATE", typeof(string));
                dtReel.Columns.Add("VENDORCODE", typeof(string));
                dtReel.Columns.Add("VENDORITEMCODE", typeof(string));
                dtReel.Columns.Add("VENDERLOTNO", typeof(string));
                dtReel.Columns.Add("MANUFACTURER", typeof(string));
                dtReel.Columns.Add("EXDATE", typeof(string));
                dtReel.Columns.Add("QTY", typeof(int));
                dtReel.Columns.Add("USERCODE", typeof(string));
                dtReel.Columns.Add("MDATE", typeof(string));
                dtReel.Columns.Add("MTIME", typeof(string));

                //2.收集数据
                string factory = result.Data?.Factory ?? "";

                // 遍历明细填充DataTable
                if (result.Data.Detail != null && result.Data.Detail.Count > 0)
                {
                    foreach (var item in result.Data.Detail)
                    {
                        // 新建一行
                        DataRow dr = dtReel.NewRow();

                        // 赋值所有字段
                        dr["Factory"] = factory;
                        dr["RECEIPTNO"] = item.RECEIPTNO ?? "";
                        dr["RECEIPTLINE"] = item.RECEIPTLINE;
                        dr["STORAGECODE"] = item.STORAGECODE ?? "";
                        dr["MCODE"] = item.MCODE ?? "";
                        dr["MNAME"] = item.MNAME ?? "";
                        dr["REELID"] = item.REELID ?? "";
                        dr["DATECODE"] = item.DATECODE ?? "";
                        dr["SNSCALE"] = item.SNSCALE ?? "";
                        dr["VENDERDATE"] = item.VENDERDATE ?? "";
                        dr["VENDORCODE"] = item.VENDORCODE ?? "";
                        dr["VENDORITEMCODE"] = item.VENDORITEMCODE ?? "";
                        dr["VENDERLOTNO"] = item.VENDERLOTNO ?? "";
                        dr["MANUFACTURER"] = item.MANUFACTURER ?? "";
                        dr["EXDATE"] = item.EXDATE ?? "";
                        dr["QTY"] = item.QTY;
                        dr["USERCODE"] = item.USERCODE ?? "";
                        dr["MDATE"] = item.MDATE ?? "";
                        dr["MTIME"] = item.MTIME ?? "";

                        // 加入表
                        dtReel.Rows.Add(dr);
                    }
                }

                clsERP.funAddMaterial_WIP(factory, dtReel);

                strResult = "success";



            exitFun:
                ;
            }
            catch (Exception ex)
            {
                strResult = "fail";
                strMsg = ex.Message;
            }
            finally
            {
                //组装返回JOSN
                var resModel = new ReceiveReelMaterialByWMS_Response();



                if (strResult == "success")
                {
                    resModel.result = "1";
                }
                else
                {
                    // 失败逻辑
                    resModel.result = "0";
                    resModel.msg = strMsg;
                }

                //resModel 转成JOSN返回
                strResponseJson = JsonConvert.SerializeObject(resModel);
                funSendReelMaterialByWMS = strResponseJson;

                // 紀錄Transaction Log
                tcEAI_C.clsERP.addTransactionLog_ErrorCode(DateTime.Now.ToString("yyyyMMddHHmmssss"),
                    "INV", "funReceiveReelMaterialByWMS",
                    "WMS", "WMS", DateTime.Now.ToString(),
                    strResult, strKeyValue, strMessage, strException, strRequestJson, strResponseJson, "ReceiveReelMaterialByWMS",
                    Conversions.ToInteger(System.Configuration.ConfigurationManager.AppSettings["keepLog"]),
                    Conversions.ToInteger(System.Configuration.ConfigurationManager.AppSettings["keepXML"]),
                    LogClass: "WMS");
            }

            return funSendReelMaterialByWMS;
        }

        #endregion


        #region "SPC 接收数据"

        /// <summary>
        /// 计量
        /// </summary>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public static string funGetJLSPCData(object parameters)
        {
            string GetJLSPCData = default(string);
            string strResult = ""; //返回结果
            string strMsg = ""; //返回信息
            string strKeyValue = "";
            var strException = new List<ArrayList>();  // Exception XML字串
            var strMessage = new List<ArrayList>();    // Message XML字串
            string strResponseJson = "";//传出JOSN
            string strRequestJson = ""; //传入JOSN

            //调 clsERP 传入参数
            string SPCSerial_QMS = "";
            string MaterialNo = "";
            string MTLVendor = "";
            string Employee = "";
            string LotNo = "";
            string OPNo = "";
            string QCItemNo = "";
            string DC = "";
            string PartNo = "";
            var listTest = new List<decimal>();


            try
            {

                strRequestJson = funCheckJson(parameters);

                // ======================
                // 1.反序列化 JSON
                // ======================
                var result = JsonConvert.DeserializeObject<SPC_GetJLSPCData_Request>(strRequestJson);

                //要因 没有值，则给 * 
                SPCSerial_QMS = GetSafeString(result.SPCSERIAL);
                MaterialNo = GetSafeString(result.MaterialNo);
                MTLVendor = GetSafeString(result.MTLVendor);
                Employee = GetSafeString(result.UserNo);
                LotNo = GetSafeString(result.LOTNO);
                OPNo = GetSafeString(result.OPNO);
                QCItemNo = GetSafeString(result.QCItemNo);
                DC = GetSafeString(result.DC);
                PartNo = GetSafeString(result.PARTNO);

                //实测值，转换成list
                var list = result.TestResults;
                foreach (var item in list)
                {
                    //item.TestValue 防空
                    if (item.TestValue.ToString() != "")
                    {
                        listTest.Add(item.TestValue);
                    }

                }



                clsERP.funGetJLSPCData(ref strMessage, ref strException, SPCSerial_QMS, MaterialNo, MTLVendor, Employee, LotNo, OPNo, QCItemNo, DC, PartNo, listTest);

                strResult = "success";



            exitFun:
                ;
            }
            catch (Exception ex)
            {
                strResult = "fail";
                //翻译
                strMsg = modWS.TranslateMsg(ex.Message);

            }
            finally
            {
                //组装返回JOSN


                SPC_GetJLSPCData_Response response = null;

                if (strResult == "success")
                {
                    response = new SPC_GetJLSPCData_Response
                    {
                        code = 0,
                        message = "成功",
                        success = true,
                        data = null,
                        tradeNo = null,
                        notSuccess = false
                    };
                }
                else
                {
                    // 失败逻辑
                    response = new SPC_GetJLSPCData_Response
                    {
                        code = 1,
                        message = strMsg,
                        success = false,
                        data = null,
                        tradeNo = null,
                        notSuccess = true
                    };
                }

                //resModel 转成JOSN返回
                strResponseJson = JsonConvert.SerializeObject(response);
                GetJLSPCData = strResponseJson;

                // 紀錄Transaction Log
                tcEAI_C.clsERP.addTransactionLog_ErrorCode(DateTime.Now.ToString("yyyyMMddHHmmssss"),
                    "SPC", "funGetJLSPCData",
                    "QMS", "QMS", DateTime.Now.ToString(),
                    strResult, strKeyValue, strMessage, strException, strRequestJson, strResponseJson, "GetJLSPCData",
                    Conversions.ToInteger(System.Configuration.ConfigurationManager.AppSettings["keepLog"]),
                    Conversions.ToInteger(System.Configuration.ConfigurationManager.AppSettings["keepXML"]),
                    LogClass: "QMS");
            }

            return GetJLSPCData;
        }


        /// <summary>
        /// 计数
        /// </summary>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public static string funGetJSSPCData(object parameters)
        {
            string GetJLSPCData = default(string);
            string strResult = ""; //返回结果
            string strMsg = ""; //返回信息
            string strKeyValue = "";
            var strException = new List<ArrayList>();  // Exception XML字串
            var strMessage = new List<ArrayList>();    // Message XML字串
            string strResponseJson = "";//传出JOSN
            string strRequestJson = ""; //传入JOSN

            //调 clsERP 传入参数
            string SPCSerial_QMS = "";
            string MaterialNo = "";
            string MTLVendor = "";
            string Employee = "";
            string LotNo = "";
            string ProDuct = "";
            string EquipMent = "";
            string DC = "";
            string PartNo = "";
            var listTest = new List<decimal>();


            try
            {

                strRequestJson = funCheckJson(parameters);

                // ======================
                // 1.反序列化 JSON
                // ======================
                var result = JsonConvert.DeserializeObject<SPC_GetJSSPCData_Request>(strRequestJson);

                //要因 没有值，则给 * 
                SPCSerial_QMS = GetSafeString(result.SPCSERIAL);
                MaterialNo = GetSafeString(result.MaterialNo);
                MTLVendor = GetSafeString(result.MTLVendor);
                Employee = GetSafeString(result.UserNo);
                LotNo = GetSafeString(result.LOTNO);
                ProDuct = GetSafeString(result.PRODUCT);
                EquipMent = GetSafeString(result.EQUIPMENT);
                DC = GetSafeString(result.DC);
                //PartNo = GetSafeString(result.PARTNO);


                clsERP.funGetJSSPCData(ref strMessage, ref strException, SPCSerial_QMS, MaterialNo, MTLVendor, Employee, LotNo, ProDuct, EquipMent, DC, result.QCItemDetails);




                strResult = "success";



            exitFun:
                ;
            }
            catch (Exception ex)
            {
                strResult = "fail";
                //翻译
                strMsg = modWS.TranslateMsg(ex.Message);

            }
            finally
            {
                //组装返回JOSN


                SPC_GetJSSPCData_Response response = null;

                if (strResult == "success")
                {
                    response = new SPC_GetJSSPCData_Response
                    {
                        code = 0,
                        message = "成功",
                        success = true,
                        data = null,
                        tradeNo = null,
                        notSuccess = false
                    };
                }
                else
                {
                    // 失败逻辑
                    response = new SPC_GetJSSPCData_Response
                    {
                        code = 1,
                        message = strMsg,
                        success = false,
                        data = null,
                        tradeNo = null,
                        notSuccess = true
                    };
                }

                //resModel 转成JOSN返回
                strResponseJson = JsonConvert.SerializeObject(response);
                GetJLSPCData = strResponseJson;

                // 紀錄Transaction Log
                tcEAI_C.clsERP.addTransactionLog_ErrorCode(DateTime.Now.ToString("yyyyMMddHHmmssss"),
                    "SPC", "funGetJSSPCData",
                    "QMS", "QMS", DateTime.Now.ToString(),
                    strResult, strKeyValue, strMessage, strException, strRequestJson, strResponseJson, "GetJSSPCData",
                    Conversions.ToInteger(System.Configuration.ConfigurationManager.AppSettings["keepLog"]),
                    Conversions.ToInteger(System.Configuration.ConfigurationManager.AppSettings["keepXML"]),
                    LogClass: "QMS");
            }

            return GetJLSPCData;
        }


        /// <summary>
        /// 如果字符串为 null 或空字符串，返回默认值（默认*），否则返回原值
        /// </summary>
        /// <param name="value">要判断的字段</param>
        /// <param name="defaultValue">为空时替换的值，默认*</param>
        /// <returns></returns>
        public static string GetSafeString(string value, string defaultValue = "*")
        {
            return string.IsNullOrEmpty(value) ? defaultValue : value;
        }
        #endregion


        #region "工单砍单、取消卡控接口"
        public static string funCheckMONoCanEditCancel(object parameters)
        {
            string funCheckMONoCanEditCancel = default(string);
            string strResult = ""; //返回结果
            string strMsg = ""; //返回信息
            string strKeyValue = "";
            var strException = new List<ArrayList>();  // Exception XML字串
            var strMessage = new List<ArrayList>();    // Message XML字串
            string strResponseJson = "";//传出JOSN
            string strRequestJson = ""; //传入JOSN



            decimal decQuantity = 0; //数量
            int intStatus = 0; //状态

            decimal InputQty = 0;//工单投入
            decimal OutputQty = 0;//工单产出
            string CurrentStatus = defString;//当前状态

            bool bolclsERP = false; //调用clsERP方法是否成功

            try
            {

                strRequestJson = funCheckJson(parameters);

                // ======================
                // 1.反序列化 JSON
                // ======================
                var result = JsonConvert.DeserializeObject<ERP_CheckMONoCanEditCancel_Request>(strRequestJson);


                //检查 result.MONO 是否为空
                if (string.IsNullOrEmpty(result.MONo))
                {
                    throw new Exception("MONO不能为空");
                }

                //检查数据 result.Quantity 和 result.Status  如果不是数值型，则提示
                if (!decimal.TryParse(result.Quantity.ToString(), out decQuantity))
                {
                    throw new Exception("Quantity必须是数值型");

                }

                if (!int.TryParse(result.Status.ToString(), out intStatus))
                {
                    throw new Exception("Status必须是数值型");

                }

                //intStatus 只能是0和1
                if (intStatus != 0 && intStatus != 1)
                {
                    throw new Exception("Status必须是0或1");
                }



                bolclsERP = clsERP.funCheckMONoCanEditCancel_M(ref strMessage, ref strException, ref InputQty, ref OutputQty, ref CurrentStatus, result.MONo, decQuantity, intStatus);
                if (bolclsERP == false)
                {
                    //说明有提示
                    modWS.ChgTranslateMessage(ref strMessage, ref strMsg);
                    throw new Exception(strMsg);
                }

                strResult = "success";



            exitFun:
                ;
            }
            catch (Exception ex)
            {
                strResult = "fail";
                //翻译
                strMsg = modWS.TranslateMsg(ex.Message);

            }
            finally
            {
                //组装返回JOSN


                ERP_CheckMONoCanEditCancel_Response response = null;

                if (strResult == "success")
                {
                    response = new ERP_CheckMONoCanEditCancel_Response
                    {
                        code = 200,
                        message = "check successfully",
                        data = new ERP_MOData
                        {
                            InputQty = InputQty,
                            OutputQty = OutputQty,
                            CurrentStatus = CurrentStatus,
                            Rusult = "PASS"
                        },
                        requestId = ""
                    };
                }
                else
                {
                    // 失败逻辑
                    response = new ERP_CheckMONoCanEditCancel_Response
                    {
                        code = 500,
                        message = strMsg,
                        data = null  // 序列化后不显示data字段
                    };
                }

                //resModel 转成JOSN返回
                strResponseJson = JsonConvert.SerializeObject(response);
                funCheckMONoCanEditCancel = strResponseJson;

                // 紀錄Transaction Log
                tcEAI_C.clsERP.addTransactionLog_ErrorCode(DateTime.Now.ToString("yyyyMMddHHmmssss"),
                    "OE", "funCheckMONoCanEditCancel",
                    "ERP", "ERP", DateTime.Now.ToString(),
                    strResult, strKeyValue, strMessage, strException, strRequestJson, strResponseJson, "CheckMONoCanEditCancel",
                    Conversions.ToInteger(System.Configuration.ConfigurationManager.AppSettings["keepLog"]),
                    Conversions.ToInteger(System.Configuration.ConfigurationManager.AppSettings["keepXML"]),
                    LogClass: "ERP");
            }

            return funCheckMONoCanEditCancel;
        }
        #endregion


        #region"Materialhold"
        public static string Materialhold(object parameters)
        {
            string GetJLSPCData = default(string);
            string strResult = ""; //返回结果
            string strMsg = ""; //返回信息
            string strKeyValue = "";
            var strException = new List<ArrayList>();  // Exception XML字串
            var strMessage = new List<ArrayList>();    // Message XML字串
            string strResponseJson = "";//传出JOSN
            string strRequestJson = ""; //传入JOSN

            //调 clsERP 传入参数
            string source = "";
            string materialno = "";
            string materiallotno = "";
            string holdstate = "";
            string creator = "";
            string date = "";
            string reasonno = "ERPhold";
            var listTest = new List<decimal>();
            int REVERSALMETHOD = -1;
            try
            {

                strRequestJson = funCheckJson(parameters);

                // ======================
                // 1.反序列化 JSON
                // ======================
                var result = JsonConvert.DeserializeObject<MaterialHoldRequest>(strRequestJson);

                //要因 没有值，则给 * 
                source = GetSafeString(result.source);
                materialno = GetSafeString(result.materialno);
                materiallotno = GetSafeString(result.materiallotno);
                holdstate = GetSafeString(result.holdstate);
                creator = GetSafeString(result.creator);
                date = GetSafeString(result.date);
                reasonno = GetSafeString(result.reasonno);
                if (reasonno == "*")
                {
                    reasonno = "ERPhold";
                }
                bool bolclsERP = clsERP.funGetMaterialhold(ref strMessage, ref strException, source, materialno, materiallotno, holdstate, creator, date, reasonno);

                if (bolclsERP == true)
                {
                    strResult = "success";
                }
                else
                {
                    strResult = "fail";
                }
            }
            catch (Exception ex)
            {
                strResult = "fail";
                //翻译
                strMsg = modWS.TranslateMsg(ex.Message);

            }
            finally
            {
                //组装返回JOSN


                MaterialHoldResponse response = null;

                if (strResult == "success")
                {

                    response = new MaterialHoldResponse
                    {
                        result = true,
                        msg = ""
                    };
                }
                else
                {
                    MaterialHoldError error = new MaterialHoldError();
                    error.code = "RMQ-01-00-0001";
                    error.message = strMsg;
                    // 失败逻辑
                    response = new MaterialHoldResponse
                    {
                        result = false,
                        msg = strMsg,
                        error = error
                    };
                }

                //resModel 转成JOSN返回
                strResponseJson = JsonConvert.SerializeObject(response);
                GetJLSPCData = strResponseJson;

                // 紀錄Transaction Log
                tcEAI_C.clsERP.addTransactionLog_ErrorCode(DateTime.Now.ToString("yyyyMMddHHmmssss"),
                    "WIP", "Materialhold",
                    "ERP", "ERP", DateTime.Now.ToString(),
                    strResult, strKeyValue, strMessage, strException, strRequestJson, strResponseJson, "Materialhold",
                    Conversions.ToInteger(System.Configuration.ConfigurationManager.AppSettings["keepLog"]),
                    Conversions.ToInteger(System.Configuration.ConfigurationManager.AppSettings["keepXML"]),
                    LogClass: "ERP");
            }

            return GetJLSPCData;
        }

        #endregion

        #region"工单bom"
        /// <summary>
        /// 计量
        /// </summary>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public static string PrdBomList(object parameters)
        {
            string GetJLSPCData = default(string);
            string strResult = ""; //返回结果
            string strMsg = ""; //返回信息
            string strKeyValue = "";
            var strException = new List<ArrayList>();  // Exception XML字串
            var strMessage = new List<ArrayList>();    // Message XML字串
            string strResponseJson = "";//传出JOSN
            string strRequestJson = ""; //传入JOSN

            //调 clsERP 传入参数
            string Productid = "";
            string ProductVersion = "";

            var listTest = new List<decimal>();
            int REVERSALMETHOD = -1;
            try
            {

                strRequestJson = funCheckJson(parameters);

                // ======================
                // 1.反序列化 JSON
                // ======================
                var result = JsonConvert.DeserializeObject<BomRequest>(strRequestJson);

                //要因 没有值，则给 * 
                Productid = GetSafeString(result.PRODUCTNO);
                ProductVersion = GetSafeString(result.PRODUCTVERSION);

                if (Productid == "*")
                {
                    throw new Exception("未传产品信息！");
                }
                if (ProductVersion == "*")
                {
                    throw new Exception("未传产品版本信息！");
                }
                if (result.Bomlist.Count == 0)
                {
                    throw new Exception("未传产品Bom信息！");
                }

                bool bolclsERP = clsERP.GetProdBOMInfo(ref strMessage, ref strException, Productid, ProductVersion, result);

                if (bolclsERP == true)
                {
                    strResult = "success";
                }
                else
                {
                    strResult = "fail";
                }
            }
            catch (Exception ex)
            {
                strResult = "fail";
                //翻译
                strMsg = modWS.TranslateMsg(ex.Message);

            }
            finally
            {
                //组装返回JOSN


                MappingResponse response = null;

                if (strResult == "success")
                {

                    response = new MappingResponse
                    {
                        code = "0000",
                        message = "success",
                        time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                        data = null,
                        extras = null,
                        logId = "",
                        requestId = DateTime.Now.ToString("yyyyMMddHHmmssss")
                    };
                }
                else
                {
                    // 失败逻辑
                    response = new MappingResponse
                    {
                        code = "1111",
                        message = strMsg,
                        time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                        data = null,
                        extras = null,
                        logId = "",
                        requestId = DateTime.Now.ToString("yyyyMMddHHmmssss")
                    };
                }

                //resModel 转成JOSN返回
                strResponseJson = JsonConvert.SerializeObject(response);
                GetJLSPCData = strResponseJson;

                // 紀錄Transaction Log
                tcEAI_C.clsERP.addTransactionLog_ErrorCode(DateTime.Now.ToString("yyyyMMddHHmmssss"),
                    "WIP", "PrdBomList",
                    "ERP", "ERP", DateTime.Now.ToString(),
                    strResult, strKeyValue, strMessage, strException, strRequestJson, strResponseJson, "PrdBomList",
                    Conversions.ToInteger(System.Configuration.ConfigurationManager.AppSettings["keepLog"]),
                    Conversions.ToInteger(System.Configuration.ConfigurationManager.AppSettings["keepXML"]),
                    LogClass: "ERP");
            }

            return GetJLSPCData;
        }


        #endregion

        #region"钢片绑定"
        /// <summary>
        /// 钢片绑定接口：根据设备编号查询批号，绑定钢片
        /// </summary>
        public static string CarrierTackIn(object parameters)
        {
            string GetJLSPCData = default(string);
            string strResult = "";
            string strMsg = "";
            string strKeyValue = "";
            var strException = new List<ArrayList>();
            var strMessage = new List<ArrayList>();
            string strResponseJson = "";
            string strRequestJson = "";

            string equipmentno = "";
            string steelno = "";
            string carrierno = "";
            string lotno = "";

            try
            {
                strRequestJson = funCheckJson(parameters);

                var result = JsonConvert.DeserializeObject<SteelBindRequest>(strRequestJson);
                equipmentno = GetSafeString(result.equipmentno);
                steelno = GetSafeString(result.steelno);
                carrierno = GetSafeString(result.carrierno);

                // 校验参数
                if (string.IsNullOrEmpty(equipmentno))
                {
                    throw new Exception("设备编号不能为空");
                }
                if (string.IsNullOrEmpty(steelno))
                {
                    throw new Exception("钢片编号不能为空");
                }
                if (string.IsNullOrEmpty(carrierno))
                {
                    throw new Exception("料盒不能为空");
                }

                bool bolResult = clsERP.funSteelBind(ref strMessage, ref strException, equipmentno, steelno, carrierno, ref lotno);

                if (bolResult)
                {
                   
                }
                else
                {
                    strResult = "fail";
                    if (strException.Count > 0 && strException[0].Count > 1)
                    {
                        strMsg = strException[0][1].ToString();
                    }
                }
                bool bolclsEAP = clsEAP.funTrackIn_InquirybyLot(ref strMessage, ref strException, carrierno, equipmentno);
                if (bolclsEAP == false)
                {
                    //说明有提示
                    modWS.ChgTranslateMessage(ref strMessage, ref strMsg);
                    throw new Exception(strMsg);
                }
                strResult = "success";

            }
            catch (Exception ex)
            {
                strResult = "fail";
                strMsg = modWS.TranslateMsg(ex.Message);
            }
            finally
            {
                SteelBindResponse response = null;
                if (strResult == "success")
                {
                    response = new SteelBindResponse
                    {
                        code = "0000",
                        data = new SteelBindData
                        {
                            message = "成功",
                            lotno = lotno,
                            steelno = steelno
                        },
                        extras = null,
                        message = "成功",
                        time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                        logId = "",
                        requestId = DateTime.Now.ToString("yyyyMMddHHmmssss")
                    };
                }
                else
                {
                    response = new SteelBindResponse
                    {
                        code = "1111",
                        data = null,
                        extras = null,
                        message = "进站失败，" + strMsg,
                        time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                        logId = "",
                        requestId = DateTime.Now.ToString("yyyyMMddHHmmssss")
                    };
                }

                strResponseJson = JsonConvert.SerializeObject(response);
                GetJLSPCData = strResponseJson;

                tcEAI_C.clsERP.addTransactionLog_ErrorCode(DateTime.Now.ToString("yyyyMMddHHmmssss"),
                    "WIP", "CarrierTackIn",
                    "ERP", "ERP", DateTime.Now.ToString(),
                    strResult, strKeyValue, strMessage, strException, strRequestJson, strResponseJson, "CarrierTackIn",
                    Conversions.ToInteger(System.Configuration.ConfigurationManager.AppSettings["keepLog"]),
                    Conversions.ToInteger(System.Configuration.ConfigurationManager.AppSettings["keepXML"]),
                    LogClass: "ERP");
            }

            return GetJLSPCData;
        }
        #endregion





        #region Reel校验接口
        //public static string CheckReelQty(string jsonInput)
        //{
        //    JObject response = new JObject();
        //    try
        //    {
        //        JObject requestJson = JObject.Parse(jsonInput);
        //        string factory = (string)requestJson["Data"]?["Factory"];
        //        string reelId = (string)requestJson["Data"]?["Detail"]?["REELID"];
        //        string qty = (string)requestJson["Data"]?["Detail"]?["QTY"];
        //        bool isSuccess = true;

        //        if (isSuccess)
        //        {
        //            response["result"] = 1;
        //            response["qty"] = qty;
        //            response["mcode"] = "111";
        //            response["vendorcode"] = "123456";
        //            response["vendordate"] = "20240512";
        //            response["manufacturer"] = "龙旗";
        //            response["vendorlotno"] = "123";
        //            response["oraFacReel"] = "12";
        //            response["snscale"] = "09";
        //            response["mpn"] = "";
        //            response["produceArea"] = "";
        //            response["cnum"] = 0;
        //            response["msg"] = null;
        //        }
        //        else
        //        {
        //            response["result"] = 0;
        //            response["msg"] = $"未找到该料卷{reelId}";
        //            response["qty"] = "";
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        response["result"] = 0;
        //        response["msg"] = "解析异常或系统错误: " + ex.Message;
        //        response["qty"] = "";

        //        // 此处可以加上你原来的记录 Log 的代码
        //    }

        //    return response.ToString(Newtonsoft.Json.Formatting.None );
        //}

        public static string CheckReelQty(object parameters)
        {
            JObject response = new JObject();
            string strResult = "fail"; //返回结果
            string strKeyValue = "";
            var strException = new List<ArrayList>();  // Exception XML字串
            var strMessage = new List<ArrayList>();    // Message XML字串
            string strResponseJson = "";//传出JOSN
            string strRequestJson = ""; //传入JOSN
            try
            {
                //取得报文，并校验接口规范的Header四参数（Content-Type／Source-System／Target-System／Authorization）
                strRequestJson = funCheckJson(parameters);

                JObject requestJson = JObject.Parse(strRequestJson);
                string factory = requestJson["Data"]?["Factory"]?.ToString();
                string reelId = requestJson["Data"]?["Detail"]?["REELID"]?.ToString();
                string qty = requestJson["Data"]?["Detail"]?["QTY"]?.ToString();
                string STORAGECODE = requestJson["Data"]?["Detail"]?["STORAGECODE"]?.ToString();

                if (string.IsNullOrEmpty(reelId))
                {
                    throw new Exception("[%料卷唯一码必须传入!%]");
                }
                strKeyValue = reelId;

                bool isSuccess = false;
                string mcode = "";
                string qty1 = "";
                string vendordate = "";
                string vendorcode = "";
                string manufacturer = "";
                string vendorlotno = "";
                string snscale = "";
                bool everExisted = false;
                isSuccess = clsERP.CheckReelQty(ref strMessage, ref strException, reelId, STORAGECODE ?? "", ref mcode, ref qty1, ref vendordate, ref vendorcode, ref manufacturer, ref vendorlotno, ref snscale, ref everExisted);
                if (isSuccess)
                {
                    response["result"] = 1;
                    response["qty"] = qty1;
                    response["mcode"] = mcode;
                    //供应商编码、生产厂家、供应商批次、09条码四栏，取自线边仓表对应栏位
                    response["vendorcode"] = vendorcode;
                    response["vendordate"] = vendordate;
                    response["manufacturer"] = manufacturer;
                    response["vendorlotno"] = vendorlotno;
                    response["oraFacReel"] = reelId;
                    response["snscale"] = snscale;
                    //MPN、产地两栏线边仓表无对应栏位、WMS进料报文亦未带入，
                    //本次维持回空值，俟数据来源确认后另案补做取数
                    response["mpn"] = "";
                    response["produceArea"] = "";
                    response["cnum"] = 0;
                    response["msg"] = null;
                    strResult = "success";
                }
                else
                {
                    response["result"] = 0;
                    //区分「料卷已扣光」与「卷号根本不存在」，此两者现场处理方式不同
                    if (everExisted)
                    {
                        response["msg"] = $"料卷{reelId}已扣光";
                    }
                    else
                    {
                        response["msg"] = $"未找到该料卷{reelId}";
                    }
                    response["qty"] = "";
                    strResult = "fail";
                }
            }
            catch (Exception ex)
            {
                response["result"] = 0;
                response["msg"] = "数据解析异常或系统错误: " + ex.Message;
                response["qty"] = "";
                strResult = "fail";
            }
            finally
            {
                strResponseJson = response.ToString(Newtonsoft.Json.Formatting.None);

                // 紀錄Transaction Log
                tcEAI_C.clsERP.addTransactionLog_ErrorCode(DateTime.Now.ToString("yyyyMMddHHmmssss"),
                    "INV", "CheckReelQty",
                    "WMS", "WMS", DateTime.Now.ToString(),
                    strResult, strKeyValue, strMessage, strException, strRequestJson, strResponseJson, "CheckReelQty",
                    Conversions.ToInteger(System.Configuration.ConfigurationManager.AppSettings["keepLog"]),
                    Conversions.ToInteger(System.Configuration.ConfigurationManager.AppSettings["keepXML"]),
                    LogClass: "WMS");
            }

            return strResponseJson;
        }
        #endregion


        #region "WMS退料，扣减线边仓料卷数量"
        public static string ReelReturn(object parameters)
        {
            string ReelReturn = default(string);
            string strResult = ""; //返回结果
            string strMsg = ""; //返回信息
            string strKeyValue = "";
            var strException = new List<ArrayList>();  // Exception XML字串
            var strMessage = new List<ArrayList>();    // Message XML字串
            string strResponseJson = "";//传出JOSN
            string strRequestJson = ""; //传入JOSN

            try
            {
                //取得报文，并校验接口规范的Header四参数（Content-Type／Source-System／Target-System／Authorization）
                strRequestJson = funCheckJson(parameters);

                // ======================
                // 1.反序列化 JSON
                // ======================
                var result = JsonConvert.DeserializeObject<ReelReturn_Request>(strRequestJson);

                if (result.Data == null || result.Data.Detail == null)
                {
                    throw new Exception("[%无明细数据!%]");
                }

                var detail = result.Data.Detail;

                string mvdCode = detail.MVDCODE ?? "";
                string moCode = detail.MOCODE ?? "";
                string fromStorage = detail.FROMSTORAGE ?? "";
                string toStorage = detail.TOSTORAGE ?? "";
                string userCode = detail.USERCODE ?? "";
                string mDate = detail.MDATE ?? "";
                string mTime = detail.MTIME ?? "";

                if (mvdCode == "" || fromStorage == "")
                {
                    throw new Exception("[%退料单号,供应仓都必须传入!%]");
                }
                strKeyValue = mvdCode;

                if (detail.REELINFO == null || detail.REELINFO.Count == 0)
                {
                    throw new Exception("[%料卷信息必须传入!%]");
                }

                // 定义最终要组装的DataTable
                DataTable dtReelInfo = new DataTable();

                // 先给DataTable创建所有列
                dtReelInfo.Columns.Add("REELID", typeof(string));
                dtReelInfo.Columns.Add("MCODE", typeof(string));
                dtReelInfo.Columns.Add("QTY", typeof(string));

                //2.收集数据：依REELINFO逐笔扣减，MLIST仅为汇总不参与扣减
                foreach (var item in detail.REELINFO)
                {
                    // 新建一行
                    DataRow dr = dtReelInfo.NewRow();

                    // 赋值所有字段
                    dr["REELID"] = item.REELID ?? "";
                    dr["MCODE"] = item.MCODE ?? "";
                    dr["QTY"] = item.QTY ?? "";

                    // 加入表
                    dtReelInfo.Rows.Add(dr);
                }

                bool bolclsERP = false;
                bolclsERP = clsERP.ReelReturn(ref strMessage, ref strException, mvdCode, moCode, fromStorage, toStorage, userCode, mDate, mTime, dtReelInfo);
                if (bolclsERP == false)
                {
                    //说明有提示
                    modWS.ChgTranslateMessage(ref strMessage, ref strMsg);
                    throw new Exception(strMsg);
                }

                strResult = "success";



            exitFun:
                ;
            }
            catch (Exception ex)
            {
                strResult = "fail";
                strMsg = ex.Message;
            }
            finally
            {
                //组装返回JOSN
                var resModel = new ReelReturn_Response();

                if (strResult == "success")
                {
                    resModel.result = "1";
                }
                else
                {
                    // 失败逻辑
                    resModel.result = "0";
                    resModel.msg = strMsg;
                }

                //resModel 转成JOSN返回
                strResponseJson = JsonConvert.SerializeObject(resModel);
                ReelReturn = strResponseJson;

                // 紀錄Transaction Log
                tcEAI_C.clsERP.addTransactionLog_ErrorCode(DateTime.Now.ToString("yyyyMMddHHmmssss"),
                    "INV", "ReelReturn",
                    "WMS", "WMS", DateTime.Now.ToString(),
                    strResult, strKeyValue, strMessage, strException, strRequestJson, strResponseJson, "ReelReturn",
                    Conversions.ToInteger(System.Configuration.ConfigurationManager.AppSettings["keepLog"]),
                    Conversions.ToInteger(System.Configuration.ConfigurationManager.AppSettings["keepXML"]),
                    LogClass: "WMS");
            }

            return ReelReturn;
        }

        #endregion

    }

}
