using ICSSoft.Common;
using ICSSoft.Entity;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace ICSSoft.DataProject
{
    /// <summary>
    /// 使用中
    /// 生产模块
    /// </summary>
    public class ICSManufactureService
    {
        private static log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        #region 生产发料
        /// <summary>
        /// 生产发料
        /// </summary>
        /// <param name="TransCode"></param>
        /// <param name="TransSequence"></param>
        /// <param name="Quantity"></param>
        /// <param name="WorkPoint"></param>
        /// <param name="cmd"></param>
        public static void MOIssueDoc(string TransCode, string TransSequence, string Quantity, string WorkPoint, SqlCommand cmd, Dictionary<string, string> language)
        {
            try
            {
                string sql = @"DECLARE @Status VARCHAR(10)
                                SELECT @Status=b.ERPStatus FROM ICSMOPick  a
                                INNER JOIN ICSMO b ON  a.MODetailID=b.MODetailID AND a.WorkPoint=b.WorkPoint
                                WHERE b.MOCode='{0}' AND b.Sequence+'~'+a.Sequence='{3}' AND a.WorkPoint='{1}'

                                IF (@Status IS NULL)
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo125") + @"',16,1);
                                    RETURN
                                END
                                ELSE IF (@Status!='2')
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo126") + @"',16,1);
                                    RETURN
                                END
                                UPDATE a SET IssueQuantity=ISNULL(IssueQuantity,0)+'{2}'
                                FROM ICSMOPick  a
                                INNER JOIN ICSMO b ON  a.MODetailID=b.MODetailID AND a.WorkPoint=b.WorkPoint
                                WHERE b.MOCode='{0}' AND b.Sequence+'~'+a.Sequence='{3}' AND a.WorkPoint='{1}'

                                IF EXISTS(SELECT a.ID FROM ICSMOPick  a
	                                INNER JOIN ICSMO b ON  a.MODetailID=b.MODetailID AND a.WorkPoint=b.WorkPoint
	                                WHERE b.MOCode='{0}' AND b.Sequence+'~'+a.Sequence='{3}' and a.WorkPoint='{1}' AND a.Quantity<a.IssueQuantity)
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo091") + @"',16,1);
                                    RETURN
                                END";

                sql = string.Format(sql, TransCode, WorkPoint, Quantity, TransSequence);

                if (!DBHelper.ExecuteNonQuery(sql, cmd))
                {
                    throw new Exception(language.GetNameByCode("WMSAPIInfo127"));//"生产领料单更新失败!");
                }
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 生产发料接口
        /// </summary>
        /// <param name="TransType"></param>
        /// <param name="Identification"></param>
        /// <param name="cmd"></param>
        public static void MOIssueDocERP(string TransType, string Identification, SqlCommand cmd, Dictionary<string, string> language, string BusinessCode)
        {
            try
            {
                #region ERP
                string sql = @"SELECT y.DepCode+a.FromWarehouseCode+y.MOCode+a.MUSER AS Costre,y.DepCode,a.FromWarehouseCode AS WarehouseCode,y.MOCode,a.MUSER,ROW_NUMBER() OVER (ORDER BY y.DepCode,a.FromWarehouseCode,y.MOCode,x.PickID,a.InvCode) AS Sequence,
	                            a.InvCode,SUM(a.Quantity) AS Quantity,SUM(a.Quantity*(x.Amount/x.Quantity)) AS Amount,x.PickID,con.Enable AS UpdateTodoQuantity
	                            ,a.WorkPoint,ISNULL(ext.ProjectCode, '') AS ProjectCode,CASE WHEN (invBat.BatchEnable IS NULL AND ISNULL(inv.BatchEnable, '0')='1') OR ISNULL(invBat.BatchEnable, '0')='1' THEN ISNULL(ext.BatchCode, '') ELSE '' END AS BatchCode,ISNULL(ext.Version, '') AS Version,ISNULL(ext.Brand, '') AS Brand,
	                            ISNULL(ext.cFree1, '') AS cFree1,ISNULL(ext.cFree2, '') AS cFree2,ISNULL(ext.cFree3, '') AS cFree3,ISNULL(ext.cFree4, '') AS cFree4,ISNULL(ext.cFree5, '') AS cFree5,ISNULL(ext.cFree6, '') AS cFree6,ISNULL(ext.cFree7, '') AS cFree7,ISNULL(ext.cFree8, '') AS cFree8,ISNULL(ext.cFree9, '') AS cFree9,ISNULL(ext.cFree10, '') AS cFree10,conv.Enable AS CompleteVerification                                   
                            INTO #TempERP
                            FROM ICSWareHouseLotInfoLog a
                            INNER JOIN ICSInventoryLot lot ON a.LotNo=lot.LotNo AND a.WorkPoint=lot.WorkPoint
                            INNER JOIN ICSExtension ext ON lot.ExtensionID=ext.ID AND lot.WorkPoint=ext.WorkPoint
                            INNER JOIN ICSInventory inv ON a.InvCode=inv.InvCode AND a.WorkPoint=inv.WorkPoint
                            LEFT JOIN ICSInventoryBatchEnable invBat ON a.InvCode=invBat.InvCode AND a.FromWarehouseCode=invBat.WHCode AND a.WorkPoint=invBat.WorkPoint
                            INNER JOIN ICSMO y ON a.TransCode=y.MOCode AND a.WorkPoint=y.WorkPoint
                            INNER JOIN ICSMOPick x ON x.MODetailID=y.MODetailID AND a.TransSequence=y.Sequence+'~'+x.Sequence AND x.WorkPoint=y.WorkPoint
                            INNER JOIN ICSConfiguration con ON con.Code='Stock002' AND a.WorkPoint=con.WorkPoint
                            INNER JOIN ICSConfiguration conv ON conv.Code='CompleteVerification' AND a.WorkPoint=conv.WorkPoint
                            WHERE a.Identification='{0}' AND  ERPUpload='0' AND a.BusinessCode = '13' 
                            GROUP BY y.DepCode,a.FromWarehouseCode,y.MOCode,a.MUSER,a.InvCode,x.PickID,x.MODetailID,con.Enable,conv.Enable
                                ,a.WorkPoint,ISNULL(ext.ProjectCode, ''),CASE WHEN (invBat.BatchEnable IS NULL AND ISNULL(inv.BatchEnable, '0')='1') OR ISNULL(invBat.BatchEnable, '0')='1' THEN ISNULL(ext.BatchCode, '') ELSE '' END,ISNULL(ext.Version, ''),ISNULL(ext.Brand, ''),
                                ISNULL(ext.cFree1, ''),ISNULL(ext.cFree2, ''),ISNULL(ext.cFree3, ''),ISNULL(ext.cFree4, ''),ISNULL(ext.cFree5, ''),ISNULL(ext.cFree6, ''),ISNULL(ext.cFree7, ''),ISNULL(ext.cFree8, ''),ISNULL(ext.cFree9, ''),ISNULL(ext.cFree10, '')

                            SELECT DISTINCT Costre,WorkPoint,DepCode,WarehouseCode AS WHCode,'生产订单' AS SourceType,MOCode AS SourceCode,MUSER AS [User],SYSDATETIME() AS MTime,UpdateTodoQuantity,CompleteVerification FROM #TempERP
                            SELECT Costre,Sequence,InvCode,Quantity,Amount,PickID AS SourceDetailID,ProjectCode,BatchCode,Version,Brand,cFree1,cFree2,cFree3,cFree4,cFree5,cFree6,cFree7,cFree8,cFree9,cFree10 FROM #TempERP

                            DROP TABLE #TempERP";
                sql = string.Format(sql, Identification);
                DataSet ds = DBHelper.SQlReturnDataSet(sql, cmd);

                string Inputstr = DataToJsonHelper.DataSetToJson(ds, "details", "Costre");
                string resultStr = HTTPHelper.HttpPost(TransType, ERPUrl.MOIssueDocURL, Inputstr);
                Result result = new Result();
                result = JsonConvert.DeserializeObject<Result>(resultStr);
                if (result.Success)
                {
                    try
                    {
                        JArray res = (JArray)JsonConvert.DeserializeObject(result.Data.ToString());
                        foreach (var item in res)
                        {
                            JObject jo = (JObject)item;
                            JArray resdetail = (JArray)JsonConvert.DeserializeObject(jo["details"].ToString());
                            foreach (var detail in resdetail)
                            {
                                JObject det = (JObject)detail;
                                string allcol = jo["cWhCode"].ToString() + det["ProjectCode"].ToString() + det["cBatch"].ToString() + det["version"].ToString() + det["brand"].ToString() + det["cFree1"].ToString() + det["cFree2"].ToString() + det["cFree3"].ToString() + det["cFree4"].ToString() + det["cFree5"].ToString()
                                    + det["cFree6"].ToString() + det["cFree7"].ToString() + det["cFree8"].ToString() + det["cFree9"].ToString() + det["cFree10"].ToString();
                                ICSWareHouseLotInfoService.WareHouseLotInfoLogUpdate(TransType, det["SourceDetailID"].ToString(), Identification, jo["ID"].ToString(),
                                    det["DetailID"].ToString(), jo["IssueCode"].ToString(), det["Sequence"].ToString(), allcol, cmd, language, BusinessCode);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        log.Debug(ex.ToString());
                        log.Debug(resultStr);
                    }
                }
                else
                {
                    throw new Exception(language.GetNameByCode("WMSAPIInfo080") + result.Message);
                }
                #endregion
            }
            catch (Exception)
            {
                throw;
            }
        }
        #endregion

        #region 领料申请单生产发料(不扫描条码)
        /// <summary>
        /// 领料申请单生产发料
        /// </summary>
        /// <param name="TransCode"></param>
        /// <param name="TransSequence"></param>
        /// <param name="Quantity"></param>
        /// <param name="WorkPoint"></param>
        /// <param name="cmd"></param>
        public static void MOApplyWithOutLot(string TransCode, string WorkPoint, SqlCommand cmd, Dictionary<string, string> language)
        {
            try
            {
                string sql = @"IF (Select SUM(IssueQuantity) from ICSMOApply WHERE ApplyCode='{0}' AND WorkPoint='{1}'
								GROUP BY ApplyCode)>0
                                BEGIN
	                                RAISERROR('源头单据:{0} 已经领料,无法再次领料!',16,1)
                                    RETURN
                                END
                                UPDATE a SET IssueQuantity=Quantity
                                FROM ICSMOApply  a
                                WHERE a.ApplyCode='{0}' AND a.WorkPoint='{1}'";

                sql = string.Format(sql, TransCode, WorkPoint);

                if (!DBHelper.ExecuteNonQuery(sql, cmd))
                {
                    throw new Exception(language.GetNameByCode("WMSAPIInfo130"));//"领料申请单更新失败!");
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
        #endregion

        #region 领料申请单生产发料
        /// <summary>
        /// 领料申请单生产发料
        /// </summary>
        /// <param name="TransCode"></param>
        /// <param name="TransSequence"></param>
        /// <param name="Quantity"></param>
        /// <param name="WorkPoint"></param>
        /// <param name="cmd"></param>
        public static void MOApply(string TransCode, string TransSequence, string Quantity, string WorkPoint, SqlCommand cmd, Dictionary<string, string> language)
        {
            try
            {
                string sql = @"DECLARE @Status VARCHAR(10)
                                SELECT @Status=a.Status FROM ICSMOApply  a
                                WHERE a.ApplyCode='{0}' AND a.Sequence='{3}' AND a.WorkPoint='{1}'

                                IF (@Status IS NULL)
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo128") + @"',16,1);
                                    RETURN
                                END
                                ELSE IF (@Status!='2')
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo129") + @"',16,1);
                                    RETURN
                                END
                                UPDATE a SET IssueQuantity=ISNULL(IssueQuantity,0)+'{2}'
                                FROM ICSMOApply  a
                                WHERE a.ApplyCode='{0}' AND a.Sequence='{3}' AND a.WorkPoint='{1}'

                                IF EXISTS(SELECT a.ID FROM ICSMOApply  a
	                                WHERE a.ApplyCode='{0}' AND a.Sequence='{3}' and a.WorkPoint='{1}' AND a.Quantity<a.IssueQuantity)
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo091") + @"',16,1);
                                    RETURN
                                END";

                sql = string.Format(sql, TransCode, WorkPoint, Quantity, TransSequence);

                if (!DBHelper.ExecuteNonQuery(sql, cmd))
                {
                    throw new Exception(language.GetNameByCode("WMSAPIInfo130"));//"领料申请单更新失败!");
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
        /// <summary>
        /// 领料申请单生产发料(货柜)
        /// </summary>
        /// <param name="TransCode"></param>
        /// <param name="TransSequence"></param>
        /// <param name="Quantity"></param>
        /// <param name="WorkPoint"></param>
        /// <param name="cmd"></param>
        public static void MOApplyHG(string TransCode, string WorkPoint, SqlCommand cmd, Dictionary<string, string> language)
        {
            try
            {
               
                string sql = @"IF EXISTS (SELECT ID FROM ICSMOApply WHERE IssueQuantity=Quantity AND  ApplyCode='{0}' and WorkPoint='{1}' )
                               BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo472") + @"',16,1);
                                    RETURN
                                END;
                              UPDATE ICSMOApply set IssueQuantity=Quantity
	                           WHERE ApplyCode='{0}' and WorkPoint='{1}'";

                sql = string.Format(sql, TransCode, WorkPoint);

                if (!DBHelper.ExecuteNonQuery(sql, cmd))
                {
                    throw new Exception(language.GetNameByCode("WMSAPIInfo130"));//"领料申请单更新失败!");
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
        /// <summary>
        /// 领料申请单发料确认(记录发料人员)
        /// </summary>
        /// <param name="TransCode"></param>
        /// <param name="TransSequence"></param>
        /// <param name="Quantity"></param>
        /// <param name="WorkPoint"></param>
        /// <param name="cmd"></param>
        /// <param name="language"></param>
        public static void MOApplySaveUser(string TransCode, string MuserName, string WorkPoint, SqlCommand cmd, Dictionary<string, string> language)
        {
            try
            {
                string chksql = @"select ISNULL(SUM(ISNULL(Quantity,0)),0) AS Quantity,ISNULL(SUM(ISNULL(IssueQuantity,0)),0) AS IssueQuantity from ICSMOApply
                                  where ApplyCode='{0}' AND WorkPoint='{1}'
                                  GROUP BY ApplyCode";
                chksql = string.Format(chksql, TransCode, WorkPoint);
                DataTable chkdt = DBHelper.SQlReturnData(chksql, cmd);
                if (chkdt.Rows.Count != 0)
                {
                    if (Convert.ToDecimal(chkdt.Rows[0]["Quantity"]) != Convert.ToDecimal(chkdt.Rows[0]["IssueQuantity"]))
                    {
                        throw new Exception("领料单尚未全部领料,请全部领完后在进行生产人员确认!");
                    }
                }
                string sql = @"DECLARE @Status VARCHAR(10)
                                SELECT @Status=a.Status FROM ICSMOApply  a
                                WHERE a.ApplyCode='{0}' AND a.WorkPoint='{1}'

                                IF (@Status IS NULL)
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo130") + @"',16,1);
                                    RETURN
                                END
                                UPDATE a SET MUSERNAME='{2}'
                                FROM ICSMOApply  a
                                WHERE a.ApplyCode='{0}' AND a.WorkPoint='{1}'
                                update ICSContainerReceiptsNumber set EATTRIBUTE5='已解除'
                                where TransCode='{0}'";

                sql = string.Format(sql, TransCode, WorkPoint, MuserName);

                if (!DBHelper.ExecuteNonQuery(sql, cmd))
                {
                    throw new Exception(language.GetNameByCode("WMSAPIInfo204"));//"领料申请单确认人员更新失败!");
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
        /// <summary>
        /// 领料申请单生产发料接口(SAP)
        /// </summary>
        /// <param name="TransType"></param>
        /// <param name="Identification"></param>
        /// <param name="cmd"></param>
        public static void MOApplyERP(string TransType, string Identification, SqlCommand cmd, Dictionary<string, string> language, string BusinessCode)
        {
            try
            {
                #region SAP(三层结构)
                string IsSuccess = "";
                string ErrorMessage = "";
                string sql = @" select Distinct A.ApplyCode,A.WorkPoint,A.EATTRIBUTE from ICSMOApply A
                                LEFT JOIN ICSWareHouseLotInfoLog B ON B.TransCode=A.ApplyCode AND B.WorkPoint=A.WorkPoint
                                where B.Identification='{0}' AND BusinessCode='14'";
                sql = string.Format(sql, Identification);
                DataTable dt = DBHelper.SQlReturnData(sql, cmd);
                if (dt.Rows.Count == 0)
                {
                    throw new Exception("单据查询失败!");//单据查询失败
                }
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    string chksql = @"select SUM(Quantity) AS Quantity,SUM(IssueQuantity) AS IssueQuantity from ICSMOApply
                                      where ApplyCode='{0}' and WorkPoint='{1}'
                                      GROUP BY ApplyCode,WorkPoint";
                    chksql = string.Format(chksql, dt.Rows[i]["ApplyCode"].ToString(), dt.Rows[i]["WorkPoint"].ToString());
                    DataTable chkdt = DBHelper.SQlReturnData(chksql, cmd);
                    if (Convert.ToDecimal(chkdt.Rows[0]["Quantity"]) == Convert.ToDecimal(chkdt.Rows[0]["IssueQuantity"]))
                    {
                        SAPCallBackDocVPN.ZWMS_SK_WS_PZ Client = new SAPCallBackDocVPN.ZWMS_SK_WS_PZ();
                        SAPCallBackDocVPN.ZWMS_SK_WS_PZ1 Info = new SAPCallBackDocVPN.ZWMS_SK_WS_PZ1();
                        Info.NEWID = Identification;
                        Info.DANJU = dt.Rows[i]["ApplyCode"].ToString();
                        if (dt.Rows[i]["EATTRIBUTE"].ToString() == "01" || dt.Rows[i]["EATTRIBUTE"].ToString() == "20")
                        {
                            Info.STATE = "1";
                        }
                        else
                        {
                            Info.STATE = "0";
                        }
                        List<SAPCallBackDocVPN.ZWMS_PZ> ItemList = new List<SAPCallBackDocVPN.ZWMS_PZ>();
                        List<SAPCallBackDocVPN.ZWEBS_GERNR> ItemLineList = new List<SAPCallBackDocVPN.ZWEBS_GERNR>();
                        Info.Z_FLAG = new SAPCallBackDocVPN.ZWEB_RETURN[1];
                        sql = @"select A.ApplyCode,A.InvCode,A.Sequence,A.SAPSequence,A.Quantity,A.IssueQuantity
                            ,ISNULL(B.BatchCode,'') AS BatchCode from ICSMOApply A
                            LEFT JOIN ICSExtension B ON B.ID=A.ExtensionID AND B.WorkPoint=A.WorkPoint
                            WHERE ApplyCode='{0}' AND A.WorkPoint='{1}'";
                        sql = string.Format(sql, dt.Rows[i]["ApplyCode"].ToString(), dt.Rows[i]["WorkPoint"].ToString());
                        DataTable Sapdt = DBHelper.SQlReturnData(sql, cmd);
                        foreach (DataRow dr in Sapdt.Rows)
                        {
                            if (Convert.ToDecimal(dr["Quantity"].ToString()) == Convert.ToDecimal(dr["IssueQuantity"].ToString()))
                            {
                                SAPCallBackDocVPN.ZWMS_PZ Item = new SAPCallBackDocVPN.ZWMS_PZ();
                                SAPCallBackDocVPN.ZWEBS_GERNR ItemLine = new SAPCallBackDocVPN.ZWEBS_GERNR();
                                Item.DANJU = dr["ApplyCode"].ToString();
                                Item.POSNR = dr["SAPSequence"].ToString();
                                Item.LINGYSL = System.Decimal.Round(Convert.ToDecimal(dr["Quantity"].ToString()), 3);
                                ItemList.Add(Item);
                                if (dr["BatchCode"].ToString() != "")
                                {
                                    ItemLine.DANJU = dr["ApplyCode"].ToString();
                                    ItemLine.POSNR = dr["SAPSequence"].ToString();
                                    ItemLine.MATNR = dr["InvCode"].ToString();
                                    ItemLine.GERNR = dr["BatchCode"].ToString();
                                    ItemLineList.Add(ItemLine);
                                }
                            }
                        }
                        if (ItemList.Count > 0)
                        {
                            Info.Z_ITEM = ItemList.ToArray();
                            if (ItemLineList.Count > 0)
                            {
                                Info.Z_GERNR = ItemLineList.ToArray();
                            }
                            else
                            {
                                Info.Z_GERNR = new SAPCallBackDocVPN.ZWEBS_GERNR[1];
                            }
                            SAPCallBackDocVPN.ZWMS_SK_WS_PZResponse result = new SAPCallBackDocVPN.ZWMS_SK_WS_PZResponse();
                            result = Client.CallZWMS_SK_WS_PZ(Info);
                            if (result.Z_NULL == "N")
                            {
                                foreach (SAPCallBackDocVPN.ZWEB_RETURN resultItem in result.Z_FLAG)
                                {
                                    IsSuccess = "N";
                                    ErrorMessage += resultItem.L_MESSAGE + "/r/n";
                                }
                            }
                        }
                    }
                }
                if (IsSuccess == "N")
                {
                    throw new Exception(ErrorMessage);
                }
                #endregion
            }
            catch (Exception ex)
            {
                throw;
            }
        }
        /// <summary>
        /// 领料申请单过账SAP
        /// </summary>
        /// <param name="TransCode"></param>
        /// <param name="MuserName"></param>
        /// <param name="WorkPoint"></param>
        /// <param name="cmd"></param>
        /// <param name="language"></param>
        public static void MOApplySAPGZ(string TransCode, string MuserName, string WorkPoint, SqlCommand cmd, Dictionary<string, string> language)
        {
            try
            {
                #region SAP(三层结构)
                string IsSuccess = "";
                string ErrorMessage = "";
                string sql = @"select A.ID,A.ApplyCode,A.InvCode,A.Sequence,A.SAPSequence,A.Quantity,A.IssueQuantity
                            ,ISNULL(B.BatchCode,'') AS BatchCode from ICSMOApply A
                            LEFT JOIN ICSExtension B ON B.ID=A.ExtensionID AND B.WorkPoint=A.WorkPoint
                            WHERE ApplyCode='{0}' AND A.WorkPoint='{1}'";
                sql = string.Format(sql, TransCode, WorkPoint);
                DataTable Sapdt = DBHelper.SQlReturnData(sql, cmd);
                if (Sapdt.Rows.Count == 0)
                {
                    throw new Exception(string.Format(language.GetNameByCode("WMSAPIInfo205"), TransCode));//单据查询失败
                }
                SAPCallBackDocVPN.ZWMS_SK_WS_PZ Client = new SAPCallBackDocVPN.ZWMS_SK_WS_PZ();
                SAPCallBackDocVPN.ZWMS_SK_WS_PZ1 Info = new SAPCallBackDocVPN.ZWMS_SK_WS_PZ1();
                Info.NEWID = Sapdt.Rows[0]["ID"].ToString();
                Info.DANJU = TransCode;
                Info.STATE = "0";
                List<SAPCallBackDocVPN.ZWMS_PZ> ItemList = new List<SAPCallBackDocVPN.ZWMS_PZ>();
                List<SAPCallBackDocVPN.ZWEBS_GERNR> ItemLineList = new List<SAPCallBackDocVPN.ZWEBS_GERNR>();
                Info.Z_FLAG = new SAPCallBackDocVPN.ZWEB_RETURN[1];

                foreach (DataRow dr in Sapdt.Rows)
                {
                    if (Convert.ToDecimal(dr["Quantity"].ToString()) == Convert.ToDecimal(dr["IssueQuantity"].ToString()))
                    {
                        SAPCallBackDocVPN.ZWMS_PZ Item = new SAPCallBackDocVPN.ZWMS_PZ();
                        SAPCallBackDocVPN.ZWEBS_GERNR ItemLine = new SAPCallBackDocVPN.ZWEBS_GERNR();
                        Item.DANJU = dr["ApplyCode"].ToString();
                        Item.POSNR = dr["SAPSequence"].ToString();
                        Item.LINGYSL = System.Decimal.Round(Convert.ToDecimal(dr["Quantity"].ToString()), 3);
                        ItemList.Add(Item);
                        if (dr["BatchCode"].ToString() != "")
                        {
                            ItemLine.DANJU = dr["ApplyCode"].ToString();
                            ItemLine.POSNR = dr["SAPSequence"].ToString();
                            ItemLine.MATNR = dr["InvCode"].ToString();
                            ItemLine.GERNR = dr["BatchCode"].ToString();
                            ItemLineList.Add(ItemLine);
                        }

                    }
                }
                if (ItemList.Count > 0)
                {
                    Info.Z_ITEM = ItemList.ToArray();
                    if (ItemLineList.Count > 0)
                    {
                        Info.Z_GERNR = ItemLineList.ToArray();
                    }
                    else
                    {
                        Info.Z_GERNR = new SAPCallBackDocVPN.ZWEBS_GERNR[1];
                    }
                    SAPCallBackDocVPN.ZWMS_SK_WS_PZResponse result = new SAPCallBackDocVPN.ZWMS_SK_WS_PZResponse();
                    result = Client.CallZWMS_SK_WS_PZ(Info);
                    if (result.Z_NULL == "N")
                    {
                        foreach (SAPCallBackDocVPN.ZWEB_RETURN resultItem in result.Z_FLAG)
                        {
                            IsSuccess = "N";
                            ErrorMessage += resultItem.L_MESSAGE + "/r/n";
                        }
                    }
                }
                if (IsSuccess == "N")
                {
                    throw new Exception(ErrorMessage);
                }
                #endregion
            }
            catch (Exception)
            {
                throw;
            }
        }
        #endregion

        #region 材料出库单生产发料
        /// <summary>
        /// 材料出库单生产发料
        /// </summary>
        /// <param name="TransCode"></param>
        /// <param name="TransSequence"></param>
        /// <param name="Quantity"></param>
        /// <param name="WorkPoint"></param>
        /// <param name="cmd"></param>
        public static void MOIssue(string TransCode, string TransSequence, string Quantity, string WorkPoint, SqlCommand cmd, Dictionary<string, string> language)
        {
            try
            {
                string sql = @"DECLARE @Status VARCHAR(10)
                                SELECT @Status=a.Status FROM ICSMOIssue  a
                                WHERE a.IssueCode='{0}' AND a.Sequence='{3}' AND a.WorkPoint='{1}'

                                IF (@Status IS NULL)
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo131") + @"',16,1);
                                    RETURN
                                END
                                --ELSE IF (@Status!='1')
                                --BEGIN
	                                --RAISERROR('" + language.GetNameByCode("WMSAPIInfo132") + @"',16,1);
                                    --RETURN
                                --END
                                UPDATE a SET IssueQuantity=ISNULL(IssueQuantity,0)+'{2}'
                                FROM ICSMOIssue  a
                                WHERE a.IssueCode='{0}' AND a.Sequence='{3}' AND a.WorkPoint='{1}'

                                IF EXISTS(SELECT a.ID FROM ICSMOIssue  a
	                                WHERE a.IssueCode='{0}' AND a.Sequence='{3}' and a.WorkPoint='{1}' AND a.Quantity<a.IssueQuantity)
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo091") + @"',16,1);
                                    RETURN
                                END";

                sql = string.Format(sql, TransCode, WorkPoint, Quantity, TransSequence);

                if (!DBHelper.ExecuteNonQuery(sql, cmd))
                {
                    throw new Exception(language.GetNameByCode("WMSAPIInfo133"));//"材料出库单更新失败!");
                }
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 材料出库单生产发料接口
        /// </summary>
        /// <param name="TransType"></param>
        /// <param name="Identification"></param>
        /// <param name="cmd"></param>
        public static void MOIssueERP(string TransType, string Identification, SqlCommand cmd, Dictionary<string, string> language, string BusinessCode)
        {
            try
            {
                #region ERP开立状态单据审核
                string sql = @"IF EXISTS(SELECT b.ID FROM ICSWareHouseLotInfoLog a
                                    INNER JOIN ICSMOIssue b ON a.TransCode=b.IssueCode AND a.TransSequence=b.Sequence AND a.WorkPoint=b.WorkPoint
                                    WHERE a.Identification='{0}' AND b.Quantity!=b.IssueQuantity)
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo094") + @"',16,1);
                                    RETURN
                                END
                                SELECT b.IssueID AS ID,a.MUSER AS [User],SYSDATETIME() AS MTime,con.Enable AS UpdateTodoQuantity
	                            ,conStock.Enable AS UpdateStock,a.WorkPoint
                                FROM ICSWareHouseLotInfoLog a
                                INNER JOIN ICSMOIssue b ON a.TransCode=b.IssueCode AND a.TransSequence=b.Sequence AND a.WorkPoint=b.WorkPoint
                                INNER JOIN ICSConfiguration con ON con.Code='Stock002' AND a.WorkPoint=con.WorkPoint
                                INNER JOIN ICSConfiguration conStock ON conStock.Code='UpdateStock002' AND a.WorkPoint=conStock.WorkPoint
                                WHERE a.Identification='{0}' AND  ERPUpload='0' AND a.BusinessCode = '15' 
                                GROUP BY b.IssueID,a.MUSER,con.Enable
                                ,conStock.Enable,a.WorkPoint";
                sql = string.Format(sql, Identification);
                DataTable dt = DBHelper.SQlReturnData(sql, cmd);

                string Inputstr = JsonConvert.SerializeObject(dt);
                string resultStr = HTTPHelper.HttpPost(TransType, ERPUrl.MOIssueURL, Inputstr);
                Result result = new Result();
                result = JsonConvert.DeserializeObject<Result>(resultStr);
                if (result.Success)
                {
                    try
                    {
                        foreach (DataRow dr in dt.Rows)
                        {
                            ICSWareHouseLotInfoService.WareHouseLotInfoLogUpdate(TransType, dr["ID"].ToString(), Identification, "", "", "", "", "", cmd, language, BusinessCode);
                        }
                    }
                    catch (Exception ex)
                    {
                        log.Debug(ex.ToString());
                        log.Debug(resultStr);
                    }
                }
                else
                {
                    throw new Exception(language.GetNameByCode("WMSAPIInfo080") + result.Message);
                }
                #endregion
            }
            catch (Exception)
            {
                throw;
            }
        }
        #endregion



        #region 生产退料
        /// <summary>
        /// 生产退料(货柜)
        /// </summary>
        /// <param name="TransCode"></param>
        /// <param name="WorkPoint"></param>
        /// <param name="cmd"></param>
        /// <param name="language"></param>
        public static void MOIssueDocNegativeHG(string TransCode, string TransLine, string WorkPoint, SqlCommand cmd, Dictionary<string, string> language, string quantity)
        {
            try
            {
                string sql = "";
                decimal iquantity = Convert.ToDecimal(quantity);
                sql = @" IF EXISTS (SELECT ID FROM ICSMOApplyNegDetail WHERE IssueNegQuantity=Quantity AND ApplyNegCode='{0}' and Sequence='{1}'  and WorkPoint='{2}' )
                         BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo472") + @"',16,1);
                                    RETURN
                                END;
                         Update ICSMOApplyNegDetail set IssueNegQuantity=IssueNegQuantity+{3}
                         where ApplyNegCode='{0}' and Sequence='{1}'  and WorkPoint='{2}'";
                sql = string.Format(sql, TransCode, TransLine, WorkPoint, iquantity);
                if (!DBHelper.ExecuteNonQuery(sql, cmd))
                {
                    throw new Exception(language.GetNameByCode("WMSAPIInfo134"));//"生产退料单更新失败!");
                }
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 生产退料
        /// </summary>
        /// <param name="TransCode"></param>
        /// <param name="TransSequence"></param>
        /// <param name="Quantity"></param>
        /// <param name="WorkPoint"></param>
        /// <param name="cmd"></param>
        public static void MOIssueDocNegative(string TransType, string LogID, string LotNo, string Quantity, string WorkPoint, SqlCommand cmd, Dictionary<string, string> language)
        {
            try
            {
                string table = "";
                string sql = "";
                if (string.IsNullOrWhiteSpace(LogID))
                {
                    string type = "";
                    if (TransType == TransTypeEnum.MOIssueDocNegative.GetDescription())
                    {
                        table = "INNER JOIN ICSMOPick e ON c.SourceDetailID=e.PickID AND c.WorkPoint=e.WorkPoint";
                        type = "1";
                    }
                    //改动 生产退料 -生产退料单 - 领料申请单 和发料申请单没有关系
                    else if (TransType == TransTypeEnum.MOIssueDocNegativeApply.GetDescription())
                    {
                        //table = "INNER JOIN ICSMOApply e ON c.SourceDetailID=e.ApplyDetailID AND c.WorkPoint=e.WorkPoint";
                        type = "2";
                    }
                    else if (TransType == TransTypeEnum.MOIssueDocNegativeIssue.GetDescription())
                    {
                        table = "INNER JOIN ICSMOIssue e ON c.SourceDetailID=e.IssueDetailID AND c.WorkPoint=e.WorkPoint";
                        type = "3";
                    }
                    else
                    {
                        throw new Exception(language.GetNameByCode("WMSAPIInfo003"));//"类型不符!");
                    }
                    #region 新条码
                    if (TransType == TransTypeEnum.MOIssueDocNegativeApply.GetDescription())
                    {
                        sql = @"UPDATE c SET IssueNegQuantity=ISNULL(IssueNegQuantity,0)+'{2}'
                            FROM ICSInventoryLot a
                            INNER JOIN ICSInventoryLotDetail b ON a.LotNo=b.LotNo AND a.WorkPoint=b.WorkPoint
                            INNER JOIN ICSMOApplyNegDetail c ON b.TransCode=c.ApplyNegCode AND b.TransSequence=c.Sequence AND b.WorkPoint=c.WorkPoint
                            INNER JOIN ICSMOApplyNeg d ON c.ApplyNegCode=d.ApplyNegCode AND c.WorkPoint=d.WorkPoint
                            WHERE a.LotNo='{0}' AND a.WorkPoint='{1}' AND d.Type='{4}'
                            IF EXISTS(SELECT a.LotNo FROM ICSInventoryLot a
                                INNER JOIN ICSInventoryLotDetail b ON a.LotNo=b.LotNo AND a.WorkPoint=b.WorkPoint
                                INNER JOIN ICSMOApplyNegDetail c ON b.TransCode=c.ApplyNegCode AND b.TransSequence=c.Sequence AND b.WorkPoint=c.WorkPoint
                                INNER JOIN ICSMOApplyNeg d ON c.ApplyNegCode=d.ApplyNegCode AND c.WorkPoint=d.WorkPoint
                                WHERE a.LotNo='{0}' AND a.WorkPoint='{1}' AND d.Type='{4}' AND c.Quantity<c.IssueNegQuantity)
                            BEGIN
	                            RAISERROR('" + language.GetNameByCode("WMSAPIInfo114") + @"',16,1);
                            END";

                    }
                    else
                    {
                        sql = @"UPDATE c SET IssueNegQuantity=ISNULL(IssueNegQuantity,0)+'{2}'
                            FROM ICSInventoryLot a
                            INNER JOIN ICSInventoryLotDetail b ON a.LotNo=b.LotNo AND a.WorkPoint=b.WorkPoint
                            INNER JOIN ICSMOApplyNegDetail c ON b.TransCode=c.ApplyNegCode AND b.TransSequence=c.Sequence AND b.WorkPoint=c.WorkPoint
                            INNER JOIN ICSMOApplyNeg d ON c.ApplyNegCode=d.ApplyNegCode AND c.WorkPoint=d.WorkPoint
                            WHERE a.LotNo='{0}' AND a.WorkPoint='{1}' AND d.Type='{4}'
                            IF EXISTS(SELECT a.LotNo FROM ICSInventoryLot a
                                INNER JOIN ICSInventoryLotDetail b ON a.LotNo=b.LotNo AND a.WorkPoint=b.WorkPoint
                                INNER JOIN ICSMOApplyNegDetail c ON b.TransCode=c.ApplyNegCode AND b.TransSequence=c.Sequence AND b.WorkPoint=c.WorkPoint
                                INNER JOIN ICSMOApplyNeg d ON c.ApplyNegCode=d.ApplyNegCode AND c.WorkPoint=d.WorkPoint
                                WHERE a.LotNo='{0}' AND a.WorkPoint='{1}' AND d.Type='{4}' AND c.Quantity<c.IssueNegQuantity)
                            BEGIN
	                            RAISERROR('" + language.GetNameByCode("WMSAPIInfo114") + @"',16,1);
                            END

                            UPDATE e SET IssueQuantity=ISNULL(IssueQuantity,0)-'{2}'
                            FROM ICSInventoryLot a
                            INNER JOIN ICSInventoryLotDetail b ON a.LotNo=b.LotNo AND a.WorkPoint=b.WorkPoint
                            INNER JOIN ICSMOApplyNegDetail c ON b.TransCode=c.ApplyNegCode AND b.TransSequence=c.Sequence AND b.WorkPoint=c.WorkPoint
                            INNER JOIN ICSMOApplyNeg d ON c.ApplyNegCode=d.ApplyNegCode AND c.WorkPoint=d.WorkPoint
                            {3}
                            WHERE a.LotNo='{0}' AND a.WorkPoint='{1}' AND d.Type='{4}'
                            IF EXISTS(SELECT a.LotNo FROM ICSInventoryLot a
                                INNER JOIN ICSInventoryLotDetail b ON a.LotNo=b.LotNo AND a.WorkPoint=b.WorkPoint
                                INNER JOIN ICSMOApplyNegDetail c ON b.TransCode=c.ApplyNegCode AND b.TransSequence=c.Sequence AND b.WorkPoint=c.WorkPoint
                                INNER JOIN ICSMOApplyNeg d ON c.ApplyNegCode=d.ApplyNegCode AND c.WorkPoint=d.WorkPoint
                                {3}
                                WHERE a.LotNo='{0}' AND a.WorkPoint='{1}' AND d.Type='{4}' AND e.IssueQuantity<0)
                            BEGIN
	                            RAISERROR('" + language.GetNameByCode("WMSAPIInfo192") + @"',16,1);
                            END";
                    }

                    sql = string.Format(sql, LotNo, WorkPoint, Quantity, table, type);
                    #endregion
                }
                else
                {
                    if (TransType == TransTypeEnum.MOIssueDocNegative.GetDescription())
                    {
                        table = @"INNER JOIN ICSMO b ON a.TransCode=b.MOCode AND a.WorkPoint=b.WorkPoint
                            INNER JOIN ICSMOPick c ON b.MODetailID = c.MODetailID AND b.WorkPoint = c.WorkPoint AND a.TransSequence = b.Sequence + '~' + c.Sequence";
                    }
                    else if (TransType == TransTypeEnum.MOIssueDocNegativeApply.GetDescription())
                    {
                        table = "INNER JOIN ICSMOApply c ON a.TransCode=c.ApplyCode  AND a.TransSequence=c.Sequence AND a.WorkPoint=c.WorkPoint";
                    }
                    else if (TransType == TransTypeEnum.MOIssueDocNegativeIssue.GetDescription())
                    {
                        table = "INNER JOIN ICSMOIssue c ON a.TransCode=c.IssueCode  AND a.TransSequence=c.Sequence AND a.WorkPoint=c.WorkPoint";
                    }
                    else
                    {
                        throw new Exception(language.GetNameByCode("WMSAPIInfo003"));//"类型不符!");
                    }
                    #region 原条码
                    sql = @"UPDATE c SET IssueQuantity=ISNULL(IssueQuantity,0)-'{2}'
                            FROM ICSWareHouseLotInfoLog a
	                          {3}
                            WHERE a.LotNo='{0}' AND a.WorkPoint='{1}' AND a.ID='{4}'
                            IF EXISTS(SELECT a.LotNo FROM ICSWareHouseLotInfoLog a
                            {3}
                            WHERE a.LotNo='{0}' AND a.WorkPoint='{1}' AND a.ID='{4}' AND c.IssueQuantity<0)
                            BEGIN
	                            RAISERROR('" + language.GetNameByCode("WMSAPIInfo192") + @"',16,1);
                            END";
                    sql = string.Format(sql, LotNo, WorkPoint, Quantity, table, LogID);
                    #endregion
                }
                if (!DBHelper.ExecuteNonQuery(sql, cmd))
                {
                    throw new Exception(language.GetNameByCode("WMSAPIInfo134"));//"生产退料单更新失败!");
                }
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 生产退料接口
        /// </summary>
        /// <param name="TransType"></param>
        /// <param name="Identification"></param>
        /// <param name="cmd"></param>
        public static void MOIssueDocNegativeERP(string TransType, string Identification, SqlCommand cmd, Dictionary<string, string> language, string BusinessCode)
        {
            try
            {
                #region SAP(三层结构)
                string IsSuccess = "";
                string ErrorMessage = "";
                string sql = @" select Distinct A.ApplyNegCode,A.WorkPoint from ICSMOApplyNeg A
                                LEFT JOIN ICSWareHouseLotInfoLog B ON B.TransCode=A.ApplyNegCode AND B.WorkPoint=A.WorkPoint
                                where B.Identification='{0}' AND BusinessCode='16'";
                sql = string.Format(sql, Identification);
                DataTable dt = DBHelper.SQlReturnData(sql, cmd);
                if (dt.Rows.Count > 1)
                {
                    throw new Exception(language.GetNameByCode("WMSAPIInfo202"));//单次提交单据数量卡控(只允许一张单据)
                }
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    string chksql = @"select SUM(B.Quantity) AS Quantity,SUM(B.IssueNegQuantity) AS IssueQuantity from ICSMOApplyNeg A
									  LEFT JOIN ICSMOApplyNegDetail B ON B.ApplyNegCode=A.ApplyNegCode AND B.WorkPoint=A.WorkPoint
                                      where A.ApplyNegCode='{0}' and A.WorkPoint='{1}'
                                      GROUP BY A.ApplyNegCode,A.WorkPoint";
                    chksql = string.Format(chksql, dt.Rows[i]["ApplyNegCode"].ToString(), dt.Rows[i]["WorkPoint"].ToString());
                    DataTable chkdt = DBHelper.SQlReturnData(chksql, cmd);
                    if (Convert.ToDecimal(chkdt.Rows[0]["Quantity"]) == Convert.ToDecimal(chkdt.Rows[0]["IssueQuantity"]))
                    {
                        SAPCallBackDocVPN.ZWMS_SK_WS_PZ Client = new SAPCallBackDocVPN.ZWMS_SK_WS_PZ();
                        SAPCallBackDocVPN.ZWMS_SK_WS_PZ1 Info = new SAPCallBackDocVPN.ZWMS_SK_WS_PZ1();
                        Info.NEWID = Identification;
                        Info.DANJU = dt.Rows[i]["ApplyNegCode"].ToString();
                        Info.STATE = "0";
                        List<SAPCallBackDocVPN.ZWMS_PZ> ItemList = new List<SAPCallBackDocVPN.ZWMS_PZ>();
                        List<SAPCallBackDocVPN.ZWEBS_GERNR> ItemLineList = new List<SAPCallBackDocVPN.ZWEBS_GERNR>();
                        Info.Z_FLAG = new SAPCallBackDocVPN.ZWEB_RETURN[1];
                        sql = @" select A.ApplyNegCode,B.SAPSequence,B.InvCode,B.Sequence,B.Quantity,B.IssueNegQuantity
                            ,ISNULL(C.BatchCode,'') AS BatchCode from ICSMOApplyNeg A
							LEFT JOIN ICSMOApplyNegDetail B ON B.ApplyNegCode=A.ApplyNegCode AND B.WorkPoint=A.WorkPoint
                            LEFT JOIN ICSExtension C ON C.ID=B.ExtensionID AND C.WorkPoint=B.WorkPoint
                            WHERE A.ApplyNegCode='{0}' AND A.WorkPoint='{1}'";
                        sql = string.Format(sql, dt.Rows[i]["ApplyNegCode"].ToString(), dt.Rows[i]["WorkPoint"].ToString());
                        DataTable Sapdt = DBHelper.SQlReturnData(sql, cmd);
                        foreach (DataRow dr in Sapdt.Rows)
                        {
                            if (Convert.ToDecimal(dr["Quantity"].ToString()) == Convert.ToDecimal(dr["IssueNegQuantity"].ToString()))
                            {
                                SAPCallBackDocVPN.ZWMS_PZ Item = new SAPCallBackDocVPN.ZWMS_PZ();
                                SAPCallBackDocVPN.ZWEBS_GERNR ItemLine = new SAPCallBackDocVPN.ZWEBS_GERNR();
                                Item.DANJU = dr["ApplyNegCode"].ToString();
                                Item.POSNR = dr["SAPSequence"].ToString();
                                Item.LINGYSL = System.Decimal.Round(Convert.ToDecimal(dr["Quantity"].ToString()), 3);
                                ItemList.Add(Item);
                                if (dr["BatchCode"].ToString() != "")
                                {
                                    ItemLine.DANJU = dr["ApplyNegCode"].ToString();
                                    ItemLine.POSNR = dr["SAPSequence"].ToString();
                                    ItemLine.MATNR = dr["InvCode"].ToString();
                                    ItemLine.GERNR = dr["BatchCode"].ToString();
                                    ItemLineList.Add(ItemLine);
                                }
                            }
                        }
                        if (ItemList.Count > 0)
                        {
                            Info.Z_ITEM = ItemList.ToArray();
                            if (ItemLineList.Count > 0)
                            {
                                Info.Z_GERNR = ItemLineList.ToArray();
                            }
                            else
                            {
                                Info.Z_GERNR = new SAPCallBackDocVPN.ZWEBS_GERNR[1];
                            }
                            SAPCallBackDocVPN.ZWMS_SK_WS_PZResponse result = new SAPCallBackDocVPN.ZWMS_SK_WS_PZResponse();
                            result = Client.CallZWMS_SK_WS_PZ(Info);
                            if (result.Z_NULL == "N")
                            {
                                foreach (SAPCallBackDocVPN.ZWEB_RETURN resultItem in result.Z_FLAG)
                                {
                                    IsSuccess = "N";
                                    ErrorMessage += resultItem.L_MESSAGE + "/r/n";
                                }
                            }
                        }
                    }
                }
                if (IsSuccess == "N")
                {
                    throw new Exception(ErrorMessage);
                }
                #endregion
            }
            catch (Exception)
            {
                throw;
            }
        }
        #endregion

        #region 生产入库
        /// <summary>
        /// 生产入库
        /// </summary>
        /// <param name="TransCode"></param>
        /// <param name="TransSequence"></param>
        /// <param name="Quantity"></param>
        /// <param name="WorkPoint"></param>
        /// <param name="cmd"></param>
        public static void ManufactureReceiveDoc(string LotNo, string Quantity, string WorkPoint, SqlCommand cmd, Dictionary<string, string> language)
        {
            try
            {
                string sql = @"DECLARE @Status VARCHAR(10)
                                SELECT @Status=c.ERPStatus FROM ICSInventoryLot a
                                INNER JOIN ICSInventoryLotDetail b ON a.LotNo=b.LotNo AND a.WorkPoint=b.WorkPoint
                                INNER JOIN ICSMO c ON b.TransCode=c.MOCode AND b.TransSequence=c.Sequence AND b.WorkPoint=c.WorkPoint
                                WHERE a.LotNo='{0}' AND a.WorkPoint='{1}'

                                IF (@Status IS NULL)
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo081") + @"',16,1);
                                    RETURN
                                END
                                ELSE IF (@Status='3')
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo082") + @"',16,1);
                                    RETURN
                                END
                               UPDATE c SET RCVQuantity=ISNULL(RCVQuantity,0)+'{2}'
                                FROM ICSInventoryLot a
                                INNER JOIN ICSInventoryLotDetail b ON a.LotNo=b.LotNo AND a.WorkPoint=b.WorkPoint
                                INNER JOIN ICSMO c ON b.TransCode=c.MOCode AND b.TransSequence=c.Sequence AND b.WorkPoint=c.WorkPoint
                                WHERE a.LotNo='{0}' AND a.WorkPoint='{1}'
                                IF EXISTS(SELECT a.LotNo FROM ICSInventoryLot a
                                    INNER JOIN ICSInventoryLotDetail b ON a.LotNo=b.LotNo AND a.WorkPoint=b.WorkPoint
                                    INNER JOIN ICSMO c ON b.TransCode=c.MOCode AND b.TransSequence=c.Sequence AND b.WorkPoint=c.WorkPoint
                                    WHERE a.LotNo='{0}' AND a.WorkPoint='{1}' AND c.Quantity<c.RCVQuantity)
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo083") + @"',16,1);
                                END";
                sql = string.Format(sql, LotNo, WorkPoint, Quantity);
                if (!DBHelper.ExecuteNonQuery(sql, cmd))
                {
                    throw new Exception(language.GetNameByCode("WMSAPIInfo136"));//"生产订单更新失败!");
                }
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 生产入库接口
        /// </summary>
        /// <param name="TransType"></param>
        /// <param name="Identification"></param>
        /// <param name="cmd"></param>
        public static void ManufactureReceiveDocERP(string TransType, string Identification, SqlCommand cmd, Dictionary<string, string> language, string BusinessCode)
        {
            try
            {
                #region ERP
                string sql = @"SELECT c.DepCode+a.ToWarehouseCode+c.MOCode+a.MUSER AS Costre,c.MODetailID+ISNULL(ext.ProjectCode, '')+CASE WHEN (invBat.BatchEnable IS NULL AND ISNULL(inv.BatchEnable, '0')='1') OR ISNULL(invBat.BatchEnable, '0')='1' THEN ISNULL(ext.BatchCode, '') ELSE '' END+ISNULL(ext.Version, '')+ISNULL(ext.Brand, '')+
                                ISNULL(ext.cFree1, '')+ISNULL(ext.cFree2, '')+ISNULL(ext.cFree3, '')+ISNULL(ext.cFree4, '')+ISNULL(ext.cFree5, '')+ISNULL(ext.cFree6, '')+ISNULL(ext.cFree7, '')+ISNULL(ext.cFree8, '')+ISNULL(ext.cFree9, '')+ISNULL(ext.cFree10, '') AS Costre2,c.DepCode,a.ToWarehouseCode AS WarehouseCode,c.MOCode,a.MUSER,ROW_NUMBER() OVER (ORDER BY c.DepCode,a.ToWarehouseCode,c.MOCode,c.MODetailID,a.InvCode) AS Sequence,
                                    a.InvCode,SUM(a.Quantity) AS Quantity,SUM(a.Quantity*(lot.Amount/lot.Quantity)) AS Amount,c.MODetailID,con.Enable AS UpdateTodoQuantity
                                ,a.WorkPoint,ISNULL(ext.ProjectCode, '') AS ProjectCode,CASE WHEN (invBat.BatchEnable IS NULL AND ISNULL(inv.BatchEnable, '0')='1') OR ISNULL(invBat.BatchEnable, '0')='1' THEN ISNULL(ext.BatchCode, '') ELSE '' END AS BatchCode,ISNULL(ext.Version, '') AS Version,ISNULL(ext.Brand, '') AS Brand,
	                            ISNULL(ext.cFree1, '') AS cFree1,ISNULL(ext.cFree2, '') AS cFree2,ISNULL(ext.cFree3, '') AS cFree3,ISNULL(ext.cFree4, '') AS cFree4,ISNULL(ext.cFree5, '') AS cFree5,ISNULL(ext.cFree6, '') AS cFree6,ISNULL(ext.cFree7, '') AS cFree7,ISNULL(ext.cFree8, '') AS cFree8,ISNULL(ext.cFree9, '') AS cFree9,ISNULL(ext.cFree10, '') AS cFree10,conv.Enable AS CompleteVerification,a.TransSequence
                                 INTO #TempERP
                                FROM ICSWareHouseLotInfoLog a
                                INNER JOIN ICSInventoryLot lot ON a.LotNo=lot.LotNo AND a.WorkPoint=lot.WorkPoint
                                INNER JOIN ICSExtension ext ON lot.ExtensionID=ext.ID AND lot.WorkPoint=ext.WorkPoint
                                INNER JOIN ICSInventory inv ON a.InvCode=inv.InvCode AND a.WorkPoint=inv.WorkPoint
                                LEFT JOIN ICSInventoryBatchEnable invBat ON a.InvCode=invBat.InvCode AND a.ToWarehouseCode=invBat.WHCode AND a.WorkPoint=invBat.WorkPoint
                                INNER JOIN ICSInventoryLotDetail b ON a.LotNo=b.LotNo AND a.WorkPoint=b.WorkPoint
                                INNER JOIN ICSMO c ON b.TransCode=c.MOCode AND b.TransSequence=c.Sequence AND b.WorkPoint=c.WorkPoint
                                INNER JOIN ICSConfiguration con ON con.Code='Stock001' AND a.WorkPoint=con.WorkPoint
                                INNER JOIN ICSConfiguration conv ON conv.Code='CompleteVerification' AND a.WorkPoint=conv.WorkPoint
                                WHERE a.Identification='{0}' AND  ERPUpload='0' AND BusinessCode='{1}'
                                GROUP BY c.DepCode,a.ToWarehouseCode,c.MOCode,a.MUSER,a.InvCode,c.MODetailID,con.Enable,conv.Enable
                                ,a.WorkPoint,ISNULL(ext.ProjectCode, ''),CASE WHEN (invBat.BatchEnable IS NULL AND ISNULL(inv.BatchEnable, '0')='1') OR ISNULL(invBat.BatchEnable, '0')='1' THEN ISNULL(ext.BatchCode, '') ELSE '' END,ISNULL(ext.Version, ''),ISNULL(ext.Brand, ''),
                                ISNULL(ext.cFree1, ''),ISNULL(ext.cFree2, ''),ISNULL(ext.cFree3, ''),ISNULL(ext.cFree4, ''),ISNULL(ext.cFree5, ''),ISNULL(ext.cFree6, ''),ISNULL(ext.cFree7, ''),ISNULL(ext.cFree8, ''),ISNULL(ext.cFree9, ''),ISNULL(ext.cFree10, ''),a.TransSequence

                                SELECT DISTINCT Costre,WorkPoint,DepCode,WarehouseCode AS WHCode,MOCode,MUSER AS [User],SYSDATETIME() AS MTime,UpdateTodoQuantity,CompleteVerification FROM #TempERP
                                SELECT Costre,Costre2,TransSequence,Sequence,InvCode,Quantity,Amount,MODetailID,ProjectCode,BatchCode,Version,Brand,cFree1,cFree2,cFree3,cFree4,cFree5,cFree6,cFree7,cFree8,cFree9,cFree10
                                FROM #TempERP
																
								SELECT a.FromWarehouseCode AS WHCode,c.MODetailID+te.ProjectCode+te.BatchCode+te.Version+te.Brand+te.cFree1+te.cFree2+te.cFree3+te.cFree4+te.cFree5+te.cFree6+te.cFree7+te.cFree8+te.cFree9+te.cFree10 AS Costre2,a.TransCode,a.TransSequence AS Sequence,a.InvCode,SUM(c.Quantity/b.Quantity*a.Quantity) as Quantity,SUM((c.Quantity/b.Quantity*a.Quantity)*(c.Amount/c.Quantity)) AS Amount,c.PickID,ISNULL(ext.ProjectCode, '') AS ProjectCode,CASE WHEN (invBat.BatchEnable IS NULL AND ISNULL(inv.BatchEnable, '0')='1') OR ISNULL(invBat.BatchEnable, '0')='1' THEN ISNULL(ext.BatchCode, '') ELSE '' END AS BatchCode,ISNULL(ext.Version, '') AS Version,ISNULL(ext.Brand, '') AS Brand,ISNULL(ext.cFree1, '') AS cFree1,ISNULL(ext.cFree2, '') AS cFree2,ISNULL(ext.cFree3, '') AS cFree3,ISNULL(ext.cFree4, '') AS cFree4,ISNULL(ext.cFree5, '') AS cFree5,ISNULL(ext.cFree6, '') AS cFree6,ISNULL(ext.cFree7, '') AS cFree7,ISNULL(ext.cFree8, '') AS cFree8,ISNULL(ext.cFree9, '') AS cFree9,ISNULL(ext.cFree10, '') AS cFree10
	                            FROM ICSWareHouseLotInfoLog a
                                INNER JOIN ICSInventoryLot lot ON a.LotNo=lot.LotNo AND a.WorkPoint=lot.WorkPoint
	                            INNER JOIN ICSMO b ON b.MOCode=a.TransCode AND b.WorkPoint=a.WorkPoint
	                            INNER JOIN ICSMOPick c ON c.MODetailID=b.MODetailID AND c.WorkPoint=b.WorkPoint AND a.TransSequence=b.Sequence+'~'+c.Sequence
	                            INNER JOIN ICSExtension ext ON ext.ID=c.ExtensionID AND ext.WorkPoint=c.WorkPoint
	                            INNER JOIN ICSInventory inv ON a.InvCode=inv.InvCode AND a.WorkPoint=inv.WorkPoint
                              LEFT JOIN ICSInventoryBatchEnable invBat ON a.InvCode=invBat.InvCode AND a.ToWarehouseCode=invBat.WHCode AND a.WorkPoint=invBat.WorkPoint
                                INNER JOIN #TempERP te ON te.TransSequence=SUBSTRING(a.TransSequence,1,CHARINDEX('~',a.TransSequence)-1)
	                            WHERE a.Identification='{0}' AND a.TransType='12'
                                GROUP BY a.FromWarehouseCode,c.MODetailID,a.TransCode,a.TransSequence,a.InvCode,c.PickID,ISNULL(ext.ProjectCode, ''),CASE WHEN (invBat.BatchEnable IS NULL AND ISNULL(inv.BatchEnable, '0')='1') OR ISNULL(invBat.BatchEnable, '0')='1' THEN ISNULL(ext.BatchCode, '') ELSE '' END,ISNULL(ext.Version, ''),ISNULL(ext.Brand, ''),
                                ISNULL(ext.cFree1, ''),ISNULL(ext.cFree2, ''),ISNULL(ext.cFree3, ''),ISNULL(ext.cFree4, ''),ISNULL(ext.cFree5, ''),ISNULL(ext.cFree6, ''),ISNULL(ext.cFree7, ''),ISNULL(ext.cFree8, ''),ISNULL(ext.cFree9, ''),ISNULL(ext.cFree10, ''),a.TransSequence,te.ProjectCode,te.BatchCode,te.Version,te.Brand,te.cFree1,te.cFree2,te.cFree3,te.cFree4,te.cFree5,te.cFree6,te.cFree7,te.cFree8,te.cFree9,te.cFree10

                                DROP TABLE #TempERP";
                sql = string.Format(sql, Identification, BusinessCode);
                DataSet ds = DBHelper.SQlReturnDataSet(sql, cmd);

                string Inputstr = DataToJsonHelper.DataSetToJson(ds, "details", "Costre", "detailss", "Costre2");
                string resultStr = HTTPHelper.HttpPost(TransType, ERPUrl.ManufactureReceiveDocURL, Inputstr);
                Result result = new Result();
                result = JsonConvert.DeserializeObject<Result>(resultStr);
                if (result.Success)
                {
                    try
                    {
                        JArray res = (JArray)JsonConvert.DeserializeObject(result.Data.ToString());
                        foreach (var item in res)
                        {
                            JObject jo = (JObject)item;
                            JArray resdetail = (JArray)JsonConvert.DeserializeObject(jo["details"].ToString());
                            foreach (var detail in resdetail)
                            {
                                JObject det = (JObject)detail;
                                string allcol = "" + det["ProjectCode"].ToString() + det["cBatch"].ToString() + det["version"].ToString() + det["brand"].ToString() + det["cFree1"].ToString() + det["cFree2"].ToString() + det["cFree3"].ToString() + det["cFree4"].ToString() + det["cFree5"].ToString()
                                + det["cFree6"].ToString() + det["cFree7"].ToString() + det["cFree8"].ToString() + det["cFree9"].ToString() + det["cFree10"].ToString();
                                ICSWareHouseLotInfoService.WareHouseLotInfoLogUpdate(TransType, det["MODetailID"].ToString(), Identification, jo["ID"].ToString(),
                                    det["DetailID"].ToString(), jo["MRCVCode"].ToString(), det["Sequence"].ToString(), allcol, cmd, language, BusinessCode);
                                JArray resdetails = (JArray)JsonConvert.DeserializeObject(det["detailss"].ToString());
                                foreach (var details in resdetails)
                                {
                                    JObject dets = (JObject)details;
                                    if (dets != null)
                                    {
                                        //直接回写
                                        string ERPupdate = @"UPDATE a set ERPID='{2}',ERPDetailID='{3}',ERPCode='{4}',ERPSequence='{5}',ERPUpload='1'
                                                FROM ICSWareHouseLotInfoLog a
                                                LEFT JOIN ICSMO b ON a.TransCode=b.MOCode AND a.WorkPoint=b.WorkPoint
                                                LEFT JOIN ICSMOPick c ON b.MODetailID=c.MODetailID AND b.WorkPoint=c.WorkPoint AND a.TransSequence=b.Sequence+'~'+c.Sequence
                                                WHERE c.PickID='{0}' and a.Identification='{1}' AND  ERPUpload='0' AND a.BusinessCode ='{6}'";
                                        ERPupdate = string.Format(ERPupdate, dets["SourceDetailID"].ToString(), Identification, dets["IDs"].ToString(), dets["ERPDetailID"].ToString(), dets["MRCVCode"].ToString()
                                            , dets["Sequence"].ToString(), BusinessCode);

                                        if (!DBHelper.ExecuteNonQuery(ERPupdate, cmd))
                                        {
                                            throw new Exception(language.GetNameByCode("WMSAPIInfo079"));//"成品倒冲回写失败!";
                                        }
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        log.Debug(ex.ToString());
                        log.Debug(resultStr);
                        throw new Exception(language.GetNameByCode("WMSAPIInfo200") + ex);
                    }
                }
                else
                {
                    throw new Exception(language.GetNameByCode("WMSAPIInfo080") + result.Message);
                }
                #endregion
            }
            catch (Exception)
            {
                throw;
            }
        }
        #endregion

        #region 开立的生产入库单
        /// <summary>
        /// 开立的生产入库单
        /// </summary>
        /// <param name="TransCode"></param>
        /// <param name="TransSequence"></param>
        /// <param name="Quantity"></param>
        /// <param name="WorkPoint"></param>
        /// <param name="cmd"></param>
        public static void ManufactureReceive(string LotNo, string Quantity, string WorkPoint, SqlCommand cmd, Dictionary<string, string> language)
        {
            try
            {
                string sql = @"DECLARE @Status VARCHAR(10)
                                SELECT @Status=c.Status FROM ICSInventoryLot a
                                INNER JOIN ICSInventoryLotDetail b ON a.LotNo=b.LotNo AND a.WorkPoint=b.WorkPoint
                                INNER JOIN ICSManufactureReceive c ON b.TransCode=c.RCVCode AND b.TransSequence=c.Sequence AND b.WorkPoint=c.WorkPoint
                                WHERE a.LotNo='{0}' AND a.WorkPoint='{1}' AND c.Type='1'

                                IF (@Status IS NULL)
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo081") + @"',16,1);
                                    RETURN
                                END
                                ELSE IF (@Status!='1')
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo137") + @"',16,1);
                                    RETURN
                                END
                               UPDATE c SET RCVQuantity=ISNULL(RCVQuantity,0)+'{2}'
                                FROM ICSInventoryLot a
                                INNER JOIN ICSInventoryLotDetail b ON a.LotNo=b.LotNo AND a.WorkPoint=b.WorkPoint
                                INNER JOIN ICSManufactureReceive c ON b.TransCode=c.RCVCode AND b.TransSequence=c.Sequence AND b.WorkPoint=c.WorkPoint
                                WHERE a.LotNo='{0}' AND a.WorkPoint='{1}' AND c.Type='1'
                                IF EXISTS(SELECT a.LotNo FROM ICSInventoryLot a
                                    INNER JOIN ICSInventoryLotDetail b ON a.LotNo=b.LotNo AND a.WorkPoint=b.WorkPoint
                                    INNER JOIN ICSManufactureReceive c ON b.TransCode=c.RCVCode AND b.TransSequence=c.Sequence AND b.WorkPoint=c.WorkPoint
                                    WHERE a.LotNo='{0}' AND a.WorkPoint='{1}' AND c.Type='1' AND c.Quantity<c.RCVQuantity)
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo083") + @"',16,1);
                                END";
                sql = string.Format(sql, LotNo, WorkPoint, Quantity);
                if (!DBHelper.ExecuteNonQuery(sql, cmd))
                {
                    throw new Exception(language.GetNameByCode("WMSAPIInfo138"));//"生产入库单更新失败!");
                }
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 开立的生产入库单(货柜)
        /// </summary>
        /// <param name="TransCode"></param>
        /// <param name="TransSequence"></param>
        /// <param name="Quantity"></param>
        /// <param name="WorkPoint"></param>
        /// <param name="cmd"></param>
        public static void ManufactureReceiveForHG(string TransCode, string TransLine, string WorkPoint, SqlCommand cmd, Dictionary<string, string> language,string quantity)
        {
            try
            {
                decimal iquantity = Convert.ToDecimal(quantity);
                string sql = @"IF EXISTS (SELECT ID FROM ICSManufactureReceive WHERE RCVQuantity=Quantity AND RCVCode='{0}' and Sequence='{1}' and WorkPoint='{2}' )
                               BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo471") + @"',16,1);
                                    RETURN
                                END;
                               UPDATE  ICSManufactureReceive set RCVQuantity=RCVQuantity+{3}
                               Where RCVCode='{0}' and Sequence='{1}' and WorkPoint='{2}'";
                sql = string.Format(sql, TransCode, TransLine, WorkPoint, iquantity);
                if (!DBHelper.ExecuteNonQuery(sql, cmd))
                {
                    throw new Exception(language.GetNameByCode("WMSAPIInfo138"));//"生产入库单更新失败!");
                }
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 开立的生产入库单
        /// </summary>
        /// <param name="TransType"></param>
        /// <param name="Identification"></param>
        /// <param name="cmd"></param>
        public static void ManufactureReceiveERP(string TransType, string Identification, SqlCommand cmd, Dictionary<string, string> language, string BusinessCode)
        {
            try
            {
                #region SAP(三层结构)
                string IsSuccess = "";
                string ErrorMessage = "";
                string sql = @" select Distinct A.RCVCode,A.WorkPoint from ICSManufactureReceive A
                                LEFT JOIN ICSWareHouseLotInfoLog B ON B.TransCode=A.RCVCode AND B.WorkPoint=A.WorkPoint
                                where B.Identification='{0}' AND BusinessCode='18'";
                sql = string.Format(sql, Identification);
                DataTable dt = DBHelper.SQlReturnData(sql, cmd);
                if (dt.Rows.Count > 1)
                {
                    throw new Exception(language.GetNameByCode("WMSAPIInfo202"));//单次提交单据数量卡控(只允许一张单据)
                }
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    string chksql = @"select SUM(Quantity) AS Quantity,SUM(RCVQuantity) AS RCVQuantity from ICSManufactureReceive
                                      where RCVCode='{0}' and WorkPoint='{1}'
                                      GROUP BY RCVCode,WorkPoint";
                    chksql = string.Format(chksql, dt.Rows[i]["RCVCode"].ToString(), dt.Rows[i]["WorkPoint"].ToString());
                    DataTable chkdt = DBHelper.SQlReturnData(chksql, cmd);
                    if (Convert.ToDecimal(chkdt.Rows[0]["Quantity"]) == Convert.ToDecimal(chkdt.Rows[0]["RCVQuantity"]))
                    {
                        SAPCallBackDocVPN.ZWMS_SK_WS_PZ Client = new SAPCallBackDocVPN.ZWMS_SK_WS_PZ();
                        SAPCallBackDocVPN.ZWMS_SK_WS_PZ1 Info = new SAPCallBackDocVPN.ZWMS_SK_WS_PZ1();
                        Info.NEWID = Identification;
                        Info.DANJU = dt.Rows[i]["RCVCode"].ToString();
                        Info.STATE = "0";
                        List<SAPCallBackDocVPN.ZWMS_PZ> ItemList = new List<SAPCallBackDocVPN.ZWMS_PZ>();
                        List<SAPCallBackDocVPN.ZWEBS_GERNR> ItemLineList = new List<SAPCallBackDocVPN.ZWEBS_GERNR>();
                        Info.Z_FLAG = new SAPCallBackDocVPN.ZWEB_RETURN[1];
                        sql = @"select A.RCVCode,A.SAPSequence,A.InvCode,A.Sequence,A.Quantity,A.RCVQuantity
                            ,ISNULL(B.BatchCode,'') AS BatchCode from ICSManufactureReceive A
                            LEFT JOIN ICSExtension B ON B.ID=A.ExtensionID AND B.WorkPoint=A.WorkPoint
                            WHERE RCVCode='{0}' AND A.WorkPoint='{1}'";
                        sql = string.Format(sql, dt.Rows[i]["RCVCode"].ToString(), dt.Rows[i]["WorkPoint"].ToString());
                        DataTable Sapdt = DBHelper.SQlReturnData(sql, cmd);
                        foreach (DataRow dr in Sapdt.Rows)
                        {
                            if (Convert.ToDecimal(dr["Quantity"].ToString()) == Convert.ToDecimal(dr["RCVQuantity"].ToString()))
                            {
                                SAPCallBackDocVPN.ZWMS_PZ Item = new SAPCallBackDocVPN.ZWMS_PZ();
                                SAPCallBackDocVPN.ZWEBS_GERNR ItemLine = new SAPCallBackDocVPN.ZWEBS_GERNR();
                                Item.DANJU = dr["RCVCode"].ToString();
                                Item.POSNR = dr["SAPSequence"].ToString();
                                Item.LINGYSL = System.Decimal.Round(Convert.ToDecimal(dr["Quantity"].ToString()), 3);
                                ItemList.Add(Item);
                                if (dr["BatchCode"].ToString() != "")
                                {
                                    ItemLine.DANJU = dr["RCVCode"].ToString();
                                    ItemLine.POSNR = dr["SAPSequence"].ToString();
                                    ItemLine.MATNR = dr["InvCode"].ToString();
                                    ItemLine.GERNR = dr["BatchCode"].ToString();
                                    ItemLineList.Add(ItemLine);
                                }
                            }
                        }
                        if (ItemList.Count > 0)
                        {
                            Info.Z_ITEM = ItemList.ToArray();
                            if (ItemLineList.Count > 0)
                            {
                                Info.Z_GERNR = ItemLineList.ToArray();
                            }
                            else
                            {
                                Info.Z_GERNR = new SAPCallBackDocVPN.ZWEBS_GERNR[1];
                            }
                            SAPCallBackDocVPN.ZWMS_SK_WS_PZResponse result = new SAPCallBackDocVPN.ZWMS_SK_WS_PZResponse();
                            result = Client.CallZWMS_SK_WS_PZ(Info);
                            if (result.Z_NULL == "N")
                            {
                                foreach (SAPCallBackDocVPN.ZWEB_RETURN resultItem in result.Z_FLAG)
                                {
                                    IsSuccess = "N";
                                    ErrorMessage += resultItem.L_MESSAGE + "/r/n";
                                }
                            }
                        }
                    }
                }
                if (IsSuccess == "N")
                {
                    throw new Exception(ErrorMessage);
                }
                #endregion
            }
            catch (Exception)
            {
                throw;
            }
        }
        #endregion

        #region 返工工单
        /// <summary>
        /// 返工工单
        /// </summary>
        /// <param name="TransCode"></param>
        /// <param name="TransSequence"></param>
        /// <param name="Quantity"></param>
        /// <param name="WorkPoint"></param>
        /// <param name="cmd"></param>
        public static void ReWorkReceiveMo(string LotNo, string Quantity, string WarehouseCode,
            string LocationCode, string WorkPoint, String User, string BusinessCode, SqlCommand cmd, Dictionary<string, string> language)
        {
            try
            {
                string sql = @"DECLARE @Status VARCHAR(10)
                                SELECT @Status=c.ERPStatus FROM ICSInventoryLot a
                                INNER JOIN ICSInventoryLotDetail b ON a.LotNo=b.LotNo AND a.WorkPoint=b.WorkPoint
                                INNER JOIN ICSMO c ON b.TransCode=c.MOCode AND b.WorkPoint=c.WorkPoint
                                INNER JOIN ICSMOPick d ON d.MODetailID=c.MODetailID   AND b.WorkPoint=c.WorkPoint and b.TransSequence=c.Sequence+'-'+d.Sequence            
                                WHERE a.LotNo='{0}' AND a.WorkPoint='{1}'

                                IF (@Status IS NULL)
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo081") + @"',16,1);
                                    RETURN
                                END
                                ELSE IF (@Status='3')
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo082") + @"',16,1);
                                    RETURN
                                END
                               UPDATE d SET IssueQuantity=ISNULL(IssueQuantity,0)+'{2}'
                                FROM ICSInventoryLot a
                                INNER JOIN ICSInventoryLotDetail b ON a.LotNo=b.LotNo AND a.WorkPoint=b.WorkPoint
                                INNER JOIN ICSMO c ON b.TransCode=c.MOCode  AND b.WorkPoint=c.WorkPoint
                                INNER JOIN ICSMOPick d ON d.MODetailID=c.MODetailID  AND d.WorkPoint=c.WorkPoint and b.TransSequence=c.Sequence+'-'+d.Sequence
                                WHERE a.LotNo='{0}' AND a.WorkPoint='{1}'
                                IF EXISTS(SELECT a.LotNo FROM ICSInventoryLot a
                                    INNER JOIN ICSInventoryLotDetail b ON a.LotNo=b.LotNo AND a.WorkPoint=b.WorkPoint
                                    INNER JOIN ICSMO c ON b.TransCode=c.MOCode  AND b.WorkPoint=c.WorkPoint
                                    INNER JOIN ICSMOPick d ON d.MODetailID=c.MODetailID   AND d.WorkPoint=c.WorkPoint and b.TransSequence=c.Sequence+'-'+d.Sequence   
                                    WHERE a.LotNo='{0}' AND a.WorkPoint='{1}' AND d.IssueQuantity>d.Quantity)
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo083") + @"',16,1);
                                END";
                sql = string.Format(sql, LotNo, WorkPoint, Quantity);
                if (!DBHelper.ExecuteNonQuery(sql, cmd))
                {
                    throw new Exception(language.GetNameByCode("WMSAPIInfo366"));//"生产工单更新失败!");
                }
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 返工工单
        /// </summary>
        /// <param name="TransType"></param>
        /// <param name="Identification"></param>
        /// <param name="cmd"></param>
        public static void ReWorkReceiveMoERP(string TransType, string Identification, SqlCommand cmd, Dictionary<string, string> language, string BusinessCode)
        {
            try
            {
                #region ERP开立状态单据审核
                String sql = @"SELECT c.DepCode+a.ToWarehouseCode+c.MOCode+a.MUSER AS Costre,c.DepCode,a.ToWarehouseCode AS WarehouseCode,c.MOCode,a.MUSER,d.Sequence AS Sequence,
                                    a.InvCode,SUM(a.Quantity) AS Quantity,0 AS Amount,d.PickID AS MODetailID,Enable AS UpdateTodoQuantity
                                ,a.WorkPoint,ISNULL(ext.ProjectCode, '') AS ProjectCode,CASE WHEN (invBat.BatchEnable IS NULL AND ISNULL(inv.BatchEnable, '0')='1') OR ISNULL(invBat.BatchEnable, '0')='1' THEN ISNULL(ext.BatchCode, '') ELSE '' END AS BatchCode,ISNULL(ext.Version, '') AS Version,ISNULL(ext.Brand, '') AS Brand,
	                            ISNULL(ext.cFree1, '') AS cFree1,ISNULL(ext.cFree2, '') AS cFree2,ISNULL(ext.cFree3, '') AS cFree3,ISNULL(ext.cFree4, '') AS cFree4,ISNULL(ext.cFree5, '') AS cFree5,ISNULL(ext.cFree6, '') AS cFree6,ISNULL(ext.cFree7, '') AS cFree7,ISNULL(ext.cFree8, '') AS cFree8,ISNULL(ext.cFree9, '') AS cFree9,ISNULL(ext.cFree10, '') AS cFree10                                   
                                INTO #TempERP
                                FROM ICSWareHouseLotInfoLog a
                                INNER JOIN ICSInventoryLot lot ON a.LotNo=lot.LotNo AND a.WorkPoint=lot.WorkPoint
                                INNER JOIN ICSExtension ext ON lot.ExtensionID=ext.ID AND lot.WorkPoint=ext.WorkPoint
                                INNER JOIN ICSInventory inv ON a.InvCode=inv.InvCode AND a.WorkPoint=inv.WorkPoint
                                LEFT JOIN ICSInventoryBatchEnable invBat ON a.InvCode=invBat.InvCode AND a.ToWarehouseCode=invBat.WHCode AND a.WorkPoint=invBat.WorkPoint
                                INNER JOIN ICSInventoryLotDetail b ON a.LotNo=b.LotNo AND a.WorkPoint=b.WorkPoint
                                INNER JOIN ICSMO c ON b.TransCode=c.MOCode  AND b.WorkPoint=c.WorkPoint
                                INNER JOIN ICSMOPick d ON d.MODetailID=c.MODetailID  AND d.WorkPoint=c.WorkPoint and b.TransSequence=c.Sequence+'-'+d.Sequence
                                INNER JOIN ICSConfiguration con ON con.Code='Stock001' AND a.WorkPoint=con.WorkPoint
                                WHERE a.Identification='{0}' AND  ERPUpload='0' AND BusinessCode='{1}'
                                GROUP BY c.DepCode,a.ToWarehouseCode,c.MOCode,a.MUSER,a.InvCode,d.PickID,Enable,d.Sequence
                                ,a.WorkPoint,ISNULL(ext.ProjectCode, ''),CASE WHEN (invBat.BatchEnable IS NULL AND ISNULL(inv.BatchEnable, '0')='1') OR ISNULL(invBat.BatchEnable, '0')='1' THEN ISNULL(ext.BatchCode, '') ELSE '' END,ISNULL(ext.Version, ''),ISNULL(ext.Brand, ''),
                                ISNULL(ext.cFree1, ''),ISNULL(ext.cFree2, ''),ISNULL(ext.cFree3, ''),ISNULL(ext.cFree4, ''),ISNULL(ext.cFree5, ''),ISNULL(ext.cFree6, ''),ISNULL(ext.cFree7, ''),ISNULL(ext.cFree8, ''),ISNULL(ext.cFree9, ''),ISNULL(ext.cFree10, '')

                                SELECT DISTINCT Costre,WorkPoint,DepCode,WarehouseCode AS WHCode,MOCode,MUSER AS [User],SYSDATETIME() AS MTime,UpdateTodoQuantity FROM #TempERP
                                SELECT Costre,Sequence,InvCode,Quantity,Amount,MODetailID,ProjectCode,BatchCode,Version,Brand,cFree1,cFree2,cFree3,cFree4,cFree5,cFree6,cFree7,cFree8,cFree9,cFree10
                                FROM #TempERP

                                DROP TABLE #TempERP";
                sql = string.Format(sql, Identification, BusinessCode);
                DataSet ds = DBHelper.SQlReturnDataSet(sql, cmd);

                string Inputstr = DataToJsonHelper.DataSetToJson(ds, "details", "Costre");
                string resultStr = HTTPHelper.HttpPost(TransType, ERPUrl.ICSReWorkReceiveMoURL, Inputstr);
                Result result = new Result();
                result = JsonConvert.DeserializeObject<Result>(resultStr);
                if (result.Success)
                {
                    try
                    {
                        JArray res = (JArray)JsonConvert.DeserializeObject(result.Data.ToString());
                        foreach (var item in res)
                        {
                            JObject jo = (JObject)item;
                            JArray resdetail = (JArray)JsonConvert.DeserializeObject(jo["details"].ToString());
                            foreach (var detail in resdetail)
                            {
                                JObject det = (JObject)detail;
                                string col = jo["cWhCode"].ToString() + det["ProjectCode"].ToString() + det["cBatch"].ToString() + det["version"].ToString() + det["brand"].ToString() + det["cFree1"].ToString() + det["cFree2"].ToString() + det["cFree3"].ToString() + det["cFree4"].ToString() + det["cFree5"].ToString()
                                    + det["cFree6"].ToString() + det["cFree7"].ToString() + det["cFree8"].ToString() + det["cFree9"].ToString() + det["cFree10"].ToString();
                                ICSWareHouseLotInfoService.WareHouseLotInfoLogUpdate(TransType, det["MODetailID"].ToString(), Identification, jo["ID"].ToString(),
                                    det["DetailID"].ToString(), jo["MRCVCode"].ToString(), det["Sequence"].ToString(), col, cmd, language, BusinessCode);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        log.Debug(ex.ToString());
                        log.Debug(resultStr);
                    }
                }
                else
                {
                    throw new Exception(language.GetNameByCode("WMSAPIInfo080") + result.Message);
                }
                #endregion
            }
            catch (Exception)
            {
                throw;
            }
        }
        #endregion
    }
}