using ICSSoft.Common;
using ICSSoft.Entity;
using Newtonsoft.Json;
using NFine.Code;
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 ICSSubmitService
    {
        private static log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        private static string connString = System.Configuration.ConfigurationManager.AppSettings["ConnStr"];
        private static string enableCode = "";
        private static string excessQtySql = "";

        #region 源头单据信息
        /// <summary>
        /// 源头单据信息
        /// </summary>
        /// <param name="JsonData"></param>
        /// <returns></returns>
        public static DataTable TransInformationGet(WMSSourceDocumentModel JsonData)
        {
            var language = LanguageHelper.GetName("WMSAPIInfo");
            using (SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString))
            {
                conn.Open();
                string sql = string.Empty;
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = conn;
                cmd.CommandTimeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["TimeOut"]);
                try
                {
                    if (string.IsNullOrEmpty(JsonData.TransCode))
                    {
                        throw new Exception(language.GetNameByCode("WMSAPIInfo001"));//"单据号不能为空!"
                    }
                    else if (string.IsNullOrEmpty(JsonData.TransType))
                    {
                        throw new Exception(language.GetNameByCode("WMSAPIInfo002"));//"单据类型不能为空!"
                    }
                    else if (!EnumHelper.HasDescriptions(typeof(TransTypeEnum), JsonData.TransType))
                    {
                        throw new Exception(language.GetNameByCode("WMSAPIInfo003"));//"单据类型不存在!"
                    }
                    else if (string.IsNullOrEmpty(JsonData.WorkPoint))
                    {
                        throw new Exception(language.GetNameByCode("WMSAPIInfo004"));//"站点不能为空!"
                    }

                    string TransType = JsonData.TransType;
                    #region SLQ
                    string sqlCheck = @"IF NOT EXISTS(SELECT a.ID FROM {1} WHERE {2})
                                    BEGIN
	                                    RAISERROR('" + language.GetNameByCode("WMSAPIInfo035") + @"',16,1);
                                        RETURN
                                    END
                                    ";

                    if (TransType == TransTypeEnum.ASN.GetDescription()|| TransType == TransTypeEnum.OASN.GetDescription())
                    {
                         sql = @"SELECT a.ID,
                                    {0}
                                    convert(varchar(100),'') AS LocationCode,
                                    convert(varchar(100),'') AS LotNo,
                                    convert(varchar(10),'') AS ToWarehouseCode,
									0 AS LocationQty,
                                    0 AS isMatched,
                                    a.InvCode,
                                    inv.InvName,
                                    inv.InvStd,
                                    a.Quantity,
                                    inv.InvUnit,
                                    a.Amount,
                                    --a.WHCode,
                                    inv.AmountUnit,
                                    --wh.WarehouseName AS WHName,
                                    ISNULL(ext.ProjectCode, '') AS ProjectCode,
                                    a.ExtensionID,
                                    --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,
                                    a.MUSER AS [User],
                                    a.MTIME AS [MTime]
                                    {4}
                                    FROM {1}
                                    INNER JOIN ICSExtension ext ON a.ExtensionID=ext.ID AND a.WorkPoint=ext.WorkPoint
                                    INNER JOIN ICSInventory inv ON a.InvCode=inv.InvCode AND a.WorkPoint=inv.WorkPoint
                                    --LEFT JOIN ICSWarehouse wh ON a.WHCode=wh.WarehouseCode AND a.WorkPoint=wh.WorkPoint
                                    --LEFT JOIN ICSInventoryBatchEnable invBat ON a.InvCode=invBat.InvCode AND a.WHCode=invBat.WHCode AND a.WorkPoint=invBat.WorkPoint
                                    WHERE {2} ";
                    }
                    else
                    {
                        sql = @"SELECT a.ID,
                                    {0}
                                    convert(varchar(100),'') AS LocationCode,
                                    convert(varchar(100),'') AS LotNo,
                                    convert(varchar(10),'') AS ToWarehouseCode,
									0 AS LocationQty,
                                    0 AS isMatched,
                                    a.InvCode,
                                    inv.InvName,
                                    inv.InvStd,
                                    a.Quantity,
                                    inv.InvUnit,
                                    a.Amount,
                                    a.WHCode,
                                    inv.AmountUnit,
                                    wh.WarehouseName AS WHName,
                                    ISNULL(ext.ProjectCode, '') AS ProjectCode,
                                    a.ExtensionID,
                                    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,
                                    a.MUSER AS [User],
                                    a.MTIME AS [MTime]
                                    {4}
                                    FROM {1}
                                    INNER JOIN ICSExtension ext ON a.ExtensionID=ext.ID AND a.WorkPoint=ext.WorkPoint
                                    INNER JOIN ICSInventory inv ON a.InvCode=inv.InvCode AND a.WorkPoint=inv.WorkPoint
                                    LEFT JOIN ICSWarehouse wh ON a.WHCode=wh.WarehouseCode AND a.WorkPoint=wh.WorkPoint
                                    LEFT JOIN ICSInventoryBatchEnable invBat ON a.InvCode=invBat.InvCode AND a.WHCode=invBat.WHCode AND a.WorkPoint=invBat.WorkPoint
                                    WHERE {2} ";
                    }
                        

                    string Picksql = @"SELECT row_number() over (order by c.Code,c.InvCode,d.MTIME,d.LotNO) AS rowNo,
	                        c.Code,
	                        c.InvCode,
	                        c.InvName,
	                        c.InvStd,
c.InvUnit,
	                        FLOOR(c.iQuantity) AS iQuantity,
	                        d.WarehouseCode,
	                        d.LocationCode,
	                        d.LotNO,
	                        FLOOR(ISNULL(d.Quantity, 0)) AS QTY,
	                        CONVERT(varchar(100),d.MTIME, 23) MTIME,
	                        FLOOR(f.QTYTotal) QTYTotal  INTO #temp 
                        FROM
                        ({0}) c
                        LEFT JOIN ICSWareHouseLotInfo d ON c.InvCode=d.INVCode  AND ((LEN(ISNULL(c.WHCode,''))<=0) OR (LEN(ISNULL(c.WHCode,''))>0) AND c.WhCode=d.WarehouseCode)  AND d.WorkPoint='{1}' AND d.Quantity>0
                        left join ICSInventoryLot m on d.LotNo=m.LotNo and d.WorkPoint=m.WorkPoint and c.ExtensionID=m.ExtensionID
                        LEFT JOIN (SELECT INVCode,WarehouseCode,SUM(Quantity) AS QTYTotal FROM ICSWareHouseLotInfo  WHERE WorkPoint='{1}' GROUP BY INVCode,WarehouseCode) f ON c.InvCode=f.INVCode AND c.WhCode=f.WarehouseCode
                        

DECLARE @ItemCode VARCHAR(50),
	@QTY DECIMAL(18,3), 
	@ItemCodeCurrent VARCHAR(50),
	@QTYCurrent DECIMAL(18,3),
	@iQuantityCurrent DECIMAL(18,3),
	@CanDelete BIT,
	@Row INT,
	@rowCurrent INT
SET @Row = @@rowcount
SET @rowCurrent=1
SET @CanDelete=0
SET @ItemCode=''

WHILE @rowCurrent<=@Row
	BEGIN
		SELECT @ItemCodeCurrent=InvCode,@QTYCurrent=QTY,@iQuantityCurrent=iQuantity FROM #temp WHERE rowNo=@rowCurrent

PRINT(@rowCurrent)
		IF @ItemCode<>@ItemCodeCurrent
		BEGIN
			SET @ItemCode=@ItemCodeCurrent
			SET @QTY=0
			SET @CanDelete=0
		END

		IF @CanDelete=1 
		BEGIN
			DELETE FROM #temp WHERE rowNo=@rowCurrent
			SET @rowCurrent += 1
			CONTINUE
		END

		SET @QTY += @QTYCurrent
		IF @QTY>=@iQuantityCurrent
		BEGIN
			SET @CanDelete=1 
		END
		
		SET @rowCurrent += 1
	END
SELECT * FROM #temp
DROP TABLE #temp
";
                    #endregion

                    bool isDeliveryNotice = false;      //送货、到货、含委外
                    string columns = string.Empty;      //查询源头单据表的特殊列名
                    string tableName = string.Empty;    //查询源头单据表名
                    string where = string.Empty;        //查询源头单据的过滤条件
                    bool isMerge = false;               //合并发料
                    string columnsMerge = string.Empty;      //合并发料查询源头单据表的特殊列名
                    string tableNameMerge = string.Empty;    //合并发料查询源头单据表名
                    string sqls= string.Empty;
                    string sqlCheckSign = "";
                    DataTable flag =null;

                    #region 检料表信息
                    if (TransType == TransTypeEnum.MOIssueDoc.GetDescription())
                    {
                        enableCode = "Over001";
                        excessQtySql = ",(dbo.GetExcessQty(a.InvCode, b.Sequence+'~'+a.Sequence, b.MOCode, a.WorkPoint,'"+enableCode+"')) AS excessQty";
                        #region 工单备料sql
                        sqls = @" SELECT
	                        c.MOCode as Code,
	                        a.InvCode,
	                        b.InvName,
	                        b.InvStd,
	                        SUM(ISNULL(a.Quantity, 0)) AS iQuantity,
	                        a.WhCode,
b.InvUnit,
							a.ExtensionID
                        FROM
	                        ICSMOPick a
							inner join ICSMO c on a.MODetailID=c.MODetailID and a.WorkPoint=c.WorkPoint
                            LEFT JOIN ICSINVENTORY b ON a.InvCode = b.InvCode AND a.WorkPoint=b.WorkPoint
                            WHERE  c.MOCode  in ({0}) AND a.WorkPoint = '{1}'
                            GROUP BY c.MOCode,a.InvCode,b.InvName,b.InvStd,b.InvUnit,a.WhCode,a.ExtensionID";
                        #endregion
                    }
                    if (TransType == TransTypeEnum.MOApply.GetDescription())
                    {
                        enableCode = "Over002";
                        excessQtySql = ",(dbo.GetExcessQty(a.InvCode, a.Sequence, a.ApplyCode, a.WorkPoint,'" + enableCode + "')) AS excessQty";
                        #region 工单领料SQL
                        sqls = @"   select
	                        a.ApplyCode as Code,
	                        a.InvCode,
	                        b.InvName,
	                        b.InvStd,
b.InvUnit,
	                        SUM(ISNULL(a.Quantity, 0)) AS iQuantity,
	                        a.WhCode,
							a.ExtensionID
                        FROM
	                        ICSMOApply a
                        LEFT JOIN ICSINVENTORY b ON a.InvCode = b.InvCode AND a.WorkPoint=b.WorkPoint
                        WHERE a.ApplyCode in ({0}) AND a.WorkPoint = '{1}'
                        GROUP BY a.ApplyCode,a.InvCode,b.InvName,b.InvStd,b.InvUnit,a.WhCode,a.ExtensionID";
                        #endregion
                    }
                    if (TransType == TransTypeEnum.MOIssue.GetDescription())
                    {
                        //enableCode = "Over003";
                        excessQtySql = "";
                        #region 工单材料出库SQL
                        sqls = @"  select
	                        a.IssueCode as Code,
	                        a.InvCode,
	                        b.InvName,
	                        b.InvStd,
b.InvUnit,
	                        SUM(ISNULL(a.Quantity, 0)) AS iQuantity,
	                        a.WhCode,
							a.ExtensionID
                        FROM
	                        ICSMOIssue a
                        LEFT JOIN ICSINVENTORY b ON a.InvCode = b.InvCode AND a.WorkPoint=b.WorkPoint
                        WHERE a.IssueCode in ({0}) AND a.WorkPoint = '{1}'
                        GROUP BY a.IssueCode,a.InvCode,b.InvName,b.InvStd,b.InvUnit,a.WhCode,a.ExtensionID";
                        #endregion
                    }
                    if (TransType == TransTypeEnum.OutsourcingIssueDoc.GetDescription())
                    {
                        enableCode = "Over004";
                        excessQtySql = ",(dbo.GetExcessQty(a.InvCode, b.Sequence+'~'+a.Sequence, b.OOCode, a.WorkPoint,'" + enableCode + "')) AS excessQty";
                        #region 委外备料SQL
                        sqls = @"   								select
	                        c.OOCode as Code,
	                        a.InvCode,
	                        b.InvName,
	                        b.InvStd,
b.InvUnit,
	                        SUM(ISNULL(a.Quantity, 0)) AS iQuantity,
	                        a.WhCode,
													a.ExtensionID
                        FROM
	                        ICSOOPick a
							left join ICSOutsourcingOrder c on a.OODetailID=c.OODetailID and a.WorkPoint=c.WorkPoint
                        LEFT JOIN ICSINVENTORY b ON a.InvCode = b.InvCode AND a.WorkPoint=b.WorkPoint
                     WHERE c.OOCode in ({0}) AND a.WorkPoint = '{1}'
                        GROUP BY c.OOCode,a.InvCode,b.InvName,b.InvStd,b.InvUnit,a.WhCode,	a.ExtensionID";
                        #endregion
                    }
                    if (TransType == TransTypeEnum.OOApply.GetDescription())
                    {
                        enableCode = "Over005";
                        excessQtySql = ",(dbo.GetExcessQty(a.InvCode, a.Sequence, a.ApplyCode, a.WorkPoint,'" + enableCode + "')) AS excessQty";
                        #region 委外领料SQL
                        sqls = @"   	select
	                        a.ApplyCode as Code,
	                        a.InvCode,
	                        b.InvName,
	                        b.InvStd,
b.InvUnit,
	                        SUM(ISNULL(a.Quantity, 0)) AS iQuantity,
	                        a.WhCode,
													a.ExtensionID
                        FROM
	                        ICSOApply a
                        LEFT JOIN ICSINVENTORY b ON a.InvCode = b.InvCode AND a.WorkPoint=b.WorkPoint
                        WHERE a.ApplyCode in ({0}) AND a.WorkPoint = '{1}'
                        GROUP BY a.ApplyCode,a.InvCode,b.InvName,b.InvStd,b.InvUnit,a.WhCode,a.ExtensionID";
                        #endregion
                    }
                    if (TransType == TransTypeEnum.OOIssue.GetDescription())
                    {
                        //enableCode = "Over006";
                        excessQtySql = "";
                        #region 委外材料出库SQL
                        sqls = @" 	select
	                        a.IssueCode as Code,
	                        a.InvCode,
	                        b.InvName,
	                        b.InvStd,
b.InvUnit,
	                        SUM(ISNULL(a.Quantity, 0)) AS iQuantity,
	                        a.WhCode,
a.ExtensionID
                        FROM
	                        ICSOIssue a
                        LEFT JOIN ICSINVENTORY b ON a.InvCode = b.InvCode AND a.WorkPoint=b.WorkPoint
                     WHERE a.IssueCode in ({0}) AND a.WorkPoint = '{1}'
                        GROUP BY a.IssueCode,a.InvCode,b.InvName,b.InvStd,b.InvUnit,a.WhCode,a.ExtensionID";
                        #endregion
                    }
                    if (TransType == TransTypeEnum.SalesShipmentDoc.GetDescription())
                    {
                        enableCode = "";
                        excessQtySql = "";
                        #region 销售发货SQL
                        sqls = @"   select
	                        a.SDNCode as Code,
	                        a.InvCode,
	                        b.InvName,
	                        b.InvStd,
b.InvUnit,
	                        SUM(ISNULL(a.Quantity, 0)) AS iQuantity,
	                        a.WhCode,
a.ExtensionID
                        FROM
	                        ICSSDN a
                        LEFT JOIN ICSINVENTORY b ON a.InvCode = b.InvCode AND a.WorkPoint=b.WorkPoint
                     WHERE a.SDNCode in ({0}) AND a.WorkPoint = '{1}'
                        GROUP BY a.SDNCode,a.InvCode,b.InvName,b.InvStd,b.InvUnit,a.WhCode,a.ExtensionID";
                        #endregion
                    }
                    if (TransType == TransTypeEnum.OtherOutDoc.GetDescription())
                    {
                        enableCode = "";
                        excessQtySql = "";
                        #region 其它出库SQL
                        sqls = @" select
	                        a.OutCode as Code,
	                        a.InvCode,
	                        b.InvName,
	                        b.InvStd,
b.InvUnit,
	                        SUM(ISNULL(a.Quantity, 0)) AS iQuantity,
	                        a.WhCode,
a.ExtensionID
                        FROM
	                        ICSOtherOut a
                        LEFT JOIN ICSINVENTORY b ON a.InvCode = b.InvCode AND a.WorkPoint=b.WorkPoint
                        WHERE a.OutCode in ({0}) AND a.WorkPoint = '{1}'
                        GROUP BY a.OutCode,a.InvCode,b.InvName,b.InvStd,b.InvUnit,a.WhCode,a.ExtensionID";
                        #endregion
                    }
                    if (TransType == TransTypeEnum.BrrowDoc.GetDescription())
                    {
                        enableCode = "";
                        excessQtySql = "";
                        #region 借用SQL
                        sqls = @"select
	                        a.BrrowCode as Code,
	                        a.InvCode,
						
	                        b.InvName,
	                        b.InvStd,
b.InvUnit,
	                        SUM(ISNULL(a.Quantity, 0)) AS iQuantity,
	                        a.WhCode,
a.ExtensionID
                        FROM
	                        ICSBrrow a
                        LEFT JOIN ICSINVENTORY b ON a.InvCode = b.InvCode AND a.WorkPoint=b.WorkPoint
                        WHERE a.BrrowCode in ({0}) AND a.WorkPoint = '{1}'
                        GROUP BY a.BrrowCode,a.InvCode,b.InvName,b.InvStd,b.InvUnit,a.WhCode,a.ExtensionID";
                        #endregion
                    }
                    if (TransType == TransTypeEnum.OneStepTransferDocIn.GetDescription())
                    {
                        enableCode = "";
                        excessQtySql = "";
                        #region 物料调拨
                        sqls = @"						select
	                        a.TransferNO as Code,
	                        a.InvCode,
						
	                        b.InvName,
	                        b.InvStd,
b.InvUnit,
	                        SUM(ISNULL(a.Quantity, 0)) AS iQuantity,
	                        a.FromWarehouseCode as WhCode,
a.ExtensionID
                        FROM
	                        ICSTransfer a
                        LEFT JOIN ICSINVENTORY b ON a.InvCode = b.InvCode AND a.WorkPoint=b.WorkPoint
						 WHERE a.TransferNO in ({0}) AND a.WorkPoint = '{1}'
                        GROUP BY a.TransferNO,a.InvCode,b.InvName,b.InvStd,b.InvUnit,a.FromWarehouseCode,a.ExtensionID";
                        #endregion
                    }
                    if (TransType == TransTypeEnum.TwoStepTransferDocOut.GetDescription())
                    {
                        enableCode = "";
                        excessQtySql = "";
                        #region 两步调出
                        sqls = @"select
	                        a.OutCode as Code,
	                        a.InvCode,
						
	                        b.InvName,
	                        b.InvStd,
b.InvUnit,
	                        SUM(ISNULL(a.Quantity, 0)) AS iQuantity,
	                        a.WHCode ,
a.ExtensionID
                     from  ICSOtherOut a
                        INNER JOIN ICSTransfer tra ON a.TransferDetailID=tra.TransferDetailID AND a.WorkPoint=tra.WorkPoint
                        LEFT JOIN ICSINVENTORY b ON a.InvCode = b.InvCode AND a.WorkPoint=b.WorkPoint
						 WHERE a.OutCode in ({0}) AND a.WorkPoint = '{1}'
                        GROUP BY a.OutCode,a.InvCode,b.InvName,b.InvStd,b.InvUnit,a.WHCode,a.ExtensionID";
                        #endregion
                    }
                    #endregion
                    #region 出库
                    #region 采购退货
                    if (TransType == TransTypeEnum.PurchaseReceiveDoctNegative.GetDescription())
                    {
                        isDeliveryNotice = true;
                        columns = @"a.DNCode AS TransCode,
                                    a.DNDetailID AS DetailID,
                                    a.DNType AS Type,
                                    a.Sequence AS TransSequence,
                                    a.RCVQuantity AS IssueQuantity,
                                    a.Quantity,
                                    a.Amount,
                                    a.MUSER AS [User],
                                    a.MTIME AS [MTime],";

                        tableName = @"ICSDeliveryNotice a ";

                        where = @" a.DNCode='{0}' AND a.WorkPoint='{1}' AND a.DNType='2' AND a.Status<>'3'";
                    }
                    #endregion
                    //#region 工单关联
                    //else if (TransType == TransTypeEnum.ICSMOReceive.GetDescription())
                    //{
                    //    isDeliveryNotice = true;
                    //    columns = @"a.MOCode AS TransCode,
                    //                a.Sequence AS TransSequence,";

                    //    tableName = @"ICSMO a ";

                    //    where = @" a.MOCode='{0}' AND a.WorkPoint='{1}' and a.ERPStatus<>'3'";
                    //}
                    //#endregion
                    #region 委外发料(合并发料)
                    else if (TransType == TransTypeEnum.OutsourcingIssueDoc.GetDescription())
                    {
                        sqlCheckSign = @"select * from ICSConfiguration where code = 'OutWithLocationCode004' and enable = '1'";
                        flag = DBHelper.SQlReturnData(sqlCheckSign, cmd);
                        isMerge = true;
                        columnsMerge = @"mer.MergeID+'~'+b.OOCode AS TransCode,
                                    a.PickID AS DetailID,
                                    a.SupplyType AS Type,
                                    b.Sequence+'~'+a.Sequence AS TransSequence,
                                    a.IssueQuantity AS IssueQuantity,";

                        tableNameMerge = @"ICSOOPick  a
                                INNER JOIN ICSOutsourcingOrder b ON  a.OODetailID=b.OODetailID AND a.WorkPoint=b.WorkPoint
                                    INNER JOIN ICSMOPickMerge mer ON a.id=mer.SourceID AND a.WorkPoint=mer.WorkPoint";

                        columns = @"b.OOCode AS TransCode,
                                    a.PickID AS DetailID,
                                    a.SupplyType AS Type,
                                    b.Sequence+'~'+a.Sequence AS TransSequence,
                                    a.IssueQuantity AS IssueQuantity,";

                        tableName = @"ICSOOPick  a
                                INNER JOIN ICSOutsourcingOrder b ON  a.OODetailID=b.OODetailID AND a.WorkPoint=b.WorkPoint ";

                        where = @" b.OOCode='{0}' AND a.WorkPoint='{1}' AND a.SupplyType='3' AND b.Status<>'3' and isnull(a.EATTRIBUTE1,'')<>'1' AND a.Quantity-a.IssueQuantity>0";
                    }
                    #endregion
                    #region 委外退货
                    else if (TransType == TransTypeEnum.OutsourcingReturnBack.GetDescription())
                    {
                        isDeliveryNotice = true;
                        columns = @"a.ODNCode AS TransCode,
                                    a.ODNDetailID AS DetailID,
                                    a.ODNType AS Type,
                                    a.Sequence AS TransSequence,
                                    a.RCVQuantity AS IssueQuantity,
                                    a.Quantity,
                                    a.Amount,
                                    a.MUSER AS [User],
                                    a.MTIME AS [MTime],";

                        tableName = @"ICSODeliveryNotice a ";

                        where = @" a.ODNCode='{0}' AND a.WorkPoint='{1}' AND a.ODNType='2' AND a.Status<>'3'";
                    }
                    #endregion
                    #region 生产发料(合并发料)
                    else if (TransType == TransTypeEnum.MOIssueDoc.GetDescription())
                    {
                        sqlCheckSign = @"select * from ICSConfiguration where code = 'OutWithLocationCode001' and enable = '1'";
                        flag = DBHelper.SQlReturnData(sqlCheckSign, cmd);
                        isMerge = true;
                        columnsMerge = @"mer.MergeID+'~'+b.MOCode AS TransCode,
                                    a.PickID AS DetailID,
                                    a.SupplyType AS Type,
                                    b.Sequence+'~'+a.Sequence AS TransSequence,
                                    a.IssueQuantity AS IssueQuantity,";

                        tableNameMerge = @"ICSMOPick  a
	                                INNER JOIN ICSMO b ON  a.MODetailID=b.MODetailID AND a.WorkPoint=b.WorkPoint
                                    INNER JOIN ICSMOPickMerge mer ON a.id=mer.SourceID AND a.WorkPoint=mer.WorkPoint";

                        columns = @"b.MOCode AS TransCode,
                                    a.PickID AS DetailID,
                                    a.SupplyType AS Type,
                                    b.Sequence+'~'+a.Sequence AS TransSequence,
                                    a.IssueQuantity AS IssueQuantity,";

                        tableName = @"ICSMOPick  a
	                                INNER JOIN ICSMO b ON  a.MODetailID=b.MODetailID AND a.WorkPoint=b.WorkPoint ";

                        where = @" b.MOCode='{0}' AND a.WorkPoint='{1}' AND a.SupplyType='3' AND b.MOStatus<>'3' and a.EATTRIBUTE1<>'1' AND a.Quantity-a.IssueQuantity>0";
                    }
                    #endregion
                    #region 销售出库(合并发料)
                    else if (TransType == TransTypeEnum.SalesShipmentDoc.GetDescription())
                    {
                        sqlCheckSign = @"select * from ICSConfiguration where code = 'OutWithLocationCode007' and enable = '1'";
                        flag = DBHelper.SQlReturnData(sqlCheckSign, cmd);
                        isMerge = true;
                        columnsMerge = @"mer.MergeID+'~'+a.SDNCode AS TransCode,
                                    a.SDNDetailID AS DetailID,
                                    a.SOCode,
                                    a.Type,
                                    a.Sequence AS TransSequence,
                                    a.SDNQuantity AS IssueQuantity,";

                        tableNameMerge = @"ICSSDN a 
                                    INNER JOIN ICSMOPickMerge mer ON a.id=mer.SourceID AND a.WorkPoint=mer.WorkPoint";

                        columns = @"a.SDNCode AS TransCode,
                                    a.SDNDetailID AS DetailID,
                                    a.SOCode,
                                    a.Type,
                                    a.Sequence AS TransSequence,
                                    a.SDNQuantity AS IssueQuantity,";

                        tableName = @"ICSSDN a ";

                        where = @" a.SDNCode='{0}' AND a.WorkPoint='{1}' AND a.Type='1' AND a.Status<>'3' AND a.Quantity-a.SDNQuantity>0";
                    }
                    #endregion
                    #region 盘点
                    else if (TransType == TransTypeEnum.Check.GetDescription())
                    {
                        #region SLQ
                        sql = @"SELECT a.ID,
                                    {0}
                                    a.Quantity,
                                    a.SelectLevel AS LocationCode,
                                    a.Amount,
                                    a.MUSER AS [User],
                                    a.MTIME AS [MTime]
                                    FROM {1} 
                                    WHERE {2} ";
                        #endregion

                        columns = @"a.CheckCode AS TransCode,
                                    a.ID,
                                    '' AS Type,";

                        tableName = @"ICSCheck a ";

                        where = @" a.CheckCode='{0}' AND a.WorkPoint='{1}' and a.Status='1'";
                    }
                    #endregion
                    #region 一步调拨(合并发料)
                    else if (TransType == TransTypeEnum.OneStepTransferDocIn.GetDescription())
                    {
                        sqlCheckSign = @"select * from ICSConfiguration where code = 'OutWithLocationCode009' and enable = '1'";
                        flag = DBHelper.SQlReturnData(sqlCheckSign, cmd);
                        isMerge = true;
                        columnsMerge = @"mer.MergeID+'~'+a.TransferNO AS TransCode,
                                    a.TransferDetailID AS DetailID,
                                    '' AS Type,
                                    a.Sequence AS TransSequence,
                                    a.TransferQuantity AS IssueQuantity,
                                    a.ToWarehouseCode,";

                        tableNameMerge = @"ICSTransfer a 
                                    INNER JOIN ICSMOPickMerge mer ON a.id=mer.SourceID AND a.WorkPoint=mer.WorkPoint";

                        #region SLQ
                        sql = @"SELECT a.ID,
                                    {0}
                                    convert(varchar(100),'') AS LocationCode,
                                    convert(varchar(100),'') AS LotNo,
									0 AS LocationQty,
                                    0 AS isMatched,
                                    a.InvCode,
                                    inv.InvName,
                                    inv.InvStd,
                                    a.Quantity,
                                    inv.InvUnit,
                                    a.Amount,
                                    a.FromWarehouseCode AS WHCode,
                                    inv.AmountUnit,
                                    wh.WarehouseName AS WHName,
                                    a.ExtensionID,
                                    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 AS BatchCode,
                                    ext.Version,
                                    ext.Brand,
                                    ext.cFree1,
                                    ext.cFree2,
                                    ext.cFree3,
                                    ext.cFree4,
                                    ext.cFree5,
                                    ext.cFree6,
                                    ext.cFree7,
                                    ext.cFree8,
                                    ext.cFree9,
                                    ext.cFree10,
                                    a.MUSER AS [User],
                                    a.MTIME AS [MTime]
                                    FROM {1}
                                    INNER JOIN ICSExtension ext ON a.ExtensionID=ext.ID AND a.WorkPoint=ext.WorkPoint
                                    INNER JOIN ICSInventory inv ON a.InvCode=inv.InvCode AND a.WorkPoint=inv.WorkPoint
                                    LEFT JOIN ICSWarehouse wh ON a.FromWarehouseCode=wh.WarehouseCode AND a.WorkPoint=wh.WorkPoint
                                    LEFT JOIN ICSInventoryBatchEnable invBat ON a.InvCode=invBat.InvCode AND a.FromWarehouseCode=invBat.WHCode AND a.WorkPoint=invBat.WorkPoint
                                    WHERE {2} ";
                        #endregion

                        columns = @"a.TransferNO AS TransCode,
                                    a.TransferDetailID AS DetailID,
                                    '' AS Type,
                                    a.Sequence AS TransSequence,
                                    a.TransferQuantity AS IssueQuantity,
                                    a.ToWarehouseCode,";

                        tableName = @"ICSTransfer a ";

                        where = @" a.TransferNO='{0}' AND a.WorkPoint='{1}' AND a.Status='1' AND a.Status<>'3'";
                    }
                    #endregion
                    #region 调拨申请单(领料)
                    else if (TransType == TransTypeEnum.StepTransferApplicationIn.GetDescription())
                    {
                        isMerge = true;
                        columnsMerge = @"mer.MergeID+'~'+a.TransferNO AS TransCode,
                                    a.TransferDetailID AS DetailID,
                                    '' AS Type,
                                    a.Sequence AS TransSequence,
                                    a.TransferQuantity AS IssueQuantity,
                                    a.ToWarehouseCode,";

                        tableNameMerge = @"ICSTransferApplication a 
                                    INNER JOIN ICSMOPickMerge mer ON a.id=mer.SourceID AND a.WorkPoint=mer.WorkPoint";

                        #region SLQ
                        sql = @"SELECT a.ID,
                                    {0}
                                    convert(varchar(100),'') AS LocationCode,
                                    convert(varchar(100),'') AS LotNo,
									0 AS LocationQty,
                                    0 AS isMatched,
                                    a.InvCode,
                                    inv.InvName,
                                    inv.InvStd,
                                    a.Quantity,
                                    inv.InvUnit,
                                    a.Amount,
                                    a.FromWarehouseCode AS WHCode,
                                    inv.AmountUnit,
                                    wh.WarehouseName AS WHName,
                                    a.ExtensionID,
                                    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 AS BatchCode,
                                    ext.Version,
                                    ext.Brand,
                                    ext.cFree1,
                                    ext.cFree2,
                                    ext.cFree3,
                                    ext.cFree4,
                                    ext.cFree5,
                                    ext.cFree6,
                                    ext.cFree7,
                                    ext.cFree8,
                                    ext.cFree9,
                                    ext.cFree10,
                                    a.MUSER AS [User],
                                    a.MTIME AS [MTime]
                                    FROM {1}
                                    INNER JOIN ICSExtension ext ON a.ExtensionID=ext.ID AND a.WorkPoint=ext.WorkPoint
                                    INNER JOIN ICSInventory inv ON a.InvCode=inv.InvCode AND a.WorkPoint=inv.WorkPoint
                                    LEFT JOIN ICSWarehouse wh ON a.FromWarehouseCode=wh.WarehouseCode AND a.WorkPoint=wh.WorkPoint
                                    LEFT JOIN ICSInventoryBatchEnable invBat ON a.InvCode=invBat.InvCode AND a.FromWarehouseCode=invBat.WHCode AND a.WorkPoint=invBat.WorkPoint
                                    WHERE {2} ";
                        #endregion

                        columns = @"a.TransferNO AS TransCode,
                                    a.TransferDetailID AS DetailID,
                                    '' AS Type,
                                    a.Sequence AS TransSequence,
                                    a.TransferQuantity AS IssueQuantity,
                                    a.ToWarehouseCode,";

                        tableName = @"ICSTransferApplication a ";

                        where = @" a.TransferNO='{0}' AND a.WorkPoint='{1}' AND a.Status='2' AND a.Status<>'3'";
                    }
                    #endregion
                    #region 调拨(合并发料)
                    else if (TransType == TransTypeEnum.StepTransferDocIn.GetDescription())
                    {
                    }
                    #endregion
                    #region 两步调出(合并发料)
                    else if (TransType == TransTypeEnum.TwoStepTransferDocOut.GetDescription())
                    {
                        sqlCheckSign = @"select * from ICSConfiguration where code = 'OutWithLocationCode010' and enable = '1'";
                        flag = DBHelper.SQlReturnData(sqlCheckSign, cmd);
                        isMerge = true;
                        columnsMerge = @"mer.MergeID+'~'+a.OutCode AS TransCode,
                                    a.OutDetailID AS DetailID,
                                    '' AS Type,
                                    a.Sequence AS TransSequence,
                                    a.OutQuantity AS IssueQuantity,";

                        tableNameMerge = @"ICSOtherOut a
                                    INNER JOIN ICSTransfer tra ON a.TransferDetailID=tra.TransferDetailID AND a.WorkPoint=tra.WorkPoint
                                    INNER JOIN ICSMOPickMerge mer ON a.id=mer.SourceID AND a.WorkPoint=mer.WorkPoint";

                        columns = @"a.OutCode AS TransCode,
                                    a.OutDetailID AS DetailID,
                                    '' AS Type,
                                    a.Sequence AS TransSequence,
                                    a.OutQuantity AS IssueQuantity,";

                        tableName = @"ICSOtherOut a
                                    INNER JOIN ICSTransfer tra ON a.TransferDetailID=tra.TransferDetailID AND a.WorkPoint=tra.WorkPoint ";

                        where = @" a.OutCode='{0}' AND a.WorkPoint='{1}' AND a.Status<>'3' AND a.Quantity-a.OutQuantity>0";
                    }
                    #endregion
                    #region 其他出库(合并发料)
                    else if (TransType == TransTypeEnum.OtherOutDoc.GetDescription())
                    {
                        sqlCheckSign = @"select * from ICSConfiguration where code = 'OutWithLocationCode008' and enable = '1'";
                        flag = DBHelper.SQlReturnData(sqlCheckSign, cmd);
                        isMerge = true;
                        columnsMerge = @"mer.MergeID+'~'+a.OutCode AS TransCode,
                                    a.OutDetailID AS DetailID,
                                    '' AS Type,
                                    a.Sequence AS TransSequence,
                                    a.OutQuantity AS IssueQuantity,";

                        tableNameMerge = @"ICSOtherOut a 
                                    INNER JOIN ICSMOPickMerge mer ON a.id=mer.SourceID AND a.WorkPoint=mer.WorkPoint";

                        columns = @"a.OutCode AS TransCode,
                                    a.OutDetailID AS DetailID,
                                    '' AS Type,
                                    a.Sequence AS TransSequence,
                                    a.OutQuantity AS IssueQuantity,";

                        tableName = @"ICSOtherOut a ";

                        where = @" a.OutCode='{0}' AND a.WorkPoint='{1}' AND a.Status<>'3' AND a.Quantity-a.OutQuantity>0";
                    }
                    #endregion
                    #region 领料申请单发料(合并发料)
                    else if (TransType == TransTypeEnum.MOApply.GetDescription())
                    {
                        sqlCheckSign = @"select * from ICSConfiguration where code = 'OutWithLocationCode002' and enable = '1'";
                        flag = DBHelper.SQlReturnData(sqlCheckSign, cmd);
                        isMerge = true;
                        columnsMerge = @"mer.MergeID+'~'+a.ApplyCode AS TransCode,
                                    a.ApplyDetailID AS DetailID,
                                    a.Type,
                                    a.Sequence AS TransSequence,
                                    a.IssueQuantity AS IssueQuantity,";

                        tableNameMerge = @"ICSMOApply a 
                                    INNER JOIN ICSMOPickMerge mer ON a.ID=mer.SourceID AND a.WorkPoint=mer.WorkPoint";

                        columns = @"a.ApplyCode AS TransCode,
                                    a.ApplyDetailID AS DetailID,
                                    a.Type,
                                    a.Sequence AS TransSequence,
                                    a.IssueQuantity AS IssueQuantity,";

                        tableName = @"ICSMOApply a ";

                        where = @" a.ApplyCode='{0}' AND a.WorkPoint='{1}' AND a.Status<>'3' AND a.Quantity-a.IssueQuantity>0";
                    }
                    #endregion
                    #region 补料申请单发料(合并发料)
                    else if (TransType == TransTypeEnum.MOReplenishment.GetDescription())
                    {
                        sqlCheckSign = @"select * from ICSConfiguration where code = 'OutWithLocationCode012' and enable = '1'";
                        flag = DBHelper.SQlReturnData(sqlCheckSign, cmd);
                        isMerge = true;
                        columnsMerge = @"mer.MergeID+'~'+a.ApplyCode AS TransCode,
                                    a.ApplyDetailID AS DetailID,
                                    a.Type,
                                    a.Sequence AS TransSequence,
                                    a.IssueQuantity AS IssueQuantity,";

                        tableNameMerge = @"ICSMOReplenishment a 
                                    INNER JOIN ICSMOPickMerge mer ON a.ID=mer.SourceID AND a.WorkPoint=mer.WorkPoint";

                        columns = @"a.ReplenishmentCode AS TransCode,
                                    a.ReplenishmentDetailID AS DetailID,
                                    a.Type,
                                    a.Sequence AS TransSequence,
                                    a.IssueQuantity AS IssueQuantity,";

                        tableName = @"ICSMOReplenishment a ";

                        where = @" a.ReplenishmentCode='{0}' AND a.WorkPoint='{1}' AND a.Status<>'3' AND a.Quantity-a.IssueQuantity>0";
                    }
                    #endregion
                    #region 委外领料申请单发料(合并发料)
                    else if (TransType == TransTypeEnum.OOApply.GetDescription())
                    {
                        sqlCheckSign = @"select * from ICSConfiguration where code = 'OutWithLocationCode005' and enable = '1'";
                        flag = DBHelper.SQlReturnData(sqlCheckSign, cmd);
                        isMerge = true;
                        columnsMerge = @"mer.MergeID+'~'+a.ApplyCode AS TransCode,
                                    a.ApplyDetailID AS DetailID,
                                    a.Type,
                                    a.Sequence AS TransSequence,
                                    a.IssueQuantity AS IssueQuantity,";

                        tableNameMerge = @"ICSOApply a 
                                    INNER JOIN ICSMOPickMerge mer ON a.ID=mer.SourceID AND a.WorkPoint=mer.WorkPoint";

                        columns = @"a.ApplyCode AS TransCode,
                                    a.ApplyDetailID AS DetailID,
                                    a.Type,
                                    a.Sequence AS TransSequence,
                                    a.IssueQuantity AS IssueQuantity,";

                        tableName = @"ICSOApply a  ";

                        where = @" a.ApplyCode='{0}' AND a.WorkPoint='{1}' AND a.Status<>'3' AND a.Quantity-a.IssueQuantity>0";
                    }
                    #endregion
                    #region 开立材料出库(合并发料)
                    else if (TransType == TransTypeEnum.MOIssue.GetDescription())
                    {
                        sqlCheckSign = @"select * from ICSConfiguration where code = 'OutWithLocationCode003' and enable = '1'";
                        flag = DBHelper.SQlReturnData(sqlCheckSign, cmd);
                        isMerge = true;
                        columnsMerge = @"mer.MergeID+'~'+a.IssueCode AS TransCode,
                                    a.IssueDetailID AS DetailID,
                                    a.Type,
                                    a.Sequence AS TransSequence,
                                    a.IssueQuantity AS IssueQuantity,";

                        tableNameMerge = @"ICSMOIssue a 
                                    INNER JOIN ICSMOPickMerge mer ON a.ID=mer.SourceID AND a.WorkPoint=mer.WorkPoint";

                        columns = @"a.IssueCode AS TransCode,
                                    a.IssueDetailID AS DetailID,
                                    a.Type,
                                    a.Sequence AS TransSequence,
                                    a.IssueQuantity AS IssueQuantity,";

                        tableName = @"ICSMOIssue a ";

                        where = @" a.IssueCode='{0}' AND a.WorkPoint='{1}' AND a.Status<>'3' AND a.Quantity-a.IssueQuantity>0";
                    }
                    #endregion
                    #region 开立委外材料出库(合并发料)
                    else if (TransType == TransTypeEnum.OOIssue.GetDescription())
                    {
                        sqlCheckSign = @"select * from ICSConfiguration where code = 'OutWithLocationCode006' and enable = '1'";
                        flag = DBHelper.SQlReturnData(sqlCheckSign, cmd);
                        isMerge = true;
                        columnsMerge = @"mer.MergeID+'~'+a.IssueCode AS TransCode,
                                    a.IssueDetailID AS DetailID,
                                    a.Type,
                                    a.Sequence AS TransSequence,
                                    a.IssueQuantity AS IssueQuantity,";

                        tableNameMerge = @"ICSOIssue a 
                                    INNER JOIN ICSMOPickMerge mer ON a.ID=mer.SourceID AND a.WorkPoint=mer.WorkPoint";

                        columns = @"a.IssueCode AS TransCode,
                                    a.IssueDetailID AS DetailID,
                                    a.Type,
                                    a.Sequence AS TransSequence,
                                    a.IssueQuantity AS IssueQuantity,";

                        tableName = @"ICSOIssue a ";

                        where = @" a.IssueCode='{0}' AND a.WorkPoint='{1}' AND a.Status<>'3' AND a.Quantity-a.IssueQuantity>0";
                    }
                    #endregion
                    #region 开立红字入库单
                    else if (TransType == TransTypeEnum.PurchaseReceive.GetDescription())
                    {
                        columns = @"a.RCVCode AS TransCode,
                                    a.RCVDetailID AS DetailID,
                                    a.Type,
                                    a.Sequence AS TransSequence,
                                    a.RCVQuantity AS IssueQuantity,";

                        tableName = @"ICSPurchaseReceive a ";

                        where = @" a.RCVCode='{0}' AND a.WorkPoint='{1}' AND a.Type='2' AND a.Status<>'3'";
                    }
                    #endregion
                    #region 开立委外红字入库单
                    else if (TransType == TransTypeEnum.OutsourcingReceiveDocNegative.GetDescription())
                    {
                        columns = @"a.RCVCode AS TransCode,
                                    a.RCVDetailID AS DetailID,
                                    a.Type,
                                    a.Sequence AS TransSequence,
                                    a.RCVQuantity AS IssueQuantity,";

                        tableName = @"ICSOutsourcingReceive a ";

                        where = @" a.RCVCode='{0}' AND a.WorkPoint='{1}' AND a.Type='2' AND a.Status<>'3'";
                    }
                    #endregion
                    #region 借用(合并发料)
                    else if (TransType == TransTypeEnum.BrrowDoc.GetDescription())
                    {
                        sqlCheckSign = @"select * from ICSConfiguration where code = 'OutWithLocationCode011' and enable = '1'";
                        flag = DBHelper.SQlReturnData(sqlCheckSign, cmd);
                        isMerge = true;
                        columnsMerge = @"mer.MergeID+'~'+a.BrrowCode AS TransCode,
                                    a.BrrowDetailID AS DetailID,
                                    '' AS Type,
                                    a.Sequence AS TransSequence,
                                    a.BrrowQuantity AS IssueQuantity,";

                        tableNameMerge = @"ICSBrrow a 
                                    INNER JOIN ICSMOPickMerge mer ON a.BrrowDetailID=mer.SourceID AND a.WorkPoint=mer.WorkPoint";

                        columns = @"a.BrrowCode AS TransCode,
                                    a.BrrowDetailID AS DetailID,
                                    '' AS Type,
                                    a.Sequence AS TransSequence,
                                    a.BrrowQuantity AS IssueQuantity,";

                        tableName = @"ICSBrrow a ";

                        where = @" a.BrrowCode='{0}' AND a.WorkPoint='{1}' AND a.Status<>'3' AND a.Quantity-a.BrrowQuantity>0";
                    }
                    #endregion
                    #region 送货单
                    else if (TransType == TransTypeEnum.ASN.GetDescription())
                    {
                        isDeliveryNotice = true;
                        columns = @"asn.ASNCode AS TransCode,
                                    asn.ID AS DetailID,
                                    asn.LotNo,
                                    '' AS Type,
                                    asn.Sequence AS TransSequence,
                                    asn.DNQuantity AS IssueQuantity,
                                    asn.Quantity,
                                    asn.Quantity*(a.Amount/a.Quantity) AS Amount,
                                    asn.MUSER AS [User],
                                    asn.MTIME AS [MTime],";

                        tableName = @"ICSInventoryLot a 
                                    INNER JOIN ICSASNDetail asn ON a.LotNo=asn.LotNo AND a.WorkPoint=asn.WorkPoint ";

                        where = @" asn.ASNCode='{0}' AND a.WorkPoint='{1}' ";
                    }
                    #endregion
                    #region 委外送货单
                    else if (TransType == TransTypeEnum.OASN.GetDescription())
                    {
                        isDeliveryNotice = true;
                        columns = @"asn.OASNCode AS TransCode,
                                    asn.ID AS DetailID,
                                    asn.LotNo,
                                    '' AS Type,
                                    asn.Sequence AS TransSequence,
                                    asn.ODNQuantity AS IssueQuantity,
                                    asn.Quantity,
                                    asn.Quantity*(a.Amount/a.Quantity) AS Amount,
                                    asn.MUSER AS [User],
                                    asn.MTIME AS [MTime],";

                        tableName = @"ICSInventoryLot a 
                                    INNER JOIN ICSOASNDetail asn ON a.LotNo=asn.LotNo AND a.WorkPoint=asn.WorkPoint ";

                        where = @" asn.OASNCode='{0}' AND a.WorkPoint='{1}' ";
                    }
                    #endregion
                    #endregion
                    #region 入库
                    #region 采购入库
                    else if (TransType == TransTypeEnum.PurchaseReceiveDoc.GetDescription())
                    {
                    }
                    #endregion
                    #region 审核的到货单
                    else if (TransType == TransTypeEnum.DeliveryNotice.GetDescription())
                    {
                    }
                    #endregion
                    #region 采购拒收
                    else if (TransType == TransTypeEnum.PurchaseRejectDoc.GetDescription())
                    {
                    }
                    #endregion
                    #region 审核的委外到货单
                    else if (TransType == TransTypeEnum.ODeliveryNotice.GetDescription())
                    {
                    }
                    #endregion
                    #region 委外拒收
                    else if (TransType == TransTypeEnum.OutsourcingRejectDoc.GetDescription())
                    {
                    }
                    #endregion
                    #region 委外入库
                    else if (TransType == TransTypeEnum.OutsourcingReceiveDoc.GetDescription())
                    {
                    }
                    #endregion
                    #region 生产退料
                    else if (TransType == TransTypeEnum.MOIssueDocNegative.GetDescription()
                        || TransType == TransTypeEnum.MOIssueDocNegativeApply.GetDescription()
                        || TransType == TransTypeEnum.MOIssueDocNegativeIssue.GetDescription())
                    {
                    }
                    #endregion
                    #region 委外退料
                    else if (TransType == TransTypeEnum.ICSOutsourcingIssueDoNegative.GetDescription()
                        || TransType == TransTypeEnum.ICSOutsourcingIssueDoNegativeApply.GetDescription()
                        || TransType == TransTypeEnum.ICSOutsourcingIssueDoNegativeIssue.GetDescription())
                    {
                        #region SLQ
                        sql = @"SELECT a.ID,
                                    {0}
                                    FROM {1}
                                    INNER JOIN ICSExtension ext ON a.ExtensionID=ext.ID AND a.WorkPoint=ext.WorkPoint
                                    INNER JOIN ICSInventory inv ON a.InvCode=inv.InvCode AND a.WorkPoint=inv.WorkPoint
                                    WHERE {2} ";
                        #endregion

                        columns = @"a.OApplyNegCode AS TransCode,
                                    a.Sequence AS TransSequence";

                        tableName = @"ICSOApplyNegDetail a 
                                        INNER JOIN ICSOApplyNeg d ON a.OApplyNegCode=d.OApplyNegCode AND a.WorkPoint=d.WorkPoint";

                        where = @" a.OApplyNegCode='{0}' AND a.WorkPoint='{1}' AND  a.Quantity>a.IssueNegQuantity AND d.Status<>'3'";
                    }
                    #endregion
                    #region 生产入库
                    else if (TransType == TransTypeEnum.ManufactureReceiveDoc.GetDescription())
                    {
                    }
                    #endregion
                    #region 开立的生产入库单
                    else if (TransType == TransTypeEnum.ManufactureReceive.GetDescription())
                    {
                    }
                    #endregion
                    #region 返工工单
                    else if (TransType == TransTypeEnum.ReWorkReceiveMo.GetDescription())
                    {
                    }
                    #endregion
                    #region 销售退货
                    else if (TransType == TransTypeEnum.SalesShipmentDocNegative.GetDescription())
                    {
                    }
                    #endregion
                    #region 两步调入
                    else if (TransType == TransTypeEnum.TwoStepTransferDocIn.GetDescription())
                    {
                        columns = @"a.InCode AS TransCode,
                                    a.InDetailID AS DetailID,
                                    '' AS Type,
                                    a.Sequence AS TransSequence,
                                    a.InQuantity AS IssueQuantity,";

                        tableName = @"ICSOtherIn a
                                    INNER JOIN ICSTransfer tra ON a.TransferDetailID=tra.TransferDetailID AND a.WorkPoint=tra.WorkPoint ";

                        where = @" a.InCode='{0}' AND a.WorkPoint='{1}' AND a.Status<>'3'";
                    }
                    #endregion
                    #region 销售退货-原条码
                    else if (TransType == TransTypeEnum.SalesReturnBack.GetDescription())
                    {
                        columns = @"a.SDNCode AS TransCode,
                                    a.SDNDetailID AS DetailID,
                                    a.Type,
                                    a.Sequence AS TransSequence,
                                    a.SDNQuantity AS IssueQuantity,";

                        tableName = @"ICSSDN a ";

                        where = @" a.SDNCode='{0}' AND a.WorkPoint='{1}' AND a.Type='2' AND a.Status<>'3'";
                    }
                    #endregion
                    #region 其他入库
                    else if (TransType == TransTypeEnum.OtherInDoc.GetDescription())
                    {
                    }
                    #endregion
                    #region 拆卸单
                    else if (TransType == TransTypeEnum.DisassemblyDoc.GetDescription())
                    {
                        columns = @"a.DABDOCCode AS TransCode,
                                    a.DABDOCDetailID AS DetailID,
                                    a.DABDOCType AS Type,
                                    a.Sequence AS TransSequence,
                                    a.DABDOCQuantity AS IssueQuantity,";

                        tableName = @"ICSDisassemblyDoc a";

                        where = @" a.DABDOCCode='{0}' AND a.WorkPoint='{1}' AND a.DABDOCType='2' AND a.Status<>'3' ";
                    }
                    #endregion
                    #region 归还
                    else if (TransType == TransTypeEnum.ReturnDoc.GetDescription())
                    {
                    }
                    #endregion
                    #endregion
                    if (string.IsNullOrWhiteSpace(columns) || string.IsNullOrWhiteSpace(tableName) || string.IsNullOrWhiteSpace(where))
                        throw new Exception(language.GetNameByCode("WMSAPIInfo003"));
                    #region 判断是否启用匹配库位
                   
                    if (flag != null && flag.Rows.Count > 0)
                    //if (true)
                    {
                        sql = @"select * into #maintemp from  (" + sql + @")a 
                                    select * into #resulttemp from #maintemp 
                                    truncate table #resulttemp
                                    select a.lotno,a.locationcode,a.invcode,(a.quantity-a.lockQuantity) as quantity ,a.mtime,a.warehousecode,isnull(ext.ProjectCode,'')as ProjectCode, isnull(ext.Version,'')as Version,
                                    isnull(ext.Brand,'')as Brand,
                                    isnull(ext.cFree1,'')as cFree1,
                                    isnull(ext.cFree2,'') cFree2,
                                    isnull(ext.cFree3,'') cFree3,
                                    isnull(ext.cFree4,'') cFree4,
                                    isnull(ext.cFree5,'') cFree5,
                                    isnull(ext.cFree6,'') cFree6,
                                    isnull(ext.cFree7,'') cFree7,
                                    isnull(ext.cFree8,'') cFree8,
                                    isnull(ext.cFree9,'') cFree9,
                                    isnull(ext.cFree10,'') cFree10,ISNULL(ext.BatchCode, '') BatchCode  into #barcodetemp 
                                    from ICSWareHouseLotInfo 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 
                                    LEFT JOIN
                                    (select invcode,ProjectCode,BatchCode,Version,Brand,cFree1,cFree2,cFree3,cFree4,cFree5,cFree6,cFree7,cFree8,cFree9,cFree10,WHCODE from #maintemp 
                                    group by invcode,ProjectCode,BatchCode,Version,Brand,cFree1,cFree2,cFree3,cFree4,cFree5,cFree6,cFree7,cFree8,cFree9,cFree10,WHCODE) b on a.invcode = b.invcode  
                                    where (a.warehousecode = b.whcode or ISNULL(b.whcode,'')='') and  a.Quantity-a.lockQuantity>0 and 
                                                           
                                    ((LEN(ISNULL(b.ProjectCode,''))<=0)or((LEN(ISNULL(b.ProjectCode,''))>0) and ext.ProjectCode = b.ProjectCode)) 
                                    and  ((LEN(ISNULL(b.Version,''))<=0)or((LEN(ISNULL(b.Version,''))>0) and ext.Version =b.Version)) and 
                                    ((LEN(ISNULL(b.Brand,''))<=0)or ((LEN(ISNULL(b.Brand,''))>0) and ext.Brand =b.Brand)) and 
                                    ((LEN(ISNULL(b.BatchCode,''))<=0)or((LEN(ISNULL(b.BatchCode,''))>0) and ext.BatchCode =b.BatchCode))  and
                                    ((LEN(ISNULL(b.cFree1,''))<=0)or((LEN(ISNULL(b.cFree1,''))>0) and ext.cFree1 =b.cFree1)) and 
                                    ((LEN(ISNULL(b.cFree2,''))<=0)or((LEN(ISNULL(b.cFree2,''))>0) and ext.cFree2 =b.cFree2)) and 
                                    ((LEN(ISNULL(b.cFree3,''))<=0)or((LEN(ISNULL(b.cFree3,''))>0) and ext.cFree3 =b.cFree3)) and 
                                    ((LEN(ISNULL(b.cFree4,''))<=0)or((LEN(ISNULL(b.cFree4,''))>0) and ext.cFree4 =b.cFree4)) and 
                                    ((LEN(ISNULL(b.cFree5,''))<=0)or((LEN(ISNULL(b.cFree5,''))>0) and ext.cFree5 =b.cFree5)) and 
                                    ((LEN(ISNULL(b.cFree6,''))<=0)or((LEN(ISNULL(b.cFree6,''))>0) and ext.cFree6 =b.cFree6)) and 
                                    ((LEN(ISNULL(b.cFree7,''))<=0)or((LEN(ISNULL(b.cFree7,''))>0) and ext.cFree7 =b.cFree7)) and 
                                    ((LEN(ISNULL(b.cFree8,''))<=0)or((LEN(ISNULL(b.cFree8,''))>0) and ext.cFree8 =b.cFree8)) and 
                                    ((LEN(ISNULL(b.cFree9,''))<=0)or((LEN(ISNULL(b.cFree9,''))>0) and ext.cFree9 =b.cFree9))  and
                                    ((LEN(ISNULL(b.cFree10,''))<=0)or((LEN(ISNULL(b.cFree10,''))>0) and ext.cFree10 =b.cFree10))

                                    BEGIN
                                    DECLARE @transSequence VARCHAR(50);--当前循环的行号
                                    DECLARE @qty decimal(18, 4);--条码表数量
                                    DECLARE @needqty decimal(18, 4);--本行所需数量
                                    DECLARE @lotno VARCHAR(50);--本行所需数量
                                    DECLARE @locationcode VARCHAR(50);--本行所在库位
                                    DECLARE @WHCode VARCHAR(50);--本行所在仓库
                                    DECLARE @invcode VARCHAR(50);--本行条码
                                    DECLARE @issueQuantity decimal(18, 4);
                                    DECLARE tempCursor CURSOR FOR (select transSequence from #maintemp);   --创建游标tempCursor,并定义游标所指向的集合	
	                                    OPEN tempCursor;                              --打开游标
	                                    FETCH NEXT FROM tempCursor INTO @transSequence;          --游标读取下一个数据
	                                    WHILE @@fetch_status=0  
		                                    BEGIN
			                                    select @needqty=Quantity,@issueQuantity=issueQuantity from #maintemp where transSequence = @transSequence
				                                    PRINT @transSequence
				                                    WHILE @needqty>0
					                                    BEGIN

						                                    select top 1 @qty = isnull(a.quantity,0), @locationcode = isnull(a.locationcode,''),@lotno = isnull(a.lotno,''),@WHCode = isnull(a.warehousecode,''),@invcode = b.invcode from #barcodetemp a
						                                    right JOIN(select invcode,ProjectCode,BatchCode,Version,Brand,cFree1,cFree2,cFree3,cFree4,cFree5,cFree6,cFree7,cFree8,cFree9,cFree10,WHCODE from #maintemp where transSequence=@transSequence)b on a.invcode = b.invcode 
						                                    and ((isnull(b.ProjectCode,'')<>'' and b.ProjectCode = a.ProjectCode) or isnull(b.ProjectCode,'') ='') and  
                                                            ((isnull(b.Version,'')<>'' and b.Version = a.Version) or isnull(b.Version,'') ='') and 
                                                            ((isnull(b.Brand,'')<>'' and b.Brand = a.Brand )or isnull(b.Brand,'') ='') and 
                                                            ((isnull(b.cFree1,'')<>'' and b.cFree1  =a.cFree1) or isnull(b.cFree1,'') ='') and 
                                                            ((isnull(b.cFree2,'')<>'' and b.cFree2  =a.cFree2 )or isnull(b.cFree2,'') ='') and 
                                                            ((isnull(b.cFree3,'')<>'' and b.cFree3  =a.cFree3 )or isnull(b.cFree3,'') ='') and 
                                                            ((isnull(b.cFree4,'')<>'' and b.cFree4  =a.cFree4 )or isnull(b.cFree4,'') ='') and 
                                                            ((isnull(b.cFree5,'')<>'' and b.cFree5  =a.cFree5) or isnull(b.cFree5,'') ='') and 
                                                            ((isnull(b.cFree6,'')<>'' and b.cFree6  =a.cFree6 )or isnull(b.cFree6,'') ='') and 
                                                            ((isnull(b.cFree7,'')<>'' and b.cFree7  =a.cFree7) or isnull(b.cFree7,'') ='') and 
                                                            ((isnull(b.cFree8,'')<>'' and b.cFree8  =a.cFree8) or isnull(b.cFree8,'') ='') and 
                                                            ((isnull(b.cFree9,'')<>'' and b.cFree9  =a.cFree9) or isnull(b.cFree9,'') ='') and
                                                            ((isnull(b.cFree10,'')<>'' and b.cFree10  =a.cFree10) or isnull(b.cFree10,'') ='') and 
															((isnull(b.BatchCode,'')<>'' and b.BatchCode  =a.BatchCode) or isnull(b.BatchCode,'') ='')ORDER BY mtime,locationcode
						                                     IF(@needqty-@issueQuantity-@qty>=0 and ISNULL(@lotno, '')<>'')  
							                                    BEGIN
								                                    insert INTO #resulttemp (id,TransCode,DetailID,Type,TransSequence,IssueQuantity,Quantity,
									                                    Amount,[User],[MTime],InvCode,InvName,InvStd,InvUnit,WHCode,ToWarehouseCode,LocationCode,LocationQty,isMatched,AmountUnit,lotNo,
									                                    WHName,ExtensionID,ProjectCode,BatchCode, Version,Brand,cFree1,cFree2,cFree3,cFree4,cFree5,cFree6,cFree7,cFree8,cFree9,cFree10) 
								                                    SELECT id,TransCode,DetailID,Type,TransSequence,IssueQuantity,Quantity,
									                                    ISNULL(Amount, 0),[User],[MTime],InvCode,InvName,ISNULL(InvStd, ''),InvUnit,isnull(@WHCode,''),isnull(ToWarehouseCode,''),isnull(@LocationCode,''),@qty,1,ISNULL(AmountUnit, ''),ISNULL(@lotno, ''),
									                                    WHName,ExtensionID,ProjectCode,BatchCode, Version,Brand,cFree1,cFree2,cFree3,cFree4,cFree5,cFree6,cFree7,cFree8,cFree9,cFree10 from #maintemp where #maintemp.transSequence = @transSequence
								                                    delete from #barcodetemp where lotno = @lotno
								                                    SET @needqty=@needqty-@qty
							                                    END
						                                    ELSE if(@needqty-@issueQuantity-@qty<0 and ISNULL(@lotno, '')<>''and @needqty-@issueQuantity>0) 
							                                    BEGIN
								
								                                    insert INTO #resulttemp (id,TransCode,DetailID,Type,TransSequence,IssueQuantity,Quantity,
									                                    Amount,[User],[MTime],InvCode,InvName,InvStd,InvUnit,WHCode,ToWarehouseCode,LocationCode,LocationQty,isMatched,AmountUnit,lotno,
									                                    WHName,ExtensionID,ProjectCode,BatchCode, Version,Brand,cFree1,cFree2,cFree3,cFree4,cFree5,cFree6,cFree7,cFree8,cFree9,cFree10) 
								                                    SELECT id,TransCode,DetailID,Type,TransSequence,IssueQuantity,Quantity,
									                                    ISNULL(Amount, 0),[User],[MTime],InvCode,InvName,ISNULL(InvStd, ''),InvUnit,isnull(@WHCode,''),isnull(ToWarehouseCode,''),isnull(@LocationCode,''),case WHEN ISNULL(@qty, 0)=0 THEN 0 else @needqty-@issueQuantity end ,1,ISNULL(AmountUnit, ''),ISNULL(@lotno, ''),
									                                    WHName,ExtensionID,ProjectCode,BatchCode, Version,Brand,cFree1,cFree2,cFree3,cFree4,cFree5,cFree6,cFree7,cFree8,cFree9,cFree10 from #maintemp where #maintemp.transSequence = @transSequence
									                                    update #barcodetemp set quantity = @qty-@needqty+-@issueQuantity  where lotno = @lotno
									                                    SET @needqty=@needqty-@issueQuantity-@qty

							                                    END
                                                            ELSE  
							                                    BEGIN
								
								                                    insert INTO #resulttemp (id,TransCode,DetailID,Type,TransSequence,IssueQuantity,Quantity,
									                                    Amount,[User],[MTime],InvCode,InvName,InvStd,InvUnit,WHCode,ToWarehouseCode,LocationCode,LocationQty,isMatched,AmountUnit,lotno,
									                                    WHName,ExtensionID,ProjectCode,BatchCode, Version,Brand,cFree1,cFree2,cFree3,cFree4,cFree5,cFree6,cFree7,cFree8,cFree9,cFree10) 
								                                    SELECT id,TransCode,DetailID,Type,TransSequence,IssueQuantity,Quantity,
									                                    ISNULL(Amount, 0),[User],[MTime],InvCode,InvName,ISNULL(InvStd, ''),InvUnit,isnull(@WHCode,''),isnull(ToWarehouseCode,''),isnull(@LocationCode,''),0 ,1,ISNULL(AmountUnit, ''),ISNULL(@lotno, ''),
									                                    WHName,ExtensionID,ProjectCode,BatchCode, Version,Brand,cFree1,cFree2,cFree3,cFree4,cFree5,cFree6,cFree7,cFree8,cFree9,cFree10 from #maintemp where #maintemp.transSequence = @transSequence
									                                  
									                                    SET @needqty=0

							                                    END
					                                    END
			                                    FETCH NEXT FROM tempCursor INTO @transSequence;
		                                    END
	                                    CLOSE tempCursor
	                                    DEALLOCATE tempCursor
                                    END

    
									select id,TransCode,DetailID,Type,TransSequence,IssueQuantity,Quantity,
									[User],[MTime],InvCode,InvName,InvStd,InvUnit,WHCode,ToWarehouseCode,LocationCode,sum(LocationQty)as LocationQty,isMatched,AmountUnit,--lotno,
									WHName,ExtensionID,ProjectCode,BatchCode, Version,Brand,cFree1,cFree2,cFree3,cFree4,cFree5,cFree6,cFree7,cFree8,cFree9,cFree10 from #resulttemp GROUP BY id,TransCode,DetailID,Type,TransSequence,IssueQuantity,Quantity,
									[User],[MTime],InvCode,InvName,InvStd,InvUnit,WHCode,ToWarehouseCode,LocationCode,isMatched,AmountUnit,--lotno,
									WHName,ExtensionID,ProjectCode,BatchCode, Version,Brand,cFree1,cFree2,cFree3,cFree4,cFree5,cFree6,cFree7,cFree8,cFree9,cFree10 ORDER BY locationcode ASC ,InvCode ASC


                                DROP table #maintemp
                                DROP table #resulttemp
                                DROP table #barcodetemp";
                    }
                    #endregion
                    if (isDeliveryNotice)//送货、到货、含委外
                    {
                        #region SLQ
                        sql = sqlCheck + @"SELECT a.ID,
                                    {0}
                                    a.InvCode,
                                    inv.InvName,
                                    inv.InvStd,
                                    inv.InvUnit,
                                    '' AS WHCode,
                                    inv.AmountUnit,
                                    '' AS WHName,
                                    a.ExtensionID,
                                    ext.ProjectCode,
                                    CASE WHEN ISNULL(inv.BatchEnable, '0')='1' THEN ext.BatchCode ELSE '' END AS BatchCode,
                                    ext.Version,
                                    ext.Brand,
                                    ext.cFree1,
                                    ext.cFree2,
                                    ext.cFree3,
                                    ext.cFree4,
                                    ext.cFree5,
                                    ext.cFree6,
                                    ext.cFree7,
                                    ext.cFree8,
                                    ext.cFree9,
                                    ext.cFree10
                                    FROM {1}
                                    INNER JOIN ICSExtension ext ON a.ExtensionID=ext.ID AND a.WorkPoint=ext.WorkPoint
                                    INNER JOIN ICSInventory inv ON a.InvCode=inv.InvCode AND a.WorkPoint=inv.WorkPoint
                                    WHERE {2} ";
                        #endregion
                    }
                    else if(isMerge)//合并发料
                    {
                        #region SLQ
                        string sqlMerge = "SELECT ID FROM ICSMOPickMerge WHERE MergeID='"+ JsonData.TransCode + "' AND WorkPoint='"+ JsonData.WorkPoint + "'";
                   
                        DataTable sign = DBHelper.SQlReturnData(sqlMerge, cmd);
                        if (sign != null && sign.Rows.Count > 0)
                        {
                            string whereMerge = string.Format("mer.MergeID='{0}' AND mer.WorkPoint='{1}'", JsonData.TransCode, JsonData.WorkPoint);
                            sql = string.Format(sql, columnsMerge, tableNameMerge, whereMerge, JsonData.TransCode, excessQtySql);
                        }
                        else 
                        {
                            sql = @" BEGIN
                                    IF EXISTS(SELECT a.ID FROM {1} INNER JOIN ICSMOPickMerge c ON a.ID=c.SourceID AND a.WorkPoint=c.WorkPoint WHERE {2})
                                    BEGIN
	                                    RAISERROR('" + language.GetNameByCode("WMSAPIInfo194") + @"',16,1);
                                        RETURN
                                    END
                                " + sqlCheck + sql + @"
                                END";
                        }           
                        #endregion
                    }
                    else
                    {
                        sql = sqlCheck + sql;
                    }
                    
                    where = string.Format(where, JsonData.TransCode, JsonData.WorkPoint);
                    sql = string.Format(sql, columns, tableName, where, JsonData.TransCode,excessQtySql);

                    sqls = string.Format(sqls, JsonData.TransCode, JsonData.WorkPoint);
                    Picksql = string.Format(Picksql,sqls,JsonData.WorkPoint);

                    //DataTable table2 = DBHelper.SQlReturnData(Picksql, cmd);
                    //return table2;
                    log.Debug("源头单据sql:" + sql);

                    DataTable table = DBHelper.SQlReturnData(sql, cmd);
                    return table;
                }
                catch (Exception ex)
                {
                    log.Error(ex.Message);
                    throw new Exception(ex.Message);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                    }
                    conn.Dispose();
                }
            }
        }
        #endregion

        #region 源头单据检料表信息
        /// <summary>
        /// 源头单据信息
        /// </summary>
        /// <param name="JsonData"></param>
        /// <returns></returns>
        public static DataTable TransPickGet(WMSSourceDocumentModel JsonData)
        {
            var language = LanguageHelper.GetName("WMSAPIInfo");
            using (SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString))
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = conn;
                cmd.CommandTimeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["TimeOut"]);
                try
                {
                    if (string.IsNullOrEmpty(JsonData.TransCode))
                    {
                        throw new Exception(language.GetNameByCode("WMSAPIInfo001"));//"单据号不能为空!"
                    }
                    else if (string.IsNullOrEmpty(JsonData.TransType))
                    {
                        throw new Exception(language.GetNameByCode("WMSAPIInfo002"));//"单据类型不能为空!"
                    }
                    else if (!EnumHelper.HasDescriptions(typeof(TransTypeEnum), JsonData.TransType))
                    {
                        throw new Exception(language.GetNameByCode("WMSAPIInfo003"));//"单据类型不存在!"
                    }
                    else if (string.IsNullOrEmpty(JsonData.WorkPoint))
                    {
                        throw new Exception(language.GetNameByCode("WMSAPIInfo004"));//"站点不能为空!"
                    }

                    string TransType = JsonData.TransType;
                    #region SLQ

                    string Picksql = @"SELECT row_number() over (order by c.Code,c.InvCode,d.MTIME,d.LotNO) AS rowNo,
	                        c.Code,
	                        c.InvCode,
	                        c.InvName,
	                        c.InvStd,
c.InvUnit,
	                        FLOOR(c.iQuantity) AS iQuantity,
	                        d.WarehouseCode,
	                        d.LocationCode,
	                        d.LotNO,
	                        FLOOR(ISNULL(d.Quantity, 0)) AS QTY,
	                        CONVERT(varchar(100),d.MTIME, 23) MTIME,
	                        FLOOR(f.QTYTotal) QTYTotal  INTO #temp 
                        FROM
                        ({0}) c
                        LEFT JOIN ICSWareHouseLotInfo d ON c.InvCode=d.INVCode  AND ((LEN(ISNULL(c.WHCode,''))<=0) OR (LEN(ISNULL(c.WHCode,''))>0) AND c.WhCode=d.WarehouseCode)  AND d.WorkPoint='{1}' AND d.Quantity>0
                        left join ICSInventoryLot m on d.LotNo=m.LotNo and d.WorkPoint=m.WorkPoint and c.ExtensionID=m.ExtensionID
                        LEFT JOIN (SELECT INVCode,WarehouseCode,SUM(Quantity) AS QTYTotal FROM ICSWareHouseLotInfo  WHERE WorkPoint='{1}' GROUP BY INVCode,WarehouseCode) f ON c.InvCode=f.INVCode AND c.WhCode=f.WarehouseCode
                        

DECLARE @ItemCode VARCHAR(50),
	@QTY DECIMAL(18,3), 
	@ItemCodeCurrent VARCHAR(50),
	@QTYCurrent DECIMAL(18,3),
	@iQuantityCurrent DECIMAL(18,3),
	@CanDelete BIT,
	@Row INT,
	@rowCurrent INT
SET @Row = @@rowcount
SET @rowCurrent=1
SET @CanDelete=0
SET @ItemCode=''

WHILE @rowCurrent<=@Row
	BEGIN
		SELECT @ItemCodeCurrent=InvCode,@QTYCurrent=QTY,@iQuantityCurrent=iQuantity FROM #temp WHERE rowNo=@rowCurrent

PRINT(@rowCurrent)
		IF @ItemCode<>@ItemCodeCurrent
		BEGIN
			SET @ItemCode=@ItemCodeCurrent
			SET @QTY=0
			SET @CanDelete=0
		END

		IF @CanDelete=1 
		BEGIN
			DELETE FROM #temp WHERE rowNo=@rowCurrent
			SET @rowCurrent += 1
			CONTINUE
		END

		SET @QTY += @QTYCurrent
		IF @QTY>=@iQuantityCurrent
		BEGIN
			SET @CanDelete=1 
		END
		
		SET @rowCurrent += 1
	END
SELECT * FROM #temp
DROP TABLE #temp
";
                    #endregion
                    
                    string sqls = string.Empty;

                    #region 检料表信息
                    if (TransType == TransTypeEnum.MOIssueDoc.GetDescription())
                    {
                        #region 工单备料sql
                        sqls = @" SELECT
	                        c.MOCode as Code,
	                        a.InvCode,
	                        b.InvName,
	                        b.InvStd,
	                        SUM(ISNULL(a.Quantity, 0)) AS iQuantity,
	                        a.WhCode,
b.InvUnit,
							a.ExtensionID
                        FROM
	                        ICSMOPick a
							inner join ICSMO c on a.MODetailID=c.MODetailID and a.WorkPoint=c.WorkPoint
                            LEFT JOIN ICSINVENTORY b ON a.InvCode = b.InvCode AND a.WorkPoint=b.WorkPoint
                            WHERE  c.MOCode  in ('{0}') AND a.WorkPoint = '{1}'
                            GROUP BY c.MOCode,a.InvCode,b.InvName,b.InvStd,b.InvUnit,a.WhCode,a.ExtensionID";
                        #endregion
                    }
                    if (TransType == TransTypeEnum.MOApply.GetDescription())
                    {
                        #region 工单领料SQL
                        sqls = @"   select
	                        a.ApplyCode as Code,
	                        a.InvCode,
	                        b.InvName,
	                        b.InvStd,
b.InvUnit,
	                        SUM(ISNULL(a.Quantity, 0)) AS iQuantity,
	                        a.WhCode,
							a.ExtensionID
                        FROM
	                        ICSMOApply a
                        LEFT JOIN ICSINVENTORY b ON a.InvCode = b.InvCode AND a.WorkPoint=b.WorkPoint
                        WHERE a.ApplyCode in ({0}) AND a.WorkPoint = '{1}'
                        GROUP BY a.ApplyCode,a.InvCode,b.InvName,b.InvStd,b.InvUnit,a.WhCode,a.ExtensionID";
                        #endregion
                    }
                    if (TransType == TransTypeEnum.MOReplenishment.GetDescription())
                    {
                        #region 工单补料SQL
                        sqls = @"   select
	                        a.ReplenishmentCode as Code,
	                        a.InvCode,
	                        b.InvName,
	                        b.InvStd,
b.InvUnit,
	                        SUM(ISNULL(a.Quantity, 0)) AS iQuantity,
	                        a.WhCode,
							a.ExtensionID
                        FROM
	                        ICSMOReplenishment a
                        LEFT JOIN ICSINVENTORY b ON a.InvCode = b.InvCode AND a.WorkPoint=b.WorkPoint
                        WHERE a.ReplenishmentCode in ({0}) AND a.WorkPoint = '{1}'
                        GROUP BY a.ReplenishmentCode,a.InvCode,b.InvName,b.InvStd,b.InvUnit,a.WhCode,a.ExtensionID";
                        #endregion
                    }
                    if (TransType == TransTypeEnum.MOIssue.GetDescription())
                    {
                        #region 工单材料出库SQL
                        sqls = @"  select
	                        a.IssueCode as Code,
	                        a.InvCode,
	                        b.InvName,
	                        b.InvStd,
b.InvUnit,
	                        SUM(ISNULL(a.Quantity, 0)) AS iQuantity,
	                        a.WhCode,
							a.ExtensionID
                        FROM
	                        ICSMOIssue a
                        LEFT JOIN ICSINVENTORY b ON a.InvCode = b.InvCode AND a.WorkPoint=b.WorkPoint
                        WHERE a.IssueCode in ({0}) AND a.WorkPoint = '{1}'
                        GROUP BY a.IssueCode,a.InvCode,b.InvName,b.InvStd,b.InvUnit,a.WhCode,a.ExtensionID";
                        #endregion
                    }
                    if (TransType == TransTypeEnum.OutsourcingIssueDoc.GetDescription())
                    {
                        #region 委外备料SQL
                        sqls = @"   								select
	                        c.OOCode as Code,
	                        a.InvCode,
	                        b.InvName,
	                        b.InvStd,
b.InvUnit,
	                        SUM(ISNULL(a.Quantity, 0)) AS iQuantity,
	                        a.WhCode,
													a.ExtensionID
                        FROM
	                        ICSOOPick a
							left join ICSOutsourcingOrder c on a.OODetailID=c.OODetailID and a.WorkPoint=c.WorkPoint
                        LEFT JOIN ICSINVENTORY b ON a.InvCode = b.InvCode AND a.WorkPoint=b.WorkPoint
                     WHERE c.OOCode in ({0}) AND a.WorkPoint = '{1}'
                        GROUP BY c.OOCode,a.InvCode,b.InvName,b.InvStd,b.InvUnit,a.WhCode,	a.ExtensionID";
                        #endregion
                    }
                    if (TransType == TransTypeEnum.OOApply.GetDescription())
                    {
                        #region 委外领料SQL
                        sqls = @"   	select
	                        a.ApplyCode as Code,
	                        a.InvCode,
	                        b.InvName,
	                        b.InvStd,
b.InvUnit,
	                        SUM(ISNULL(a.Quantity, 0)) AS iQuantity,
	                        a.WhCode,
													a.ExtensionID
                        FROM
	                        ICSOApply a
                        LEFT JOIN ICSINVENTORY b ON a.InvCode = b.InvCode AND a.WorkPoint=b.WorkPoint
                        WHERE a.ApplyCode in ({0}) AND a.WorkPoint = '{1}'
                        GROUP BY a.ApplyCode,a.InvCode,b.InvName,b.InvStd,b.InvUnit,a.WhCode,a.ExtensionID";
                        #endregion
                    }
                    if (TransType == TransTypeEnum.OOIssue.GetDescription())
                    {
                        #region 委外材料出库SQL
                        sqls = @" 	select
	                        a.IssueCode as Code,
	                        a.InvCode,
	                        b.InvName,
	                        b.InvStd,
b.InvUnit,
	                        SUM(ISNULL(a.Quantity, 0)) AS iQuantity,
	                        a.WhCode,
a.ExtensionID
                        FROM
	                        ICSOIssue a
                        LEFT JOIN ICSINVENTORY b ON a.InvCode = b.InvCode AND a.WorkPoint=b.WorkPoint
                     WHERE a.IssueCode in ({0}) AND a.WorkPoint = '{1}'
                        GROUP BY a.IssueCode,a.InvCode,b.InvName,b.InvStd,b.InvUnit,a.WhCode,a.ExtensionID";
                        #endregion
                    }
                    if (TransType == TransTypeEnum.SalesShipmentDoc.GetDescription())
                    {
                        #region 销售发货SQL
                        sqls = @"   select
	                        a.SDNCode as Code,
	                        a.InvCode,
	                        b.InvName,
	                        b.InvStd,
b.InvUnit,
	                        SUM(ISNULL(a.Quantity, 0)) AS iQuantity,
	                        a.WhCode,
a.ExtensionID
                        FROM
	                        ICSSDN a
                        LEFT JOIN ICSINVENTORY b ON a.InvCode = b.InvCode AND a.WorkPoint=b.WorkPoint
                     WHERE a.SDNCode in ('{0}') AND a.WorkPoint = '{1}'
                        GROUP BY a.SDNCode,a.InvCode,b.InvName,b.InvStd,b.InvUnit,a.WhCode,a.ExtensionID";
                        #endregion
                    }
                    if (TransType == TransTypeEnum.OtherOutDoc.GetDescription())
                    {
                        #region 其它出库SQL
                        sqls = @" select
	                        a.OutCode as Code,
	                        a.InvCode,
	                        b.InvName,
	                        b.InvStd,
b.InvUnit,
	                        SUM(ISNULL(a.Quantity, 0)) AS iQuantity,
	                        a.WhCode,
a.ExtensionID
                        FROM
	                        ICSOtherOut a
                        LEFT JOIN ICSINVENTORY b ON a.InvCode = b.InvCode AND a.WorkPoint=b.WorkPoint
                        WHERE a.OutCode in ({0}) AND a.WorkPoint = '{1}'
                        GROUP BY a.OutCode,a.InvCode,b.InvName,b.InvStd,b.InvUnit,a.WhCode,a.ExtensionID";
                        #endregion
                    }
                    if (TransType == TransTypeEnum.BrrowDoc.GetDescription())
                    {
                        #region 借用SQL
                        sqls = @"select
	                        a.BrrowCode as Code,
	                        a.InvCode,
						
	                        b.InvName,
	                        b.InvStd,
b.InvUnit,
	                        SUM(ISNULL(a.Quantity, 0)) AS iQuantity,
	                        a.WhCode,
a.ExtensionID
                        FROM
	                        ICSBrrow a
                        LEFT JOIN ICSINVENTORY b ON a.InvCode = b.InvCode AND a.WorkPoint=b.WorkPoint
                        WHERE a.BrrowCode in ({0}) AND a.WorkPoint = '{1}'
                        GROUP BY a.BrrowCode,a.InvCode,b.InvName,b.InvStd,b.InvUnit,a.WhCode,a.ExtensionID";
                        #endregion
                    }
                    if (TransType == TransTypeEnum.OneStepTransferDocIn.GetDescription())
                    {
                        #region 物料调拨
                        sqls = @"						select
	                        a.TransferNO as Code,
	                        a.InvCode,
						
	                        b.InvName,
	                        b.InvStd,
b.InvUnit,
	                        SUM(ISNULL(a.Quantity, 0)) AS iQuantity,
	                        a.FromWarehouseCode as WhCode,
a.ExtensionID
                        FROM
	                        ICSTransfer a
                        LEFT JOIN ICSINVENTORY b ON a.InvCode = b.InvCode AND a.WorkPoint=b.WorkPoint
						 WHERE a.TransferNO in ({0}) AND a.WorkPoint = '{1}'
                        GROUP BY a.TransferNO,a.InvCode,b.InvName,b.InvStd,b.InvUnit,a.FromWarehouseCode,a.ExtensionID";
                        #endregion
                    }
                    if (TransType == TransTypeEnum.TwoStepTransferDocOut.GetDescription())
                    {
                        #region 两步调出
                        sqls = @"select
	                        a.OutCode as Code,
	                        a.InvCode,
						
	                        b.InvName,
	                        b.InvStd,
b.InvUnit,
	                        SUM(ISNULL(a.Quantity, 0)) AS iQuantity,
	                        a.WHCode ,
a.ExtensionID
                     from  ICSOtherOut a
                        INNER JOIN ICSTransfer tra ON a.TransferDetailID=tra.TransferDetailID AND a.WorkPoint=tra.WorkPoint
                        LEFT JOIN ICSINVENTORY b ON a.InvCode = b.InvCode AND a.WorkPoint=b.WorkPoint
						 WHERE a.OutCode in ({0}) AND a.WorkPoint = '{1}'
                        GROUP BY a.OutCode,a.InvCode,b.InvName,b.InvStd,b.InvUnit,a.WHCode,a.ExtensionID";
                        #endregion
                    }
                    #endregion

                    sqls = string.Format(sqls, JsonData.TransCode, JsonData.WorkPoint);
                    Picksql = string.Format(Picksql, sqls, JsonData.WorkPoint);

                    DataTable table = DBHelper.SQlReturnData(Picksql, cmd);
                    return table;

                }
                catch (Exception ex)
                {
                    log.Error(ex.Message);
                    throw new Exception(ex.Message);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                    }
                    conn.Dispose();
                }
            }
        }
        #endregion

        /// <summary>
        /// 所有未完成单据号
        /// </summary>
        /// <param name="JsonData"></param>
        /// <returns></returns>
        public static DataTable TransCodeGet(WMSSourceDocumentModel JsonData)
        {
            var language = LanguageHelper.GetName("WMSAPIInfo");
            using (SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString))
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = conn;
                cmd.CommandTimeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["TimeOut"]);
                try
                {
                    if (string.IsNullOrEmpty(JsonData.TransType))
                    {
                        throw new Exception(language.GetNameByCode("WMSAPIInfo002"));//"单据类型不能为空!"
                    }
                    else if (!EnumHelper.HasDescriptions(typeof(TransTypeEnum), JsonData.TransType))
                    {
                        throw new Exception(language.GetNameByCode("WMSAPIInfo003"));//"单据类型不存在!"
                    }
                    else if (string.IsNullOrEmpty(JsonData.WorkPoint))
                    {
                        throw new Exception(language.GetNameByCode("WMSAPIInfo004"));//"站点不能为空!"
                    }

                    string TransType = JsonData.TransType;
                    #region SLQ
                    //string sqlCheck = @"IF NOT EXISTS(SELECT a.ID FROM {1} WHERE {2})
                    //                BEGIN
                    //                 RAISERROR('" + language.GetNameByCode("WMSAPIInfo035") + @"',16,1);
                    //                    RETURN
                    //                END
                    //                ";
                    string sql = @"SELECT 
                                    {0}
                                    FROM {1}
                                    WHERE {2} 
                                    order by TransCode asc";
                    #endregion

                    bool isDeliveryNotice = false;      //送货、到货、含委外
                    bool MOApplyWithBin = false;      //生产领料-库位
                    bool OtherOutDocWithBin = false;      //杂发-库位
                    string columns = string.Empty;      //查询源头单据表的特殊列名
                    string tableName = string.Empty;    //查询源头单据表名
                    string where = string.Empty;        //查询源头单据的过滤条件
                    bool isMerge = false;               //合并发料
                    string columnsMerge = string.Empty;      //合并发料查询源头单据表的特殊列名
                    string tableNameMerge = string.Empty;    //合并发料查询源头单据表名
                    #region 出库
                    #region 采购退货
                    if (TransType == TransTypeEnum.PurchaseReceiveDoctNegative.GetDescription())
                    {
                        columns = @" DISTINCT a.DNCode AS TransCode";

                        tableName = @"ICSDeliveryNotice a ";

                        where = @" a.WorkPoint='{1}' AND a.DNType='2' AND a.Status='2' AND (a.Quantity-a.RCVQuantity)>0";
                    }
                    #endregion
                    #region 其他出库
                    else if (TransType == TransTypeEnum.OtherOutDoc.GetDescription())
                    {
                        columns = @" DISTINCT a.OutCode AS TransCode";

                        tableName = @"ICSOtherOut a ";

                        where = @" a.Status='1' AND a.WorkPoint='{1}' and a.Quantity>a.OutQuantity";
                    }
                    #endregion
                    #region 一步调拨(合并发料)
                    else if (TransType == TransTypeEnum.OneStepTransferDocIn.GetDescription())
                    {
                        columns = @" DISTINCT a.TransferNO AS TransCode";

                        tableName = @"ICSTransfer a ";

                        where = @"  a.WorkPoint='{1}' AND a.Status='1' AND a.Quantity>a.TransferQuantity AND Type='1'";
                    }
                    #endregion
                    #region 调拨申请单(合并发料)
                    else if (TransType == TransTypeEnum.StepTransferApplicationIn.GetDescription())
                    {
                        columns = @" DISTINCT a.TransferNO AS TransCode";

                        tableName = @"ICSTransferApplication a ";

                        where = @"  a.WorkPoint='{1}' AND a.Status='2' AND a.Quantity>a.TransferQuantity AND Type='1'";
                    }
                    #endregion
                    #region 委外退料
                    else if (TransType == TransTypeEnum.ICSOutsourcingIssueDoNegative.GetDescription())
                    {
                        columns = @" DISTINCT a.OApplyNegCode AS TransCode";

                        tableName = @"ICSOApplyNegDetail a 
                                    INNER JOIN ICSOApplyNeg d ON a.OApplyNegCode=d.OApplyNegCode AND a.WorkPoint=d.WorkPoint";

                        where = @"  a.WorkPoint='{1}' AND d.Status='1' AND a.Quantity>a.IssueNegQuantity AND d.Type='1'";
                    }
                    #endregion
                    #region 生产发料(合并发料)
                    else if (TransType == TransTypeEnum.MOIssueDoc.GetDescription())
                    {
                        columns = @" DISTINCT b.MOCode AS TransCode";

                        tableName = @" ICSMOPick  a
	                                INNER JOIN ICSMO b ON  a.MODetailID=b.MODetailID AND a.WorkPoint=b.WorkPoint ";

                        where = @" a.WorkPoint='{1}' AND a.SupplyType='3' AND b.MOStatus<>'3' and a.EATTRIBUTE1<>'1' and a.Quantity-a.IssueQuantity>0";
                    }
                    #endregion
                    #region 开立材料出库(合并发料)
                    else if (TransType == TransTypeEnum.MOIssue.GetDescription())
                    {
                        columns = @" DISTINCT a.IssueCode AS TransCode";

                        tableName = @" ICSMOIssue a ";

                        where = @" a.WorkPoint='{1}' AND a.Status<>'3' and a.Quantity-a.IssueQuantity>0";
                    }
                    #endregion
                    #region 生产发料-领料申请单
                    else if (TransType == TransTypeEnum.MOApply.GetDescription())
                    {
                        columns = @" DISTINCT a.ApplyCode AS TransCode";

                        tableName = @" ICSMOApply a";

                        where = @" a.Status='2' AND a.WorkPoint='{1}' and a.Quantity-a.IssueQuantity>0";
                    }
                    #endregion
                    #region 开立委外材料出库(合并发料)
                    else if (TransType == TransTypeEnum.OOIssue.GetDescription())
                    {
                        columns = @" DISTINCT a.IssueCode AS TransCode";

                        tableName = @" ICSOIssue a ";

                        where = @" a.WorkPoint='{1}' AND a.Status<>'3' and a.Quantity-a.IssueQuantity>0";
                    }
                    #endregion
                    #region 委外领料申请单发料(合并发料)
                    else if (TransType == TransTypeEnum.OOApply.GetDescription())
                    {
                        columns = @" DISTINCT a.ApplyCode AS TransCode";

                        tableName = @" ICSOApply a  ";

                        where = @" a.WorkPoint='{1}' AND a.Status<>'3' and a.Quantity-a.IssueQuantity>0";
                    }
                    #endregion
                    #region 委外发料(合并发料)
                    else if (TransType == TransTypeEnum.OutsourcingIssueDoc.GetDescription())
                    {
                        columns = @" DISTINCT b.OOCode AS TransCode";

                        tableName = @" ICSOOPick  a
                                INNER JOIN ICSOutsourcingOrder b ON  a.OODetailID=b.OODetailID AND a.WorkPoint=b.WorkPoint ";

                        where = @" a.WorkPoint='{1}' AND a.SupplyType='3' AND b.Status<>'3' and a.EATTRIBUTE1<>'1' and a.Quantity-a.IssueQuantity>0";
                    }
                    #endregion
                    #region 销售出库(合并发料)
                    else if (TransType == TransTypeEnum.SalesShipmentDoc.GetDescription())
                    {
                        columns = @" DISTINCT a.SDNCode AS TransCode";

                        tableName = @"ICSSDN a ";

                        where = @" a.WorkPoint='{1}' AND a.Type='1' AND a.Status<>'3' and a.Quantity-a.SDNQuantity>0";
                    }
                    #endregion
                    #region 盘点
                    else if (TransType == TransTypeEnum.Check.GetDescription())
                    {

                        columns = @" DISTINCT a.CheckCode AS TransCode";

                        tableName = @"ICSCheck a ";

                        where = @" a.WorkPoint='{1}' ";
                    }
                    #endregion
                    where = string.Format(where, JsonData.TransCode, JsonData.WorkPoint);
                    sql = string.Format(sql, columns, tableName, where, JsonData.TransCode);
                    log.Debug("源头单据sql : " + sql);
                    DataTable table = DBHelper.SQlReturnData(sql, cmd);
                    return table;
                    #endregion
                }
                catch (Exception ex)
                {
                    log.Error(ex.Message);
                    throw new Exception(ex.Message);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                    }
                    conn.Dispose();
                }
            }
        }

        #region 条码信息
        /// <summary>
        /// 条码信息
        /// </summary>
        /// <param name="JsonData"></param>
        /// <returns></returns>
        public static Result BarCodeInformationGet(BarCodeModel JsonData)
        {
            var language = LanguageHelper.GetName("WMSAPIInfo");
            DataTable table = new DataTable();
            DataTable ZLtable = new DataTable();
            using (SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString))
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = conn;
                cmd.CommandTimeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["TimeOut"]);
                try
                {
                    string ScanType = DBHelper.ScanTypeCheck(JsonData.Code, JsonData.WorkPoint, cmd);
                    if (string.IsNullOrEmpty(JsonData.Code))
                    {
                        throw new Exception(language.GetNameByCode("WMSAPIInfo005"));//"条码不能为空!"
                    }
                    else if (string.IsNullOrEmpty(JsonData.TransType))
                    {
                        throw new Exception(language.GetNameByCode("WMSAPIInfo002"));//"单据类型不能为空!"
                    }
                    else if (!EnumHelper.HasDescriptions(typeof(TransTypeEnum), JsonData.TransType))
                    {
                        throw new Exception(language.GetNameByCode("WMSAPIInfo003"));//"单据类型不存在!"
                    }
                    else if (string.IsNullOrEmpty(JsonData.WorkPoint))
                    {
                        throw new Exception(language.GetNameByCode("WMSAPIInfo004"));//"站点不能为空!"
                    }

                    string TransType = JsonData.TransType;
                    string sql = "";
                    string LotTypesql = "";
                    string Losql = "";
                    string sqlNew = "";
                    string LotType = "";
                    bool iszl = false;
                    string zlqty = "0";
                    bool needIns = ICSControlModeService.GetOrderIns(EnumHelper.GetDBValue(typeof(TransTypeEnum), TransType));
                    
                    #region SLQ
                    if (TransType == TransTypeEnum.LocationSeatch.GetDescription())
                    {
                        //Losql = @"SELECT a.ID,
                        //            con.ContainerCode,
                        //            con.ContainerName,
                        //            a.LotNo,
                        //            a.InvCode,
                        //            inv.InvName,
                        //            inv.InvStd,
                        //            inv.InvUnit,
                        //            inv.LotEnable,
                        //            {0}
                        //            inv.AmountUnit,
                        //            ext.ID AS ExtensionID,
                        //            ext.ProjectCode,
                        //            ext.Version,
                        //            ext.Brand,
                        //            ext.cFree1,
                        //            ext.cFree2,
                        //            ext.cFree3,
                        //            ext.cFree4,
                        //            ext.cFree5,
                        //            ext.cFree6,
                        //            ext.cFree7,
                        //            ext.cFree8,
                        //            ext.cFree9,
                        //            ext.cFree10,
                        //            a.MUSER AS [User],
                        //            a.MTIME AS [MTime]
                        //            FROM {1}
                        //            LEFT JOIN ICSContainerLot conlot ON a.LotNo=conlot.LotNo AND a.WorkPoint=conlot.WorkPoint
                        //            LEFT JOIN ICSContainer con ON conlot.ContainerID=con.ID AND conlot.WorkPoint=con.WorkPoint
                        //            INNER JOIN ICSInventory inv ON a.InvCode=inv.InvCode AND a.WorkPoint=inv.WorkPoint
                        //            WHERE a.Quantity>0 and a.WorkPoint='{3}'";
                        Losql = @"  DECLARE @wheresql VARCHAR(MAX)
								    DECLARE @groupsql VARCHAR(MAX)
								    DECLARE @aa VARCHAR(MAX)
								    DECLARE @bb VARCHAR(MAX)
								    DECLARE @cc VARCHAR(MAX)
								    DECLARE @dd VARCHAR(MAX)
								    DECLARE @b VARCHAR(MAX)

								    select @aa=id from ICSWareHouseLotInfo where LotNo='{2}'
										    IF @aa IS NOT NULL
											    BEGIN
											    set @wheresql='and a.lotno=''{2}''  and s.invcode IN(SELECT invcode FROM ICSWareHouseLotInfo where LotNo=''{2}'') and a.invcode=s.invcode '
											    set @groupsql=' group by inv.LotEnable,a.ID,con.ContainerCode,con.ContainerName,a.LotNo,a.InvCode,inv.InvName,inv.InvStd,inv.InvUnit,inv.LotEnable,a.warehouseCode,a.LocationCode, inv.INVCODE,inv.INVNAME,inv.INVSTD,a.Quantity,inv.AmountUnit,
								    ext.ID,ext.ProjectCode,ext.Version,ext.Brand,ext.cFree1,ext.cFree2,ext.cFree3,ext.cFree4,ext.cFree5,ext.cFree6,ext.cFree7,ext.cFree8,ext.cFree9,ext.cFree10,a.MUSER ,a.MTIME'
										    END
											
								    select @bb=id from ICSLocation where LocationCode like '%{2}%'
									    IF @bb IS not NULL
										    BEGIN
											    set @wheresql='and a.locationcode=s.locationcode and  a.LocationCode like ''%{2}%'' '
											    set @groupsql = 'group by inv.LotEnable,a.ID,con.ContainerCode,con.ContainerName,a.LotNo,a.InvCode,inv.InvName,inv.InvStd,inv.InvUnit,inv.LotEnable,a.warehouseCode,a.LocationCode, inv.INVCODE,inv.INVNAME,inv.INVSTD,a.Quantity,inv.AmountUnit,
								    ext.ID,ext.ProjectCode,ext.Version,ext.Brand,ext.cFree1,ext.cFree2,ext.cFree3,ext.cFree4,ext.cFree5,ext.cFree6,ext.cFree7,ext.cFree8,ext.cFree9,ext.cFree10,a.MUSER ,a.MTIME'
									        END
										
								    select @cc=id from ICSInventory where invcode='{2}'
										    IF @cc IS not NULL
											    BEGIN
												    set @wheresql='and  inv.invcode=''{2}'' and a.invcode=s.invcode '
												    set @groupsql='group by inv.LotEnable,a.ID,con.ContainerCode,con.ContainerName,a.LotNo,a.InvCode,inv.InvName,inv.InvStd,inv.InvUnit,inv.LotEnable,a.WarehouseCode,a.LocationCode, inv.INVCODE,inv.INVNAME,inv.INVSTD,a.Quantity,inv.AmountUnit,
								    ext.ID,ext.ProjectCode,ext.Version,ext.Brand,ext.cFree1,ext.cFree2,ext.cFree3,ext.cFree4,ext.cFree5,ext.cFree6,ext.cFree7,ext.cFree8,ext.cFree9,ext.cFree10,a.MUSER ,a.MTIME'
										    END
												
								    select @dd=id from ICSInventory where InvStd LIKE '%{2}%'
										    IF @dd IS not NULL
											    BEGIN
												    set @wheresql='and inv.InvStd LIKE ''%{2}%'' '
												    set @groupsql='group by inv.LotEnable,a.ID,con.ContainerCode,con.ContainerName,a.LotNo,a.InvCode,inv.InvName,inv.InvStd,inv.InvUnit,inv.LotEnable,a.WarehouseCode,a.LocationCode, inv.INVCODE,inv.INVNAME,inv.INVSTD,a.Quantity,inv.AmountUnit,
								    ext.ID,ext.ProjectCode,ext.Version,ext.Brand,ext.cFree1,ext.cFree2,ext.cFree3,ext.cFree4,ext.cFree5,ext.cFree6,ext.cFree7,ext.cFree8,ext.cFree9,ext.cFree10,a.MUSER ,a.MTIME'
										    END
												
								    IF @aa IS NULL and @bb IS NULL and @cc IS NULL and @dd IS NULL
								    BEGIN
									    RAISERROR('" + language.GetNameByCode("WMSAPIInfo478") + @"',16,1)
								    END
								    ELSE
								    BEGIN
													
									    set @b =
										    'SELECT a.ID,con.ContainerCode,con.ContainerName,a.LotNo,a.InvCode,
																    inv.InvName,
																    inv.InvStd,
																    inv.InvUnit,
																    inv.LotEnable,
																    a.WarehouseCode,a.LocationCode,a.Quantity as Qty,SUM(s.sumQty) sumQty,
																    inv.AmountUnit,
																    ext.ID AS ExtensionID,
																    ext.ProjectCode,
																    ext.Version,
																    ext.Brand,
																    ext.cFree1,
																    ext.cFree2,
																    ext.cFree3,
																    ext.cFree4,
																    ext.cFree5,
																    ext.cFree6,
																    ext.cFree7,
																    ext.cFree8,
																    ext.cFree9,
																    ext.cFree10,
																    a.MUSER AS [User],
																    a.MTIME AS [MTime]
																    FROM ICSWareHouseLotInfo a 
										    LEFT JOIN ICSLocation b ON a.LocationCode = b.LocationCode and a.WorkPoint=b.WorkPoint
										    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
										    LEFT JOIN (select SUM(Quantity) AS sumQty,WarehouseCode,INVCode,LocationCode,workpoint from ICSWareHouseLotInfo where quantity>0  group by WarehouseCode,INVCode,LocationCode,workpoint)s ON a.workpoint=s.workpoint 
										    LEFT JOIN ICSContainerLot conlot ON a.LotNo=conlot.LotNo AND a.WorkPoint=conlot.WorkPoint
										    LEFT JOIN ICSContainer con ON conlot.ContainerID=con.ID AND conlot.WorkPoint=con.WorkPoint
										    INNER JOIN ICSInventory inv ON a.InvCode=inv.InvCode AND a.WorkPoint=inv.WorkPoint
										    WHERE   a.Quantity>0 and a.WorkPoint=''{3}'' ' + @wheresql + @groupsql
								    END
												
								exec(@b)				
										
				
										
";
                    }
                    else
                    {
                        if (ScanType == "LOTNO")
                        {
                            sql = @"SELECT a.ID,
                                    con.ContainerCode,
                                    con.ContainerName,
                                    a.LotNo,
                                    a.InvCode,
                                    inv.InvName,
                                    inv.InvStd,
                                    inv.InvUnit,
                                    inv.LotEnable,
                                    {0}
                                    inv.AmountUnit,
                                    ext.ID AS ExtensionID,
                                    ext.ProjectCode,
                                    ext.Version,
                                    ext.Brand,
                                    ext.cFree1,
                                    ext.cFree2,
                                    ext.cFree3,
                                    ext.cFree4,
                                    ext.cFree5,
                                    ext.cFree6,
                                    ext.cFree7,
                                    ext.cFree8,
                                    ext.cFree9,
                                    ext.cFree10,
                                    a.MUSER AS [User],
                                    a.MTIME AS [MTime]
                                    FROM {1}
                                    LEFT JOIN ICSContainerLot conlot ON a.LotNo=conlot.LotNo AND a.WorkPoint=conlot.WorkPoint
                                    LEFT JOIN ICSContainer con ON conlot.ContainerID=con.ID AND conlot.WorkPoint=con.WorkPoint
                                    INNER JOIN ICSInventory inv ON a.InvCode=inv.InvCode AND a.WorkPoint=inv.WorkPoint
                                    WHERE  a.LotNo='{2}' AND a.WorkPoint='{3}' ";
                        }
                        else
                        {
                            sql = @"SELECT a.ID,
                                    con.ContainerCode,
                                    con.ContainerName,
                                    a.LotNo,
                                    a.InvCode,
                                    inv.InvName,
                                    inv.InvStd,
                                    inv.InvUnit,
                                    {0}
                                    inv.AmountUnit,
                                    ext.ID AS ExtensionID,
                                    ext.ProjectCode,
                                    ext.Version,
                                    ext.Brand,
                                    ext.cFree1,
                                    ext.cFree2,
                                    ext.cFree3,
                                    ext.cFree4,
                                    ext.cFree5,
                                    ext.cFree6,
                                    ext.cFree7,
                                    ext.cFree8,
                                    ext.cFree9,
                                    ext.cFree10,
                                    a.MUSER AS [User],
                                    a.MTIME AS [MTime]
                                    FROM {1}
                                    LEFT JOIN ICSContainerLot conlot ON a.LotNo=conlot.LotNo AND a.WorkPoint=conlot.WorkPoint
                                    LEFT JOIN ICSBomALL bom ON bom.ID=conlot.ContainerID
                                    LEFT JOIN ICSContainer con ON conlot.ContainerID=con.ID AND conlot.WorkPoint=con.WorkPoint
                                    INNER JOIN ICSInventory inv ON a.InvCode=inv.InvCode AND a.WorkPoint=inv.WorkPoint
                                    WHERE  bom.ContainerCode='{2}' AND a.WorkPoint='{3}' ";
                        }
                    }
                        

                    
                    
                    #endregion
                    bool isOut = false;                 //出库标记
                    string columns = string.Empty;      //查询源头单据表的特殊列名
                    string columnsLOCODE = string.Empty;
                    string columnsLONAME = string.Empty;
                    string columnsWHCODE = string.Empty;
                    string columnsWHNAME = string.Empty;
                    string tableName = string.Empty;    //查询源头单据表名
                    string where = string.Empty;    //排序
                    if (TransType == TransTypeEnum.PurchaseReceiveDoctNegative.GetDescription()    //采购退货
                        || TransType == TransTypeEnum.OutsourcingIssueDoc.GetDescription()         //委外发料
                        || TransType == TransTypeEnum.OutsourcingReturnBack.GetDescription()       //委外退货
                        || TransType == TransTypeEnum.MOIssueDoc.GetDescription()                  //生产发料
                        || TransType == TransTypeEnum.SalesShipmentDoc.GetDescription()            //销售出库
                        || TransType == TransTypeEnum.OneStepTransferDocIn.GetDescription()        //一步调拨
                        || TransType == TransTypeEnum.StepTransferDocIn.GetDescription()        //调拨
                        || TransType == TransTypeEnum.StepNoTransferDocIn.GetDescription()        //无源头调拨
                        || TransType == TransTypeEnum.StepTransferApplicationIn.GetDescription()        //调拨申请单
                        || TransType == TransTypeEnum.TwoStepTransferDocOut.GetDescription()       //两步调出
                        || TransType == TransTypeEnum.OtherOutDoc.GetDescription()                 //其他出库
                        || TransType == TransTypeEnum.Check.GetDescription()                       //盘点
                        || TransType == TransTypeEnum.MOApply.GetDescription()                     //领料申请单
                        || TransType == TransTypeEnum.MOReplenishment.GetDescription()                     //领料申请单
                        || TransType == TransTypeEnum.OOApply.GetDescription()                     //委外领料申请单
                        || TransType == TransTypeEnum.MOIssue.GetDescription()                     //开立材料出库单
                        || TransType == TransTypeEnum.OOIssue.GetDescription()                     //开立委外材料出库单
                        || TransType == TransTypeEnum.PurchaseReceive.GetDescription()             //开立红字入库单
                        || TransType == TransTypeEnum.OutsourcingReceiveDocNegative.GetDescription()//开立委外红字入库单
                        || TransType == TransTypeEnum.BrrowDoc.GetDescription()                    //借用
                        || TransType == TransTypeEnum.TransferLibrary.GetDescription()             //移库
                        //|| TransType == TransTypeEnum.DisassemblyDoc.GetDescription()             //拆卸单(散件生成条码入库)
                        )
                    {
                        isOut = true;
                    }
                    //库位查询
                    if (TransType == TransTypeEnum.LocationSeatch.GetDescription())
                    {
           //             Losql = @"" + Losql + "group by a.ID,con.ContainerCode,con.ContainerName,a.LotNo,a.InvCode,inv.InvName,inv.InvStd,inv.InvUnit,inv.LotEnable,s.WarehouseCode, inv.INVCODE,inv.INVNAME,inv.INVSTD,s.sumQty,inv.AmountUnit,ext.ID,ext.ProjectCode,ext.Version,ext.Brand, " +
           //                 "ext.cFree1,ext.cFree2,ext.cFree3,ext.cFree4,ext.cFree5,ext.cFree6,ext.cFree7,ext.cFree8,ext.cFree9,ext.cFree10,a.MUSER ,a.MTIME";

           //             columns = @"s.WarehouseCode, inv.INVCODE,inv.INVNAME,inv.INVSTD,sum(a.Quantity) as Qty,s.sumQty,";

           //             tableName = @"ICSWareHouseLotInfo a 
											//LEFT JOIN ICSLocation b ON a.LocationCode = b.LocationCode and a.WorkPoint=b.WorkPoint
											//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
											//LEFT JOIN (select SUM(Quantity) AS sumQty,WarehouseCode,INVCode from ICSWareHouseLotInfo  group by WarehouseCode,INVCode)s 
											//ON a.INVCode=s.INVCode ";

                    }
                    else
                    {
                        //两步调入条码
                        if (TransType == TransTypeEnum.TwoStepTransferDocIn.GetDescription())
                        {
                            if (string.IsNullOrEmpty(JsonData.TransCode))
                            {
                                throw new Exception(language.GetNameByCode("WMSAPIInfo001"));//"单据号不能为空!"
                            }
                            if (ScanType == "LOTNO")
                            {
                                sql = @"IF NOT EXISTS(SELECT a.ID FROM ICSOtherIn Otin
                                            INNER JOIN ICSTransfer tra ON Otin.TransferDetailID=tra.TransferDetailID AND Otin.WorkPoint=tra.WorkPoint
                                            INNER JOIN ICSOtherOut out ON out.TransferDetailID=tra.TransferDetailID AND out.WorkPoint=tra.WorkPoint
                                            INNER JOIN ICSWareHouseLotInfoLog log ON out.OutCode=log.TransCode AND out.Sequence=log.TransSequence AND out.WorkPoint=log.WorkPoint
                                            INNER JOIN ICSWareHouseLotInfo a ON a.LotNo=log.LotNo AND a.WorkPoint=log.WorkPoint
                                            WHERE a.LotNo='{2}' AND a.WorkPoint='{3}' AND Otin.InCode = '" + JsonData.TransCode + @"')
                                    BEGIN
	                                    RAISERROR('" + language.GetNameByCode("WMSAPIInfo036") + @"',16,1);
                                        RETURN
                                    END
                                    " + sql + "AND Otin.InCode = '" + JsonData.TransCode + @"'
                                    GROUP BY inv.LotEnable,a.ID,con.ContainerCode,con.ContainerName,a.LotNo,a.InvCode,inv.InvName,inv.InvStd,inv.InvUnit,a.WarehouseCode,
                                    wh.WarehouseName,a.LocationCode,loc.LocationName,CASE WHEN (invBat.BatchEnable IS NULL AND ISNULL(inv.BatchEnable, '0')='1') OR ISNULL(invBat.BatchEnable, '0')='1' THEN ISNULL(ext.BatchCode, '') ELSE '' END,inv.AmountUnit,
                                    ext.ID,ext.ProjectCode,ext.Version,ext.Brand,ext.cFree1,ext.cFree2,ext.cFree3,ext.cFree4,ext.cFree5,ext.cFree6,ext.cFree7,ext.cFree8,ext.cFree9,ext.cFree10,a.MUSER,a.MTIME";

                                columns = @"SUM(log.Quantity) AS Quantity,
                                    SUM(log.Quantity*(lot.Amount/lot.Quantity)) AS Amount,
                                    a.WarehouseCode AS WHCode,
                                    wh.WarehouseName AS WHName,
                                    a.LocationCode,
                                    loc.LocationName,
                                    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,";

                                tableName = @"ICSOtherIn Otin
                                    INNER JOIN ICSTransfer tra ON Otin.TransferDetailID=tra.TransferDetailID AND Otin.WorkPoint=tra.WorkPoint
                                    INNER JOIN ICSOtherOut out ON out.TransferDetailID=tra.TransferDetailID AND out.WorkPoint=tra.WorkPoint
                                    INNER JOIN ICSWareHouseLotInfoLog log ON out.OutCode=log.TransCode AND out.Sequence=log.TransSequence AND out.WorkPoint=log.WorkPoint
                                    INNER JOIN ICSWareHouseLotInfo a ON a.LotNo=log.LotNo AND a.WorkPoint=log.WorkPoint
                                    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 ICSWarehouse wh ON a.WarehouseCode=wh.WarehouseCode AND a.WorkPoint=wh.WorkPoint
                                    INNER JOIN ICSLocation loc ON a.LocationCode=loc.LocationCode AND a.WorkPoint=loc.WorkPoint
                                    LEFT JOIN ICSInventoryBatchEnable invBat ON a.InvCode=invBat.InvCode AND a.WarehouseCode=invBat.WHCode AND a.WorkPoint=invBat.WorkPoint";
                            }
                            else
                            {
                                sql = @"WITH ICSBomALL AS
                                    (
	                                    SELECT
		                                    ContainerCode AS TContainerCode,
		                                    ContainerCode AS PContainerCode,
		                                    ContainerCode AS ContainerCode,
		                                    ID,
		                                    ContainerID,
		                                    0 AS [Level],
		                                    CAST(1 AS nvarchar(MAX)) AS SortSeq,
		                                    CAST('00001' AS nvarchar(MAX)) AS Sort
	                                    FROM ICSContainer
	                                    WHERE ContainerCode='{2}'
                                    UNION ALL
	                                    SELECT
		                                    b.TContainerCode,
		                                    b.ContainerCode AS PContainerCode,
		                                    a.ContainerCode,
		                                    a.ID,
		                                    a.ContainerID,
		                                    b.[Level]+1 AS [Level],
		                                    CAST(b.SortSeq AS nvarchar(MAX))+'.'+CAST(row_number() over (order by a.ContainerCode) AS nvarchar(MAX)) AS SortSeq,
		                                    CAST(b.Sort+'.'+REPLICATE('0',5-len(row_number() over (order by a.ContainerCode)))+CAST(row_number() over (order by a.ContainerCode) AS nvarchar(MAX)) AS nvarchar(MAX)) AS Sort
	                                    FROM
		                                    ICSContainer a
	                                    INNER JOIN ICSBomALL b ON a.ID=b.ContainerID
                                    )
                                    " + sql + "AND Otin.InCode = '" + JsonData.TransCode + @"'
                                    GROUP BY inv.LotEnable,a.ID,con.ContainerCode,con.ContainerName,a.LotNo,a.InvCode,inv.InvName,inv.InvStd,inv.InvUnit,a.WarehouseCode,
                                    wh.WarehouseName,a.LocationCode,loc.LocationName,CASE WHEN (invBat.BatchEnable IS NULL AND ISNULL(inv.BatchEnable, '0')='1') OR ISNULL(invBat.BatchEnable, '0')='1' THEN ISNULL(ext.BatchCode, '') ELSE '' END,inv.AmountUnit,
                                    ext.ID,ext.ProjectCode,ext.Version,ext.Brand,ext.cFree1,ext.cFree2,ext.cFree3,ext.cFree4,ext.cFree5,ext.cFree6,ext.cFree7,ext.cFree8,ext.cFree9,ext.cFree10,a.MUSER,a.MTIME";

                                columns = @"SUM(log.Quantity) AS Quantity,
                                    SUM(log.Quantity*(lot.Amount/lot.Quantity)) AS Amount,
                                    a.WarehouseCode AS WHCode,
                                    wh.WarehouseName AS WHName,
                                    a.LocationCode,
                                    loc.LocationName,
                                    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,";

                                tableName = @"ICSOtherIn Otin
                                    INNER JOIN ICSTransfer tra ON Otin.TransferDetailID=tra.TransferDetailID AND Otin.WorkPoint=tra.WorkPoint
                                    INNER JOIN ICSOtherOut out ON out.TransferDetailID=tra.TransferDetailID AND out.WorkPoint=tra.WorkPoint
                                    INNER JOIN ICSWareHouseLotInfoLog log ON out.OutCode=log.TransCode AND out.Sequence=log.TransSequence AND out.WorkPoint=log.WorkPoint
                                    INNER JOIN ICSWareHouseLotInfo a ON a.LotNo=log.LotNo AND a.WorkPoint=log.WorkPoint
                                    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 ICSWarehouse wh ON a.WarehouseCode=wh.WarehouseCode AND a.WorkPoint=wh.WorkPoint
                                    INNER JOIN ICSLocation loc ON a.LocationCode=loc.LocationCode AND a.WorkPoint=loc.WorkPoint
                                    LEFT JOIN ICSInventoryBatchEnable invBat ON a.InvCode=invBat.InvCode AND a.WarehouseCode=invBat.WHCode AND a.WorkPoint=invBat.WorkPoint";
                            }


                        }
                        //销售退货-原条码(可支持一个条码多次发货,汇总数量,目前加了限制:785-793行)
                        else if (TransType == TransTypeEnum.SalesReturnBack.GetDescription())
                        {
                            if (string.IsNullOrEmpty(JsonData.TransCode))
                            {
                                throw new Exception(language.GetNameByCode("WMSAPIInfo001"));//"单据号不能为空!"
                            }
                            if (ScanType == "LOTNO")
                            {
                                sql = @"IF NOT EXISTS(SELECT a.ID FROM ICSSDN sdn
                                            INNER JOIN ICSWareHouseLotInfoLog log ON sdn.SDNCode=log.TransCode AND sdn.Sequence=log.TransSequence AND sdn.WorkPoint=log.WorkPoint
                                            INNER JOIN ICSWareHouseLotInfo a ON a.LotNo=log.LotNo AND a.WorkPoint=log.WorkPoint
                                            WHERE a.LotNo='{2}' AND a.WorkPoint='{3}' AND sdn.Type='1')
                                    BEGIN
	                                    RAISERROR('" + language.GetNameByCode("WMSAPIInfo037") + @"',16,1);
                                        RETURN
                                    END
                                IF EXISTS(SELECT log.LotNo FROM ICSSDN sdn
                                            INNER JOIN ICSWareHouseLotInfoLog log ON sdn.SDNCode=log.TransCode AND sdn.Sequence=log.TransSequence AND sdn.WorkPoint=log.WorkPoint
                                            INNER JOIN ICSWareHouseLotInfo a ON a.LotNo=log.LotNo AND a.WorkPoint=log.WorkPoint
                                            WHERE a.LotNo='{2}' AND a.WorkPoint='{3}' AND sdn.Type='1' AND log.BusinessCode='19'
                                            GROUP BY log.LotNo HAVING COUNT(log.LotNo)>=2)
                                    BEGIN
	                                    RAISERROR('" + string.Format(language.GetNameByCode("WMSAPIInfo191"), "{2}") + @"',16,1);
                                        RETURN
                                    END
                                    " + sql + @"AND sdn.Type='1'
                                    GROUP BY inv.LotEnable,a.ID,con.ContainerCode,con.ContainerName,a.LotNo,a.InvCode,inv.InvName,inv.InvStd,inv.InvUnit,a.WarehouseCode,
                                    wh.WarehouseName,a.LocationCode,loc.LocationName,CASE WHEN (invBat.BatchEnable IS NULL AND ISNULL(inv.BatchEnable, '0')='1') OR ISNULL(invBat.BatchEnable, '0')='1' THEN ISNULL(ext.BatchCode, '') ELSE '' END,inv.AmountUnit,
                                    ext.ID,ext.ProjectCode,ext.Version,ext.Brand,ext.cFree1,ext.cFree2,ext.cFree3,ext.cFree4,ext.cFree5,ext.cFree6,ext.cFree7,ext.cFree8,ext.cFree9,ext.cFree10,a.MUSER,a.MTIME";

                                columns = @"SUM(log.Quantity) AS Quantity,
                                    SUM(log.Quantity*(lot.Amount/lot.Quantity)) AS Amount,
                                    a.WarehouseCode AS WHCode,
                                    wh.WarehouseName AS WHName,
                                    a.LocationCode,
                                    loc.LocationName,
                                    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,";

                                tableName = @"ICSSDN sdn
                                    INNER JOIN ICSWareHouseLotInfoLog log ON sdn.SDNCode=log.TransCode AND sdn.Sequence=log.TransSequence AND sdn.WorkPoint=log.WorkPoint
                                    INNER JOIN ICSWareHouseLotInfo a ON a.LotNo=log.LotNo AND a.WorkPoint=log.WorkPoint
                                    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 ICSWarehouse wh ON a.WarehouseCode=wh.WarehouseCode AND a.WorkPoint=wh.WorkPoint
                                    INNER JOIN ICSLocation loc ON a.LocationCode=loc.LocationCode AND a.WorkPoint=loc.WorkPoint
                                    LEFT JOIN ICSInventoryBatchEnable invBat ON a.InvCode=invBat.InvCode AND a.WarehouseCode=invBat.WHCode AND a.WorkPoint=invBat.WorkPoint";
                            }
                            else
                            {
                                sql = @"WITH ICSBomALL AS
                                    (
	                                    SELECT
		                                    ContainerCode AS TContainerCode,
		                                    ContainerCode AS PContainerCode,
		                                    ContainerCode AS ContainerCode,
		                                    ID,
		                                    ContainerID,
		                                    0 AS [Level],
		                                    CAST(1 AS nvarchar(MAX)) AS SortSeq,
		                                    CAST('00001' AS nvarchar(MAX)) AS Sort
	                                    FROM ICSContainer
	                                    WHERE ContainerCode='{2}'
                                    UNION ALL
	                                    SELECT
		                                    b.TContainerCode,
		                                    b.ContainerCode AS PContainerCode,
		                                    a.ContainerCode,
		                                    a.ID,
		                                    a.ContainerID,
		                                    b.[Level]+1 AS [Level],
		                                    CAST(b.SortSeq AS nvarchar(MAX))+'.'+CAST(row_number() over (order by a.ContainerCode) AS nvarchar(MAX)) AS SortSeq,
		                                    CAST(b.Sort+'.'+REPLICATE('0',5-len(row_number() over (order by a.ContainerCode)))+CAST(row_number() over (order by a.ContainerCode) AS nvarchar(MAX)) AS nvarchar(MAX)) AS Sort
	                                    FROM
		                                    ICSContainer a
	                                    INNER JOIN ICSBomALL b ON a.ID=b.ContainerID
                                    )
                                    " + sql + @"AND sdn.Type='1'
                                    GROUP BY inv.LotEnable,a.ID,con.ContainerCode,con.ContainerName,a.LotNo,a.InvCode,inv.InvName,inv.InvStd,inv.InvUnit,a.WarehouseCode,
                                    wh.WarehouseName,a.LocationCode,loc.LocationName,CASE WHEN (invBat.BatchEnable IS NULL AND ISNULL(inv.BatchEnable, '0')='1') OR ISNULL(invBat.BatchEnable, '0')='1' THEN ISNULL(ext.BatchCode, '') ELSE '' END,inv.AmountUnit,
                                    ext.ID,ext.ProjectCode,ext.Version,ext.Brand,ext.cFree1,ext.cFree2,ext.cFree3,ext.cFree4,ext.cFree5,ext.cFree6,ext.cFree7,ext.cFree8,ext.cFree9,ext.cFree10,a.MUSER,a.MTIME";

                                columns = @"SUM(log.Quantity) AS Quantity,
                                    SUM(log.Quantity*(lot.Amount/lot.Quantity)) AS Amount,
                                    a.WarehouseCode AS WHCode,
                                    wh.WarehouseName AS WHName,
                                    a.LocationCode,
                                    loc.LocationName,
                                    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,";

                                tableName = @"ICSSDN sdn
                                    INNER JOIN ICSWareHouseLotInfoLog log ON sdn.SDNCode=log.TransCode AND sdn.Sequence=log.TransSequence AND sdn.WorkPoint=log.WorkPoint
                                    INNER JOIN ICSWareHouseLotInfo a ON a.LotNo=log.LotNo AND a.WorkPoint=log.WorkPoint
                                    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 ICSWarehouse wh ON a.WarehouseCode=wh.WarehouseCode AND a.WorkPoint=wh.WorkPoint
                                    INNER JOIN ICSLocation loc ON a.LocationCode=loc.LocationCode AND a.WorkPoint=loc.WorkPoint
                                    LEFT JOIN ICSInventoryBatchEnable invBat ON a.InvCode=invBat.InvCode AND a.WarehouseCode=invBat.WHCode AND a.WorkPoint=invBat.WorkPoint";
                            }

                        }
                        //生产(委外)退料-原条码+新条码
                        //先校验日志里面是否有原条码(同一种类型的条码只能发一次料才能原条码退,不然更新源头单据数量有问题,根据LogID判断是否原条码退回),如果没有查询新条码
                        else if (TransType == TransTypeEnum.MOIssueDocNegative.GetDescription()
                            || TransType == TransTypeEnum.MOIssueDocNegativeApply.GetDescription()
                            || TransType == TransTypeEnum.MOIssueDocNegativeIssue.GetDescription()
                            || TransType == TransTypeEnum.ICSOutsourcingIssueDoNegative.GetDescription()
                            || TransType == TransTypeEnum.ICSOutsourcingIssueDoNegativeApply.GetDescription()
                            || TransType == TransTypeEnum.ICSOutsourcingIssueDoNegativeIssue.GetDescription())
                        {
                            string type = "13";
                            string msglanguage = "WMSAPIInfo185";
                            if (TransType == TransTypeEnum.MOIssueDocNegativeApply.GetDescription())
                            {
                                type = "14";
                                msglanguage = "WMSAPIInfo186";
                            }
                            else if (TransType == TransTypeEnum.MOIssueDocNegativeIssue.GetDescription())
                            {
                                type = "15";
                                msglanguage = "WMSAPIInfo187";
                            }
                            else if (TransType == TransTypeEnum.ICSOutsourcingIssueDoNegative.GetDescription())
                            {
                                type = "5";
                                msglanguage = "WMSAPIInfo188";
                            }
                            else if (TransType == TransTypeEnum.ICSOutsourcingIssueDoNegativeApply.GetDescription())
                            {
                                type = "6";
                                msglanguage = "WMSAPIInfo189";
                            }
                            else if (TransType == TransTypeEnum.ICSOutsourcingIssueDoNegativeIssue.GetDescription())
                            {
                                type = "7";
                                msglanguage = "WMSAPIInfo190";
                            }
                            #region 新条码
                            if (ScanType == "LOTNO")
                            {
                                sqlNew = @"IF NOT EXISTS(SELECT a.ID FROM ICSInventoryLot a WHERE a.LotNo='{2}' AND a.WorkPoint='{3}')
                                    BEGIN
	                                    RAISERROR('" + string.Format(language.GetNameByCode("WMSAPIInfo038"), "{2}") + @"',16,1);
                                        RETURN
                                    END
                                IF EXISTS(SELECT a.ID FROM ICSWareHouseLotInfo a WHERE a.LotNo='{2}' AND a.WorkPoint='{3}')
                                    BEGIN
	                                    RAISERROR('" + language.GetNameByCode("WMSAPIInfo039") + @"',16,1);
                                        RETURN
                                    END
                                IF EXISTS(SELECT a.ID FROM ICSInventoryLot a 
                                        INNER JOIN ICSInventory b ON a.InvCode=b.InvCode AND a.WorkPoint=b.WorkPoint
                                        LEFT JOIN ICSInspection ins ON a.LotNo=ins.LotNo AND a.WorkPoint=ins.WorkPoint
                                        WHERE a.LotNo='{2}' AND a.WorkPoint='{3}' AND (b.InvIQC='1'AND ins.LotNo IS NULL))
                                    BEGIN
	                                    RAISERROR('" + language.GetNameByCode("WMSAPIInfo040") + @"',16,1);
                                        RETURN
                                    END
                                    " + sql;

                                if (TransType == TransTypeEnum.MOIssueDocNegative.GetDescription()
                            || TransType == TransTypeEnum.MOIssueDocNegativeApply.GetDescription()
                            || TransType == TransTypeEnum.MOIssueDocNegativeIssue.GetDescription())
                                {
                                    columns = @"ISNULL(ins.QualifiedQuantity+ins.WaiveQuantity, a.Quantity) AS Quantity,
                                    a.Quantity*(a.Amount/a.Quantity) AS Amount,
                                    (select negg.WHCode from ICSMOApplyNegDetail neg 
                                    INNER JOIN ICSMOApplyNeg negg ON neg.ApplyNegCode=negg.ApplyNegCode
									inner join ICSInventoryLotDetail lotdetail on neg.ApplyNegCode=lotdetail.TransCode
									and neg.Sequence=lotdetail.TransSequence 
									where lotdetail.LotNo=a.LotNo and lotdetail.WorkPoint=a.WorkPoint) AS WHCode,
                                    '' AS WHName,
                                    '' AS LocationCode,
                                    '' AS LocationName,
                                    '' AS LogID,
                                    ext.BatchCode AS BatchCode,";
                                }

                                if (TransType == TransTypeEnum.ICSOutsourcingIssueDoNegative.GetDescription()
                            || TransType == TransTypeEnum.ICSOutsourcingIssueDoNegativeApply.GetDescription()
                            || TransType == TransTypeEnum.ICSOutsourcingIssueDoNegativeIssue.GetDescription())
                                {
                                    columns = @"ISNULL(ins.QualifiedQuantity+ins.WaiveQuantity, a.Quantity) AS Quantity,
                                    a.Quantity*(a.Amount/a.Quantity) AS Amount,
                                    (select negg.WHCode from ICSOApplyNegDetail neg 
                                    INNER JOIN ICSOApplyNeg negg ON neg.OApplyNegCode=negg.OApplyNegCode
									inner join ICSInventoryLotDetail lotdetail on neg.OApplyNegCode=lotdetail.TransCode
									and neg.Sequence=lotdetail.TransSequence 
									where lotdetail.LotNo=a.LotNo and lotdetail.WorkPoint=a.WorkPoint) AS WHCode,
                                    '' AS WHName,
                                    '' AS LocationCode,
                                    '' AS LocationName,
                                    '' AS LogID,
                                    ext.BatchCode AS BatchCode,";
                                }
                                    

                                tableName = @"ICSInventoryLot a
                                    INNER JOIN ICSExtension ext ON a.ExtensionID=ext.ID AND a.WorkPoint=ext.WorkPoint
                                    LEFT JOIN ICSInspection ins ON a.LotNo=ins.LotNo AND a.WorkPoint=ins.WorkPoint";
                            }
                            else
                            {
                                sqlNew = @"WITH ICSBomALL AS
                                    (
	                                    SELECT
		                                    ContainerCode AS TContainerCode,
		                                    ContainerCode AS PContainerCode,
		                                    ContainerCode AS ContainerCode,
		                                    ID,
		                                    ContainerID,
		                                    0 AS [Level],
		                                    CAST(1 AS nvarchar(MAX)) AS SortSeq,
		                                    CAST('00001' AS nvarchar(MAX)) AS Sort
	                                    FROM ICSContainer
	                                    WHERE ContainerCode='{2}'
                                    UNION ALL
	                                    SELECT
		                                    b.TContainerCode,
		                                    b.ContainerCode AS PContainerCode,
		                                    a.ContainerCode,
		                                    a.ID,
		                                    a.ContainerID,
		                                    b.[Level]+1 AS [Level],
		                                    CAST(b.SortSeq AS nvarchar(MAX))+'.'+CAST(row_number() over (order by a.ContainerCode) AS nvarchar(MAX)) AS SortSeq,
		                                    CAST(b.Sort+'.'+REPLICATE('0',5-len(row_number() over (order by a.ContainerCode)))+CAST(row_number() over (order by a.ContainerCode) AS nvarchar(MAX)) AS nvarchar(MAX)) AS Sort
	                                    FROM
		                                    ICSContainer a
	                                    INNER JOIN ICSBomALL b ON a.ID=b.ContainerID
                                    )
                                    " + sql;

                                columns = @"ISNULL(ins.QualifiedQuantity+ins.WaiveQuantity, a.Quantity) AS Quantity,
                                    a.Quantity*(a.Amount/a.Quantity) AS Amount,
                                    '' AS WHCode,
                                    '' AS WHName,
                                    '' AS LocationCode,
                                    '' AS LocationName,
                                    ext.BatchCode AS BatchCode,";

                                tableName = @"ICSInventoryLot a
                                    INNER JOIN ICSExtension ext ON a.ExtensionID=ext.ID AND a.WorkPoint=ext.WorkPoint
                                    LEFT JOIN ICSInspection ins ON a.LotNo=ins.LotNo AND a.WorkPoint=ins.WorkPoint";
                            }

                            sqlNew = string.Format(sqlNew, columns, tableName, JsonData.Code, JsonData.WorkPoint, zlqty);
                            #endregion
                            #region 原条码
                            if (ScanType == "LOTNO")
                            {
                                sql = sql + @" AND log.BusinessCode IN('" + type + @"') GROUP BY inv.LotEnable,log.ID,a.ID,con.ContainerCode,con.ContainerName,a.LotNo,a.InvCode,inv.InvName,inv.InvStd,inv.InvUnit,a.WarehouseCode,
                                wh.WarehouseName,a.LocationCode,loc.LocationName,CASE WHEN(invBat.BatchEnable IS NULL AND ISNULL(inv.BatchEnable, '0')= '1') OR ISNULL(invBat.BatchEnable, '0')= '1' THEN ISNULL(ext.BatchCode, '') ELSE '' END,inv.AmountUnit,
                                ext.ID,ext.ProjectCode,ext.Version,ext.Brand,ext.cFree1,ext.cFree2,ext.cFree3,ext.cFree4,ext.cFree5,ext.cFree6,ext.cFree7,ext.cFree8,ext.cFree9,ext.cFree10,a.MUSER,a.MTIME
                                ";
                                sql = @"IF EXISTS(" + sql + @")
                                BEGIN
                                " + sql + @"
                                END
                                ELSE
                                BEGIN
                                " + sqlNew + @"
                                END";
                                sql = @"IF EXISTS(SELECT log.LotNo FROM ICSWareHouseLotInfoLog log
                                        INNER JOIN ICSWareHouseLotInfo a ON a.LotNo=log.LotNo AND a.WorkPoint=log.WorkPoint
                                        WHERE a.LotNo='{2}' AND a.WorkPoint='{3}' AND log.BusinessCode='" + type + @"'
                                        GROUP BY log.LotNo HAVING COUNT(log.LotNo)>=2)
                                BEGIN
	                                RAISERROR('" + string.Format(language.GetNameByCode(msglanguage), "{2}") + @"',16,1);
                                    RETURN
                                END
                                " + sql;

                                columns = @"SUM(log.Quantity) AS Quantity,
                                    SUM(log.Quantity*(lot.Amount/lot.Quantity)) AS Amount,
                                    a.WarehouseCode AS WHCode,
                                    wh.WarehouseName AS WHName,
                                    a.LocationCode,
                                    loc.LocationName,
                                    log.ID AS LogID,
                                    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,";

                                tableName = @"ICSWareHouseLotInfoLog log
                                    INNER JOIN ICSWareHouseLotInfo a ON a.LotNo=log.LotNo AND a.WorkPoint=log.WorkPoint
                                    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 ICSWarehouse wh ON a.WarehouseCode=wh.WarehouseCode AND a.WorkPoint=wh.WorkPoint
                                    INNER JOIN ICSLocation loc ON a.LocationCode=loc.LocationCode AND a.WorkPoint=loc.WorkPoint
                                    LEFT JOIN ICSInventoryBatchEnable invBat ON a.InvCode=invBat.InvCode AND a.WarehouseCode=invBat.WHCode AND a.WorkPoint=invBat.WorkPoint";
                            }
                            else
                            {
                                sql = sql + @" AND log.BusinessCode IN('" + type + @"') GROUP BY inv.LotEnable,log.ID,a.ID,con.ContainerCode,con.ContainerName,a.LotNo,a.InvCode,inv.InvName,inv.InvStd,inv.InvUnit,a.WarehouseCode,
                                wh.WarehouseName,a.LocationCode,loc.LocationName,CASE WHEN(invBat.BatchEnable IS NULL AND ISNULL(inv.BatchEnable, '0')= '1') OR ISNULL(invBat.BatchEnable, '0')= '1' THEN ISNULL(ext.BatchCode, '') ELSE '' END,inv.AmountUnit,
                                ext.ID,ext.ProjectCode,ext.Version,ext.Brand,ext.cFree1,ext.cFree2,ext.cFree3,ext.cFree4,ext.cFree5,ext.cFree6,ext.cFree7,ext.cFree8,ext.cFree9,ext.cFree10,a.MUSER,a.MTIME
                                ";
                                sql = @"IF EXISTS(" + sql + @")
                                BEGIN
                                " + sql + @"
                                END
                                ELSE
                                BEGIN
                                " + sqlNew + @"
                                END";
                                sql = @"WITH ICSBomALL AS
                                    (
	                                    SELECT
		                                    ContainerCode AS TContainerCode,
		                                    ContainerCode AS PContainerCode,
		                                    ContainerCode AS ContainerCode,
		                                    ID,
		                                    ContainerID,
		                                    0 AS [Level],
		                                    CAST(1 AS nvarchar(MAX)) AS SortSeq,
		                                    CAST('00001' AS nvarchar(MAX)) AS Sort
	                                    FROM ICSContainer
	                                    WHERE ContainerCode='{2}'
                                    UNION ALL
	                                    SELECT
		                                    b.TContainerCode,
		                                    b.ContainerCode AS PContainerCode,
		                                    a.ContainerCode,
		                                    a.ID,
		                                    a.ContainerID,
		                                    b.[Level]+1 AS [Level],
		                                    CAST(b.SortSeq AS nvarchar(MAX))+'.'+CAST(row_number() over (order by a.ContainerCode) AS nvarchar(MAX)) AS SortSeq,
		                                    CAST(b.Sort+'.'+REPLICATE('0',5-len(row_number() over (order by a.ContainerCode)))+CAST(row_number() over (order by a.ContainerCode) AS nvarchar(MAX)) AS nvarchar(MAX)) AS Sort
	                                    FROM
		                                    ICSContainer a
	                                    INNER JOIN ICSBomALL b ON a.ID=b.ContainerID
                                    )
                                " + sql;

                                columns = @"SUM(log.Quantity) AS Quantity,
                                    SUM(log.Quantity*(lot.Amount/lot.Quantity)) AS Amount,
                                    a.WarehouseCode AS WHCode,
                                    wh.WarehouseName AS WHName,
                                    a.LocationCode,
                                    loc.LocationName,
                                    log.ID AS LogID,
                                    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,";

                                tableName = @"ICSWareHouseLotInfoLog log
                                    INNER JOIN ICSWareHouseLotInfo a ON a.LotNo=log.LotNo AND a.WorkPoint=log.WorkPoint
                                    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 ICSWarehouse wh ON a.WarehouseCode=wh.WarehouseCode AND a.WorkPoint=wh.WorkPoint
                                    INNER JOIN ICSLocation loc ON a.LocationCode=loc.LocationCode AND a.WorkPoint=loc.WorkPoint
                                    LEFT JOIN ICSInventoryBatchEnable invBat ON a.InvCode=invBat.InvCode AND a.WarehouseCode=invBat.WHCode AND a.WorkPoint=invBat.WorkPoint";
                            }

                            #endregion
                        }
                        //分批
                        else if (TransType == TransTypeEnum.LOTSplit.GetDescription() || TransType == TransTypeEnum.LOTMerge.GetDescription())
                        {
                            sql = @"IF NOT EXISTS(SELECT a.ID FROM ICSWareHouseLotInfo a WHERE a.LotNo='{2}' AND a.WorkPoint='{3}' AND a.Quantity>0)
                                    BEGIN
	                                    RAISERROR('" + string.Format(language.GetNameByCode("WMSAPIInfo038"), "{2}") + @"',16,1);
                                        RETURN
                                    END
                                    " + sql;

                            columns = @"a.Quantity,
                                    a.Quantity*(lot.Amount/lot.Quantity) AS Amount,
                                    a.WarehouseCode AS WHCode,
                                    wh.WarehouseName AS WHName,
                                    a.LocationCode,
                                    loc.LocationName,
                                    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(split.SplitLotNo, a.LotNo+'-1') AS SplitLotNo,";

                            tableName = @"ICSWareHouseLotInfo 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 ICSWarehouse wh ON a.WarehouseCode=wh.WarehouseCode AND a.WorkPoint=wh.WorkPoint
                                    INNER JOIN ICSLocation loc ON a.LocationCode=loc.LocationCode AND a.WorkPoint=loc.WorkPoint
                                    LEFT JOIN (SELECT EATTRIBUTE1 AS LotNo,WorkPoint,EATTRIBUTE1+'-'+CAST((MAX(CAST(reverse(substring(reverse(LotNo),1,charindex('-',reverse(LotNo)) - 1)) AS INT))+1) AS VARCHAR) AS SplitLotNo FROM ICSInventoryLot GROUP BY EATTRIBUTE1,WorkPoint) split ON a.LotNo=split.LotNo AND a.WorkPoint=split.WorkPoint
                                    LEFT JOIN ICSInventoryBatchEnable invBat ON a.InvCode=invBat.InvCode AND a.WarehouseCode=invBat.WHCode AND a.WorkPoint=invBat.WorkPoint";
                        }
                        //出库条码
                        else if (isOut)
                        {
                            if (TransType == TransTypeEnum.MOIssueDoc.GetDescription() || TransType == TransTypeEnum.MOApply.GetDescription()
                                   || TransType == TransTypeEnum.MOIssue.GetDescription() || TransType == TransTypeEnum.OutsourcingIssueDoc.GetDescription()
                                   || TransType == TransTypeEnum.OOApply.GetDescription() || TransType == TransTypeEnum.OOIssue.GetDescription()
                                   || TransType == TransTypeEnum.SalesShipmentDoc.GetDescription() || TransType == TransTypeEnum.OtherOutDoc.GetDescription()
                                   || TransType == TransTypeEnum.BrrowDoc.GetDescription() || TransType == TransTypeEnum.StepTransferDocIn.GetDescription()
                                   || TransType == TransTypeEnum.TwoStepTransferDocOut.GetDescription() || TransType == TransTypeEnum.MOReplenishment.GetDescription())
                            {
                                if (JsonData.IsPick!="1")
                                {
                                    ZLtable = ICSControlModeService.GetZL();
                                    if (ZLtable == null)
                                    {
                                        throw new Exception(language.GetNameByCode("WMSAPIInfo471"));
                                    }

                                    for (int i = 0; i < ZLtable.Rows.Count; i++)
                                    {

                                        string zlName = ZLtable.Rows[i]["Name"].ToString();
                                        string zlTransCode = ZLtable.Rows[i]["BusinessCode"].ToString();
                                        string Enable = ZLtable.Rows[i]["Enable"].ToString();
                                        if (JsonData.TransType.Equals(zlName))
                                        {
                                            if (Enable.Equals("True"))
                                            {
                                                string zlsql = @"IF NOT EXISTS(select a.Quantity,c.Name from ICSWareHouseLotInfoLog a 
                                            left join ICSInventoryLot b on a.LotNo=b.LotNo and a.WorkPoint=b.WorkPoint and a.InvCode=b.InvCode
                                            left join ICSType c on a.BusinessCode=c.Code and c.tablecode='ICSWareHouseLotInfoLog' and c.ColumnCode='BusinessCode'
                                            where b.LotNo='{0}' and b.WorkPoint='{1}' and a.TransType='15' and c.name='{2}' and a.TransCode='{3}')
                                            BEGIN
	                                            RAISERROR('" + language.GetNameByCode("WMSAPIInfo469") + @"',16,1);
                                                RETURN
                                            END
                                            select a.Quantity,c.Name from ICSWareHouseLotInfoLog a 
                                            left join ICSInventoryLot b on a.LotNo=b.LotNo and a.WorkPoint=b.WorkPoint and a.InvCode=b.InvCode
                                            left join ICSType c on a.BusinessCode=c.Code and c.tablecode='ICSWareHouseLotInfoLog' and c.ColumnCode='BusinessCode'
                                            where b.LotNo='{0}' and b.WorkPoint='{1}' and a.TransType='15' and c.name='{2}' and a.TransCode='{3}'";
                                                zlsql = string.Format(zlsql, JsonData.Code, JsonData.WorkPoint, JsonData.TransType, JsonData.TransCode);
                                                DataTable zlltable = DBHelper.SQlReturnData(zlsql, cmd);
                                                if (zlltable != null || zlltable.Rows.Count > 0)
                                                {

                                                    zlqty = zlltable.Rows[0]["Quantity"].ToString();
                                                    iszl = true;
                                                }
                                            }
                                        }
                                    }

                                }
                                
                            }
                                

                            if (ScanType == "LOTNO")
                            {
                                sql = @"IF NOT EXISTS(SELECT a.ID FROM ICSWareHouseLotInfo a WHERE a.LotNo='{2}' AND a.WorkPoint='{3}' AND a.Quantity>0)
                                    BEGIN
	                                    RAISERROR('" + string.Format(language.GetNameByCode("WMSAPIInfo038"), "{2}") + @"',16,1);
                                        RETURN
                                    END
                                    " + sql;

                                if (iszl)
                                {
                                    columns = @"{0} as Quantity,
                                    {0}*(lot.Amount/lot.Quantity) AS Amount,
                                    a.id AS LogID,
                                    a.FromWarehouseCode AS WHCode,
                                    wh.WarehouseName AS WHName,
                                    inv.LotEnable,     
                                    a.FromLocationCode,    
                                    loc.LocationName,     
                                    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,";
                                    columns = string.Format(columns, zlqty);

                                    tableName = @"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 ICSWarehouse wh ON a.FromWarehouseCode=wh.WarehouseCode AND a.WorkPoint=wh.WorkPoint
                                    INNER JOIN ICSLocation loc ON a.FromLocationCode=loc.LocationCode AND a.WorkPoint=loc.WorkPoint
                                    LEFT JOIN ICSInventoryBatchEnable invBat ON a.InvCode=invBat.InvCode AND a.FromWarehouseCode=invBat.WHCode AND a.WorkPoint=invBat.WorkPoint";
                                }
                                else
                                {
                                    if(TransType == TransTypeEnum.Check.GetDescription())
                                    {
                                        columns = @"case when inv.AmountEnable='1' then (a.Quantity-a.lockQuantity)*(lot.Amount/lot.Quantity) else (a.Quantity-a.lockQuantity) end AS Quantity,
                                        (a.Quantity-a.lockQuantity)*(lot.Amount/lot.Quantity) AS Amount,
                                        '' AS LogID,
                                        a.WarehouseCode AS WHCode,
                                        wh.WarehouseName AS WHName,
                                        inv.LotEnable,     
                                        a.LocationCode,    
                                        loc.LocationName,     
                                        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,";

                                            tableName = @"ICSWareHouseLotInfo 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 ICSWarehouse wh ON a.WarehouseCode=wh.WarehouseCode AND a.WorkPoint=wh.WorkPoint
                                        INNER JOIN ICSLocation loc ON a.LocationCode=loc.LocationCode AND a.WorkPoint=loc.WorkPoint
                                        LEFT JOIN ICSInventoryBatchEnable invBat ON a.InvCode=invBat.InvCode AND a.WarehouseCode=invBat.WHCode AND a.WorkPoint=invBat.WorkPoint";
                                    }
                                    else
                                    {
                                        columns = @"(a.Quantity-a.lockQuantity) AS Quantity,
                                        (a.Quantity-a.lockQuantity)*(lot.Amount/lot.Quantity) AS Amount,
                                        '' AS LogID,
                                        a.WarehouseCode AS WHCode,
                                        wh.WarehouseName AS WHName,
                                        inv.LotEnable,     
                                        a.LocationCode,    
                                        loc.LocationName,     
                                        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,";

                                            tableName = @"ICSWareHouseLotInfo 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 ICSWarehouse wh ON a.WarehouseCode=wh.WarehouseCode AND a.WorkPoint=wh.WorkPoint
                                        INNER JOIN ICSLocation loc ON a.LocationCode=loc.LocationCode AND a.WorkPoint=loc.WorkPoint
                                        LEFT JOIN ICSInventoryBatchEnable invBat ON a.InvCode=invBat.InvCode AND a.WarehouseCode=invBat.WHCode AND a.WorkPoint=invBat.WorkPoint";
                                    }
                                    
                                }
                                

                                
                            }
                            else
                            {
                                sql = @"
                                    WITH ICSBomALL AS
                                    (
	                                    SELECT
		                                    ContainerCode AS TContainerCode,
		                                    ContainerCode AS PContainerCode,
		                                    ContainerCode AS ContainerCode,
		                                    ID,
		                                    ContainerID,
		                                    0 AS [Level],
		                                    CAST(1 AS nvarchar(MAX)) AS SortSeq,
		                                    CAST('00001' AS nvarchar(MAX)) AS Sort
	                                    FROM ICSContainer
	                                    WHERE ContainerCode='{2}'
                                    UNION ALL
	                                    SELECT
		                                    b.TContainerCode,
		                                    b.ContainerCode AS PContainerCode,
		                                    a.ContainerCode,
		                                    a.ID,
		                                    a.ContainerID,
		                                    b.[Level]+1 AS [Level],
		                                    CAST(b.SortSeq AS nvarchar(MAX))+'.'+CAST(row_number() over (order by a.ContainerCode) AS nvarchar(MAX)) AS SortSeq,
		                                    CAST(b.Sort+'.'+REPLICATE('0',5-len(row_number() over (order by a.ContainerCode)))+CAST(row_number() over (order by a.ContainerCode) AS nvarchar(MAX)) AS nvarchar(MAX)) AS Sort
	                                    FROM
		                                    ICSContainer a
	                                    INNER JOIN ICSBomALL b ON a.ID=b.ContainerID
                                    )
                                    " + sql;

                                columns = @"(a.Quantity-a.lockQuantity) AS Quantity,
                                    (a.Quantity-a.lockQuantity)*(lot.Amount/lot.Quantity) AS Amount,
                                    a.WarehouseCode AS WHCode,
                                    wh.WarehouseName AS WHName,
                                    a.LocationCode,
                                    loc.LocationName,
                                    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,";

                                tableName = @"ICSWareHouseLotInfo 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 ICSWarehouse wh ON a.WarehouseCode=wh.WarehouseCode AND a.WorkPoint=wh.WorkPoint
                                    INNER JOIN ICSLocation loc ON a.LocationCode=loc.LocationCode AND a.WorkPoint=loc.WorkPoint
                                    LEFT JOIN ICSInventoryBatchEnable invBat ON a.InvCode=invBat.InvCode AND a.WarehouseCode=invBat.WHCode AND a.WorkPoint=invBat.WorkPoint
                                    ";
                            }


                        }
                        //入库条码
                        else
                        {

                            if (ScanType == "LOTNO")
                            {

                                
                                if ((TransType == TransTypeEnum.PurchaseReceiveDoc.GetDescription() || TransType == TransTypeEnum.DeliveryNotice.GetDescription()
                                    || TransType == TransTypeEnum.OutsourcingReceiveDoc.GetDescription() || TransType == TransTypeEnum.ODeliveryNotice.GetDescription()
                                    || TransType == TransTypeEnum.ManufactureReceiveDoc.GetDescription() || TransType == TransTypeEnum.ManufactureReceive.GetDescription()
                                    || TransType == TransTypeEnum.MOStockINByProduct.GetDescription() || TransType == TransTypeEnum.MOStockINByProductNoTrans.GetDescription()
                                    || TransType == TransTypeEnum.OOStockINByProduct.GetDescription() || TransType == TransTypeEnum.OtherInDoc.GetDescription()) && needIns)
                                {
                                    sql = @" 
                                IF NOT EXISTS(SELECT a.ID FROM ICSInventoryLot a WHERE a.LotNo = '{2}' AND a.WorkPoint = '{3}')
                                            BEGIN

                                                RAISERROR('" + string.Format(language.GetNameByCode("WMSAPIInfo038"), "{2}") + @"', 16, 1);
                                RETURN
                                END
                                IF EXISTS(SELECT a.ID FROM ICSWareHouseLotInfo a WHERE a.LotNo='{2}' AND a.WorkPoint='{3}')
                                    BEGIN
	                                    RAISERROR('" + language.GetNameByCode("WMSAPIInfo039") + @"',16,1);
                                        RETURN
                                    END
                                IF EXISTS(SELECT a.ID FROM ICSInventoryLot a 
                                        INNER JOIN ICSInventory b ON a.InvCode=b.InvCode AND a.WorkPoint=b.WorkPoint
										LEFT JOIN ICSInspection ins ON a.LotNo=ins.LotNo AND a.WorkPoint=ins.WorkPoint
                                        WHERE a.LotNo='{2}' AND a.WorkPoint='{3}' AND   (b.InvIQC='1' AND ins.LotNo IS NULL))
                                    BEGIN
	                                    RAISERROR('" + language.GetNameByCode("WMSAPIInfo040") + @"',16,1);
                                        RETURN
                                    END
                                    " + sql;
                                }
                                else
                                {
                                    sql = @" 
                                IF NOT EXISTS(SELECT a.ID FROM ICSInventoryLot a WHERE a.LotNo = '{2}' AND a.WorkPoint = '{3}')
                                            BEGIN

                                                RAISERROR('" + string.Format(language.GetNameByCode("WMSAPIInfo038"), "{2}") + @"', 16, 1);
                                RETURN
                                END
                                IF EXISTS(SELECT a.ID FROM ICSWareHouseLotInfo a WHERE a.LotNo='{2}' AND a.WorkPoint='{3}')
                                    BEGIN
	                                    RAISERROR('" + language.GetNameByCode("WMSAPIInfo039") + @"',16,1);
                                        RETURN
                                    END
                                    " + sql;
                                }
                                    



                                ControlMode mode = ICSControlModeService.GetSuLocation();

                                //获取条码类型
                                LotTypesql = @"IF NOT EXISTS(SELECT Type FROM ICSInventoryLot WHERE LotNo='{0}' AND WorkPoint='{1}')
                                    BEGIN
	                                    RAISERROR('" + language.GetNameByCode("WMSAPIInfo461") + @"',16,1);
                                        RETURN
                                    END
                                        SELECT Type FROM ICSInventoryLot WHERE LotNo='{0}' AND WorkPoint='{1}'";
                                LotTypesql = string.Format(LotTypesql, JsonData.Code, JsonData.WorkPoint);
                                DataTable dt = DBHelper.SQlReturnData(LotTypesql, cmd);
                                if (dt != null && dt.Rows.Count > 0)
                                {
                                    LotType = dt.Rows[0]["Type"].ToString();
                                }

                                if (mode != null)
                                {
                                    if (mode.itemCode.Equals("LocationRemind01"))//固定库位:物料和库位绑定,显示库位名称列表
                                    {
                                        columnsLONAME = @"
                                                (SELECT locat.LocationName from ICSWareHouseLotInfo loinfo
                                                LEFT JOIN ICSLocation locat on locat.LocationCode=loinfo.LocationCode and loinfo.WorkPoint=locat.WorkPoint
                                                where loinfo.lotno=a.lotno and  loinfo.invcode=a.invcode and a.WorkPoint=loinfo.WorkPoint) AS LocationName,";

                                        columnsLOCODE = @"
                                                (SELECT locat.LocationCode from ICSWareHouseLotInfo loinfo
                                                LEFT JOIN ICSLocation locat on locat.LocationCode=loinfo.LocationCode and loinfo.WorkPoint=locat.WorkPoint
                                                where loinfo.lotno=a.lotno and loinfo.invcode=a.invcode and a.WorkPoint=loinfo.WorkPoint) AS LocationCode,";

                                    }
                                    else if (mode.itemCode.Equals("LocationRemind02"))//在库库位:物料有库存的对应库位,显示库位名称列表
                                    {
                                        columnsLONAME = @"
                                            STUFF(
											    (SELECT DISTINCT ',' + LocationName
												    from ICSLocation  wh
												    LEFT JOIN ICSWareHouseLotInfo lotinfo on wh.LocationCode=lotinfo.LocationCode and wh.WorkPoint=lotinfo.WorkPoint 
												    WHERE a.InvCode=lotinfo.InvCode AND a.WorkPoint=lotinfo.WorkPoint and lotinfo.Quantity>0
												    FOR xml path('')
											    ),1,1,''
											    ) AS LocationName,";

                                        columnsLOCODE = @"
                                            STUFF(
											    (SELECT DISTINCT ',' + LocationCode
												    from ICSLocation  wh
												    LEFT JOIN ICSWareHouseLotInfo lotinfo on wh.LocationCode=lotinfo.LocationCode and wh.WorkPoint=lotinfo.WorkPoint 
												    WHERE a.InvCode=lotinfo.InvCode AND a.WorkPoint=lotinfo.WorkPoint and lotinfo.Quantity>0
												    FOR xml path('')
											    ),1,1,''
											    ) AS LocationCode,";
                                    }
                                    else if (mode.itemCode.Equals("LocationRemind03"))//最近一次出入库的库位,显示库位名称
                                    {
                                        columnsLONAME = @"
                                                (SELECT Top 1 locat.LocationName from ICSWareHouseLotInfoLog log 
											LEFT JOIN ICSLocation locat on locat.LocationCode=log.ToLocationCode and log.WorkPoint=locat.WorkPoint where log.TransType='2' and a.InvCode=log.InvCode AND a.WorkPoint=log.WorkPoint
											ORDER BY log.Mtime desc) AS LocationName,";

                                        columnsLOCODE = @"
                                                (SELECT Top 1 locat.LocationCode from ICSWareHouseLotInfoLog log 
											LEFT JOIN ICSLocation locat on locat.LocationCode=log.ToLocationCode and log.WorkPoint=locat.WorkPoint where log.TransType='2' and a.InvCode=log.InvCode AND a.WorkPoint=log.WorkPoint
											ORDER BY log.Mtime desc) AS LocationCode,";
                                    }

                                }
                                else
                                    {
                                    columnsLONAME = @"
                                        STUFF(
											(SELECT DISTINCT ',' + LocationName
												from ICSLocation  wh
												LEFT JOIN ICSWareHouseLotInfoLog lotinfo on wh.LocationCode=lotinfo.ToLocationCode and wh.WorkPoint=lotinfo.WorkPoint 
												WHERE a.InvCode=lotinfo.InvCode AND a.WorkPoint=lotinfo.WorkPoint and (lotinfo.TransType='2' OR lotinfo.TransType='3')
												FOR xml path('')
											),1,1,''
											) AS LocationName,";
                                    columnsLOCODE = @"
                                        STUFF(
											(SELECT DISTINCT ',' + LocationCode
												from ICSLocation  wh
												LEFT JOIN ICSWareHouseLotInfoLog lotinfo on wh.LocationCode=lotinfo.ToLocationCode and wh.WorkPoint=lotinfo.WorkPoint 
												WHERE a.InvCode=lotinfo.InvCode AND a.WorkPoint=lotinfo.WorkPoint and (lotinfo.TransType='2' OR lotinfo.TransType='3')
												FOR xml path('')
											),1,1,''
											) AS LocationCode,";

                                }

                                #region 根据条码类型找到单据仓库信息
                                if (LotType.Equals("1"))
                                {//生产退料
                                    columnsWHCODE = @"ISNULL((SELECT negg.WHCODE FROM ICSMOApplyNegDetail neg LEFT JOIN ICSMOApplyNeg negg ON neg.ApplyNegCode=negg.ApplyNegCode 
                                                        WHERE  lotdd.TransCode=neg.ApplyNegCode AND lotdd.TransSequence=neg.Sequence AND lotdd.WorkPoint=neg.WorkPoint and negg.Type='1'),'') AS WHCode";
                                    columnsWHNAME = @"ISNULL((SELECT WarehouseName from ICSWareHouse where WarehouseCode in (SELECT negg.WHCODE FROM ICSMOApplyNegDetail neg LEFT JOIN ICSMOApplyNeg negg ON neg.ApplyNegCode=negg.ApplyNegCode 
                                                        WHERE  lotdd.TransCode=neg.ApplyNegCode AND lotdd.TransSequence=neg.Sequence AND lotdd.WorkPoint=neg.WorkPoint and negg.Type='1') AND WorkPoint=a.WorkPoint),'') AS WHName";
                                }
                                else if (LotType.Equals("2"))
                                {//委外退料
                                    columnsWHCODE = @"ISNULL((SELECT negg.WHCODE FROM ICSOApplyNegDetail neg LEFT JOIN ICSOApplyNeg negg ON neg.OApplyNegCode=negg.OApplyNegCode 
                                                        WHERE  lotdd.TransCode=neg.OApplyNegCode AND lotdd.TransSequence=neg.Sequence AND lotdd.WorkPoint=neg.WorkPoint and negg.Type='1'),'') AS WHCode";
                                    columnsWHNAME = @"ISNULL((SELECT WarehouseName from ICSWareHouse where WarehouseCode in (SELECT negg.WHCODE FROM ICSOApplyNegDetail neg LEFT JOIN ICSOApplyNeg negg ON neg.OApplyNegCode=negg.OApplyNegCode 
                                                        WHERE  lotdd.TransCode=neg.OApplyNegCode AND lotdd.TransSequence=neg.Sequence AND lotdd.WorkPoint=neg.WorkPoint and negg.Type='1') AND WorkPoint=a.WorkPoint),'') AS WHName";
                                }
                                else if (LotType.Equals("3"))
                                {//工单
                                    columnsWHCODE = @"ISNULL((SELECT a.WHCode FROM ICSMO a WHERE a.MOCode=lotdd.TransCode AND a.Sequence=lotdd.TransSequence AND a.WorkPoint=lotdd.WorkPoint),'') AS WHCode";
                                    columnsWHNAME = @"ISNULL((SELECT WarehouseName from ICSWareHouse where WarehouseCode in (SELECT a.WHCode FROM ICSMO a WHERE a.MOCode=lotdd.TransCode AND a.Sequence=lotdd.TransSequence AND a.WorkPoint=lotdd.WorkPoint) AND WorkPoint=a.WorkPoint),'') AS WHName";
                                }
                                else if (LotType.Equals("4"))
                                {//销售退货
                                    columnsWHCODE = @"ISNULL((SELECT a.WHCode FROM ICSSDN a WHERE a.SDNCode=lotdd.TransCode AND a.Sequence=lotdd.TransSequence AND a.WorkPoint=lotdd.WorkPoint),'') AS WHCode";
                                    columnsWHNAME = @"ISNULL((SELECT WarehouseName from ICSWareHouse where WarehouseCode in (SELECT a.WHCode FROM ICSSDN a WHERE a.SDNCode=lotdd.TransCode AND a.Sequence=lotdd.TransSequence AND a.WorkPoint=lotdd.WorkPoint) AND WorkPoint=a.WorkPoint),'') AS WHName";
                                }
                                else if (LotType.Equals("5"))
                                {//其他入库
                                    columnsWHCODE = @"ISNULL((SELECT a.WHCode FROM ICSOtherIn a WHERE a.InCode=lotdd.TransCode AND a.Sequence=lotdd.TransSequence AND a.WorkPoint=lotdd.WorkPoint),'') AS WHCode";
                                    columnsWHNAME = @"ISNULL((SELECT WarehouseName from ICSWareHouse where WarehouseCode in (SELECT a.WHCode FROM ICSOtherIn a WHERE a.InCode=lotdd.TransCode AND a.Sequence=lotdd.TransSequence AND a.WorkPoint=lotdd.WorkPoint) AND WorkPoint=a.WorkPoint),'') AS WHName";
                                }
                                else if (LotType.Equals("6"))
                                {//归还单
                                    columnsWHCODE = @"ISNULL((SELECT a.WHCode FROM ICSReturn a WHERE a.ReturnCode=lotdd.TransCode AND a.Sequence=lotdd.TransSequence AND a.WorkPoint=lotdd.WorkPoint),'') AS WHCode";
                                    columnsWHNAME = @"ISNULL((SELECT WarehouseName from ICSWareHouse where WarehouseCode in (SELECT a.WHCode FROM ICSReturn a WHERE a.ReturnCode=lotdd.TransCode AND a.Sequence=lotdd.TransSequence AND a.WorkPoint=lotdd.WorkPoint) AND WorkPoint=a.WorkPoint),'') AS WHName";
                                }
                                else if (LotType.Equals("7"))
                                {//采购到货单
                                    columnsWHCODE = @"ISNULL((SELECT a.WHCode FROM ICSDeliveryNotice a WHERE a.DNCode=lotdd.TransCode AND a.Sequence=lotdd.TransSequence AND a.WorkPoint=lotdd.WorkPoint AND a.DNType='1'),'') AS WHCode";
                                    columnsWHNAME = @"ISNULL((SELECT WarehouseName from ICSWareHouse where WarehouseCode in (SELECT a.WHCode FROM ICSDeliveryNotice a WHERE a.DNCode=lotdd.TransCode AND a.Sequence=lotdd.TransSequence AND a.WorkPoint=lotdd.WorkPoint AND a.DNType='1') AND WorkPoint=a.WorkPoint),'') AS WHName";
                                }
                                else if (LotType.Equals("8"))
                                {//委外到货单
                                    columnsWHCODE = @"ISNULL((SELECT a.WHCode FROM ICSODeliveryNotice a WHERE a.ODNCode=lotdd.TransCode AND a.Sequence=lotdd.TransSequence AND a.WorkPoint=lotdd.WorkPoint and a.ODNType='1'),'') AS WHCode";
                                    columnsWHNAME = @"ISNULL((SELECT WarehouseName from ICSWareHouse where WarehouseCode in (SELECT a.WHCode FROM ICSODeliveryNotice a WHERE a.ODNCode=lotdd.TransCode AND a.Sequence=lotdd.TransSequence AND a.WorkPoint=lotdd.WorkPoint and a.ODNType='1') AND WorkPoint=a.WorkPoint),'') AS WHName";
                                }
                                else if (LotType.Equals("9"))
                                {//成品入库单
                                    columnsWHCODE = @"ISNULL((SELECT a.WHCode FROM ICSManufactureReceive a WHERE a.RCVCode=lotdd.TransCode AND a.Sequence=lotdd.TransSequence AND a.WorkPoint=lotdd.WorkPoint),'') AS WHCode";
                                    columnsWHNAME = @"ISNULL((SELECT WarehouseName from ICSWareHouse where WarehouseCode in (SELECT a.WHCode FROM ICSManufactureReceive a WHERE a.RCVCode=lotdd.TransCode AND a.Sequence=lotdd.TransSequence AND a.WorkPoint=lotdd.WorkPoint) AND WorkPoint=a.WorkPoint),'') AS WHName";
                                }
                                else if (LotType.Equals("10"))
                                {//拒收单
                                    columnsWHCODE = @"ISNULL((SELECT a.WHCode FROM ICSDeliveryNotice a WHERE a.DNCode=lotdd.TransCode AND a.Sequence=lotdd.TransSequence AND a.WorkPoint=lotdd.WorkPoint AND a.DNType='3'),'') AS WHCode";
                                    columnsWHNAME = @"ISNULL((SELECT WarehouseName from ICSWareHouse where WarehouseCode in (SELECT a.WHCode FROM ICSDeliveryNotice a WHERE a.DNCode=lotdd.TransCode AND a.Sequence=lotdd.TransSequence AND a.WorkPoint=lotdd.WorkPoint AND a.DNType='3') AND WorkPoint=a.WorkPoint),'') AS WHName";
                                }
                                else if (LotType.Equals("11"))
                                {//委外拒收单
                                    columnsWHCODE = @"ISNULL((SELECT a.WHCode FROM ICSODeliveryNotice a WHERE a.ODNCode=lotdd.TransCode AND a.Sequence=lotdd.TransSequence AND a.WorkPoint=lotdd.WorkPoint and a.ODNType='3'),'') AS WHCode";
                                    columnsWHNAME = @"ISNULL((SELECT WarehouseName from ICSWareHouse where WarehouseCode in (SELECT a.WHCode FROM ICSODeliveryNotice a WHERE a.ODNCode=lotdd.TransCode AND a.Sequence=lotdd.TransSequence AND a.WorkPoint=lotdd.WorkPoint and a.ODNType='3') AND WorkPoint=a.WorkPoint),'') AS WHName";
                                }
                                else if (LotType.Equals("12"))
                                {//领料申请退料
                                    columnsWHCODE = @"ISNULL((SELECT negg.WHCODE FROM ICSMOApplyNegDetail neg LEFT JOIN ICSMOApplyNeg negg ON neg.ApplyNegCode=negg.ApplyNegCode 
                                                        WHERE  lotdd.TransCode=neg.ApplyNegCode AND lotdd.TransSequence=neg.Sequence AND lotdd.WorkPoint=neg.WorkPoint and negg.Type='2'),'') AS WHCode";
                                    columnsWHNAME = @"ISNULL((SELECT WarehouseName from ICSWareHouse where WarehouseCode in (SELECT negg.WHCODE FROM ICSMOApplyNegDetail neg LEFT JOIN ICSMOApplyNeg negg ON neg.ApplyNegCode=negg.ApplyNegCode 
                                                        WHERE  lotdd.TransCode=neg.ApplyNegCode AND lotdd.TransSequence=neg.Sequence AND lotdd.WorkPoint=neg.WorkPoint and negg.Type='2') AND WorkPoint=a.WorkPoint),'') AS WHName";
                                }
                                else if (LotType.Equals("13"))
                                {//材料出库退料
                                    columnsWHCODE = @"ISNULL((SELECT negg.WHCODE FROM ICSMOApplyNegDetail neg LEFT JOIN ICSMOApplyNeg negg ON neg.ApplyNegCode=negg.ApplyNegCode 
                                                        WHERE  lotdd.TransCode=neg.ApplyNegCode AND lotdd.TransSequence=neg.Sequence AND lotdd.WorkPoint=neg.WorkPoint and negg.Type='3'),'') AS WHCode";
                                    columnsWHNAME = @"ISNULL((SELECT WarehouseName from ICSWareHouse where WarehouseCode in (SELECT negg.WHCODE FROM ICSMOApplyNegDetail neg LEFT JOIN ICSMOApplyNeg negg ON neg.ApplyNegCode=negg.ApplyNegCode 
                                                        WHERE  lotdd.TransCode=neg.ApplyNegCode AND lotdd.TransSequence=neg.Sequence AND lotdd.WorkPoint=neg.WorkPoint and negg.Type='3') AND WorkPoint=a.WorkPoint),'') AS WHName";
                                }
                                else if (LotType.Equals("14"))
                                {//委外领料申请退料
                                    columnsWHCODE = @"ISNULL((SELECT negg.WHCODE FROM ICSOApplyNegDetail neg LEFT JOIN ICSOApplyNeg negg ON neg.OApplyNegCode=negg.OApplyNegCode 
                                                        WHERE  lotdd.TransCode=neg.OApplyNegCode AND lotdd.TransSequence=neg.Sequence AND lotdd.WorkPoint=neg.WorkPoint and negg.Type='2'),'') AS WHCode";
                                    columnsWHNAME = @"ISNULL((SELECT WarehouseName from ICSWareHouse where WarehouseCode in (SELECT negg.WHCODE FROM ICSOApplyNegDetail neg LEFT JOIN ICSOApplyNeg negg ON neg.OApplyNegCode=negg.OApplyNegCode 
                                                        WHERE  lotdd.TransCode=neg.OApplyNegCode AND lotdd.TransSequence=neg.Sequence AND lotdd.WorkPoint=neg.WorkPoint and negg.Type='2') AND WorkPoint=a.WorkPoint),'') AS WHName";
                                }
                                else if (LotType.Equals("15"))
                                {//委外材料出库退料
                                    columnsWHCODE = @"ISNULL((SELECT negg.WHCODE FROM ICSOApplyNegDetail neg LEFT JOIN ICSOApplyNeg negg ON neg.OApplyNegCode=negg.OApplyNegCode 
                                                        WHERE  lotdd.TransCode=neg.OApplyNegCode AND lotdd.TransSequence=neg.Sequence AND lotdd.WorkPoint=neg.WorkPoint and negg.Type='3'),'') AS WHCode";
                                    columnsWHNAME = @"ISNULL((SELECT WarehouseName from ICSWareHouse where WarehouseCode in (SELECT negg.WHCODE FROM ICSOApplyNegDetail neg LEFT JOIN ICSOApplyNeg negg ON neg.OApplyNegCode=negg.OApplyNegCode 
                                                        WHERE  lotdd.TransCode=neg.OApplyNegCode AND lotdd.TransSequence=neg.Sequence AND lotdd.WorkPoint=neg.WorkPoint and negg.Type='3') AND WorkPoint=a.WorkPoint),'') AS WHName";
                                }
                                else if (LotType.Equals("16"))
                                {//返工工单
                                    columnsWHCODE = @"ISNULL((SELECT pick.WHCode FROM ICSMOPick pick LEFT JOIN ICSMO moo ON pick.MODetailID=moo.MODetailID AND pick.WorkPoint=moo.WorkPoint  
                                                        WHERE moo.MOCode=lotdd.TransCode AND pick.Sequence=lotdd.TransSequence AND pick.WorkPoint=lotdd.WorkPoint),'') AS WHCode  ";
                                    columnsWHNAME = @"ISNULL((SELECT WarehouseName from ICSWareHouse where WarehouseCode in (SELECT pick.WHCode FROM ICSMOPick pick LEFT JOIN ICSMO moo ON pick.MODetailID=moo.MODetailID AND pick.WorkPoint=moo.WorkPoint  
                                                        WHERE moo.MOCode=lotdd.TransCode AND pick.Sequence=lotdd.TransSequence AND pick.WorkPoint=lotdd.WorkPoint) AND WorkPoint=a.WorkPoint),'') AS WHName  ";
                                }
                                else
                                {
                                    columnsWHCODE = @"'' AS WHCode";
                                    columnsWHNAME = @"'' AS WHName";
                                }
                                #endregion

                                if ((TransType == TransTypeEnum.PurchaseReceiveDoc.GetDescription() || TransType == TransTypeEnum.DeliveryNotice.GetDescription()
                                    || TransType == TransTypeEnum.OutsourcingReceiveDoc.GetDescription() || TransType == TransTypeEnum.ODeliveryNotice.GetDescription()
                                    || TransType == TransTypeEnum.ManufactureReceiveDoc.GetDescription() || TransType == TransTypeEnum.MOStockINByProductNoTrans.GetDescription()
                                    || TransType == TransTypeEnum.ManufactureReceive.GetDescription() || TransType == TransTypeEnum.OOStockINByProduct.GetDescription()
                                    || TransType == TransTypeEnum.MOStockINByProduct.GetDescription() || TransType == TransTypeEnum.OtherInDoc.GetDescription()) && needIns)
                                {
                                    columns = @"ISNULL(ins.QualifiedQuantity+ins.WaiveQuantity, a.Quantity) AS Quantity,
                                                a.Quantity*(a.Amount/a.Quantity) AS Amount,a.Type,
                                                {0},{2},
                                                lotdd.TransCode,lotdd.TransSequence,
                                                a.Type,
                                                {3}
                                                {1}
                                                ext.BatchCode AS BatchCode,";
                                    
                                    tableName = @"ICSInventoryLot a
                                            INNER JOIN ICSExtension ext ON a.ExtensionID=ext.ID AND a.WorkPoint=ext.WorkPoint
                                            LEFT JOIN ICSInventoryLotDetail lotdd ON lotdd.LotNo=a.LotNo AND a.WorkPoint=lotdd.WorkPoint
                                            LEFT JOIN ICSInspection ins ON a.LotNo=ins.LotNo AND a.WorkPoint=ins.WorkPoint";
                                }
                                else
                                {
                                    columns = @"a.Quantity AS Quantity,
                                                a.Quantity*(a.Amount/a.Quantity) AS Amount,a.Type,
                                                {0},{2},
                                                a.Type,
                                                {3}
                                                {1}
                                                ext.BatchCode AS BatchCode,";
                                    
                                    tableName = @"ICSInventoryLot a
                                            INNER JOIN ICSExtension ext ON a.ExtensionID=ext.ID AND a.WorkPoint=ext.WorkPoint
                                            LEFT JOIN ICSInventoryLotDetail lotdd ON lotdd.LotNo=a.LotNo AND a.WorkPoint=lotdd.WorkPoint";
                                }

                               

                                columns = string.Format(columns, columnsWHCODE,  columnsLONAME, columnsWHNAME, columnsLOCODE);


                            }
                            else
                            {
                                sql = @"
                                    WITH ICSBomALL AS
                                    (
	                                    SELECT
		                                    ContainerCode AS TContainerCode,
		                                    ContainerCode AS PContainerCode,
		                                    ContainerCode AS ContainerCode,
		                                    ID,
		                                    ContainerID,
		                                    0 AS [Level],
		                                    CAST(1 AS nvarchar(MAX)) AS SortSeq,
		                                    CAST('00001' AS nvarchar(MAX)) AS Sort
	                                    FROM ICSContainer
	                                    WHERE ContainerCode='{2}'
                                    UNION ALL
	                                    SELECT
		                                    b.TContainerCode,
		                                    b.ContainerCode AS PContainerCode,
		                                    a.ContainerCode,
		                                    a.ID,
		                                    a.ContainerID,
		                                    b.[Level]+1 AS [Level],
		                                    CAST(b.SortSeq AS nvarchar(MAX))+'.'+CAST(row_number() over (order by a.ContainerCode) AS nvarchar(MAX)) AS SortSeq,
		                                    CAST(b.Sort+'.'+REPLICATE('0',5-len(row_number() over (order by a.ContainerCode)))+CAST(row_number() over (order by a.ContainerCode) AS nvarchar(MAX)) AS nvarchar(MAX)) AS Sort
	                                    FROM
		                                    ICSContainer a
	                                    INNER JOIN ICSBomALL b ON a.ID=b.ContainerID
                                    )
                                    " + sql;

                                if ((TransType == TransTypeEnum.PurchaseReceiveDoc.GetDescription() || TransType == TransTypeEnum.DeliveryNotice.GetDescription()
                                    || TransType == TransTypeEnum.OutsourcingReceiveDoc.GetDescription() || TransType == TransTypeEnum.ODeliveryNotice.GetDescription()
                                    || TransType == TransTypeEnum.ManufactureReceiveDoc.GetDescription() || TransType == TransTypeEnum.ManufactureReceive.GetDescription()
                                    || TransType == TransTypeEnum.MOStockINByProduct.GetDescription() || TransType == TransTypeEnum.MOStockINByProductNoTrans.GetDescription()
                                    || TransType == TransTypeEnum.OOStockINByProduct.GetDescription() || TransType == TransTypeEnum.OtherInDoc.GetDescription()) && needIns)
                                {
                                    columns = @"ISNULL(ins.QualifiedQuantity+ins.WaiveQuantity, a.Quantity) AS Quantity,
                                    a.Quantity*(a.Amount/a.Quantity) AS Amount,a.Type,
                                    '' AS WHCode,
                                    '' AS WHName,
                                    '' AS LocationCode,
                                    '' AS LocationName,
                                    ext.BatchCode AS BatchCode,";

                                    tableName = @"ICSInventoryLot a
                                    INNER JOIN ICSExtension ext ON a.ExtensionID=ext.ID AND a.WorkPoint=ext.WorkPoint
                                    LEFT JOIN ICSInspection ins ON a.LotNo=ins.LotNo AND a.WorkPoint=ins.WorkPoint";
                                }
                                else
                                {
                                    columns = @"a.Quantity AS Quantity,
                                    a.Quantity*(a.Amount/a.Quantity) AS Amount,a.Type,
                                    '' AS WHCode,
                                    '' AS WHName,
                                    '' AS LocationCode,
                                    '' AS LocationName,
                                    ext.BatchCode AS BatchCode,";

                                    tableName = @"ICSInventoryLot a
                                    INNER JOIN ICSExtension ext ON a.ExtensionID=ext.ID AND a.WorkPoint=ext.WorkPoint";
                                }
                                    
                            }

                        }
                    }


                    if (TransType != TransTypeEnum.LocationSeatch.GetDescription())
                    {
                        if (string.IsNullOrWhiteSpace(columns) || string.IsNullOrWhiteSpace(tableName))
                            throw new Exception(language.GetNameByCode("WMSAPIInfo003"));
                    }
                    

                    if (TransType == TransTypeEnum.LocationSeatch.GetDescription())
                    {
                        Losql = string.Format(Losql, columns, tableName, JsonData.Code, JsonData.WorkPoint);

                         table = DBHelper.SQlReturnData(Losql, cmd);
                    }
                    else
                    {
                        sql = string.Format(sql, columns, tableName, JsonData.Code, JsonData.WorkPoint,zlqty);
                        log.Info("条码sql:" + sql);
                        table = DBHelper.SQlReturnData(sql, cmd);
                    }
                    
                    if (table == null || table.Rows.Count <= 0)
                        throw new Exception(language.GetNameByCode("WMSAPIInfo008"));//"未查询到条码数据!"

                    #region 出库检验是否符合源头单据
                    
                    string msg = string.Empty;
                    bool isLimit = false;
                    string sqlCheckSign = @"select F_EnabledMark  from Sys_SRM_Items where F_EnCode = 'OutWithLocationCode' and F_EnabledMark = '1'";
                    DataTable flag = DBHelper.SQlReturnData(sqlCheckSign, cmd);
                    if (isOut)   // && TransType != TransTypeEnum.LOTSplit.GetDescription()
                    {//&& TransType != TransTypeEnum.TransferLibrary.GetDescription()
                        string Lot = "";
                        string workP = "";
                        if (TransType == TransTypeEnum.TransferLibrary.GetDescription())
                        {
                            foreach (DataRow drLot in table.Rows)
                            {
                                Lot = drLot["LotNo"].ToString();
                                sql = @"SELECT WarehouseCode FROM ICSWareHouseLotInfo a WHERE LotNo='{0}' AND WorkPoint='{1}'";
                                sql = string.Format(sql, Lot, JsonData.WorkPoint);
                                DataTable dt = DBHelper.SQlReturnData(sql, cmd);
                                if (dt == null || dt.Rows.Count <= 0)
                                {
                                    throw new Exception(string.Format(language.GetNameByCode("WMSAPIInfo171"), Lot));
                                }
                                string whcode = dt.Rows[0]["WarehouseCode"].ToString();
                                if (!JsonData.WHCode.Equals(whcode))
                                {
                                    throw new Exception(string.Format(language.GetNameByCode("WMSAPIInfo395"), JsonData.WHCode, whcode));
                                }
                            }

                        }
                        else if(TransType != TransTypeEnum.LocationSeatch.GetDescription() && TransType != TransTypeEnum.StepNoTransferDocIn.GetDescription())
                        {
                           
                            if (string.IsNullOrEmpty(JsonData.TransCode))
                            {
                                throw new Exception(language.GetNameByCode("WMSAPIInfo001"));//"单据号不能为空!"
                            }
                            WMSSourceDocumentModel model = new WMSSourceDocumentModel();
                            model.TransCode = JsonData.TransCode;
                            model.TransType = JsonData.TransType;
                            model.WorkPoint = JsonData.WorkPoint;
                            DataTable TransData = TransInformationGet(model);
                            DataView dataView = TransData.DefaultView;
                            foreach (DataRow drLot in table.Rows)
                            {
                                Lot = drLot["LotNo"].ToString();
                                //盘点不需要对比以下属性
                                if (TransType == TransTypeEnum.Check.GetDescription())
                                    continue;

                                string rowFilter = "InvCode='" + drLot["InvCode"] + "'";
                                CheckTrans(dataView, rowFilter, string.Format(language.GetNameByCode("WMSAPIInfo041"), Lot, drLot["InvCode"]));
                                rowFilter += " AND (LEN(ISNULL(WHCode,''))<=0 OR (LEN(ISNULL(WHCode,''))>0 AND WHCode='" + drLot["WHCode"] + "'))";
                                CheckTrans(dataView, rowFilter, string.Format(language.GetNameByCode("WMSAPIInfo042"), Lot, drLot["WHCode"]));
                                
                                rowFilter += " AND (LEN(ISNULL(ProjectCode,''))<=0 OR (LEN(ISNULL(ProjectCode,''))>0 AND ProjectCode='" + drLot["ProjectCode"] + "'))";
                               
                                CheckTrans(dataView, rowFilter, string.Format(language.GetNameByCode("WMSAPIInfo500"), Lot, drLot["ProjectCode"], GetExtentionName("ProjectCode", JsonData.WorkPoint, cmd, language)));
                                
                                rowFilter += "AND (LEN(ISNULL(BatchCode,''))<=0 OR (LEN(ISNULL(BatchCode,''))>0 AND BatchCode='" + drLot["BatchCode"] + "'))";
                                CheckTrans(dataView, rowFilter, string.Format(language.GetNameByCode("WMSAPIInfo500"), Lot, drLot["BatchCode"], GetExtentionName("BatchCode", JsonData.WorkPoint, cmd, language)));
                                rowFilter += "AND (LEN(ISNULL(Version,''))<=0 OR (LEN(ISNULL(Version,''))>0 AND Version='" + drLot["Version"] + "'))";
                                CheckTrans(dataView, rowFilter, string.Format(language.GetNameByCode("WMSAPIInfo500"), Lot, drLot["Version"], GetExtentionName("Version", JsonData.WorkPoint, cmd, language)));
                                rowFilter += "AND (LEN(ISNULL(Brand,''))<=0 OR (LEN(ISNULL(Brand,''))>0 AND Brand='" + drLot["Brand"] + "'))";
                                CheckTrans(dataView, rowFilter, string.Format(language.GetNameByCode("WMSAPIInfo500"), Lot, drLot["Brand"], GetExtentionName("Brand", JsonData.WorkPoint, cmd, language)));
                                rowFilter += "AND (LEN(ISNULL(cFree1,''))<=0 OR (LEN(ISNULL(cFree1,''))>0 AND cFree1='" + drLot["cFree1"] + "'))";
                                CheckTrans(dataView, rowFilter, string.Format(language.GetNameByCode("WMSAPIInfo500"), Lot, drLot["cFree1"], GetExtentionName("cFree1", JsonData.WorkPoint, cmd, language)));
                                rowFilter += "AND (LEN(ISNULL(cFree2,''))<=0 OR (LEN(ISNULL(cFree2,''))>0 AND cFree2='" + drLot["cFree2"] + "'))";
                                CheckTrans(dataView, rowFilter, string.Format(language.GetNameByCode("WMSAPIInfo500"), Lot, drLot["cFree2"], GetExtentionName("cFree2", JsonData.WorkPoint, cmd, language)));
                                rowFilter += "AND (LEN(ISNULL(cFree3,''))<=0 OR (LEN(ISNULL(cFree3,''))>0 AND cFree3='" + drLot["cFree3"] + "'))";
                                CheckTrans(dataView, rowFilter, string.Format(language.GetNameByCode("WMSAPIInfo500"), Lot, drLot["cFree3"], GetExtentionName("cFree3", JsonData.WorkPoint, cmd, language)));
                                rowFilter += "AND (LEN(ISNULL(cFree4,''))<=0 OR (LEN(ISNULL(cFree4,''))>0 AND cFree4='" + drLot["cFree4"] + "'))";
                                CheckTrans(dataView, rowFilter, string.Format(language.GetNameByCode("WMSAPIInfo500"), Lot, drLot["cFree4"], GetExtentionName("cFree4", JsonData.WorkPoint, cmd, language)));
                                rowFilter += "AND (LEN(ISNULL(cFree5,''))<=0 OR (LEN(ISNULL(cFree5,''))>0 AND cFree5='" + drLot["cFree5"] + "'))";
                                CheckTrans(dataView, rowFilter, string.Format(language.GetNameByCode("WMSAPIInfo500"), Lot, drLot["cFree5"], GetExtentionName("cFree5", JsonData.WorkPoint, cmd, language)));
                                rowFilter += "AND (LEN(ISNULL(cFree6,''))<=0 OR (LEN(ISNULL(cFree6,''))>0 AND cFree6='" + drLot["cFree6"] + "'))";
                                CheckTrans(dataView, rowFilter, string.Format(language.GetNameByCode("WMSAPIInfo500"), Lot, drLot["cFree6"], GetExtentionName("cFree6", JsonData.WorkPoint, cmd, language)));
                                rowFilter += "AND (LEN(ISNULL(cFree7,''))<=0 OR (LEN(ISNULL(cFree7,''))>0 AND cFree7='" + drLot["cFree7"] + "'))";
                                CheckTrans(dataView, rowFilter, string.Format(language.GetNameByCode("WMSAPIInfo500"), Lot, drLot["cFree7"], GetExtentionName("cFree7", JsonData.WorkPoint, cmd, language)));
                                rowFilter += "AND (LEN(ISNULL(cFree8,''))<=0 OR (LEN(ISNULL(cFree8,''))>0 AND cFree8='" + drLot["cFree8"] + "'))";
                                CheckTrans(dataView, rowFilter, string.Format(language.GetNameByCode("WMSAPIInfo500"), Lot, drLot["cFree8"], GetExtentionName("cFree8", JsonData.WorkPoint, cmd, language)));
                                rowFilter += "AND (LEN(ISNULL(cFree9,''))<=0 OR (LEN(ISNULL(cFree9,''))>0 AND cFree9='" + drLot["cFree9"] + "'))";
                                CheckTrans(dataView, rowFilter, string.Format(language.GetNameByCode("WMSAPIInfo500"), Lot, drLot["cFree9"], GetExtentionName("cFree9", JsonData.WorkPoint, cmd, language)));
                                rowFilter += "AND (LEN(ISNULL(cFree10,''))<=0 OR (LEN(ISNULL(cFree10,''))>0 AND cFree10='" + drLot["cFree10"] + "'))";
                                CheckTrans(dataView, rowFilter, string.Format(language.GetNameByCode("WMSAPIInfo500"), Lot, drLot["cFree10"], GetExtentionName("cFree10", JsonData.WorkPoint, cmd, language)));
                                if (flag != null && flag.Rows.Count > 0)
                                {
                                    rowFilter += " AND LocationCode='" + drLot["LocationCode"] + "'";
                                    CheckTrans(dataView, rowFilter, string.Format(language.GetNameByCode("WMSAPIInfo042"), Lot, drLot["LocationCode"]));
                                }
                                
                                //保质期管理
                                var resultEffective = Effective(Lot, JsonData.WorkPoint, cmd, language);
                                //0 - 已经是最早的批次
                                //1 - 不管控
                                //2 - 提醒
                                //3 - 限制
                                if (resultEffective == "2")
                                {
                                    msg += string.Format(language.GetNameByCode("WMSAPIInfo181"), Lot) + Environment.NewLine;
                                }
                                else if (resultEffective == "3")
                                {
                                    msg += string.Format(language.GetNameByCode("WMSAPIInfo182"), Lot) + Environment.NewLine;
                                    isLimit = true;
                                }

                                string rowFilternew = rowFilter+" AND LEN(ISNULL(ProjectCode,''))>0";
                                string sqlnew = CheckTransnew(dataView, rowFilternew, "ProjectCode");
                                rowFilternew = rowFilter + " AND  LEN(ISNULL(BatchCode,''))>0";
                                sqlnew += CheckTransnew(dataView, rowFilternew, "BatchCode");
                                rowFilternew = rowFilter + " AND LEN(ISNULL(Version,''))>0";
                                sqlnew += CheckTransnew(dataView, rowFilternew, "Version");
                                rowFilternew = rowFilter + " AND LEN(ISNULL(Brand,''))>0";
                                sqlnew += CheckTransnew(dataView, rowFilternew, "Brand");
                                rowFilternew = rowFilter + " AND LEN(ISNULL(cFree1,''))>0";
                                sqlnew += CheckTransnew(dataView, rowFilternew, "cFree1");
                                rowFilternew = rowFilter + " AND LEN(ISNULL(cFree2,''))>0";
                                sqlnew += CheckTransnew(dataView, rowFilternew, "cFree2");
                                rowFilternew = rowFilter + " AND LEN(ISNULL(cFree3,''))>0";
                                sqlnew += CheckTransnew(dataView, rowFilternew, "cFree3");
                                rowFilternew = rowFilter + " AND LEN(ISNULL(cFree4,''))>0";
                                sqlnew += CheckTransnew(dataView, rowFilternew, "cFree4");
                                rowFilternew = rowFilter + " AND LEN(ISNULL(cFree5,''))>0";
                                sqlnew += CheckTransnew(dataView, rowFilternew, "cFree5");
                                rowFilternew = rowFilter + " AND LEN(ISNULL(cFree6,''))>0";
                                sqlnew += CheckTransnew(dataView, rowFilternew, "cFree6");
                                rowFilternew = rowFilter + " AND LEN(ISNULL(cFree7,''))>0";
                                sqlnew += CheckTransnew(dataView, rowFilternew, "cFree7");
                                rowFilternew = rowFilter + " AND LEN(ISNULL(cFree8,''))>0 ";
                                sqlnew += CheckTransnew(dataView, rowFilternew, "cFree8");
                                rowFilternew = rowFilter + " AND LEN(ISNULL(cFree9,''))>0";
                                sqlnew += CheckTransnew(dataView, rowFilternew, "cFree9");
                                rowFilternew = rowFilter + " AND LEN(ISNULL(cFree10,''))>0";
                                sqlnew += CheckTransnew(dataView, rowFilternew, "cFree10");



                                if(TransType != TransTypeEnum.OtherOutDoc.GetDescription())
                                {
                                    //先进先出判断
                                    var result = CanOut(Lot, JsonData.WorkPoint, JsonData.ScanLotCode, sqlnew, cmd, language);
                                    //0 - 已经是最早的批次
                                    //1 - 不管控
                                    //2 - 提醒
                                    //3 - 限制
                                    if (result == "2")
                                    {
                                        msg += string.Format(language.GetNameByCode("WMSAPIInfo178"), Lot) + Environment.NewLine;
                                    }
                                    else if (result == "3")
                                    {
                                        msg += string.Format(language.GetNameByCode("WMSAPIInfo179"), Lot) + Environment.NewLine;
                                        isLimit = true;
                                    }
                                }
                                
                            }
                        }

                    }
                    #endregion
                    //return table;
                    Result res = new Result();
                    res.Success = true;
                    res.Message = msg;// "接口调用成功!";
                    if (!isLimit)
                        res.Data = table;
                    return res;
                    //出库时
                    //Message无值、Data有值,可直接处理
                    //Message有值、Data有值,弹出提醒框(可点击确定、取消,确定后继续出库,取消后不处理这批条码),显示Message信息
                    //Message有值、Data无值,弹出警告框(只能点击确定,且不处理这批条码),显示Message信息
                }
                catch (Exception ex)
                {
                    log.Error(ex.Message);
                    throw new Exception(ex.Message);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                    }
                    conn.Dispose();
                }
            }
        }
        /// <summary>
        /// 校验条码对应的物料、自由项等信息是否与源头单据匹配
        /// </summary>
        private static DataView CheckTrans(DataView dataView, string rowFilter, string message)
        {
            dataView.RowFilter = rowFilter;
            if (dataView == null || dataView.Count <= 0)
                throw new Exception(message);
            return dataView;
        }
        #endregion

        private static string CheckTransnew(DataView dataView, string rowFilter, string aaa)
        {
            
            dataView.RowFilter = rowFilter;
            if (dataView == null || dataView.Count <= 0)
                return "";
            return " AND bext."+ aaa + "=yext."+ aaa ;
        }

        /// <summary>
        /// 上架
        /// </summary>BusinessCode,TransType 两个类型
        /// <param name="JsonData"></param>
        /// <returns></returns>
        public static DataTable LOTStockCreate(List<LOTStockUpCreateIModel> JsonData)
        {
            var language = LanguageHelper.GetName("WMSAPIInfo");
            if (JsonData.Count <= 0)
            {
                throw new Exception(language.GetNameByCode("WMSAPIInfo007"));//"传送数据为空!"
            }

            using (SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString))
            {
                conn.Open();
                SqlTransaction sqlTran = conn.BeginTransaction();
                SqlCommand cmd = new SqlCommand();
                cmd.Transaction = sqlTran;
                cmd.Connection = conn;
                cmd.CommandTimeout= Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["TimeOut"]);
                string BusinessCode = string.Empty;
                try
                {
                    DataTable dtable = new DataTable();
                    string result = string.Empty;
                    string TransType = string.Empty;
                    string TransTypeOriginal = string.Empty;//记录不合格入库条码的原条码的类型
                    string Identification = Guid.NewGuid().ToString();
                    foreach (var item in JsonData)
                    {
                        TransType = item.TransType;
                        if (!EnumHelper.HasDescriptions(typeof(TransTypeEnum), TransType))
                        {
                            throw new Exception(LanguageHelper.GetNameSingle("WMSAPIInfo003"));//"单据类型不存在!"
                        }
                        string WHTransType = "2";
                        

                        foreach (var itemInfo in item.detail)
                        {
                            #region 两步调入
                            if (TransType == TransTypeEnum.TwoStepTransferDocIn.GetDescription())
                            {
                                //更新源头单据数量
                                ICSWareHouseService.TwoStepTransferDocIn(itemInfo.TransCode, itemInfo.TransSequence, itemInfo.LotNo, itemInfo.Quantity, item.WorkPoint, cmd, language);

                                //入库
                                ICSWareHouseLotInfoService.WareHouseLotInfoTwoStepTransferDocIn(Identification, itemInfo.TransCode, itemInfo.TransSequence,
                                    itemInfo.WarehouseCode, itemInfo.LocationCode, itemInfo.LotNo, itemInfo.Quantity, item.User, item.WorkPoint, "6", TransTypeEnum.TwoStepTransferDocIn.GetDescription<DBValue>(), cmd, language);
                            }
                            #endregion
                            #region 销售退货-原条码
                            else if (TransType == TransTypeEnum.SalesReturnBack.GetDescription())
                            {
                                //更新源头单据数量
                                ICSSalesService.SalesReturnBackIn(itemInfo.TransCode, itemInfo.TransSequence, itemInfo.LotNo, itemInfo.Quantity, item.WorkPoint, cmd, language);

                                //入库
                                BusinessCode = TransTypeEnum.SalesReturnBack.GetDescription<DBValue>();
                                //入库
                                ICSWareHouseLotInfoService.WareHouseLotInfoUp(Identification, itemInfo.LocationCode, itemInfo.LotNo, itemInfo.Quantity,
                                    item.User, item.WorkPoint, WHTransType, BusinessCode, cmd, language, itemInfo.LogID, itemInfo.InvCode + itemInfo.WarehouseCode,"","");

                                //更新日志表源头单据信息
                                string sql = @"UPDATE ICSWareHouseLotInfoLog SET TransCode='{3}',TransSequence='{4}'
                                               WHERE LotNo='{0}' AND WorkPoint='{1}' AND Identification='{2}' AND TransCode='' AND TransSequence=''";
                                sql = string.Format(sql, itemInfo.LotNo, item.WorkPoint, Identification, itemInfo.TransCode, itemInfo.TransSequence);
                                if (!DBHelper.ExecuteNonQuery(sql, cmd))
                                {
                                    throw new Exception(language.GetNameByCode("WMSAPIInfo143"));//"销售退货单更新失败!");
                                }
                            }
                            #endregion
                            else
                            {
                                #region 采购入库
                                if (TransType == TransTypeEnum.PurchaseReceiveDoc.GetDescription())
                                {
                                    //更新源头单据数量
                                    ICSPurchaseService.PurchaseReceiveDoc(itemInfo.LotNo, itemInfo.Quantity, item.WorkPoint, cmd, language);
                                    BusinessCode = TransTypeEnum.PurchaseReceiveDoc.GetDescription<DBValue>();
                                }
                                #endregion
                                #region 审核的到货单
                                else if (TransType == TransTypeEnum.DeliveryNotice.GetDescription())
                                {
                                    //更新源头单据数量
                                    ICSPurchaseService.DeliveryNoticeIn(itemInfo.LotNo, itemInfo.Quantity, item.WorkPoint, cmd, language);
                                    BusinessCode = TransTypeEnum.DeliveryNotice.GetDescription<DBValue>();
                                }
                                #endregion
                                #region 采购拒收
                                else if (TransType == TransTypeEnum.PurchaseRejectDoc.GetDescription())
                                {
                                    //更新源头单据数量
                                    ICSPurchaseService.PurchaseRejectDocIn(itemInfo.LotNo, itemInfo.Quantity, item.WorkPoint, cmd, language);
                                    BusinessCode = TransTypeEnum.PurchaseRejectDoc.GetDescription<DBValue>();
                                }
                                #endregion
                                #region 审核的委外到货单
                                else if (TransType == TransTypeEnum.ODeliveryNotice.GetDescription())
                                {
                                    //更新源头单据数量
                                    ICSOutsourcingService.ODeliveryNoticeIn(itemInfo.LotNo, itemInfo.Quantity, item.WorkPoint, cmd, language);
                                    BusinessCode = TransTypeEnum.ODeliveryNotice.GetDescription<DBValue>();
                                }
                                #endregion
                                #region 委外拒收
                                else if (TransType == TransTypeEnum.OutsourcingRejectDoc.GetDescription())
                                {
                                    //更新源头单据数量
                                    ICSOutsourcingService.OutsourcingRejectDocIn(itemInfo.LotNo, itemInfo.Quantity, item.WorkPoint, cmd, language);
                                    BusinessCode = TransTypeEnum.OutsourcingRejectDoc.GetDescription<DBValue>();
                                }
                                #endregion
                                #region 委外退料
                                else if (TransType == TransTypeEnum.ICSOutsourcingIssueDoNegative.GetDescription()
                                        || TransType == TransTypeEnum.ICSOutsourcingIssueDoNegativeApply.GetDescription()
                                        || TransType == TransTypeEnum.ICSOutsourcingIssueDoNegativeIssue.GetDescription())
                                {
                                    //更新源头单据数量
                                    ICSOutsourcingService.OutsourcingIssueDoNegative(TransType, itemInfo.LogID, itemInfo.LotNo, itemInfo.Quantity, item.WorkPoint, itemInfo.TransCode, itemInfo.TransSequence, cmd, language);
                                    BusinessCode = TransTypeEnum.ICSOutsourcingIssueDoNegative.GetDescription<DBValue>();
                                }
                                #endregion
                                #region 返工工单
                                else if (TransType == TransTypeEnum.ReWorkReceiveMo.GetDescription())
                                {
                                    //更新源头单据数量
                                    ICSManufactureService.ReWorkReceiveMo(itemInfo.LotNo, itemInfo.Quantity, itemInfo.WarehouseCode, itemInfo.LocationCode, item.WorkPoint, item.User, TransTypeEnum.ReWorkReceiveMo.GetDescription<DBValue>(), cmd, language);
                                    BusinessCode = TransTypeEnum.ReWorkReceiveMo.GetDescription<DBValue>();
                                }
                                #endregion
                                #region 委外入库
                                else if (TransType == TransTypeEnum.OutsourcingReceiveDoc.GetDescription())
                                {
                                    //更新源头单据数量
                                    ICSOutsourcingService.OutsourcingReceiveDoc(itemInfo.LotNo, itemInfo.Quantity, item.WorkPoint, cmd, language);
                                    BusinessCode = TransTypeEnum.OutsourcingReceiveDoc.GetDescription<DBValue>();
                                }
                                #endregion
                                #region 生产退料
                                else if (TransType == TransTypeEnum.MOIssueDocNegative.GetDescription()
                                        || TransType == TransTypeEnum.MOIssueDocNegativeApply.GetDescription()
                                        || TransType == TransTypeEnum.MOIssueDocNegativeIssue.GetDescription())
                                {
                                    log.Debug("生产退料1" + TransTypeEnum.MOIssueDocNegative.GetDescription());
                                    log.Debug("生产退料2" + TransTypeEnum.MOIssueDocNegativeApply.GetDescription());
                                    log.Debug("生产退料3" + TransTypeEnum.MOIssueDocNegativeIssue.GetDescription());
                                    log.Debug("生产退料4"+TransType);
                                    //更新源头单据数量
                                    ICSManufactureService.MOIssueDocNegative(TransType, itemInfo.LogID, itemInfo.LotNo, itemInfo.Quantity, item.WorkPoint, cmd, language);
                                    BusinessCode = TransTypeEnum.MOIssueDocNegative.GetDescription<DBValue>();
                                    log.Debug("生产退料5");
                                }
                                #endregion
                                #region 生产入库
                                else if (TransType == TransTypeEnum.ManufactureReceiveDoc.GetDescription())
                                {
                                    log.Debug("生产入库" + TransType);
                                    //更新源头单据数量
                                    ICSManufactureService.ManufactureReceiveDoc(itemInfo.LotNo, itemInfo.Quantity, item.WorkPoint, cmd, language);
                                    BusinessCode = TransTypeEnum.ManufactureReceiveDoc.GetDescription<DBValue>();
                                }
                                #endregion
                                #region 开立的生产入库单
                                else if (TransType == TransTypeEnum.ManufactureReceive.GetDescription())
                                {
                                    //更新源头单据数量
                                    ICSManufactureService.ManufactureReceive(itemInfo.LotNo, itemInfo.Quantity, item.WorkPoint, cmd, language);
                                    BusinessCode = TransTypeEnum.ManufactureReceive.GetDescription<DBValue>();
                                }
                                #endregion
                                #region 销售退货
                                else if (TransType == TransTypeEnum.SalesShipmentDocNegative.GetDescription())
                                {
                                    //更新源头单据数量
                                    ICSSalesService.SalesShipmentDocNegative(itemInfo.LotNo, itemInfo.Quantity, item.WorkPoint, cmd, language);
                                    BusinessCode = TransTypeEnum.SalesShipmentDocNegative.GetDescription<DBValue>();
                                }
                                #endregion
                                #region 其他入库
                                else if (TransType == TransTypeEnum.OtherInDoc.GetDescription())
                                {
                                    //更新源头单据数量
                                    ICSWareHouseService.OtherInDoc(itemInfo.LotNo, itemInfo.Quantity, item.WorkPoint, cmd, language);
                                    BusinessCode = TransTypeEnum.OtherInDoc.GetDescription<DBValue>();
                                }
                                #endregion
                                #region 拆卸单
                                else if (TransType == TransTypeEnum.DisassemblyDoc.GetDescription())
                                {
                                    ICSWareHouseService.DisassemblyDoc(itemInfo.LotNo, itemInfo.Quantity, item.WorkPoint, cmd, language);
                                    WHTransType = "11";
                                    BusinessCode = TransTypeEnum.DisassemblyDoc.GetDescription<DBValue>();
                                }
                                #endregion
                                #region 归还
                                else if (TransType == TransTypeEnum.ReturnDoc.GetDescription())
                                {
                                    //更新源头单据数量
                                    ICSWareHouseService.ReturnDoc(itemInfo.LotNo, itemInfo.Quantity, item.WorkPoint, cmd, language);
                                    BusinessCode = TransTypeEnum.ReturnDoc.GetDescription<DBValue>();
                                }
                                #endregion
                                #region 不合格入库
                                else if (TransType == TransTypeEnum.UnqualifiedIN.GetDescription())
                                {
                                    string sql = @"SELECT b.Type FROM ICSInventoryLot a
                                                    LEFT JOIN ICSInventoryLot b ON a.EATTRIBUTE1=b.LotNo AND b.WorkPoint=a.WorkPoint
                                                    WHERE a.LotNo='{0}' AND a.Type='17' AND a.WorkPoint='{1}'";
                                    sql = string.Format(sql, itemInfo.LotNo, item.WorkPoint);
                                    DataTable dt = DBHelper.SQlReturnData(sql, cmd);
                                    if (dt.Rows.Count != 0)
                                    {
                                        TransTypeOriginal = dt.Rows[0]["Type"].ToString();
                                    }

                                    if (TransTypeOriginal == string.Empty)
                                    {
                                        //throw new Exception(language.GetNameByCode(""));
                                        throw new Exception("未查询到条码" + itemInfo.LotNo + "的原条码");
                                    }
                                    #region 审核的到货单
                                    else if (TransTypeOriginal == "7")
                                    {
                                        //更新源头单据数量
                                        ICSPurchaseService.DeliveryNoticeIn(itemInfo.LotNo, itemInfo.Quantity, item.WorkPoint, cmd, language);
                                        //BusinessCode = TransTypeEnum.DeliveryNotice.GetDescription<DBValue>();
                                        TransTypeOriginal = TransTypeEnum.DeliveryNotice.GetDescription();
                                    }
                                    #endregion
                                    #region 审核的委外到货单
                                    else if (TransTypeOriginal == "8")
                                    {
                                        //更新源头单据数量
                                        ICSOutsourcingService.ODeliveryNoticeIn(itemInfo.LotNo, itemInfo.Quantity, item.WorkPoint, cmd, language);
                                        //BusinessCode = TransTypeEnum.ODeliveryNotice.GetDescription<DBValue>();
                                        TransTypeOriginal = TransTypeEnum.ODeliveryNotice.GetDescription();
                                    }
                                    #endregion
                                    #region 委外退料
                                    else if (TransTypeOriginal == "2"
                                            || TransTypeOriginal == "14"
                                            || TransTypeOriginal == "15")
                                    {
                                        //更新源头单据数量
                                        ICSOutsourcingService.OutsourcingIssueDoNegative(TransTypeOriginal, itemInfo.LogID, itemInfo.LotNo, itemInfo.Quantity, item.WorkPoint, itemInfo.TransCode, itemInfo.TransSequence, cmd, language);
                                        //BusinessCode = TransTypeEnum.ICSOutsourcingIssueDoNegative.GetDescription<DBValue>();
                                        TransTypeOriginal = TransTypeEnum.ICSOutsourcingIssueDoNegative.GetDescription();
                                    }
                                    #endregion
                                    #region 生产退料
                                    else if (TransTypeOriginal == "1"
                                            || TransTypeOriginal == "12"
                                            || TransTypeOriginal == "13")
                                    {
                                        log.Debug("生产退料1" + TransTypeEnum.MOIssueDocNegative.GetDescription());
                                        log.Debug("生产退料2" + TransTypeEnum.MOIssueDocNegativeApply.GetDescription());
                                        log.Debug("生产退料3" + TransTypeEnum.MOIssueDocNegativeIssue.GetDescription());
                                        log.Debug("生产退料4" + TransTypeOriginal);
                                        //更新源头单据数量
                                        ICSManufactureService.MOIssueDocNegative(TransTypeOriginal, itemInfo.LogID, itemInfo.LotNo, itemInfo.Quantity, item.WorkPoint, cmd, language);
                                        //BusinessCode = TransTypeEnum.MOIssueDocNegative.GetDescription<DBValue>();
                                        TransTypeOriginal = TransTypeEnum.MOIssueDocNegative.GetDescription();
                                    }
                                    #endregion
                                    #region 生产入库
                                    else if (TransTypeOriginal == "3")
                                    {
                                        log.Debug("生产入库" + TransTypeOriginal);
                                        //更新源头单据数量
                                        ICSManufactureService.ManufactureReceiveDoc(itemInfo.LotNo, itemInfo.Quantity, item.WorkPoint, cmd, language);
                                        //BusinessCode = TransTypeEnum.ManufactureReceiveDoc.GetDescription<DBValue>();
                                        TransTypeOriginal = TransTypeEnum.ManufactureReceiveDoc.GetDescription();
                                    }
                                    #endregion
                                    #region 销售退货
                                    else if (TransTypeOriginal == "4")
                                    {
                                        //更新源头单据数量
                                        ICSSalesService.SalesShipmentDocNegative(itemInfo.LotNo, itemInfo.Quantity, item.WorkPoint, cmd, language);
                                        //BusinessCode = TransTypeEnum.SalesShipmentDocNegative.GetDescription<DBValue>();
                                        TransTypeOriginal = TransTypeEnum.SalesShipmentDocNegative.GetDescription();
                                    }
                                    #endregion
                                    #region 其他入库
                                    else if (TransTypeOriginal == "5")
                                    {
                                        //更新源头单据数量
                                        ICSWareHouseService.OtherInDoc(itemInfo.LotNo, itemInfo.Quantity, item.WorkPoint, cmd, language);
                                        //BusinessCode = TransTypeEnum.OtherInDoc.GetDescription<DBValue>();
                                        TransTypeOriginal = TransTypeEnum.OtherInDoc.GetDescription();
                                    }
                                    #endregion

                                    BusinessCode = TransTypeEnum.UnqualifiedIN.GetDescription<DBValue>();
                                }
                                #endregion
                                #region 副产品入库
                                else if (TransType == TransTypeEnum.MOStockINByProduct.GetDescription())
                                {
                                    log.Debug("副产品入库" + TransType);
                                    //更新源头单据数量
                                    ICSManufactureService.MOStockINByProductDoc(itemInfo.LotNo, itemInfo.Quantity, item.WorkPoint, cmd, language);
                                    BusinessCode = TransTypeEnum.MOStockINByProduct.GetDescription<DBValue>();
                                }
                                #endregion
                                #region 委外副产品入库
                                else if (TransType == TransTypeEnum.OOStockINByProduct.GetDescription())
                                {
                                    log.Debug("副产品入库" + TransType);
                                    //更新源头单据数量
                                    ICSManufactureService.OOStockINByProductDoc(itemInfo.LotNo, itemInfo.Quantity, item.WorkPoint, cmd, language);
                                    BusinessCode = TransTypeEnum.OOStockINByProduct.GetDescription<DBValue>();
                                }
                                #endregion

                                #region 副产品入库(无源头)
                                else if (TransType == TransTypeEnum.MOStockINByProductNoTrans.GetDescription())
                                {
                                    log.Debug("无源头副产品入库" + TransType);
                                    //更新源头单据数量
                                    //ICSManufactureService.MOStockINByProductDoc(itemInfo.LotNo, itemInfo.Quantity, item.WorkPoint, cmd, language);
                                    BusinessCode = TransTypeEnum.MOStockINByProductNoTrans.GetDescription<DBValue>();
                                }
                                #endregion
                                else
                                {
                                    throw new Exception(LanguageHelper.GetNameSingle("WMSAPIInfo003"));//"单据类型不存在!"
                                }
                                //入库
                                ICSWareHouseLotInfoService.WareHouseLotInfoUp(Identification, itemInfo.LocationCode, itemInfo.LotNo, itemInfo.Quantity,
                                    item.User, item.WorkPoint, WHTransType, BusinessCode, cmd, language,itemInfo.LogID,itemInfo.InvCode + itemInfo.WarehouseCode, itemInfo.TransCode, itemInfo.TransSequence);
                            }
                        }

                        #region 拆卸单
                        if (TransType == TransTypeEnum.DisassemblyDoc.GetDescription())
                        {
                            //更新套件锁定数量
                            ICSWareHouseService.DisassemblyDoc(Identification, cmd, language);
                        }
                        #endregion}
                    }
                    //上传ERP
                    if (Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["UploadERP"]))
                    {
                        if (TransTypeOriginal != string.Empty)
                        {
                            TransType = TransTypeOriginal;
                        }
                        //采购入库
                        if (TransType == TransTypeEnum.PurchaseReceiveDoc.GetDescription()) 
                        {
                            if (DBHelper.IsU9()) 
                            { ICSPurchaseService.CreatePOArriveERP(TransType, Identification, cmd, language, BusinessCode,"RCV01"); } 
                            else 
                            { ICSPurchaseService.PurchaseReceiveDocERP(TransType, Identification, cmd, language, BusinessCode); }
                        }

                        //审核的到货单
                        else if (TransType == TransTypeEnum.DeliveryNotice.GetDescription())
                            dtable = ICSPurchaseService.DeliveryNoticeInERP(TransType, Identification, cmd, language, BusinessCode);
                        //采购拒收
                        else if (TransType == TransTypeEnum.PurchaseRejectDoc.GetDescription())
                            ICSPurchaseService.PurchaseRejectDocInERP(TransType, Identification, cmd, language, BusinessCode);
                        //审核的委外到货单
                        else if (TransType == TransTypeEnum.ODeliveryNotice.GetDescription())
                            ICSOutsourcingService.ODeliveryNoticeInERP(TransType, Identification, cmd, language, BusinessCode);
                        //委外拒收
                        else if (TransType == TransTypeEnum.OutsourcingRejectDoc.GetDescription())
                            ICSOutsourcingService.OutsourcingRejectDocInERP(TransType, Identification, cmd, language, BusinessCode);
                        //委外退料
                        else if (TransType == TransTypeEnum.ICSOutsourcingIssueDoNegative.GetDescription()
                                || TransType == TransTypeEnum.ICSOutsourcingIssueDoNegativeApply.GetDescription()
                                || TransType == TransTypeEnum.ICSOutsourcingIssueDoNegativeIssue.GetDescription())
                            ICSOutsourcingService.OutsourcingIssueDoNegativeERP(TransType, Identification, cmd, language, BusinessCode);
                        //委外入库
                        else if (TransType == TransTypeEnum.OutsourcingReceiveDoc.GetDescription())
                        {
                            if (DBHelper.IsU9())
                            { ICSOutsourcingService.CreateOOArriveERP(TransType, Identification, cmd, language, BusinessCode, "RCV11"); }
                            else { ICSOutsourcingService.OutsourcingReceiveDocERP(TransType, Identification, cmd, language, BusinessCode); }
                        }
                            
                        //生产退料
                        else if (TransType == TransTypeEnum.MOIssueDocNegative.GetDescription()
                            || TransType == TransTypeEnum.MOIssueDocNegativeApply.GetDescription()
                            || TransType == TransTypeEnum.MOIssueDocNegativeIssue.GetDescription())
                            ICSManufactureService.MOIssueDocNegativeERP(TransType, Identification, cmd, language, BusinessCode);
                        //生产入库
                        else if (TransType == TransTypeEnum.ManufactureReceiveDoc.GetDescription())

                            ICSManufactureService.ManufactureReceiveDocERP(TransType, Identification, cmd, language,BusinessCode);
                        //副产品入库
                        else if (TransType == TransTypeEnum.MOStockINByProduct.GetDescription())
                            ICSManufactureService.MOStockINByProductDocERP(TransType, Identification, cmd, language,BusinessCode);
                        //委外副产品入库
                        else if (TransType == TransTypeEnum.OOStockINByProduct.GetDescription())
                            ICSManufactureService.OOStockINByProductDocERP(TransType, Identification, cmd, language, BusinessCode);
                        //无源头副产品入库
                        else if (TransType == TransTypeEnum.MOStockINByProductNoTrans.GetDescription())
                            ICSManufactureService.MOStockINByProductNoTransDocERP(TransType, Identification, cmd, language, BusinessCode);
                        //开立的生产入库单
                        else if (TransType == TransTypeEnum.ManufactureReceive.GetDescription())
                            ICSManufactureService.ManufactureReceiveERP(TransType, Identification, cmd, language, BusinessCode);
                        //返工工单
                        else if (TransType == TransTypeEnum.ReWorkReceiveMo.GetDescription())
                            ICSManufactureService.ReWorkReceiveMoERP(TransType, Identification, cmd, language, BusinessCode);
                        //销售退货
                        else if (TransType == TransTypeEnum.SalesShipmentDocNegative.GetDescription())
                            ICSSalesService.SalesShipmentDocNegativeERP(TransType, Identification, cmd, language, BusinessCode);
                        //两步调入
                        else if (TransType == TransTypeEnum.TwoStepTransferDocIn.GetDescription())
                            ICSWareHouseService.TwoStepTransferDocInERP(TransType, Identification, cmd, language, BusinessCode);
                        //销售退货-原条码
                        else if (TransType == TransTypeEnum.SalesReturnBack.GetDescription())
                            ICSSalesService.SalesReturnBackInERP(TransType, Identification, cmd, language, BusinessCode);
                        //其他入库
                        else if (TransType == TransTypeEnum.OtherInDoc.GetDescription())
                        {
                            if (DBHelper.IsU9())
                                ICSWareHouseService.CreateOtherInDocERP(TransType, Identification, cmd, language, BusinessCode);
                            else
                                ICSWareHouseService.OtherInDocERP(TransType, Identification, cmd, language, BusinessCode);
                        }
                        //拆卸单
                        if (TransType == TransTypeEnum.DisassemblyDoc.GetDescription())
                            ICSWareHouseService.DisassemblyDocERP(TransType, Identification, cmd, language, BusinessCode);
                        //归还
                        else if (TransType == TransTypeEnum.ReturnDoc.GetDescription())
                            ICSWareHouseService.ReturnDocERP(TransType, Identification, cmd, language, BusinessCode);
                    }
                    if (TransType == TransTypeEnum.DeliveryNotice.GetDescription())
                    {
                        cmd.Transaction.Commit();
                        return dtable;
                    }
                    else
                    {
                        DataTable table = GetData(Identification, 1, cmd);
                        cmd.Transaction.Commit();
                        return table;
                    }
                }
                catch (Exception ex)
                {
                    if (cmd.Transaction != null)
                        cmd.Transaction.Rollback();
                    log.Error(ex.Message);
                    throw new Exception(ex.Message);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                    }
                    conn.Dispose();
                }
            }
        }

        /// <summary>
        /// 上架(奥美专用)
        /// </summary>BusinessCode,TransType 两个类型
        /// <param name="JsonData"></param>
        /// <returns></returns>
        public static DataTable LOTStockCreateAM(List<LOTStockUpCreateIModel> JsonData)
        {
            var language = LanguageHelper.GetName("WMSAPIInfo");
            if (JsonData.Count <= 0)
            {
                throw new Exception(language.GetNameByCode("WMSAPIInfo007"));//"传送数据为空!"
            }

            using (SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString))
            {
                conn.Open();
                SqlTransaction sqlTran = conn.BeginTransaction();
                SqlCommand cmd = new SqlCommand();
                cmd.Transaction = sqlTran;
                cmd.Connection = conn;
                cmd.CommandTimeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["TimeOut"]);
                string BusinessCode = string.Empty;
                try
                {
                    string TransType = string.Empty;
                    DataTable dtable = new DataTable();
                    string TransTypeOriginal = string.Empty;//记录不合格入库条码的原条码的类型
                    string Identification = Guid.NewGuid().ToString();
                    foreach (var item in JsonData)
                    {
                        TransType = item.TransType;
                        if (!EnumHelper.HasDescriptions(typeof(TransTypeEnum), TransType))
                        {
                            throw new Exception(LanguageHelper.GetNameSingle("WMSAPIInfo003"));//"单据类型不存在!"
                        }
                        string WHTransType = "2";


                        foreach (var itemInfo in item.detail)
                        {
                            #region 两步调入
                            if (TransType == TransTypeEnum.TwoStepTransferDocIn.GetDescription())
                            {
                                //更新源头单据数量
                                ICSWareHouseService.TwoStepTransferDocIn(itemInfo.TransCode, itemInfo.TransSequence, itemInfo.LotNo, itemInfo.Quantity, item.WorkPoint, cmd, language);

                                //入库
                                ICSWareHouseLotInfoService.WareHouseLotInfoTwoStepTransferDocIn(Identification, itemInfo.TransCode, itemInfo.TransSequence,
                                    itemInfo.WarehouseCode, itemInfo.LocationCode, itemInfo.LotNo, itemInfo.Quantity, item.User, item.WorkPoint, "6", TransTypeEnum.TwoStepTransferDocIn.GetDescription<DBValue>(), cmd, language);
                            }
                            #endregion
                            #region 销售退货-原条码
                            else if (TransType == TransTypeEnum.SalesReturnBack.GetDescription())
                            {
                                //更新源头单据数量
                                ICSSalesService.SalesReturnBackIn(itemInfo.TransCode, itemInfo.TransSequence, itemInfo.LotNo, itemInfo.Quantity, item.WorkPoint, cmd, language);

                                //入库
                                BusinessCode = TransTypeEnum.SalesReturnBack.GetDescription<DBValue>();
                                //入库
                                ICSWareHouseLotInfoService.WareHouseLotInfoUp(Identification, itemInfo.LocationCode, itemInfo.LotNo, itemInfo.Quantity,
                                    item.User, item.WorkPoint, WHTransType, BusinessCode, cmd, language, itemInfo.LogID, itemInfo.InvCode + itemInfo.WarehouseCode,"","");

                                //更新日志表源头单据信息
                                string sql = @"UPDATE ICSWareHouseLotInfoLog SET TransCode='{3}',TransSequence='{4}'
                                               WHERE LotNo='{0}' AND WorkPoint='{1}' AND Identification='{2}' AND TransCode='' AND TransSequence=''";
                                sql = string.Format(sql, itemInfo.LotNo, item.WorkPoint, Identification, itemInfo.TransCode, itemInfo.TransSequence);
                                if (!DBHelper.ExecuteNonQuery(sql, cmd))
                                {
                                    throw new Exception(language.GetNameByCode("WMSAPIInfo143"));//"销售退货单更新失败!");
                                }
                            }
                            #endregion
                            else
                            {
                                #region 采购入库
                                if (TransType == TransTypeEnum.PurchaseReceiveDoc.GetDescription())
                                {
                                    //更新源头单据数量
                                    ICSPurchaseService.PurchaseReceiveDoc(itemInfo.LotNo, itemInfo.Quantity, item.WorkPoint, cmd, language);
                                    BusinessCode = TransTypeEnum.PurchaseReceiveDoc.GetDescription<DBValue>();
                                }
                                #endregion
                                #region 审核的到货单
                                else if (TransType == TransTypeEnum.DeliveryNotice.GetDescription())
                                {
                                    //更新源头单据数量
                                    ICSPurchaseService.DeliveryNoticeIn(itemInfo.LotNo, itemInfo.Quantity, item.WorkPoint, cmd, language);
                                    BusinessCode = TransTypeEnum.DeliveryNotice.GetDescription<DBValue>();
                                }
                                #endregion
                                #region 采购拒收
                                else if (TransType == TransTypeEnum.PurchaseRejectDoc.GetDescription())
                                {
                                    //更新源头单据数量
                                    ICSPurchaseService.PurchaseRejectDocIn(itemInfo.LotNo, itemInfo.Quantity, item.WorkPoint, cmd, language);
                                    BusinessCode = TransTypeEnum.PurchaseRejectDoc.GetDescription<DBValue>();
                                }
                                #endregion
                                #region 审核的委外到货单
                                else if (TransType == TransTypeEnum.ODeliveryNotice.GetDescription())
                                {
                                    //更新源头单据数量
                                    ICSOutsourcingService.ODeliveryNoticeIn(itemInfo.LotNo, itemInfo.Quantity, item.WorkPoint, cmd, language);
                                    BusinessCode = TransTypeEnum.ODeliveryNotice.GetDescription<DBValue>();
                                }
                                #endregion
                                #region 委外拒收
                                else if (TransType == TransTypeEnum.OutsourcingRejectDoc.GetDescription())
                                {
                                    //更新源头单据数量
                                    ICSOutsourcingService.OutsourcingRejectDocIn(itemInfo.LotNo, itemInfo.Quantity, item.WorkPoint, cmd, language);
                                    BusinessCode = TransTypeEnum.OutsourcingRejectDoc.GetDescription<DBValue>();
                                }
                                #endregion
                                #region 委外退料
                                else if (TransType == TransTypeEnum.ICSOutsourcingIssueDoNegative.GetDescription()
                                        || TransType == TransTypeEnum.ICSOutsourcingIssueDoNegativeApply.GetDescription()
                                        || TransType == TransTypeEnum.ICSOutsourcingIssueDoNegativeIssue.GetDescription())
                                {
                                    //更新源头单据数量
                                    ICSOutsourcingService.OutsourcingIssueDoNegative(TransType, itemInfo.LogID, itemInfo.LotNo, itemInfo.Quantity, item.WorkPoint, itemInfo.TransCode, itemInfo.TransSequence, cmd, language);
                                    BusinessCode = TransTypeEnum.ICSOutsourcingIssueDoNegative.GetDescription<DBValue>();
                                }
                                #endregion
                                #region 返工工单
                                else if (TransType == TransTypeEnum.ReWorkReceiveMo.GetDescription())
                                {
                                    //更新源头单据数量
                                    ICSManufactureService.ReWorkReceiveMo(itemInfo.LotNo, itemInfo.Quantity, itemInfo.WarehouseCode, itemInfo.LocationCode, item.WorkPoint, item.User, TransTypeEnum.ReWorkReceiveMo.GetDescription<DBValue>(), cmd, language);
                                    BusinessCode = TransTypeEnum.ReWorkReceiveMo.GetDescription<DBValue>();
                                }
                                #endregion
                                #region 委外入库
                                else if (TransType == TransTypeEnum.OutsourcingReceiveDoc.GetDescription())
                                {
                                    //更新源头单据数量
                                    ICSOutsourcingService.OutsourcingReceiveAMDoc(itemInfo.LotNo, itemInfo.Quantity, item.WorkPoint, cmd, language);
                                    BusinessCode = TransTypeEnum.OutsourcingReceiveDoc.GetDescription<DBValue>();
                                }
                                #endregion
                                #region 生产退料
                                else if (TransType == TransTypeEnum.MOIssueDocNegative.GetDescription()
                                        || TransType == TransTypeEnum.MOIssueDocNegativeApply.GetDescription()
                                        || TransType == TransTypeEnum.MOIssueDocNegativeIssue.GetDescription())
                                {
                                    //工单行查子件信息
                                    string chekkksql = @"select a.Sequence,a.InvCode FROM ICSMOPick  a
                                    INNER JOIN ICSMO b ON  a.MODetailID=b.MODetailID AND a.WorkPoint=b.WorkPoint
                                    WHERE b.MOCode='{0}' AND b.Sequence='{2}' AND a.WorkPoint='{1}' ";
                                    chekkksql = string.Format(chekkksql, itemInfo.TransCode, item.WorkPoint, itemInfo.TransSequence);
                                    log.Debug("工单行查子件信息" + chekkksql);
                                    DataTable dtaa = DBHelper.SQlReturnData(chekkksql, cmd);
                                    //查询条码的物料
                                    string cheklotsql = @"select a.InvCode FROM ICSInventoryLot  a
                                    WHERE a.LotNo='{0}'  AND a.WorkPoint='{1}' ";
                                    cheklotsql = string.Format(cheklotsql, itemInfo.LotNo, item.WorkPoint);
                                    log.Debug("查询条码的物料" + cheklotsql);
                                    DataTable lotdata = DBHelper.SQlReturnData(cheklotsql, cmd);

                                    //DataTable ad0=dtaa.Select(a => a.invcode == lotdata.Rows[0]["InvCode"].ToString());
                                    DataRow[] drs = dtaa.Select("InvCode ='" + lotdata.Rows[0]["InvCode"].ToString() + "'");
                                    if (drs == null || drs.Length == 0)
                                    {
                                        throw new Exception("当前扫描的条码物料和单据子件物料没有匹配的行,请确认!");
                                    }
                                    //DataTable ad0 = dtaa.AsEnumerable()
                                    //.Where(a => a.Field<string>("InvCode") == lotdata.Rows[0]["InvCode"].ToString())
                                    //.CopyToDataTable();
                                    //if (ad0 == null || ad0.Rows.Count == 0)
                                    //{
                                    //    throw new Exception("当前扫描的条码物料和单据子件物料没有匹配的行,请确认!");
                                    //}
                                    string seq = itemInfo.TransSequence + "~" + drs[0]["Sequence"].ToString();
                                    log.Debug("工单子件行号:" + seq);
                                    string chekksql = @"select c.EATTRIBUTE1 FROM ICSMOPick  a
                                INNER JOIN ICSMO b ON  a.MODetailID=b.MODetailID AND a.WorkPoint=b.WorkPoint
                                INNER JOIN ICSInventory c on a.InvCode=c.InvCode and a.WorkPoint=c.WorkPoint
                                WHERE b.MOCode='{0}' AND b.Sequence+'~'+a.Sequence='{3}' AND a.WorkPoint='{1}' and c.AmountEnable='1'";
                                    chekksql = string.Format(chekksql, itemInfo.TransCode, item.WorkPoint, itemInfo.Quantity, seq);
                                    DataTable dta = DBHelper.SQlReturnData(chekksql, cmd);
                                    if (dta.Rows.Count > 0)
                                    {
                                        itemInfo.Quantity = (decimal.Parse(itemInfo.Quantity) * decimal.Parse(dta.Rows[0]["EATTRIBUTE1"].ToString())).ToString();
                                    }

                                    //更新源头单据数量
                                    ICSManufactureService.AMMOIssueDocNegative(TransType, itemInfo.LogID, itemInfo.LotNo, itemInfo.Quantity, item.WorkPoint,itemInfo.TransCode, seq, cmd, language);
                                    BusinessCode = TransTypeEnum.MOIssueDocNegative.GetDescription<DBValue>();
                                    log.Debug("生产退料5");
                                }
                                #endregion
                                #region 生产入库
                                else if (TransType == TransTypeEnum.ManufactureReceiveDoc.GetDescription())
                                {
                                    log.Debug("生产入库" + TransType);
                                    //更新源头单据数量
                                    ICSManufactureService.ManufactureReceiveDocAM(itemInfo.LotNo, itemInfo.Quantity, item.WorkPoint, cmd, language);
                                    BusinessCode = TransTypeEnum.ManufactureReceiveDoc.GetDescription<DBValue>();
                                }
                                #endregion
                                #region 开立的生产入库单
                                else if (TransType == TransTypeEnum.ManufactureReceive.GetDescription())
                                {
                                    //更新源头单据数量
                                    ICSManufactureService.ManufactureReceive(itemInfo.LotNo, itemInfo.Quantity, item.WorkPoint, cmd, language);
                                    BusinessCode = TransTypeEnum.ManufactureReceive.GetDescription<DBValue>();
                                }
                                #endregion
                                #region 销售退货
                                else if (TransType == TransTypeEnum.SalesShipmentDocNegative.GetDescription())
                                {
                                    //更新源头单据数量
                                    ICSSalesService.SalesShipmentDocNegative(itemInfo.LotNo, itemInfo.Quantity, item.WorkPoint, cmd, language);
                                    BusinessCode = TransTypeEnum.SalesShipmentDocNegative.GetDescription<DBValue>();
                                }
                                #endregion
                                #region 其他入库
                                else if (TransType == TransTypeEnum.OtherInDoc.GetDescription())
                                {
                                    //更新源头单据数量
                                    ICSWareHouseService.OtherInDoc(itemInfo.LotNo, itemInfo.Quantity, item.WorkPoint, cmd, language);
                                    BusinessCode = TransTypeEnum.OtherInDoc.GetDescription<DBValue>();
                                }
                                #endregion
                                #region 拆卸单
                                else if (TransType == TransTypeEnum.DisassemblyDoc.GetDescription())
                                {
                                    ICSWareHouseService.DisassemblyDoc(itemInfo.LotNo, itemInfo.Quantity, item.WorkPoint, cmd, language);
                                    WHTransType = "11";
                                    BusinessCode = TransTypeEnum.DisassemblyDoc.GetDescription<DBValue>();
                                }
                                #endregion
                                #region 归还
                                else if (TransType == TransTypeEnum.ReturnDoc.GetDescription())
                                {
                                    //更新源头单据数量
                                    ICSWareHouseService.ReturnDoc(itemInfo.LotNo, itemInfo.Quantity, item.WorkPoint, cmd, language);
                                    BusinessCode = TransTypeEnum.ReturnDoc.GetDescription<DBValue>();
                                }
                                #endregion
                                #region 不合格入库
                                else if (TransType == TransTypeEnum.UnqualifiedIN.GetDescription())
                                {
                                    string sql = @"SELECT b.Type FROM ICSInventoryLot a
                                                    LEFT JOIN ICSInventoryLot b ON a.EATTRIBUTE1=b.LotNo AND b.WorkPoint=a.WorkPoint
                                                    WHERE a.LotNo='{0}' AND a.Type='17' AND a.WorkPoint='{1}'";
                                    sql = string.Format(sql, itemInfo.LotNo, item.WorkPoint);
                                    DataTable dt = DBHelper.SQlReturnData(sql, cmd);
                                    if (dt.Rows.Count != 0)
                                    {
                                        TransTypeOriginal = dt.Rows[0]["Type"].ToString();
                                    }

                                    if (TransTypeOriginal == string.Empty)
                                    {
                                        //throw new Exception(language.GetNameByCode(""));
                                        throw new Exception("未查询到条码" + itemInfo.LotNo + "的原条码");
                                    }
                                    #region 审核的到货单
                                    else if (TransTypeOriginal == "7")
                                    {
                                        //更新源头单据数量
                                        ICSPurchaseService.DeliveryNoticeIn(itemInfo.LotNo, itemInfo.Quantity, item.WorkPoint, cmd, language);
                                        //BusinessCode = TransTypeEnum.DeliveryNotice.GetDescription<DBValue>();
                                        TransTypeOriginal = TransTypeEnum.DeliveryNotice.GetDescription();
                                    }
                                    #endregion
                                    #region 审核的委外到货单
                                    else if (TransTypeOriginal == "8")
                                    {
                                        //更新源头单据数量
                                        ICSOutsourcingService.ODeliveryNoticeIn(itemInfo.LotNo, itemInfo.Quantity, item.WorkPoint, cmd, language);
                                        //BusinessCode = TransTypeEnum.ODeliveryNotice.GetDescription<DBValue>();
                                        TransTypeOriginal = TransTypeEnum.ODeliveryNotice.GetDescription();
                                    }
                                    #endregion
                                    #region 委外退料
                                    else if (TransTypeOriginal == "2"
                                            || TransTypeOriginal == "14"
                                            || TransTypeOriginal == "15")
                                    {
                                        //更新源头单据数量
                                        ICSOutsourcingService.OutsourcingIssueDoNegative(TransTypeOriginal, itemInfo.LogID, itemInfo.LotNo, itemInfo.Quantity, item.WorkPoint, itemInfo.TransCode, itemInfo.TransSequence, cmd, language);
                                        //BusinessCode = TransTypeEnum.ICSOutsourcingIssueDoNegative.GetDescription<DBValue>();
                                        TransTypeOriginal = TransTypeEnum.ICSOutsourcingIssueDoNegative.GetDescription();
                                    }
                                    #endregion
                                    #region 生产退料
                                    else if (TransTypeOriginal == "1"
                                            || TransTypeOriginal == "12"
                                            || TransTypeOriginal == "13")
                                    {
                                        log.Debug("生产退料1" + TransTypeEnum.MOIssueDocNegative.GetDescription());
                                        log.Debug("生产退料2" + TransTypeEnum.MOIssueDocNegativeApply.GetDescription());
                                        log.Debug("生产退料3" + TransTypeEnum.MOIssueDocNegativeIssue.GetDescription());
                                        log.Debug("生产退料4" + TransTypeOriginal);
                                        //更新源头单据数量
                                        ICSManufactureService.MOIssueDocNegative(TransTypeOriginal, itemInfo.LogID, itemInfo.LotNo, itemInfo.Quantity, item.WorkPoint, cmd, language);
                                        //BusinessCode = TransTypeEnum.MOIssueDocNegative.GetDescription<DBValue>();
                                        TransTypeOriginal = TransTypeEnum.MOIssueDocNegative.GetDescription();
                                    }
                                    #endregion
                                    #region 生产入库
                                    else if (TransTypeOriginal == "3")
                                    {
                                        log.Debug("生产入库" + TransTypeOriginal);
                                        //更新源头单据数量
                                        ICSManufactureService.ManufactureReceiveDoc(itemInfo.LotNo, itemInfo.Quantity, item.WorkPoint, cmd, language);
                                        //BusinessCode = TransTypeEnum.ManufactureReceiveDoc.GetDescription<DBValue>();
                                        TransTypeOriginal = TransTypeEnum.ManufactureReceiveDoc.GetDescription();
                                    }
                                    #endregion
                                    #region 销售退货
                                    else if (TransTypeOriginal == "4")
                                    {
                                        //更新源头单据数量
                                        ICSSalesService.SalesShipmentDocNegative(itemInfo.LotNo, itemInfo.Quantity, item.WorkPoint, cmd, language);
                                        //BusinessCode = TransTypeEnum.SalesShipmentDocNegative.GetDescription<DBValue>();
                                        TransTypeOriginal = TransTypeEnum.SalesShipmentDocNegative.GetDescription();
                                    }
                                    #endregion
                                    #region 其他入库
                                    else if (TransTypeOriginal == "5")
                                    {
                                        //更新源头单据数量
                                        ICSWareHouseService.OtherInDoc(itemInfo.LotNo, itemInfo.Quantity, item.WorkPoint, cmd, language);
                                        //BusinessCode = TransTypeEnum.OtherInDoc.GetDescription<DBValue>();
                                        TransTypeOriginal = TransTypeEnum.OtherInDoc.GetDescription();
                                    }
                                    #endregion

                                    BusinessCode = TransTypeEnum.UnqualifiedIN.GetDescription<DBValue>();
                                }
                                #endregion
                                #region 联副产品入库
                                else if (TransType == TransTypeEnum.MOStockINByProduct.GetDescription())
                                {
                                    log.Debug("联副产品入库" + TransType);
                                    //更新源头单据数量
                                    ICSManufactureService.MOStockINByProductAMDoc(itemInfo.LotNo, itemInfo.Quantity, item.WorkPoint, cmd, language);
                                    BusinessCode = TransTypeEnum.MOStockINByProduct.GetDescription<DBValue>();
                                }
                                #endregion
                                #region 委外副产品入库
                                else if (TransType == TransTypeEnum.OOStockINByProduct.GetDescription())
                                {
                                    log.Debug("副产品入库" + TransType);
                                    //更新源头单据数量
                                    ICSManufactureService.OOStockINByProductDoc(itemInfo.LotNo, itemInfo.Quantity, item.WorkPoint, cmd, language);
                                    BusinessCode = TransTypeEnum.OOStockINByProduct.GetDescription<DBValue>();
                                }
                                #endregion

                                #region 副产品入库(无源头)
                                else if (TransType == TransTypeEnum.MOStockINByProductNoTrans.GetDescription())
                                {
                                    log.Debug("无源头副产品入库" + TransType);
                                    //更新源头单据数量
                                    //ICSManufactureService.MOStockINByProductDoc(itemInfo.LotNo, itemInfo.Quantity, item.WorkPoint, cmd, language);
                                    BusinessCode = TransTypeEnum.MOStockINByProductNoTrans.GetDescription<DBValue>();
                                }
                                #endregion
                                else
                                {
                                    throw new Exception(LanguageHelper.GetNameSingle("WMSAPIInfo003"));//"单据类型不存在!"
                                }
                                //入库
                                ICSWareHouseLotInfoService.WareHouseLotInfoUpAM(Identification, itemInfo.LocationCode, itemInfo.LotNo, itemInfo.Quantity,
                                    item.User, item.WorkPoint, WHTransType, BusinessCode, cmd, language, itemInfo.LogID, itemInfo.InvCode + itemInfo.WarehouseCode, itemInfo.TransCode, itemInfo.TransSequence);
                            }
                        }

                        #region 拆卸单
                        if (TransType == TransTypeEnum.DisassemblyDoc.GetDescription())
                        {
                            //更新套件锁定数量
                            ICSWareHouseService.DisassemblyDoc(Identification, cmd, language);
                        }
                        #endregion}
                    }
                    //上传ERP
                    if (Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["UploadERP"]))
                    {
                        if (TransTypeOriginal != string.Empty)
                        {
                            TransType = TransTypeOriginal;
                        }
                        //采购入库
                        if (TransType == TransTypeEnum.PurchaseReceiveDoc.GetDescription())
                            ICSPurchaseService.PurchaseReceiveDocERP(TransType, Identification, cmd, language, BusinessCode);
                        //审核的到货单
                        else if (TransType == TransTypeEnum.DeliveryNotice.GetDescription())
                            dtable = ICSPurchaseService.DeliveryNoticeInERP(TransType, Identification, cmd, language, BusinessCode);
                        //采购拒收
                        else if (TransType == TransTypeEnum.PurchaseRejectDoc.GetDescription())
                            ICSPurchaseService.PurchaseRejectDocInERP(TransType, Identification, cmd, language, BusinessCode);
                        //审核的委外到货单
                        else if (TransType == TransTypeEnum.ODeliveryNotice.GetDescription())
                            ICSOutsourcingService.ODeliveryNoticeInERP(TransType, Identification, cmd, language, BusinessCode);
                        //委外拒收
                        else if (TransType == TransTypeEnum.OutsourcingRejectDoc.GetDescription())
                            ICSOutsourcingService.OutsourcingRejectDocInERP(TransType, Identification, cmd, language, BusinessCode);
                        //委外退料
                        else if (TransType == TransTypeEnum.ICSOutsourcingIssueDoNegative.GetDescription()
                                || TransType == TransTypeEnum.ICSOutsourcingIssueDoNegativeApply.GetDescription()
                                || TransType == TransTypeEnum.ICSOutsourcingIssueDoNegativeIssue.GetDescription())
                            ICSOutsourcingService.OutsourcingIssueDoNegativeERP(TransType, Identification, cmd, language, BusinessCode);
                        //委外入库
                        else if (TransType == TransTypeEnum.OutsourcingReceiveDoc.GetDescription())
                            ICSOutsourcingService.OutsourcingReceiveDocERP(TransType, Identification, cmd, language, BusinessCode);
                        //生产退料
                        else if (TransType == TransTypeEnum.MOIssueDocNegative.GetDescription()
                            || TransType == TransTypeEnum.MOIssueDocNegativeApply.GetDescription()
                            || TransType == TransTypeEnum.MOIssueDocNegativeIssue.GetDescription())
                            ICSManufactureService.MOIssueDocNegativeERP(TransType, Identification, cmd, language, BusinessCode);
                        //生产入库
                        else if (TransType == TransTypeEnum.ManufactureReceiveDoc.GetDescription())
                            ICSManufactureService.ManufactureReceiveDocERP(TransType, Identification, cmd, language, BusinessCode);
                        //副产品入库
                        else if (TransType == TransTypeEnum.MOStockINByProduct.GetDescription())
                            ICSManufactureService.MOStockINByProductDocERP(TransType, Identification, cmd, language, BusinessCode);
                        //委外副产品入库
                        else if (TransType == TransTypeEnum.OOStockINByProduct.GetDescription())
                            ICSManufactureService.OOStockINByProductDocERP(TransType, Identification, cmd, language, BusinessCode);
                        //无源头副产品入库
                        else if (TransType == TransTypeEnum.MOStockINByProductNoTrans.GetDescription())
                            ICSManufactureService.MOStockINByProductNoTransDocERP(TransType, Identification, cmd, language, BusinessCode);
                        //开立的生产入库单
                        else if (TransType == TransTypeEnum.ManufactureReceive.GetDescription())
                            ICSManufactureService.ManufactureReceiveERP(TransType, Identification, cmd, language, BusinessCode);
                        //返工工单
                        else if (TransType == TransTypeEnum.ReWorkReceiveMo.GetDescription())
                            ICSManufactureService.ReWorkReceiveMoERP(TransType, Identification, cmd, language, BusinessCode);
                        //销售退货
                        else if (TransType == TransTypeEnum.SalesShipmentDocNegative.GetDescription())
                            ICSSalesService.SalesShipmentDocNegativeERP(TransType, Identification, cmd, language, BusinessCode);
                        //两步调入
                        else if (TransType == TransTypeEnum.TwoStepTransferDocIn.GetDescription())
                            ICSWareHouseService.TwoStepTransferDocInERP(TransType, Identification, cmd, language, BusinessCode);
                        //销售退货-原条码
                        else if (TransType == TransTypeEnum.SalesReturnBack.GetDescription())
                            ICSSalesService.SalesReturnBackInERP(TransType, Identification, cmd, language, BusinessCode);
                        //其他入库
                        else if (TransType == TransTypeEnum.OtherInDoc.GetDescription())
                            ICSWareHouseService.OtherInDocERP(TransType, Identification, cmd, language, BusinessCode);
                        //拆卸单
                        if (TransType == TransTypeEnum.DisassemblyDoc.GetDescription())
                            ICSWareHouseService.DisassemblyDocERP(TransType, Identification, cmd, language, BusinessCode);
                        //归还
                        else if (TransType == TransTypeEnum.ReturnDoc.GetDescription())
                            ICSWareHouseService.ReturnDocERP(TransType, Identification, cmd, language, BusinessCode);
                    }
                    if(TransType == TransTypeEnum.DeliveryNotice.GetDescription())
                    {
                        cmd.Transaction.Commit();
                        return dtable;
                    }
                    else
                    {
                        DataTable table = GetData(Identification, 1, cmd);
                        cmd.Transaction.Commit();
                        return table;
                    }
                    
                }
                catch (Exception ex)
                {
                    if (cmd.Transaction != null)
                        cmd.Transaction.Rollback();
                    log.Error(ex.Message);
                    throw new Exception(ex.Message);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                    }
                    conn.Dispose();
                }
            }
        }


        /// <summary>
        /// 下架
        /// </summary>
        /// <param name="JsonData"></param>
        /// <returns></returns>
        public static DataTable LOTStockDownCreate(List<LOTStockModel> JsonData)
        {
            String PrintEnable = "";
            var language = LanguageHelper.GetName("WMSAPIInfo");
            if (JsonData.Count <= 0)
            {
                throw new Exception(language.GetNameByCode("WMSAPIInfo007"));//"传送数据为空!"
            }
            List<LOTStockModelList> model = new List<LOTStockModelList>();
            DataTable printTable = new DataTable();
            using (SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString))
            {
                conn.Open();
                SqlTransaction sqlTran = conn.BeginTransaction();
                SqlCommand cmd = new SqlCommand();
                cmd.Transaction = sqlTran;
                cmd.Connection = conn;
                cmd.CommandTimeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["TimeOut"]);
                string BusinessCode = string.Empty;
                try
                {
                    string TransType = string.Empty;
                    string Identification = Guid.NewGuid().ToString();
                    foreach (var item in JsonData)
                    {
                        TransType = item.TransType;
                        if (!EnumHelper.HasDescriptions(typeof(TransTypeEnum), TransType))
                        {
                            throw new Exception(LanguageHelper.GetNameSingle("WMSAPIInfo003"));//"单据类型不存在!"
                        }
                        else if (string.IsNullOrEmpty(item.TransCode))
                        {
                            throw new Exception(language.GetNameByCode("WMSAPIInfo001"));//"单据号不能为空!"
                        }
                        string[] trans = item.TransCode.Split('~');
                        string MergeID = "";
                        if (trans.Length == 2)
                        {
                            MergeID = trans[0];
                            item.TransCode = trans[1];
                        }
                        #region 采购退货
                        if (TransType == TransTypeEnum.PurchaseReceiveDoctNegative.GetDescription())
                        {
                            BusinessCode = TransTypeEnum.PurchaseReceiveDoctNegative.GetDescription<DBValue>();
                            //更新源头单据数量
                            ICSPurchaseService.PurchaseReceiveDoctNegative(item.TransCode, item.TransSequence, item.Quantity, item.WorkPoint, cmd, language);

                            foreach (var itemInfo in item.detail)
                            {
                                //出库
                                printTable=ICSWareHouseLotInfoService.WareHouseLotInfoDown(Identification, item.TransCode, item.TransSequence, itemInfo.LotNo, itemInfo.CurrentQuantity,
                                    item.User, item.WorkPoint, "3", TransTypeEnum.PurchaseReceiveDoctNegative.GetDescription<DBValue>(), cmd, language, itemInfo.LogID, "");
                            }
                        }
                        #endregion
                        #region 委外发料
                        else if (TransType == TransTypeEnum.OutsourcingIssueDoc.GetDescription())
                        {
                            BusinessCode = TransTypeEnum.OutsourcingIssueDoc.GetDescription<DBValue>();
                            //更新源头单据数量
                            ICSOutsourcingService.OutsourcingIssueDoc(item.TransCode, item.TransSequence, item.Quantity, item.WorkPoint, cmd, language,enableCode);

                            foreach (var itemInfo in item.detail)
                            {
                                //出库
                                printTable=ICSWareHouseLotInfoService.WareHouseLotInfoDown(Identification, item.TransCode, item.TransSequence, itemInfo.LotNo, itemInfo.CurrentQuantity,
                                    item.User, item.WorkPoint, "3", TransTypeEnum.OutsourcingIssueDoc.GetDescription<DBValue>(), cmd, language, itemInfo.LogID, MergeID);
                            }
                        }
                        #endregion
                        #region 委外退货
                        else if (TransType == TransTypeEnum.OutsourcingReturnBack.GetDescription())
                        {
                            BusinessCode = TransTypeEnum.OutsourcingReturnBack.GetDescription<DBValue>();
                            //更新源头单据数量
                            ICSOutsourcingService.OutsourcingReturnBack(item.TransCode, item.TransSequence, item.Quantity, item.WorkPoint, cmd, language);

                            foreach (var itemInfo in item.detail)
                            {
                                //出库
                                printTable = ICSWareHouseLotInfoService.WareHouseLotInfoDown(Identification, item.TransCode, item.TransSequence, itemInfo.LotNo, itemInfo.CurrentQuantity,
                                    item.User, item.WorkPoint, "3", TransTypeEnum.OutsourcingReturnBack.GetDescription<DBValue>(), cmd, language, itemInfo.LogID, "");
                            }
                        }
                        #endregion
                        #region 生产发料
                        else if (TransType == TransTypeEnum.MOIssueDoc.GetDescription())
                        {
                            BusinessCode = TransTypeEnum.MOIssueDoc.GetDescription<DBValue>();
                            //更新源头单据数量
                            ICSManufactureService.MOIssueDoc(item.TransCode, item.TransSequence, item.Quantity, item.WorkPoint, cmd, language,enableCode);

                            foreach (var itemInfo in item.detail)
                            {
                                //出库
                                printTable=ICSWareHouseLotInfoService.WareHouseLotInfoDown(Identification, item.TransCode, item.TransSequence, itemInfo.LotNo, itemInfo.CurrentQuantity,
                                    item.User, item.WorkPoint, "3", TransTypeEnum.MOIssueDoc.GetDescription<DBValue>(), cmd, language, itemInfo.LogID, MergeID);
                            }
                        }
                        #endregion
                        #region 销售出库
                        else if (TransType == TransTypeEnum.SalesShipmentDoc.GetDescription())
                        {
                            BusinessCode = TransTypeEnum.SalesShipmentDoc.GetDescription<DBValue>();
                            //更新源头单据数量
                            ICSSalesService.SalesShipmentDoc(item.TransCode, item.TransSequence, item.Quantity, item.WorkPoint, cmd, language);

                            foreach (var itemInfo in item.detail)
                            {
                                //出库
                                printTable = ICSWareHouseLotInfoService.WareHouseLotInfoDown(Identification, item.TransCode, item.TransSequence, itemInfo.LotNo, itemInfo.CurrentQuantity,
                                    item.User, item.WorkPoint, "3", TransTypeEnum.SalesShipmentDoc.GetDescription<DBValue>(), cmd, language, itemInfo.LogID, MergeID);
                            }
                        }
                        #endregion
                        #region 两步调出
                        else if (TransType == TransTypeEnum.TwoStepTransferDocOut.GetDescription())
                        {
                            BusinessCode = TransTypeEnum.TwoStepTransferDocOut.GetDescription<DBValue>();
                            //更新源头单据数量
                            ICSWareHouseService.TwoStepTransferDocOut(item.TransCode, item.TransSequence, item.Quantity, item.WorkPoint, cmd, language);

                            foreach (var itemInfo in item.detail)
                            {
                                //出库
                                printTable = ICSWareHouseLotInfoService.WareHouseLotInfoDown(Identification, item.TransCode, item.TransSequence, itemInfo.LotNo, itemInfo.CurrentQuantity,
                                    item.User, item.WorkPoint, "6", TransTypeEnum.TwoStepTransferDocOut.GetDescription<DBValue>(), cmd, language, itemInfo.LogID, MergeID);
                            }
                        }
                        #endregion
                        #region 其他出库
                        else if (TransType == TransTypeEnum.OtherOutDoc.GetDescription())
                        {
                            BusinessCode = TransTypeEnum.OtherOutDoc.GetDescription<DBValue>();
                            //更新源头单据数量
                            ICSWareHouseService.OtherOutDoc(item.TransCode, item.TransSequence, item.Quantity, item.WorkPoint, cmd, language);

                            foreach (var itemInfo in item.detail)
                            {
                                //出库
                                printTable=ICSWareHouseLotInfoService.WareHouseLotInfoDown(Identification, item.TransCode, item.TransSequence, itemInfo.LotNo, itemInfo.CurrentQuantity,
                                    item.User, item.WorkPoint, "3", TransTypeEnum.OtherOutDoc.GetDescription<DBValue>(), cmd, language, itemInfo.LogID, MergeID);
                            }
                        }
                        #endregion
                        #region 领料申请单发料
                        else if (TransType == TransTypeEnum.MOApply.GetDescription())
                        {
                           
                            BusinessCode = TransTypeEnum.MOApply.GetDescription<DBValue>();
                            //更新源头单据数量
                            ICSManufactureService.MOApply(item.TransCode, item.TransSequence, item.Quantity, item.WorkPoint, cmd, language, enableCode);
                           
                            foreach (var itemInfo in item.detail)
                            {
                                //出库
                                printTable = ICSWareHouseLotInfoService.WareHouseLotInfoDown(Identification, item.TransCode, item.TransSequence, itemInfo.LotNo, itemInfo.CurrentQuantity,
                                    item.User, item.WorkPoint, "3", TransTypeEnum.MOApply.GetDescription<DBValue>(), cmd, language, itemInfo.LogID, MergeID);
                                
                            }
                        }
                        #endregion
                        #region 补料申请单发料
                        else if (TransType == TransTypeEnum.MOReplenishment.GetDescription())
                        {
                            BusinessCode = TransTypeEnum.MOReplenishment.GetDescription<DBValue>();
                            //更新源头单据数量
                            ICSManufactureService.MOReplenishment(item.TransCode, item.TransSequence, item.Quantity, item.WorkPoint, cmd, language, enableCode);

                            foreach (var itemInfo in item.detail)
                            {
                                //出库
                                printTable = ICSWareHouseLotInfoService.WareHouseLotInfoDown(Identification, item.TransCode, item.TransSequence, itemInfo.LotNo, itemInfo.CurrentQuantity,
                                    item.User, item.WorkPoint, "3", TransTypeEnum.MOReplenishment.GetDescription<DBValue>(), cmd, language, itemInfo.LogID, MergeID);
                            }
                        }
                        #endregion
                        #region 委外领料申请单发料
                        else if (TransType == TransTypeEnum.OOApply.GetDescription())
                        {
                            BusinessCode = TransTypeEnum.OOApply.GetDescription<DBValue>();
                            //更新源头单据数量
                            ICSOutsourcingService.OOApply(item.TransCode, item.TransSequence, item.Quantity, item.WorkPoint, cmd, language,enableCode);

                            foreach (var itemInfo in item.detail)
                            {
                                //出库
                                printTable = ICSWareHouseLotInfoService.WareHouseLotInfoDown(Identification, item.TransCode, item.TransSequence, itemInfo.LotNo, itemInfo.CurrentQuantity,
                                    item.User, item.WorkPoint, "3", TransTypeEnum.OOApply.GetDescription<DBValue>(), cmd, language, itemInfo.LogID, MergeID);
                            }
                        }
                        #endregion
                        #region 开立材料出库
                        else if (TransType == TransTypeEnum.MOIssue.GetDescription())
                        {
                            BusinessCode = TransTypeEnum.MOIssue.GetDescription<DBValue>();
                            //更新源头单据数量
                            ICSManufactureService.MOIssue(item.TransCode, item.TransSequence, item.Quantity, item.WorkPoint, cmd, language);

                            foreach (var itemInfo in item.detail)
                            {
                                //出库
                                printTable=ICSWareHouseLotInfoService.WareHouseLotInfoDown(Identification, item.TransCode, item.TransSequence, itemInfo.LotNo, itemInfo.CurrentQuantity,
                                    item.User, item.WorkPoint, "3", TransTypeEnum.MOIssue.GetDescription<DBValue>(), cmd, language, itemInfo.LogID, MergeID);
                            }
                        }
                        #endregion
                        #region 开立委外材料出库
                        else if (TransType == TransTypeEnum.OOIssue.GetDescription())
                        {
                            BusinessCode = TransTypeEnum.OOIssue.GetDescription<DBValue>();
                            //更新源头单据数量
                            ICSOutsourcingService.OOIssue(item.TransCode, item.TransSequence, item.Quantity, item.WorkPoint, cmd, language);

                            foreach (var itemInfo in item.detail)
                            {
                                //出库
                                printTable=ICSWareHouseLotInfoService.WareHouseLotInfoDown(Identification, item.TransCode, item.TransSequence, itemInfo.LotNo, itemInfo.CurrentQuantity,
                                    item.User, item.WorkPoint, "3", TransTypeEnum.OOIssue.GetDescription<DBValue>(), cmd, language, itemInfo.LogID, MergeID);
                            }
                        }
                        #endregion
                        #region 开立红字入库单
                        else if (TransType == TransTypeEnum.PurchaseReceive.GetDescription())
                        {
                            BusinessCode = TransTypeEnum.PurchaseReceive.GetDescription<DBValue>();
                            //更新源头单据数量
                            ICSPurchaseService.PurchaseReceive(item.TransCode, item.TransSequence, item.Quantity, item.WorkPoint, cmd, language);

                            foreach (var itemInfo in item.detail)
                            {
                                //出库
                                printTable=ICSWareHouseLotInfoService.WareHouseLotInfoDown(Identification, item.TransCode, item.TransSequence, itemInfo.LotNo, itemInfo.CurrentQuantity,
                                    item.User, item.WorkPoint, "3", TransTypeEnum.PurchaseReceive.GetDescription<DBValue>(), cmd, language, itemInfo.LogID, "");
                            }
                        }
                        #endregion
                        #region 开立委外红字入库单
                        else if (TransType == TransTypeEnum.OutsourcingReceiveDocNegative.GetDescription())
                        {
                            BusinessCode = TransTypeEnum.OutsourcingReceiveDocNegative.GetDescription<DBValue>();
                            //更新源头单据数量
                            ICSOutsourcingService.OutsourcingReceiveDocNegative(item.TransCode, item.TransSequence, item.Quantity, item.WorkPoint, cmd, language);

                            foreach (var itemInfo in item.detail)
                            {
                                //出库
                                printTable=ICSWareHouseLotInfoService.WareHouseLotInfoDown(Identification, item.TransCode, item.TransSequence, itemInfo.LotNo, itemInfo.CurrentQuantity,
                                    item.User, item.WorkPoint, "3", TransTypeEnum.OutsourcingReceiveDocNegative.GetDescription<DBValue>(), cmd, language, itemInfo.LogID, "");
                            }
                        }
                        #endregion
                        #region 借用
                        else if (TransType == TransTypeEnum.BrrowDoc.GetDescription())
                        {
                            BusinessCode = TransTypeEnum.BrrowDoc.GetDescription<DBValue>();
                            //更新源头单据数量
                            ICSWareHouseService.BrrowDoc(item.TransCode, item.TransSequence, item.Quantity, item.WorkPoint, cmd, language);
                            
                            foreach (var itemInfo in item.detail)
                            {
                                //出库
                                printTable=ICSWareHouseLotInfoService.WareHouseLotInfoDown(Identification, item.TransCode, item.TransSequence, itemInfo.LotNo, itemInfo.CurrentQuantity,
                                    item.User, item.WorkPoint, "3", TransTypeEnum.BrrowDoc.GetDescription<DBValue>(), cmd, language, itemInfo.LogID, MergeID);

                            }
                        }
                        #endregion
                        else
                        {
                            throw new Exception(LanguageHelper.GetNameSingle("WMSAPIInfo003"));//"单据类型不存在!"
                        }
                    }
                    //上传ERP
                    if (Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["UploadERP"]))
                    {
                        //采购退货
                        if (TransType == TransTypeEnum.PurchaseReceiveDoctNegative.GetDescription())
                            ICSPurchaseService.PurchaseReceiveDoctNegativeERP(TransType, Identification, cmd, language, BusinessCode);
                        //委外发料
                        else if (TransType == TransTypeEnum.OutsourcingIssueDoc.GetDescription())
                            ICSOutsourcingService.OutsourcingIssueDocERP(TransType, Identification, cmd, language, BusinessCode);
                        //委外退货
                        else if (TransType == TransTypeEnum.OutsourcingReturnBack.GetDescription())
                        {
                            if (DBHelper.IsU9())
                            { ICSOutsourcingService.U9OutsourcingReturnBackERP(TransType, Identification, cmd, language, BusinessCode); }
                            else
                                ICSOutsourcingService.OutsourcingReturnBackERP(TransType, Identification, cmd, language, BusinessCode);
                       }
                           
                        //生产发料
                        else if (TransType == TransTypeEnum.MOIssueDoc.GetDescription())
                            ICSManufactureService.MOIssueDocERP(TransType, Identification, cmd, language, BusinessCode);
                        //销售出库
                        else if (TransType == TransTypeEnum.SalesShipmentDoc.GetDescription())
                        { 
                            if (DBHelper.IsU9()) 
                            { ICSSalesService.U9SalesShipmentDocERP(TransType, Identification, cmd, language, BusinessCode); }
                            else { ICSSalesService.SalesShipmentDocERP(TransType, Identification, cmd, language, BusinessCode); }                        
                        }
                            
                        //两步调出
                        else if (TransType == TransTypeEnum.TwoStepTransferDocOut.GetDescription())
                            ICSWareHouseService.TwoStepTransferDocOutERP(TransType, Identification, cmd, language, BusinessCode);
                        //其他出库
                        else if (TransType == TransTypeEnum.OtherOutDoc.GetDescription()) 
                        {
                            if (DBHelper.IsU9())
                            {
                                ICSWareHouseService.CreateOtherOutDocERP(TransType, Identification, cmd, language, BusinessCode);
                            }
                            else
                                ICSWareHouseService.OtherOutDocERP(TransType, Identification, cmd, language, BusinessCode);

                        }

                        //领料申请单发料
                        if (TransType == TransTypeEnum.MOApply.GetDescription()) 
                        {
                                ICSManufactureService.MOApplyERP(TransType, Identification, cmd, language, BusinessCode);
                        }
                            
                        //补料申请单发料
                        if (TransType == TransTypeEnum.MOReplenishment.GetDescription())
                            ICSManufactureService.MOReplenishmentERP(TransType, Identification, cmd, language, BusinessCode);
                        //委外领料申请单发料
                        if (TransType == TransTypeEnum.OOApply.GetDescription())
                            ICSOutsourcingService.OOApplyERP(TransType, Identification, cmd, language, BusinessCode);
                        //开立材料出库
                        if (TransType == TransTypeEnum.MOIssue.GetDescription()) 
                        { 
                            if (DBHelper.IsU9()) 
                            { ICSManufactureService.U9MOIssueERP(TransType, Identification, cmd, language, BusinessCode); } 
                            else { ICSManufactureService.MOIssueERP(TransType, Identification, cmd, language, BusinessCode); }
                        }
                        
                        //开立委外材料出库
                        if (TransType == TransTypeEnum.OOIssue.GetDescription())
                            ICSOutsourcingService.OOIssueERP(TransType, Identification, cmd, language, BusinessCode);
                        //开立红字入库单
                        if (TransType == TransTypeEnum.PurchaseReceive.GetDescription())
                            ICSPurchaseService.PurchaseReceiveERP(TransType, Identification, cmd, language, BusinessCode);
                        //开立委外红字入库单
                        if (TransType == TransTypeEnum.OutsourcingReceiveDocNegative.GetDescription())
                            ICSOutsourcingService.OutsourcingReceiveDocNegativeERP(TransType, Identification, cmd, language, BusinessCode);
                        //借用
                        if (TransType == TransTypeEnum.BrrowDoc.GetDescription())
                            ICSWareHouseService.BrrowDocERP(TransType, Identification, cmd, language, BusinessCode);
                    }
                    if (!printTable.Equals("{}"))
                    {
                        cmd.Transaction.Commit();
                        return printTable;
                    }
                    else
                    {
                        DataTable table = GetData(Identification, 2, cmd);
                        cmd.Transaction.Commit();
                        return table;
                    }
                   
                }
                catch (Exception ex)
                {
                    if (cmd.Transaction != null)
                        cmd.Transaction.Rollback();
                    log.Error(ex.Message);
                    throw new Exception(ex.Message);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                    }
                    conn.Dispose();
                }
            }
        }

        /// <summary>
        /// 下架
        /// </summary>
        /// <param name="JsonData"></param>
        /// <returns></returns>
        public static DataTable LOTStockDownAMCreate(List<LOTStockModel> JsonData)
        {
            String PrintEnable = "";
            var language = LanguageHelper.GetName("WMSAPIInfo");
            if (JsonData.Count <= 0)
            {
                throw new Exception(language.GetNameByCode("WMSAPIInfo007"));//"传送数据为空!"
            }
            List<LOTStockModelList> model = new List<LOTStockModelList>();
            DataTable printTable = new DataTable();
            using (SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString))
            {
                conn.Open();
                SqlTransaction sqlTran = conn.BeginTransaction();
                SqlCommand cmd = new SqlCommand();
                cmd.Transaction = sqlTran;
                cmd.Connection = conn;
                cmd.CommandTimeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["TimeOut"]);
                string BusinessCode = string.Empty;
                try
                {
                    string TransType = string.Empty;
                    string Identification = Guid.NewGuid().ToString();
                    foreach (var item in JsonData)
                    {
                        TransType = item.TransType;
                        if (!EnumHelper.HasDescriptions(typeof(TransTypeEnum), TransType))
                        {
                            throw new Exception(LanguageHelper.GetNameSingle("WMSAPIInfo003"));//"单据类型不存在!"
                        }
                        else if (string.IsNullOrEmpty(item.TransCode))
                        {
                            throw new Exception(language.GetNameByCode("WMSAPIInfo001"));//"单据号不能为空!"
                        }
                        string[] trans = item.TransCode.Split('~');
                        string MergeID = "";
                        if (trans.Length == 2)
                        {
                            MergeID = trans[0];
                            item.TransCode = trans[1];
                        }
                        #region 采购退货
                        if (TransType == TransTypeEnum.PurchaseReceiveDoctNegative.GetDescription())
                        {
                            BusinessCode = TransTypeEnum.PurchaseReceiveDoctNegative.GetDescription<DBValue>();
                            //更新源头单据数量
                            ICSPurchaseService.PurchaseReceiveDoctNegative(item.TransCode, item.TransSequence, item.Quantity, item.WorkPoint, cmd, language);

                            foreach (var itemInfo in item.detail)
                            {
                                //出库
                                printTable = ICSWareHouseLotInfoService.WareHouseLotInfoDown(Identification, item.TransCode, item.TransSequence, itemInfo.LotNo, itemInfo.CurrentQuantity,
                                    item.User, item.WorkPoint, "3", TransTypeEnum.PurchaseReceiveDoctNegative.GetDescription<DBValue>(), cmd, language, itemInfo.LogID, "");
                            }
                        }
                        #endregion
                        #region 委外发料
                        else if (TransType == TransTypeEnum.OutsourcingIssueDoc.GetDescription())
                        {
                            BusinessCode = TransTypeEnum.OutsourcingIssueDoc.GetDescription<DBValue>();
                            //更新源头单据数量
                            ICSOutsourcingService.OutsourcingIssueDoc(item.TransCode, item.TransSequence, item.Quantity, item.WorkPoint, cmd, language, enableCode);

                            foreach (var itemInfo in item.detail)
                            {
                                //出库
                                printTable = ICSWareHouseLotInfoService.WareHouseLotInfoDown(Identification, item.TransCode, item.TransSequence, itemInfo.LotNo, itemInfo.CurrentQuantity,
                                    item.User, item.WorkPoint, "3", TransTypeEnum.OutsourcingIssueDoc.GetDescription<DBValue>(), cmd, language, itemInfo.LogID, MergeID);
                            }
                        }
                        #endregion
                        #region 委外退货
                        else if (TransType == TransTypeEnum.OutsourcingReturnBack.GetDescription())
                        {
                            BusinessCode = TransTypeEnum.OutsourcingReturnBack.GetDescription<DBValue>();
                            //更新源头单据数量
                            ICSOutsourcingService.OutsourcingReturnBack(item.TransCode, item.TransSequence, item.Quantity, item.WorkPoint, cmd, language);

                            foreach (var itemInfo in item.detail)
                            {
                                //出库
                                printTable = ICSWareHouseLotInfoService.WareHouseLotInfoDown(Identification, item.TransCode, item.TransSequence, itemInfo.LotNo, itemInfo.CurrentQuantity,
                                    item.User, item.WorkPoint, "3", TransTypeEnum.OutsourcingReturnBack.GetDescription<DBValue>(), cmd, language, itemInfo.LogID, "");
                            }
                        }
                        #endregion
                        #region 生产发料
                        else if (TransType == TransTypeEnum.MOIssueDoc.GetDescription())
                        {
                            BusinessCode = TransTypeEnum.MOIssueDoc.GetDescription<DBValue>();
                            //工单行查子件信息
                            string chekkksql = @"select a.Sequence,a.InvCode FROM ICSMOPick  a
                                INNER JOIN ICSMO b ON  a.MODetailID=b.MODetailID AND a.WorkPoint=b.WorkPoint
                                WHERE b.MOCode='{0}' AND b.Sequence='{2}' AND a.WorkPoint='{1}' ";
                            chekkksql = string.Format(chekkksql, item.TransCode, item.WorkPoint, item.TransSequence);
                            log.Debug("工单行查子件信息" + chekkksql);
                            DataTable dtaa = DBHelper.SQlReturnData(chekkksql, cmd);
                            
                            //ICSManufactureService.AMMOIssueDoc(item.TransCode, item.TransSequence, item.Quantity, item.WorkPoint, cmd, language, enableCode);

                            foreach (var itemInfo in item.detail)
                            {
                                //查询条码的物料
                                string cheklotsql = @"select a.InvCode FROM ICSInventoryLot  a
                                WHERE a.LotNo='{0}'  AND a.WorkPoint='{1}' ";
                                cheklotsql = string.Format(cheklotsql, itemInfo.LotNo, item.WorkPoint);
                                log.Debug("查询条码的物料" + cheklotsql);
                                DataTable lotdata = DBHelper.SQlReturnData(cheklotsql, cmd);

                                //DataTable ad0=dtaa.Select(a => a.invcode == lotdata.Rows[0]["InvCode"].ToString());
                                DataRow[] drs = dtaa.Select("InvCode ='" + lotdata.Rows[0]["InvCode"].ToString() + "'");
                                if (drs==null||drs.Length==0)
                                {
                                    throw new Exception("当前扫描的条码物料和单据子件物料没有匹配的行,请确认!");
                                }
                                //DataTable ad0 = dtaa.AsEnumerable()
                                //.Where(a => a.Field<string>("InvCode") == lotdata.Rows[0]["InvCode"].ToString())
                                //.CopyToDataTable();
                                //if (ad0 == null || ad0.Rows.Count == 0)
                                //{
                                //    throw new Exception("当前扫描的条码物料和单据子件物料没有匹配的行,请确认!");
                                //}
                                string seq = item.TransSequence + "~" + drs[0]["Sequence"].ToString();
                                log.Debug("工单子件行号:" + seq);
                                //判断是否开启辅计量,计算辅计量比例
                                string chekksql = @"select c.EATTRIBUTE1 FROM ICSMOPick  a
                                INNER JOIN ICSMO b ON  a.MODetailID=b.MODetailID AND a.WorkPoint=b.WorkPoint
                                INNER JOIN ICSInventory c on a.InvCode=c.InvCode and a.WorkPoint=c.WorkPoint
                                WHERE b.MOCode='{0}' AND b.Sequence+'~'+a.Sequence='{3}' AND a.WorkPoint='{1}' and c.AmountEnable='1'";
                                chekksql = string.Format(chekksql, item.TransCode, item.WorkPoint, itemInfo.CurrentQuantity, seq);
                                DataTable dta = DBHelper.SQlReturnData(chekksql, cmd);
                                if (dta.Rows.Count > 0)
                                {
                                    itemInfo.CurrentQuantity = (decimal.Parse(itemInfo.CurrentQuantity) * decimal.Parse(dta.Rows[0]["EATTRIBUTE1"].ToString())).ToString();
                                }
                                //更新源头单据数量
                                ICSManufactureService.AMMOIssueDoc(item.TransCode, seq, itemInfo.CurrentQuantity, item.WorkPoint, cmd, language, enableCode);
                                //出库
                                printTable = ICSWareHouseLotInfoService.AMWareHouseLotInfoDown(Identification, item.TransCode, seq, itemInfo.LotNo, itemInfo.CurrentQuantity,
                                    item.User, item.WorkPoint, "3", TransTypeEnum.MOIssueDoc.GetDescription<DBValue>(), cmd, language, itemInfo.LogID, MergeID);
                            }
                        }
                        #endregion
                        #region 销售出库
                        else if (TransType == TransTypeEnum.SalesShipmentDoc.GetDescription())
                        {
                            BusinessCode = TransTypeEnum.SalesShipmentDoc.GetDescription<DBValue>();
                            
                            //出库
                            //出库
                            string chekkksql = @"select a.Sequence,a.InvCode FROM ICSSDN a
                                WHERE a.SDNCode='{0}' AND a.WorkPoint='{1}' ";
                            chekkksql = string.Format(chekkksql, item.TransCode, item.WorkPoint);
                            log.Debug("销售发货单行信息" + chekkksql);
                            DataTable dtaa = DBHelper.SQlReturnData(chekkksql, cmd);

                            foreach (var itemInfo in item.detail)
                            {
                                
                                //查询条码的物料
                                string cheklotsql = @"select a.InvCode FROM ICSInventoryLot  a
                                WHERE a.LotNo='{0}'  AND a.WorkPoint='{1}' ";
                                cheklotsql = string.Format(cheklotsql, itemInfo.LotNo, item.WorkPoint);
                                log.Debug("查询条码的物料" + cheklotsql);
                                DataTable lotdata = DBHelper.SQlReturnData(cheklotsql, cmd);

                                //DataTable ad0=dtaa.Select(a => a.invcode == lotdata.Rows[0]["InvCode"].ToString());
                                DataRow[] drs = dtaa.Select("InvCode ='" + lotdata.Rows[0]["InvCode"].ToString() + "'");
                                if (drs == null || drs.Length == 0)
                                {
                                    throw new Exception("当前扫描的条码物料和单据物料没有匹配的行,请确认!");
                                }
                                //DataTable ad0 = dtaa.AsEnumerable()
                                //.Where(a => a.Field<string>("InvCode") == lotdata.Rows[0]["InvCode"].ToString())
                                //.CopyToDataTable();
                                //if (ad0 == null || ad0.Rows.Count == 0)
                                //{
                                //    throw new Exception("当前扫描的条码物料和单据子件物料没有匹配的行,请确认!");
                                //}
                                string seq = drs[0]["Sequence"].ToString();
                                log.Debug("销售发货单行号:" + seq);

                                string chekksql = @"select c.EATTRIBUTE1 FROM ICSSDN  a
                                INNER JOIN ICSInventory c on a.InvCode=c.InvCode and a.WorkPoint=c.WorkPoint
                                WHERE a.SDNCode='{0}' AND a.Sequence='{2}' AND a.WorkPoint='{1}' and c.AmountEnable='1'";
                                chekksql = string.Format(chekksql, item.TransCode, item.WorkPoint, seq);
                                DataTable dta = DBHelper.SQlReturnData(chekksql, cmd);
                                if (dta.Rows.Count > 0)
                                {
                                    itemInfo.CurrentQuantity = (decimal.Parse(itemInfo.CurrentQuantity) * decimal.Parse(dta.Rows[0]["EATTRIBUTE1"].ToString())).ToString();
                                }
                                log.Debug("本次数量:" + itemInfo.CurrentQuantity);
                                //更新源头单据数量
                                ICSSalesService.AMSalesShipmentDoc(item.TransCode, seq, itemInfo.CurrentQuantity, item.WorkPoint, cmd, language);

                                printTable = ICSWareHouseLotInfoService.AMWareHouseLotInfoDown(Identification, item.TransCode, seq, itemInfo.LotNo, itemInfo.CurrentQuantity,
                                    item.User, item.WorkPoint, "3", TransTypeEnum.SalesShipmentDoc.GetDescription<DBValue>(), cmd, language, itemInfo.LogID, MergeID);
                            }
                        }
                        #endregion
                        #region 两步调出
                        else if (TransType == TransTypeEnum.TwoStepTransferDocOut.GetDescription())
                        {
                            BusinessCode = TransTypeEnum.TwoStepTransferDocOut.GetDescription<DBValue>();
                            //更新源头单据数量
                            ICSWareHouseService.TwoStepTransferDocOut(item.TransCode, item.TransSequence, item.Quantity, item.WorkPoint, cmd, language);

                            foreach (var itemInfo in item.detail)
                            {
                                //出库
                                printTable = ICSWareHouseLotInfoService.WareHouseLotInfoDown(Identification, item.TransCode, item.TransSequence, itemInfo.LotNo, itemInfo.CurrentQuantity,
                                    item.User, item.WorkPoint, "6", TransTypeEnum.TwoStepTransferDocOut.GetDescription<DBValue>(), cmd, language, itemInfo.LogID, MergeID);
                            }
                        }
                        #endregion
                        #region 其他出库
                        else if (TransType == TransTypeEnum.OtherOutDoc.GetDescription())
                        {
                            BusinessCode = TransTypeEnum.OtherOutDoc.GetDescription<DBValue>();
                            //更新源头单据数量
                            ICSWareHouseService.OtherOutDoc(item.TransCode, item.TransSequence, item.Quantity, item.WorkPoint, cmd, language);

                            foreach (var itemInfo in item.detail)
                            {
                                //出库
                                printTable = ICSWareHouseLotInfoService.WareHouseLotInfoDown(Identification, item.TransCode, item.TransSequence, itemInfo.LotNo, itemInfo.CurrentQuantity,
                                    item.User, item.WorkPoint, "3", TransTypeEnum.OtherOutDoc.GetDescription<DBValue>(), cmd, language, itemInfo.LogID, MergeID);
                            }
                        }
                        #endregion
                        #region 领料申请单发料
                        else if (TransType == TransTypeEnum.MOApply.GetDescription())
                        {

                            BusinessCode = TransTypeEnum.MOApply.GetDescription<DBValue>();
                            //更新源头单据数量
                            ICSManufactureService.MOApply(item.TransCode, item.TransSequence, item.Quantity, item.WorkPoint, cmd, language, enableCode);

                            foreach (var itemInfo in item.detail)
                            {
                                //出库
                                printTable = ICSWareHouseLotInfoService.WareHouseLotInfoDown(Identification, item.TransCode, item.TransSequence, itemInfo.LotNo, itemInfo.CurrentQuantity,
                                    item.User, item.WorkPoint, "3", TransTypeEnum.MOApply.GetDescription<DBValue>(), cmd, language, itemInfo.LogID, MergeID);

                            }
                        }
                        #endregion
                        #region 补料申请单发料
                        else if (TransType == TransTypeEnum.MOReplenishment.GetDescription())
                        {
                            BusinessCode = TransTypeEnum.MOReplenishment.GetDescription<DBValue>();
                            //更新源头单据数量
                            ICSManufactureService.MOReplenishment(item.TransCode, item.TransSequence, item.Quantity, item.WorkPoint, cmd, language, enableCode);

                            foreach (var itemInfo in item.detail)
                            {
                                //出库
                                printTable = ICSWareHouseLotInfoService.WareHouseLotInfoDown(Identification, item.TransCode, item.TransSequence, itemInfo.LotNo, itemInfo.CurrentQuantity,
                                    item.User, item.WorkPoint, "3", TransTypeEnum.MOReplenishment.GetDescription<DBValue>(), cmd, language, itemInfo.LogID, MergeID);
                            }
                        }
                        #endregion
                        #region 委外领料申请单发料
                        else if (TransType == TransTypeEnum.OOApply.GetDescription())
                        {
                            BusinessCode = TransTypeEnum.OOApply.GetDescription<DBValue>();
                            //更新源头单据数量
                            ICSOutsourcingService.OOApply(item.TransCode, item.TransSequence, item.Quantity, item.WorkPoint, cmd, language, enableCode);

                            foreach (var itemInfo in item.detail)
                            {
                                //出库
                                printTable = ICSWareHouseLotInfoService.WareHouseLotInfoDown(Identification, item.TransCode, item.TransSequence, itemInfo.LotNo, itemInfo.CurrentQuantity,
                                    item.User, item.WorkPoint, "3", TransTypeEnum.OOApply.GetDescription<DBValue>(), cmd, language, itemInfo.LogID, MergeID);
                            }
                        }
                        #endregion
                        #region 开立材料出库
                        else if (TransType == TransTypeEnum.MOIssue.GetDescription())
                        {
                            BusinessCode = TransTypeEnum.MOIssue.GetDescription<DBValue>();
                            //更新源头单据数量
                            ICSManufactureService.MOIssue(item.TransCode, item.TransSequence, item.Quantity, item.WorkPoint, cmd, language);

                            foreach (var itemInfo in item.detail)
                            {
                                //出库
                                printTable = ICSWareHouseLotInfoService.WareHouseLotInfoDown(Identification, item.TransCode, item.TransSequence, itemInfo.LotNo, itemInfo.CurrentQuantity,
                                    item.User, item.WorkPoint, "3", TransTypeEnum.MOIssue.GetDescription<DBValue>(), cmd, language, itemInfo.LogID, MergeID);
                            }
                        }
                        #endregion
                        #region 开立委外材料出库
                        else if (TransType == TransTypeEnum.OOIssue.GetDescription())
                        {
                            BusinessCode = TransTypeEnum.OOIssue.GetDescription<DBValue>();
                            //更新源头单据数量
                            ICSOutsourcingService.OOIssue(item.TransCode, item.TransSequence, item.Quantity, item.WorkPoint, cmd, language);

                            foreach (var itemInfo in item.detail)
                            {
                                //出库
                                printTable = ICSWareHouseLotInfoService.WareHouseLotInfoDown(Identification, item.TransCode, item.TransSequence, itemInfo.LotNo, itemInfo.CurrentQuantity,
                                    item.User, item.WorkPoint, "3", TransTypeEnum.OOIssue.GetDescription<DBValue>(), cmd, language, itemInfo.LogID, MergeID);
                            }
                        }
                        #endregion
                        #region 开立红字入库单
                        else if (TransType == TransTypeEnum.PurchaseReceive.GetDescription())
                        {
                            BusinessCode = TransTypeEnum.PurchaseReceive.GetDescription<DBValue>();
                            //更新源头单据数量
                            ICSPurchaseService.PurchaseReceive(item.TransCode, item.TransSequence, item.Quantity, item.WorkPoint, cmd, language);

                            foreach (var itemInfo in item.detail)
                            {
                                //出库
                                printTable = ICSWareHouseLotInfoService.WareHouseLotInfoDown(Identification, item.TransCode, item.TransSequence, itemInfo.LotNo, itemInfo.CurrentQuantity,
                                    item.User, item.WorkPoint, "3", TransTypeEnum.PurchaseReceive.GetDescription<DBValue>(), cmd, language, itemInfo.LogID, "");
                            }
                        }
                        #endregion
                        #region 开立委外红字入库单
                        else if (TransType == TransTypeEnum.OutsourcingReceiveDocNegative.GetDescription())
                        {
                            BusinessCode = TransTypeEnum.OutsourcingReceiveDocNegative.GetDescription<DBValue>();
                            //更新源头单据数量
                            ICSOutsourcingService.OutsourcingReceiveDocNegative(item.TransCode, item.TransSequence, item.Quantity, item.WorkPoint, cmd, language);

                            foreach (var itemInfo in item.detail)
                            {
                                //出库
                                printTable = ICSWareHouseLotInfoService.WareHouseLotInfoDown(Identification, item.TransCode, item.TransSequence, itemInfo.LotNo, itemInfo.CurrentQuantity,
                                    item.User, item.WorkPoint, "3", TransTypeEnum.OutsourcingReceiveDocNegative.GetDescription<DBValue>(), cmd, language, itemInfo.LogID, "");
                            }
                        }
                        #endregion
                        #region 借用
                        else if (TransType == TransTypeEnum.BrrowDoc.GetDescription())
                        {
                            BusinessCode = TransTypeEnum.BrrowDoc.GetDescription<DBValue>();
                            //更新源头单据数量
                            ICSWareHouseService.BrrowDoc(item.TransCode, item.TransSequence, item.Quantity, item.WorkPoint, cmd, language);

                            foreach (var itemInfo in item.detail)
                            {
                                //出库
                                printTable = ICSWareHouseLotInfoService.WareHouseLotInfoDown(Identification, item.TransCode, item.TransSequence, itemInfo.LotNo, itemInfo.CurrentQuantity,
                                    item.User, item.WorkPoint, "3", TransTypeEnum.BrrowDoc.GetDescription<DBValue>(), cmd, language, itemInfo.LogID, MergeID);

                            }
                        }
                        #endregion
                        else
                        {
                            throw new Exception(LanguageHelper.GetNameSingle("WMSAPIInfo003"));//"单据类型不存在!"
                        }
                    }
                    //上传ERP
                    if (Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["UploadERP"]))
                    {
                        //采购退货
                        if (TransType == TransTypeEnum.PurchaseReceiveDoctNegative.GetDescription())
                            ICSPurchaseService.PurchaseReceiveDoctNegativeERP(TransType, Identification, cmd, language, BusinessCode);
                        //委外发料
                        else if (TransType == TransTypeEnum.OutsourcingIssueDoc.GetDescription())
                            ICSOutsourcingService.OutsourcingIssueDocERP(TransType, Identification, cmd, language, BusinessCode);
                        //委外退货
                        else if (TransType == TransTypeEnum.OutsourcingReturnBack.GetDescription())
                        {
                            if (DBHelper.IsU9())
                            { ICSOutsourcingService.U9OutsourcingReturnBackERP(TransType, Identification, cmd, language, BusinessCode); }
                            else
                                ICSOutsourcingService.OutsourcingReturnBackERP(TransType, Identification, cmd, language, BusinessCode);
                        }

                        //生产发料
                        else if (TransType == TransTypeEnum.MOIssueDoc.GetDescription())
                            ICSManufactureService.MOIssueDocERP(TransType, Identification, cmd, language, BusinessCode);
                        //销售出库
                        else if (TransType == TransTypeEnum.SalesShipmentDoc.GetDescription())
                        {
                            if (DBHelper.IsU9())
                            { ICSSalesService.U9SalesShipmentDocERP(TransType, Identification, cmd, language, BusinessCode); }
                            else { ICSSalesService.SalesShipmentDocERP(TransType, Identification, cmd, language, BusinessCode); }
                        }

                        //两步调出
                        else if (TransType == TransTypeEnum.TwoStepTransferDocOut.GetDescription())
                            ICSWareHouseService.TwoStepTransferDocOutERP(TransType, Identification, cmd, language, BusinessCode);
                        //其他出库
                        else if (TransType == TransTypeEnum.OtherOutDoc.GetDescription())
                        {
                            if (DBHelper.IsU9())
                            {
                                ICSWareHouseService.CreateOtherOutDocERP(TransType, Identification, cmd, language, BusinessCode);
                            }
                            else
                                ICSWareHouseService.OtherOutDocERP(TransType, Identification, cmd, language, BusinessCode);

                        }

                        //领料申请单发料
                        if (TransType == TransTypeEnum.MOApply.GetDescription())
                        {
                            ICSManufactureService.MOApplyERP(TransType, Identification, cmd, language, BusinessCode);
                        }

                        //补料申请单发料
                        if (TransType == TransTypeEnum.MOReplenishment.GetDescription())
                            ICSManufactureService.MOReplenishmentERP(TransType, Identification, cmd, language, BusinessCode);
                        //委外领料申请单发料
                        if (TransType == TransTypeEnum.OOApply.GetDescription())
                            ICSOutsourcingService.OOApplyERP(TransType, Identification, cmd, language, BusinessCode);
                        //开立材料出库
                        if (TransType == TransTypeEnum.MOIssue.GetDescription())
                        {
                            if (DBHelper.IsU9())
                            { ICSManufactureService.U9MOIssueERP(TransType, Identification, cmd, language, BusinessCode); }
                            else { ICSManufactureService.MOIssueERP(TransType, Identification, cmd, language, BusinessCode); }
                        }

                        //开立委外材料出库
                        if (TransType == TransTypeEnum.OOIssue.GetDescription())
                            ICSOutsourcingService.OOIssueERP(TransType, Identification, cmd, language, BusinessCode);
                        //开立红字入库单
                        if (TransType == TransTypeEnum.PurchaseReceive.GetDescription())
                            ICSPurchaseService.PurchaseReceiveERP(TransType, Identification, cmd, language, BusinessCode);
                        //开立委外红字入库单
                        if (TransType == TransTypeEnum.OutsourcingReceiveDocNegative.GetDescription())
                            ICSOutsourcingService.OutsourcingReceiveDocNegativeERP(TransType, Identification, cmd, language, BusinessCode);
                        //借用
                        if (TransType == TransTypeEnum.BrrowDoc.GetDescription())
                            ICSWareHouseService.BrrowDocERP(TransType, Identification, cmd, language, BusinessCode);
                    }
                    if (!printTable.Equals("{}"))
                    {
                        cmd.Transaction.Commit();
                        return printTable;
                    }
                    else
                    {
                        DataTable table = GetData(Identification, 2, cmd);
                        cmd.Transaction.Commit();
                        return table;
                    }

                }
                catch (Exception ex)
                {
                    if (cmd.Transaction != null)
                        cmd.Transaction.Rollback();
                    log.Error(ex.Message);
                    throw new Exception(ex.Message);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                    }
                    conn.Dispose();
                }
            }
        }

        #region 采购
        /// <summary>
        /// 采购到货
        /// </summary>
        /// <param name="JsonData"></param>
        /// <returns></returns>
        public static DataTable DeliveryNoticeCreate(List<ICSDeliveryNotice> JsonData)
        {
            var language = LanguageHelper.GetName("WMSAPIInfo");
            if (JsonData.Count <= 0)
            {
                throw new Exception(language.GetNameByCode("WMSAPIInfo007"));//"传送数据为空!"
            }
            using (SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString))
            {
                conn.Open();
                SqlTransaction sqlTran = conn.BeginTransaction();
                SqlCommand cmd = new SqlCommand();
                cmd.Transaction = sqlTran;
                cmd.Connection = conn;
                cmd.CommandTimeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["TimeOut"]);
                try
                {
                    string asncodes = string.Empty;
                    string sql = string.Empty;
                    foreach (var item in JsonData)
                    {
                        if (string.IsNullOrEmpty(item.ASNCode))
                        {
                            throw new Exception(language.GetNameByCode("WMSAPIInfo009"));//"送货单号不能为空!"
                        }

                        //获取单号
                        sql = @"IF EXISTS(SELECT a.ID FROM ICSDeliveryNotice a WHERE a.ASNCode='{0}' AND DNType = '1' AND a.WorkPoint='{1}')
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo057") + @"',16,1);
                                    RETURN
                                END
                                DECLARE @Status VARCHAR(10)
                                SELECT @Status=Status FROM ICSASN WHERE ASNCode='{0}' and WorkPoint='{1}'

                                IF (@Status IS NULL)
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo058") + @"',16,1);
                                    RETURN
                                END
                                ELSE IF (@Status!='2')
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo059") + @"',16,1);
                                    RETURN
                                END

                                DECLARE @MaxNO INT,@date varchar(20)='DN'+SUBSTRING(CONVERT(varchar(8), GETDATE(), 112), 1, 8)
                                SELECT @MaxNO=SUBSTRING(MAX(DNCode),LEN(@date)+1,LEN(MAX(DNCode))-LEN(@date))+1 FROM ICSDeliveryNotice 
                                    WHERE SUBSTRING(DNCode, 1, LEN(@date))=@date
                                IF @MaxNO IS NULL
                                BEGIN
	                                SELECT @date+'00001' AS Code
                                END
                                ELSE
                                BEGIN
	                                SELECT @date+REPLICATE('0',5-LEN(@MaxNO))+CAST(@MaxNO AS nvarchar(10))  AS Code
                                END ";
                        sql = string.Format(sql, item.ASNCode, item.WorkPoint);
                        string Code = DBHelper.ExecuteScalar(sql, cmd).ToString();
                        //修改送货单到货数量
                        foreach (var itemInfo in item.detail)
                        {
                            sql = @"UPDATE ICSASNDetail SET DNQuantity=ISNULL(DNQuantity, 0)+'{2}'
                                    WHERE LotNo='{0}' AND WorkPoint='{1}'";
                            sql = string.Format(sql, itemInfo.LotNo, item.WorkPoint, itemInfo.Quantity);

                            if (!DBHelper.ExecuteNonQuery(sql, cmd))
                            {
                                throw new Exception(language.GetNameByCode("WMSAPIInfo010")); //"送货单子表信息更新失败!");
                            }

                            sql = @"UPDATE ICSInventoryLot SET Quantity='{2}'
                                    WHERE LotNo='{0}' AND WorkPoint='{1}'";
                            sql = string.Format(sql, itemInfo.LotNo, item.WorkPoint, itemInfo.Quantity);

                            if (!DBHelper.ExecuteNonQuery(sql, cmd))
                            {
                                throw new Exception(language.GetNameByCode("WMSAPIInfo462")); //"条码表信息更新失败!");
                            }
                        }


                        //创建到货单信息
                        sql = @"IF NOT EXISTS(SELECT F_Account FROM Sys_SRM_User WHERE F_Account='{1}' AND F_Location='{2}')
                                BEGIN
	                                RAISERROR('" + string.Format(language.GetNameByCode("WMSAPIInfo060"), "{1}") + @"',16,1);
                                    RETURN
                                END

                                INSERT INTO ICSDeliveryNotice(ID,DNCode,Sequence,VenCode,DepCode,
                                    DNType,InvCode,Quantity,Amount,RCVQuantity,
                                    UnitPrice,Currency,Status,CreatePerson,CreateDateTime,
                                    POID,PODetailID,DNID,DNDetailID,ExtensionID,
                                    MUSER,MUSERName,MTIME,WorkPoint,EATTRIBUTE1,ASNCode)
                                    SELECT NEWID(),'{0}',row_number() OVER (ORDER BY b.InvCode),d.VenCode,d.DepCode,
                                    '1',b.InvCode,SUM(a.DNQuantity),'0','0',
                                    d.UnitPrice,d.Currency,'2',e.F_Account,GETDATE(),
                                    d.POID,d.PODetailID,newid(),newid(),b.ExtensionID,
                                    e.F_Account,e.F_RealName,GETDATE(),a.WorkPoint,'',a.ASNCode
                                FROM ICSASNDetail a
                                INNER JOIN ICSInventoryLot b ON a.LotNo=b.LotNo AND a.WorkPoint=b.WorkPoint
                                INNER JOIN ICSInventoryLotDetail c ON b.LotNo=c.LotNo AND b.WorkPoint=c.WorkPoint
                                INNER JOIN ICSPurchaseOrder d ON c.TransCode=d.POCode AND c.TransSequence=d.Sequence AND c.WorkPoint=d.WorkPoint
                                INNER JOIN Sys_SRM_User e ON e.F_Account='{1}' AND e.F_Location='{2}'
                                WHERE a.ASNCode='{3}' AND a.WorkPoint='{2}'
                                GROUP BY d.POID,d.PODetailID,d.VenCode,d.UnitPrice,d.Currency,d.DepCode,b.ExtensionID,b.InvCode,a.ASNCode,e.F_Account,e.F_RealName,a.WorkPoint";
                        sql = string.Format(sql, Code, item.User, item.WorkPoint, item.ASNCode);

                        if (!DBHelper.ExecuteNonQuery(sql, cmd))
                        {
                            throw new Exception(language.GetNameByCode("WMSAPIInfo011")); //"到货单信息创建失败!");
                        }
                        if (Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["UploadERP"]))
                        {
                            if (!DBHelper.IsU9())
                                ICSPurchaseService.DeliveryNoticeERP(Code, item.WorkPoint, cmd, language);
                        }
                        asncodes += "'" + item.ASNCode + item.WorkPoint + "',";
                    }
                    if (string.IsNullOrWhiteSpace(asncodes))
                    {
                        throw new Exception(language.GetNameByCode("WMSAPIInfo009"));//"请传入送货单信息!");
                    }
                    #region 查询返回数据
                    sql = @"SELECT
	                            n.POCode,
	                            n.Sequence AS POSequence,
	                            a.ASNCode,
	                            a.DNCode,
	                            a.Sequence,
	                            a.VenCode,
	                            a.DepCode,
	                            a.InvCode,
	                            inv.InvName,
	                            inv.InvStd,
	                            a.Quantity,
	                            inv.InvUnit,
	                            a.Amount,
	                            inv.AmountUnit,
	                            a.RCVQuantity,
	                            a.UnitPrice,
	                            a.Currency,
	                            a.POID,
	                            a.PODetailID,
	                            a.DNID,
	                            a.DNDetailID,
	                            ext.ProjectCode,
	                            ext.BatchCode,
	                            ext.Version,
	                            ext.Brand,
	                            ext.cFree1,
	                            ext.cFree2,
	                            ext.cFree3,
	                            ext.cFree4,
	                            ext.cFree5,
	                            ext.cFree6,
	                            ext.cFree7,
	                            ext.cFree8,
	                            ext.cFree9,
	                            ext.cFree10,
	                            a.MUSER AS [User],
	                            a.MTIME AS [MTime]
                            FROM ICSDeliveryNotice a
                            INNER JOIN ICSPurchaseOrder n ON a.POID =n.POID AND a.PODetailID=n.PODetailID AND a.WorkPoint=n.WorkPoint
                            INNER JOIN ICSExtension ext ON a.ExtensionID=ext.ID AND a.WorkPoint=ext.WorkPoint
                            INNER JOIN ICSInventory inv ON a.InvCode=inv.InvCode AND a.WorkPoint=inv.WorkPoint
                            WHERE a.ASNCode+a.WorkPoint IN ({0})";
                    sql = string.Format(sql, asncodes.Substring(0, asncodes.Length - 1));
                    DataTable data = DBHelper.SQlReturnData(sql, cmd);
                    #endregion
                    cmd.Transaction.Commit();
                    return data;
                }
                catch (Exception ex)
                {
                    if (cmd.Transaction != null)
                        cmd.Transaction.Rollback();
                    log.Error(ex.Message);
                    throw new Exception(ex.Message);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                    }
                    conn.Dispose();
                }
            }
        }

        /// <summary>
        /// 采购拒收
        /// </summary>
        /// <param name="JsonData"></param>
        /// <returns></returns>
        public static DataTable PurchaseRejectDocCreate(List<ICSDeliveryNotice> JsonData)
        {
            var language = LanguageHelper.GetName("WMSAPIInfo");
            if (JsonData.Count <= 0)
            {
                throw new Exception(language.GetNameByCode("WMSAPIInfo007"));//"传送数据为空!"
            }
            using (SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString))
            {
                conn.Open();
                SqlTransaction sqlTran = conn.BeginTransaction();
                SqlCommand cmd = new SqlCommand();
                cmd.Transaction = sqlTran;
                cmd.Connection = conn;
                cmd.CommandTimeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["TimeOut"]);
                try
                {
                    string lots = string.Empty;
                    string sql = string.Empty;
                    foreach (var item in JsonData)
                    {
                        if (string.IsNullOrEmpty(item.DNCode))
                        {
                            throw new Exception(language.GetNameByCode("WMSAPIInfo012"));//"到货单号不能为空!");
                        }

                        //获取单号
                        sql = @"DECLARE @Status VARCHAR(10)
                                SELECT @Status=Status FROM ICSDeliveryNotice WHERE DNCode='{0}' and DNType='1'  and WorkPoint='{1}'

                                IF (@Status IS NULL)
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo061") + @"',16,1);
                                    RETURN
                                END
                                ELSE IF (@Status!='2')
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo062") + @"',16,1);
                                    RETURN
                                END

                                DECLARE @MaxNO INT,@date varchar(20)='RJT'+SUBSTRING(CONVERT(varchar(8), GETDATE(), 112), 1, 8)
                                SELECT @MaxNO=SUBSTRING(MAX(DNCode),LEN(@date)+1,LEN(MAX(DNCode))-LEN(@date))+1 FROM ICSDeliveryNotice 
                                    WHERE SUBSTRING(DNCode, 1, LEN(@date))=@date
                                IF @MaxNO IS NULL
                                BEGIN
	                                SELECT @date+'00001' AS Code
                                END
                                ELSE
                                BEGIN
	                                SELECT @date+REPLICATE('0',5-LEN(@MaxNO))+CAST(@MaxNO AS nvarchar(10))  AS Code
                                END ";
                        sql = string.Format(sql, item.DNCode, item.WorkPoint);
                        string Code = DBHelper.ExecuteScalar(sql, cmd).ToString();
                        //修改送货单到货数量
                        foreach (var itemInfo in item.detail)
                        {
                            sql = @"IF NOT EXISTS(SELECT F_Account FROM Sys_SRM_User WHERE F_Account='{3}' AND F_Location='{2}')
                                    BEGIN
	                                    RAISERROR('" + string.Format(language.GetNameByCode("WMSAPIInfo060"), "{3}") + @"',16,1);
                                        RETURN
                                    END

                                    IF EXISTS(SELECT a.ID FROM ICSDeliveryNotice a WHERE a.EATTRIBUTE1='{1}' AND DNType = '3' AND a.WorkPoint='{2}')
                                    BEGIN
	                                    RAISERROR('" + language.GetNameByCode("WMSAPIInfo063") + @"',16,1);
                                        RETURN
                                    END
                                    INSERT INTO ICSDeliveryNotice(ID,DNCode,Sequence,VenCode,DepCode,
                                    DNType,InvCode,Quantity,Amount,RCVQuantity,
                                    UnitPrice,Currency,Status,CreatePerson,CreateDateTime,
                                    POID,PODetailID,DNID,DNDetailID,ExtensionID,
                                    MUSER,MUSERName,MTIME,WorkPoint,EATTRIBUTE1,ASNCode)
                                    SELECT NEWID(),'{4}',  '{11}', '{5}',  '{6}',
                                    '3',d.InvCode,'{7}', '{8}', 0, 
                                    '{9}', '{10}', '2', e.F_Account, SYSDATETIME(), 
                                    a.DNID,a.DNDetailID, '0', '0', a.ExtensionID,
                                    e.F_Account,e.F_RealName, SYSDATETIME(), a.WorkPoint, d.LOTNO,''
                                    FROM ICSDeliveryNotice a
                                    INNER JOIN ICSASNDetail b ON a.ASNCode=b.ASNCode  AND a.WorkPoint=b.WorkPoint
									INNER JOIN ICSInventoryLot d ON b.LotNo=d.LotNo AND a.InvCode=d.InvCode AND b.WorkPoint=d.WorkPoint
                                    INNER JOIN ICSInventoryLotDetail m on d.LotNo=m.LotNo and d.WorkPoint=m.WorkPoint
                                    INNER JOIN ICSPurchaseOrder n ON m.TransCode =n.POCode AND m.TransSequence=n.Sequence AND a.PODetailID=n.PODetailID AND m.WorkPoint=n.WorkPoint
		                            INNER JOIN ICSInspection h ON h.LotNo=d.LotNo  AND h.WorkPoint=a.WorkPoint
                                    INNER JOIN Sys_SRM_User e ON e.F_Account='{3}' AND e.F_Location='{2}'
                                    WHERE a.DNCode='{0}' and d.LOTNO='{1}' AND a.WorkPoint='{2}'";
                            sql = string.Format(sql, item.DNCode, itemInfo.LotNo, item.WorkPoint, item.User, Code, item.VenCode, item.DepCode, itemInfo.Quantity, itemInfo.Amount, itemInfo.UnitPrice, itemInfo.Currency, itemInfo.Sequence);

                            if (!DBHelper.ExecuteNonQuery(sql, cmd))
                            {
                                throw new Exception(language.GetNameByCode("WMSAPIInfo013"));//"拒收单创建失败!");
                            }
                            lots += "'" + itemInfo.LotNo + item.WorkPoint + "',";
                        }
                        //增加了webconfig 判断不是U9,调用U8接口
                        if (Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["UploadERP"])&& !DBHelper.IsU9())
                            ICSPurchaseService.PurchaseRejectDocInNewERP(item.DNCode, Code, item.WorkPoint, cmd, language);
                    }
                    if (string.IsNullOrWhiteSpace(lots))
                    {
                        throw new Exception(language.GetNameByCode("WMSAPIInfo005"));//"请传入条码信息!");
                    }
                    #region 查询返回数据
                    sql = @"SELECT
	                            n.DNCode,
	                            n.Sequence,
	                            a.DNCode AS RJTCode,
	                            a.Sequence AS RJTSequence,
	                            a.VenCode,
	                            a.DepCode,
	                            a.InvCode,
	                            inv.InvName,
	                            inv.InvStd,
	                            a.Quantity,
	                            inv.InvUnit,
	                            a.Amount,
	                            inv.AmountUnit,
	                            a.RCVQuantity,
	                            a.UnitPrice,
	                            a.Currency,
	                            a.POID,
	                            a.PODetailID,
	                            a.DNID,
	                            a.DNDetailID,
	                            ext.ProjectCode,
	                            ext.BatchCode,
	                            ext.Version,
	                            ext.Brand,
	                            ext.cFree1,
	                            ext.cFree2,
	                            ext.cFree3,
	                            ext.cFree4,
	                            ext.cFree5,
	                            ext.cFree6,
	                            ext.cFree7,
	                            ext.cFree8,
	                            ext.cFree9,
	                            ext.cFree10,
	                            a.MUSER AS [User],
	                            a.MTIME AS [MTime]
                            FROM ICSDeliveryNotice a
                            INNER JOIN ICSDeliveryNotice n ON a.POID =n.DNID AND a.PODetailID=n.DNDetailID AND a.WorkPoint=n.WorkPoint
                            INNER JOIN ICSExtension ext ON a.ExtensionID=ext.ID AND a.WorkPoint=ext.WorkPoint
                            INNER JOIN ICSInventory inv ON a.InvCode=inv.InvCode AND a.WorkPoint=inv.WorkPoint
                            WHERE a.EATTRIBUTE1+a.WorkPoint IN ({0})";
                    sql = string.Format(sql, lots.Substring(0, lots.Length - 1));
                    DataTable data = DBHelper.SQlReturnData(sql, cmd);
                    #endregion
                    cmd.Transaction.Commit();
                    return data;
                }
                catch (Exception ex)
                {
                    if (cmd.Transaction != null)
                        cmd.Transaction.Rollback();
                    log.Error(ex.Message);
                    throw new Exception(ex.Message);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                    }
                    conn.Dispose();
                }
            }
        }


        /// <summary>
        /// 无订单采购拒收
        /// </summary>
        /// <param name="JsonData"></param>
        /// <returns></returns>
        public static DataTable PurchaseRejectDocNoTransCreate(List<ICSDeliveryNotice> JsonData)
        {
            var language = LanguageHelper.GetName("WMSAPIInfo");
            if (JsonData.Count <= 0)
            {
                throw new Exception(language.GetNameByCode("WMSAPIInfo007"));//"传送数据为空!"
            }
            using (SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString))
            {
                conn.Open();
                SqlTransaction sqlTran = conn.BeginTransaction();
                SqlCommand cmd = new SqlCommand();
                cmd.Transaction = sqlTran;
                cmd.Connection = conn;
                cmd.CommandTimeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["TimeOut"]);
                try
                {
                    string lots = string.Empty;
                    string sql = string.Empty;
                    foreach (var item in JsonData)
                    {
                        if (string.IsNullOrEmpty(item.DNCode))
                        {
                            throw new Exception(language.GetNameByCode("WMSAPIInfo012"));//"到货单号不能为空!");
                        }

                        //获取单号
                        sql = @"DECLARE @Status VARCHAR(10)
                                SELECT @Status=Status FROM ICSDeliveryNotice WHERE DNCode='{0}' and DNType='1'  and WorkPoint='{1}'

                                IF (@Status IS NULL)
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo061") + @"',16,1);
                                    RETURN
                                END
                                ELSE IF (@Status!='2')
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo062") + @"',16,1);
                                    RETURN
                                END

                                DECLARE @MaxNO INT,@date varchar(20)='RJT'+SUBSTRING(CONVERT(varchar(8), GETDATE(), 112), 1, 8)
                                SELECT @MaxNO=SUBSTRING(MAX(DNCode),LEN(@date)+1,LEN(MAX(DNCode))-LEN(@date))+1 FROM ICSDeliveryNotice 
                                    WHERE SUBSTRING(DNCode, 1, LEN(@date))=@date
                                IF @MaxNO IS NULL
                                BEGIN
	                                SELECT @date+'00001' AS Code
                                END
                                ELSE
                                BEGIN
	                                SELECT @date+REPLICATE('0',5-LEN(@MaxNO))+CAST(@MaxNO AS nvarchar(10))  AS Code
                                END ";
                        sql = string.Format(sql, item.DNCode, item.WorkPoint);
                        string Code = DBHelper.ExecuteScalar(sql, cmd).ToString();
                        //修改送货单到货数量
                        foreach (var itemInfo in item.detail)
                        {
                            sql = @"IF NOT EXISTS(SELECT F_Account FROM Sys_SRM_User WHERE F_Account='{3}' AND F_Location='{2}')
                                    BEGIN
	                                    RAISERROR('" + string.Format(language.GetNameByCode("WMSAPIInfo060"), "{3}") + @"',16,1);
                                        RETURN
                                    END

                                    IF EXISTS(SELECT a.ID FROM ICSDeliveryNotice a WHERE a.EATTRIBUTE1='{1}' AND DNType = '3' AND a.WorkPoint='{2}')
                                    BEGIN
	                                    RAISERROR('" + language.GetNameByCode("WMSAPIInfo063") + @"',16,1);
                                        RETURN
                                    END
                                    INSERT INTO ICSDeliveryNotice(ID,DNCode,Sequence,VenCode,DepCode,
                                    DNType,InvCode,Quantity,Amount,RCVQuantity,
                                    UnitPrice,Currency,Status,CreatePerson,CreateDateTime,
                                    POID,PODetailID,DNID,DNDetailID,ExtensionID,
                                    MUSER,MUSERName,MTIME,WorkPoint,EATTRIBUTE1,ASNCode)
                                    SELECT NEWID(),'{4}',  '{11}', '{5}',  '{6}',
                                    '3',d.InvCode,'{7}', '{8}', 0, 
                                    '{9}', '{10}', '2', e.F_Account, SYSDATETIME(), 
                                    a.DNID,a.DNDetailID, '0', '0', a.ExtensionID,
                                    e.F_Account,e.F_RealName, SYSDATETIME(), a.WorkPoint, d.LOTNO,''
                                    FROM ICSDeliveryNotice a
                                    --INNER JOIN ICSASNDetail b ON a.ASNCode=b.ASNCode  AND a.WorkPoint=b.WorkPoint
                                    INNER JOIN ICSInventoryLotDetail m on  a.DNCode=m.TransCode and a.Sequence=m.TransSequence and a.WorkPoint=m.WorkPoint
                                    INNER JOIN ICSInventoryLot d ON m.LotNo=d.LotNo AND a.InvCode=d.InvCode AND a.WorkPoint=d.WorkPoint
                                    --INNER JOIN ICSPurchaseOrder n ON a.PODetailID=n.PODetailID AND m.WorkPoint=n.WorkPoint
		                            INNER JOIN ICSInspection h ON h.LotNo=d.LotNo  AND h.WorkPoint=a.WorkPoint
                                    INNER JOIN Sys_SRM_User e ON e.F_Account='{3}' AND e.F_Location='{2}'
                                    WHERE a.DNCode='{0}' and d.LOTNO='{1}' AND a.WorkPoint='{2}'";
                            sql = string.Format(sql, item.DNCode, itemInfo.LotNo, item.WorkPoint, item.User, Code, item.VenCode, item.DepCode, itemInfo.Quantity, itemInfo.Amount, itemInfo.UnitPrice, itemInfo.Currency, itemInfo.Sequence);

                            if (!DBHelper.ExecuteNonQuery(sql, cmd))
                            {
                                throw new Exception(language.GetNameByCode("WMSAPIInfo013"));//"拒收单创建失败!");
                            }
                            lots += "'" + itemInfo.LotNo + item.WorkPoint + "',";
                        }
                        if (Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["UploadERP"]))
                            ICSPurchaseService.PurchaseRejectDocInNewERP(item.DNCode, Code, item.WorkPoint, cmd, language);
                    }
                    if (string.IsNullOrWhiteSpace(lots))
                    {
                        throw new Exception(language.GetNameByCode("WMSAPIInfo005"));//"请传入条码信息!");
                    }
                    #region 查询返回数据
                    sql = @"SELECT
	                            n.DNCode,
	                            n.Sequence,
	                            a.DNCode AS RJTCode,
	                            a.Sequence AS RJTSequence,
	                            a.VenCode,
	                            a.DepCode,
	                            a.InvCode,
	                            inv.InvName,
	                            inv.InvStd,
	                            a.Quantity,
	                            inv.InvUnit,
	                            a.Amount,
	                            inv.AmountUnit,
	                            a.RCVQuantity,
	                            a.UnitPrice,
	                            a.Currency,
	                            a.POID,
	                            a.PODetailID,
	                            a.DNID,
	                            a.DNDetailID,
	                            ext.ProjectCode,
	                            ext.BatchCode,
	                            ext.Version,
	                            ext.Brand,
	                            ext.cFree1,
	                            ext.cFree2,
	                            ext.cFree3,
	                            ext.cFree4,
	                            ext.cFree5,
	                            ext.cFree6,
	                            ext.cFree7,
	                            ext.cFree8,
	                            ext.cFree9,
	                            ext.cFree10,
	                            a.MUSER AS [User],
	                            a.MTIME AS [MTime]
                            FROM ICSDeliveryNotice a
                            INNER JOIN ICSDeliveryNotice n ON a.POID =n.DNID AND a.PODetailID=n.DNDetailID AND a.WorkPoint=n.WorkPoint
                            INNER JOIN ICSExtension ext ON a.ExtensionID=ext.ID AND a.WorkPoint=ext.WorkPoint
                            INNER JOIN ICSInventory inv ON a.InvCode=inv.InvCode AND a.WorkPoint=inv.WorkPoint
                            WHERE a.EATTRIBUTE1+a.WorkPoint IN ({0})";
                    sql = string.Format(sql, lots.Substring(0, lots.Length - 1));
                    DataTable data = DBHelper.SQlReturnData(sql, cmd);
                    #endregion
                    cmd.Transaction.Commit();
                    return data;
                }
                catch (Exception ex)
                {
                    if (cmd.Transaction != null)
                        cmd.Transaction.Rollback();
                    log.Error(ex.Message);
                    throw new Exception(ex.Message);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                    }
                    conn.Dispose();
                }
            }
        }


        /// <summary>
        /// 采购订单
        /// </summary>
        /// <param name="JsonData"></param>
        /// <returns></returns>
        public static DataTable PurOrderCreate(List<ICSPurchaseOrder> JsonData)
        {
            var language = LanguageHelper.GetName("WMSAPIInfo");
            if (JsonData.Count <= 0)
            {
                throw new Exception(language.GetNameByCode("WMSAPIInfo007"));//"传送数据为空!"
            }
            using (SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString))
            {
                conn.Open();
                SqlTransaction sqlTran = conn.BeginTransaction();
                SqlCommand cmd = new SqlCommand();
                cmd.Transaction = sqlTran;
                cmd.Connection = conn;
                cmd.CommandTimeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["TimeOut"]);
                try
                {
                    string codes = string.Empty;
                    string sql = string.Empty;
                    string Colspan = string.Empty;
                    string IDD = string.Empty;
                    //获取单号
                    sql = @"DECLARE @MaxNO INT,@date varchar(20)='POIA'+SUBSTRING(CONVERT(varchar(8), GETDATE(), 112), 1, 8)
                                SELECT @MaxNO=SUBSTRING(MAX(POCode),LEN(@date)+1,LEN(MAX(POCode))-LEN(@date))+1 FROM ICSPurchaseOrder 
                                    WHERE SUBSTRING(POCode, 1, LEN(@date))=@date
                                IF @MaxNO IS NULL
                                BEGIN
	                                SELECT @date+'00001' AS Code
                                END
                                ELSE
                                BEGIN
	                                SELECT @date+REPLICATE('0',5-LEN(@MaxNO))+CAST(@MaxNO AS nvarchar(10))  AS Code
                                END ";
                    string Code = DBHelper.ExecuteScalar(sql, cmd).ToString();

                    HashSet<string> uniqueItems = new HashSet<string>();
                    foreach (var item in JsonData)
                    {

                       

                        //检验自由项
                        Colspan = item.ProjectCode + "~" + item.BatchCode + "~" + item.Version
                                + "~" + item.Brand + "~" + item.cFree1
                                + "~" + item.cFree2 + "~" + item.cFree3 + "~" + item.cFree4
                                + "~" + item.cFree5 + "~" + item.cFree6 + "~" + item.cFree7
                                + "~" + item.cFree8 + "~" + item.cFree9 + "~" + item.cFree10;
                        sql = @"select ID,Colspan from ICSExtension a
                                   where Colspan='{0}' and WorkPoint='{1}'";
                        sql = string.Format(sql, Colspan, item.WorkPoint);
                        DataTable dttt = DBHelper.SQlReturnData(sql, cmd);
                        if (dttt.Rows.Count == 0)
                        {
                            IDD = Guid.NewGuid().ToString();
                            sql = @"Insert into ICSExtension(ID, Colspan, ProjectCode, BatchCode, Version, Brand, cFree1, cFree2, cFree3, cFree4, cFree5, cFree6, cFree7, cFree8, cFree9, cFree10, MTIME, MUSER, MUSERName, WorkPoint) 
                            select '{17}','{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}','{14}',GETDATE(),'{15}',f.F_RealName,'{16}'from Sys_SRM_User f where f.F_Account='{15}' and f.F_Location='{16}'";
                            sql = string.Format(sql, Colspan, item.ProjectCode, item.BatchCode, item.Version, item.Brand, item.cFree1, item.cFree2, item.cFree3, item.cFree4, item.cFree5, item.cFree6, item.cFree7, item.cFree8, item.cFree9, item.cFree10, item.User, item.WorkPoint, IDD);
                            if (!DBHelper.ExecuteNonQuery(sql, cmd))
                            {
                                throw new Exception(language.GetNameByCode("WMSAPIInfo366"));
                            }
                        }
                        else
                        {
                            IDD = dttt.Rows[0]["ID"].ToString();
                        }

                        string key = item.Sequence + "~" + item.InvCode;

                        if (uniqueItems.Contains(key))
                        {
                            throw new Exception("子件不可重复添加!");
                        }

                        uniqueItems.Add(key);

                        //创建主表
                        sql = @"IF NOT EXISTS(SELECT F_Account FROM Sys_SRM_User WHERE F_Account='{6}' AND F_Location='{4}')
                                BEGIN
	                                RAISERROR('" + string.Format(language.GetNameByCode("WMSAPIInfo060"), "{6}") + @"',16,1);
                                    RETURN
                                END

                                INSERT INTO ICSPurchaseOrder(ID,POCode ,Sequence,VenCode,DepCode
                                        ,PersonCode,POType,InvCode,Quantity,Amount
                                        ,InQuantity,UnitPrice,Currency ,Status ,CreatePerson
                                        ,CreateDateTime	,ReleaseState ,ReleaseDate,PlanArriveDate,ArriveUser,ArriveDate	
                                        ,DeliveryUser	,DeliveryDate,PRID	 ,PRDetailID ,POID	
                                        ,PODetailID	 ,ExtensionID ,MUSER,MUSERName,MTIME	
                                        ,WorkPoint	,EATTRIBUTE1,EATTRIBUTE2,EATTRIBUTE3,EATTRIBUTE4,EATTRIBUTE5,EATTRIBUTE6,EATTRIBUTE7,EATTRIBUTE8,EATTRIBUTE9,EATTRIBUTE10)
                             VALUES (NEWID(),'{0}','{1}','{2}','{3}',
                                    '','1','{5}','{8}',0,
                                    0,0,'','1','',
                                    '{7}','0','','','','',
                                    '','','0','0','',
                                    '','{9}','{6}',(select F_RealName from Sys_SRM_User where F_Account='{6}' and F_Location='{4}'),'{7}',
                                    '{4}','','','','','','','','','','')";
                        sql = string.Format(sql, Code,  item.Sequence, item.VenCode, item.DepCode,item.WorkPoint, item.InvCode, item.User,
                            item.MTime, item.Quantity, IDD);

                        if (!DBHelper.ExecuteNonQuery(sql, cmd))
                        {
                            throw new Exception(language.GetNameByCode("WMSAPIInfo0206"));//"采购订单信息创建失败!!");
                        }
                        codes += "'" + Code + item.WorkPoint + "',";
                    }
                    if (string.IsNullOrWhiteSpace(codes))
                    {
                        throw new Exception(language.GetNameByCode("WMSAPIInfo001"));//"单据号不能为空!"
                    }
                    #region 查询返回数据
                    sql = @"SELECT a.POCode,a.Sequence,
                                a.VenCode,a.DepCode,a.PersonCode,
	                            d.Name AS Status,
	                            a.Sequence,
	                            a.InvCode,
	                            inv.InvName,
	                            inv.InvStd,
	                            a.Quantity,
	                            inv.InvUnit,
	                            a.Amount,
	                            inv.AmountUnit,
	                            a.InQuantity,
	                            ext.ProjectCode,
	                            ext.BatchCode,
	                            ext.Version,
	                            ext.Brand,
	                            ext.cFree1,
	                            ext.cFree2,
	                            ext.cFree3,
	                            ext.cFree4,
	                            ext.cFree5,
	                            ext.cFree6,
	                            ext.cFree7,
	                            ext.cFree8,
	                            ext.cFree9,
	                            ext.cFree10,
	                            a.MUSER AS [User],
	                            a.MTIME AS [MTime]
                            FROM ICSPurchaseOrder a 
                            LEFT JOIN ICSType d ON d.TableCode='ICSPurchaseOrder' AND d.ColumnCode='Status' AND a.Status=d.Code AND a.WorkPoint=d.WorkPoint
                            INNER JOIN ICSExtension ext ON a.ExtensionID=ext.ID AND a.WorkPoint=ext.WorkPoint
                            INNER JOIN ICSInventory inv ON a.InvCode=inv.InvCode AND a.WorkPoint=inv.WorkPoint
                            WHERE a.POCode+a.WorkPoint IN ({0})";
                    sql = string.Format(sql, codes.Substring(0, codes.Length - 1));
                    DataTable data = DBHelper.SQlReturnData(sql, cmd);
                    #endregion
                    cmd.Transaction.Commit();
                    return data;
                }
                catch (Exception ex)
                {
                    if (cmd.Transaction != null)
                        cmd.Transaction.Rollback();
                    log.Error(ex.Message);
                    throw new Exception(ex.Message);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                    }
                    conn.Dispose();
                }
            }
        }

        /// <summary>
        /// 采购订单 修改
        /// </summary>
        /// <param name="JsonData"></param>
        /// <returns></returns>
        public static DataTable ICSPurOrderUpdate(List<ICSPurchaseOrder> JsonData)
        {
            var language = LanguageHelper.GetName("WMSAPIInfo");
            if (JsonData.Count <= 0)
            {
                throw new Exception(language.GetNameByCode("WMSAPIInfo007"));//"传送数据为空!"
            }
            using (SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString))
            {
                conn.Open();
                SqlTransaction sqlTran = conn.BeginTransaction();
                SqlCommand cmd = new SqlCommand();
                cmd.Transaction = sqlTran;
                cmd.Connection = conn;
                cmd.CommandTimeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["TimeOut"]);
                try
                {
                    string sql = string.Empty;
                    string Checksql = string.Empty;
                    string Code = string.Empty;
                    string ids = string.Empty;
                    string Colspan = string.Empty;
                    string IDD = string.Empty;
                    foreach (var item in JsonData)
                    {

                        //检验自由项
                        Colspan = item.ProjectCode + "~" + item.BatchCode + "~" + item.Version
                                + "~" + item.Brand + "~" + item.cFree1
                                + "~" + item.cFree2 + "~" + item.cFree3 + "~" + item.cFree4
                                + "~" + item.cFree5 + "~" + item.cFree6 + "~" + item.cFree7
                                + "~" + item.cFree8 + "~" + item.cFree9 + "~" + item.cFree10;
                        Checksql = @"select ID,Colspan from ICSExtension a
                                   where Colspan='{0}' and WorkPoint='{1}'";
                        Checksql = string.Format(Checksql, Colspan, item.WorkPoint);
                        DataTable dttt = DBHelper.SQlReturnData(Checksql, cmd);
                        if (dttt.Rows.Count == 0)
                        {
                            IDD = Guid.NewGuid().ToString();
                            Checksql = @"Insert into ICSExtension(ID, Colspan, ProjectCode, BatchCode, Version, Brand, cFree1, cFree2, cFree3, cFree4, cFree5, cFree6, cFree7, cFree8, cFree9, cFree10, MTIME, MUSER, MUSERName, WorkPoint) 
                            select '{17}','{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}','{14}',GETDATE(),'{15}',f.F_RealName,'{16}'from Sys_SRM_User f where f.F_Account='{15}' and f.F_Location='{16}'";
                            Checksql = string.Format(Checksql, Colspan, item.ProjectCode, item.BatchCode, item.Version, item.Brand, item.cFree1, item.cFree2, item.cFree3, item.cFree4, item.cFree5, item.cFree6, item.cFree7, item.cFree8, item.cFree9, item.cFree10, item.User, item.WorkPoint, IDD);
                            if (!DBHelper.ExecuteNonQuery(Checksql, cmd))
                            {
                                throw new Exception(language.GetNameByCode("WMSAPIInfo366"));
                            }
                        }
                        else
                        {
                            IDD = dttt.Rows[0]["ID"].ToString();
                        }

                        //主表修改
                        sql = @"IF NOT EXISTS(SELECT F_Account FROM Sys_SRM_User WHERE F_Account='{4}' AND F_Location='{6}')
                                BEGIN
	                                RAISERROR('" + string.Format(language.GetNameByCode("WMSAPIInfo060"), "{4}") + @"',16,1);
                                    RETURN
                                END

                                DECLARE @Status VARCHAR(10)
                                SELECT distinct @Status=Status FROM ICSPurchaseOrder WHERE PoCode='{0}' and WorkPoint='{6}'

                                IF (@Status IS NULL)
                                BEGIN
	                                RAISERROR('" + string.Format(language.GetNameByCode("WMSAPIInfo0205"), "{0}") + @"',16,1);
                                    RETURN
                                END
                                ELSE IF (@Status!='1')
                                BEGIN
	                                RAISERROR('" + string.Format(language.GetNameByCode("WMSAPIInfo0202"), "{0}") + @"',16,1);
                                    RETURN
                                END
";
                        sql = string.Format(sql, item.PoCode, item.Sequence, item.InvCode, item.Quantity, item.User,
                            item.MTime, item.WorkPoint);


                        


                        if (!string.IsNullOrWhiteSpace(item.Sequence))
                        {
                            //创建子表
                            sql += @"IF EXISTS(Select *  from  ICSPurchaseOrder where PoCode ='{0}'and Sequence ='{1}')
Begin
											UPDATE ICSPurchaseOrder set InvCode='{5}',Quantity='{8}',MUSER= '{6}',VenCode = '{2}',DepCode = '{3}',MUSERName=(select F_RealName from Sys_SRM_User where F_Account='{6}' and F_Location='{4}'),MTIME='{7}'
											where PoCode ='{0}'and Sequence ='{1}'
END
										ELSE
BEGIN
											INSERT INTO ICSPurchaseOrder
												  (ID,POCode ,Sequence,VenCode,DepCode
                                        ,PersonCode,POType,InvCode,Quantity,Amount
                                        ,InQuantity,UnitPrice,Currency ,Status ,CreatePerson
                                        ,CreateDateTime	,ReleaseState ,ReleaseDate,PlanArriveDate,ArriveUser,ArriveDate	
                                        ,DeliveryUser	,DeliveryDate,PRID	 ,PRDetailID ,POID	
                                        ,PODetailID	 ,ExtensionID ,MUSER,MUSERName,MTIME	
                                        ,WorkPoint	,EATTRIBUTE1,EATTRIBUTE2,EATTRIBUTE3,EATTRIBUTE4,EATTRIBUTE5,EATTRIBUTE6,EATTRIBUTE7,EATTRIBUTE8,EATTRIBUTE9,EATTRIBUTE10)
												  VALUES (NEWID(),'{0}','{1}','{2}','{3}',
                                    '','1','{5}','{8}',0,
                                    0,0,'','1','',
                                    '','0','','','','',
                                    '','','0','0','',
                                    '','',(select F_RealName from Sys_SRM_User where F_Account='{6}' and F_Location='{4}'),'{6}','{7}',
                                    '{4}','','','','','','','','','','')
END";
                            sql = string.Format(sql, item.PoCode, item.Sequence, item.VenCode, item.DepCode, item.WorkPoint, item.InvCode, item.User,
                            item.MTime, item.Quantity, IDD);
                        }

                        if (!DBHelper.ExecuteNonQuery(sql, cmd))
                        {
                            throw new Exception(language.GetNameByCode("WMSAPIInfo0204"));//"采购订单信息修改失败!");
                        }
                        ids += "'" + item.Sequence + "',";
                        Code = item.PoCode;
                    }
                    sql = @"DELETE from ICSPurchaseOrder  where PoCode ='{0}' and Sequence not in ({1})";
                    sql = string.Format(sql, Code, ids.Substring(0, ids.Length - 1));
                    DBHelper.ExecuteNonQuery(sql, cmd);

                    #region 查询返回数据
                    sql = @"SELECT a.POCode,a.Sequence,
                                a.VenCode,a.DepCode,a.PersonCode,
	                            d.Name AS Status,
	                            a.Sequence,
	                            a.InvCode,
	                            inv.InvName,
	                            inv.InvStd,
	                            a.Quantity,
	                            inv.InvUnit,
	                            a.Amount,
	                            inv.AmountUnit,
	                            a.InQuantity,
	                            ext.ProjectCode,
	                            ext.BatchCode,
	                            ext.Version,
	                            ext.Brand,
	                            ext.cFree1,
	                            ext.cFree2,
	                            ext.cFree3,
	                            ext.cFree4,
	                            ext.cFree5,
	                            ext.cFree6,
	                            ext.cFree7,
	                            ext.cFree8,
	                            ext.cFree9,
	                            ext.cFree10,
	                            a.MUSER AS [User],
	                            a.MTIME AS [MTime]
                            FROM ICSPurchaseOrder a 
                            LEFT JOIN ICSType d ON d.TableCode='ICSPurchaseOrder' AND d.ColumnCode='Status' AND a.Status=d.Code AND a.WorkPoint=d.WorkPoint
                            INNER JOIN ICSExtension ext ON a.ExtensionID=ext.ID AND a.WorkPoint=ext.WorkPoint
                            INNER JOIN ICSInventory inv ON a.InvCode=inv.InvCode AND a.WorkPoint=inv.WorkPoint
                            WHERE a.POCode+a.WorkPoint IN ('{0}')";
                    sql = string.Format(sql, Code, ids.Substring(0, ids.Length - 1));
                    DataTable data = DBHelper.SQlReturnData(sql, cmd);
                    #endregion
                    cmd.Transaction.Commit();
                    return data;
                }
                catch (Exception ex)
                {
                    if (cmd.Transaction != null)
                        cmd.Transaction.Rollback();
                    log.Error(ex.Message);
                    throw new Exception(ex.Message);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                    }
                    conn.Dispose();
                }
            }
        }

        /// <summary>
        /// 采购订单审核
        /// </summary>
        /// <param name="JsonData"></param>
        /// <returns></returns>
        public static DataTable PurOrderApprove(List<ICSUser> JsonData)
        {
            string flag = string.Empty;
            var language = LanguageHelper.GetName("WMSAPIInfo");
            if (JsonData.Count <= 0)
            {
                throw new Exception(language.GetNameByCode("WMSAPIInfo007"));//"传送数据为空!"
            }
            using (SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString))
            {
                conn.Open();
                SqlTransaction sqlTran = conn.BeginTransaction();
                SqlCommand cmd = new SqlCommand();
                cmd.Transaction = sqlTran;
                cmd.Connection = conn;
                cmd.CommandTimeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["TimeOut"]);
                try
                {
                    string sql = string.Empty;
                    string ids = string.Empty;
                    foreach (var item in JsonData)
                    {
                        bool hasApproveFlag = JsonData.Any(u => u.ApproveFlag != null);
                        if (hasApproveFlag == true)
                        {
                            flag = item.ApproveFlag;
                        }
                        if (string.IsNullOrEmpty(item.ID))
                        {
                            throw new Exception(language.GetNameByCode("WMSAPIInfo018"));//"单据ID不能为空!");
                        }
                        if (string.IsNullOrEmpty(item.User))
                        {
                            throw new Exception(language.GetNameByCode("WMSAPIInfo019"));//"操作人不能为空!");
                        }
                        if (item.MTime <= new DateTime(2000, 1, 1))
                        {
                            throw new Exception(language.GetNameByCode("WMSAPIInfo020"));//"操作时间不能为空!");
                        }
                        if (flag.Equals("1")|| flag=="")
                        {
                            //获取单号
                            sql = @"DECLARE @Status VARCHAR(10)
                                SELECT @Status=Status FROM ICSPurchaseOrder WHERE PoCode='{0}'

                                IF (@Status IS NULL)
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo065") + @"',16,1);
                                    RETURN
                                END
                                ELSE IF (@Status!='1')
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo0202") + @"',16,1);
                                    RETURN
                                END
                             update ICSPurchaseOrder set Status='2',MUSER='{1}',MTIME='{2}' where PoCode='{0}'";
                            sql = string.Format(sql, item.ID, item.User, item.MTime);
                            if (!DBHelper.ExecuteNonQuery(sql, cmd))
                            {
                                throw new Exception(language.GetNameByCode("WMSAPIInfo0203"));//"采购订单审核失败!");
                            }
                            ids += "'" + item.ID + "',";
                        }
                        else
                        {
                            //获取单号
                            sql = @"DECLARE @Status VARCHAR(10)
                                SELECT @Status=Status FROM ICSPurchaseOrder WHERE PoCode='{0}'

                                IF (@Status IS NULL)
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo065") + @"',16,1);
                                    RETURN
                                END
                                ELSE IF (@Status!='2')
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo473") + @"',16,1);
                                    RETURN
                                END
                                IF EXISTS (select id from ICSPurchaseOrder where PoCode='{0}' and InQuantity>0)
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo474") + @"',16,1);
                                    RETURN
                                END
                             update ICSPurchaseOrder set Status='1',MUSER='{1}',MTIME='{2}' where PoCode='{0}'";
                            sql = string.Format(sql, item.ID, item.User, item.MTime);
                            if (!DBHelper.ExecuteNonQuery(sql, cmd))
                            {
                                throw new Exception(language.GetNameByCode("WMSAPIInfo475"));//"采购订单弃审失败!");
                            }
                            ids += "'" + item.ID + "',";
                        }
                        
                    }
                    if (string.IsNullOrWhiteSpace(ids))
                    {
                        throw new Exception(language.GetNameByCode("WMSAPIInfo006"));//"ID不能为空!"
                    }
                    #region 查询返回数据
                    sql = @"SELECT a.POCode,a.Sequence,
                                a.VenCode,a.DepCode,a.PersonCode,
	                            d.Name AS Status,
	                            a.Sequence,
	                            a.InvCode,
	                            inv.InvName,
	                            inv.InvStd,
	                            a.Quantity,
	                            inv.InvUnit,
	                            a.Amount,
	                            inv.AmountUnit,
	                            a.InQuantity,
	                            ext.ProjectCode,
	                            ext.BatchCode,
	                            ext.Version,
	                            ext.Brand,
	                            ext.cFree1,
	                            ext.cFree2,
	                            ext.cFree3,
	                            ext.cFree4,
	                            ext.cFree5,
	                            ext.cFree6,
	                            ext.cFree7,
	                            ext.cFree8,
	                            ext.cFree9,
	                            ext.cFree10,
	                            a.MUSER AS [User],
	                            a.MTIME AS [MTime]
                            FROM ICSPurchaseOrder a 
                            LEFT JOIN ICSType d ON d.TableCode='ICSPurchaseOrder' AND d.ColumnCode='Status' AND a.Status=d.Code AND a.WorkPoint=d.WorkPoint
                            INNER JOIN ICSExtension ext ON a.ExtensionID=ext.ID AND a.WorkPoint=ext.WorkPoint
                            INNER JOIN ICSInventory inv ON a.InvCode=inv.InvCode AND a.WorkPoint=inv.WorkPoint
                            WHERE a.ID IN ({0})";
                    sql = string.Format(sql, ids.Substring(0, ids.Length - 1));
                    DataTable data = DBHelper.SQlReturnData(sql, cmd);
                    #endregion
                    cmd.Transaction.Commit();
                    return data;
                }
                catch (Exception ex)
                {
                    if (cmd.Transaction != null)
                        cmd.Transaction.Rollback();
                    log.Error(ex.Message);
                    throw new Exception(ex.Message);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                    }
                    conn.Dispose();
                }
            }
        }

        /// <summary>
        /// 销售订单审核
        /// </summary>
        /// <param name="JsonData"></param>
        /// <returns></returns>
        public static DataTable SalesOrderApprove(List<ICSUser> JsonData)
        {
            string flag = string.Empty;
            var language = LanguageHelper.GetName("WMSAPIInfo");
            if (JsonData.Count <= 0)
            {
                throw new Exception(language.GetNameByCode("WMSAPIInfo007"));//"传送数据为空!"
            }
            using (SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString))
            {
                conn.Open();
                SqlTransaction sqlTran = conn.BeginTransaction();
                SqlCommand cmd = new SqlCommand();
                cmd.Transaction = sqlTran;
                cmd.Connection = conn;
                cmd.CommandTimeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["TimeOut"]);
                try
                {
                    string sql = string.Empty;
                    string ids = string.Empty;
                    foreach (var item in JsonData)
                    {
                        bool hasApproveFlag = JsonData.Any(u => u.ApproveFlag != null);
                        if (hasApproveFlag==true)
                        {
                            flag = item.ApproveFlag;
                        }
                        if (string.IsNullOrEmpty(item.ID))
                        {
                            throw new Exception(language.GetNameByCode("WMSAPIInfo018"));//"单据ID不能为空!");
                        }
                        if (string.IsNullOrEmpty(item.User))
                        {
                            throw new Exception(language.GetNameByCode("WMSAPIInfo019"));//"操作人不能为空!");
                        }
                        if (item.MTime <= new DateTime(2000, 1, 1))
                        {
                            throw new Exception(language.GetNameByCode("WMSAPIInfo020"));//"操作时间不能为空!");
                        }

                        if (flag.Equals("1")|| flag=="")
                        {
                            //获取单号
                            sql = @"DECLARE @Status VARCHAR(10)
                                SELECT @Status=Status  FROM ICSSDN WHERE SDNCode='{0}'

                                IF (@Status IS NULL)
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo065") + @"',16,1);
                                    RETURN
                                END
                                ELSE IF (@Status!='1')
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo066") + @"',16,1);
                                    RETURN
                                END
                             update ICSSDN set Status='2',MUSER='{1}',MTIME='{2}' where SDNCode='{0}'";
                            sql = string.Format(sql, item.ID, item.User, item.MTime);
                            if (!DBHelper.ExecuteNonQuery(sql, cmd))
                            {
                                throw new Exception(language.GetNameByCode("WMSAPIInfo026"));//"生产退料申请单审核失败!");
                            }
                            ids += "'" + item.ID + "',";
                        }
                        else
                        {
                            //获取单号
                            sql = @"DECLARE @Status VARCHAR(10)
                                SELECT @Status=Status  FROM ICSSDN WHERE SDNCode='{0}'

                                IF (@Status IS NULL)
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo065") + @"',16,1);
                                    RETURN
                                END
                                ELSE IF (@Status!='2')
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo473") + @"',16,1);
                                    RETURN
                                END
                                IF EXISTS (select id from ICSSDN where SDNCode='{0}' and SDNQuantity>0)
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo474") + @"',16,1);
                                    RETURN
                                END
                             update ICSSDN set Status='1',MUSER='{1}',MTIME='{2}' where SDNCode='{0}'";
                            sql = string.Format(sql, item.ID, item.User, item.MTime);
                            if (!DBHelper.ExecuteNonQuery(sql, cmd))
                            {
                                throw new Exception(language.GetNameByCode("WMSAPIInfo475"));//"生产退料申请单审核失败!");
                            }
                            ids += "'" + item.ID + "',";
                        }
                        
                    }
                    if (string.IsNullOrWhiteSpace(ids))
                    {
                        throw new Exception(language.GetNameByCode("WMSAPIInfo006"));//"ID不能为空!"
                    }
                    #region 查询返回数据
                    sql = @"SELECT a.SDNCode,a.Sequence,
	                            d.Name AS Status,
	                            a.Sequence,
	                            a.InvCode,
	                            inv.InvName,
	                            inv.InvStd,
	                            a.Quantity,
	                            inv.InvUnit,
	                            a.Amount,
	                            inv.AmountUnit,
	                            ext.ProjectCode,
	                            ext.BatchCode,
	                            ext.Version,
	                            ext.Brand,
	                            ext.cFree1,
	                            ext.cFree2,
	                            ext.cFree3,
	                            ext.cFree4,
	                            ext.cFree5,
	                            ext.cFree6,
	                            ext.cFree7,
	                            ext.cFree8,
	                            ext.cFree9,
	                            ext.cFree10,
	                            a.MUSER AS [User],
	                            a.MTIME AS [MTime]
                            FROM ICSSDN a 
                            LEFT JOIN ICSType d ON d.TableCode='ICSSDN' AND d.ColumnCode='Status' AND a.Status=d.Code AND a.WorkPoint=d.WorkPoint
                            INNER JOIN ICSExtension ext ON a.ExtensionID=ext.ID AND a.WorkPoint=ext.WorkPoint
                            INNER JOIN ICSInventory inv ON a.InvCode=inv.InvCode AND a.WorkPoint=inv.WorkPoint
                            WHERE a.SDNCode IN ({0})";
                    sql = string.Format(sql, ids.Substring(0, ids.Length - 1));
                    DataTable data = DBHelper.SQlReturnData(sql, cmd);
                    #endregion
                    cmd.Transaction.Commit();
                    return data;
                }
                catch (Exception ex)
                {
                    if (cmd.Transaction != null)
                        cmd.Transaction.Rollback();
                    log.Error(ex.Message);
                    throw new Exception(ex.Message);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                    }
                    conn.Dispose();
                }
            }
        }


        /// <summary>
        /// 生产订单审核
        /// </summary>
        /// <param name="JsonData"></param>
        /// <returns></returns>
        public static DataTable ICSMOApprove(List<ICSUser> JsonData)
        {
            string flag = string.Empty;
            var language = LanguageHelper.GetName("WMSAPIInfo");
            if (JsonData.Count <= 0)
            {
                throw new Exception(language.GetNameByCode("WMSAPIInfo007"));//"传送数据为空!"
            }
            using (SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString))
            {
                conn.Open();
                SqlTransaction sqlTran = conn.BeginTransaction();
                SqlCommand cmd = new SqlCommand();
                cmd.Transaction = sqlTran;
                cmd.Connection = conn;
                cmd.CommandTimeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["TimeOut"]);
                try
                {
                    string sql = string.Empty;
                    string ids = string.Empty;
                    foreach (var item in JsonData)
                    {
                        bool hasApproveFlag = JsonData.Any(u => u.ApproveFlag != null);
                        if (hasApproveFlag == true)
                        {
                            flag = item.ApproveFlag;
                        }
                        if (string.IsNullOrEmpty(item.ID))
                        {
                            throw new Exception(language.GetNameByCode("WMSAPIInfo018"));//"单据ID不能为空!");
                        }
                        if (string.IsNullOrEmpty(item.User))
                        {
                            throw new Exception(language.GetNameByCode("WMSAPIInfo019"));//"操作人不能为空!");
                        }
                        if (item.MTime <= new DateTime(2000, 1, 1))
                        {
                            throw new Exception(language.GetNameByCode("WMSAPIInfo020"));//"操作时间不能为空!");
                        }

                        if (flag.Equals("1")|| flag=="")
                        {
                            //获取单号
                            sql = @"DECLARE @Status VARCHAR(10)
                                SELECT @Status=MOStatus FROM ICSMO WHERE mocode='{0}'

                                IF (@Status IS NULL)
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo065") + @"',16,1);
                                    RETURN
                                END
                                ELSE IF (@Status!='1')
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo066") + @"',16,1);
                                    RETURN
                                END
                             update ICSMO set MOStatus='2',MUSER='{1}',MTIME='{2}' where mocode='{0}'";
                            sql = string.Format(sql, item.ID, item.User, item.MTime);
                            if (!DBHelper.ExecuteNonQuery(sql, cmd))
                            {
                                throw new Exception(language.GetNameByCode("WMSAPIInfo026"));//"生产退料申请单审核失败!");
                            }
                            ids += "'" + item.ID + "',";
                        }
                        else
                        {
                            //获取单号
                            sql = @"DECLARE @Status VARCHAR(10)
                                SELECT @Status=MOStatus FROM ICSMO WHERE mocode='{0}'

                                IF (@Status IS NULL)
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo065") + @"',16,1);
                                    RETURN
                                END
                                ELSE IF (@Status!='2')
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo473") + @"',16,1);
                                    RETURN
                                END
                                IF EXISTS (select id from ICSMO where MOCode='{0}' and RCVQuantity>0)
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo474") + @"',16,1);
                                    RETURN
                                END
                             update ICSMO set MOStatus='1',MUSER='{1}',MTIME='{2}' where mocode='{0}'";
                            sql = string.Format(sql, item.ID, item.User, item.MTime);
                            if (!DBHelper.ExecuteNonQuery(sql, cmd))
                            {
                                throw new Exception(language.GetNameByCode("WMSAPIInfo475"));//"生产退料申请单审核失败!");
                            }
                            ids += "'" + item.ID + "',";
                        }
                        
                    }
                    if (string.IsNullOrWhiteSpace(ids))
                    {
                        throw new Exception(language.GetNameByCode("WMSAPIInfo006"));//"ID不能为空!"
                    }
                    #region 查询返回数据
                    sql = @"SELECT a.ID, a.MOCode, a.Sequence, a.InvCode, a.Quantity, 
									 a.Amount, a.RCVQuantity, a.DepCode, a.WHCode, a.StartDate, a.DueDate, 
                                        a.MOStatus, a.MOMemo, a.CreatePerson, a.CreateDateTime, a.ERPStatus, a.MOID, a.MODetailID,
                                        a.ExtensionID, a.MUSER, a.MUSERName, a.MTIME, a.WorkPoint
                            FROM ICSMO a 
                           
                            WHERE a.mocode IN ({0})";
                    sql = string.Format(sql, ids.Substring(0, ids.Length - 1));
                    DataTable data = DBHelper.SQlReturnData(sql, cmd);
                    #endregion
                    cmd.Transaction.Commit();
                    return data;
                }
                catch (Exception ex)
                {
                    if (cmd.Transaction != null)
                        cmd.Transaction.Rollback();
                    log.Error(ex.Message);
                    throw new Exception(ex.Message);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                    }
                    conn.Dispose();
                }
            }
        }


        #endregion
        /// <summary>
        /// 生产订单
        /// </summary>
        /// <param name="JsonData"></param>
        /// <returns></returns>
        public static DataTable ICSMOCreate(List<ICSMO> JsonData)
        {
            var language = LanguageHelper.GetName("WMSAPIInfo");
            if (JsonData.Count <= 0)
            {
                throw new Exception(language.GetNameByCode("WMSAPIInfo007"));//"传送数据为空!"
            }
            using (SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString))
            {
                conn.Open();
                SqlTransaction sqlTran = conn.BeginTransaction();
                SqlCommand cmd = new SqlCommand();
                string Colspan = string.Empty;
                string IDD = string.Empty;
                cmd.Transaction = sqlTran;
                cmd.Connection = conn;
                cmd.CommandTimeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["TimeOut"]);
                try
                {
                    string codes = string.Empty;
                    string sql = string.Empty;
                      sql = @"DECLARE @MaxNO INT,@date varchar(20)='MO'+SUBSTRING(CONVERT(varchar(8), GETDATE(), 112), 1, 8)
                                SELECT @MaxNO=SUBSTRING(MAX(MOCODE),LEN(@date)+1,LEN(MAX(MOCODE))-LEN(@date))+1 FROM ICSMO 
                                    WHERE SUBSTRING(MOCODE, 1, LEN(@date))=@date
                                IF @MaxNO IS NULL
                                BEGIN
	                                SELECT @date+'00001' AS Code
                                END
                                ELSE
                                BEGIN
	                                SELECT @date+REPLICATE('0',5-LEN(@MaxNO))+CAST(@MaxNO AS nvarchar(10))  AS Code
                                END ";
                        string Code = DBHelper.ExecuteScalar(sql, cmd).ToString();


                    HashSet<string> uniqueItems = new HashSet<string>();


                    foreach (var item in JsonData)
                    {

                        //检验自由项
                        Colspan = item.ProjectCode + "~" + item.BatchCode + "~" + item.Version
                                + "~" + item.Brand + "~" + item.cFree1
                                + "~" + item.cFree2 + "~" + item.cFree3 + "~" + item.cFree4
                                + "~" + item.cFree5 + "~" + item.cFree6 + "~" + item.cFree7
                                + "~" + item.cFree8 + "~" + item.cFree9 + "~" + item.cFree10;
                        sql = @"select ID,Colspan from ICSExtension a
                                   where Colspan='{0}' and WorkPoint='{1}'";
                        sql = string.Format(sql, Colspan, item.WorkPoint);
                        DataTable dttt = DBHelper.SQlReturnData(sql, cmd);
                        if (dttt.Rows.Count == 0)
                        {
                            IDD = Guid.NewGuid().ToString();
                            sql = @"Insert into ICSExtension(ID, Colspan, ProjectCode, BatchCode, Version, Brand, cFree1, cFree2, cFree3, cFree4, cFree5, cFree6, cFree7, cFree8, cFree9, cFree10, MTIME, MUSER, MUSERName, WorkPoint) 
                            select '{17}','{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}','{14}',GETDATE(),'{15}',f.F_RealName,'{16}'from Sys_SRM_User f where f.F_Account='{15}' and f.F_Location='{16}'";
                            sql = string.Format(sql, Colspan, item.ProjectCode, item.BatchCode, item.Version, item.Brand, item.cFree1, item.cFree2, item.cFree3, item.cFree4, item.cFree5, item.cFree6, item.cFree7, item.cFree8, item.cFree9, item.cFree10, item.User, item.WorkPoint, IDD);
                            if (!DBHelper.ExecuteNonQuery(sql, cmd))
                            {
                                throw new Exception(language.GetNameByCode("WMSAPIInfo366"));
                            }
                        }
                        else
                        {
                            IDD = dttt.Rows[0]["ID"].ToString();
                        }

                        //获取单号

                        string key = item.Sequence + "~" + item.InvCode;

                        if (uniqueItems.Contains(key))
                        {
                            throw new Exception("子件不可重复添加!");
                        }

                        uniqueItems.Add(key);

                        //创建主表
                        sql = @"IF NOT EXISTS(SELECT F_Account FROM Sys_SRM_User WHERE F_Account='{4}' AND F_Location='{6}')
                                BEGIN
	                                RAISERROR('" + string.Format(language.GetNameByCode("WMSAPIInfo060"), "{4}") + @"',16,1);
                                    RETURN
                                END

                                INSERT INTO ICSMO
                                     (a.ID, a.MOCode, a.Sequence, a.InvCode, a.Quantity, 
									 a.Amount, a.RCVQuantity, a.DepCode, a.WHCode, a.StartDate, a.DueDate, 
                                        a.MOStatus, a.MOMemo, a.CreatePerson, a.CreateDateTime, a.ERPStatus, a.MOID, a.MODetailID,
                                        a.ExtensionID, a.MUSER, a.MUSERName, a.MTIME, a.WorkPoint, a.EATTRIBUTE1, a.EATTRIBUTE2,
                                        a.EATTRIBUTE3, a.EATTRIBUTE4, a.EATTRIBUTE5,
                                        a.EATTRIBUTE6, a.EATTRIBUTE7, a.EATTRIBUTE8, a.EATTRIBUTE9, a.EATTRIBUTE10)
                                    VALUES (NEWID(),'{0}','{1}','{2}','{3}',
                                    '0','0','','','{8}',
                                    '{9}',1,'','{4}','{5}',
                                    '1','','','{7}',
                                    '{4}',(select F_RealName from Sys_SRM_User where F_Account='{4}' and F_Location='{6}'),'{5}','{6}','',
                                    '','','','','','','','','')";
                        sql = string.Format(sql, Code, item.Sequence, item.InvCode, item.Quantity, item.User,
                            item.MTIME, item.WorkPoint,IDD,item.StartDate,item.EndDate,item.WHCODE);

                        if (!DBHelper.ExecuteNonQuery(sql, cmd))
                        {
                            throw new Exception(language.GetNameByCode("WMSAPIInfo022"));//"生产订单信息创建失败!");
                        }
                       
                    }
                    codes = "'" + Code + "'";
                    if (string.IsNullOrWhiteSpace(codes))
                    {
                        throw new Exception(language.GetNameByCode("WMSAPIInfo001"));//"单据号不能为空!"
                    }
                   
                    #region 查询返回数据
                    sql = @"SELECT a.ID, a.MOCode, a.Sequence, a.InvCode, a.Quantity, 
									 a.Amount, a.RCVQuantity, a.DepCode, a.WHCode, a.StartDate, a.DueDate, 
                                        a.MOStatus, a.MOMemo, a.CreatePerson, a.CreateDateTime, a.ERPStatus, a.MOID, a.MODetailID,
                                        a.ExtensionID, a.MUSER, a.MUSERName, a.MTIME, a.WorkPoint
                            FROM ICSMO a 
                           
                            WHERE a.MOCODE+a.WorkPoint IN ({0})";
                    sql = string.Format(sql, codes);
                    DataTable data = DBHelper.SQlReturnData(sql, cmd);
                    #endregion
                    cmd.Transaction.Commit();
                    return data;
                }
                catch (Exception ex)
                {
                    if (cmd.Transaction != null)
                        cmd.Transaction.Rollback();
                    log.Error(ex.Message);
                    throw new Exception(ex.Message);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                    }
                    conn.Dispose();
                }
            }
        }

        #region 销售订单
        /// <summary>
        /// 销售订单创建
        /// </summary>
        /// <returns></returns>
        public static DataTable ICSSalesOrderCreate(List<ICSSalesOrder> JsonData)
        {
            var language = LanguageHelper.GetName("WMSAPIInfo");
            if (JsonData.Count <= 0)
            {
                throw new Exception(language.GetNameByCode("WMSAPIInfo007"));//"传送数据为空!"
            }
            using (SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString))
            {
                conn.Open();
                SqlTransaction sqlTran = conn.BeginTransaction();
                SqlCommand cmd = new SqlCommand();
                cmd.Transaction = sqlTran;
                cmd.Connection = conn;
                cmd.CommandTimeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["TimeOut"]);
                try
                {
                    string codes = string.Empty;
                    string sql = string.Empty;
                    string Colspan = string.Empty;
                    string IDD = string.Empty;
                        //获取单号
                        sql = @"DECLARE @MaxNO INT,@date varchar(20)='POIA'+SUBSTRING(CONVERT(varchar(8), GETDATE(), 112), 1, 8)
                                SELECT @MaxNO=SUBSTRING(MAX(SDNCode),LEN(@date)+1,LEN(MAX(SDNCode))-LEN(@date))+1 FROM ICSSDN 
                                    WHERE SUBSTRING(SDNCode, 1, LEN(@date))=@date
                                IF @MaxNO IS NULL
                                BEGIN
	                                SELECT @date+'00001' AS Code
                                END
                                ELSE
                                BEGIN
	                                SELECT @date+REPLICATE('0',5-LEN(@MaxNO))+CAST(@MaxNO AS nvarchar(10))  AS Code
                                END ";
                        string Code = DBHelper.ExecuteScalar(sql, cmd).ToString();

                    HashSet<string> uniqueItems = new HashSet<string>();

                    foreach (var item in JsonData)
                    {

                        //检验自由项
                        Colspan = item.ProjectCode + "~" + item.BatchCode + "~" + item.Version
                                + "~" + item.Brand + "~" + item.cFree1
                                + "~" + item.cFree2 + "~" + item.cFree3 + "~" + item.cFree4
                                + "~" + item.cFree5 + "~" + item.cFree6 + "~" + item.cFree7
                                + "~" + item.cFree8 + "~" + item.cFree9 + "~" + item.cFree10;
                        sql = @"select ID,Colspan from ICSExtension a
                                   where Colspan='{0}' and WorkPoint='{1}'";
                        sql = string.Format(sql, Colspan, item.WorkPoint);
                        DataTable dttt = DBHelper.SQlReturnData(sql, cmd);
                        if (dttt.Rows.Count == 0)
                        {
                            IDD = Guid.NewGuid().ToString();
                            sql = @"Insert into ICSExtension(ID, Colspan, ProjectCode, BatchCode, Version, Brand, cFree1, cFree2, cFree3, cFree4, cFree5, cFree6, cFree7, cFree8, cFree9, cFree10, MTIME, MUSER, MUSERName, WorkPoint) 
                            select '{17}','{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}','{14}',GETDATE(),'{15}',f.F_RealName,'{16}'from Sys_SRM_User f where f.F_Account='{15}' and f.F_Location='{16}'";
                            sql = string.Format(sql, Colspan, item.ProjectCode, item.BatchCode, item.Version, item.Brand, item.cFree1, item.cFree2, item.cFree3, item.cFree4, item.cFree5, item.cFree6, item.cFree7, item.cFree8, item.cFree9, item.cFree10, item.User, item.WorkPoint, IDD);
                            if (!DBHelper.ExecuteNonQuery(sql, cmd))
                            {
                                throw new Exception(language.GetNameByCode("WMSAPIInfo366"));
                            }
                        }
                        else
                        {
                            IDD = dttt.Rows[0]["ID"].ToString();
                        }

                        string key = item.Sequence + "~" + item.InvCode;

                        if (uniqueItems.Contains(key))
                        {
                            throw new Exception("子件不可重复添加!");
                        }

                        uniqueItems.Add(key);
                        //创建主表
                        sql = @"IF NOT EXISTS(SELECT F_Account FROM Sys_SRM_User WHERE F_Account='{7}' AND F_Location='{6}')
                                BEGIN
	                                RAISERROR('" + string.Format(language.GetNameByCode("WMSAPIInfo060"), "{7}") + @"',16,1);
                                    RETURN
                                END

                                INSERT INTO ICSSDN(ID,SDNCode,Sequence,SOCode,SOSequence,CusCode,CusName,Type,ArriveDate,WHCode,
                                        InvCode,Quantity,CreatePerson,CreateDateTime,Status,SDNID,SDNDetailID,ExtensionID,MUSER,MUSERName,MTIME,WorkPoint) 
                                VALUES(NEWID(),'{0}',{1},'','','{2}','{3}',3,'{8}','{10}',
                                        '{4}',{5},'{7}','{8}',1,'','','{9}','{7}','{7}','{8}','{6}')
                                ";
                        sql = string.Format(sql, Code, item.Sequence, item.CusCode, item.CusName, item.InvCode, item.Quantity, item.WorkPoint, item.User,
                            item.MTime, IDD, item.WHCode);

                        if (!DBHelper.ExecuteNonQuery(sql, cmd))
                        {
                            throw new Exception(language.GetNameByCode("WMSAPIInfo022"));//"采购订单信息创建失败!");
                        }
                        codes += "'" + Code + item.WorkPoint + "',";
                    }
                    if (string.IsNullOrWhiteSpace(codes))
                    {
                        throw new Exception(language.GetNameByCode("WMSAPIInfo001"));//"单据号不能为空!"
                    }
                    #region 查询返回数据
                    sql = @"SELECT a.DNCode,a.Sequence,
                                a.VenCode,a.DepCode,
	                            d.Name AS Status,
	                            a.Sequence,
	                            a.InvCode,
	                            inv.InvName,
	                            inv.InvStd,
	                            a.Quantity,
	                            inv.InvUnit,
	                            a.Amount,
	                            inv.AmountUnit,
	                            ext.ProjectCode,
	                            ext.BatchCode,
	                            ext.Version,
	                            ext.Brand,
	                            ext.cFree1,
	                            ext.cFree2,
	                            ext.cFree3,
	                            ext.cFree4,
	                            ext.cFree5,
	                            ext.cFree6,
	                            ext.cFree7,
	                            ext.cFree8,
	                            ext.cFree9,
	                            ext.cFree10,
	                            a.MUSER AS [User],
	                            a.MTIME AS [MTime]
                            FROM ICSDeliveryNotice a 
                            LEFT JOIN ICSType d ON d.TableCode='ICSDeliveryNotice' AND d.ColumnCode='Status' AND a.Status=d.Code AND a.WorkPoint=d.WorkPoint
                            INNER JOIN ICSExtension ext ON a.ExtensionID=ext.ID AND a.WorkPoint=ext.WorkPoint
                            INNER JOIN ICSInventory inv ON a.InvCode=inv.InvCode AND a.WorkPoint=inv.WorkPoint
                            WHERE a.DNCode+a.WorkPoint IN ({0})";
                    sql = string.Format(sql, codes.Substring(0, codes.Length - 1));
                    DataTable data = DBHelper.SQlReturnData(sql, cmd);
                    #endregion
                    cmd.Transaction.Commit();
                    return data;
                }
                catch (Exception ex)
                {
                    if (cmd.Transaction != null)
                        cmd.Transaction.Rollback();
                    log.Error(ex.Message);
                    throw new Exception(ex.Message);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                    }
                    conn.Dispose();
                }
            }
        }

        /// <summary>
        /// 销售订单 修改
        /// </summary>
        /// <param name="JsonData"></param>
        /// <returns></returns>
        public static DataTable ICSSalesOrderUpdate(List<ICSSalesOrder> JsonData)
        {
            var language = LanguageHelper.GetName("WMSAPIInfo");
            if (JsonData.Count <= 0)
            {
                throw new Exception(language.GetNameByCode("WMSAPIInfo007"));//"传送数据为空!"
            }
            using (SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString))
            {
                conn.Open();
                SqlTransaction sqlTran = conn.BeginTransaction();
                SqlCommand cmd = new SqlCommand();
                cmd.Transaction = sqlTran;
                cmd.Connection = conn;
                cmd.CommandTimeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["TimeOut"]);
                try
                {
                    string sql = string.Empty;
                    string Checksql = string.Empty;
                    string Code = string.Empty;
                    string ids = string.Empty;
                    string Colspan = string.Empty;
                    string IDD = string.Empty;
                    foreach (var item in JsonData)
                    {

                        //检验自由项
                        Colspan = item.ProjectCode + "~" + item.BatchCode + "~" + item.Version
                                + "~" + item.Brand + "~" + item.cFree1
                                + "~" + item.cFree2 + "~" + item.cFree3 + "~" + item.cFree4
                                + "~" + item.cFree5 + "~" + item.cFree6 + "~" + item.cFree7
                                + "~" + item.cFree8 + "~" + item.cFree9 + "~" + item.cFree10;
                        Checksql = @"select ID,Colspan from ICSExtension a
                                   where Colspan='{0}' and WorkPoint='{1}'";
                        Checksql = string.Format(Checksql, Colspan, item.WorkPoint);
                        DataTable dttt = DBHelper.SQlReturnData(Checksql, cmd);
                        if (dttt.Rows.Count == 0)
                        {
                            IDD = Guid.NewGuid().ToString();
                            Checksql = @"Insert into ICSExtension(ID, Colspan, ProjectCode, BatchCode, Version, Brand, cFree1, cFree2, cFree3, cFree4, cFree5, cFree6, cFree7, cFree8, cFree9, cFree10, MTIME, MUSER, MUSERName, WorkPoint) 
                            select '{17}','{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}','{14}',GETDATE(),'{15}',f.F_RealName,'{16}'from Sys_SRM_User f where f.F_Account='{15}' and f.F_Location='{16}'";
                            Checksql = string.Format(Checksql, Colspan, item.ProjectCode, item.BatchCode, item.Version, item.Brand, item.cFree1, item.cFree2, item.cFree3, item.cFree4, item.cFree5, item.cFree6, item.cFree7, item.cFree8, item.cFree9, item.cFree10, item.User, item.WorkPoint, IDD);
                            if (!DBHelper.ExecuteNonQuery(Checksql, cmd))
                            {
                                throw new Exception(language.GetNameByCode("WMSAPIInfo366"));
                            }
                        }
                        else
                        {
                            IDD = dttt.Rows[0]["ID"].ToString();
                        }

                        //主表修改
                        sql = @"IF NOT EXISTS(SELECT F_Account FROM Sys_SRM_User WHERE F_Account='{4}' AND F_Location='{6}')
                                BEGIN
	                                RAISERROR('" + string.Format(language.GetNameByCode("WMSAPIInfo060"), "{4}") + @"',16,1);
                                    RETURN
                                END

                                DECLARE @Status VARCHAR(10)
                                SELECT distinct @Status=Status FROM ICSSDN WHERE SDNCode='{0}' and WorkPoint='{6}'

                                IF (@Status IS NULL)
                                BEGIN
	                                RAISERROR('" + string.Format(language.GetNameByCode("WMSAPIInfo065"), "{0}") + @"',16,1);
                                    RETURN
                                END
                                ELSE IF (@Status!='1')
                                BEGIN
	                                RAISERROR('" + string.Format(language.GetNameByCode("WMSAPIInfo066"), "{0}") + @"',16,1);
                                    RETURN
                                END
";
                        sql = string.Format(sql, item.SDNCode, item.Sequence, item.InvCode, item.Quantity, item.User,
                            item.MTime, item.WorkPoint);





                        if (!string.IsNullOrWhiteSpace(item.Sequence))
                        {
                            //创建子表
                            sql += @"IF EXISTS(Select *  from  ICSSDN where SDNCode ='{0}'and Sequence ='{1}')
Begin
											UPDATE ICSSDN set InvCode='{4}',Quantity='{5}',WHCode='{10}',MUSER= '{7}',MUSERName=(select F_RealName from Sys_SRM_User where F_Account='{7}' and F_Location='{6}'),MTIME='{8}'
											where SDNCode ='{0}' and Sequence ='{1}'
END
										ELSE
BEGIN
                                            INSERT INTO ICSSDN(ID,SDNCode,Sequence,SOCode,SOSequence,CusCode,CusName,Type,ArriveDate,WHCode,
                                        InvCode,Quantity,CreatePerson,CreateDateTime,Status,SDNID,SDNDetailID,ExtensionID,MUSER,MUSERName,MTIME,WorkPoint) 
                                VALUES(NEWID(),'{0}',{1},'','','{2}','{3}',3,'{8}','{10}',
                                        '{4}',{5},'{7}','{8}',1,'','','{9}','{7}','{7}','{8}','{6}') 
END";
                            
                            sql = string.Format(sql, item.SDNCode, item.Sequence, item.CusCode, item.CusName, item.InvCode, item.Quantity, item.WorkPoint, item.User,
                            item.MTime, IDD, item.WHCode);
                        }

                        if (!DBHelper.ExecuteNonQuery(sql, cmd))
                        {
                            throw new Exception(language.GetNameByCode("WMSAPIInfo025"));//"采购订单信息修改失败!");
                        }
                        ids += "'" + item.Sequence + "',";
                        Code = item.SDNCode;
                    }
                    sql = @"DELETE from ICSDeliveryNotice  where DNCode ='{0}' and Sequence not in ({1})";
                    sql = string.Format(sql, Code, ids.Substring(0, ids.Length - 1));
                    DBHelper.ExecuteNonQuery(sql, cmd);

                    #region 查询返回数据
                    sql = @"SELECT a.DNCode,a.Sequence,
                                a.VenCode,a.DepCode,
	                            d.Name AS Status,
	                            a.Sequence,
	                            a.InvCode,
	                            inv.InvName,
	                            inv.InvStd,
	                            a.Quantity,
	                            inv.InvUnit,
	                            a.Amount,
	                            inv.AmountUnit,
	                            ext.ProjectCode,
	                            ext.BatchCode,
	                            ext.Version,
	                            ext.Brand,
	                            ext.cFree1,
	                            ext.cFree2,
	                            ext.cFree3,
	                            ext.cFree4,
	                            ext.cFree5,
	                            ext.cFree6,
	                            ext.cFree7,
	                            ext.cFree8,
	                            ext.cFree9,
	                            ext.cFree10,
	                            a.MUSER AS [User],
	                            a.MTIME AS [MTime]
                            FROM ICSDeliveryNotice a 
                            LEFT JOIN ICSType d ON d.TableCode='ICSDeliveryNotice' AND d.ColumnCode='Status' AND a.Status=d.Code AND a.WorkPoint=d.WorkPoint
                            INNER JOIN ICSExtension ext ON a.ExtensionID=ext.ID AND a.WorkPoint=ext.WorkPoint
                            INNER JOIN ICSInventory inv ON a.InvCode=inv.InvCode AND a.WorkPoint=inv.WorkPoint
                            WHERE a.DNCode+a.WorkPoint IN ('{0}')";
                    sql = string.Format(sql, Code, ids.Substring(0, ids.Length - 1));
                    DataTable data = DBHelper.SQlReturnData(sql, cmd);
                    #endregion
                    cmd.Transaction.Commit();
                    return data;
                }
                catch (Exception ex)
                {
                    if (cmd.Transaction != null)
                        cmd.Transaction.Rollback();
                    log.Error(ex.Message);
                    throw new Exception(ex.Message);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                    }
                    conn.Dispose();
                }
            }
        }

        #endregion

        /// <summary>
        /// 生产退料 修改
        /// </summary>
        /// <param name="JsonData"></param>
        /// <returns></returns>
        public static DataTable ICSMOUpdate(List<ICSMO> JsonData)
        {
            var language = LanguageHelper.GetName("WMSAPIInfo");
            if (JsonData.Count <= 0)
            {
                throw new Exception(language.GetNameByCode("WMSAPIInfo007"));//"传送数据为空!"
            }
            using (SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString))
            {
                conn.Open();
                SqlTransaction sqlTran = conn.BeginTransaction();
                SqlCommand cmd = new SqlCommand();
                cmd.Transaction = sqlTran;
                cmd.Connection = conn;
                cmd.CommandTimeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["TimeOut"]);
                try
                {
                    string sql = string.Empty;
                    string Checksql = string.Empty;
                    string Code = string.Empty;
                    string ids = string.Empty;
                    string Colspan = string.Empty;
                    string IDD = string.Empty;
                    foreach (var item in JsonData)
                    {
                        //检验自由项
                        Colspan = item.ProjectCode + "~" + item.BatchCode + "~" + item.Version
                                + "~" + item.Brand + "~" + item.cFree1
                                + "~" + item.cFree2 + "~" + item.cFree3 + "~" + item.cFree4
                                + "~" + item.cFree5 + "~" + item.cFree6 + "~" + item.cFree7
                                + "~" + item.cFree8 + "~" + item.cFree9 + "~" + item.cFree10;
                        Checksql = @"select ID,Colspan from ICSExtension a
                                   where Colspan='{0}' and WorkPoint='{1}'";
                        Checksql = string.Format(Checksql, Colspan, item.WorkPoint);
                        DataTable dttt = DBHelper.SQlReturnData(Checksql, cmd);
                        if (dttt.Rows.Count == 0)
                        {
                            IDD = Guid.NewGuid().ToString();
                            Checksql = @"Insert into ICSExtension(ID, Colspan, ProjectCode, BatchCode, Version, Brand, cFree1, cFree2, cFree3, cFree4, cFree5, cFree6, cFree7, cFree8, cFree9, cFree10, MTIME, MUSER, MUSERName, WorkPoint) 
                            select '{17}','{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}','{14}',GETDATE(),'{15}',f.F_RealName,'{16}'from Sys_SRM_User f where f.F_Account='{15}' and f.F_Location='{16}'";
                            Checksql = string.Format(Checksql, Colspan, item.ProjectCode, item.BatchCode, item.Version, item.Brand, item.cFree1, item.cFree2, item.cFree3, item.cFree4, item.cFree5, item.cFree6, item.cFree7, item.cFree8, item.cFree9, item.cFree10, item.User, item.WorkPoint, IDD);
                            if (!DBHelper.ExecuteNonQuery(Checksql, cmd))
                            {
                                throw new Exception(language.GetNameByCode("WMSAPIInfo366"));
                            }
                        }
                        else
                        {
                            IDD = dttt.Rows[0]["ID"].ToString();
                        }

                        //主表修改
                        sql = @"IF NOT EXISTS(SELECT F_Account FROM Sys_SRM_User WHERE F_Account='{4}' AND F_Location='{6}')
                                BEGIN
	                                RAISERROR('" + string.Format(language.GetNameByCode("WMSAPIInfo060"), "{4}") + @"',16,1);
                                    RETURN
                                END

                                DECLARE @Status VARCHAR(10)
                                SELECT distinct @Status=moStatus FROM ICSMO WHERE MOCODE='{0}' and WorkPoint='{6}'

                                IF (@Status IS NULL)
                                BEGIN
	                                RAISERROR('" + string.Format(language.GetNameByCode("WMSAPIInfo065"), "{0}") + @"',16,1);
                                    RETURN
                                END
                                ELSE IF (@Status!='1')
                                BEGIN
	                                RAISERROR('" + string.Format(language.GetNameByCode("WMSAPIInfo066"), "{0}") + @"',16,1);
                                    RETURN
                                END
";
                        sql = string.Format(sql, item.MOCODE, item.Sequence, item.InvCode, item.Quantity, item.User,
                            item.MTIME, item.WorkPoint);


                      


                        if (!string.IsNullOrWhiteSpace(item.Sequence))
                        {
                            //创建子表
                            sql+= @"IF EXISTS(Select *  from  icsmo where mocode ='{0}'and Sequence ='{1}')
Begin
											UPDATE icsmo set InvCode='{2}',Quantity='{3}',MUSER= '{4}',MUSERName=(select F_RealName from Sys_SRM_User where F_Account='{4}' and F_Location='{6}'),MTIME='{5}'
											where mocode ='{0}'and Sequence ='{1}'
END
										ELSE
BEGIN
											INSERT INTO ICSMO
												  (ID, MOCode, Sequence, InvCode, Quantity, 
												  Amount, RCVQuantity, DepCode, WHCode, StartDate, DueDate, 
												  MOStatus, MOMemo, CreatePerson, CreateDateTime, ERPStatus, MOID, MODetailID,
												  ExtensionID, MUSER, MUSERName, MTIME, WorkPoint, EATTRIBUTE1, EATTRIBUTE2,
												  EATTRIBUTE3, EATTRIBUTE4, EATTRIBUTE5,
												  EATTRIBUTE6, EATTRIBUTE7, EATTRIBUTE8, EATTRIBUTE9, EATTRIBUTE10)
												  VALUES (NEWID(),'{0}','{1}','{2}','{3}',
                                                    '0','0','','','{5}',
                                                    '{5}',1,'','{4}','{5}',
                                                    '1','','','',
                                                    '{4}',(select F_RealName from Sys_SRM_User where F_Account='{4}' and F_Location='{6}'),'{5}','{6}','{7}',
                                                    '','','','','','','','','')
END";
                            sql = string.Format(sql, item.MOCODE, item.Sequence, item.InvCode, item.Quantity, item.User,
                                    item.MTIME, item.WorkPoint,IDD);
                            log.Debug("111"+sql);
                        }

                        if (!DBHelper.ExecuteNonQuery(sql, cmd))
                        {
                            throw new Exception(language.GetNameByCode("WMSAPIInfo025"));//"生产退料单子表信息修改失败!");
                        }
                        ids += "'" + item.Sequence + "',";
                        Code = item.MOCODE;
                    }
                    sql = @"DELETE from icsmo  where mocode ='{0}' and Sequence not in ({1})";
                    sql = string.Format(sql, Code, ids.Substring(0, ids.Length - 1));
                    DBHelper.ExecuteNonQuery(sql, cmd);

                    #region 查询返回数据
                    sql = @"SELECT a.ID, a.MOCode, a.Sequence, a.InvCode, a.Quantity, 
									 a.Amount, a.RCVQuantity, a.DepCode, a.WHCode, a.StartDate, a.DueDate, 
                                        a.MOStatus, a.MOMemo, a.CreatePerson, a.CreateDateTime, a.ERPStatus, a.MOID, a.MODetailID,
                                        a.ExtensionID, a.MUSER, a.MUSERName, a.MTIME, a.WorkPoint, a.EATTRIBUTE1, a.EATTRIBUTE2,
                                        a.EATTRIBUTE3, a.EATTRIBUTE4, a.EATTRIBUTE5,
                                        a.EATTRIBUTE6, a.EATTRIBUTE7, a.EATTRIBUTE8, a.EATTRIBUTE9, a.EATTRIBUTE10
                            FROM ICSMO a 
                           
                            WHERE mocode ='{0}' and Sequence in ({1})";
                    sql = string.Format(sql, Code, ids.Substring(0, ids.Length - 1));
                    DataTable data = DBHelper.SQlReturnData(sql, cmd);
                    #endregion
                    cmd.Transaction.Commit();
                    return data;
                }
                catch (Exception ex)
                {
                    if (cmd.Transaction != null)
                        cmd.Transaction.Rollback();
                    log.Error(ex.Message);
                    throw new Exception(ex.Message);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                    }
                    conn.Dispose();
                }
            }
        }



        #region 委外
        /// <summary>
        /// 委外退料 新建
        /// </summary>
        /// <param name="JsonData"></param>
        /// <returns></returns>
        public static DataTable OutsourcingIssueDoNegativeApplyCreate(List<ICSOApplyNeg> JsonData)
        {
            var language = LanguageHelper.GetName("WMSAPIInfo");
            if (JsonData.Count <= 0)
            {
                throw new Exception(language.GetNameByCode("WMSAPIInfo007"));//"传送数据为空!"
            }
            using (SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString))
            {
                conn.Open();
                SqlTransaction sqlTran = conn.BeginTransaction();
                SqlCommand cmd = new SqlCommand();
                cmd.Transaction = sqlTran;
                cmd.Connection = conn;
                cmd.CommandTimeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["TimeOut"]);
                try
                {
                    string codes = string.Empty;
                    string sql = string.Empty;

                    foreach (var item in JsonData)
                    {
                        //获取单号
                        sql = @"DECLARE @MaxNO INT,@date varchar(20)='OOIA'+SUBSTRING(CONVERT(varchar(8), GETDATE(), 112), 1, 8)
                                SELECT @MaxNO=SUBSTRING(MAX(OApplyNegCode),LEN(@date)+1,LEN(MAX(OApplyNegCode))-LEN(@date))+1 FROM ICSOApplyNeg 
                                    WHERE SUBSTRING(OApplyNegCode, 1, LEN(@date))=@date
                                IF @MaxNO IS NULL
                                BEGIN
	                                SELECT @date+'00001' AS Code
                                END
                                ELSE
                                BEGIN
	                                SELECT @date+REPLICATE('0',5-LEN(@MaxNO))+CAST(@MaxNO AS nvarchar(10))  AS Code
                                END ";
                        string Code = DBHelper.ExecuteScalar(sql, cmd).ToString();
                        //创建主表
                        sql = @"IF NOT EXISTS(SELECT F_Account FROM Sys_SRM_User WHERE F_Account='{2}' AND F_Location='{4}')
                                BEGIN
	                                RAISERROR('" + string.Format(language.GetNameByCode("WMSAPIInfo060"), "{2}") + @"',16,1);
                                    RETURN
                                END

                                INSERT INTO ICSOApplyNeg(ID,OApplyNegCode,WHCode,Status,Type,Memo,CreatePerson,CreateDateTime,MUSER,MUSERName,MTIME,WorkPoint,EATTRIBUTE1)
                             VALUES (NEWID(),'{0}','{1}','1','{5}','','{2}','{3}','{2}',(select F_RealName from Sys_SRM_User where F_Account='{2}' and F_Location='{4}'),'{3}','{4}','')";
                        sql = string.Format(sql, Code, item.WHCode, item.User, item.MTime, item.WorkPoint, item.Type);

                        if (!DBHelper.ExecuteNonQuery(sql, cmd))
                        {
                            throw new Exception(language.GetNameByCode("WMSAPIInfo014"));//"委外退料单信息创建失败!");
                        }
                        HashSet<string> uniqueItems = new HashSet<string>();

                        foreach (var itemInfo in item.detail)
                        {
                            string key = itemInfo.Sequence + "~" + itemInfo.InvCode;

                            if (uniqueItems.Contains(key))
                            {
                                throw new Exception("子件不可重复添加!");
                            }

                            uniqueItems.Add(key);

                            // 创建子表
                            sql = @"INSERT INTO ICSOApplyNegDetail(ID,OApplyNegCode,Sequence,SourceDetailID,InvCode,
                Quantity,Amount,IssueNegQuantity,ExtensionID,MUSER,
                MUSERName,MTIME,WorkPoint,EATTRIBUTE1)
                VALUES (NEWID(),'{0}','{1}','{2}','{3}',
                '{4}','{5}',0,'{6}','{7}',
                (select F_RealName from Sys_SRM_User where F_Account='{7}' and F_Location='{8}'),SYSDATETIME(),'{8}','')";
                            sql = string.Format(sql, Code, itemInfo.Sequence, itemInfo.SourceDetailID, itemInfo.InvCode, itemInfo.Quantity, itemInfo.Amount, itemInfo.ExtensionID, item.User, item.WorkPoint);

                            if (!DBHelper.ExecuteNonQuery(sql, cmd))
                            {
                                throw new Exception(language.GetNameByCode("WMSAPIInfo015"));//"委外退料单子表信息创建失败!");
                            }
                        }
                        //校验退料数量是否超出领料数量
                        sql = CheckOutsourcingIssueDoc(item.Type, Code, item.WorkPoint, language);
                        DBHelper.ExecuteNonQuery(sql, cmd);
                        codes += "'" + Code + item.WorkPoint + "',";
                    }
                    if (string.IsNullOrWhiteSpace(codes))
                    {
                        throw new Exception(language.GetNameByCode("WMSAPIInfo001"));//"单据号不能为空!"
                    }
                    #region 查询返回数据
                    sql = @"SELECT a.OApplyNegCode,
	                            c.WHCode,
	                            c.Memo,
	                            d.Name AS Status,
	                            a.Sequence,
	                            a.InvCode,
	                            inv.InvName,
	                            inv.InvStd,
	                            a.Quantity,
	                            inv.InvUnit,
	                            a.Amount,
	                            inv.AmountUnit,
	                            a.IssueNegQuantity,
	                            ext.ProjectCode,
	                            ext.BatchCode,
	                            ext.Version,
	                            ext.Brand,
	                            ext.cFree1,
	                            ext.cFree2,
	                            ext.cFree3,
	                            ext.cFree4,
	                            ext.cFree5,
	                            ext.cFree6,
	                            ext.cFree7,
	                            ext.cFree8,
	                            ext.cFree9,
	                            ext.cFree10,
	                            a.MUSER AS [User],
	                            a.MTIME AS [MTime]
                            FROM ICSOApplyNegDetail a 
                            INNER JOIN ICSOApplyNeg c ON a.OApplyNegCode=c.OApplyNegCode AND a.WorkPoint=c.WorkPoint
                            LEFT JOIN ICSType d ON d.TableCode='ICSOApplyNeg' AND d.ColumnCode='Status' AND c.Status=d.Code AND c.WorkPoint=d.WorkPoint 
                            INNER JOIN ICSExtension ext ON a.ExtensionID=ext.ID AND a.WorkPoint=ext.WorkPoint
                            INNER JOIN ICSInventory inv ON a.InvCode=inv.InvCode AND a.WorkPoint=inv.WorkPoint
                            WHERE a.OApplyNegCode+a.WorkPoint IN ({0})";
                    sql = string.Format(sql, codes.Substring(0, codes.Length - 1));
                    DataTable data = DBHelper.SQlReturnData(sql, cmd);
                    #endregion
                    cmd.Transaction.Commit();
                    return data;
                }
                catch (Exception ex)
                {
                    if (cmd.Transaction != null)
                        cmd.Transaction.Rollback();
                    log.Error(ex.Message);
                    throw new Exception(ex.Message);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                    }
                    conn.Dispose();
                }
            }
        }

        /// <summary>
        /// 委外退料 新建
        /// </summary>
        /// <param name="JsonData"></param>
        /// <returns></returns>
        public static DataTable AMOutsourcingIssueDoNegativeApplyCreate(List<ICSOApplyNeg> JsonData)
        {
            var language = LanguageHelper.GetName("WMSAPIInfo");
            if (JsonData.Count <= 0)
            {
                throw new Exception(language.GetNameByCode("WMSAPIInfo007"));//"传送数据为空!"
            }
            using (SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString))
            {
                conn.Open();
                SqlTransaction sqlTran = conn.BeginTransaction();
                SqlCommand cmd = new SqlCommand();
                cmd.Transaction = sqlTran;
                cmd.Connection = conn;
                cmd.CommandTimeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["TimeOut"]);
                try
                {
                    string codes = string.Empty;
                    string sql = string.Empty;

                    foreach (var item in JsonData)
                    {
                        //获取单号
                        sql = @"DECLARE @MaxNO INT,@date varchar(20)='OOIA'+SUBSTRING(CONVERT(varchar(8), GETDATE(), 112), 1, 8)
                                SELECT @MaxNO=SUBSTRING(MAX(OApplyNegCode),LEN(@date)+1,LEN(MAX(OApplyNegCode))-LEN(@date))+1 FROM ICSOApplyNeg 
                                    WHERE SUBSTRING(OApplyNegCode, 1, LEN(@date))=@date
                                IF @MaxNO IS NULL
                                BEGIN
	                                SELECT @date+'00001' AS Code
                                END
                                ELSE
                                BEGIN
	                                SELECT @date+REPLICATE('0',5-LEN(@MaxNO))+CAST(@MaxNO AS nvarchar(10))  AS Code
                                END ";
                        string Code = DBHelper.ExecuteScalar(sql, cmd).ToString();
                        //创建主表
                        sql = @"IF NOT EXISTS(SELECT F_Account FROM Sys_SRM_User WHERE F_Account='{2}' AND F_Location='{4}')
                                BEGIN
	                                RAISERROR('" + string.Format(language.GetNameByCode("WMSAPIInfo060"), "{2}") + @"',16,1);
                                    RETURN
                                END

                                INSERT INTO ICSOApplyNeg(ID,OApplyNegCode,WHCode,Status,Type,Memo,CreatePerson,CreateDateTime,MUSER,MUSERName,MTIME,WorkPoint,EATTRIBUTE1)
                             VALUES (NEWID(),'{0}','{1}','1','{5}','','{2}','{3}','{2}',(select F_RealName from Sys_SRM_User where F_Account='{2}' and F_Location='{4}'),'{3}','{4}','')";
                        sql = string.Format(sql, Code, item.WHCode, item.User, item.MTime, item.WorkPoint, item.Type);

                        if (!DBHelper.ExecuteNonQuery(sql, cmd))
                        {
                            throw new Exception(language.GetNameByCode("WMSAPIInfo014"));//"委外退料单信息创建失败!");
                        }
                        HashSet<string> uniqueItems = new HashSet<string>();

                        foreach (var itemInfo in item.detail)
                        {
                            string chekksql = @"select c.EATTRIBUTE1 ICSInventory c 
                                WHERE c.InvCode='{0}'AND c.WorkPoint='{1}' and c.AmountEnable='1'";
                            chekksql = string.Format(chekksql, itemInfo.InvCode, itemInfo.WorkPoint);
                            DataTable dta = DBHelper.SQlReturnData(chekksql, cmd);
                            if (dta.Rows.Count > 0)
                            {
                                itemInfo.Quantity = (itemInfo.Quantity * decimal.Parse(dta.Rows[0]["EATTRIBUTE1"].ToString()));
                            }

                            string key = itemInfo.Sequence + "~" + itemInfo.InvCode;

                            if (uniqueItems.Contains(key))
                            {
                                throw new Exception("子件不可重复添加!");
                            }

                            uniqueItems.Add(key);

                            // 创建子表
                            sql = @"INSERT INTO ICSOApplyNegDetail(ID,OApplyNegCode,Sequence,SourceDetailID,InvCode,
                Quantity,Amount,IssueNegQuantity,ExtensionID,MUSER,
                MUSERName,MTIME,WorkPoint,EATTRIBUTE1)
                VALUES (NEWID(),'{0}','{1}','{2}','{3}',
                '{4}','{5}',0,'{6}','{7}',
                (select F_RealName from Sys_SRM_User where F_Account='{7}' and F_Location='{8}'),SYSDATETIME(),'{8}','')";
                            sql = string.Format(sql, Code, itemInfo.Sequence, itemInfo.SourceDetailID, itemInfo.InvCode, itemInfo.Quantity, itemInfo.Amount, itemInfo.ExtensionID, item.User, item.WorkPoint);

                            if (!DBHelper.ExecuteNonQuery(sql, cmd))
                            {
                                throw new Exception(language.GetNameByCode("WMSAPIInfo015"));//"委外退料单子表信息创建失败!");
                            }
                        }
                        //校验退料数量是否超出领料数量
                        sql = CheckOutsourcingIssueDoc(item.Type, Code, item.WorkPoint, language);
                        DBHelper.ExecuteNonQuery(sql, cmd);
                        codes += "'" + Code + item.WorkPoint + "',";
                    }
                    if (string.IsNullOrWhiteSpace(codes))
                    {
                        throw new Exception(language.GetNameByCode("WMSAPIInfo001"));//"单据号不能为空!"
                    }
                    #region 查询返回数据
                    sql = @"SELECT a.OApplyNegCode,
	                            c.WHCode,
	                            c.Memo,
	                            d.Name AS Status,
	                            a.Sequence,
	                            a.InvCode,
	                            inv.InvName,
	                            inv.InvStd,
	                            a.Quantity,
	                            inv.InvUnit,
	                            a.Amount,
	                            inv.AmountUnit,
	                            a.IssueNegQuantity,
	                            ext.ProjectCode,
	                            ext.BatchCode,
	                            ext.Version,
	                            ext.Brand,
	                            ext.cFree1,
	                            ext.cFree2,
	                            ext.cFree3,
	                            ext.cFree4,
	                            ext.cFree5,
	                            ext.cFree6,
	                            ext.cFree7,
	                            ext.cFree8,
	                            ext.cFree9,
	                            ext.cFree10,
	                            a.MUSER AS [User],
	                            a.MTIME AS [MTime]
                            FROM ICSOApplyNegDetail a 
                            INNER JOIN ICSOApplyNeg c ON a.OApplyNegCode=c.OApplyNegCode AND a.WorkPoint=c.WorkPoint
                            LEFT JOIN ICSType d ON d.TableCode='ICSOApplyNeg' AND d.ColumnCode='Status' AND c.Status=d.Code AND c.WorkPoint=d.WorkPoint 
                            INNER JOIN ICSExtension ext ON a.ExtensionID=ext.ID AND a.WorkPoint=ext.WorkPoint
                            INNER JOIN ICSInventory inv ON a.InvCode=inv.InvCode AND a.WorkPoint=inv.WorkPoint
                            WHERE a.OApplyNegCode+a.WorkPoint IN ({0})";
                    sql = string.Format(sql, codes.Substring(0, codes.Length - 1));
                    DataTable data = DBHelper.SQlReturnData(sql, cmd);
                    #endregion
                    cmd.Transaction.Commit();
                    return data;
                }
                catch (Exception ex)
                {
                    if (cmd.Transaction != null)
                        cmd.Transaction.Rollback();
                    log.Error(ex.Message);
                    throw new Exception(ex.Message);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                    }
                    conn.Dispose();
                }
            }
        }

        private static string CheckOutsourcingIssueDoc(string Type, string Code, string WorkPoint, Dictionary<string, string> language)
        {
            string sql = string.Empty;
            if (Type == "1")
            {
                sql = @"DECLARE @PickID VARCHAR(10)
                        SELECT @PickID=b.PickID
                        FROM ICSOApplyNegDetail a 
                        INNER JOIN ICSOOPick b ON a.SourceDetailID=b.PickID AND a.WorkPoint=b.WorkPoint
                        INNER JOIN ICSOApplyNeg c ON a.OApplyNegCode=c.OApplyNegCode AND a.WorkPoint=c.WorkPoint
                        WHERE c.Type='{2}' AND a.WorkPoint='{1}'
                            AND a.SourceDetailID IN (SELECT a.SourceDetailID
                                FROM ICSOApplyNegDetail a 
                                INNER JOIN ICSOApplyNeg c ON a.OApplyNegCode=c.OApplyNegCode AND a.WorkPoint=c.WorkPoint
                                WHERE c.OApplyNegCode='{0}' AND c.Type='{2}' AND a.WorkPoint='{1}')
                        GROUP BY b.PickID
                        HAVING MAX(b.Quantity)<SUM(a.Quantity)

                        IF (@PickID IS NOT NULL)
                        BEGIN
	                        DECLARE @InvCode VARCHAR(100)
	                        SELECT @InvCode='" + language.GetNameByCode("WMSAPIInfo064") + @"' FROM ICSOOPick WHERE PickID=@PickID AND WorkPoint='{1}'
	                        RAISERROR(@InvCode,16,1);
	                        RETURN
                        END ";
            }
            else if (Type == "2")
            {
                sql = @"DECLARE @ApplyDetailID VARCHAR(10)
                        SELECT @ApplyDetailID=b.ApplyDetailID
                        FROM ICSOApplyNegDetail a 
                        INNER JOIN ICSOApply b ON a.SourceDetailID=b.ApplyDetailID AND a.WorkPoint=b.WorkPoint
                        INNER JOIN ICSOApplyNeg c ON a.OApplyNegCode=c.OApplyNegCode AND a.WorkPoint=c.WorkPoint
                        WHERE c.Type='{2}' AND a.WorkPoint='{1}'
                            AND a.SourceDetailID IN (SELECT a.SourceDetailID
                                FROM ICSOApplyNegDetail a 
                                INNER JOIN ICSOApplyNeg c ON a.OApplyNegCode=c.OApplyNegCode AND a.WorkPoint=c.WorkPoint
                                WHERE c.OApplyNegCode='{0}' AND c.Type='{2}' AND a.WorkPoint='{1}')
                        GROUP BY b.ApplyDetailID
                        HAVING MAX(b.Quantity)<SUM(a.Quantity)

                        IF (@ApplyDetailID IS NOT NULL)
                        BEGIN
	                        DECLARE @InvCode VARCHAR(100)
	                        SELECT @InvCode='" + language.GetNameByCode("WMSAPIInfo064") + @"' FROM ICSOApply WHERE ApplyDetailID=@ApplyDetailID AND WorkPoint='{1}'
	                        RAISERROR(@InvCode,16,1);
	                        RETURN
                        END ";
            }
            else if (Type == "3")
            {
                sql = @"DECLARE @IssueDetailID VARCHAR(10)
                        SELECT @IssueDetailID=b.IssueDetailID
                        FROM ICSOApplyNegDetail a 
                        INNER JOIN ICSOIssue b ON a.SourceDetailID=b.IssueDetailID AND a.WorkPoint=b.WorkPoint
                        INNER JOIN ICSOApplyNeg c ON a.OApplyNegCode=c.OApplyNegCode AND a.WorkPoint=c.WorkPoint
                        WHERE c.Type='{2}' AND a.WorkPoint='{1}'
                            AND a.SourceDetailID IN (SELECT a.SourceDetailID
                                FROM ICSOApplyNegDetail a 
                                INNER JOIN ICSOApplyNeg c ON a.OApplyNegCode=c.OApplyNegCode AND a.WorkPoint=c.WorkPoint
                                WHERE c.OApplyNegCode='{0}' AND c.Type='{2}' AND a.WorkPoint='{1}')
                        GROUP BY b.IssueDetailID
                        HAVING MAX(b.Quantity)<SUM(a.Quantity)

                        IF (@IssueDetailID IS NOT NULL)
                        BEGIN
	                        DECLARE @InvCode VARCHAR(100)
	                        SELECT @InvCode='" + language.GetNameByCode("WMSAPIInfo064") + @"' FROM ICSOIssue WHERE IssueDetailID=@IssueDetailID AND WorkPoint='{1}'
	                        RAISERROR(@InvCode,16,1);
	                        RETURN
                        END ";
            }
            else
            {
                throw new Exception(language.GetNameByCode("WMSAPIInfo003"));//"类型不符!");
            }
            sql = string.Format(sql, Code, WorkPoint, Type);
            return sql;
        }

        /// <summary>
        /// 委外退料 修改
        /// </summary>
        /// <param name="JsonData"></param>
        /// <returns></returns>
        public static DataTable OutsourcingIssueDoNegativeApplyUpdate(List<ICSOApplyNeg> JsonData)
        {
            var language = LanguageHelper.GetName("WMSAPIInfo");
            if (JsonData.Count <= 0)
            {
                throw new Exception(language.GetNameByCode("WMSAPIInfo007"));//"传送数据为空!"
            }
            using (SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString))
            {
                conn.Open();
                SqlTransaction sqlTran = conn.BeginTransaction();
                SqlCommand cmd = new SqlCommand();
                cmd.Transaction = sqlTran;
                cmd.Connection = conn;
                cmd.CommandTimeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["TimeOut"]);
                try
                {
                    string sql = string.Empty;
                    string Code = string.Empty;
                    string ids = string.Empty;
                    string idss = string.Empty;
                    foreach (var item in JsonData)
                    {
                        //主表修改
                        sql = @"IF NOT EXISTS(SELECT F_Account FROM Sys_SRM_User WHERE F_Account='{1}' AND F_Location='{4}')
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo060") + @"',16,1);
                                    RETURN
                                END

                                DECLARE @Status VARCHAR(10)
                                SELECT @Status=Status FROM ICSOApplyNeg WHERE ID='{3}' and WorkPoint='{4}'

                                IF (@Status IS NULL)
                                BEGIN
	                                RAISERROR('" + string.Format(language.GetNameByCode("WMSAPIInfo065"), "{3}") + @"',16,1);
                                    RETURN
                                END
                                ELSE IF (@Status!='1')
                                BEGIN
	                                RAISERROR('" + string.Format(language.GetNameByCode("WMSAPIInfo066"), "{3}") + @"',16,1);
                                    RETURN
                                END
                                update ICSOApplyNeg set WHCode='{0}',MUSER='{1}',MUSERName=(select F_RealName from Sys_SRM_User where F_Account='{1}' and F_Location='{4}'),MTIME='{2}' where ID='{3}' and WorkPoint='{4}' ";
                        sql = string.Format(sql, item.WHCode, item.User, item.MTime, item.id, item.WorkPoint);

                        if (!DBHelper.ExecuteNonQuery(sql, cmd))
                        {
                            throw new Exception(language.GetNameByCode("WMSAPIInfo016"));//"委外退料单信息修改失败!");
                        }
                        //var detail = item.detail.Where(a => a.DetailID.Length <= 0).Count();
                        //if (detail > 0)
                        //{
                        //    sql = @"SELECT OApplyNegCode FROM ICSOApplyNeg where ID='{0}' and WorkPoint='{1}'";
                        //    sql = string.Format(sql, item.id, item.WorkPoint);
                        //    Code = DBHelper.ExecuteScalar(sql, cmd).ToString();
                        //}
                        sql = @"SELECT OApplyNegCode FROM ICSOApplyNeg where ID='{0}' and WorkPoint='{1}'";
                        sql = string.Format(sql, item.id, item.WorkPoint);
                        Code = DBHelper.ExecuteScalar(sql, cmd).ToString();
                        foreach (var itemInfo in item.detail)
                        {
                            if (string.IsNullOrWhiteSpace(itemInfo.DetailID))
                            {
                                //创建子表
                                sql = @"INSERT INTO ICSOApplyNegDetail(ID,OApplyNegCode,Sequence,SourceDetailID,InvCode,
                                        Quantity,Amount,IssueNegQuantity,ExtensionID,MUSER,
                                        MUSERName,MTIME,WorkPoint,EATTRIBUTE1)
                                        VALUES (NEWID(),'{0}','{1}','{2}','{3}',
                                        '{4}','{5}',0,'{6}','{7}',
                                        (select F_RealName from Sys_SRM_User where F_Account='{7}' and F_Location='{8}'),SYSDATETIME(),'{8}','')";
                                sql = string.Format(sql, Code, itemInfo.Sequence, itemInfo.SourceDetailID, itemInfo.InvCode, itemInfo.Quantity, itemInfo.Amount, itemInfo.ExtensionID, item.User, item.WorkPoint);
                            }
                            else
                            {
                                //子表修改
                                sql = @"update ICSOApplyNegDetail set InvCode='{0}' ,Quantity='{1}',Amount='{2}',SourceDetailID='{3}',MUSER='{6}',MUSERName=(select F_RealName from Sys_SRM_User where F_Account='{6}' and F_Location='{5}')  where ID='{4}' and WorkPoint='{5}'";
                                sql = string.Format(sql, itemInfo.InvCode, itemInfo.Quantity, itemInfo.Amount, itemInfo.SourceDetailID, itemInfo.DetailID, item.WorkPoint, item.User);
                            }
                            if (!DBHelper.ExecuteNonQuery(sql, cmd))
                            {
                                throw new Exception(language.GetNameByCode("WMSAPIInfo017"));//"委外退料单子表信息修改失败!");
                            }
                            idss += "'" + itemInfo.DetailID + "',";
                        }
                        //校验退料数量是否超出领料数量
                        sql = CheckOutsourcingIssueDoc(item.Type, Code, item.WorkPoint, language);
                        DBHelper.ExecuteNonQuery(sql, cmd);
                        ids += "'" + item.id + "',";
                    }
                    sql = @"DELETE from ICSOApplyNegDetail  where OApplyNegCode ='{0}' and id not in ({1})";
                    sql = string.Format(sql, Code, idss.Substring(0, idss.Length - 1));
                    DBHelper.ExecuteNonQuery(sql, cmd);
                    if (string.IsNullOrWhiteSpace(ids))
                    {
                        throw new Exception(language.GetNameByCode("WMSAPIInfo006"));//"ID不能为空!"
                    }
                    #region 查询返回数据
                    sql = @"SELECT a.OApplyNegCode,
	                            c.WHCode,
	                            c.Memo,
	                            d.Name AS Status,
	                            a.Sequence,
	                            a.InvCode,
	                            inv.InvName,
	                            inv.InvStd,
	                            a.Quantity,
	                            inv.InvUnit,
	                            a.Amount,
	                            inv.AmountUnit,
	                            a.IssueNegQuantity,
	                            ext.ProjectCode,
	                            ext.BatchCode,
	                            ext.Version,
	                            ext.Brand,
	                            ext.cFree1,
	                            ext.cFree2,
	                            ext.cFree3,
	                            ext.cFree4,
	                            ext.cFree5,
	                            ext.cFree6,
	                            ext.cFree7,
	                            ext.cFree8,
	                            ext.cFree9,
	                            ext.cFree10,
	                            a.MUSER AS [User],
	                            a.MTIME AS [MTime]
                            FROM ICSOApplyNegDetail a 
                            INNER JOIN ICSOApplyNeg c ON a.OApplyNegCode=c.OApplyNegCode AND a.WorkPoint=c.WorkPoint
                            LEFT JOIN ICSType d ON d.TableCode='ICSOApplyNeg' AND d.ColumnCode='Status' AND c.Status=d.Code AND c.WorkPoint=d.WorkPoint 
                            INNER JOIN ICSExtension ext ON a.ExtensionID=ext.ID AND a.WorkPoint=ext.WorkPoint
                            INNER JOIN ICSInventory inv ON a.InvCode=inv.InvCode AND a.WorkPoint=inv.WorkPoint
                            WHERE c.ID IN ({0})";
                    sql = string.Format(sql, ids.Substring(0, ids.Length - 1));
                    DataTable data = DBHelper.SQlReturnData(sql, cmd);
                    #endregion
                    cmd.Transaction.Commit();
                    return data;
                }
                catch (Exception ex)
                {
                    if (cmd.Transaction != null)
                        cmd.Transaction.Rollback();
                    log.Error(ex.Message);
                    throw new Exception(ex.Message);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                    }
                    conn.Dispose();
                }
            }
        }


        /// <summary>
        /// 委外退料 修改
        /// </summary>
        /// <param name="JsonData"></param>
        /// <returns></returns>
        public static DataTable AMOutsourcingIssueDoNegativeApplyUpdate(List<ICSOApplyNeg> JsonData)
        {
            var language = LanguageHelper.GetName("WMSAPIInfo");
            if (JsonData.Count <= 0)
            {
                throw new Exception(language.GetNameByCode("WMSAPIInfo007"));//"传送数据为空!"
            }
            using (SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString))
            {
                conn.Open();
                SqlTransaction sqlTran = conn.BeginTransaction();
                SqlCommand cmd = new SqlCommand();
                cmd.Transaction = sqlTran;
                cmd.Connection = conn;
                cmd.CommandTimeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["TimeOut"]);
                try
                {
                    string sql = string.Empty;
                    string Code = string.Empty;
                    string ids = string.Empty;
                    string idss = string.Empty;
                    foreach (var item in JsonData)
                    {
                        //主表修改
                        sql = @"IF NOT EXISTS(SELECT F_Account FROM Sys_SRM_User WHERE F_Account='{1}' AND F_Location='{4}')
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo060") + @"',16,1);
                                    RETURN
                                END

                                DECLARE @Status VARCHAR(10)
                                SELECT @Status=Status FROM ICSOApplyNeg WHERE ID='{3}' and WorkPoint='{4}'

                                IF (@Status IS NULL)
                                BEGIN
	                                RAISERROR('" + string.Format(language.GetNameByCode("WMSAPIInfo065"), "{3}") + @"',16,1);
                                    RETURN
                                END
                                ELSE IF (@Status!='1')
                                BEGIN
	                                RAISERROR('" + string.Format(language.GetNameByCode("WMSAPIInfo066"), "{3}") + @"',16,1);
                                    RETURN
                                END
                                update ICSOApplyNeg set WHCode='{0}',MUSER='{1}',MUSERName=(select F_RealName from Sys_SRM_User where F_Account='{1}' and F_Location='{4}'),MTIME='{2}' where ID='{3}' and WorkPoint='{4}' ";
                        sql = string.Format(sql, item.WHCode, item.User, item.MTime, item.id, item.WorkPoint);

                        if (!DBHelper.ExecuteNonQuery(sql, cmd))
                        {
                            throw new Exception(language.GetNameByCode("WMSAPIInfo016"));//"委外退料单信息修改失败!");
                        }
                        //var detail = item.detail.Where(a => a.DetailID.Length <= 0).Count();
                        //if (detail > 0)
                        //{
                        //    sql = @"SELECT OApplyNegCode FROM ICSOApplyNeg where ID='{0}' and WorkPoint='{1}'";
                        //    sql = string.Format(sql, item.id, item.WorkPoint);
                        //    Code = DBHelper.ExecuteScalar(sql, cmd).ToString();
                        //}
                        sql = @"SELECT OApplyNegCode FROM ICSOApplyNeg where ID='{0}' and WorkPoint='{1}'";
                        sql = string.Format(sql, item.id, item.WorkPoint);
                        Code = DBHelper.ExecuteScalar(sql, cmd).ToString();
                        foreach (var itemInfo in item.detail)
                        {
                            string chekksql = @"select c.EATTRIBUTE1 ICSInventory c 
                                WHERE c.InvCode='{0}'AND c.WorkPoint='{1}' and c.AmountEnable='1'";
                            chekksql = string.Format(chekksql, itemInfo.InvCode, itemInfo.WorkPoint);
                            DataTable dta = DBHelper.SQlReturnData(chekksql, cmd);
                            if (dta.Rows.Count > 0)
                            {
                                itemInfo.Quantity = (itemInfo.Quantity * decimal.Parse(dta.Rows[0]["EATTRIBUTE1"].ToString()));
                            }
                            if (string.IsNullOrWhiteSpace(itemInfo.DetailID))
                            {
                                //创建子表
                                sql = @"INSERT INTO ICSOApplyNegDetail(ID,OApplyNegCode,Sequence,SourceDetailID,InvCode,
                                        Quantity,Amount,IssueNegQuantity,ExtensionID,MUSER,
                                        MUSERName,MTIME,WorkPoint,EATTRIBUTE1)
                                        VALUES (NEWID(),'{0}','{1}','{2}','{3}',
                                        '{4}','{5}',0,'{6}','{7}',
                                        (select F_RealName from Sys_SRM_User where F_Account='{7}' and F_Location='{8}'),SYSDATETIME(),'{8}','')";
                                sql = string.Format(sql, Code, itemInfo.Sequence, itemInfo.SourceDetailID, itemInfo.InvCode, itemInfo.Quantity, itemInfo.Amount, itemInfo.ExtensionID, item.User, item.WorkPoint);
                            }
                            else
                            {
                                //子表修改
                                sql = @"update ICSOApplyNegDetail set InvCode='{0}' ,Quantity='{1}',Amount='{2}',SourceDetailID='{3}',MUSER='{6}',MUSERName=(select F_RealName from Sys_SRM_User where F_Account='{6}' and F_Location='{5}')  where ID='{4}' and WorkPoint='{5}'";
                                sql = string.Format(sql, itemInfo.InvCode, itemInfo.Quantity, itemInfo.Amount, itemInfo.SourceDetailID, itemInfo.DetailID, item.WorkPoint, item.User);
                            }
                            if (!DBHelper.ExecuteNonQuery(sql, cmd))
                            {
                                throw new Exception(language.GetNameByCode("WMSAPIInfo017"));//"委外退料单子表信息修改失败!");
                            }
                            idss += "'" + itemInfo.DetailID + "',";
                        }
                        //校验退料数量是否超出领料数量
                        sql = CheckOutsourcingIssueDoc(item.Type, Code, item.WorkPoint, language);
                        DBHelper.ExecuteNonQuery(sql, cmd);
                        ids += "'" + item.id + "',";
                    }
                    sql = @"DELETE from ICSOApplyNegDetail  where OApplyNegCode ='{0}' and id not in ({1})";
                    sql = string.Format(sql, Code, idss.Substring(0, idss.Length - 1));
                    DBHelper.ExecuteNonQuery(sql, cmd);
                    if (string.IsNullOrWhiteSpace(ids))
                    {
                        throw new Exception(language.GetNameByCode("WMSAPIInfo006"));//"ID不能为空!"
                    }
                    #region 查询返回数据
                    sql = @"SELECT a.OApplyNegCode,
	                            c.WHCode,
	                            c.Memo,
	                            d.Name AS Status,
	                            a.Sequence,
	                            a.InvCode,
	                            inv.InvName,
	                            inv.InvStd,
	                            a.Quantity,
	                            inv.InvUnit,
	                            a.Amount,
	                            inv.AmountUnit,
	                            a.IssueNegQuantity,
	                            ext.ProjectCode,
	                            ext.BatchCode,
	                            ext.Version,
	                            ext.Brand,
	                            ext.cFree1,
	                            ext.cFree2,
	                            ext.cFree3,
	                            ext.cFree4,
	                            ext.cFree5,
	                            ext.cFree6,
	                            ext.cFree7,
	                            ext.cFree8,
	                            ext.cFree9,
	                            ext.cFree10,
	                            a.MUSER AS [User],
	                            a.MTIME AS [MTime]
                            FROM ICSOApplyNegDetail a 
                            INNER JOIN ICSOApplyNeg c ON a.OApplyNegCode=c.OApplyNegCode AND a.WorkPoint=c.WorkPoint
                            LEFT JOIN ICSType d ON d.TableCode='ICSOApplyNeg' AND d.ColumnCode='Status' AND c.Status=d.Code AND c.WorkPoint=d.WorkPoint 
                            INNER JOIN ICSExtension ext ON a.ExtensionID=ext.ID AND a.WorkPoint=ext.WorkPoint
                            INNER JOIN ICSInventory inv ON a.InvCode=inv.InvCode AND a.WorkPoint=inv.WorkPoint
                            WHERE c.ID IN ({0})";
                    sql = string.Format(sql, ids.Substring(0, ids.Length - 1));
                    DataTable data = DBHelper.SQlReturnData(sql, cmd);
                    #endregion
                    cmd.Transaction.Commit();
                    return data;
                }
                catch (Exception ex)
                {
                    if (cmd.Transaction != null)
                        cmd.Transaction.Rollback();
                    log.Error(ex.Message);
                    throw new Exception(ex.Message);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                    }
                    conn.Dispose();
                }
            }
        }

        /// <summary>
        /// 委外退料审核
        /// </summary>
        /// <param name="JsonData"></param>
        /// <returns></returns>
        public static DataTable OutsourcingIssueDoNegativeApplyApprove(List<ICSUser> JsonData)
        {
            string flag = string.Empty;
            var language = LanguageHelper.GetName("WMSAPIInfo");
            if (JsonData.Count <= 0)
            {
                throw new Exception(language.GetNameByCode("WMSAPIInfo007"));//"传送数据为空!"
            }
            using (SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString))
            {
                conn.Open();
                SqlTransaction sqlTran = conn.BeginTransaction();
                SqlCommand cmd = new SqlCommand();
                cmd.Transaction = sqlTran;
                cmd.Connection = conn;
                cmd.CommandTimeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["TimeOut"]);
                try
                {
                    string sql = string.Empty;
                    string ids = string.Empty;
                    foreach (var item in JsonData)
                    {
                        bool hasApproveFlag = JsonData.Any(u => u.ApproveFlag != null);
                        if (hasApproveFlag == true)
                        {
                            flag = item.ApproveFlag;
                        }
                        if (string.IsNullOrEmpty(item.ID))
                        {
                            throw new Exception(language.GetNameByCode("WMSAPIInfo018"));//"单据ID不能为空!");
                        }
                        if (string.IsNullOrEmpty(item.User))
                        {
                            throw new Exception(language.GetNameByCode("WMSAPIInfo019"));//"操作人不能为空!");
                        }
                        if (item.MTime <= new DateTime(2000, 1, 1))
                        {
                            throw new Exception(language.GetNameByCode("WMSAPIInfo020"));//"操作时间不能为空!");
                        }

                        if (flag.Equals("1")|| flag=="")
                        {
                            //获取单号
                            sql = @"DECLARE @Status VARCHAR(10)
                                SELECT @Status=Status FROM ICSOApplyNeg WHERE ID='{0}'

                                IF (@Status IS NULL)
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo065") + @"',16,1);
                                    RETURN
                                END
                                ELSE IF (@Status!='1')
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo066") + @"',16,1);
                                    RETURN
                                END
                             update ICSOApplyNeg set Status='2',MUSER='{1}',MTIME='{2}' where ID='{0}'";
                            sql = string.Format(sql, item.ID, item.User, item.MTime);
                            if (!DBHelper.ExecuteNonQuery(sql, cmd))
                            {
                                throw new Exception(language.GetNameByCode("WMSAPIInfo021"));//"委外退料申请单审核失败!");
                            }
                            ids += "'" + item.ID + "',";
                        }
                        else
                        {
                            //获取单号
                            sql = @"DECLARE @Status VARCHAR(10)
                                SELECT @Status=Status FROM ICSOApplyNeg WHERE ID='{0}'

                                IF (@Status IS NULL)
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo065") + @"',16,1);
                                    RETURN
                                END
                                ELSE IF (@Status!='2')
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo473") + @"',16,1);
                                    RETURN
                                END
                                IF EXISTS (select a.id from ICSOApplyNeg a 
                                left join ICSOApplyNegDetail b on a.OApplyNegCode=b.OApplyNegCode and a.WorkPoint=b.WorkPoint
                                where a.ID='{0}' and b.IssueNegQuantity>0)
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo474") + @"',16,1);
                                    RETURN
                                END
                             update ICSOApplyNeg set Status='1',MUSER='{1}',MTIME='{2}' where ID='{0}'";
                            sql = string.Format(sql, item.ID, item.User, item.MTime);
                            if (!DBHelper.ExecuteNonQuery(sql, cmd))
                            {
                                throw new Exception(language.GetNameByCode("WMSAPIInfo475"));//"委外退料申请单审核失败!");
                            }
                            ids += "'" + item.ID + "',";
                        }

                        
                    }
                    if (string.IsNullOrWhiteSpace(ids))
                    {
                        throw new Exception(language.GetNameByCode("WMSAPIInfo006"));//"ID不能为空!"
                    }
                    #region 查询返回数据
                    sql = @"SELECT a.OApplyNegCode,
	                            c.WHCode,
	                            c.Memo,
	                            d.Name AS Status,
	                            a.Sequence,
	                            a.InvCode,
	                            inv.InvName,
	                            inv.InvStd,
	                            a.Quantity,
	                            inv.InvUnit,
	                            a.Amount,
	                            inv.AmountUnit,
	                            a.IssueNegQuantity,
	                            ext.ProjectCode,
	                            ext.BatchCode,
	                            ext.Version,
	                            ext.Brand,
	                            ext.cFree1,
	                            ext.cFree2,
	                            ext.cFree3,
	                            ext.cFree4,
	                            ext.cFree5,
	                            ext.cFree6,
	                            ext.cFree7,
	                            ext.cFree8,
	                            ext.cFree9,
	                            ext.cFree10,
	                            a.MUSER AS [User],
	                            a.MTIME AS [MTime]
                            FROM ICSOApplyNegDetail a 
                            INNER JOIN ICSOApplyNeg c ON a.OApplyNegCode=c.OApplyNegCode AND a.WorkPoint=c.WorkPoint
                            LEFT JOIN ICSType d ON d.TableCode='ICSOApplyNeg' AND d.ColumnCode='Status' AND c.Status=d.Code AND c.WorkPoint=d.WorkPoint 
                            INNER JOIN ICSExtension ext ON a.ExtensionID=ext.ID AND a.WorkPoint=ext.WorkPoint
                            INNER JOIN ICSInventory inv ON a.InvCode=inv.InvCode AND a.WorkPoint=inv.WorkPoint
                            WHERE c.ID IN ({0})";
                    sql = string.Format(sql, ids.Substring(0, ids.Length - 1));
                    DataTable data = DBHelper.SQlReturnData(sql, cmd);
                    #endregion
                    cmd.Transaction.Commit();
                    return data;
                }
                catch (Exception ex)
                {
                    if (cmd.Transaction != null)
                        cmd.Transaction.Rollback();
                    log.Error(ex.Message);
                    throw new Exception(ex.Message);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                    }
                    conn.Dispose();
                }
            }
        }

        /// <summary>
        /// 委外到货
        /// </summary>
        /// <param name="JsonData"></param>
        /// <returns></returns>
        public static DataTable OutsourcingDeliveryNoticeCreate(List<ICSDeliveryNotice> JsonData)
        {
            var language = LanguageHelper.GetName("WMSAPIInfo");
            if (JsonData.Count <= 0)
            {
                throw new Exception(language.GetNameByCode("WMSAPIInfo007"));//"传送数据为空!"
            }
            using (SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString))
            {
                conn.Open();
                SqlTransaction sqlTran = conn.BeginTransaction();
                SqlCommand cmd = new SqlCommand();
                cmd.Transaction = sqlTran;
                cmd.Connection = conn;
                cmd.CommandTimeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["TimeOut"]);
                try
                {
                    string asncodes = string.Empty;
                    string sql = string.Empty;
                    foreach (var item in JsonData)
                    {
                        if (string.IsNullOrEmpty(item.OASNCode))
                        {
                            throw new Exception(language.GetNameByCode("WMSAPIInfo009"));//"送货单号不能为空!");
                        }

                        //获取单号
                        sql = @"IF EXISTS(SELECT a.ID FROM ICSODeliveryNotice a WHERE a.OASNCode='{0}' AND ODNType = '1' AND a.WorkPoint='{1}')
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo057") + @"',16,1);
                                    RETURN
                                END
                                DECLARE @Status VARCHAR(10)
                                SELECT @Status=Status FROM ICSOASN WHERE OASNCode='{0}' and WorkPoint='{1}'

                                IF (@Status IS NULL)
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo058") + @"',16,1);
                                    RETURN
                                END
                                ELSE IF (@Status!='2')
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo059") + @"',16,1);
                                    RETURN
                                END

                                DECLARE @MaxNO INT,@date varchar(20)='ODN'+SUBSTRING(CONVERT(varchar(8), GETDATE(), 112), 1, 8)
                                SELECT @MaxNO=SUBSTRING(MAX(ODNCode),LEN(@date)+1,LEN(MAX(ODNCode))-LEN(@date))+1 FROM ICSODeliveryNotice 
                                    WHERE SUBSTRING(ODNCode, 1, LEN(@date))=@date
                                IF @MaxNO IS NULL
                                BEGIN
	                                SELECT @date+'00001' AS Code
                                END
                                ELSE
                                BEGIN
	                                SELECT @date+REPLICATE('0',5-LEN(@MaxNO))+CAST(@MaxNO AS nvarchar(10))  AS Code
                                END ";
                        sql = string.Format(sql, item.OASNCode, item.WorkPoint);
                        string Code = DBHelper.ExecuteScalar(sql, cmd).ToString();
                        //修改送货单到货数量
                        foreach (var itemInfo in item.detail)
                        {
                            sql = @"UPDATE ICSOASNDetail SET ODNQuantity=ISNULL(ODNQuantity, 0)+'{2}'
                                    WHERE LotNo='{0}' AND WorkPoint='{1}'";
                            sql = string.Format(sql, itemInfo.LotNo, item.WorkPoint, itemInfo.Quantity);

                            if (!DBHelper.ExecuteNonQuery(sql, cmd))
                            {
                                throw new Exception(language.GetNameByCode("WMSAPIInfo010")); //"委外送货单子表信息更新失败!");
                            }
                        }
                        //创建到货单信息
                        sql = @"IF NOT EXISTS(SELECT F_Account FROM Sys_SRM_User WHERE F_Account='{1}' AND F_Location='{2}')
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo060") + @"',16,1);
                                    RETURN
                                END

                                INSERT INTO ICSODeliveryNotice(ID,ODNCode,Sequence,VenCode,DepCode,
                                    ODNType,InvCode,Quantity,Amount,RCVQuantity,
                                    UnitPrice,Currency,Status,CreatePerson,CreateDateTime,
                                    OOID,OODetailID,ODNID,ODNDetailID,ExtensionID,
                                    MUSER,MUSERName,MTIME,WorkPoint,EATTRIBUTE1,OASNCode)
                                    SELECT NEWID(),'{0}',row_number() OVER (ORDER BY b.InvCode),d.VenCode,d.DepCode,
                                    '1',b.InvCode,SUM(a.ODNQuantity),'0','0',
                                    d.UnitPrice,d.Currency,'2',e.F_Account,GETDATE(),
                                    d.OOID,d.OODetailID,newid(),newid(),b.ExtensionID,
                                    e.F_Account,e.F_RealName,GETDATE(),a.WorkPoint,'',a.OASNCode
                                FROM ICSOASNDetail a
                                INNER JOIN ICSInventoryLot b ON a.LotNo=b.LotNo AND a.WorkPoint=b.WorkPoint
                                INNER JOIN ICSInventoryLotDetail c ON b.LotNo=c.LotNo AND b.WorkPoint=c.WorkPoint
                                INNER JOIN ICSOutsourcingOrder d ON c.TransCode=d.OOCode AND c.TransSequence=d.Sequence AND c.WorkPoint=d.WorkPoint
                                INNER JOIN Sys_SRM_User e ON e.F_Account='{1}' AND e.F_Location='{2}'
                                WHERE a.OASNCode='{3}' AND a.WorkPoint='{2}'
                                GROUP BY d.OOID,d.OODetailID,d.VenCode,d.UnitPrice,d.Currency,d.DepCode,b.ExtensionID,b.InvCode,a.OASNCode,e.F_Account,e.F_RealName,a.WorkPoint";
                        sql = string.Format(sql, Code, item.User, item.WorkPoint, item.OASNCode);

                        if (!DBHelper.ExecuteNonQuery(sql, cmd))
                        {
                            throw new Exception(language.GetNameByCode("WMSAPIInfo011")); //"到货单信息创建失败!");
                        }
                        if (!DBHelper.IsU9())
                            ICSOutsourcingService.OutsourcingDeliveryNoticeERP(Code, item.WorkPoint, cmd, language);
                        asncodes += "'" + item.OASNCode + item.WorkPoint + "',";
                    }
                    if (string.IsNullOrWhiteSpace(asncodes))
                    {
                        throw new Exception(language.GetNameByCode("WMSAPIInfo009"));//"请传入送货单信息!");
                    }
                    #region 查询返回数据
                    sql = @"SELECT
	                            n.OOCode,
	                            n.Sequence AS OOSequence,
	                            a.OASNCode,
	                            a.ODNCode,
	                            a.Sequence,
	                            a.VenCode,
	                            a.DepCode,
	                            a.InvCode,
	                            inv.InvName,
	                            inv.InvStd,
	                            a.Quantity,
	                            inv.InvUnit,
	                            a.Amount,
	                            inv.AmountUnit,
	                            a.RCVQuantity,
	                            a.UnitPrice,
	                            a.Currency,
	                            a.OOID,
	                            a.OODetailID,
	                            a.ODNID,
	                            a.ODNDetailID,
	                            ext.ProjectCode,
	                            ext.BatchCode,
	                            ext.Version,
	                            ext.Brand,
	                            ext.cFree1,
	                            ext.cFree2,
	                            ext.cFree3,
	                            ext.cFree4,
	                            ext.cFree5,
	                            ext.cFree6,
	                            ext.cFree7,
	                            ext.cFree8,
	                            ext.cFree9,
	                            ext.cFree10,
	                            a.MUSER AS [User],
	                            a.MTIME AS [MTime]
                            FROM ICSODeliveryNotice a
                            INNER JOIN ICSOutsourcingOrder n ON a.OOID =n.OOID AND a.OODetailID=n.OODetailID AND a.WorkPoint=n.WorkPoint
                            INNER JOIN ICSExtension ext ON a.ExtensionID=ext.ID AND a.WorkPoint=ext.WorkPoint
                            INNER JOIN ICSInventory inv ON a.InvCode=inv.InvCode AND a.WorkPoint=inv.WorkPoint
                            WHERE a.OASNCode+a.WorkPoint IN ({0})";
                    sql = string.Format(sql, asncodes.Substring(0, asncodes.Length - 1));
                    DataTable data = DBHelper.SQlReturnData(sql, cmd);
                    #endregion
                    cmd.Transaction.Commit();
                    return data;
                }
                catch (Exception ex)
                {
                    if (cmd.Transaction != null)
                        cmd.Transaction.Rollback();
                    log.Error(ex.Message);
                    throw new Exception(ex.Message);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                    }
                    conn.Dispose();
                }
            }
        }

        /// <summary>
        /// 委外拒收
        /// </summary>
        /// <param name="JsonData"></param>
        /// <returns></returns>
        public static DataTable OutsourcingRejectDocCreate(List<ICSDeliveryNotice> JsonData)
        {
            var language = LanguageHelper.GetName("WMSAPIInfo");
            if (JsonData.Count <= 0)
            {
                throw new Exception(language.GetNameByCode("WMSAPIInfo007"));//"传送数据为空!"
            }
            using (SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString))
            {
                conn.Open();
                SqlTransaction sqlTran = conn.BeginTransaction();
                SqlCommand cmd = new SqlCommand();
                cmd.Transaction = sqlTran;
                cmd.Connection = conn;
                cmd.CommandTimeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["TimeOut"]);
                try
                {
                    string lots = string.Empty;
                    string sql = string.Empty;
                    foreach (var item in JsonData)
                    {
                        if (string.IsNullOrEmpty(item.ODNCode))
                        {
                            throw new Exception(language.GetNameByCode("WMSAPIInfo012"));//"到货单号不能为空!");
                        }

                        //获取单号
                        sql = @"DECLARE @Status VARCHAR(10)
                                SELECT @Status=Status FROM ICSODeliveryNotice WHERE ODNCode='{0}' and ODNType='1'  and WorkPoint='{1}'

                                IF (@Status IS NULL)
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo061") + @"',16,1);
                                    RETURN
                                END
                                ELSE IF (@Status!='2')
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo062") + @"',16,1);
                                    RETURN
                                END

                                DECLARE @MaxNO INT,@date varchar(20)='ORJT'+SUBSTRING(CONVERT(varchar(8), GETDATE(), 112), 1, 8)
                                SELECT @MaxNO=SUBSTRING(MAX(ODNCode),LEN(@date)+1,LEN(MAX(ODNCode))-LEN(@date))+1 FROM ICSODeliveryNotice 
                                    WHERE SUBSTRING(ODNCode, 1, LEN(@date))=@date
                                IF @MaxNO IS NULL
                                BEGIN
	                                SELECT @date+'00001' AS Code
                                END
                                ELSE
                                BEGIN
	                                SELECT @date+REPLICATE('0',5-LEN(@MaxNO))+CAST(@MaxNO AS nvarchar(10))  AS Code
                                END ";
                        sql = string.Format(sql, item.ODNCode, item.WorkPoint);
                        string Code = DBHelper.ExecuteScalar(sql, cmd).ToString();
                        //修改送货单到货数量
                        foreach (var itemInfo in item.detail)
                        {
                            sql = @"IF NOT EXISTS(SELECT F_Account FROM Sys_SRM_User WHERE F_Account='{3}' AND F_Location='{2}')
                                    BEGIN
	                                    RAISERROR('" + string.Format(language.GetNameByCode("WMSAPIInfo060"), "{3}") + @"',16,1);
                                        RETURN
                                    END

                                    IF EXISTS(SELECT a.ID FROM ICSODeliveryNotice a WHERE a.EATTRIBUTE1='{1}' AND ODNType = '3' AND a.WorkPoint='{2}')
                                    BEGIN
	                                    RAISERROR('" + language.GetNameByCode("WMSAPIInfo063") + @"',16,1);
                                        RETURN
                                    END
                                    INSERT INTO ICSODeliveryNotice(ID,ODNCode,Sequence,VenCode,DepCode,
                                    ODNType,InvCode,Quantity,Amount,RCVQuantity,
                                    UnitPrice,Currency,Status,CreatePerson,CreateDateTime,
                                    OOID,OODetailID,ODNID,ODNDetailID,ExtensionID,
                                    MUSER,MUSERName,MTIME,WorkPoint,EATTRIBUTE1,OASNCode)
                                    SELECT NEWID(),'{4}',  '{11}', '{5}',  '{6}',
                                    '3',d.InvCode,'{7}', '{8}', 0, 
                                    '{9}', '{10}', '2', e.F_Account, SYSDATETIME(), 
                                    a.ODNID,a.ODNDetailID, '0', '0', a.ExtensionID,
                                    e.F_Account,e.F_RealName, SYSDATETIME(), a.WorkPoint, b.LOTNO,''
                                    FROM ICSODeliveryNotice a
                                    INNER JOIN ICSOASNDetail b ON a.OASNCode=b.OASNCode  AND a.WorkPoint=b.WorkPoint
                                    INNER JOIN ICSInventoryLot d ON b.LotNo=d.LotNo AND a.InvCode=d.InvCode AND b.WorkPoint=d.WorkPoint
                                    INNER JOIN ICSInventoryLotDetail m on d.LotNo=m.LotNo and d.WorkPoint=m.WorkPoint
                                    INNER JOIN ICSOutsourcingOrder n ON m.TransCode =n.OOCode AND m.TransSequence=n.Sequence AND a.OODetailID=n.OODetailID AND m.WorkPoint=n.WorkPoint
                                    INNER JOIN ICSInspection h ON h.LotNo=b.LotNo  AND h.WorkPoint=b.WorkPoint
                                    INNER JOIN Sys_SRM_User e ON e.F_Account='{3}' AND e.F_Location='{2}'
                                    WHERE a.ODNCode='{0}' and b.LOTNO='{1}' AND a.WorkPoint='{2}'";
                            sql = string.Format(sql, item.ODNCode, itemInfo.LotNo, item.WorkPoint, item.User, Code, item.VenCode, item.DepCode, itemInfo.Quantity, itemInfo.Amount, itemInfo.UnitPrice, itemInfo.Currency, itemInfo.Sequence);

                            if (!DBHelper.ExecuteNonQuery(sql, cmd))
                            {
                                throw new Exception(language.GetNameByCode("WMSAPIInfo013"));//"拒收单创建失败!");
                            }
                            lots += "'" + itemInfo.LotNo + item.WorkPoint + "',";
                        }
                        ICSOutsourcingService.OutsourcingRejectDocInNewERP(item.ODNCode, Code, item.WorkPoint, cmd, language);
                    }
                    if (string.IsNullOrWhiteSpace(lots))
                    {
                        throw new Exception(language.GetNameByCode("WMSAPIInfo005"));//"请传入条码信息!");
                    }
                    #region 查询返回数据
                    sql = @"SELECT
	                            n.ODNCode,
	                            n.Sequence,
	                            a.ODNCode AS RJTCode,
	                            a.Sequence AS RJTSequence,
	                            a.VenCode,
	                            a.DepCode,
	                            a.InvCode,
	                            inv.InvName,
	                            inv.InvStd,
	                            a.Quantity,
	                            inv.InvUnit,
	                            a.Amount,
	                            inv.AmountUnit,
	                            a.RCVQuantity,
	                            a.UnitPrice,
	                            a.Currency,
	                            a.OOID,
	                            a.OODetailID,
	                            a.ODNID,
	                            a.ODNDetailID,
	                            ext.ProjectCode,
	                            ext.BatchCode,
	                            ext.Version,
	                            ext.Brand,
	                            ext.cFree1,
	                            ext.cFree2,
	                            ext.cFree3,
	                            ext.cFree4,
	                            ext.cFree5,
	                            ext.cFree6,
	                            ext.cFree7,
	                            ext.cFree8,
	                            ext.cFree9,
	                            ext.cFree10,
	                            a.MUSER AS [User],
	                            a.MTIME AS [MTime]
                            FROM ICSODeliveryNotice a
                            INNER JOIN ICSODeliveryNotice n ON a.OOID =n.ODNID AND a.OODetailID=n.ODNDetailID AND a.WorkPoint=n.WorkPoint
                            INNER JOIN ICSExtension ext ON a.ExtensionID=ext.ID AND a.WorkPoint=ext.WorkPoint
                            INNER JOIN ICSInventory inv ON a.InvCode=inv.InvCode AND a.WorkPoint=inv.WorkPoint
                            WHERE a.EATTRIBUTE1+a.WorkPoint IN ({0})";
                    sql = string.Format(sql, lots.Substring(0, lots.Length - 1));
                    DataTable data = DBHelper.SQlReturnData(sql, cmd);
                    #endregion
                    cmd.Transaction.Commit();
                    return data;
                }
                catch (Exception ex)
                {
                    if (cmd.Transaction != null)
                        cmd.Transaction.Rollback();
                    log.Error(ex.Message);
                    throw new Exception(ex.Message);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                    }
                    conn.Dispose();
                }
            }
        }

        /// <summary>
        /// 无订单委外拒收
        /// </summary>
        /// <param name="JsonData"></param>
        /// <returns></returns>
        public static DataTable OutsourcingRejectDocNoTransCreate(List<ICSDeliveryNotice> JsonData)
        {
            var language = LanguageHelper.GetName("WMSAPIInfo");
            if (JsonData.Count <= 0)
            {
                throw new Exception(language.GetNameByCode("WMSAPIInfo007"));//"传送数据为空!"
            }
            using (SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString))
            {
                conn.Open();
                SqlTransaction sqlTran = conn.BeginTransaction();
                SqlCommand cmd = new SqlCommand();
                cmd.Transaction = sqlTran;
                cmd.Connection = conn;
                cmd.CommandTimeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["TimeOut"]);
                try
                {
                    string lots = string.Empty;
                    string sql = string.Empty;
                    foreach (var item in JsonData)
                    {
                        if (string.IsNullOrEmpty(item.ODNCode))
                        {
                            throw new Exception(language.GetNameByCode("WMSAPIInfo012"));//"到货单号不能为空!");
                        }

                        //获取单号
                        sql = @"DECLARE @Status VARCHAR(10)
                                SELECT @Status=Status FROM ICSODeliveryNotice WHERE ODNCode='{0}' and ODNType='1'  and WorkPoint='{1}'

                                IF (@Status IS NULL)
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo061") + @"',16,1);
                                    RETURN
                                END
                                ELSE IF (@Status!='2')
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo062") + @"',16,1);
                                    RETURN
                                END

                                DECLARE @MaxNO INT,@date varchar(20)='ORJT'+SUBSTRING(CONVERT(varchar(8), GETDATE(), 112), 1, 8)
                                SELECT @MaxNO=SUBSTRING(MAX(ODNCode),LEN(@date)+1,LEN(MAX(ODNCode))-LEN(@date))+1 FROM ICSODeliveryNotice 
                                    WHERE SUBSTRING(ODNCode, 1, LEN(@date))=@date
                                IF @MaxNO IS NULL
                                BEGIN
	                                SELECT @date+'00001' AS Code
                                END
                                ELSE
                                BEGIN
	                                SELECT @date+REPLICATE('0',5-LEN(@MaxNO))+CAST(@MaxNO AS nvarchar(10))  AS Code
                                END ";
                        sql = string.Format(sql, item.ODNCode, item.WorkPoint);
                        string Code = DBHelper.ExecuteScalar(sql, cmd).ToString();
                        //修改送货单到货数量
                        foreach (var itemInfo in item.detail)
                        {
                            sql = @"IF NOT EXISTS(SELECT F_Account FROM Sys_SRM_User WHERE F_Account='{3}' AND F_Location='{2}')
                                    BEGIN
	                                    RAISERROR('" + string.Format(language.GetNameByCode("WMSAPIInfo060"), "{3}") + @"',16,1);
                                        RETURN
                                    END

                                    IF EXISTS(SELECT a.ID FROM ICSODeliveryNotice a WHERE a.EATTRIBUTE1='{1}' AND ODNType = '3' AND a.WorkPoint='{2}')
                                    BEGIN
	                                    RAISERROR('" + language.GetNameByCode("WMSAPIInfo063") + @"',16,1);
                                        RETURN
                                    END
                                    INSERT INTO ICSODeliveryNotice(ID,ODNCode,Sequence,VenCode,DepCode,
                                    ODNType,InvCode,Quantity,Amount,RCVQuantity,
                                    UnitPrice,Currency,Status,CreatePerson,CreateDateTime,
                                    OOID,OODetailID,ODNID,ODNDetailID,ExtensionID,
                                    MUSER,MUSERName,MTIME,WorkPoint,EATTRIBUTE1,OASNCode)
                                    SELECT NEWID(),'{4}',  '{11}', '{5}',  '{6}',
                                    '3',d.InvCode,'{7}', '{8}', 0, 
                                    '{9}', '{10}', '2', e.F_Account, SYSDATETIME(), 
                                    a.ODNID,a.ODNDetailID, '0', '0', a.ExtensionID,
                                    e.F_Account,e.F_RealName, SYSDATETIME(), a.WorkPoint, d.LOTNO,''
                                    FROM ICSODeliveryNotice a
									INNER JOIN ICSInventoryLotDetail m on  a.ODNCode=m.TransCode and a.Sequence=m.TransSequence and a.WorkPoint=m.WorkPoint
                                    INNER JOIN ICSInventoryLot d ON m.LotNo=d.LotNo AND a.InvCode=d.InvCode AND a.WorkPoint=d.WorkPoint
                                    INNER JOIN ICSInspection h ON h.LotNo=d.LotNo  AND h.WorkPoint=a.WorkPoint
                                    INNER JOIN Sys_SRM_User e ON e.F_Account='{3}' AND e.F_Location='{2}'
                                    WHERE a.ODNCode='{0}' and d.LOTNO='{1}' AND a.WorkPoint='{2}'";
                            sql = string.Format(sql, item.ODNCode, itemInfo.LotNo, item.WorkPoint, item.User, Code, item.VenCode, item.DepCode, itemInfo.Quantity, itemInfo.Amount, itemInfo.UnitPrice, itemInfo.Currency, itemInfo.Sequence);
                            
                            if (!DBHelper.ExecuteNonQuery(sql, cmd))
                            {
                                throw new Exception(language.GetNameByCode("WMSAPIInfo013"));//"拒收单创建失败!");
                            }
                            lots += "'" + itemInfo.LotNo + item.WorkPoint + "',";
                        }
                        ICSOutsourcingService.OutsourcingRejectDocInNewERP(item.ODNCode, Code, item.WorkPoint, cmd, language);
                    }
                    if (string.IsNullOrWhiteSpace(lots))
                    {
                        throw new Exception(language.GetNameByCode("WMSAPIInfo005"));//"请传入条码信息!");
                    }
                    #region 查询返回数据
                    sql = @"SELECT
	                            n.ODNCode,
	                            n.Sequence,
	                            a.ODNCode AS RJTCode,
	                            a.Sequence AS RJTSequence,
	                            a.VenCode,
	                            a.DepCode,
	                            a.InvCode,
	                            inv.InvName,
	                            inv.InvStd,
	                            a.Quantity,
	                            inv.InvUnit,
	                            a.Amount,
	                            inv.AmountUnit,
	                            a.RCVQuantity,
	                            a.UnitPrice,
	                            a.Currency,
	                            a.OOID,
	                            a.OODetailID,
	                            a.ODNID,
	                            a.ODNDetailID,
	                            ext.ProjectCode,
	                            ext.BatchCode,
	                            ext.Version,
	                            ext.Brand,
	                            ext.cFree1,
	                            ext.cFree2,
	                            ext.cFree3,
	                            ext.cFree4,
	                            ext.cFree5,
	                            ext.cFree6,
	                            ext.cFree7,
	                            ext.cFree8,
	                            ext.cFree9,
	                            ext.cFree10,
	                            a.MUSER AS [User],
	                            a.MTIME AS [MTime]
                            FROM ICSODeliveryNotice a
                            INNER JOIN ICSODeliveryNotice n ON a.OOID =n.ODNID AND a.OODetailID=n.ODNDetailID AND a.WorkPoint=n.WorkPoint
                            INNER JOIN ICSExtension ext ON a.ExtensionID=ext.ID AND a.WorkPoint=ext.WorkPoint
                            INNER JOIN ICSInventory inv ON a.InvCode=inv.InvCode AND a.WorkPoint=inv.WorkPoint
                            WHERE a.EATTRIBUTE1+a.WorkPoint IN ({0})";
                    sql = string.Format(sql, lots.Substring(0, lots.Length - 1));
                    DataTable data = DBHelper.SQlReturnData(sql, cmd);
                    #endregion
                    cmd.Transaction.Commit();
                    return data;
                }
                catch (Exception ex)
                {
                    if (cmd.Transaction != null)
                        cmd.Transaction.Rollback();
                    log.Error(ex.Message);
                    throw new Exception(ex.Message);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                    }
                    conn.Dispose();
                }
            }
        }

        #endregion

        #region 生产

        /// <summary>
        /// 生产退料 新建
        /// </summary>
        /// <param name="JsonData"></param>
        /// <returns></returns>
        public static DataTable MOIssueDocNegativeApplyCreate(List<ICSMOApplyNeg> JsonData)
        {
            var language = LanguageHelper.GetName("WMSAPIInfo");
            if (JsonData.Count <= 0)
            {
                throw new Exception(language.GetNameByCode("WMSAPIInfo007"));//"传送数据为空!"
            }
            using (SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString))
            {
                conn.Open();
                SqlTransaction sqlTran = conn.BeginTransaction();
                SqlCommand cmd = new SqlCommand();
                cmd.Transaction = sqlTran;
                cmd.Connection = conn;
                cmd.CommandTimeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["TimeOut"]);
                try
                {
                    string codes = string.Empty;
                    string sql = string.Empty;

                    foreach (var item in JsonData)
                    {
                        //获取单号
                        sql = @"DECLARE @MaxNO INT,@date varchar(20)='MOIA'+SUBSTRING(CONVERT(varchar(8), GETDATE(), 112), 1, 8)
                                SELECT @MaxNO=SUBSTRING(MAX(ApplyNegCode),LEN(@date)+1,LEN(MAX(ApplyNegCode))-LEN(@date))+1 FROM ICSMOApplyNeg 
                                    WHERE SUBSTRING(ApplyNegCode, 1, LEN(@date))=@date
                                IF @MaxNO IS NULL
                                BEGIN
	                                SELECT @date+'00001' AS Code
                                END
                                ELSE
                                BEGIN
	                                SELECT @date+REPLICATE('0',5-LEN(@MaxNO))+CAST(@MaxNO AS nvarchar(10))  AS Code
                                END ";
                        string Code = DBHelper.ExecuteScalar(sql, cmd).ToString();
                        //创建主表
                        sql = @"IF NOT EXISTS(SELECT F_Account FROM Sys_SRM_User WHERE F_Account='{2}' AND F_Location='{4}')
                                BEGIN
	                                RAISERROR('" + string.Format(language.GetNameByCode("WMSAPIInfo060"), "{2}") + @"',16,1);
                                    RETURN
                                END

                                INSERT INTO ICSMOApplyNeg(ID,ApplyNegCode,WHCode,Status,Type,Memo,CreatePerson,CreateDateTime,MUSER,MUSERName,MTIME,WorkPoint,EATTRIBUTE1)
                             VALUES (NEWID(),'{0}','{1}','1','{5}','','{2}','{3}','{2}',(select F_RealName from Sys_SRM_User where F_Account='{2}' and F_Location='{4}'),'{3}','{4}','')";
                        sql = string.Format(sql, Code, item.WHCode, item.User, item.MTime, item.WorkPoint, item.Type);

                        if (!DBHelper.ExecuteNonQuery(sql, cmd))
                        {
                            throw new Exception(language.GetNameByCode("WMSAPIInfo022"));//"生产退料单信息创建失败!");
                        }
                        HashSet<string> addedItems = new HashSet<string>();

                        foreach (var itemInfo in item.detail)
                        {
                            // 创建子表
                            sql = @"INSERT INTO ICSMOApplyNegDetail(ID,ApplyNegCode,Sequence,SourceDetailID,InvCode,
                                    Quantity,Amount,IssueNegQuantity,ExtensionID,MUSER,
                                    MUSERName,MTIME,WorkPoint,EATTRIBUTE1)
                                    VALUES (NEWID(),'{0}','{1}','{2}','{3}',
                                    '{4}','{5}',0,'{6}','{7}',
                                    (select F_RealName from Sys_SRM_User where F_Account='{7}' and F_Location='{8}'),SYSDATETIME(),'{8}','')";
                            sql = string.Format(sql, Code, itemInfo.Sequence, itemInfo.SourceDetailID, itemInfo.InvCode, itemInfo.Quantity, itemInfo.Amount, itemInfo.ExtensionID, item.User, item.WorkPoint);

                            if (!DBHelper.ExecuteNonQuery(sql, cmd))
                            {
                                throw new Exception(language.GetNameByCode("WMSAPIInfo023"));//"生产退料单子表信息创建失败!");
                            }

                            string key = itemInfo.Sequence + "~" + itemInfo.InvCode;

                            if (addedItems.Contains(key))
                            {
                                throw new Exception("子件不可重复添加!");
                            }

                            addedItems.Add(key);
                        }
                        //校验退料数量是否超出领料数量
                        sql = CheckMOIssueDoc(item.Type, item.ID, item.WorkPoint, language);
                        DBHelper.ExecuteNonQuery(sql, cmd);
                        codes += "'" + Code + item.WorkPoint + "',";
                    }
                    if (string.IsNullOrWhiteSpace(codes))
                    {
                        throw new Exception(language.GetNameByCode("WMSAPIInfo001"));//"单据号不能为空!"
                    }
                    #region 查询返回数据
                    sql = @"SELECT a.ApplyNegCode,
	                            c.WHCode,
	                            c.Memo,
	                            d.Name AS Status,
	                            a.Sequence,
	                            a.InvCode,
	                            inv.InvName,
	                            inv.InvStd,
	                            a.Quantity,
	                            inv.InvUnit,
	                            a.Amount,
	                            inv.AmountUnit,
	                            a.IssueNegQuantity,
	                            ext.ProjectCode,
	                            ext.BatchCode,
	                            ext.Version,
	                            ext.Brand,
	                            ext.cFree1,
	                            ext.cFree2,
	                            ext.cFree3,
	                            ext.cFree4,
	                            ext.cFree5,
	                            ext.cFree6,
	                            ext.cFree7,
	                            ext.cFree8,
	                            ext.cFree9,
	                            ext.cFree10,
	                            a.MUSER AS [User],
	                            a.MTIME AS [MTime]
                            FROM ICSMOApplyNegDetail a 
                            INNER JOIN ICSMOApplyNeg c ON a.ApplyNegCode=c.ApplyNegCode AND a.WorkPoint=c.WorkPoint
                            LEFT JOIN ICSType d ON d.TableCode='ICSMOApplyNeg' AND d.ColumnCode='Status' AND c.Status=d.Code AND c.WorkPoint=d.WorkPoint
                            INNER JOIN ICSExtension ext ON a.ExtensionID=ext.ID AND a.WorkPoint=ext.WorkPoint
                            INNER JOIN ICSInventory inv ON a.InvCode=inv.InvCode AND a.WorkPoint=inv.WorkPoint
                            WHERE a.ApplyNegCode+a.WorkPoint IN ({0})";
                    sql = string.Format(sql, codes.Substring(0, codes.Length - 1));
                    DataTable data = DBHelper.SQlReturnData(sql, cmd);
                    #endregion
                    cmd.Transaction.Commit();
                    return data;
                }
                catch (Exception ex)
                {
                    if (cmd.Transaction != null)
                        cmd.Transaction.Rollback();
                    log.Error(ex.Message);
                    throw new Exception(ex.Message);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                    }
                    conn.Dispose();
                }
            }
        }

        /// <summary>
        /// 生产退料 新建
        /// </summary>
        /// <param name="JsonData"></param>
        /// <returns></returns>
        public static DataTable AMMOIssueDocNegativeApplyCreate(List<ICSMOApplyNeg> JsonData)
        {
            var language = LanguageHelper.GetName("WMSAPIInfo");
            if (JsonData.Count <= 0)
            {
                throw new Exception(language.GetNameByCode("WMSAPIInfo007"));//"传送数据为空!"
            }
            using (SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString))
            {
                conn.Open();
                SqlTransaction sqlTran = conn.BeginTransaction();
                SqlCommand cmd = new SqlCommand();
                cmd.Transaction = sqlTran;
                cmd.Connection = conn;
                cmd.CommandTimeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["TimeOut"]);
                try
                {
                    string codes = string.Empty;
                    string sql = string.Empty;

                    foreach (var item in JsonData)
                    {
                        //获取单号
                        sql = @"DECLARE @MaxNO INT,@date varchar(20)='MOIA'+SUBSTRING(CONVERT(varchar(8), GETDATE(), 112), 1, 8)
                                SELECT @MaxNO=SUBSTRING(MAX(ApplyNegCode),LEN(@date)+1,LEN(MAX(ApplyNegCode))-LEN(@date))+1 FROM ICSMOApplyNeg 
                                    WHERE SUBSTRING(ApplyNegCode, 1, LEN(@date))=@date
                                IF @MaxNO IS NULL
                                BEGIN
	                                SELECT @date+'00001' AS Code
                                END
                                ELSE
                                BEGIN
	                                SELECT @date+REPLICATE('0',5-LEN(@MaxNO))+CAST(@MaxNO AS nvarchar(10))  AS Code
                                END ";
                        string Code = DBHelper.ExecuteScalar(sql, cmd).ToString();
                        //创建主表
                        sql = @"IF NOT EXISTS(SELECT F_Account FROM Sys_SRM_User WHERE F_Account='{2}' AND F_Location='{4}')
                                BEGIN
	                                RAISERROR('" + string.Format(language.GetNameByCode("WMSAPIInfo060"), "{2}") + @"',16,1);
                                    RETURN
                                END

                                INSERT INTO ICSMOApplyNeg(ID,ApplyNegCode,WHCode,Status,Type,Memo,CreatePerson,CreateDateTime,MUSER,MUSERName,MTIME,WorkPoint,EATTRIBUTE1)
                             VALUES (NEWID(),'{0}','{1}','1','{5}','','{2}','{3}','{2}',(select F_RealName from Sys_SRM_User where F_Account='{2}' and F_Location='{4}'),'{3}','{4}','')";
                        sql = string.Format(sql, Code, item.WHCode, item.User, item.MTime, item.WorkPoint, item.Type);

                        if (!DBHelper.ExecuteNonQuery(sql, cmd))
                        {
                            throw new Exception(language.GetNameByCode("WMSAPIInfo022"));//"生产退料单信息创建失败!");
                        }
                        HashSet<string> addedItems = new HashSet<string>();

                        foreach (var itemInfo in item.detail)
                        {
                            string chekksql = @"select c.EATTRIBUTE1 ICSInventory c 
                                WHERE c.InvCode='{0}'AND c.WorkPoint='{1}' and c.AmountEnable='1'";
                            chekksql = string.Format(chekksql, itemInfo.InvCode, itemInfo.WorkPoint);
                            DataTable dta = DBHelper.SQlReturnData(chekksql, cmd);
                            if (dta.Rows.Count > 0)
                            {
                                itemInfo.Quantity = (decimal.Parse(itemInfo.Quantity) * decimal.Parse(dta.Rows[0]["EATTRIBUTE1"].ToString())).ToString();
                            }
                            // 创建子表
                            sql = @"INSERT INTO ICSMOApplyNegDetail(ID,ApplyNegCode,Sequence,SourceDetailID,InvCode,
                                    Quantity,Amount,IssueNegQuantity,ExtensionID,MUSER,
                                    MUSERName,MTIME,WorkPoint,EATTRIBUTE1)
                                    VALUES (NEWID(),'{0}','{1}','{2}','{3}',
                                    '{4}','{5}',0,'{6}','{7}',
                                    (select F_RealName from Sys_SRM_User where F_Account='{7}' and F_Location='{8}'),SYSDATETIME(),'{8}','')";
                            sql = string.Format(sql, Code, itemInfo.Sequence, itemInfo.SourceDetailID, itemInfo.InvCode, itemInfo.Quantity, itemInfo.Amount, itemInfo.ExtensionID, item.User, item.WorkPoint);

                            if (!DBHelper.ExecuteNonQuery(sql, cmd))
                            {
                                throw new Exception(language.GetNameByCode("WMSAPIInfo023"));//"生产退料单子表信息创建失败!");
                            }

                            string key = itemInfo.Sequence + "~" + itemInfo.InvCode;

                            if (addedItems.Contains(key))
                            {
                                throw new Exception("子件不可重复添加!");
                            }

                            addedItems.Add(key);
                        }
                        //校验退料数量是否超出领料数量
                        sql = CheckMOIssueDoc(item.Type, item.ID, item.WorkPoint, language);
                        DBHelper.ExecuteNonQuery(sql, cmd);
                        codes += "'" + Code + item.WorkPoint + "',";
                    }
                    if (string.IsNullOrWhiteSpace(codes))
                    {
                        throw new Exception(language.GetNameByCode("WMSAPIInfo001"));//"单据号不能为空!"
                    }
                    #region 查询返回数据
                    sql = @"SELECT a.ApplyNegCode,
	                            c.WHCode,
	                            c.Memo,
	                            d.Name AS Status,
	                            a.Sequence,
	                            a.InvCode,
	                            inv.InvName,
	                            inv.InvStd,
	                            a.Quantity,
	                            inv.InvUnit,
	                            a.Amount,
	                            inv.AmountUnit,
	                            a.IssueNegQuantity,
	                            ext.ProjectCode,
	                            ext.BatchCode,
	                            ext.Version,
	                            ext.Brand,
	                            ext.cFree1,
	                            ext.cFree2,
	                            ext.cFree3,
	                            ext.cFree4,
	                            ext.cFree5,
	                            ext.cFree6,
	                            ext.cFree7,
	                            ext.cFree8,
	                            ext.cFree9,
	                            ext.cFree10,
	                            a.MUSER AS [User],
	                            a.MTIME AS [MTime]
                            FROM ICSMOApplyNegDetail a 
                            INNER JOIN ICSMOApplyNeg c ON a.ApplyNegCode=c.ApplyNegCode AND a.WorkPoint=c.WorkPoint
                            LEFT JOIN ICSType d ON d.TableCode='ICSMOApplyNeg' AND d.ColumnCode='Status' AND c.Status=d.Code AND c.WorkPoint=d.WorkPoint
                            INNER JOIN ICSExtension ext ON a.ExtensionID=ext.ID AND a.WorkPoint=ext.WorkPoint
                            INNER JOIN ICSInventory inv ON a.InvCode=inv.InvCode AND a.WorkPoint=inv.WorkPoint
                            WHERE a.ApplyNegCode+a.WorkPoint IN ({0})";
                    sql = string.Format(sql, codes.Substring(0, codes.Length - 1));
                    DataTable data = DBHelper.SQlReturnData(sql, cmd);
                    #endregion
                    cmd.Transaction.Commit();
                    return data;
                }
                catch (Exception ex)
                {
                    if (cmd.Transaction != null)
                        cmd.Transaction.Rollback();
                    log.Error(ex.Message);
                    throw new Exception(ex.Message);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                    }
                    conn.Dispose();
                }
            }
        }

        private static string CheckMOIssueDoc(string Type, string ID, string WorkPoint, Dictionary<string, string> language)
        {
            string sql = string.Empty;
            if (Type == "1")
            {
                sql = @"DECLARE @PickID VARCHAR(10)
                        SELECT @PickID=b.PickID
                        FROM ICSMOApplyNegDetail a 
                        INNER JOIN ICSMOPick b ON a.SourceDetailID=b.PickID AND a.WorkPoint=b.WorkPoint
                        INNER JOIN ICSMOApplyNeg c ON a.ApplyNegCode=c.ApplyNegCode AND a.WorkPoint=c.WorkPoint
                        WHERE c.Type='{2}' AND a.WorkPoint='{1}'
                            AND a.SourceDetailID IN (SELECT a.SourceDetailID
                                FROM ICSMOApplyNegDetail a 
                                INNER JOIN ICSMOApplyNeg c ON a.ApplyNegCode=c.ApplyNegCode AND a.WorkPoint=c.WorkPoint
                                WHERE c.ApplyNegCode='{0}' AND c.Type='{2}' AND a.WorkPoint='{1}')
                        GROUP BY b.PickID
                        HAVING MAX(b.Quantity)<SUM(a.Quantity)

                        IF (@PickID IS NOT NULL)
                        BEGIN
	                        DECLARE @InvCode VARCHAR(100)
	                        SELECT @InvCode='" + language.GetNameByCode("WMSAPIInfo064") + @"' FROM ICSMOPick WHERE PickID=@PickID AND WorkPoint='{1}'
	                        RAISERROR(@InvCode,16,1);
	                        RETURN
                        END ";
            }
            else if (Type == "2")
            {
                sql = @"DECLARE @ApplyDetailID VARCHAR(10)
                        SELECT @ApplyDetailID=b.ApplyDetailID
                        FROM ICSMOApplyNegDetail a 
                        INNER JOIN ICSMOApply b ON a.SourceDetailID=b.ApplyDetailID AND a.WorkPoint=b.WorkPoint
                        INNER JOIN ICSMOApplyNeg c ON a.ApplyNegCode=c.ApplyNegCode AND a.WorkPoint=c.WorkPoint
                        WHERE c.Type='{2}' AND a.WorkPoint='{1}'
                            AND a.SourceDetailID IN (SELECT a.SourceDetailID
                                FROM ICSMOApplyNegDetail a 
                                INNER JOIN ICSMOApplyNeg c ON a.ApplyNegCode=c.ApplyNegCode AND a.WorkPoint=c.WorkPoint
                                WHERE c.ApplyNegCode='{0}' AND c.Type='{2}' AND a.WorkPoint='{1}')
                        GROUP BY b.ApplyDetailID
                        HAVING MAX(b.Quantity)<SUM(a.Quantity)

                        IF (@ApplyDetailID IS NOT NULL)
                        BEGIN
	                        DECLARE @InvCode VARCHAR(100)
	                        SELECT @InvCode='" + language.GetNameByCode("WMSAPIInfo064") + @"' FROM ICSMOApply WHERE ApplyDetailID=@ApplyDetailID AND WorkPoint='{1}'
	                        RAISERROR(@InvCode,16,1);
	                        RETURN
                        END ";
            }
            else if (Type == "3")
            {
                sql = @"DECLARE @IssueDetailID VARCHAR(10)
                        SELECT @IssueDetailID=b.IssueDetailID
                        FROM ICSMOApplyNegDetail a 
                        INNER JOIN ICSMOIssue b ON a.SourceDetailID=b.IssueDetailID AND a.WorkPoint=b.WorkPoint
                        INNER JOIN ICSMOApplyNeg c ON a.ApplyNegCode=c.ApplyNegCode AND a.WorkPoint=c.WorkPoint
                        WHERE c.Type='{2}' AND a.WorkPoint='{1}'
                            AND a.SourceDetailID IN (SELECT a.SourceDetailID
                                FROM ICSMOApplyNegDetail a 
                                INNER JOIN ICSMOApplyNeg c ON a.ApplyNegCode=c.ApplyNegCode AND a.WorkPoint=c.WorkPoint
                                WHERE c.ApplyNegCode='{0}' AND c.Type='{2}' AND a.WorkPoint='{1}')
                        GROUP BY b.IssueDetailID
                        HAVING MAX(b.Quantity)<SUM(a.Quantity)

                        IF (@IssueDetailID IS NOT NULL)
                        BEGIN
	                        DECLARE @InvCode VARCHAR(100)
	                        SELECT @InvCode='" + language.GetNameByCode("WMSAPIInfo064") + @"' FROM ICSMOIssue WHERE IssueDetailID=@IssueDetailID AND WorkPoint='{1}'
	                        RAISERROR(@InvCode,16,1);
	                        RETURN
                        END ";
            }
            else
            {
                throw new Exception(language.GetNameByCode("WMSAPIInfo003"));//"类型不符!");
            }
            sql = string.Format(sql, ID, WorkPoint, Type);
            return sql;
        }
        /// <summary>
        /// 生产退料 修改
        /// </summary>
        /// <param name="JsonData"></param>
        /// <returns></returns>
        public static DataTable MOIssueDocNegativeApplyUpdate(List<ICSMOApplyNeg> JsonData)
        {
            var language = LanguageHelper.GetName("WMSAPIInfo");
            if (JsonData.Count <= 0)
            {
                throw new Exception(language.GetNameByCode("WMSAPIInfo007"));//"传送数据为空!"
            }
            using (SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString))
            {
                conn.Open();
                SqlTransaction sqlTran = conn.BeginTransaction();
                SqlCommand cmd = new SqlCommand();
                cmd.Transaction = sqlTran;
                cmd.Connection = conn;
                cmd.CommandTimeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["TimeOut"]);
                try
                {
                    string sql = string.Empty;
                    string Code = string.Empty;
                    string ids = string.Empty;
                    string idss = string.Empty;
                    foreach (var item in JsonData)
                    {
                        //主表修改
                        sql = @"IF NOT EXISTS(SELECT F_Account FROM Sys_SRM_User WHERE F_Account='{1}' AND F_Location='{4}')
                                BEGIN
	                                RAISERROR('" + string.Format(language.GetNameByCode("WMSAPIInfo060"), "{1}") + @"',16,1);
                                    RETURN
                                END

                                DECLARE @Status VARCHAR(10)
                                SELECT @Status=Status FROM ICSMOApplyNeg WHERE ID='{3}' and WorkPoint='{4}'

                                IF (@Status IS NULL)
                                BEGIN
	                                RAISERROR('" + string.Format(language.GetNameByCode("WMSAPIInfo065"), "{3}") + @"',16,1);
                                    RETURN
                                END
                                ELSE IF (@Status!='1')
                                BEGIN
	                                RAISERROR('" + string.Format(language.GetNameByCode("WMSAPIInfo066"), "{3}") + @"',16,1);
                                    RETURN
                                END
                                update ICSMOApplyNeg set WHCode='{0}',MUSER='{1}',MUSERName=(select F_RealName from Sys_SRM_User where F_Account='{1}' and F_Location='{4}'),MTIME='{2}' where ID='{3}' and WorkPoint='{4}' ";
                        sql = string.Format(sql, item.WHCode, item.User, item.MTime, item.ID, item.WorkPoint);

                        if (!DBHelper.ExecuteNonQuery(sql, cmd))
                        {
                            throw new Exception(language.GetNameByCode("WMSAPIInfo024"));//"生产退料单信息修改失败!");
                        }
                        //var detail = item.detail.Where(a => a.DetailID.Length <= 0).Count();
                        //if (detail > 0)
                        //{
                        //    sql = @"SELECT ApplyNegCode FROM ICSMOApplyNeg where ID='{0}' and WorkPoint='{1}'";
                        //    sql = string.Format(sql, item.ID, item.WorkPoint);
                        //    Code = DBHelper.ExecuteScalar(sql, cmd).ToString();
                        //}
                        sql = @"SELECT ApplyNegCode FROM ICSMOApplyNeg where ID='{0}' and WorkPoint='{1}'";
                        sql = string.Format(sql, item.ID, item.WorkPoint);
                        Code = DBHelper.ExecuteScalar(sql, cmd).ToString();
                        foreach (var itemInfo in item.detail)
                        {
                            if (string.IsNullOrWhiteSpace(itemInfo.DetailID))
                            {
                                //创建子表
                                sql = @"INSERT INTO ICSMOApplyNegDetail(ID,ApplyNegCode,Sequence,SourceDetailID,InvCode,Quantity,Amount,IssueNegQuantity,ExtensionID,MUSER,
                                        MUSERName,MTIME,WorkPoint,EATTRIBUTE1)
                                        VALUES (NEWID(),'{0}','{1}','{2}','{3}',
                                        '{4}','{5}',0,'{6}','{7}',
                                        (select F_RealName from Sys_SRM_User where F_Account='{7}' and F_Location='{8}'),SYSDATETIME(),'{8}','')";
                                sql = string.Format(sql, Code, itemInfo.Sequence, itemInfo.SourceDetailID, itemInfo.InvCode, itemInfo.Quantity, itemInfo.Amount, itemInfo.ExtensionID, item.User, item.WorkPoint);
                            }
                            else
                            {
                                //子表修改
                                sql = @"update ICSMOApplyNegDetail set InvCode='{0}' ,Quantity='{1}',Amount='{2}',SourceDetailID='{3}',MUSER='{6}',MUSERName=(select F_RealName from Sys_SRM_User where F_Account='{6}' and F_Location='{5}')  where ID='{4}' and WorkPoint='{5}'";
                                sql = string.Format(sql, itemInfo.InvCode, itemInfo.Quantity, itemInfo.Amount, itemInfo.SourceDetailID, itemInfo.DetailID, item.WorkPoint, item.User);
                            }
                            if (!DBHelper.ExecuteNonQuery(sql, cmd))
                            {
                                throw new Exception(language.GetNameByCode("WMSAPIInfo025"));//"生产退料单子表信息修改失败!");
                            }
                            idss += "'" + itemInfo.DetailID + "',";
                        }
                        //校验退料数量是否超出领料数量
                        sql = CheckMOIssueDoc(item.Type, item.ID, item.WorkPoint, language);
                        DBHelper.ExecuteNonQuery(sql, cmd);
                        ids += "'" + item.ID + "',";
                    }

                    sql = @"DELETE from ICSMOApplyNegDetail  where ApplyNegCode ='{0}' and id not in ({1})";
                    sql = string.Format(sql, Code, idss.Substring(0, idss.Length - 1));
                    DBHelper.ExecuteNonQuery(sql, cmd);
                    if (string.IsNullOrWhiteSpace(ids))
                    {
                        throw new Exception(language.GetNameByCode("WMSAPIInfo006"));//"ID不能为空!"
                    }
                    #region 查询返回数据
                    sql = @"SELECT a.ApplyNegCode,
	                            c.WHCode,
	                            c.Memo,
	                            d.Name AS Status,
	                            a.Sequence,
	                            a.InvCode,
	                            inv.InvName,
	                            inv.InvStd,
	                            a.Quantity,
	                            inv.InvUnit,
	                            a.Amount,
	                            inv.AmountUnit,
	                            a.IssueNegQuantity,
	                            ext.ProjectCode,
	                            ext.BatchCode,
	                            ext.Version,
	                            ext.Brand,
	                            ext.cFree1,
	                            ext.cFree2,
	                            ext.cFree3,
	                            ext.cFree4,
	                            ext.cFree5,
	                            ext.cFree6,
	                            ext.cFree7,
	                            ext.cFree8,
	                            ext.cFree9,
	                            ext.cFree10,
	                            a.MUSER AS [User],
	                            a.MTIME AS [MTime]
                            FROM ICSMOApplyNegDetail a 
                            INNER JOIN ICSMOApplyNeg c ON a.ApplyNegCode=c.ApplyNegCode AND a.WorkPoint=c.WorkPoint
                            LEFT JOIN ICSType d ON d.TableCode='ICSMOApplyNeg' AND d.ColumnCode='Status' AND c.Status=d.Code AND c.WorkPoint=d.WorkPoint
                            INNER JOIN ICSExtension ext ON a.ExtensionID=ext.ID AND a.WorkPoint=ext.WorkPoint
                            INNER JOIN ICSInventory inv ON a.InvCode=inv.InvCode AND a.WorkPoint=inv.WorkPoint
                            WHERE c.ID IN ({0})";
                    sql = string.Format(sql, ids.Substring(0, ids.Length - 1));
                    DataTable data = DBHelper.SQlReturnData(sql, cmd);
                    #endregion
                    cmd.Transaction.Commit();
                    return data;
                }
                catch (Exception ex)
                {
                    if (cmd.Transaction != null)
                        cmd.Transaction.Rollback();
                    log.Error(ex.Message);
                    throw new Exception(ex.Message);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                    }
                    conn.Dispose();
                }
            }
        }


        /// <summary>
        /// 生产退料 修改
        /// </summary>
        /// <param name="JsonData"></param>
        /// <returns></returns>
        public static DataTable AMMOIssueDocNegativeApplyUpdate(List<ICSMOApplyNeg> JsonData)
        {
            var language = LanguageHelper.GetName("WMSAPIInfo");
            if (JsonData.Count <= 0)
            {
                throw new Exception(language.GetNameByCode("WMSAPIInfo007"));//"传送数据为空!"
            }
            using (SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString))
            {
                conn.Open();
                SqlTransaction sqlTran = conn.BeginTransaction();
                SqlCommand cmd = new SqlCommand();
                cmd.Transaction = sqlTran;
                cmd.Connection = conn;
                cmd.CommandTimeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["TimeOut"]);
                try
                {
                    string sql = string.Empty;
                    string Code = string.Empty;
                    string ids = string.Empty;
                    string idss = string.Empty;
                    foreach (var item in JsonData)
                    {
                        //主表修改
                        sql = @"IF NOT EXISTS(SELECT F_Account FROM Sys_SRM_User WHERE F_Account='{1}' AND F_Location='{4}')
                                BEGIN
	                                RAISERROR('" + string.Format(language.GetNameByCode("WMSAPIInfo060"), "{1}") + @"',16,1);
                                    RETURN
                                END

                                DECLARE @Status VARCHAR(10)
                                SELECT @Status=Status FROM ICSMOApplyNeg WHERE ID='{3}' and WorkPoint='{4}'

                                IF (@Status IS NULL)
                                BEGIN
	                                RAISERROR('" + string.Format(language.GetNameByCode("WMSAPIInfo065"), "{3}") + @"',16,1);
                                    RETURN
                                END
                                ELSE IF (@Status!='1')
                                BEGIN
	                                RAISERROR('" + string.Format(language.GetNameByCode("WMSAPIInfo066"), "{3}") + @"',16,1);
                                    RETURN
                                END
                                update ICSMOApplyNeg set WHCode='{0}',MUSER='{1}',MUSERName=(select F_RealName from Sys_SRM_User where F_Account='{1}' and F_Location='{4}'),MTIME='{2}' where ID='{3}' and WorkPoint='{4}' ";
                        sql = string.Format(sql, item.WHCode, item.User, item.MTime, item.ID, item.WorkPoint);

                        if (!DBHelper.ExecuteNonQuery(sql, cmd))
                        {
                            throw new Exception(language.GetNameByCode("WMSAPIInfo024"));//"生产退料单信息修改失败!");
                        }
                        //var detail = item.detail.Where(a => a.DetailID.Length <= 0).Count();
                        //if (detail > 0)
                        //{
                        //    sql = @"SELECT ApplyNegCode FROM ICSMOApplyNeg where ID='{0}' and WorkPoint='{1}'";
                        //    sql = string.Format(sql, item.ID, item.WorkPoint);
                        //    Code = DBHelper.ExecuteScalar(sql, cmd).ToString();
                        //}
                        sql = @"SELECT ApplyNegCode FROM ICSMOApplyNeg where ID='{0}' and WorkPoint='{1}'";
                        sql = string.Format(sql, item.ID, item.WorkPoint);
                        Code = DBHelper.ExecuteScalar(sql, cmd).ToString();
                        foreach (var itemInfo in item.detail)
                        {
                            string chekksql = @"select c.EATTRIBUTE1 ICSInventory c 
                                WHERE c.InvCode='{0}'AND c.WorkPoint='{1}' and c.AmountEnable='1'";
                            chekksql = string.Format(chekksql, itemInfo.InvCode, itemInfo.WorkPoint);
                            DataTable dta = DBHelper.SQlReturnData(chekksql, cmd);
                            if (dta.Rows.Count > 0)
                            {
                                itemInfo.Quantity = (decimal.Parse(itemInfo.Quantity) * decimal.Parse(dta.Rows[0]["EATTRIBUTE1"].ToString())).ToString();
                            }
                            if (string.IsNullOrWhiteSpace(itemInfo.DetailID))
                            {
                                //创建子表
                                sql = @"INSERT INTO ICSMOApplyNegDetail(ID,ApplyNegCode,Sequence,SourceDetailID,InvCode,Quantity,Amount,IssueNegQuantity,ExtensionID,MUSER,
                                        MUSERName,MTIME,WorkPoint,EATTRIBUTE1)
                                        VALUES (NEWID(),'{0}','{1}','{2}','{3}',
                                        '{4}','{5}',0,'{6}','{7}',
                                        (select F_RealName from Sys_SRM_User where F_Account='{7}' and F_Location='{8}'),SYSDATETIME(),'{8}','')";
                                sql = string.Format(sql, Code, itemInfo.Sequence, itemInfo.SourceDetailID, itemInfo.InvCode, itemInfo.Quantity, itemInfo.Amount, itemInfo.ExtensionID, item.User, item.WorkPoint);
                            }
                            else
                            {
                                //子表修改
                                sql = @"update ICSMOApplyNegDetail set InvCode='{0}' ,Quantity='{1}',Amount='{2}',SourceDetailID='{3}',MUSER='{6}',MUSERName=(select F_RealName from Sys_SRM_User where F_Account='{6}' and F_Location='{5}')  where ID='{4}' and WorkPoint='{5}'";
                                sql = string.Format(sql, itemInfo.InvCode, itemInfo.Quantity, itemInfo.Amount, itemInfo.SourceDetailID, itemInfo.DetailID, item.WorkPoint, item.User);
                            }
                            if (!DBHelper.ExecuteNonQuery(sql, cmd))
                            {
                                throw new Exception(language.GetNameByCode("WMSAPIInfo025"));//"生产退料单子表信息修改失败!");
                            }
                            idss += "'" + itemInfo.DetailID + "',";
                        }
                        //校验退料数量是否超出领料数量
                        sql = CheckMOIssueDoc(item.Type, item.ID, item.WorkPoint, language);
                        DBHelper.ExecuteNonQuery(sql, cmd);
                        ids += "'" + item.ID + "',";
                    }

                    sql = @"DELETE from ICSMOApplyNegDetail  where ApplyNegCode ='{0}' and id not in ({1})";
                    sql = string.Format(sql, Code, idss.Substring(0, idss.Length - 1));
                    DBHelper.ExecuteNonQuery(sql, cmd);
                    if (string.IsNullOrWhiteSpace(ids))
                    {
                        throw new Exception(language.GetNameByCode("WMSAPIInfo006"));//"ID不能为空!"
                    }
                    #region 查询返回数据
                    sql = @"SELECT a.ApplyNegCode,
	                            c.WHCode,
	                            c.Memo,
	                            d.Name AS Status,
	                            a.Sequence,
	                            a.InvCode,
	                            inv.InvName,
	                            inv.InvStd,
	                            a.Quantity,
	                            inv.InvUnit,
	                            a.Amount,
	                            inv.AmountUnit,
	                            a.IssueNegQuantity,
	                            ext.ProjectCode,
	                            ext.BatchCode,
	                            ext.Version,
	                            ext.Brand,
	                            ext.cFree1,
	                            ext.cFree2,
	                            ext.cFree3,
	                            ext.cFree4,
	                            ext.cFree5,
	                            ext.cFree6,
	                            ext.cFree7,
	                            ext.cFree8,
	                            ext.cFree9,
	                            ext.cFree10,
	                            a.MUSER AS [User],
	                            a.MTIME AS [MTime]
                            FROM ICSMOApplyNegDetail a 
                            INNER JOIN ICSMOApplyNeg c ON a.ApplyNegCode=c.ApplyNegCode AND a.WorkPoint=c.WorkPoint
                            LEFT JOIN ICSType d ON d.TableCode='ICSMOApplyNeg' AND d.ColumnCode='Status' AND c.Status=d.Code AND c.WorkPoint=d.WorkPoint
                            INNER JOIN ICSExtension ext ON a.ExtensionID=ext.ID AND a.WorkPoint=ext.WorkPoint
                            INNER JOIN ICSInventory inv ON a.InvCode=inv.InvCode AND a.WorkPoint=inv.WorkPoint
                            WHERE c.ID IN ({0})";
                    sql = string.Format(sql, ids.Substring(0, ids.Length - 1));
                    DataTable data = DBHelper.SQlReturnData(sql, cmd);
                    #endregion
                    cmd.Transaction.Commit();
                    return data;
                }
                catch (Exception ex)
                {
                    if (cmd.Transaction != null)
                        cmd.Transaction.Rollback();
                    log.Error(ex.Message);
                    throw new Exception(ex.Message);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                    }
                    conn.Dispose();
                }
            }
        }

        /// <summary>
        /// 生产退料审核
        /// </summary>
        /// <param name="JsonData"></param>
        /// <returns></returns>
        public static DataTable MOIssueDocNegativeApplyApprove(List<ICSUser> JsonData)
        {
            string flag = string.Empty;
            var language = LanguageHelper.GetName("WMSAPIInfo");
            if (JsonData.Count <= 0)
            {
                throw new Exception(language.GetNameByCode("WMSAPIInfo007"));//"传送数据为空!"
            }
            using (SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString))
            {
                conn.Open();
                SqlTransaction sqlTran = conn.BeginTransaction();
                SqlCommand cmd = new SqlCommand();
                cmd.Transaction = sqlTran;
                cmd.Connection = conn;
                cmd.CommandTimeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["TimeOut"]);
                try
                {
                    string sql = string.Empty;
                    string ids = string.Empty;
                    foreach (var item in JsonData)
                    {
                        bool hasApproveFlag = JsonData.Any(u => u.ApproveFlag != null);
                        if (hasApproveFlag == true)
                        {
                            flag = item.ApproveFlag;
                        }
                        if (string.IsNullOrEmpty(item.ID))
                        {
                            throw new Exception(language.GetNameByCode("WMSAPIInfo018"));//"单据ID不能为空!");
                        }
                        if (string.IsNullOrEmpty(item.User))
                        {
                            throw new Exception(language.GetNameByCode("WMSAPIInfo019"));//"操作人不能为空!");
                        }
                        if (item.MTime <= new DateTime(2000, 1, 1))
                        {
                            throw new Exception(language.GetNameByCode("WMSAPIInfo020"));//"操作时间不能为空!");
                        }
                        if (flag.Equals("1")|| flag=="")
                        {
                            //获取单号
                            sql = @"DECLARE @Status VARCHAR(10)
                                SELECT @Status=Status FROM ICSMOApplyNeg WHERE ID='{0}'

                                IF (@Status IS NULL)
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo065") + @"',16,1);
                                    RETURN
                                END
                                ELSE IF (@Status!='1')
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo066") + @"',16,1);
                                    RETURN
                                END
                             update ICSMOApplyNeg set Status='2',MUSER='{1}',MTIME='{2}' where ID='{0}'";
                            sql = string.Format(sql, item.ID, item.User, item.MTime);
                            if (!DBHelper.ExecuteNonQuery(sql, cmd))
                            {
                                throw new Exception(language.GetNameByCode("WMSAPIInfo026"));//"生产退料申请单审核失败!");
                            }
                            ids += "'" + item.ID + "',";
                        }
                        else
                        {
                            //获取单号
                            sql = @"DECLARE @Status VARCHAR(10)
                                SELECT @Status=Status FROM ICSMOApplyNeg WHERE ID='{0}'

                                IF (@Status IS NULL)
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo065") + @"',16,1);
                                    RETURN
                                END
                                ELSE IF (@Status!='2')
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo473") + @"',16,1);
                                    RETURN
                                END
                                IF EXISTS (select a.id from ICSMOApplyNeg a 
                                left join ICSMOApplyNegDetail b on a.ApplyNegCode=b.ApplyNegCode and a.WorkPoint=b.WorkPoint
                                where a.ID='{0}' and b.IssueNegQuantity>0)
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo474") + @"',16,1);
                                    RETURN
                                END
                             update ICSMOApplyNeg set Status='1',MUSER='{1}',MTIME='{2}' where ID='{0}'";
                            sql = string.Format(sql, item.ID, item.User, item.MTime);
                            if (!DBHelper.ExecuteNonQuery(sql, cmd))
                            {
                                throw new Exception(language.GetNameByCode("WMSAPIInfo475"));//"生产退料申请单弃审失败!");
                            }
                            ids += "'" + item.ID + "',";
                        }
                        
                    }
                    if (string.IsNullOrWhiteSpace(ids))
                    {
                        throw new Exception(language.GetNameByCode("WMSAPIInfo006"));//"ID不能为空!"
                    }
                    #region 查询返回数据
                    sql = @"SELECT a.ApplyNegCode,
	                            c.WHCode,
	                            c.Memo,
	                            d.Name AS Status,
	                            a.Sequence,
	                            a.InvCode,
	                            inv.InvName,
	                            inv.InvStd,
	                            a.Quantity,
	                            inv.InvUnit,
	                            a.Amount,
	                            inv.AmountUnit,
	                            a.IssueNegQuantity,
	                            ext.ProjectCode,
	                            ext.BatchCode,
	                            ext.Version,
	                            ext.Brand,
	                            ext.cFree1,
	                            ext.cFree2,
	                            ext.cFree3,
	                            ext.cFree4,
	                            ext.cFree5,
	                            ext.cFree6,
	                            ext.cFree7,
	                            ext.cFree8,
	                            ext.cFree9,
	                            ext.cFree10,
	                            a.MUSER AS [User],
	                            a.MTIME AS [MTime]
                            FROM ICSMOApplyNegDetail a 
                            INNER JOIN ICSMOApplyNeg c ON a.ApplyNegCode=c.ApplyNegCode AND a.WorkPoint=c.WorkPoint
                            LEFT JOIN ICSType d ON d.TableCode='ICSMOApplyNeg' AND d.ColumnCode='Status' AND c.Status=d.Code AND c.WorkPoint=d.WorkPoint
                            INNER JOIN ICSExtension ext ON a.ExtensionID=ext.ID AND a.WorkPoint=ext.WorkPoint
                            INNER JOIN ICSInventory inv ON a.InvCode=inv.InvCode AND a.WorkPoint=inv.WorkPoint
                            WHERE c.ID IN ({0})";
                    sql = string.Format(sql, ids.Substring(0, ids.Length - 1));
                    DataTable data = DBHelper.SQlReturnData(sql, cmd);
                    #endregion
                    cmd.Transaction.Commit();
                    return data;
                }
                catch (Exception ex)
                {
                    if (cmd.Transaction != null)
                        cmd.Transaction.Rollback();
                    log.Error(ex.Message);
                    throw new Exception(ex.Message);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                    }
                    conn.Dispose();
                }
            }
        }
        #endregion




        #region 一步调拨(调拨申请单)
        /// <summary>
        /// 一步调拨(调拨申请单)
        /// </summary>
        /// <param name="JsonData"></param>
        /// <returns></returns>
        public static DataTable OneStepTransferApplicationIn(List<TransferApplication> JsonData)
        {
            var language = LanguageHelper.GetName("WMSAPIInfo");
            if (JsonData.Count <= 0)
            {
                throw new Exception(language.GetNameByCode("WMSAPIInfo007"));//"传送数据为空!"
            }
            DataTable printTable = new DataTable();
            using (SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString))
            {
                conn.Open();
                SqlTransaction sqlTran = conn.BeginTransaction();
                SqlCommand cmd = new SqlCommand();
                cmd.Transaction = sqlTran;
                cmd.Connection = conn;
                cmd.CommandTimeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["TimeOut"]);
                string BusinessCode = string.Empty;
                try
                {
                    string sql = string.Empty;
                    string Identification = Guid.NewGuid().ToString();
                    foreach (var item in JsonData)
                    {
                        if (string.IsNullOrEmpty(item.TransCode))
                        {
                            throw new Exception(language.GetNameByCode("WMSAPIInfo027"));//"调拨申请单号不能为空!");
                        }

                        string[] trans = item.TransCode.Split('~');
                        string MergeID = "";
                        if (trans.Length == 2)
                        {
                            MergeID = trans[0];
                            item.TransCode = trans[1];
                        }
                        //验证信息
                        sql = @"DECLARE @Status VARCHAR(10)
                                SELECT @Status=Status FROM ICSTransferApplication WHERE TransferNO='{0}' and WorkPoint='{1}' AND Type = '1'

                                IF (@Status IS NULL)
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo067") + @"',16,1);
                                    RETURN
                                END
                                ELSE IF (@Status!='1')
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo068") + @"',16,1);
                                    RETURN
                                END";
                        sql = string.Format(sql, item.TransCode, item.WorkPoint);
                        DBHelper.ExecuteNonQuery(sql, cmd);

                        foreach (var itemInfo in item.Detail)
                        {
                            //验证仓库库位信息
                            sql = @"IF NOT EXISTS(SELECT a.ID FROM ICSWareHouse a WHERE a.WarehouseCode='{0}' AND a.WorkPoint='{1}')
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo069") + @"',16,1);
                                    RETURN
                                END
                                IF NOT EXISTS(SELECT a.ID FROM ICSLocation a WHERE a.LocationCode='{2}' AND a.WorkPoint='{1}')
                                BEGIN
	                                RAISERROR('" + string.Format(language.GetNameByCode("WMSAPIInfo070"), "{2}") + @"',16,1);
                                    RETURN
                                END
                                IF NOT EXISTS(SELECT a.ID 
                                FROM ICSWareHouse a 
                                INNER JOIN ICSLocation b ON a.ID=b.WHID AND a.WorkPoint=b.WorkPoint
                                WHERE a.WarehouseCode='{0}' AND a.WorkPoint='{1}' AND b.LocationCode='{2}')
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo071") + @"',16,1);
                                    RETURN
                                END";
                            sql = string.Format(sql, itemInfo.WarehouseCode, item.WorkPoint, itemInfo.LocationCode);
                            DBHelper.ExecuteNonQuery(sql, cmd);

                            BusinessCode = TransTypeEnum.StepTransferApplicationIn.GetDescription<DBValue>();
                            //更新源头单据信息
                            ICSWareHouseService.OneStepTransferApplicationIn(item.TransCode, item.TransSequence, item.WorkPoint, itemInfo.CurrentQuantity, cmd, language);

                            //更新条码信息
                            printTable = ICSWareHouseLotInfoService.WareHouseLotInfoTransfer(Identification, item.TransCode, item.TransSequence, itemInfo.WarehouseCode, itemInfo.LocationCode,
                                itemInfo.LotNo, itemInfo.CurrentQuantity, item.User, item.WorkPoint, "14", TransTypeEnum.StepTransferApplicationIn.GetDescription<DBValue>(), cmd, language, MergeID);
                        }
                    }
                    ICSWareHouseService.OneStepTransferDocInERP(TransTypeEnum.OneStepTransferDocIn.GetDescription(), Identification, cmd, language, BusinessCode);

                    if (!printTable.Equals("{}"))
                    {
                        cmd.Transaction.Commit();
                        return printTable;
                    }
                    else
                    {
                        DataTable table = GetData(Identification, 3, cmd);
                        cmd.Transaction.Commit();
                        return table;
                    }

                }
                catch (Exception ex)
                {
                    if (cmd.Transaction != null)
                        cmd.Transaction.Rollback();
                    log.Error(ex.Message);
                    throw new Exception(ex.Message);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                    }
                    conn.Dispose();
                }
            }
        }
        #endregion



        #region 一步调拨
        /// <summary>
        /// 一步调拨
        /// </summary>
        /// <param name="JsonData"></param>
        /// <returns></returns>
        public static DataTable OneStepTransferDocIn(List<TransferDoc> JsonData)
        {
            var language = LanguageHelper.GetName("WMSAPIInfo");
            if (JsonData.Count <= 0)
            {
                throw new Exception(language.GetNameByCode("WMSAPIInfo007"));//"传送数据为空!"
            }
            DataTable printTable = new DataTable();
            using (SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString))
            {
                conn.Open();
                SqlTransaction sqlTran = conn.BeginTransaction();
                SqlCommand cmd = new SqlCommand();
                cmd.Transaction = sqlTran;
                cmd.Connection = conn;
                cmd.CommandTimeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["TimeOut"]);
                string BusinessCode = string.Empty;
                try
                {
                    string sql = string.Empty;
                    string Identification = Guid.NewGuid().ToString();
                    foreach (var item in JsonData)
                    {
                        if (string.IsNullOrEmpty(item.TransCode))
                        {
                            throw new Exception(language.GetNameByCode("WMSAPIInfo027"));//"调拨单号不能为空!");
                        }

                        string[] trans = item.TransCode.Split('~');
                        string MergeID = "";
                        if (trans.Length == 2)
                        {
                            MergeID = trans[0];
                            item.TransCode = trans[1];
                        }
                        //验证信息
                        sql = @"DECLARE @Status VARCHAR(10)
                                SELECT @Status=Status FROM ICSTransfer WHERE TransferNO='{0}' and WorkPoint='{1}' AND Type = '1'

                                IF (@Status IS NULL)
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo067") + @"',16,1);
                                    RETURN
                                END
                                ELSE IF (@Status!='1')
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo068") + @"',16,1);
                                    RETURN
                                END";
                        sql = string.Format(sql, item.TransCode, item.WorkPoint);
                        DBHelper.ExecuteNonQuery(sql, cmd);

                        foreach (var itemInfo in item.Detail)
                        {
                            //验证仓库库位信息
                            sql = @"IF NOT EXISTS(SELECT a.ID FROM ICSWareHouse a WHERE a.WarehouseCode='{0}' AND a.WorkPoint='{1}')
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo069") + @"',16,1);
                                    RETURN
                                END
                                IF NOT EXISTS(SELECT a.ID FROM ICSLocation a WHERE a.LocationCode='{2}' AND a.WorkPoint='{1}')
                                BEGIN
	                                RAISERROR('" + string.Format(language.GetNameByCode("WMSAPIInfo070"), "{2}") + @"',16,1);
                                    RETURN
                                END
                                IF NOT EXISTS(SELECT a.ID 
                                FROM ICSWareHouse a 
                                INNER JOIN ICSLocation b ON a.ID=b.WHID AND a.WorkPoint=b.WorkPoint
                                WHERE a.WarehouseCode='{0}' AND a.WorkPoint='{1}' AND b.LocationCode='{2}')
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo071") + @"',16,1);
                                    RETURN
                                END";
                            sql = string.Format(sql, itemInfo.WarehouseCode, item.WorkPoint, itemInfo.LocationCode);
                            DBHelper.ExecuteNonQuery(sql, cmd);

                            BusinessCode = TransTypeEnum.OneStepTransferDocIn.GetDescription<DBValue>();
                            //更新源头单据信息
                            ICSWareHouseService.OneStepTransferDocIn(item.TransCode, item.TransSequence, item.WorkPoint, itemInfo.CurrentQuantity, cmd, language);

                            //更新条码信息
                            printTable=ICSWareHouseLotInfoService.WareHouseLotInfoTransfer(Identification, item.TransCode, item.TransSequence, itemInfo.WarehouseCode, itemInfo.LocationCode,
                                itemInfo.LotNo, itemInfo.CurrentQuantity, item.User, item.WorkPoint, "6", TransTypeEnum.OneStepTransferDocIn.GetDescription<DBValue>(), cmd, language, MergeID);
                        }
                    }
                    ICSWareHouseService.OneStepTransferDocInERP(TransTypeEnum.OneStepTransferDocIn.GetDescription(), Identification, cmd, language, BusinessCode);

                    if (!printTable.Equals("{}"))
                    {
                        cmd.Transaction.Commit();
                        return printTable;
                    }
                    else
                    {
                        DataTable table = GetData(Identification, 3, cmd);
                        cmd.Transaction.Commit();
                        return table;
                    }
                    
                }
                catch (Exception ex)
                {
                    if (cmd.Transaction != null)
                        cmd.Transaction.Rollback();
                    log.Error(ex.Message);
                    throw new Exception(ex.Message);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                    }
                    conn.Dispose();
                }
            }
        }
        #endregion

        #region 调拨
        /// <summary>
        /// 调拨
        /// </summary>
        /// <param name="JsonData"></param>
        /// <returns></returns>
        public static DataTable TransferDocCreate(List<TransferDoc> JsonData)
        {
            var language = LanguageHelper.GetName("WMSAPIInfo");
            if (JsonData.Count <= 0)
            {
                throw new Exception(language.GetNameByCode("WMSAPIInfo007"));//"传送数据为空!"
            }
            using (SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString))
            {
                conn.Open();
                SqlTransaction sqlTran = conn.BeginTransaction();
                SqlCommand cmd = new SqlCommand();
                cmd.Transaction = sqlTran;
                cmd.Connection = conn;
                cmd.CommandTimeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["TimeOut"]);
                string BusinessCode = string.Empty;
                try
                {
                    string sql = string.Empty;
                    string Identification = Guid.NewGuid().ToString();
                    foreach (var item in JsonData)
                    {
                        string MergeID = "";

                        foreach (var itemInfo in item.Detail)
                        {
                            //验证仓库库位信息
                            sql = @"IF NOT EXISTS(SELECT a.ID FROM ICSWareHouse a WHERE a.WarehouseCode='{0}' AND a.WorkPoint='{1}')
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo069") + @"',16,1);
                                    RETURN
                                END
                                IF NOT EXISTS(SELECT a.ID FROM ICSLocation a WHERE a.LocationCode='{2}' AND a.WorkPoint='{1}')
                                BEGIN
	                                RAISERROR('" + string.Format(language.GetNameByCode("WMSAPIInfo070"), "{2}") + @"',16,1);
                                    RETURN
                                END
                                IF NOT EXISTS(SELECT a.ID 
                                FROM ICSWareHouse a 
                                INNER JOIN ICSLocation b ON a.ID=b.WHID AND a.WorkPoint=b.WorkPoint
                                WHERE a.WarehouseCode='{0}' AND a.WorkPoint='{1}' AND b.LocationCode='{2}')
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo071") + @"',16,1);
                                    RETURN
                                END";
                            sql = string.Format(sql, itemInfo.WarehouseCode, item.WorkPoint, itemInfo.LocationCode);
                            DBHelper.ExecuteNonQuery(sql, cmd);

                            BusinessCode = TransTypeEnum.StepTransferDocIn.GetDescription<DBValue>();

                            //更新条码信息
                            ICSWareHouseLotInfoService.WareHouseLotInfoTransfer(Identification, item.TransCode, item.TransSequence, itemInfo.WarehouseCode, itemInfo.LocationCode,
                                itemInfo.LotNo, itemInfo.CurrentQuantity, item.User, item.WorkPoint, "6", TransTypeEnum.StepTransferDocIn.GetDescription<DBValue>(), cmd, language, MergeID);
                        }
                    }
                    ICSWareHouseService.StepTransferDocInERP(TransTypeEnum.StepTransferDocIn.GetDescription(), Identification, cmd, language, BusinessCode);

                    DataTable table = GetData(Identification, 3, cmd);
                    cmd.Transaction.Commit();
                    return table;
                }
                catch (Exception ex)
                {
                    if (cmd.Transaction != null)
                        cmd.Transaction.Rollback();
                    log.Error(ex.Message);
                    throw new Exception(ex.Message);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                    }
                    conn.Dispose();
                }
            }
        }
        #endregion


        #region 无源头调拨
        /// <summary>
        /// 无源头调拨
        /// </summary>
        /// <param name="JsonData"></param>
        /// <returns></returns>
        public static DataTable OneStepNoTransferDocIn(List<TransferDoc> JsonData)
        {
            var language = LanguageHelper.GetName("WMSAPIInfo");
            if (JsonData.Count <= 0)
            {
                throw new Exception(language.GetNameByCode("WMSAPIInfo007"));//"传送数据为空!"
            }
            using (SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString))
            {
                conn.Open();
                SqlTransaction sqlTran = conn.BeginTransaction();
                SqlCommand cmd = new SqlCommand();
                cmd.Transaction = sqlTran;
                DataTable printTable = new DataTable();
                cmd.Connection = conn;
                cmd.CommandTimeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["TimeOut"]);
                try
                {
                    string sql = string.Empty;
                    string Identification = Guid.NewGuid().ToString();
                    string BusinessCode = "";
                    foreach (var item in JsonData)
                    {

                        string MergeID = "";

                        foreach (var itemInfo in item.Detail)
                        {
                            //判断是否开启辅计量,计算辅计量比例
                            string chekksql = @"select c.EATTRIBUTE1 FROM ICSInventoryLot  a
                                INNER JOIN ICSInventory c on a.InvCode=c.InvCode and a.WorkPoint=c.WorkPoint
                                WHERE a.lotno='{0}'  AND a.WorkPoint='{1}' and c.AmountEnable='1'";
                            chekksql = string.Format(chekksql, itemInfo.LotNo, item.WorkPoint, itemInfo.CurrentQuantity);
                            DataTable dta = DBHelper.SQlReturnData(chekksql, cmd);
                            if (dta.Rows.Count > 0)
                            {
                                itemInfo.CurrentQuantity = (decimal.Parse(itemInfo.CurrentQuantity) * decimal.Parse(dta.Rows[0]["EATTRIBUTE1"].ToString())).ToString();
                            }

                            //验证仓库库位信息
                            sql = @"IF NOT EXISTS(SELECT a.ID FROM ICSWareHouse a WHERE a.WarehouseCode='{0}' AND a.WorkPoint='{1}')
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo069") + @"',16,1);
                                    RETURN
                                END
                                IF NOT EXISTS(SELECT a.ID FROM ICSLocation a WHERE a.LocationCode='{2}' AND a.WorkPoint='{1}')
                                BEGIN
	                                RAISERROR('" + string.Format(language.GetNameByCode("WMSAPIInfo070"), "{2}") + @"',16,1);
                                    RETURN
                                END
                                IF NOT EXISTS(SELECT a.ID FROM ICSWareHouseLotInfo a WHERE a.LotNo='{3}' AND a.WorkPoint='{1}' AND a.Quantity>={4})
                                BEGIN
	                                RAISERROR('" + string.Format(language.GetNameByCode("WMSAPIInfo368")) + @"',16,1);
                                    RETURN
                                END
                                IF NOT EXISTS(SELECT a.ID 
                                FROM ICSWareHouse a 
                                INNER JOIN ICSLocation b ON a.ID=b.WHID AND a.WorkPoint=b.WorkPoint
                                WHERE a.WarehouseCode='{0}' AND a.WorkPoint='{1}' AND b.LocationCode='{2}')
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo071") + @"',16,1);
                                    RETURN
                                END";
                            sql = string.Format(sql, itemInfo.WarehouseCode, item.WorkPoint, itemInfo.LocationCode, itemInfo.LotNo, itemInfo.CurrentQuantity);
                            DBHelper.ExecuteNonQuery(sql, cmd);
                            BusinessCode = TransTypeEnum.StepNoTransferDocIn.GetDescription<DBValue>();

                            //更新条码信息
                            printTable = ICSWareHouseLotInfoService.WareHouseLotInfoNoTransfer(Identification, itemInfo.WarehouseCode, itemInfo.LocationCode,
                                itemInfo.LotNo, itemInfo.CurrentQuantity, item.User, item.WorkPoint, "6", TransTypeEnum.StepNoTransferDocIn.GetDescription<DBValue>(), cmd, language, MergeID);
                        }
                    }
                    ICSWareHouseService.OneStepNoTransferDocInERP(TransTypeEnum.StepNoTransferDocIn.GetDescription(), Identification, cmd, language, BusinessCode);

                    if (!printTable.Equals("{}"))
                    {
                        cmd.Transaction.Commit();
                        return printTable;
                    }
                    else
                    {
                        DataTable table = GetData(Identification, 3, cmd);
                        cmd.Transaction.Commit();
                        return table;
                    }

                }
                catch (Exception ex)
                {
                    if (cmd.Transaction != null)
                        cmd.Transaction.Rollback();
                    log.Error(ex.Message);
                    throw new Exception(ex.Message);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                    }
                    conn.Dispose();
                }
            }
        }
        #endregion



        #region 调拨申请单
        /// <summary>
        /// 调拨
        /// </summary>
        /// <param name="JsonData"></param>
        /// <returns></returns>
        public static DataTable TransferApplicationCreate(List<TransferApplication> JsonData)
        {
            var language = LanguageHelper.GetName("WMSAPIInfo");
            if (JsonData.Count <= 0)
            {
                throw new Exception(language.GetNameByCode("WMSAPIInfo007"));//"传送数据为空!"
            }
            using (SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString))
            {
                conn.Open();
                SqlTransaction sqlTran = conn.BeginTransaction();
                SqlCommand cmd = new SqlCommand();
                cmd.Transaction = sqlTran;
                cmd.Connection = conn;
                cmd.CommandTimeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["TimeOut"]);
                string BusinessCode = string.Empty;
                try
                {
                    string sql = string.Empty;
                    string Identification = Guid.NewGuid().ToString();
                    foreach (var item in JsonData)
                    {
                        string MergeID = "";

                        foreach (var itemInfo in item.Detail)
                        {
                            //验证仓库库位信息
                            sql = @"IF NOT EXISTS(SELECT a.ID FROM ICSWareHouse a WHERE a.WarehouseCode='{0}' AND a.WorkPoint='{1}')
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo069") + @"',16,1);
                                    RETURN
                                END
                                IF NOT EXISTS(SELECT a.ID FROM ICSLocation a WHERE a.LocationCode='{2}' AND a.WorkPoint='{1}')
                                BEGIN
	                                RAISERROR('" + string.Format(language.GetNameByCode("WMSAPIInfo070"), "{2}") + @"',16,1);
                                    RETURN
                                END
                                IF NOT EXISTS(SELECT a.ID 
                                FROM ICSWareHouse a 
                                INNER JOIN ICSLocation b ON a.ID=b.WHID AND a.WorkPoint=b.WorkPoint
                                WHERE a.WarehouseCode='{0}' AND a.WorkPoint='{1}' AND b.LocationCode='{2}')
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo071") + @"',16,1);
                                    RETURN
                                END";
                            sql = string.Format(sql, itemInfo.WarehouseCode, item.WorkPoint, itemInfo.LocationCode);
                            DBHelper.ExecuteNonQuery(sql, cmd);

                            BusinessCode = TransTypeEnum.StepTransferApplicationIn.GetDescription<DBValue>();

                            //更新条码信息
                            ICSWareHouseLotInfoService.WareHouseLotInfoTransfer(Identification, item.TransCode, item.TransSequence, itemInfo.WarehouseCode, itemInfo.LocationCode,
                                itemInfo.LotNo, itemInfo.CurrentQuantity, item.User, item.WorkPoint, "14", TransTypeEnum.StepTransferApplicationIn.GetDescription<DBValue>(), cmd, language, MergeID);
                        }
                    }
                    ICSWareHouseService.StepTransferDocInERP(TransTypeEnum.StepTransferApplicationIn.GetDescription(), Identification, cmd, language, BusinessCode);

                    DataTable table = GetData(Identification, 3, cmd);
                    cmd.Transaction.Commit();
                    return table;
                }
                catch (Exception ex)
                {
                    if (cmd.Transaction != null)
                        cmd.Transaction.Rollback();
                    log.Error(ex.Message);
                    throw new Exception(ex.Message);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                    }
                    conn.Dispose();
                }
            }
        }
        #endregion

        #region 调拨申请单
        /// <summary>
        /// 调拨申请单
        /// </summary>
        /// <param name="JsonData"></param>
        /// <returns></returns>
        public static DataTable TransferApplicationInCreate(List<TransferApplication> JsonData)
        {
            var language = LanguageHelper.GetName("WMSAPIInfo");
            if (JsonData.Count <= 0)
            {
                throw new Exception(language.GetNameByCode("WMSAPIInfo007"));//"传送数据为空!"
            }
            using (SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString))
            {
                conn.Open();
                SqlTransaction sqlTran = conn.BeginTransaction();
                SqlCommand cmd = new SqlCommand();
                cmd.Transaction = sqlTran;
                cmd.Connection = conn;
                cmd.CommandTimeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["TimeOut"]);
                string BusinessCode = string.Empty;
                try
                {
                    DataTable printTable = new DataTable();
                    string sql = string.Empty;
                    string Identification = Guid.NewGuid().ToString();
                    foreach (var item in JsonData)
                    {
                        string MergeID = "";

                        foreach (var itemInfo in item.Detail)
                        {
                            //验证仓库库位信息
                            sql = @"IF NOT EXISTS(SELECT a.ID FROM ICSWareHouse a WHERE a.WarehouseCode='{0}' AND a.WorkPoint='{1}')
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo069") + @"',16,1);
                                    RETURN
                                END
                                IF NOT EXISTS(SELECT a.ID FROM ICSLocation a WHERE a.LocationCode='{2}' AND a.WorkPoint='{1}')
                                BEGIN
	                                RAISERROR('" + string.Format(language.GetNameByCode("WMSAPIInfo070"), "{2}") + @"',16,1);
                                    RETURN
                                END
                                IF NOT EXISTS(SELECT a.ID 
                                FROM ICSWareHouse a 
                                INNER JOIN ICSLocation b ON a.ID=b.WHID AND a.WorkPoint=b.WorkPoint
                                WHERE a.WarehouseCode='{0}' AND a.WorkPoint='{1}' AND b.LocationCode='{2}')
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo071") + @"',16,1);
                                    RETURN
                                END
                                IF EXISTS(SELECT ID 
                                FROM ICSWareHouseLotInfo 
                                WHERE WarehouseCode='{0}' AND WorkPoint='{1}' AND LotNo='{3}')
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo355") + @"',16,1);
                                    RETURN
                                END";
                            sql = string.Format(sql, itemInfo.WarehouseCode, item.WorkPoint, itemInfo.LocationCode, itemInfo.LotNo);
                            DBHelper.ExecuteNonQuery(sql, cmd);
                            BusinessCode = TransTypeEnum.StepTransferApplicationIn.GetDescription<DBValue>();

                            //更新源头单据信息
                            ICSWareHouseService.OneStepTransferApplicationIn(item.TransCode, item.TransSequence, item.WorkPoint, itemInfo.CurrentQuantity, cmd, language);

                            //更新条码信息
                            printTable=ICSWareHouseLotInfoService.WareHouseLotInfoTransfer(Identification, item.TransCode, item.TransSequence, itemInfo.WarehouseCode, itemInfo.LocationCode,
                                itemInfo.LotNo, itemInfo.CurrentQuantity, item.User, item.WorkPoint, "14", TransTypeEnum.StepTransferApplicationIn.GetDescription<DBValue>(), cmd, language, MergeID);
                        }
                    }
                    if (Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["UploadERP"]))
                    {
                        ICSWareHouseService.StepTransferApplicationERP(TransTypeEnum.StepTransferApplicationIn.GetDescription(), Identification, cmd, language, BusinessCode);

                    }

                    if (!printTable.Equals("{}"))
                    {
                        cmd.Transaction.Commit();
                        return printTable;
                    }
                    else
                    {
                        DataTable table = GetData(Identification, 3, cmd);
                        cmd.Transaction.Commit();
                        return table;
                    }
                }
                catch (Exception ex)
                {
                    if (cmd.Transaction != null)
                        cmd.Transaction.Rollback();
                    log.Error(ex.Message);
                    throw new Exception(ex.Message);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                    }
                    conn.Dispose();
                }
            }
        }
        #endregion

        //#region 工单关联
        ///// <summary>
        ///// 条码关联工单
        ///// </summary>
        ///// <param name="JsonData"></param>
        ///// <returns></returns>
        //public static DataTable ICSMOReceive(List<LOTStockUpCreateIModel> JsonData)
        //{
        //    var language = LanguageHelper.GetName("WMSAPIInfo");
        //    if (JsonData.Count <= 0)
        //    {
        //        throw new Exception(language.GetNameByCode("WMSAPIInfo007"));//"传送数据为空!"
        //    }
        //    using (SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString))
        //    {
        //        conn.Open();
        //        SqlTransaction sqlTran = conn.BeginTransaction();
        //        SqlCommand cmd = new SqlCommand();
        //        cmd.Transaction = sqlTran;
        //        cmd.Connection = conn;
        //        try
        //        {
        //            string sql = string.Empty;
        //            string TransType = string.Empty;
        //            string Identification = Guid.NewGuid().ToString();
        //            foreach (var item in JsonData)
        //            {
        //                string MergeID = "";

        //                foreach (var itemInfo in item.detail)
        //                {
        //                    ICSWareHouseService.ICSMOReceive(itemInfo.LotNo, itemInfo.Quantity, itemInfo.TransCode, itemInfo.TransSequence, item.WorkPoint, Identification, item.User, itemInfo.SRMLotGroup, itemInfo.ProjectCode,
        //                        itemInfo.BatchCode, itemInfo.Version, itemInfo.Brand, itemInfo.cFree1, itemInfo.cFree2, itemInfo.cFree3, itemInfo.cFree4, itemInfo.cFree5,
        //                        itemInfo.cFree6, itemInfo.cFree7, itemInfo.cFree8, itemInfo.cFree9, itemInfo.cFree10, TransTypeEnum.ICSMOReceive.GetDescription<DBValue>(), cmd, language);

        //                }

        //            }

        //            DataTable table = GetData(Identification, 3, cmd);
        //            cmd.Transaction.Commit();
        //            return table;
        //        }
        //        catch (Exception ex)
        //        {
        //            if (cmd.Transaction != null)
        //                cmd.Transaction.Rollback();
        //            log.Error(ex.Message);
        //            throw new Exception(ex.Message);
        //        }
        //        finally
        //        {
        //            if (conn.State == ConnectionState.Open)
        //            {
        //                conn.Close();
        //            }
        //            conn.Dispose();
        //        }
        //    }
        //}
        ///// <summary>
        ///// 条码与工单解绑
        ///// </summary>
        ///// <param name="JsonData"></param>
        ///// <returns></returns>
        //public static DataTable ICSMOReceiveUntie(ICSMOReceiveUntieModel JsonData)
        //{
        //    var language = LanguageHelper.GetName("WMSAPIInfo");
        //    if (JsonData == null)
        //    {
        //        throw new Exception(language.GetNameByCode("WMSAPIInfo007"));//"传送数据为空!"
        //    }
        //    using (SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString))
        //    {
        //        conn.Open();
        //        SqlTransaction sqlTran = conn.BeginTransaction();
        //        SqlCommand cmd = new SqlCommand();
        //        cmd.Transaction = sqlTran;
        //        cmd.Connection = conn;
        //        try
        //        {
        //            string sql = string.Empty;
        //            string TransType = string.Empty;
        //            string Identification = Guid.NewGuid().ToString();
        //            string MergeID = "";

        //            ICSWareHouseService.ICSMOReceiveUntie(JsonData.LotNo, JsonData.WorkPoint, TransTypeEnum.ICSMOReceive.GetDescription<DBValue>(), cmd, language);

        //            DataTable table = GetData(Identification, 3, cmd);
        //            cmd.Transaction.Commit();
        //            return table;
        //        }
        //        catch (Exception ex)
        //        {
        //            if (cmd.Transaction != null)
        //                cmd.Transaction.Rollback();
        //            log.Error(ex.Message);
        //            throw new Exception(ex.Message);
        //        }
        //        finally
        //        {
        //            if (conn.State == ConnectionState.Open)
        //            {
        //                conn.Close();
        //            }
        //            conn.Dispose();
        //        }
        //    }
        //}
        //#endregion

        //#region 工单关联条码检验
        ///// <summary>
        ///// 工单关联条码检验
        ///// </summary>
        ///// <param name="JsonData"></param>
        ///// <returns></returns>
        //public static bool ICSMOReceiveLotCheck(BarCodeModel JsonData)
        //{
        //    Boolean LotCheck = false;
        //    var language = LanguageHelper.GetName("WMSAPIInfo");
        //    using (SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString))
        //    {
        //        conn.Open();
        //        SqlTransaction sqlTran = conn.BeginTransaction();
        //        SqlCommand cmd = new SqlCommand();
        //        cmd.Transaction = sqlTran;
        //        cmd.Connection = conn;
        //        try
        //        {
        //            string sql = string.Empty;
        //            string TransType = string.Empty;
        //            string Identification = Guid.NewGuid().ToString();


        //            sql = @"select * from ICSInventoryLotDetail where LotNo='{0}' and WorkPoint='{1}'";
        //            sql = string.Format(sql, JsonData.Code, JsonData.WorkPoint);




        //            DataTable table = DBHelper.SQlReturnData(sql, cmd);
        //            cmd.Transaction.Commit();
        //            if (table.Rows.Count > 0)
        //            {
        //                LotCheck = true;
        //            }
        //            return LotCheck;
        //        }
        //        catch (Exception ex)
        //        {
        //            if (cmd.Transaction != null)
        //                cmd.Transaction.Rollback();
        //            log.Error(ex.Message);
        //            throw new Exception(ex.Message);
        //        }
        //        finally
        //        {
        //            if (conn.State == ConnectionState.Open)
        //            {
        //                conn.Close();
        //            }
        //            conn.Dispose();
        //        }
        //    }
        //}
        //#endregion

        #region 容器
        /// <summary>
        /// 查询容器
        /// </summary>
        /// <param name="JsonData"></param>
        /// <returns></returns>
        public static DataTable ICSContainerGet(BarCodeModel JsonData)
        {
            var language = LanguageHelper.GetName("WMSAPIInfo");
            if (JsonData == null)
            {
                throw new Exception(language.GetNameByCode("WMSAPIInfo007"));//"传送数据为空!"
            }
            using (SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString))
            {
                conn.Open();
                SqlTransaction sqlTran = conn.BeginTransaction();
                SqlCommand cmd = new SqlCommand();
                cmd.Transaction = sqlTran;
                cmd.Connection = conn;
                cmd.CommandTimeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["TimeOut"]);
                try
                {
                    string sql = "";
                    string TransType = string.Empty;
                    string Identification = Guid.NewGuid().ToString();
//                    if (JsonData.ifCreateContainer)
//                    {
//                        sql = @"IF EXISTS(select ContainerCODE from ICSContainer where ContainerCODE='{0}' )
//                                    BEGIN
//	                                    RAISERROR('容器:{0},已存在!',16,1)
//                                        RETURN
//                                    END
//                            else
//                            BEGIN
//                                INSERT INTO dbo.ICSContainer
//                                ( ID ,ContainerID ,ContainerCODE ,ContainerName,Memo,MTIME,MUSER ,MUSERName ,WorkPoint
//                                 ,InventoryMixed,ProjectMixed,BatchMixed,Multiplex) 
//							    Values(NEWID(),'','{0}','{0}','',GETDATE(),'{2}','{2}','{1}','0','0','0','0')
//                            END
//";
//                    }
                    
                    sql += @"IF NOT EXISTS(select ContainerCODE from ICSContainer where ContainerCODE='{0}' )
                                BEGIN
                                    RAISERROR('容器:{0},不存在!',16,1)
                                    RETURN
                                END
                            SELECT ID,ContainerID,ContainerCode,ContainerName,Memo,ContainerType,InventoryMixed,ProjectMixed,BatchMixed,Multiplex,MUSER,MUSERName,MTIME,WorkPoint,
                                EATTRIBUTE1 AS cFree1,EATTRIBUTE2 AS cFree2,EATTRIBUTE3 AS cFree3,EATTRIBUTE4 AS cFree4,EATTRIBUTE5 AS cFree5,EATTRIBUTE6 AS cFree6,EATTRIBUTE7 AS cFree7
                                ,EATTRIBUTE8 AS cFree8,EATTRIBUTE9 AS cFree9,EATTRIBUTE10 AS cFree10
                                FROM ICSContainer WHERE ContainerCode='{0}' AND WorkPoint='{1}'";
                    sql = string.Format(sql,JsonData.Code , JsonData.WorkPoint , JsonData.User);

                    DataTable table = DBHelper.SQlReturnData(sql, cmd);
                    cmd.Transaction.Commit();
                    return table;
                }
                catch (Exception ex)
                {
                    if (cmd.Transaction != null)
                        cmd.Transaction.Rollback();
                    log.Error(ex.Message);
                    throw new Exception(ex.Message);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                    }
                    conn.Dispose();
                }
            }
        }

        #region 盘点审核
        /// <summary>
        /// 多语言查询
        /// </summary>
        /// <param name="JsonData"></param>
        /// <returns></returns>
        public static DataTable CheckApove(List<ICSCheck> JsonData)
        {
            var language = LanguageHelper.GetName("WMSAPIInfo");
            if (JsonData.Count <= 0)
            {
                throw new Exception(language.GetNameByCode("WMSAPIInfo007"));//"传送数据为空!"
            }
            using (SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString))
            {
                conn.Open();
                SqlTransaction sqlTran = conn.BeginTransaction();
                SqlCommand cmd = new SqlCommand();
                cmd.Transaction = sqlTran;
                cmd.Connection = conn;
                cmd.CommandTimeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["TimeOut"]);
                try
                {
                    string lots = string.Empty;
                    string sql = string.Empty;
                    int result = 0;
                    string Identification = Guid.NewGuid().ToString();
                    foreach (var item in JsonData)
                    {
                        //创建盘点单
                        foreach (var itemInfo in item.detail)
                        {
                            ICSWareHouseLotInfoService.WareHouseLotInfoUpdate(Identification, item.CheckCode, "", itemInfo.LotNo, itemInfo.ActualQuantity, item.User, item.WorkPoint, TransTypeEnum.Check.GetDescription<DBValue>(), item.CheckKind, cmd, language);

                            lots += "'" + itemInfo.LotNo + item.WorkPoint + "',";
                        }
                        if (string.IsNullOrWhiteSpace(lots))
                        {
                            throw new Exception(language.GetNameByCode("WMSAPIInfo005"));//"请传入条码信息!");
                        }
                        //sql = @"UPDATE a SET ActualQuantity=b.ActualQuantity
                        //        FROM ICSCheck a
                        //        INNER JOIN (SELECT x.CheckCode,x.WorkPoint,y.WarehouseCode,y.InvCode,SUM(ActualQuantity) AS ActualQuantity FROM ICSCheckDetail x INNER JOIN ICSWareHouseLotInfo y ON x.LotNo=y.LotNo AND x.WorkPoint=y.WorkPoint WHERE x.LotNo+x.WorkPoint IN ({2}) GROUP BY x.CheckCode,x.WorkPoint,y.WarehouseCode,y.InvCode) b ON a.CheckCode=b.CheckCode AND a.WorkPoint=b.WorkPoint AND a.WHCode=b.WarehouseCode AND a.InvCode=b.InvCode
                        //        WHERE a.CheckCode='{0}' and a.WorkPoint='{1}'";
                        //sql = string.Format(sql, item.CheckCode, item.WorkPoint, lots.Substring(0, lots.Length - 1));

                        //if (!DBHelper.ExecuteNonQuery(sql, cmd))
                        //{
                        //    throw new Exception(language.GetNameByCode("WMSAPIInfo034"));//"盘点扫描更新盘点单失败!");
                        //}
                    }
                    #region 查询返回数据
                    sql = @"SELECT x.ID,x.CheckID,y.WarehouseCode AS WHCode,x.LotNo,
	                            y.InvCode,
	                            inv.InvName,
	                            inv.InvStd,
	                            x.Quantity,x.PrimaryQuantity,x.PrimaryAmount,x.ReplayQuantity,x.ReplayAmount,x.CheckQuantity,x.CheckAmount,
	                            inv.InvUnit,
	                            x.MUSER AS [User],
	                            x.MTIME AS [MTime]
                            FROM ICSCheckDetail x 
                            INNER JOIN ICSWareHouseLotInfo y ON x.LotNo=y.LotNo AND x.WorkPoint=y.WorkPoint 
                            INNER JOIN ICSInventory inv ON y.InvCode=inv.InvCode AND y.WorkPoint=inv.WorkPoint
                            WHERE x.LotNo+x.WorkPoint IN ({0})";
                    sql = string.Format(sql, lots.Substring(0, lots.Length - 1));
                    DataTable data = DBHelper.SQlReturnData(sql, cmd);
                    #endregion
                    cmd.Transaction.Commit();
                    return data;
                }
                catch (Exception ex)
                {
                    if (cmd.Transaction != null)
                        cmd.Transaction.Rollback();
                    log.Error(ex.Message);
                    throw new Exception(ex.Message);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                    }
                    conn.Dispose();
                }
            }
        }
        #endregion

        /// <summary>
        /// 容器关联查询容器
        /// </summary>
        /// <param name="JsonData"></param>
        /// <returns></returns>
        public static DataTable ICSContainerConGet(BarCodeModel JsonData)
        {
            var language = LanguageHelper.GetName("WMSAPIInfo");
            if (JsonData == null)
            {
                throw new Exception(language.GetNameByCode("WMSAPIInfo007"));//"传送数据为空!"
            }
            using (SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString))
            {
                conn.Open();
                SqlTransaction sqlTran = conn.BeginTransaction();
                SqlCommand cmd = new SqlCommand();
                cmd.Transaction = sqlTran;
                cmd.Connection = conn;
                cmd.CommandTimeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["TimeOut"]);
                try
                {
                    string sql = string.Empty;
                    string TransType = string.Empty;
                    string Identification = Guid.NewGuid().ToString();
                    
                    sql = @"SELECT con.ID,con.ContainerID,con.ContainerCode,con.ContainerName,con.Memo,con.ContainerType,con.InventoryMixed,con.ProjectMixed,con.BatchMixed,con.Multiplex,con.MUSER,con.MUSERName,con.MTIME,con.WorkPoint,con.
                                EATTRIBUTE1 AS cFree1,con.EATTRIBUTE2 AS cFree2,con.EATTRIBUTE3 AS cFree3,con.EATTRIBUTE4 AS cFree4,con.EATTRIBUTE5 AS cFree5,con.EATTRIBUTE6 AS cFree6,con.EATTRIBUTE7 AS cFree7
                                ,con.EATTRIBUTE8 AS cFree8,con.EATTRIBUTE9 AS cFree9,con.EATTRIBUTE10 AS cFree10
                                FROM ICSContainer a
																INNER JOIN ICSContainer con ON con.ContainerID=a.ID
																WHERE a.ContainerCode='{0}' AND a.WorkPoint='{1}'";
                    sql = string.Format(sql,JsonData.Code , JsonData.WorkPoint);

                    DataTable table = DBHelper.SQlReturnData(sql, cmd);
                    cmd.Transaction.Commit();
                    return table;
                }
                catch (Exception ex)
                {
                    if (cmd.Transaction != null)
                        cmd.Transaction.Rollback();
                    log.Error(ex.Message);
                    throw new Exception(ex.Message);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                    }
                    conn.Dispose();
                }
            }
        }
        /// <summary>
        /// 条码关联容器——查询容器关联的条码
        /// </summary>
        /// <param name="JsonData"></param>
        /// <returns></returns>
        public static DataTable ICSContainerLotGetCon(BarCodeModel JsonData)
        {
            var language = LanguageHelper.GetName("WMSAPIInfo");
            if (JsonData == null)
            {
                throw new Exception(language.GetNameByCode("WMSAPIInfo007"));//"传送数据为空!"
            }
            using (SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString))
            {
                conn.Open();
                SqlTransaction sqlTran = conn.BeginTransaction();
                SqlCommand cmd = new SqlCommand();
                cmd.Transaction = sqlTran;
                cmd.Connection = conn;
                cmd.CommandTimeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["TimeOut"]);
                try
                {
                    string sql = string.Empty;
                    string TransType = string.Empty;
                    string Identification = Guid.NewGuid().ToString();
                    
                    sql = @"SELECT con.ContainerCode,con.ContainerName,con.ContainerType,inv.InvCode,inv.InvName,lot.LotNo,inv.InvStd,lot.Quantity,inv.InvUnit,
																ext.ProjectCode,ext.BatchCode,ext.Version,ext.Brand,ext.cFree1,ext.cFree2,ext.cFree3,ext.cFree4,ext.cFree5,ext.cFree6,ext.cFree7,ext.cFree8,ext.cFree9,ext.cFree10
                                FROM ICSContainer con
																LEFT JOIN ICSContainerLot conlot ON conlot.ContainerID=con.ID
																LEFT JOIN ICSInventoryLot lot ON lot.LotNo=conLot.LotNo
																LEFT JOIN ICSInventory inv ON inv.InvCode=lot.InvCode
																LEFT JOIN ICSExtension ext ON ext.ID=lot.ExtensionID
																WHERE con.ContainerCode='{0}' AND con.WorkPoint='{1}'";
                    sql = string.Format(sql,JsonData.Code , JsonData.WorkPoint);

                    DataTable table = DBHelper.SQlReturnData(sql, cmd);
                    cmd.Transaction.Commit();
                    return table;
                }
                catch (Exception ex)
                {
                    if (cmd.Transaction != null)
                        cmd.Transaction.Rollback();
                    log.Error(ex.Message);
                    throw new Exception(ex.Message);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                    }
                    conn.Dispose();
                }
            }
        }

        /// <summary>
        /// 条码关联容器--条码查询
        /// </summary>
        /// <param name="JsonData"></param>
        /// <returns></returns>
        public static DataTable ICSContainerLotCheck(BarCodeModel JsonData)
        {
            Boolean LotCheck = false;
            var language = LanguageHelper.GetName("WMSAPIInfo");
            using (SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString))
            {
                conn.Open();
                SqlTransaction sqlTran = conn.BeginTransaction();
                SqlCommand cmd = new SqlCommand();
                cmd.Transaction = sqlTran;
                cmd.Connection = conn;
                cmd.CommandTimeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["TimeOut"]);
                try
                {
                    string sql = string.Empty;
                    string TransType = string.Empty;
                    string Identification = Guid.NewGuid().ToString();


                    sql = @"select LotNo,InvCode,Quantity,ExtensionID,Type,
                                EATTRIBUTE1 AS cFree1,EATTRIBUTE2 AS cFree2,EATTRIBUTE3 AS cFree3,EATTRIBUTE4 AS cFree4,EATTRIBUTE5 AS cFree5,EATTRIBUTE6 AS cFree6,EATTRIBUTE7 AS cFree7
                                ,EATTRIBUTE8 AS cFree8,EATTRIBUTE9 AS cFree9,EATTRIBUTE10 AS cFree10
                                from ICSInventoryLot where LotNo='{0}' and WorkPoint='{1}'";
                    sql = string.Format(sql, JsonData.Code, JsonData.WorkPoint);




                    DataTable table = DBHelper.SQlReturnData(sql, cmd);
                    cmd.Transaction.Commit();
                    return table;
                }
                catch (Exception ex)
                {
                    if (cmd.Transaction != null)
                        cmd.Transaction.Rollback();
                    log.Error(ex.Message);
                    throw new Exception(ex.Message);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                    }
                    conn.Dispose();
                }
            }
        }

        /// <summary>
        /// 容器绑定条码
        /// </summary>
        /// <param name="JsonData"></param>
        /// <returns></returns>
        public static string ICSContainerLot(List<ICSContainerLotModel> JsonData)
        {
            var language = LanguageHelper.GetName("WMSAPIInfo");
            Boolean flag;
            if (JsonData.Count <= 0)
            {
                throw new Exception(language.GetNameByCode("WMSAPIInfo007"));//"传送数据为空!"
            }
            using (SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString))
            {
                conn.Open();
                SqlTransaction sqlTran = conn.BeginTransaction();
                SqlCommand cmd = new SqlCommand();
                cmd.Transaction = sqlTran;
                cmd.Connection = conn;
                cmd.CommandTimeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["TimeOut"]);
                try
                {
                    string sql = string.Empty;
                    string TransType = string.Empty;
                    string Identification = Guid.NewGuid().ToString();
                    foreach (var item in JsonData)
                    {
                        if (item.ifCreateContainer)
                        {
                            string ContainerID = Guid.NewGuid().ToString();
                            string ContainerCode = GetSerialCode(item.WorkPoint, "ICSContainer", "ContainerCode", "Container", 5, cmd);
                            sql = @"IF EXISTS(SELECT 1 FROM ICSContainer WHERE ContainerCODE='{0}' AND WorkPoint='{1}')
                                    BEGIN
                                        RAISERROR('容器编号 " + ContainerCode + @" 已存在!请重新提交',16,1);
                                        RETURN;
                                    END

                                    INSERT INTO dbo.ICSContainer
                                    ( ID ,ContainerID ,ContainerCODE ,ContainerName,Memo,MTIME,MUSER ,MUSERName ,WorkPoint
                                     ,InventoryMixed,ProjectMixed,BatchMixed,Multiplex) 
							        Values('{3}','','{0}','{0}','',GETDATE(),'{2}','{2}','{1}','0','0','0','0')";
                            sql = string.Format(sql, ContainerCode, item.WorkPoint, item.User, ContainerID);
                            if (!DBHelper.ExecuteNonQuery(sql,cmd))
                            {
                                throw new Exception("生成箱号失败!");
                            }
                            
                            foreach (var itemInfo in item.detail)
                            {
                                flag = ICSWareHouseService.ICSContainerLot(itemInfo.LotNo, ContainerCode, item.WorkPoint, Identification, item.User, itemInfo.ProjectCode,
                                    itemInfo.BatchCode, itemInfo.Version, itemInfo.Brand, itemInfo.cFree1, itemInfo.cFree2, itemInfo.cFree3, itemInfo.cFree4, itemInfo.cFree5,
                                    itemInfo.cFree6, itemInfo.cFree7, itemInfo.cFree8, itemInfo.cFree9, itemInfo.cFree10, TransTypeEnum.ICSMOReceive.GetDescription<DBValue>(), cmd, language);
                                if (!flag)
                                {
                                    log.Error("容器绑定条码失败");
                                    throw new Exception("容器 " + ContainerCode + " 绑定条码 " + itemInfo.LotNo + " 失败");
                                }
                            }
                        }
                        else
                        {
                            foreach (var itemInfo in item.detail)
                            {
                                flag = ICSWareHouseService.ICSContainerLot(itemInfo.LotNo, itemInfo.ContainerCode, item.WorkPoint, Identification, item.User, itemInfo.ProjectCode,
                                    itemInfo.BatchCode, itemInfo.Version, itemInfo.Brand, itemInfo.cFree1, itemInfo.cFree2, itemInfo.cFree3, itemInfo.cFree4, itemInfo.cFree5,
                                    itemInfo.cFree6, itemInfo.cFree7, itemInfo.cFree8, itemInfo.cFree9, itemInfo.cFree10, TransTypeEnum.ICSMOReceive.GetDescription<DBValue>(), cmd, language);
                                if (!flag)
                                {
                                    log.Error("容器绑定条码失败");
                                    throw new Exception("容器 "+ itemInfo.ContainerCode + " 绑定条码 "+ itemInfo.LotNo + " 失败");
                                }
                            }
                        }

                        

                    }
                    cmd.Transaction.Commit();

                    return LanguageHelper.GetNameSingle("WMSAPI001");// "接口调用成功!";
                }
                catch (Exception ex)
                {
                    if (cmd.Transaction != null)
                        cmd.Transaction.Rollback();
                    log.Error(ex.Message);
                    throw new Exception(ex.Message);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                    }
                    conn.Dispose();
                }
            }
        }

        public static string GetSerialCode(string workPointCode, string tbName, string colName, string Pre, int numLen, SqlCommand cmd)
        {
            string sql = "EXEC Addins_GetSerialCode '{0}','{1}','{2}','{3}',{4}";
            sql = string.Format(sql, new object[] { workPointCode, tbName, colName, Pre, numLen });
            return DBHelper.ExecuteScalar(sql,cmd).ToString();
        }

        /// <summary>
        /// 容器与条码解绑
        /// </summary>
        /// <param name="JsonData"></param>
        /// <returns></returns>
        public static bool ICSContainerLotUntie(ICSMOReceiveUntieModel JsonData)
        {
            Boolean flag = false;
            var language = LanguageHelper.GetName("WMSAPIInfo");
            if (JsonData == null)
            {
                throw new Exception(language.GetNameByCode("WMSAPIInfo007"));//"传送数据为空!"
            }
            using (SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString))
            {
                conn.Open();
                SqlTransaction sqlTran = conn.BeginTransaction();
                SqlCommand cmd = new SqlCommand();
                cmd.Transaction = sqlTran;
                cmd.Connection = conn;
                cmd.CommandTimeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["TimeOut"]);
                try
                {
                    string sql = string.Empty;
                    string TransType = string.Empty;
                    string Identification = Guid.NewGuid().ToString();
                    string MergeID = "";

                    flag = ICSWareHouseService.ICSContainerLotUntie(JsonData.ContainerCode, JsonData.LotNo, JsonData.WorkPoint, JsonData.User, JsonData.Type, cmd, language);
                    cmd.Transaction.Commit();
                    return flag;
                }
                catch (Exception ex)
                {
                    if (cmd.Transaction != null)
                        cmd.Transaction.Rollback();
                    log.Error(ex.Message);
                    throw new Exception(ex.Message);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                    }
                    conn.Dispose();
                }
            }
        }

        /// <summary>
        /// 容器绑定父容器
        /// </summary>
        /// <param name="JsonData"></param>
        /// <returns></returns>
        public static string ICSContainerCon(List<ICSContainerConModel> JsonData)
        {
            var language = LanguageHelper.GetName("WMSAPIInfo");
            Boolean flag;
            if (JsonData.Count <= 0)
            {
                throw new Exception(language.GetNameByCode("WMSAPIInfo007"));//"传送数据为空!"
            }
            using (SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString))
            {
                conn.Open();
                SqlTransaction sqlTran = conn.BeginTransaction();
                SqlCommand cmd = new SqlCommand();
                cmd.Transaction = sqlTran;
                cmd.Connection = conn;
                cmd.CommandTimeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["TimeOut"]);
                try
                {
                    string sql = string.Empty;
                    string TransType = string.Empty;
                    string Identification = Guid.NewGuid().ToString();
                    foreach (var item in JsonData)
                    {
                        string MergeID = "";

                        foreach (var itemInfo in item.detail)
                        {
                            flag = ICSWareHouseService.ICSContainerCon(item.ContainerCode, itemInfo.ContainerCode, item.WorkPoint, item.User, item.MTime, item.Type, cmd, language);
                            
                            if (!flag)
                            {
                                log.Error("容器绑定条码失败");
                                throw new Exception("容器 " + itemInfo.ContainerCode + " 绑定父容器 " + item.ContainerCode + " 失败");
                            }
                        }

                    }
                    cmd.Transaction.Commit();

                    return LanguageHelper.GetNameSingle("WMSAPI001");// "接口调用成功!";
                }
                catch (Exception ex)
                {
                    if (cmd.Transaction != null)
                        cmd.Transaction.Rollback();
                    log.Error(ex.Message);
                    throw new Exception(ex.Message);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                    }
                    conn.Dispose();
                }
            }
        }
        /// <summary>
        /// 容器解绑父容器
        /// </summary>
        /// <param name="JsonData"></param>
        /// <returns></returns>
        public static bool ICSContainerConUntie(ICSMOReceiveUntieModel JsonData)
        {
            Boolean flag = false;
            var language = LanguageHelper.GetName("WMSAPIInfo");
            if (JsonData == null)
            {
                throw new Exception(language.GetNameByCode("WMSAPIInfo007"));//"传送数据为空!"
            }
            using (SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString))
            {
                conn.Open();
                SqlTransaction sqlTran = conn.BeginTransaction();
                SqlCommand cmd = new SqlCommand();
                cmd.Transaction = sqlTran;
                cmd.Connection = conn;
                cmd.CommandTimeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["TimeOut"]);
                try
                {
                    string sql = string.Empty;
                    string TransType = string.Empty;
                    string Identification = Guid.NewGuid().ToString();
                    string MergeID = "";

                    flag = ICSWareHouseService.ICSContainerConUntie(JsonData.ContainerCode, JsonData.WorkPoint, JsonData.User, JsonData.Type, cmd, language);
                    cmd.Transaction.Commit();
                    return flag;

                }
                catch (Exception ex)
                {
                    if (cmd.Transaction != null)
                        cmd.Transaction.Rollback();
                    log.Error(ex.Message);
                    throw new Exception(ex.Message);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                    }
                    conn.Dispose();
                }
            }
        }

        #endregion

        #region 车次
        public static DataTable ICSCartBarCodeGet(BarCodeModel JsonData)
        {
            Boolean LotCheck = false;
            var language = LanguageHelper.GetName("WMSAPIInfo");
            using (SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString))
            {
                conn.Open();
                SqlTransaction sqlTran = conn.BeginTransaction();
                SqlCommand cmd = new SqlCommand();
                cmd.Transaction = sqlTran;
                cmd.Connection = conn;
                cmd.CommandTimeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["TimeOut"]);
                try
                {
                    string sql = string.Empty;
                    string TransType = string.Empty;
                    string Identification = Guid.NewGuid().ToString();


                    sql = @"IF EXISTS (SELECT *
	                            FROM ICSCartLotNoCheckList list 
	                            WHERE list.CartNo='{0}' AND list.LotNo='{1}' 
                            )
	                            BEGIN
		                            RAISERROR('"+ language.GetNameByCode("WMSAPIInfo476") + @"',16,1)
		                            RETURN
	                            END
                            ELSE IF NOT EXISTS(
	                            SELECT 1 FROM ICSInventoryLot lot WHERE lot.LotNo='{1}'
                            )
	                            BEGIN
		                            RAISERROR('" + language.GetNameByCode("WMSAPIInfo477") + @"',16,1)
	                            END
                            ELSE IF NOT EXISTS(
	                            SELECT 1 FROM ICSWareHouseLotInfo info WHERE info.LotNo='{1}' AND info.Quantity>0
                            )
	                            BEGIN
		                            RAISERROR('" + language.GetNameByCode("WMSAPIInfo479") +@"',16,1)
	                            END
                            ELSE
	                            BEGIN
		                            SELECT lot.LotNo,lot.InvCode,info.Quantity,lot.ExtensionID,lot.Type,ext.cFree1 AS cFree1,ext.cFree2 AS cFree2,ext.cFree3 AS cFree3,ext.cFree4 AS cFree4,ext.cFree5 AS cFree5,ext.cFree6 AS cFree6,ext.cFree7 AS cFree7,ext.cFree8 AS cFree8,ext.cFree9 AS cFree9,ext.cFree10 AS cFree10
			                            FROM ICSInventoryLot lot
			                            LEFT JOIN ICSExtension ext ON ext.ID=lot.ExtensionID
			                            LEFT JOIN ICSWareHouseLotInfo info ON info.LotNo=lot.LotNo
			                            WHERE lot.LotNo='{1}'
	                            END";
                    sql = string.Format(sql, JsonData.TransCode, JsonData.Code);
                    
                    DataTable table = DBHelper.SQlReturnData(sql, cmd);
                    cmd.Transaction.Commit();
                    return table;
                }
                catch (Exception ex)
                {
                    if (cmd.Transaction != null)
                        cmd.Transaction.Rollback();
                    log.Error(ex.Message);
                    throw new Exception(ex.Message);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                    }
                    conn.Dispose();
                }
            }
        }

        public static string ICSCartScheduleCreate(List<CartScheduleModel> JsonData)
        {
            var language = LanguageHelper.GetName("WMSAPIInfo");
            Boolean flag;
            if (JsonData.Count <= 0)
            {
                throw new Exception(language.GetNameByCode("WMSAPIInfo007"));//"传送数据为空!"
            }
            using (SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString))
            {
                conn.Open();
                SqlTransaction sqlTran = conn.BeginTransaction();
                SqlCommand cmd = new SqlCommand();
                cmd.Transaction = sqlTran;
                cmd.Connection = conn;
                cmd.CommandTimeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["TimeOut"]);
                try
                {
                    string sql = string.Empty;
                    string TransType = string.Empty;
                    string Identification = Guid.NewGuid().ToString();
                    foreach (var item in JsonData)
                    {
                        string MergeID = "";

                        foreach (var itemInfo in item.detail)
                        {
                            flag = ICSWareHouseService.ICSCartScheduleCreate(itemInfo.LotNo,itemInfo.Quantity, item.CartNo, item.User, item.WorkPoint, cmd, language);
                            if (!flag)
                            {
                                log.Error("生成车次条码清单失败");
                                throw new Exception("车次 " + item.CartNo + " 与条码 " + itemInfo.LotNo + " 生成清单失败");
                            }
                        }

                    }
                    cmd.Transaction.Commit();

                    return LanguageHelper.GetNameSingle("WMSAPI001");// "接口调用成功!";
                }
                catch (Exception ex)
                {
                    if (cmd.Transaction != null)
                        cmd.Transaction.Rollback();
                    log.Error(ex.Message);
                    throw new Exception(ex.Message);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                    }
                    conn.Dispose();
                }
            }
        }
        #endregion

        #region 移库
        /// <summary>
        /// 移库
        /// </summary>
        /// <param name="JsonData"></param>
        /// <returns></returns>
        public static DataTable LibraryUpdate(List<ICSLibraryModel> JsonData)
        {
            var language = LanguageHelper.GetName("WMSAPIInfo");
            if (JsonData.Count <= 0)
            {
                throw new Exception(language.GetNameByCode("WMSAPIInfo007"));//"传送数据为空!"
            }
            using (SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString))
            {
                conn.Open();
                SqlTransaction sqlTran = conn.BeginTransaction();
                SqlCommand cmd = new SqlCommand();
                cmd.Transaction = sqlTran;
                cmd.Connection = conn;
                cmd.CommandTimeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["TimeOut"]);
                try
                {
                    string sql = string.Empty;
                    string Identification = Guid.NewGuid().ToString();
                    foreach (var item in JsonData)
                    {
                        if (string.IsNullOrEmpty(item.LotNo))
                        {
                            throw new Exception(language.GetNameByCode("WMSAPIInfo005"));//"条码不能为空!"
                        }

                        //验证仓库库位信息
                        sql = @"IF NOT EXISTS(SELECT a.ID FROM ICSWareHouse a WHERE a.WarehouseCode='{0}' AND a.WorkPoint='{1}')
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo069") + @"',16,1);
                                    RETURN
                                END
                                IF NOT EXISTS(SELECT a.ID FROM ICSLocation a WHERE a.LocationCode='{2}' AND a.WorkPoint='{1}')
                                BEGIN
	                                RAISERROR('" + string.Format(language.GetNameByCode("WMSAPIInfo072"), "{2}") + @"',16,1);
                                    RETURN
                                END
                                IF NOT EXISTS(SELECT a.ID 
                                FROM ICSWareHouse a 
                                INNER JOIN ICSLocation b ON a.ID=b.WHID AND a.WorkPoint=b.WorkPoint
                                WHERE a.WarehouseCode='{0}' AND a.WorkPoint='{1}' AND b.LocationCode='{2}')
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo071") + @"',16,1);
                                    RETURN
                                END";
                        sql = string.Format(sql, item.WarehouseCode, item.WorkPoint, item.LocationCode);
                        DBHelper.ExecuteNonQuery(sql, cmd);

                        //更新条码信息
                        ICSWareHouseLotInfoService.WareHouseLotInfoLibrary(Identification, item.TransCode, item.TransSequence, item.WarehouseCode, item.LocationCode, item.LotNo,
                            item.User, item.WorkPoint, "7", "29", cmd, language);
                    }
                    DataTable table = GetData(Identification, 3, cmd);
                    cmd.Transaction.Commit();
                    return table;
                }
                catch (Exception ex)
                {
                    if (cmd.Transaction != null)
                        cmd.Transaction.Rollback();
                    log.Error(ex.Message);
                    throw new Exception(ex.Message);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                    }
                    conn.Dispose();
                }
            }
        }
        #endregion

        #region 合并
        /// <summary>
        /// 合并
        /// </summary>
        /// <param name="JsonData"></param>
        /// <returns></returns>
        public static DataTable LOTMergeCreate(List<LOTCreateIModel> JsonData)
        {
            var language = LanguageHelper.GetName("WMSAPIInfo");
            DataTable printTable = new DataTable();
            if (JsonData.Count <= 0)
            {
                throw new Exception(language.GetNameByCode("WMSAPIInfo007"));//"传送数据为空!"
            }
            using (SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString))
            {
                conn.Open();
                SqlTransaction sqlTran = conn.BeginTransaction();
                SqlCommand cmd = new SqlCommand();
                cmd.Transaction = sqlTran;
                cmd.Connection = conn;
                cmd.CommandTimeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["TimeOut"]);
                try
                {
                    string Identification = Guid.NewGuid().ToString();
                    foreach (var item in JsonData)
                    {
                        if (string.IsNullOrEmpty(item.LotNo))
                        {
                            throw new Exception(language.GetNameByCode("WMSAPIInfo005"));//"条码不能为空!"
                        }
                        else if (item.detail.Count <= 0)
                        {
                            throw new Exception(language.GetNameByCode("WMSAPIInfo028"));//"明细信息不能为空!");
                        }
                        //合并前日志
                        ICSWareHouseLotInfoService.WareHouseLotInfoLogMerge(Identification, item.LotNo, item.User, item.WorkPoint, "5",
                            TransTypeEnum.LOTMergeBefore.GetDescription<DBValue>(),"", cmd, language);

                        foreach (var info in item.detail)
                        {
                            //合并前日志
                            ICSWareHouseLotInfoService.WareHouseLotInfoLogMerge(Identification, info.CurrentLotNo, item.User, item.WorkPoint, "5",
                                TransTypeEnum.LOTMergeBefore.GetDescription<DBValue>(),"", cmd, language);

                            //更新条码信息
                            ICSWareHouseLotInfoService.WareHouseLotInfoMerge(Identification, item.LotNo, info.CurrentLotNo, info.CurrentQuantity, item.User, item.WorkPoint, "5",
                                TransTypeEnum.LOTMergeAfter.GetDescription<DBValue>(), cmd, language);
                        }

                        //合并后日志
                        printTable = ICSWareHouseLotInfoService.WareHouseLotInfoLogMerge(Identification, item.LotNo, item.User, item.WorkPoint, "5",
                            TransTypeEnum.LOTMergeAfter.GetDescription<DBValue>(),"", cmd, language);
                    }
                    if (!printTable.Equals("{}"))
                    {
                        cmd.Transaction.Commit();
                        return printTable;
                    }
                    else
                    {
                        DataTable table = GetData(Identification, 1, cmd);
                        cmd.Transaction.Commit();
                        return table;
                    }
                }
                catch (Exception ex)
                {
                    if (cmd.Transaction != null)
                        cmd.Transaction.Rollback();
                    log.Error(ex.Message);
                    throw new Exception(ex.Message);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                    }
                    conn.Dispose();
                }
            }
        }
        #endregion

        #region 拆分
        /// <summary>
        /// 拆分
        /// </summary>
        /// <param name="JsonData"></param>
        /// <returns></returns>
        public static DataTable LOTSplitCreate(List<LOTCreateIModel> JsonData)
        {
            var language = LanguageHelper.GetName("WMSAPIInfo");
            string newlotno = "";
            DataTable printTable = new DataTable();
            if (JsonData.Count <= 0)
            {
                throw new Exception(language.GetNameByCode("WMSAPIInfo007"));//"传送数据为空!"
            }

            using (SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString))
            {
                conn.Open();
                SqlTransaction sqlTran = conn.BeginTransaction();
                SqlCommand cmd = new SqlCommand();
                cmd.Transaction = sqlTran;
                cmd.Connection = conn;
                cmd.CommandTimeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["TimeOut"]);
                try
                {
                    string Identification = Guid.NewGuid().ToString();
                    foreach (var item in JsonData)
                    {
                        if (string.IsNullOrEmpty(item.LotNo))
                        {
                            throw new Exception(language.GetNameByCode("WMSAPIInfo005"));//"条码不能为空!"
                        }
                        else if (item.detail.Count <= 0)
                        {
                            throw new Exception(language.GetNameByCode("WMSAPIInfo028"));//"明细信息不能为空!");
                        }
                        //拆分前日志
                        ICSWareHouseLotInfoService.WareHouseLotInfoLog(Identification, item.LotNo, item.User, item.WorkPoint, "4",
                            TransTypeEnum.LOTSplitBefore.GetDescription<DBValue>(),"", cmd, language);

                        foreach (var info in item.detail)
                        {
                            newlotno = info.CurrentLotNo;
                            //更新条码信息
                            ICSWareHouseLotInfoService.WareHouseLotInfoSplit(Identification, item.LotNo, info.CurrentLotNo, info.CurrentQuantity, item.User, item.WorkPoint, "4",
                                TransTypeEnum.LOTSplitAfter.GetDescription<DBValue>(), cmd, language);
                        }

                        //拆分后日志
                        printTable=ICSWareHouseLotInfoService.WareHouseLotInfoLog(Identification, item.LotNo, item.User, item.WorkPoint, "4",
                            TransTypeEnum.LOTSplitAfter.GetDescription<DBValue>(), newlotno, cmd, language);
                    }

                    //DataTable table = GetData(Identification, 1, cmd);
                    //cmd.Transaction.Commit();
                    //return table;

                    if (!printTable.Equals("{}"))
                    {
                        cmd.Transaction.Commit();
                        return printTable;
                    }
                    else
                    {
                        DataTable table = GetData(Identification, 1, cmd);
                        cmd.Transaction.Commit();
                        return table;
                    }
                }
                catch (Exception ex)
                {
                    if (cmd.Transaction != null)
                        cmd.Transaction.Rollback();
                    log.Error(ex.Message);
                    throw new Exception(ex.Message);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                    }
                    conn.Dispose();
                }
            }
        }

        /// <summary>
        /// 拆分(奥美)
        /// </summary>
        /// <param name="JsonData"></param>
        /// <returns></returns>
        public static DataTable AMLOTSplitCreate(List<LOTCreateIModel> JsonData)
        {
            var language = LanguageHelper.GetName("WMSAPIInfo");
            string newlotno = "";
            DataTable printTable = new DataTable();
            if (JsonData.Count <= 0)
            {
                throw new Exception(language.GetNameByCode("WMSAPIInfo007"));//"传送数据为空!"
            }

            using (SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString))
            {
                conn.Open();
                SqlTransaction sqlTran = conn.BeginTransaction();
                SqlCommand cmd = new SqlCommand();
                cmd.Transaction = sqlTran;
                cmd.Connection = conn;
                cmd.CommandTimeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["TimeOut"]);
                try
                {
                    string Identification = Guid.NewGuid().ToString();
                    foreach (var item in JsonData)
                    {
                        if (string.IsNullOrEmpty(item.LotNo))
                        {
                            throw new Exception(language.GetNameByCode("WMSAPIInfo005"));//"条码不能为空!"
                        }
                        else if (item.detail.Count <= 0)
                        {
                            throw new Exception(language.GetNameByCode("WMSAPIInfo028"));//"明细信息不能为空!");
                        }
                        //拆分前日志
                        ICSWareHouseLotInfoService.WareHouseLotInfoLog(Identification, item.LotNo, item.User, item.WorkPoint, "4",
                            TransTypeEnum.LOTSplitBefore.GetDescription<DBValue>(), "", cmd, language);

                        foreach (var info in item.detail)
                        {
                            newlotno = info.CurrentLotNo;
                            //更新条码信息
                            ICSWareHouseLotInfoService.AMWareHouseLotInfoSplit(Identification, item.LotNo, info.CurrentLotNo, info.CurrentQuantity, item.User, item.WorkPoint, "4",
                                TransTypeEnum.LOTSplitAfter.GetDescription<DBValue>(), cmd, language);
                        }

                        //拆分后日志
                        printTable = ICSWareHouseLotInfoService.WareHouseLotInfoLog(Identification, item.LotNo, item.User, item.WorkPoint, "4",
                            TransTypeEnum.LOTSplitAfter.GetDescription<DBValue>(), newlotno, cmd, language);
                    }

                    //DataTable table = GetData(Identification, 1, cmd);
                    //cmd.Transaction.Commit();
                    //return table;

                    if (!printTable.Equals("{}"))
                    {
                        cmd.Transaction.Commit();
                        return printTable;
                    }
                    else
                    {
                        DataTable table = GetData(Identification, 1, cmd);
                        cmd.Transaction.Commit();
                        return table;
                    }
                }
                catch (Exception ex)
                {
                    if (cmd.Transaction != null)
                        cmd.Transaction.Rollback();
                    log.Error(ex.Message);
                    throw new Exception(ex.Message);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                    }
                    conn.Dispose();
                }
            }
        }
        #endregion
        /// <summary>
        /// 获取出入库记录信息
        /// </summary>
        /// <param name="Identification"></param>
        /// <param name="type">1:入库,2:出库,3:调拨</param>
        /// <param name="cmd"></param>
        /// <returns></returns>
        private static DataTable GetData(string Identification, int type, SqlCommand cmd)
        {
            #region SLQ
            string sql = @"SELECT log.ID,
	                        log.TransCode,
	                        log.TransSequence,
	                        log.LotNo,
	                        log.InvCode,
	                        inv.InvName,
	                        inv.InvStd,
	                        log.Quantity,
	                        inv.InvUnit,
	                        log.Quantity*(lot.Amount/lot.Quantity) AS Amount,
	                        inv.AmountUnit,
	                        {1}
	                        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 AS BatchCode,
	                        ext.Version,
	                        ext.Brand,
	                        ext.cFree1,
	                        ext.cFree2,
	                        ext.cFree3,
	                        ext.cFree4,
	                        ext.cFree5,
	                        ext.cFree6,
	                        ext.cFree7,
	                        ext.cFree8,
	                        ext.cFree9,
	                        ext.cFree10,
	                        type.Name AS TransType,
	                        log.MUSER AS [User],
	                        log.MTIME AS [MTime]
                        FROM ICSWareHouseLotInfoLog log
                        LEFT JOIN ICSType type ON type.TableCode='ICSWareHouseLotInfoLog' AND type.ColumnCode='BusinessCode' AND log.BusinessCode=type.Code AND log.WorkPoint=type.WorkPoint
                        INNER JOIN ICSInventoryLot lot ON log.LotNo=lot.LotNo AND log.WorkPoint=lot.WorkPoint
                        INNER JOIN ICSExtension ext ON lot.ExtensionID=ext.ID AND lot.WorkPoint=ext.WorkPoint
                        INNER JOIN ICSInventory inv ON log.InvCode=inv.InvCode AND log.WorkPoint=inv.WorkPoint
                        {2}
                        LEFT JOIN ICSInventoryBatchEnable invBat ON log.InvCode=invBat.InvCode AND log.FromWarehouseCode=invBat.WHCode AND log.WorkPoint=invBat.WorkPoint
                        WHERE log.Identification='{0}'";
            #endregion

            string columns = @"log.ToWarehouseCode AS WHCode,
	                        log.ToLocationCode AS LocationCode,
	                        wh.WarehouseName AS WHName,
	                        loc.LocationName AS LocationName,";
            string tables = @"INNER JOIN ICSWarehouse wh ON log.ToWarehouseCode=wh.WarehouseCode AND log.WorkPoint=wh.WorkPoint
                            INNER JOIN ICSLocation loc ON log.ToLocationCode=loc.LocationCode AND log.WorkPoint=loc.WorkPoint";

            if (type == 2)//出库
            {
                columns = @"log.FromWarehouseCode AS WHCode,
	                        log.FromLocationCode AS LocationCode,
	                        wh.WarehouseName AS WHName,
	                        loc.LocationName AS LocationName,";
                tables = @"INNER JOIN ICSWarehouse wh ON log.FromWarehouseCode=wh.WarehouseCode AND log.WorkPoint=wh.WorkPoint
                            INNER JOIN ICSLocation loc ON log.FromLocationCode=loc.LocationCode AND log.WorkPoint=loc.WorkPoint";
            }
            else if (type == 3)//调拨
            {
                columns = @"log.FromWarehouseCode AS FromWHCode,
	                        log.FromLocationCode,
	                        wh.WarehouseName AS FromWHName,
	                        loc.LocationName AS FromLocationName,
                            log.ToWarehouseCode AS ToWHCode,
	                        log.ToLocationCode,
	                        whto.WarehouseName AS ToWHName,
	                        locto.LocationName AS ToLocationName,";
                tables = @"INNER JOIN ICSWarehouse wh ON log.FromWarehouseCode=wh.WarehouseCode AND log.WorkPoint=wh.WorkPoint
                            INNER JOIN ICSLocation loc ON log.FromLocationCode=loc.LocationCode AND log.WorkPoint=loc.WorkPoint
                            INNER JOIN ICSWarehouse whto ON log.ToWarehouseCode=whto.WarehouseCode AND log.WorkPoint=whto.WorkPoint
                            INNER JOIN ICSLocation locto ON log.ToLocationCode=locto.LocationCode AND log.WorkPoint=locto.WorkPoint";
            }
            sql = string.Format(sql, Identification, columns, tables);

            return DBHelper.SQlReturnData(sql, cmd);
        }
        /// <summary>
        /// 先进先出批次管控
        /// </summary>
        /// <param name="LotNo"></param>
        /// <param name="WorkPoitCode"></param>
        /// <param name="cmd"></param>
        /// <returns></returns>
        public static string CanOut(string LotNo, string WorkPoitCode, string ScanLotCode, string sqlnew, SqlCommand cmd, Dictionary<string, string> language)
        {
            try
            {
                string sql = "";
                string tsql = @"SELECT Top 1 a.F_ItemName
	                                FROM Sys_SRM_ItemsDetail a
	                                INNER JOIN Sys_SRM_Items b ON a.F_ItemId=b.F_Id
	                                WHERE b.F_EnCode='MtimeControl' AND a.F_EnabledMark='1'
																	ORDER BY a.F_SortCode DESC";
                tsql = string.Format(tsql);
                DataTable dttt = DBHelper.SQlReturnData(tsql, cmd);
               
                    //根据Sys_SRM_Items.F_Description备注列维护的提前天数,比如维护的是1,最早条码是2022.5.16,现在扫描2022.5.17的条码也能出库,扫描2022.5.18的条码不能直接出,需要校验以下逻辑
                    sql = @"DECLARE @CountNO INT,@Days INT
                                SELECT @Days=F_Description FROM Sys_SRM_Items WHERE F_EnCode='FIFO'

                                SET @CountNO=(
	                                SELECT COUNT(a.LotNO) FROM ICSWareHouseLotInfo a
	                                INNER JOIN ICSInventoryLot b ON a.LotNO=b.LotNO AND a.WorkPoint=b.WorkPoint
                                    INNER JOIN ICSExtension bext on b.ExtensionID=bext.id AND b.WorkPoint=bext.WorkPoint
	                                WHERE  a.WorkPoint='{1}' AND ISNULL(a.Quantity,0)>0  AND 1=1
	                                AND CONVERT(varchar(100), {2}, 23)<
	                                (SELECT DATEADD(DAY, -@Days, CONVERT(varchar(100), {3}, 23)) FROM ICSWareHouseLotInfo x
		                                INNER JOIN ICSInventoryLot y ON x.LotNO=y.LotNO AND x.WorkPoint=y.WorkPoint
																		INNER JOIN ICSExtension yext on y.ExtensionID=yext.id AND b.WorkPoint=yext.WorkPoint
		                                WHERE x.LotNO='{0}' AND x.WorkPoint='{1}' AND y.INVCode=b.INVCode " + sqlnew + @")
                                )
                                IF @CountNO>0
                                BEGIN
	                                SELECT TOP 1 CASE a.F_ItemCode WHEN 'FIFO01' THEN '1' WHEN 'FIFO02' THEN '2' ELSE '3' END AS Type
	                                FROM Sys_SRM_ItemsDetail a
	                                INNER JOIN Sys_SRM_Items b ON a.F_ItemId=b.F_Id
	                                WHERE b.F_EnCode='FIFO' AND a.F_EnabledMark='1'
	                                ORDER BY a.F_SortCode DESC
                                END
                                ELSE
                                BEGIN
	                                SELECT @CountNO
                                END";



                //0 - 已经是最早的批次
                //1 - 不管控
                //2 - 提醒
                //3 - 限制
                if (dttt.Rows[0]["F_ItemName"].ToString() == "失效日期")
                {
                    sql = string.Format(sql, LotNo, WorkPoitCode, "ISNULL(b.ExpirationDate,b.ProductDate)", "ISNULL(y.ExpirationDate,y.ProductDate)");
                }
                else if (dttt.Rows[0]["F_ItemName"].ToString() == "生产日期")
                {
                    sql = string.Format(sql, LotNo, WorkPoitCode, "b.ProductDate", "y.ProductDate");
                }
                else
                {
                    sql = string.Format(sql, LotNo, WorkPoitCode, "a.InDate", "x.InDate");
                }
                    
                if (!string.IsNullOrWhiteSpace(ScanLotCode))
                {
                    sql = sql.Replace("1=1", "a.LotNO NOT IN (" + ScanLotCode + ")");
                }
                var res = DBHelper.ExecuteScalar(sql, cmd).ToString();
                if (string.IsNullOrWhiteSpace(res))
                {
                    throw new Exception(language.GetNameByCode("WMSAPIInfo183"));//"查询管控信息失败!");
                }
                else
                    return res;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        /// <summary>
        /// 获取自由项名称
        /// </summary>
        /// <param name="LotNo"></param>
        /// <param name="WorkPoitCode"></param>
        /// <param name="cmd"></param>
        /// <returns></returns>
        public static string GetExtentionName(string Code, string WorkPoitCode, SqlCommand cmd, Dictionary<string, string> language)
        {
            try
            {
                //根据Sys_SRM_Items.F_Description备注列维护的提前天数,比如维护的是1,最早条码是2022.5.16,现在扫描2022.5.17的条码也能出库,扫描2022.5.18的条码不能直接出,需要校验以下逻辑
                string sql = @"select ColName from ICSExtensionEnable where ColCode='{0}' and WorkPoint='{1}'";
                sql = string.Format(sql, Code, WorkPoitCode);
                var res = DBHelper.ExecuteScalar(sql, cmd).ToString();
                    return res;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        /// <summary>
        /// 保质期管控
        /// </summary>
        /// <param name="LotNo"></param>
        /// <param name="WorkPoitCode"></param>
        /// <param name="cmd"></param>
        /// <returns></returns>
        public static string Effective(string LotNo, string WorkPoitCode, SqlCommand cmd, Dictionary<string, string> language)
        {
            try
            {
                string sql = @"DECLARE @CountNO INT,@Days INT,@CurrentDays INT
                                SELECT @CountNO=EffectiveEnable,@Days=EffectiveDays,@CurrentDays=DATEDIFF(DAY, GETDATE(), b.ExpirationDate) FROM ICSInventory a
                                INNER JOIN ICSInventoryLot b ON a.InvCode=b.InvCode AND a.WorkPoint=b.WorkPoint
                                INNER JOIN ICSWareHouseLotInfo c ON b.LotNO=c.LotNO AND b.WorkPoint=c.WorkPoint
                                WHERE  b.LotNO='{0}' AND b.WorkPoint='{1}'
                                IF @CountNO='1' AND @CurrentDays<0
                                BEGIN
	                                SELECT TOP 1 CASE a.F_ItemCode WHEN 'Effective01' THEN '1' WHEN 'Effective02' THEN '2' ELSE '3' END AS Type
	                                FROM Sys_SRM_ItemsDetail a
	                                INNER JOIN Sys_SRM_Items b ON a.F_ItemId=b.F_Id
	                                WHERE b.F_EnCode='Effective' AND a.F_EnabledMark='1'
	                                ORDER BY a.F_SortCode DESC
                                END
                                ELSE
                                BEGIN
	                                SELECT @CountNO
                                END";
                //0 - 已经是最早的批次
                //1 - 不管控
                //2 - 提醒
                //3 - 限制
                sql = string.Format(sql, LotNo, WorkPoitCode);
                var res = DBHelper.ExecuteScalar(sql, cmd).ToString();
                if (string.IsNullOrWhiteSpace(res))
                {
                    throw new Exception(language.GetNameByCode("WMSAPIInfo183"));//"查询管控信息失败!");
                }
                else
                    return res;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        #region 包装
        /// <summary>
        /// 查询包装信息
        /// </summary>
        /// <param name="JsonData"></param>
        /// <returns></returns>
        public static object ContainerGet(ICSContainer JsonData)
        {
            var language = LanguageHelper.GetName("WMSAPIInfo");
            using (SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString))
            {
                conn.Open();
                SqlTransaction sqlTran = conn.BeginTransaction();
                SqlCommand cmd = new SqlCommand();
                cmd.Transaction = sqlTran;
                cmd.Connection = conn;
                cmd.CommandTimeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["TimeOut"]);
                try
                {
                    string sql = string.Empty;
                    //目标包装
                    if (JsonData.ToContainerCode != null)
                    {
                        sql = @"IF NOT EXISTS(SELECT ID FROM ICSContainer WHERE ContainerCODE ='{0}' and WorkPoint='{1}')
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo072") + @"',16,1);
	                                RETURN
                                END
                                SELECT ContainerCode,ContainerName FROM ICSContainer WHERE  ContainerCODE ='{0}' and WorkPoint='{1}'";
                        sql = string.Format(sql, JsonData.ToContainerCode, JsonData.WorkPoint);
                    }
                    ///原包装
                    else if (JsonData.FromContainerCode != null)
                    {
                        sql = @"IF NOT EXISTS(SELECT ID FROM ICSContainer WHERE ContainerCODE ='{0}' and WorkPoint='{1}')
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo072") + @"',16,1);
	                                RETURN
                                END
                                IF NOT EXISTS(SELECT a.ID FROM ICSContainer a
	                                INNER JOIN ICSContainerLot b ON a.ID=b.ContainerID
	                                WHERE a.ContainerCODE ='{0}' and a.WorkPoint='{1}')
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo073") + @"',16,1);
	                                RETURN
                                END
                                SELECT ContainerCode,ContainerName FROM ICSContainer WHERE  ContainerCODE ='{0}' and WorkPoint='{1}'";
                        sql = string.Format(sql, JsonData.FromContainerCode, JsonData.WorkPoint);
                    }
                    else
                    {
                        throw new Exception(language.GetNameByCode("WMSAPIInfo029"));//"请传入包装条码!");
                    }

                    DataTable table = DBHelper.SQlReturnData(sql, cmd);
                    cmd.Transaction.Commit();
                    return table;
                }
                catch (Exception ex)
                {
                    if (cmd.Transaction != null)
                        cmd.Transaction.Rollback();
                    log.Error(ex.Message);
                    throw new Exception(ex.Message);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                    }
                    conn.Dispose();
                }
            }
        }

        /// <summary>
        /// 修改包装信息
        /// </summary>
        /// <param name="JsonData"></param>
        /// <returns></returns>
        public static DataTable ContainerUpdate(List<ICSContainer> JsonData)
        {
            var language = LanguageHelper.GetName("WMSAPIInfo");
            using (SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString))
            {
                conn.Open();
                SqlTransaction sqlTran = conn.BeginTransaction();
                SqlCommand cmd = new SqlCommand();
                cmd.Transaction = sqlTran;
                cmd.Connection = conn;
                cmd.CommandTimeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["TimeOut"]);
                try
                {
                    string sql = string.Empty;
                    string codes = string.Empty;
                    foreach (ICSContainer container in JsonData)
                    {
                        sql = @"IF NOT EXISTS(SELECT ID FROM ICSContainer WHERE ContainerCODE ='{0}' and WorkPoint='{1}')
                                    BEGIN
	                                    RAISERROR('" + language.GetNameByCode("WMSAPIInfo072") + @"',16,1);
	                                    RETURN
                                    END
                                    IF NOT EXISTS(SELECT a.ID FROM ICSContainer a
	                                    INNER JOIN ICSContainerLot b ON a.ID=b.ContainerID
	                                    WHERE a.ContainerCODE ='{0}' and a.WorkPoint='{1}')
                                    BEGIN
	                                    RAISERROR('" + language.GetNameByCode("WMSAPIInfo073") + @"',16,1);
	                                    RETURN
                                    END
                                    IF NOT EXISTS(SELECT ID FROM ICSContainer WHERE ContainerCODE ='{2}' and WorkPoint='{1}')
                                    BEGIN
	                                    RAISERROR('" + string.Format(language.GetNameByCode("WMSAPIInfo072"), "{2}") + @"',16,1);
	                                    RETURN
                                    END
                                    UPDATE b SET ContainerID=c.ID
                                    FROM ICSContainer a
                                    INNER JOIN ICSContainerLot b ON a.ID=b.ContainerID
                                    INNER JOIN ICSContainer c ON c.ContainerCODE ='{2}' and a.WorkPoint=c.WorkPoint
                                    WHERE a.ContainerCODE ='{0}' and a.WorkPoint='{1}'";
                        sql = string.Format(sql, container.FromContainerCode, container.WorkPoint, container.ToContainerCode);

                        if (!DBHelper.ExecuteNonQuery(sql, cmd))
                        {
                            throw new Exception(language.GetNameByCode("WMSAPIInfo030"));//"包装更新失败!");
                        }
                        codes += "'" + container.ToContainerCode + container.WorkPoint + "',";
                    }
                    sql = @"SELECT a.ContainerCode, a.ContainerName,b.LotNo FROM ICSContainer a
                                    INNER JOIN ICSContainerLot b ON a.ID=b.ContainerID
                                    WHERE a.ContainerCODE+a.WorkPoint IN({0})";
                    sql = string.Format(sql, codes.Substring(0,codes.Length - 1));
                    DataTable table = DBHelper.SQlReturnData(sql, cmd);
                    cmd.Transaction.Commit();
                    return table;
                }
                catch (Exception ex)
                {
                    if (cmd.Transaction != null)
                        cmd.Transaction.Rollback();
                    log.Error(ex.Message);
                    throw new Exception(ex.Message);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                    }
                    conn.Dispose();
                }
            }
        }
        #endregion

        #region 盘点
        /// <summary>
        /// 创建盘点单
        /// </summary>
        /// <param name="JsonData"></param>
        /// <returns></returns>
        public static DataTable CheckCreate(List<ICSCheck> JsonData)
        {
            var language = LanguageHelper.GetName("WMSAPIInfo");
            if (JsonData.Count <= 0)
            {
                throw new Exception(language.GetNameByCode("WMSAPIInfo007"));//"传送数据为空!"
            }
            using (SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString))
            {
                conn.Open();
                SqlTransaction sqlTran = conn.BeginTransaction();
                SqlCommand cmd = new SqlCommand();
                cmd.Transaction = sqlTran;
                cmd.Connection = conn;
                cmd.CommandTimeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["TimeOut"]);
                try
                {
                    string Code = string.Empty;
                    string sql = string.Empty;
                    foreach (var item in JsonData)
                    {
                        if (string.IsNullOrEmpty(item.User))
                        {
                            throw new Exception(language.GetNameByCode("WMSAPIInfo018"));//"操作人不能为空!");
                        }
                        if (string.IsNullOrEmpty(item.WorkPoint))
                        {
                            throw new Exception(language.GetNameByCode("WMSAPIInfo004"));//"站点不能为空!"
                        }

                        //获取单号
                        sql = @"IF NOT EXISTS(SELECT F_Account FROM Sys_SRM_User WHERE F_Account='{0}' AND F_Location='{1}')
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo060") + @"',16,1);
                                    RETURN
                                END

                                DECLARE @MaxNO INT,@date varchar(20)='CHK'+SUBSTRING(CONVERT(varchar(8), GETDATE(), 112), 1, 8)
                                SELECT @MaxNO=SUBSTRING(MAX(CheckCode),LEN(@date)+1,LEN(MAX(CheckCode))-LEN(@date))+1 FROM ICSCheck 
                                    WHERE SUBSTRING(CheckCode, 1, LEN(@date))=@date
                                IF @MaxNO IS NULL
                                BEGIN
	                                SELECT @date+'00001' AS Code
                                END
                                ELSE
                                BEGIN
	                                SELECT @date+REPLICATE('0',5-LEN(@MaxNO))+CAST(@MaxNO AS nvarchar(10))  AS Code
                                END ";
                        sql = string.Format(sql, item.User, item.WorkPoint);
                        Code = DBHelper.ExecuteScalar(sql, cmd).ToString();
                        //创建盘点单
                        foreach (var itemInfo in item.detail)
                        {
                            int len = itemInfo.SelectLevel.Length;
                            sql = @"IF NOT EXISTS(SELECT id FROM ICSWareHouseLotInfo WHERE SUBSTRING(LocationCode,1,{4}) = '{1}')
                                    BEGIN
	                                    RAISERROR('" + language.GetNameByCode("WMSAPIInfo460") + @"',16,1);
                                        RETURN
                                    END
                                    INSERT INTO ICSCheck (ID,CheckCode,SelectLevel,Status,Quantity,Amount,MUSER,MUSERName,MTIME,WorkPoint)
                                    SELECT  NEWID(),'{0}','{1}','1',SUM(a.Quantity),0,b.F_Account,b.F_RealName,GETDATE(),b.F_Location
                                    FROM ICSWareHouseLotInfo a
                                    INNER JOIN Sys_SRM_User b ON b.F_Account='{2}' AND b.F_Location='{3}'   
                                    WHERE SUBSTRING(a.LocationCode,1,{4}) = '{1}' 
                                    GROUP BY b.F_Account,b.F_RealName,b.F_Location";
                            sql = string.Format(sql, Code, itemInfo.SelectLevel, item.User, item.WorkPoint, len);

                            if (!DBHelper.ExecuteNonQuery(sql, cmd))
                            {
                                throw new Exception(language.GetNameByCode("WMSAPIInfo031"));//"盘点单创建失败!");
                            }
                        }
                    }
                    if (string.IsNullOrWhiteSpace(Code))
                    {
                        throw new Exception(language.GetNameByCode("WMSAPIInfo032"));//"盘点单单号不能为空!");
                    }
                    #region 查询返回数据
                    sql = @"SELECT a.ID,a.CheckCode,a.SelectLevel,
	                            a.Quantity,
	                            a.Amount,
	                            a.MUSER AS [User],
	                            a.MTIME AS [MTime]
                            FROM ICSCheck a
                            WHERE a.CheckCode='{0}'";
                    sql = string.Format(sql, Code);
                    DataTable data = DBHelper.SQlReturnData(sql, cmd);
                    #endregion
                    cmd.Transaction.Commit();
                    return data;
                }
                catch (Exception ex)
                {
                    if (cmd.Transaction != null)
                        cmd.Transaction.Rollback();
                    log.Error(ex.Message);
                    throw new Exception(ex.Message);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                    }
                    conn.Dispose();
                }
            }
        }

        /// <summary>
        /// 盘点扫描
        /// </summary>
        /// <param name="JsonData"></param>
        /// <returns></returns>
        public static DataTable LOTCheckCreate(List<ICSCheck> JsonData)
        {
            var language = LanguageHelper.GetName("WMSAPIInfo");
            if (JsonData.Count <= 0)
            {
                throw new Exception(language.GetNameByCode("WMSAPIInfo007"));//"传送数据为空!"
            }
            using (SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString))
            {
                conn.Open();
                SqlTransaction sqlTran = conn.BeginTransaction();
                SqlCommand cmd = new SqlCommand();
                cmd.Transaction = sqlTran;
                cmd.Connection = conn;
                cmd.CommandTimeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["TimeOut"]);
                try
                {
                    string lots = string.Empty;
                    string sql = string.Empty;
                    int result = 0;
                    string Identification = Guid.NewGuid().ToString();
                    foreach (var item in JsonData)
                    {
                        if (string.IsNullOrEmpty(item.User))
                        {
                            throw new Exception(language.GetNameByCode("WMSAPIInfo018"));//"操作人不能为空!");
                        }   
                        if (string.IsNullOrEmpty(item.WorkPoint))
                        {
                            throw new Exception(language.GetNameByCode("WMSAPIInfo004"));//"站点不能为空!"
                        }
                        if (string.IsNullOrEmpty(item.CheckCode))
                        {
                            throw new Exception(language.GetNameByCode("WMSAPIInfo032"));//"盘点单号不能为空!");
                        }

                        //校验
                        sql = @"IF NOT EXISTS(SELECT F_Account FROM Sys_SRM_User WHERE F_Account='{0}' AND F_Location='{1}')
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo060") + @"',16,1);
                                    RETURN
                                END

                                IF NOT EXISTS(SELECT ID FROM ICSCheck WHERE CheckCode='{2}' AND WorkPoint='{1}')
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo075") + @"',16,1);
                                    RETURN
                                END";
                        sql = string.Format(sql, item.User, item.WorkPoint, item.CheckCode);
                        DBHelper.ExecuteNonQuery(sql, cmd);
                        //创建盘点单
                        foreach (var itemInfo in item.detail)
                        {

                            string chekksql = @"select d.EATTRIBUTE1 FROM  ICSInventoryLot c 
                            INNER JOIN ICSInventory d on c.InvCode=d.InvCode and c.WorkPoint=d.WorkPoint
                            WHERE  c.WorkPoint='{1}' and c.lotno='{2}' and d.AmountEnable='1'";
                            chekksql = string.Format(chekksql, item.CheckCode, item.WorkPoint, itemInfo.LotNo);
                            DataTable dta = DBHelper.SQlReturnData(chekksql, cmd);
                            if (dta.Rows.Count > 0)
                            {
                                itemInfo.ActualQuantity = (decimal.Parse(itemInfo.ActualQuantity) * decimal.Parse(dta.Rows[0]["EATTRIBUTE1"].ToString())).ToString();
                            }
                            sql = @"IF NOT EXISTS(SELECT LotNo FROM ICSWareHouseLotInfo WHERE LotNo='{1}' AND WorkPoint='{3}')
                                    BEGIN
	                                    RAISERROR('" + language.GetNameByCode("WMSAPIInfo076") + @"',16,1);
                                        RETURN
                                    END
                                
                                    IF EXISTS(SELECT LotNo FROM ICSCheckDetail a
                                            LEFT JOIN ICSCheck b ON a.CheckID=b.ID AND  a.WorkPoint=b.WorkPoint
                                            WHERE b.CheckCode='{0}' AND a.LotNo='{1}' AND a.WorkPoint='{3}')
                                    BEGIN
                                        IF ('{5}'='初盘')
                                        BEGIN
                                            UPDATE a SET PrimaryQuantity='{4}',MUSER=b.F_Account,MUSERName=b.F_RealName,MTIME=GETDATE(),EATTRIBUTE1='1'
                                            FROM ICSCheckDetail a
                                            INNER JOIN Sys_SRM_User b ON b.F_Account='{2}' AND b.F_Location='{3}'
											LEFT JOIN ICSCheck c ON a.CheckID=c.ID AND a.WorkPoint=c.WorkPoint
                                            WHERE c.CheckCode='{0}' AND a.LotNo='{1}' and a.WorkPoint='{3}'
                                        END
                                        ELSE IF ('{5}'='抽盘')
                                        BEGIN
                                            UPDATE a SET CheckQuantity='{4}',MUSER=b.F_Account,MUSERName=b.F_RealName,MTIME=GETDATE(),EATTRIBUTE1='3'
                                            FROM ICSCheckDetail a
                                            INNER JOIN Sys_SRM_User b ON b.F_Account='{2}' AND b.F_Location='{3}'
                                            LEFT JOIN ICSCheck c ON a.CheckID=c.ID AND a.WorkPoint=c.WorkPoint
                                            WHERE c.CheckCode='{0}' AND a.LotNo='{1}' and a.WorkPoint='{3}'
                                        END
                                        ELSE
                                        BEGIN
                                            UPDATE a SET ReplayQuantity='{4}',MUSER=b.F_Account,MUSERName=b.F_RealName,MTIME=GETDATE(),EATTRIBUTE1='2'
                                            FROM ICSCheckDetail a
                                            INNER JOIN Sys_SRM_User b ON b.F_Account='{2}' AND b.F_Location='{3}'
                                            LEFT JOIN ICSCheck c ON a.CheckID=c.ID AND a.WorkPoint=c.WorkPoint
                                            WHERE c.CheckCode='{0}' AND a.LotNo='{1}' and a.WorkPoint='{3}'
                                        END
                                    END
                                    ELSE
                                    BEGIN
                                        IF ('{5}'='初盘')
                                        BEGIN
	                                        INSERT INTO ICSCheckDetail (ID,CheckID,LotNo,Quantity,Amount,PrimaryQuantity,PrimaryAmount,ReplayQuantity,ReplayAmount,CheckQuantity,CheckAmount,MUSER,MUSERName,MTIME,WorkPoint,EATTRIBUTE1)
                                            SELECT  NEWID(),c.ID,a.LotNo,a.Quantity,'0','{4}','0','0','0','0','0',b.F_Account,b.F_RealName,GETDATE(),a.WorkPoint,'1'
                                            FROM ICSWareHouseLotInfo a
                                            INNER JOIN Sys_SRM_User b ON b.F_Account='{2}' AND b.F_Location='{3}'
											LEFT JOIN ICSCheck c ON SUBSTRING(a.LocationCode,1,len(c.SelectLevel))=c.SelectLevel 
                                            WHERE a.LotNo='{1}' and a.WorkPoint='{3}' and c.CheckCode='{0}'
                                        END
                                        ELSE IF ('{5}'='抽盘')
                                        BEGIN
	                                        INSERT INTO ICSCheckDetail (ID,CheckID,LotNo,Quantity,Amount,PrimaryQuantity,PrimaryAmount,ReplayQuantity,ReplayAmount,CheckQuantity,CheckAmount,MUSER,MUSERName,MTIME,WorkPoint,EATTRIBUTE1)
                                            SELECT  NEWID(),c.ID,a.LotNo,a.Quantity,'0','0','0','0','0','{4}','0',b.F_Account,b.F_RealName,GETDATE(),a.WorkPoint,'3'
                                            FROM ICSWareHouseLotInfo a
                                            INNER JOIN Sys_SRM_User b ON b.F_Account='{2}' AND b.F_Location='{3}'
                                            LEFT JOIN ICSCheck c ON SUBSTRING(a.LocationCode,1,len(c.SelectLevel))=c.SelectLevel 
                                            WHERE a.LotNo='{1}' and a.WorkPoint='{3}' and c.CheckCode='{0}'
                                        END
                                        ELSE
                                        BEGIN
	                                        INSERT INTO ICSCheckDetail (ID,CheckID,LotNo,Quantity,Amount,PrimaryQuantity,PrimaryAmount,ReplayQuantity,ReplayAmount,CheckQuantity,CheckAmount,MUSER,MUSERName,MTIME,WorkPoint,EATTRIBUTE1)
                                            SELECT  NEWID(),c.ID,a.LotNo,a.Quantity,'0','0','0','{4}','0','0','0',b.F_Account,b.F_RealName,GETDATE(),a.WorkPoint,'2'
                                            FROM ICSWareHouseLotInfo a
                                            INNER JOIN Sys_SRM_User b ON b.F_Account='{2}' AND b.F_Location='{3}'
                                            LEFT JOIN ICSCheck c ON SUBSTRING(a.LocationCode,1,len(c.SelectLevel))=c.SelectLevel 
                                            WHERE a.LotNo='{1}' and a.WorkPoint='{3}' and c.CheckCode='{0}'
                                        END
                                    END";
                            sql = string.Format(sql, item.CheckCode, itemInfo.LotNo, item.User, item.WorkPoint, itemInfo.ActualQuantity, item.CheckKind);

                            if (!DBHelper.ExecuteNonQuery(sql, cmd))
                            {
                                throw new Exception(language.GetNameByCode("WMSAPIInfo033"));//"盘点扫描创建失败!");
                            }

                            ///更新库存
                            sql = @"UPDATE ICSWareHouseLotInfo SET LockQuantity='{2}' WHERE LotNo='{0}' AND WorkPoint='{1}'";
                            sql = string.Format(sql, itemInfo.LotNo, item.WorkPoint, itemInfo.ActualQuantity);

                            if (!DBHelper.ExecuteNonQuery(sql, cmd))
                            {
                                throw new Exception(language.GetNameByCode("WMSAPIInfo168"));//"库存更新失败!");
                            }

                            #region 更新ICSCheckDetail表

                            //string strSql = @"UPDATE ICSCheckDetail Set";
                            //if (item.CheckKind == "初盘")
                            //    strSql += @" PrimaryQuantity+=" + Convert.ToDecimal(itemInfo.ActualQuantity);
                            //else if (item.CheckKind == "复盘")
                            //    strSql += @" ReplayQuantity+=" + Convert.ToDecimal(itemInfo.ActualQuantity);
                            //else
                            //    strSql += @" CheckQuantity+=" + Convert.ToDecimal(itemInfo.ActualQuantity);
                            //strSql += @" where  ToCheckNO='" + item.CheckCode + "' AND WorkPoint='" + item.WorkPoint + "'";
                            //cmd.CommandText = strSql;
                            //result = cmd.ExecuteNonQuery();
                            //if (result <= 0)
                            //{
                            //    throw new Exception(language.GetNameByCode("WMSAPIInfo296"));//"盘点子表数量增加失败!");
                            //}

                            #endregion

                            #region 更新库存
                            //if (item.UpdateWHLI)
                            //{
                            //    ICSWareHouseLotInfoService.WareHouseLotInfoUpdate(Identification, item.CheckCode, "", itemInfo.LotNo, itemInfo.ActualQuantity, item.User, item.WorkPoint, TransTypeEnum.Check.GetDescription<DBValue>(), item.CheckKind, cmd, language);
                            //}
                            #endregion
                            lots += "'" + itemInfo.LotNo + item.WorkPoint + "',";
                        }
                        if (string.IsNullOrWhiteSpace(lots))
                        {
                            throw new Exception(language.GetNameByCode("WMSAPIInfo005"));//"请传入条码信息!");
                        }
                        //sql = @"UPDATE a SET ActualQuantity=b.ActualQuantity
                        //        FROM ICSCheck a
                        //        INNER JOIN (SELECT x.CheckCode,x.WorkPoint,y.WarehouseCode,y.InvCode,SUM(ActualQuantity) AS ActualQuantity FROM ICSCheckDetail x INNER JOIN ICSWareHouseLotInfo y ON x.LotNo=y.LotNo AND x.WorkPoint=y.WorkPoint WHERE x.LotNo+x.WorkPoint IN ({2}) GROUP BY x.CheckCode,x.WorkPoint,y.WarehouseCode,y.InvCode) b ON a.CheckCode=b.CheckCode AND a.WorkPoint=b.WorkPoint AND a.WHCode=b.WarehouseCode AND a.InvCode=b.InvCode
                        //        WHERE a.CheckCode='{0}' and a.WorkPoint='{1}'";
                        //sql = string.Format(sql, item.CheckCode, item.WorkPoint, lots.Substring(0, lots.Length - 1));

                        //if (!DBHelper.ExecuteNonQuery(sql, cmd))
                        //{
                        //    throw new Exception(language.GetNameByCode("WMSAPIInfo034"));//"盘点扫描更新盘点单失败!");
                        //}
                    }
                    #region 查询返回数据
                    sql = @"SELECT x.ID,x.CheckID,y.WarehouseCode AS WHCode,x.LotNo,
	                            y.InvCode,
	                            inv.InvName,
	                            inv.InvStd,
	                            x.Quantity,x.PrimaryQuantity,x.PrimaryAmount,x.ReplayQuantity,x.ReplayAmount,x.CheckQuantity,x.CheckAmount,
	                            inv.InvUnit,
	                            x.MUSER AS [User],
	                            x.MTIME AS [MTime]
                            FROM ICSCheckDetail x 
                            INNER JOIN ICSWareHouseLotInfo y ON x.LotNo=y.LotNo AND x.WorkPoint=y.WorkPoint 
                            INNER JOIN ICSInventory inv ON y.InvCode=inv.InvCode AND y.WorkPoint=inv.WorkPoint
                            WHERE x.LotNo+x.WorkPoint IN ({0})";
                    sql = string.Format(sql, lots.Substring(0, lots.Length - 1));
                    DataTable data = DBHelper.SQlReturnData(sql, cmd);
                    #endregion
                    cmd.Transaction.Commit();
                    return data;
                }
                catch (Exception ex)
                {
                    if (cmd.Transaction != null)
                        cmd.Transaction.Rollback();
                    log.Error(ex.Message);
                    throw new Exception(ex.Message);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                    }
                    conn.Dispose();
                }
            }
        }
        #endregion

        #region 多语言
        /// <summary>
        /// 多语言查询
        /// </summary>
        /// <param name="JsonData"></param>
        /// <returns></returns>
        public static DataTable PromptInformationGet(WMSBarCoreModel JsonData)
        {
            using (SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString))
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = conn;
                cmd.CommandTimeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["TimeOut"]);
                try
                {
                    string DefiniteLanguage = ICSDefiniteLanguageService.GetLanguage();
                    string sql = @"select " + DefiniteLanguage + " AS Name,Code from Sys_Language where 1=1";
                    if (!string.IsNullOrWhiteSpace(JsonData.Code))
                    {
                        sql += " and Code LIKE '%{0}%'";
                    }
                    sql = string.Format(sql, JsonData.Code);
                    DataTable data = DBHelper.SQlReturnData(sql, cmd);
                    return data;
                }
                catch (Exception ex)
                {
                    log.Error(ex.Message);
                    throw new Exception(ex.Message);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                    }
                    conn.Dispose();
                }
            }
        }
        #endregion

        #region 仓库/库位
        /// <summary>
        /// 仓库/库位
        /// </summary>
        /// <param name="JsonData"></param>
        /// <returns></returns>
        public static DataTable LocationGet(ICSLocation JsonData)
        {
            var language = LanguageHelper.GetName("WMSAPIInfo");
            using (SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString))
            {
                conn.Open();
                SqlTransaction sqlTran = conn.BeginTransaction();
                SqlCommand cmd = new SqlCommand();
                cmd.Transaction = sqlTran;
                cmd.Connection = conn;
                cmd.CommandTimeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["TimeOut"]);
                try
                {
                    string sql = @"IF NOT EXISTS(SELECT LocationCode FROM ICSLocation a where LocationCode like '%{0}%' AND a.WorkPoint='{1}')
                            BEGIN
	                            RAISERROR('" + language.GetNameByCode("WMSAPIInfo070") + @"',16,1);
                                RETURN
                            END
                            IF NOT EXISTS(SELECT LocationCode FROM ICSLocation a INNER JOIN ICSWarehouse b on a.WHID=b.ID and a.WorkPoint=b.WorkPoint where LocationCode like '%{0}%' AND a.WorkPoint='{1}')
                            BEGIN
	                            RAISERROR('" + language.GetNameByCode("WMSAPIInfo077") + @"',16,1);
                                RETURN
                            END
                            IF NOT EXISTS(SELECT LocationCode FROM ICSLocation a INNER JOIN ICSWarehouse b on a.WHID=b.ID and a.WorkPoint=b.WorkPoint where LocationCode like '%{0}%' AND a.WorkPoint='{1}' and b.Enable='1')
                            BEGIN
	                            RAISERROR('" + language.GetNameByCode("WMSAPIInfo078") + @"',16,1);
                                RETURN
                            END

                            SELECT 
                            LocationCode,
                            LocationName ,
                            WarehouseCode,
                            WarehouseName
                            FROM ICSLocation a
                            INNER JOIN ICSWarehouse b on a.WHID=b.ID and a.WorkPoint=b.WorkPoint where LocationCode like '%{0}%' AND a.WorkPoint='{1}' and b.Enable='1'";
                    sql = string.Format(sql, JsonData.LocationCode, JsonData.WorkPoint);
                    DataTable data = DBHelper.SQlReturnData(sql, cmd);
                    cmd.Transaction.Commit();
                    return data;
                }
                catch (Exception ex)
                {
                    if (cmd.Transaction != null)
                        cmd.Transaction.Rollback();
                    log.Error(ex.Message);
                    throw new Exception(ex.Message);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                    }
                    conn.Dispose();
                }
            }
        }


        /// <summary>
        /// 仓库/库位
        /// </summary>
        /// <param name="JsonData"></param>
        /// <returns></returns>
        public static DataTable AMLocationGet(ICSLocation JsonData)
        {
            var language = LanguageHelper.GetName("WMSAPIInfo");
            using (SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString))
            {
                conn.Open();
                SqlTransaction sqlTran = conn.BeginTransaction();
                SqlCommand cmd = new SqlCommand();
                cmd.Transaction = sqlTran;
                cmd.Connection = conn;
                cmd.CommandTimeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["TimeOut"]);
                string UserName = "";
                string WarehouseCode = "";
                try
                {
                    //检验是否分批
                    string uersql = @"SELECT F_RealName from  Sys_SRM_User  Where F_Account='{0}' AND F_Location='{1}'
                         ";
                    uersql = string.Format(uersql, JsonData.User,JsonData.WorkPoint);
                    DataTable dt = DBHelper.SQlReturnData(uersql, cmd);
                    if (dt.Rows.Count == 0)
                    {
                        throw new Exception(language.GetNameByCode("WMSAPIInfo369"));
                    }
                    else
                    {
                        UserName = dt.Rows[0]["F_RealName"].ToString();
                    }
                    string UName = UserName.Substring(0, 2);
                    string waresql = @"select WarehouseCode,WarehouseName from ICSWarehouse
                                where SUBSTRING(WarehouseName,1,2)='{0}' and WorkPoint='{1}'";
                    waresql = string.Format(waresql, UName, JsonData.WorkPoint);
                    DataTable dta = DBHelper.SQlReturnData(waresql, cmd);
                    if (dta.Rows.Count == 0)
                    {
                        throw new Exception(language.GetNameByCode("WMSAPIInfo369"));
                    }
                    else
                    {
                        UName = dta.Rows[0]["WarehouseCode"].ToString();
                    }

                   
                    //switch (UName)
                    //{
                    //    case "L1":
                    //        UName = "021";
                    //        break;
                    //    case "L2":
                    //        UName = "022";
                    //        break;
                    //    case "L3":
                    //        UName = "023";
                    //        break;
                    //    case "L4":
                    //        UName = "024";
                    //        break;
                    //    case "L5":
                    //        UName = "025";
                    //        break;
                    //    case "L6":
                    //        UName = "026";
                    //        break;
                    //    case "L7":
                    //        UName = "025";
                    //        break;
                    //    case "C1":
                    //        UName = "015";
                    //        break;
                    //}
                    string sql = @"IF NOT EXISTS(SELECT LocationCode FROM ICSLocation a where LocationCode like '%{0}%' AND a.WorkPoint='{1}')
                            BEGIN
	                            RAISERROR('" + language.GetNameByCode("WMSAPIInfo070") + @"',16,1);
                                RETURN
                            END
                            IF NOT EXISTS(SELECT LocationCode FROM ICSLocation a INNER JOIN ICSWarehouse b on a.WHID=b.ID and a.WorkPoint=b.WorkPoint where LocationCode like '%{0}%' AND a.WorkPoint='{1}')
                            BEGIN
	                            RAISERROR('" + language.GetNameByCode("WMSAPIInfo077") + @"',16,1);
                                RETURN
                            END
                            IF NOT EXISTS(SELECT LocationCode FROM ICSLocation a INNER JOIN ICSWarehouse b on a.WHID=b.ID and a.WorkPoint=b.WorkPoint where LocationCode like '%{0}%' AND a.WorkPoint='{1}' and b.Enable='1')
                            BEGIN
	                            RAISERROR('" + language.GetNameByCode("WMSAPIInfo078") + @"',16,1);
                                RETURN
                            END
                            IF NOT EXISTS(SELECT LocationCode FROM ICSLocation a INNER JOIN ICSWarehouse b on a.WHID=b.ID and a.WorkPoint=b.WorkPoint where LocationCode like '%{0}%' AND a.WorkPoint='{1}' and b.warehousecode='{2}')
                            BEGIN
	                            RAISERROR('登录人员产线与目标仓库不一致,请确认!',16,1)
                                RETURN
                            END

                            SELECT 
                            LocationCode,
                            LocationName ,
                            WarehouseCode,
                            WarehouseName
                            FROM ICSLocation a
                            INNER JOIN ICSWarehouse b on a.WHID=b.ID and a.WorkPoint=b.WorkPoint where LocationCode like '%{0}%' AND a.WorkPoint='{1}' and b.Enable='1'";
                    sql = string.Format(sql, JsonData.LocationCode, JsonData.WorkPoint, UName);
                    DataTable data = DBHelper.SQlReturnData(sql, cmd);
                    cmd.Transaction.Commit();
                    return data;
                }
                catch (Exception ex)
                {
                    if (cmd.Transaction != null)
                        cmd.Transaction.Rollback();
                    log.Error(ex.Message);
                    throw new Exception(ex.Message);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                    }
                    conn.Dispose();
                }
            }
        }
        #endregion

        #region 登陆
        public static object CheckLogin(Sys_SRM_User userModel)
        {
            using (SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString))
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = conn;
                cmd.CommandTimeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["TimeOut"]);
                try
                {
                    string sql = @"select F_Account from Sys_SRM_User where F_Account='{0}' and F_Location='{1}' and F_EnabledMark='1'";//已经启用的账号
                    sql = string.Format(sql, userModel.UserCode, userModel.WorkPoint);
                    DataTable dt = DBHelper.SQlReturnData(sql, cmd);
                    if (dt != null && dt.Rows.Count > 0)//查询的数据不为空
                    {
                        sql = @" select a.[F_Id]  as UserId
                              ,[F_Account] as userCode
                              ,[F_RealName]  as UserName
                              ,[F_NickName]
	                          ,b.F_UserPassword
	                          ,b.F_UserSecretkey
                              ,[F_HeadIcon]
                              ,[F_Gender]
                              ,[F_Birthday]
                              ,[F_MobilePhone]
                              ,[F_Email]
                              ,[F_WeChat]
                              ,[F_ManagerId]
                              ,[F_SecurityLevel]
                              ,[F_Signature]
                              ,[F_OrganizeId]
                              ,[F_DepartmentId]
                              ,[F_RoleId]
                              ,[F_DutyId]
                              ,[F_IsAdministrator]
                              ,[F_SortCode]
                              ,[F_DeleteMark]
                              ,[F_EnabledMark]
                              ,[F_Description]
                              ,[F_CreatorTime]
                              ,[F_CreatorUserId]
                              ,[F_LastModifyTime]
                              ,[F_LastModifyUserId]
                              ,[F_DeleteTime]
                              ,[F_DeleteUserId]
                              ,[F_Location] as WorkPoint
                              ,[F_VenCode]
	                          from Sys_SRM_User a 
                              left join Sys_SRM_UserLogOn b on  b.F_UserId=a.F_Id
                               where F_Account='{0}' and F_Location='{1}' and F_EnabledMark='1'";
                        sql = string.Format(sql, userModel.UserCode, userModel.WorkPoint);
                        dt = DBHelper.SQlReturnData(sql, cmd);
                        IList<UserLogOnEntity> users = DBHelper.ModelConvertHelper<UserLogOnEntity>.ConvertToModel(dt);
                        //  string dbPassword = Md5.md5(DESEncrypt.Encrypt(userModel.F_UserPassword.ToLower(), item.F_UserSecretkey.ToLower()).ToLower(), 32).ToLower();
                        foreach (var item in users)
                        {
                            //string UserPassword = Md5.md5(DESEncrypt.Encrypt(userModel.F_UserPassword.ToLower()),16).ToLower();

                            string dbPassword = Md5.md5(DESEncrypt.Encrypt(userModel.UserPassword.ToLower(), item.F_UserSecretkey.ToLower()).ToLower(), 32).ToLower();
                            if (dbPassword == item.F_UserPassword)
                            {
                                string json = JsonConvert.SerializeObject(dt);
                                List<Sys_SRM_User> userLogOnEntity = JsonConvert.DeserializeObject<List<Sys_SRM_User>>(json);
                                return userLogOnEntity;
                            }
                            else
                            {
                                throw new Exception(LanguageHelper.GetNameSingle("WMSAPI004"));//"密码不正确,请重新输入");
                            }
                        }
                    }
                    else
                    {
                        throw new Exception(LanguageHelper.GetNameSingle("WMSAPI005"));//"用户名不存在,请重新输入!");
                    }
                    return null;
                }
                catch (Exception ex)
                {
                    log.Error(ex.Message);
                    throw new Exception(ex.Message);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                    }
                    conn.Dispose();
                }
            }
        }
        #endregion


        #region 获取调拨单
        /// <summary>
        /// 获取未发,未发完调拨单
        /// </summary>
        /// <param name="JsonData"></param>
        /// <returns></returns>
        public static DataTable TransCodemationGet(TransferDoc JsonData)
        {
            var language = LanguageHelper.GetName("WMSAPIInfo");   
            if (JsonData == null)
            {
                throw new Exception(language.GetNameByCode("WMSAPIInfo007"));//"传送数据为空!"
            }
            using (SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString))
            {
                conn.Open(); 
                SqlTransaction sqlTran = conn.BeginTransaction();
                SqlCommand cmd = new SqlCommand();
                cmd.Transaction = sqlTran;
                cmd.Connection = conn;
                cmd.CommandTimeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["TimeOut"]);
                try
                {
                    string Workpoint = "";
                    Workpoint = JsonData.WorkPoint;

                    string sql = @"SELECT DISTINCT TransferNO as TransCode FROM ICSTransferApplication 
WHERE WorkPoint='{0}' AND Quantity>ISNULL(TransferQuantity, 0) order by TransferNO desc";
                    sql = string.Format(sql, Workpoint);   

                    DataTable table = DBHelper.SQlReturnData(sql, cmd);
                    return table;
                }
                catch (Exception ex)
                {
                    if (cmd.Transaction != null)
                        cmd.Transaction.Rollback();
                    log.Error(ex.Message);
                    throw new Exception(ex.Message);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                    }
                    conn.Dispose();
                }
            }
        }
        #endregion


        #region 源头单据信息(佑伦专用)
        /// <summary>
        /// 源头单据信息(佑伦专用)
        /// </summary>
        /// <param name="JsonData"></param>
        /// <returns></returns>
        public static DataTable YLTransInformationGet(WMSSourceDocumentModel JsonData)
        {
            var language = LanguageHelper.GetName("WMSAPIInfo");
            using (SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString))
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = conn;
                cmd.CommandTimeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["TimeOut"]);
                try
                {
                    if (string.IsNullOrEmpty(JsonData.TransCode))
                    {
                        throw new Exception(language.GetNameByCode("WMSAPIInfo001"));//"单据号不能为空!"
                    }
                    else if (string.IsNullOrEmpty(JsonData.TransType))
                    {
                        throw new Exception(language.GetNameByCode("WMSAPIInfo002"));//"单据类型不能为空!"
                    }
                    else if (!EnumHelper.HasDescriptions(typeof(TransTypeEnum), JsonData.TransType))
                    {
                        throw new Exception(language.GetNameByCode("WMSAPIInfo003"));//"单据类型不存在!"
                    }
                    else if (string.IsNullOrEmpty(JsonData.WorkPoint))
                    {
                        throw new Exception(language.GetNameByCode("WMSAPIInfo004"));//"站点不能为空!"
                    }

                    string TransType = JsonData.TransType;
                    #region SLQ
                    string sqlCheck = @"IF NOT EXISTS(SELECT a.ID FROM {1} WHERE {2})
                                    BEGIN
	                                    RAISERROR('" + language.GetNameByCode("WMSAPIInfo035") + @"',16,1);
                                        RETURN
                                    END
                                    ";
                    string sql = @"SELECT a.ID,
                                    {0}
                                    convert(varchar(100),'') AS LocationCode,
                                    convert(varchar(100),'') AS LotNo,
                                    convert(varchar(10),'') AS ToWarehouseCode,
									0 AS LocationQty,
                                    0 AS isMatched,
                                    a.InvCode,
                                    inv.InvName,
                                    inv.InvStd,
                                    a.Quantity,
                                    inv.InvUnit,
                                    a.Amount,
                                    a.WHCode,
                                    inv.AmountUnit,
                                    wh.WarehouseName AS WHName,
                                    ISNULL(ext.ProjectCode, '') AS ProjectCode,
                                    a.ExtensionID,
                                    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,
                                    a.MUSER AS [User],
                                    a.MTIME AS [MTime]
                                    {4}
                                    FROM {1}
                                    INNER JOIN ICSExtension ext ON a.ExtensionID=ext.ID AND a.WorkPoint=ext.WorkPoint
                                    INNER JOIN ICSInventory inv ON a.InvCode=inv.InvCode AND a.WorkPoint=inv.WorkPoint
                                    LEFT JOIN ICSWarehouse wh ON a.WHCode=wh.WarehouseCode AND a.WorkPoint=wh.WorkPoint
                                    LEFT JOIN ICSInventoryBatchEnable invBat ON a.InvCode=invBat.InvCode AND a.WHCode=invBat.WHCode AND a.WorkPoint=invBat.WorkPoint
                                    WHERE {2} ";

                    string Picksql = @"SELECT row_number() over (order by c.Code,c.InvCode,d.MTIME,d.LotNO) AS rowNo,
	                        c.Code,
	                        c.InvCode,
	                        c.InvName,
	                        c.InvStd,
c.InvUnit,
	                        FLOOR(c.iQuantity) AS iQuantity,
	                        d.WarehouseCode,
	                        d.LocationCode,
	                        d.LotNO,
	                        FLOOR(ISNULL(d.Quantity, 0)) AS QTY,
	                        CONVERT(varchar(100),d.MTIME, 23) MTIME,
	                        FLOOR(f.QTYTotal) QTYTotal  INTO #temp 
                        FROM
                        ({0}) c
                        LEFT JOIN ICSWareHouseLotInfo d ON c.InvCode=d.INVCode  AND ((LEN(ISNULL(c.WHCode,''))<=0) OR (LEN(ISNULL(c.WHCode,''))>0) AND c.WhCode=d.WarehouseCode)  AND d.WorkPoint='{1}' AND d.Quantity>0
                        left join ICSInventoryLot m on d.LotNo=m.LotNo and d.WorkPoint=m.WorkPoint and c.ExtensionID=m.ExtensionID
                        LEFT JOIN (SELECT INVCode,WarehouseCode,SUM(Quantity) AS QTYTotal FROM ICSWareHouseLotInfo  WHERE WorkPoint='{1}' GROUP BY INVCode,WarehouseCode) f ON c.InvCode=f.INVCode AND c.WhCode=f.WarehouseCode
                        

DECLARE @ItemCode VARCHAR(50),
	@QTY DECIMAL(18,3), 
	@ItemCodeCurrent VARCHAR(50),
	@QTYCurrent DECIMAL(18,3),
	@iQuantityCurrent DECIMAL(18,3),
	@CanDelete BIT,
	@Row INT,
	@rowCurrent INT
SET @Row = @@rowcount
SET @rowCurrent=1
SET @CanDelete=0
SET @ItemCode=''

WHILE @rowCurrent<=@Row
	BEGIN
		SELECT @ItemCodeCurrent=InvCode,@QTYCurrent=QTY,@iQuantityCurrent=iQuantity FROM #temp WHERE rowNo=@rowCurrent

PRINT(@rowCurrent)
		IF @ItemCode<>@ItemCodeCurrent
		BEGIN
			SET @ItemCode=@ItemCodeCurrent
			SET @QTY=0
			SET @CanDelete=0
		END

		IF @CanDelete=1 
		BEGIN
			DELETE FROM #temp WHERE rowNo=@rowCurrent
			SET @rowCurrent += 1
			CONTINUE
		END

		SET @QTY += @QTYCurrent
		IF @QTY>=@iQuantityCurrent
		BEGIN
			SET @CanDelete=1 
		END
		
		SET @rowCurrent += 1
	END
SELECT * FROM #temp
DROP TABLE #temp
";
                    #endregion

                    bool isDeliveryNotice = false;      //送货、到货、含委外
                    string columns = string.Empty;      //查询源头单据表的特殊列名
                    string tableName = string.Empty;    //查询源头单据表名
                    string where = string.Empty;        //查询源头单据的过滤条件
                    bool isMerge = false;               //合并发料
                    string columnsMerge = string.Empty;      //合并发料查询源头单据表的特殊列名
                    string tableNameMerge = string.Empty;    //合并发料查询源头单据表名
                    string sqls = string.Empty;
                    string sqlCheckSign = "";
                    DataTable flag = null;

                    #region 检料表信息
                    if (TransType == TransTypeEnum.MOIssueDoc.GetDescription())
                    {
                        enableCode = "Over001";
                        excessQtySql = ",(dbo.GetExcessQty(a.InvCode, b.Sequence+'~'+a.Sequence, b.MOCode, a.WorkPoint,'" + enableCode + "')) AS excessQty";
                        #region 工单备料sql
                        sqls = @" SELECT
	                        c.MOCode as Code,
	                        a.InvCode,
	                        b.InvName,
	                        b.InvStd,
	                        SUM(ISNULL(a.Quantity, 0)) AS iQuantity,
	                        a.WhCode,
b.InvUnit,
							a.ExtensionID
                        FROM
	                        ICSMOPick a
							inner join ICSMO c on a.MODetailID=c.MODetailID and a.WorkPoint=c.WorkPoint
                            LEFT JOIN ICSINVENTORY b ON a.InvCode = b.InvCode AND a.WorkPoint=b.WorkPoint
                            WHERE  c.MOCode  in ({0}) AND a.WorkPoint = '{1}'
                            GROUP BY c.MOCode,a.InvCode,b.InvName,b.InvStd,b.InvUnit,a.WhCode,a.ExtensionID";
                        #endregion
                    }
                    if (TransType == TransTypeEnum.MOApply.GetDescription())
                    {
                        enableCode = "Over002";
                        excessQtySql = ",(dbo.GetExcessQty(a.InvCode, a.Sequence, a.ApplyCode, a.WorkPoint,'" + enableCode + "')) AS excessQty";
                        #region 工单领料SQL
                        sqls = @"   select
	                        a.ApplyCode as Code,
	                        a.InvCode,
	                        b.InvName,
	                        b.InvStd,
b.InvUnit,
	                        SUM(ISNULL(a.Quantity, 0)) AS iQuantity,
	                        a.WhCode,
							a.ExtensionID
                        FROM
	                        ICSMOApply a
                        LEFT JOIN ICSINVENTORY b ON a.InvCode = b.InvCode AND a.WorkPoint=b.WorkPoint
                        WHERE a.ApplyCode in ({0}) AND a.WorkPoint = '{1}'
                        GROUP BY a.ApplyCode,a.InvCode,b.InvName,b.InvStd,b.InvUnit,a.WhCode,a.ExtensionID";
                        #endregion
                    }
                    if (TransType == TransTypeEnum.MOIssue.GetDescription())
                    {
                        //enableCode = "Over003";
                        excessQtySql = "";
                        #region 工单材料出库SQL
                        sqls = @"  select
	                        a.IssueCode as Code,
	                        a.InvCode,
	                        b.InvName,
	                        b.InvStd,
b.InvUnit,
	                        SUM(ISNULL(a.Quantity, 0)) AS iQuantity,
	                        a.WhCode,
							a.ExtensionID
                        FROM
	                        ICSMOIssue a
                        LEFT JOIN ICSINVENTORY b ON a.InvCode = b.InvCode AND a.WorkPoint=b.WorkPoint
                        WHERE a.IssueCode in ({0}) AND a.WorkPoint = '{1}'
                        GROUP BY a.IssueCode,a.InvCode,b.InvName,b.InvStd,b.InvUnit,a.WhCode,a.ExtensionID";
                        #endregion
                    }
                    if (TransType == TransTypeEnum.OutsourcingIssueDoc.GetDescription())
                    {
                        enableCode = "Over004";
                        excessQtySql = ",(dbo.GetExcessQty(a.InvCode, a.Sequence, b.OOCode, a.WorkPoint,'" + enableCode + "')) AS excessQty";
                        #region 委外备料SQL
                        sqls = @"   								select
	                        c.OOCode as Code,
	                        a.InvCode,
	                        b.InvName,
	                        b.InvStd,
b.InvUnit,
	                        SUM(ISNULL(a.Quantity, 0)) AS iQuantity,
	                        a.WhCode,
													a.ExtensionID
                        FROM
	                        ICSOOPick a
							left join ICSOutsourcingOrder c on a.OODetailID=c.OODetailID and a.WorkPoint=c.WorkPoint
                        LEFT JOIN ICSINVENTORY b ON a.InvCode = b.InvCode AND a.WorkPoint=b.WorkPoint
                     WHERE c.OOCode in ({0}) AND a.WorkPoint = '{1}'
                        GROUP BY c.OOCode,a.InvCode,b.InvName,b.InvStd,b.InvUnit,a.WhCode,	a.ExtensionID";
                        #endregion
                    }
                    if (TransType == TransTypeEnum.OOApply.GetDescription())
                    {
                        enableCode = "Over005";
                        excessQtySql = ",(dbo.GetExcessQty(a.InvCode, a.Sequence, a.ApplyCode, a.WorkPoint,'" + enableCode + "')) AS excessQty";
                        #region 委外领料SQL
                        sqls = @"   	select
	                        a.ApplyCode as Code,
	                        a.InvCode,
	                        b.InvName,
	                        b.InvStd,
b.InvUnit,
	                        SUM(ISNULL(a.Quantity, 0)) AS iQuantity,
	                        a.WhCode,
													a.ExtensionID
                        FROM
	                        ICSOApply a
                        LEFT JOIN ICSINVENTORY b ON a.InvCode = b.InvCode AND a.WorkPoint=b.WorkPoint
                        WHERE a.ApplyCode in ({0}) AND a.WorkPoint = '{1}'
                        GROUP BY a.ApplyCode,a.InvCode,b.InvName,b.InvStd,b.InvUnit,a.WhCode,a.ExtensionID";
                        #endregion
                    }
                    if (TransType == TransTypeEnum.OOIssue.GetDescription())
                    {
                        //enableCode = "Over006";
                        excessQtySql = "";
                        #region 委外材料出库SQL
                        sqls = @" 	select
	                        a.IssueCode as Code,
	                        a.InvCode,
	                        b.InvName,
	                        b.InvStd,
b.InvUnit,
	                        SUM(ISNULL(a.Quantity, 0)) AS iQuantity,
	                        a.WhCode,
a.ExtensionID
                        FROM
	                        ICSOIssue a
                        LEFT JOIN ICSINVENTORY b ON a.InvCode = b.InvCode AND a.WorkPoint=b.WorkPoint
                     WHERE a.IssueCode in ({0}) AND a.WorkPoint = '{1}'
                        GROUP BY a.IssueCode,a.InvCode,b.InvName,b.InvStd,b.InvUnit,a.WhCode,a.ExtensionID";
                        #endregion
                    }
                    if (TransType == TransTypeEnum.SalesShipmentDoc.GetDescription())
                    {
                        enableCode = "";
                        excessQtySql = "";
                        #region 销售发货SQL
                        sqls = @"   select
	                        a.SDNCode as Code,
	                        a.InvCode,
	                        b.InvName,
	                        b.InvStd,
b.InvUnit,
	                        SUM(ISNULL(a.Quantity, 0)) AS iQuantity,
	                        a.WhCode,
a.ExtensionID
                        FROM
	                        ICSSDN a
                        LEFT JOIN ICSINVENTORY b ON a.InvCode = b.InvCode AND a.WorkPoint=b.WorkPoint
                     WHERE a.SDNCode in ({0}) AND a.WorkPoint = '{1}'
                        GROUP BY a.SDNCode,a.InvCode,b.InvName,b.InvStd,b.InvUnit,a.WhCode,a.ExtensionID";
                        #endregion
                    }
                    if (TransType == TransTypeEnum.OtherOutDoc.GetDescription())
                    {
                        enableCode = "";
                        excessQtySql = "";
                        #region 其它出库SQL
                        sqls = @" select
	                        a.OutCode as Code,
	                        a.InvCode,
	                        b.InvName,
	                        b.InvStd,
b.InvUnit,
	                        SUM(ISNULL(a.Quantity, 0)) AS iQuantity,
	                        a.WhCode,
a.ExtensionID
                        FROM
	                        ICSOtherOut a
                        LEFT JOIN ICSINVENTORY b ON a.InvCode = b.InvCode AND a.WorkPoint=b.WorkPoint
                        WHERE a.OutCode in ({0}) AND a.WorkPoint = '{1}'
                        GROUP BY a.OutCode,a.InvCode,b.InvName,b.InvStd,b.InvUnit,a.WhCode,a.ExtensionID";
                        #endregion
                    }
                    if (TransType == TransTypeEnum.BrrowDoc.GetDescription())
                    {
                        enableCode = "";
                        excessQtySql = "";
                        #region 借用SQL
                        sqls = @"select
	                        a.BrrowCode as Code,
	                        a.InvCode,
						
	                        b.InvName,
	                        b.InvStd,
b.InvUnit,
	                        SUM(ISNULL(a.Quantity, 0)) AS iQuantity,
	                        a.WhCode,
a.ExtensionID
                        FROM
	                        ICSBrrow a
                        LEFT JOIN ICSINVENTORY b ON a.InvCode = b.InvCode AND a.WorkPoint=b.WorkPoint
                        WHERE a.BrrowCode in ({0}) AND a.WorkPoint = '{1}'
                        GROUP BY a.BrrowCode,a.InvCode,b.InvName,b.InvStd,b.InvUnit,a.WhCode,a.ExtensionID";
                        #endregion
                    }
                    if (TransType == TransTypeEnum.OneStepTransferDocIn.GetDescription())
                    {
                        enableCode = "";
                        excessQtySql = "";
                        #region 物料调拨
                        sqls = @"						select
	                        a.TransferNO as Code,
	                        a.InvCode,
						
	                        b.InvName,
	                        b.InvStd,
b.InvUnit,
	                        SUM(ISNULL(a.Quantity, 0)) AS iQuantity,
	                        a.FromWarehouseCode as WhCode,
a.ExtensionID
                        FROM
	                        ICSTransfer a
                        LEFT JOIN ICSINVENTORY b ON a.InvCode = b.InvCode AND a.WorkPoint=b.WorkPoint
						 WHERE a.TransferNO in ({0}) AND a.WorkPoint = '{1}'
                        GROUP BY a.TransferNO,a.InvCode,b.InvName,b.InvStd,b.InvUnit,a.FromWarehouseCode,a.ExtensionID";
                        #endregion
                    }
                    if (TransType == TransTypeEnum.TwoStepTransferDocOut.GetDescription())
                    {
                        enableCode = "";
                        excessQtySql = "";
                        #region 两步调出
                        sqls = @"select
	                        a.OutCode as Code,
	                        a.InvCode,
						
	                        b.InvName,
	                        b.InvStd,
b.InvUnit,
	                        SUM(ISNULL(a.Quantity, 0)) AS iQuantity,
	                        a.WHCode ,
a.ExtensionID
                     from  ICSOtherOut a
                        INNER JOIN ICSTransfer tra ON a.TransferDetailID=tra.TransferDetailID AND a.WorkPoint=tra.WorkPoint
                        LEFT JOIN ICSINVENTORY b ON a.InvCode = b.InvCode AND a.WorkPoint=b.WorkPoint
						 WHERE a.OutCode in ({0}) AND a.WorkPoint = '{1}'
                        GROUP BY a.OutCode,a.InvCode,b.InvName,b.InvStd,b.InvUnit,a.WHCode,a.ExtensionID";
                        #endregion
                    }
                    #endregion
                    #region 出库
                    #region 采购退货
                    if (TransType == TransTypeEnum.PurchaseReceiveDoctNegative.GetDescription())
                    {
                        isDeliveryNotice = true;
                        columns = @"a.DNCode AS TransCode,
                                    a.DNDetailID AS DetailID,
                                    a.DNType AS Type,
                                    a.Sequence AS TransSequence,
                                    a.RCVQuantity AS IssueQuantity,
                                    a.Quantity,
                                    a.Amount,
                                    a.MUSER AS [User],
                                    a.MTIME AS [MTime],";

                        tableName = @"ICSDeliveryNotice a ";

                        where = @" a.DNCode='{0}' AND a.WorkPoint='{1}' AND a.DNType='2' ";
                    }
                    #endregion
                    #region 委外发料(合并发料)
                    else if (TransType == TransTypeEnum.OutsourcingIssueDoc.GetDescription())
                    {
                        sqlCheckSign = @"select * from ICSConfiguration where code = 'OutWithLocationCode004' and enable = '1'";
                        flag = DBHelper.SQlReturnData(sqlCheckSign, cmd);
                        isMerge = true;
                        columnsMerge = @"mer.MergeID+'~'+b.OOCode AS TransCode,
                                    a.PickID AS DetailID,
                                    a.SupplyType AS Type,
                                    b.Sequence+'~'+a.Sequence AS TransSequence,
                                    a.IssueQuantity AS IssueQuantity,";

                        tableNameMerge = @"ICSOOPick  a
                                INNER JOIN ICSOutsourcingOrder b ON  a.OODetailID=b.OODetailID AND a.WorkPoint=b.WorkPoint
                                    INNER JOIN ICSMOPickMerge mer ON a.PickID=mer.SourceID AND a.WorkPoint=mer.WorkPoint";

                        columns = @"b.OOCode AS TransCode,
                                    a.PickID AS DetailID,
                                    a.SupplyType AS Type,
                                    b.Sequence+'~'+a.Sequence AS TransSequence,
                                    a.IssueQuantity AS IssueQuantity,";

                        tableName = @"ICSOOPick  a
                                INNER JOIN ICSOutsourcingOrder b ON  a.OODetailID=b.OODetailID AND a.WorkPoint=b.WorkPoint ";

                        where = @" b.OOCode='{0}' AND a.WorkPoint='{1}' AND a.SupplyType='3' ";
                    }
                    #endregion
                    #region 委外退货
                    else if (TransType == TransTypeEnum.OutsourcingReturnBack.GetDescription())
                    {
                        isDeliveryNotice = true;
                        columns = @"a.ODNCode AS TransCode,
                                    a.ODNDetailID AS DetailID,
                                    a.ODNType AS Type,
                                    a.Sequence AS TransSequence,
                                    a.RCVQuantity AS IssueQuantity,
                                    a.Quantity,
                                    a.Amount,
                                    a.MUSER AS [User],
                                    a.MTIME AS [MTime],";

                        tableName = @"ICSODeliveryNotice a ";

                        where = @" a.ODNCode='{0}' AND a.WorkPoint='{1}' AND a.ODNType='2' ";
                    }
                    #endregion
                    #region 生产发料(合并发料)
                    else if (TransType == TransTypeEnum.MOIssueDoc.GetDescription())
                    {
                        sqlCheckSign = @"select * from ICSConfiguration where code = 'OutWithLocationCode001' and enable = '1'";
                        flag = DBHelper.SQlReturnData(sqlCheckSign, cmd);
                        isMerge = true;
                        columnsMerge = @"mer.MergeID+'~'+b.MOCode AS TransCode,
                                    a.PickID AS DetailID,
                                    a.SupplyType AS Type,
                                    ISNULL(a.EATTRIBUTE2,'') AS JIGOU,
                                    b.Sequence+'~'+a.Sequence AS TransSequence,
                                    a.IssueQuantity AS IssueQuantity,";

                        tableNameMerge = @"ICSMOPick  a
	                                INNER JOIN ICSMO b ON  a.MODetailID=b.MODetailID AND a.WorkPoint=b.WorkPoint
                                    INNER JOIN ICSMOPickMerge mer ON a.PickID=mer.SourceID AND a.WorkPoint=mer.WorkPoint";

                        columns = @"b.MOCode AS TransCode,
                                    a.PickID AS DetailID,
                                    a.SupplyType AS Type,
                                    ISNULL(a.EATTRIBUTE2,'') AS JIGOU,
                                    b.Sequence+'~'+a.Sequence AS TransSequence,
                                    a.IssueQuantity AS IssueQuantity,";

                        tableName = @"ICSMOPick  a
	                                INNER JOIN ICSMO b ON  a.MODetailID=b.MODetailID AND a.WorkPoint=b.WorkPoint ";

                        where = @" b.MOCode='{0}' AND a.WorkPoint='{1}' AND a.SupplyType='3' AND b.MOStatus<>'3' and a.EATTRIBUTE1<>'1'";
                    }
                    #endregion
                    #region 销售出库(合并发料)
                    else if (TransType == TransTypeEnum.SalesShipmentDoc.GetDescription())
                    {
                        sqlCheckSign = @"select * from ICSConfiguration where code = 'OutWithLocationCode007' and enable = '1'";
                        flag = DBHelper.SQlReturnData(sqlCheckSign, cmd);
                        isMerge = true;
                        columnsMerge = @"mer.MergeID+'~'+a.SDNCode AS TransCode,
                                    a.SDNDetailID AS DetailID,
                                    a.SOCode,
                                    a.Type,
                                    a.Sequence AS TransSequence,
                                    a.SDNQuantity AS IssueQuantity,";

                        tableNameMerge = @"ICSSDN a 
                                    INNER JOIN ICSMOPickMerge mer ON a.SDNDetailID=mer.SourceID AND a.WorkPoint=mer.WorkPoint";

                        columns = @"a.SDNCode AS TransCode,
                                    a.SDNDetailID AS DetailID,
                                    a.SOCode,
                                    a.Type,
                                    a.Sequence AS TransSequence,
                                    a.SDNQuantity AS IssueQuantity,";

                        tableName = @"ICSSDN a ";

                        where = @" a.SDNCode='{0}' AND a.WorkPoint='{1}' AND a.Type='1' ";
                    }
                    #endregion
                    #region 盘点
                    else if (TransType == TransTypeEnum.Check.GetDescription())
                    {
                        #region SLQ
                        sql = @"SELECT a.ID,
                                    {0}
                                    a.Quantity,
                                    a.SelectLevel AS LocationCode,
                                    a.Amount,
                                    a.MUSER AS [User],
                                    a.MTIME AS [MTime]
                                    FROM {1} 
                                    WHERE {2} ";
                        #endregion

                        columns = @"a.CheckCode AS TransCode,
                                    a.ID,
                                    '' AS Type,";

                        tableName = @"ICSCheck a ";

                        where = @" a.CheckCode='{0}' AND a.WorkPoint='{1}' ";
                    }
                    #endregion
                    #region 一步调拨(合并发料)
                    else if (TransType == TransTypeEnum.OneStepTransferDocIn.GetDescription())
                    {
                        sqlCheckSign = @"select * from ICSConfiguration where code = 'OutWithLocationCode009' and enable = '1'";
                        flag = DBHelper.SQlReturnData(sqlCheckSign, cmd);
                        isMerge = true;
                        columnsMerge = @"mer.MergeID+'~'+a.TransferNO AS TransCode,
                                    a.TransferDetailID AS DetailID,
                                    '' AS Type,
                                    a.Sequence AS TransSequence,
                                    a.TransferQuantity AS IssueQuantity,
                                    a.ToWarehouseCode,";

                        tableNameMerge = @"ICSTransfer a 
                                    INNER JOIN ICSMOPickMerge mer ON a.TransferDetailID=mer.SourceID AND a.WorkPoint=mer.WorkPoint";

                        #region SLQ
                        sql = @"SELECT a.ID,
                                    {0}
                                    convert(varchar(100),'') AS LocationCode,
                                    convert(varchar(100),'') AS LotNo,
									0 AS LocationQty,
                                    0 AS isMatched,
                                    a.InvCode,
                                    inv.InvName,
                                    inv.InvStd,
                                    a.Quantity,
                                    inv.InvUnit,
                                    a.Amount,
                                    a.FromWarehouseCode AS WHCode,
                                    inv.AmountUnit,
                                    wh.WarehouseName AS WHName,
                                    a.ExtensionID,
                                    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 AS BatchCode,
                                    ext.Version,
                                    ext.Brand,
                                    ext.cFree1,
                                    ext.cFree2,
                                    ext.cFree3,
                                    ext.cFree4,
                                    ext.cFree5,
                                    ext.cFree6,
                                    ext.cFree7,
                                    ext.cFree8,
                                    ext.cFree9,
                                    ext.cFree10,
                                    a.MUSER AS [User],
                                    a.MTIME AS [MTime]
                                    FROM {1}
                                    INNER JOIN ICSExtension ext ON a.ExtensionID=ext.ID AND a.WorkPoint=ext.WorkPoint
                                    INNER JOIN ICSInventory inv ON a.InvCode=inv.InvCode AND a.WorkPoint=inv.WorkPoint
                                    LEFT JOIN ICSWarehouse wh ON a.FromWarehouseCode=wh.WarehouseCode AND a.WorkPoint=wh.WorkPoint
                                    LEFT JOIN ICSInventoryBatchEnable invBat ON a.InvCode=invBat.InvCode AND a.FromWarehouseCode=invBat.WHCode AND a.WorkPoint=invBat.WorkPoint
                                    WHERE {2} ";
                        #endregion

                        columns = @"a.TransferNO AS TransCode,
                                    a.TransferDetailID AS DetailID,
                                    '' AS Type,
                                    a.Sequence AS TransSequence,
                                    a.TransferQuantity AS IssueQuantity,
                                    a.ToWarehouseCode,";

                        tableName = @"ICSTransfer a ";

                        where = @" a.TransferNO='{0}' AND a.WorkPoint='{1}' AND a.Status='1' ";
                    }
                    #endregion
                    #region 调拨申请单(领料)
                    else if (TransType == TransTypeEnum.StepTransferApplicationIn.GetDescription())
                    {
                        isMerge = true;
                        columnsMerge = @"mer.MergeID+'~'+a.TransferNO AS TransCode,
                                    a.TransferDetailID AS DetailID,
                                    '' AS Type,
                                    a.Sequence AS TransSequence,
                                    a.TransferQuantity AS IssueQuantity,
                                    a.ToWarehouseCode,";

                        tableNameMerge = @"ICSTransferApplication a 
                                    INNER JOIN ICSMOPickMerge mer ON a.TransferDetailID=mer.SourceID AND a.WorkPoint=mer.WorkPoint";

                        #region SLQ
                        sql = @"SELECT a.ID,
                                    {0}
                                    convert(varchar(100),'') AS LocationCode,
                                    convert(varchar(100),'') AS LotNo,
									0 AS LocationQty,
                                    0 AS isMatched,
                                    a.InvCode,
                                    inv.InvName,
                                    inv.InvStd,
                                    a.Quantity,
                                    inv.InvUnit,
                                    a.Amount,
                                    a.FromWarehouseCode AS WHCode,
                                    inv.AmountUnit,
                                    wh.WarehouseName AS WHName,
                                    a.ExtensionID,
                                    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 AS BatchCode,
                                    ext.Version,
                                    ext.Brand,
                                    ext.cFree1,
                                    ext.cFree2,
                                    ext.cFree3,
                                    ext.cFree4,
                                    ext.cFree5,
                                    ext.cFree6,
                                    ext.cFree7,
                                    ext.cFree8,
                                    ext.cFree9,
                                    ext.cFree10,
                                    a.MUSER AS [User],
                                    a.MTIME AS [MTime]
                                    FROM {1}
                                    INNER JOIN ICSExtension ext ON a.ExtensionID=ext.ID AND a.WorkPoint=ext.WorkPoint
                                    INNER JOIN ICSInventory inv ON a.InvCode=inv.InvCode AND a.WorkPoint=inv.WorkPoint
                                    LEFT JOIN ICSWarehouse wh ON a.FromWarehouseCode=wh.WarehouseCode AND a.WorkPoint=wh.WorkPoint
                                    LEFT JOIN ICSInventoryBatchEnable invBat ON a.InvCode=invBat.InvCode AND a.FromWarehouseCode=invBat.WHCode AND a.WorkPoint=invBat.WorkPoint
                                    WHERE {2} ";
                        #endregion

                        columns = @"a.TransferNO AS TransCode,
                                    a.TransferDetailID AS DetailID,
                                    '' AS Type,
                                    a.Sequence AS TransSequence,
                                    a.TransferQuantity AS IssueQuantity,
                                    a.ToWarehouseCode,";

                        tableName = @"ICSTransferApplication a ";

                        where = @" a.TransferNO='{0}' AND a.WorkPoint='{1}' AND a.Status='1' ";
                    }
                    #endregion
                    #region 调拨(合并发料)
                    else if (TransType == TransTypeEnum.StepTransferDocIn.GetDescription())
                    {
                    }
                    #endregion
                    #region 两步调出(合并发料)
                    else if (TransType == TransTypeEnum.TwoStepTransferDocOut.GetDescription())
                    {
                        sqlCheckSign = @"select * from ICSConfiguration where code = 'OutWithLocationCode010' and enable = '1'";
                        flag = DBHelper.SQlReturnData(sqlCheckSign, cmd);
                        isMerge = true;
                        columnsMerge = @"mer.MergeID+'~'+a.OutCode AS TransCode,
                                    a.OutDetailID AS DetailID,
                                    '' AS Type,
                                    a.Sequence AS TransSequence,
                                    a.OutQuantity AS IssueQuantity,";

                        tableNameMerge = @"ICSOtherOut a
                                    INNER JOIN ICSTransfer tra ON a.TransferDetailID=tra.TransferDetailID AND a.WorkPoint=tra.WorkPoint
                                    INNER JOIN ICSMOPickMerge mer ON a.OutDetailID=mer.SourceID AND a.WorkPoint=mer.WorkPoint";

                        columns = @"a.OutCode AS TransCode,
                                    a.OutDetailID AS DetailID,
                                    '' AS Type,
                                    a.Sequence AS TransSequence,
                                    a.OutQuantity AS IssueQuantity,";

                        tableName = @"ICSOtherOut a
                                    INNER JOIN ICSTransfer tra ON a.TransferDetailID=tra.TransferDetailID AND a.WorkPoint=tra.WorkPoint ";

                        where = @" a.OutCode='{0}' AND a.WorkPoint='{1}' ";
                    }
                    #endregion
                    #region 其他出库(合并发料)
                    else if (TransType == TransTypeEnum.OtherOutDoc.GetDescription())
                    {
                        sqlCheckSign = @"select * from ICSConfiguration where code = 'OutWithLocationCode008' and enable = '1'";
                        flag = DBHelper.SQlReturnData(sqlCheckSign, cmd);
                        isMerge = true;
                        columnsMerge = @"mer.MergeID+'~'+a.OutCode AS TransCode,
                                    a.OutDetailID AS DetailID,
                                    '' AS Type,
                                    a.Sequence AS TransSequence,
                                    a.OutQuantity AS IssueQuantity,";

                        tableNameMerge = @"ICSOtherOut a 
                                    INNER JOIN ICSMOPickMerge mer ON a.OutDetailID=mer.SourceID AND a.WorkPoint=mer.WorkPoint";

                        columns = @"a.OutCode AS TransCode,
                                    a.OutDetailID AS DetailID,
                                    '' AS Type,
                                    a.Sequence AS TransSequence,
                                    a.OutQuantity AS IssueQuantity,";

                        tableName = @"ICSOtherOut a ";

                        where = @" a.OutCode='{0}' AND a.WorkPoint='{1}' ";
                    }
                    #endregion
                    #region 领料申请单发料(合并发料)
                    else if (TransType == TransTypeEnum.MOApply.GetDescription())
                    {
                        sqlCheckSign = @"select * from ICSConfiguration where code = 'OutWithLocationCode002' and enable = '1'";
                        flag = DBHelper.SQlReturnData(sqlCheckSign, cmd);
                        isMerge = true;
                        columnsMerge = @"mer.MergeID+'~'+a.ApplyCode AS TransCode,
                                    a.ApplyDetailID AS DetailID,
                                    a.Type,
                                    a.Sequence AS TransSequence,
                                    a.IssueQuantity AS IssueQuantity,";

                        tableNameMerge = @"ICSMOApply a 
                                    INNER JOIN ICSMOPickMerge mer ON a.ID=mer.SourceID AND a.WorkPoint=mer.WorkPoint";

                        columns = @"a.ApplyCode AS TransCode,
                                    a.ApplyDetailID AS DetailID,
                                    a.Type,
                                    a.Sequence AS TransSequence,
                                    a.IssueQuantity AS IssueQuantity,";

                        tableName = @"ICSMOApply a ";

                        where = @" a.ApplyCode='{0}' AND a.WorkPoint='{1}' ";
                    }
                    #endregion
                    #region 补料申请单发料(合并发料)
                    else if (TransType == TransTypeEnum.MOReplenishment.GetDescription())
                    {
                        sqlCheckSign = @"select * from ICSConfiguration where code = 'OutWithLocationCode012' and enable = '1'";
                        flag = DBHelper.SQlReturnData(sqlCheckSign, cmd);
                        isMerge = true;
                        columnsMerge = @"mer.MergeID+'~'+a.ApplyCode AS TransCode,
                                    a.ApplyDetailID AS DetailID,
                                    a.Type,
                                    a.Sequence AS TransSequence,
                                    a.IssueQuantity AS IssueQuantity,";

                        tableNameMerge = @"ICSMOReplenishment a 
                                    INNER JOIN ICSMOPickMerge mer ON a.ID=mer.SourceID AND a.WorkPoint=mer.WorkPoint";

                        columns = @"a.ReplenishmentCode AS TransCode,
                                    a.ReplenishmentDetailID AS DetailID,
                                    a.Type,
                                    a.Sequence AS TransSequence,
                                    a.IssueQuantity AS IssueQuantity,";

                        tableName = @"ICSMOReplenishment a ";

                        where = @" a.ReplenishmentCode='{0}' AND a.WorkPoint='{1}' ";
                    }
                    #endregion
                    #region 委外领料申请单发料(合并发料)
                    else if (TransType == TransTypeEnum.OOApply.GetDescription())
                    {
                        sqlCheckSign = @"select * from ICSConfiguration where code = 'OutWithLocationCode005' and enable = '1'";
                        flag = DBHelper.SQlReturnData(sqlCheckSign, cmd);
                        isMerge = true;
                        columnsMerge = @"mer.MergeID+'~'+a.ApplyCode AS TransCode,
                                    a.ApplyDetailID AS DetailID,
                                    a.Type,
                                    a.Sequence AS TransSequence,
                                    a.IssueQuantity AS IssueQuantity,";

                        tableNameMerge = @"ICSOApply a 
                                    INNER JOIN ICSMOPickMerge mer ON a.ID=mer.SourceID AND a.WorkPoint=mer.WorkPoint";

                        columns = @"a.ApplyCode AS TransCode,
                                    a.ApplyDetailID AS DetailID,
                                    a.Type,
                                    a.Sequence AS TransSequence,
                                    a.IssueQuantity AS IssueQuantity,";

                        tableName = @"ICSOApply a  ";

                        where = @" a.ApplyCode='{0}' AND a.WorkPoint='{1}' ";
                    }
                    #endregion
                    #region 开立材料出库(合并发料)
                    else if (TransType == TransTypeEnum.MOIssue.GetDescription())
                    {
                        sqlCheckSign = @"select * from ICSConfiguration where code = 'OutWithLocationCode003' and enable = '1'";
                        flag = DBHelper.SQlReturnData(sqlCheckSign, cmd);
                        isMerge = true;
                        columnsMerge = @"mer.MergeID+'~'+a.IssueCode AS TransCode,
                                    a.IssueDetailID AS DetailID,
                                    a.Type,
                                    a.Sequence AS TransSequence,
                                    a.IssueQuantity AS IssueQuantity,";

                        tableNameMerge = @"ICSMOIssue a 
                                    INNER JOIN ICSMOPickMerge mer ON a.IssueDetailID=mer.SourceID AND a.WorkPoint=mer.WorkPoint";

                        columns = @"a.IssueCode AS TransCode,
                                    a.IssueDetailID AS DetailID,
                                    a.Type,
                                    a.Sequence AS TransSequence,
                                    a.IssueQuantity AS IssueQuantity,";

                        tableName = @"ICSMOIssue a ";

                        where = @" a.IssueCode='{0}' AND a.WorkPoint='{1}' ";
                    }
                    #endregion
                    #region 开立委外材料出库(合并发料)
                    else if (TransType == TransTypeEnum.OOIssue.GetDescription())
                    {
                        sqlCheckSign = @"select * from ICSConfiguration where code = 'OutWithLocationCode006' and enable = '1'";
                        flag = DBHelper.SQlReturnData(sqlCheckSign, cmd);
                        isMerge = true;
                        columnsMerge = @"mer.MergeID+'~'+a.IssueCode AS TransCode,
                                    a.IssueDetailID AS DetailID,
                                    a.Type,
                                    a.Sequence AS TransSequence,
                                    a.IssueQuantity AS IssueQuantity,";

                        tableNameMerge = @"ICSOIssue a 
                                    INNER JOIN ICSMOPickMerge mer ON a.IssueDetailID=mer.SourceID AND a.WorkPoint=mer.WorkPoint";

                        columns = @"a.IssueCode AS TransCode,
                                    a.IssueDetailID AS DetailID,
                                    a.Type,
                                    a.Sequence AS TransSequence,
                                    a.IssueQuantity AS IssueQuantity,";

                        tableName = @"ICSOIssue a ";

                        where = @" a.IssueCode='{0}' AND a.WorkPoint='{1}' ";
                    }
                    #endregion
                    #region 开立红字入库单
                    else if (TransType == TransTypeEnum.PurchaseReceive.GetDescription())
                    {
                        columns = @"a.RCVCode AS TransCode,
                                    a.RCVDetailID AS DetailID,
                                    a.Type,
                                    a.Sequence AS TransSequence,
                                    a.RCVQuantity AS IssueQuantity,";

                        tableName = @"ICSPurchaseReceive a ";

                        where = @" a.RCVCode='{0}' AND a.WorkPoint='{1}' AND a.Type='2' ";
                    }
                    #endregion
                    #region 开立委外红字入库单
                    else if (TransType == TransTypeEnum.OutsourcingReceiveDocNegative.GetDescription())
                    {
                        columns = @"a.RCVCode AS TransCode,
                                    a.RCVDetailID AS DetailID,
                                    a.Type,
                                    a.Sequence AS TransSequence,
                                    a.RCVQuantity AS IssueQuantity,";

                        tableName = @"ICSOutsourcingReceive a ";

                        where = @" a.RCVCode='{0}' AND a.WorkPoint='{1}' AND a.Type='2' ";
                    }
                    #endregion
                    #region 借用(合并发料)
                    else if (TransType == TransTypeEnum.BrrowDoc.GetDescription())
                    {
                        sqlCheckSign = @"select * from ICSConfiguration where code = 'OutWithLocationCode011' and enable = '1'";
                        flag = DBHelper.SQlReturnData(sqlCheckSign, cmd);
                        isMerge = true;
                        columnsMerge = @"mer.MergeID+'~'+a.BrrowCode AS TransCode,
                                    a.BrrowDetailID AS DetailID,
                                    '' AS Type,
                                    a.Sequence AS TransSequence,
                                    a.BrrowQuantity AS IssueQuantity,";

                        tableNameMerge = @"ICSBrrow a 
                                    INNER JOIN ICSMOPickMerge mer ON a.BrrowDetailID=mer.SourceID AND a.WorkPoint=mer.WorkPoint";

                        columns = @"a.BrrowCode AS TransCode,
                                    a.BrrowDetailID AS DetailID,
                                    '' AS Type,
                                    a.Sequence AS TransSequence,
                                    a.BrrowQuantity AS IssueQuantity,";

                        tableName = @"ICSBrrow a ";

                        where = @" a.BrrowCode='{0}' AND a.WorkPoint='{1}' ";
                    }
                    #endregion
                    #region 送货单
                    else if (TransType == TransTypeEnum.ASN.GetDescription())
                    {
                        isDeliveryNotice = true;
                        columns = @"asn.ASNCode AS TransCode,
                                    asn.ID AS DetailID,
                                    asn.LotNo,
                                    '' AS Type,
                                    asn.Sequence AS TransSequence,
                                    asn.DNQuantity AS IssueQuantity,
                                    asn.Quantity,
                                    asn.Quantity*(a.Amount/a.Quantity) AS Amount,
                                    asn.MUSER AS [User],
                                    asn.MTIME AS [MTime],";

                        tableName = @"ICSInventoryLot a 
                                    INNER JOIN ICSASNDetail asn ON a.LotNo=asn.LotNo AND a.WorkPoint=asn.WorkPoint ";

                        where = @" asn.ASNCode='{0}' AND a.WorkPoint='{1}' ";
                    }
                    #endregion
                    #region 委外送货单
                    else if (TransType == TransTypeEnum.OASN.GetDescription())
                    {
                        isDeliveryNotice = true;
                        columns = @"asn.OASNCode AS TransCode,
                                    asn.ID AS DetailID,
                                    asn.LotNo,
                                    '' AS Type,
                                    asn.Sequence AS TransSequence,
                                    asn.ODNQuantity AS IssueQuantity,
                                    asn.Quantity,
                                    asn.Quantity*(a.Amount/a.Quantity) AS Amount,
                                    asn.MUSER AS [User],
                                    asn.MTIME AS [MTime],";

                        tableName = @"ICSInventoryLot a 
                                    INNER JOIN ICSOASNDetail asn ON a.LotNo=asn.LotNo AND a.WorkPoint=asn.WorkPoint ";

                        where = @" asn.OASNCode='{0}' AND a.WorkPoint='{1}' ";
                    }
                    #endregion
                    #endregion
                    #region 入库
                    #region 采购入库
                    else if (TransType == TransTypeEnum.PurchaseReceiveDoc.GetDescription())
                    {
                    }
                    #endregion
                    #region 审核的到货单
                    else if (TransType == TransTypeEnum.DeliveryNotice.GetDescription())
                    {//扫描到货单 带出检验合格条码数量 且不再库存的条码 --东辉扫描到货单入库 cjw
                        isDeliveryNotice = true;
                        columns = @"DN.DNCode AS TransCode,
                                   ISNULL(ins.QualifiedQuantity+ins.WaiveQuantity, a.Quantity) AS Quantity,
                                    a.Quantity*(a.Amount/a.Quantity) AS Amount,
                                    a.LotNo,
                                    '' AS Type,
                                    DN.Sequence AS TransSequence,
                                    DN.DNQuantity AS IssueQuantity,
                                    DN.Quantity,
                                    DN.MUSER AS [User],
                                    DN.MTIME AS [MTime],";

                        tableName = @"ICSInventoryLot a 
                                        inner join ICSInventoryLotDetail det on a.lotno = det.lotno AND a.WorkPoint=det.WorkPoint
                                        inner join  ICSDeliveryNotice  on DN.DNCode= det.TransCode and DN.Sequence = det.TransSequence aND DN.WorkPoint=det.WorkPoint AND DN.DNTYPE =1
                                        inner join ICSInspection ins on INS.lotno = a.lotno and a.workpoint = ins.workpoint
                                        LEFT JOIN ICSWareHouseLotInfo lotinfo on a.lotno = lotinfo.lotno AND a.WorkPoint=lotinfo.WorkPoint 
                                        ";

                        where = @" DN.DNCode='{0}' AND a.WorkPoint='{1}' and lotinfo.id is null ";
                    }
                    #endregion
                    #region 采购拒收
                    else if (TransType == TransTypeEnum.PurchaseRejectDoc.GetDescription())
                    {
                    }
                    #endregion
                    #region 审核的委外到货单
                    else if (TransType == TransTypeEnum.ODeliveryNotice.GetDescription())
                    {
                    }
                    #endregion
                    #region 委外拒收
                    else if (TransType == TransTypeEnum.OutsourcingRejectDoc.GetDescription())
                    {
                    }
                    #endregion
                    #region 委外退料
                    else if (TransType == TransTypeEnum.ICSOutsourcingIssueDoNegative.GetDescription()
                            || TransType == TransTypeEnum.ICSOutsourcingIssueDoNegativeApply.GetDescription()
                            || TransType == TransTypeEnum.ICSOutsourcingIssueDoNegativeIssue.GetDescription())
                    {
                    }
                    #endregion
                    #region 委外入库
                    else if (TransType == TransTypeEnum.OutsourcingReceiveDoc.GetDescription())
                    {
                    }
                    #endregion
                    #region 生产退料
                    else if (TransType == TransTypeEnum.MOIssueDocNegative.GetDescription()
                        || TransType == TransTypeEnum.MOIssueDocNegativeApply.GetDescription()
                        || TransType == TransTypeEnum.MOIssueDocNegativeIssue.GetDescription())
                    {
                    }
                    #endregion
                    #region 生产入库
                    else if (TransType == TransTypeEnum.ManufactureReceiveDoc.GetDescription())
                    {
                    }
                    #endregion
                    #region 开立的生产入库单
                    else if (TransType == TransTypeEnum.ManufactureReceive.GetDescription())
                    {
                    }
                    #endregion
                    #region 返工工单
                    else if (TransType == TransTypeEnum.ReWorkReceiveMo.GetDescription())
                    {
                    }
                    #endregion
                    #region 销售退货
                    else if (TransType == TransTypeEnum.SalesShipmentDocNegative.GetDescription())
                    {
                    }
                    #endregion
                    #region 两步调入
                    else if (TransType == TransTypeEnum.TwoStepTransferDocIn.GetDescription())
                    {
                        columns = @"a.InCode AS TransCode,
                                    a.InDetailID AS DetailID,
                                    '' AS Type,
                                    a.Sequence AS TransSequence,
                                    a.InQuantity AS IssueQuantity,";

                        tableName = @"ICSOtherIn a
                                    INNER JOIN ICSTransfer tra ON a.TransferDetailID=tra.TransferDetailID AND a.WorkPoint=tra.WorkPoint ";

                        where = @" a.InCode='{0}' AND a.WorkPoint='{1}' ";
                    }
                    #endregion
                    #region 销售退货-原条码
                    else if (TransType == TransTypeEnum.SalesReturnBack.GetDescription())
                    {
                        columns = @"a.SDNCode AS TransCode,
                                    a.SDNDetailID AS DetailID,
                                    a.Type,
                                    a.Sequence AS TransSequence,
                                    a.SDNQuantity AS IssueQuantity,";

                        tableName = @"ICSSDN a ";

                        where = @" a.SDNCode='{0}' AND a.WorkPoint='{1}' AND a.Type='2' ";
                    }
                    #endregion
                    #region 其他入库
                    else if (TransType == TransTypeEnum.OtherInDoc.GetDescription())
                    {
                    }
                    #endregion
                    #region 拆卸单
                    else if (TransType == TransTypeEnum.DisassemblyDoc.GetDescription())
                    {
                        columns = @"a.DABDOCCode AS TransCode,
                                    a.DABDOCDetailID AS DetailID,
                                    a.DABDOCType AS Type,
                                    a.Sequence AS TransSequence,
                                    a.DABDOCQuantity AS IssueQuantity,";

                        tableName = @"ICSDisassemblyDoc a";

                        where = @" a.DABDOCCode='{0}' AND a.WorkPoint='{1}' AND a.DABDOCType='2' ";
                    }
                    #endregion
                    #region 归还
                    else if (TransType == TransTypeEnum.ReturnDoc.GetDescription())
                    {
                    }
                    #endregion
                    #endregion
                    if (string.IsNullOrWhiteSpace(columns) || string.IsNullOrWhiteSpace(tableName) || string.IsNullOrWhiteSpace(where))
                        throw new Exception(language.GetNameByCode("WMSAPIInfo003"));
                    #region 判断是否启用匹配库位

                    if (flag != null && flag.Rows.Count > 0)
                    //if (true)
                    {
                        sql = @"select * into #maintemp from  (" + sql + @")a 
                                    select * into #resulttemp from #maintemp 
                                    truncate table #resulttemp
                                    select a.lotno,a.locationcode,a.invcode,(a.quantity-a.lockQuantity) as quantity ,a.mtime,a.warehousecode,isnull(ext.ProjectCode,'')as ProjectCode, isnull(ext.Version,'')as Version,
                                    isnull(ext.Brand,'')as Brand,
                                    isnull(ext.cFree1,'')as cFree1,
                                    isnull(ext.cFree2,'') cFree2,
                                    isnull(ext.cFree3,'') cFree3,
                                    isnull(ext.cFree4,'') cFree4,
                                    isnull(ext.cFree5,'') cFree5,
                                    isnull(ext.cFree6,'') cFree6,
                                    isnull(ext.cFree7,'') cFree7,
                                    isnull(ext.cFree8,'') cFree8,
                                    isnull(ext.cFree9,'') cFree9,
                                    isnull(ext.cFree10,'') cFree10,ISNULL(ext.BatchCode, '') BatchCode  into #barcodetemp 
                                    from ICSWareHouseLotInfo 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 
                                    LEFT JOIN
                                    (select invcode,ProjectCode,BatchCode,Version,Brand,cFree1,cFree2,cFree3,cFree4,cFree5,cFree6,cFree7,cFree8,cFree9,cFree10,WHCODE from #maintemp 
                                    group by invcode,ProjectCode,BatchCode,Version,Brand,cFree1,cFree2,cFree3,cFree4,cFree5,cFree6,cFree7,cFree8,cFree9,cFree10,WHCODE) b on a.invcode = b.invcode  
                                    where (a.warehousecode = b.whcode or ISNULL(b.whcode,'')='') and  a.Quantity-a.lockQuantity>0 and 
                                                           
                                    isnull(ext.ProjectCode,'') = b.ProjectCode and  isnull(ext.Version,'')=b.Version and 
                                    isnull(ext.Brand,'') =b.Brand and 
                                    isnull(ext.cFree1,'')=b.cFree1 and 
                                    isnull(ext.cFree2,'')=b.cFree2 and 
                                    isnull(ext.cFree3,'')=b.cFree3 and 
                                    isnull(ext.cFree4,'')=b.cFree4 and 
                                    isnull(ext.cFree5,'')=b.cFree5 and 
                                    isnull(ext.cFree6,'')=b.cFree6 and 
                                    isnull(ext.cFree7,'')=b.cFree7 and 
                                    isnull(ext.cFree8,'')=b.cFree8 and 
                                    isnull(ext.cFree9,'')=b.cFree9 and
                                    isnull(ext.cFree10,'')=b.cFree10 and  
									((isnull(b.BatchCode,'')<>'' and b.BatchCode  =ext.BatchCode) or isnull(b.BatchCode,'') ='')

                                    BEGIN
                                    DECLARE @transSequence VARCHAR(50);--当前循环的行号
                                    DECLARE @qty decimal(18, 4);--条码表数量
                                    DECLARE @needqty decimal(18, 4);--本行所需数量
                                    DECLARE @lotno VARCHAR(50);--本行所需数量
                                    DECLARE @locationcode VARCHAR(50);--本行所在库位
                                    DECLARE @WHCode VARCHAR(50);--本行所在仓库
                                    DECLARE @invcode VARCHAR(50);--本行条码
                                    DECLARE @issueQuantity decimal(18, 4);
                                    DECLARE tempCursor CURSOR FOR (select transSequence from #maintemp);   --创建游标tempCursor,并定义游标所指向的集合	
	                                    OPEN tempCursor;                              --打开游标
	                                    FETCH NEXT FROM tempCursor INTO @transSequence;          --游标读取下一个数据
	                                    WHILE @@fetch_status=0  
		                                    BEGIN
			                                    select @needqty=Quantity,@issueQuantity=issueQuantity from #maintemp where transSequence = @transSequence
				                                    PRINT @transSequence
				                                    WHILE @needqty>0
					                                    BEGIN

						                                    select top 1 @qty = isnull(a.quantity,0), @locationcode = isnull(a.locationcode,''),@lotno = isnull(a.lotno,''),@WHCode = isnull(a.warehousecode,''),@invcode = b.invcode from #barcodetemp a
						                                    right JOIN(select invcode,ProjectCode,BatchCode,Version,Brand,cFree1,cFree2,cFree3,cFree4,cFree5,cFree6,cFree7,cFree8,cFree9,cFree10,WHCODE from #maintemp where transSequence=@transSequence)b on a.invcode = b.invcode 
						                                    and ((isnull(b.ProjectCode,'')<>'' and b.ProjectCode = a.ProjectCode) or isnull(b.ProjectCode,'') ='') and  
                                                            ((isnull(b.Version,'')<>'' and b.Version = a.Version) or isnull(b.Version,'') ='') and 
                                                            ((isnull(b.Brand,'')<>'' and b.Brand = a.Brand )or isnull(b.Brand,'') ='') and 
                                                            ((isnull(b.cFree1,'')<>'' and b.cFree1  =a.cFree1) or isnull(b.cFree1,'') ='') and 
                                                            ((isnull(b.cFree2,'')<>'' and b.cFree2  =a.cFree2 )or isnull(b.cFree2,'') ='') and 
                                                            ((isnull(b.cFree3,'')<>'' and b.cFree3  =a.cFree3 )or isnull(b.cFree3,'') ='') and 
                                                            ((isnull(b.cFree4,'')<>'' and b.cFree4  =a.cFree4 )or isnull(b.cFree4,'') ='') and 
                                                            ((isnull(b.cFree5,'')<>'' and b.cFree5  =a.cFree5) or isnull(b.cFree5,'') ='') and 
                                                            ((isnull(b.cFree6,'')<>'' and b.cFree6  =a.cFree6 )or isnull(b.cFree6,'') ='') and 
                                                            ((isnull(b.cFree7,'')<>'' and b.cFree7  =a.cFree7) or isnull(b.cFree7,'') ='') and 
                                                            ((isnull(b.cFree8,'')<>'' and b.cFree8  =a.cFree8) or isnull(b.cFree8,'') ='') and 
                                                            ((isnull(b.cFree9,'')<>'' and b.cFree9  =a.cFree9) or isnull(b.cFree9,'') ='') and
                                                            ((isnull(b.cFree10,'')<>'' and b.cFree10  =a.cFree10) or isnull(b.cFree10,'') ='') and 
															((isnull(b.BatchCode,'')<>'' and b.BatchCode  =a.BatchCode) or isnull(b.BatchCode,'') ='')ORDER BY mtime,locationcode
						                                     IF(@needqty-@issueQuantity-@qty>=0 and ISNULL(@lotno, '')<>'')  
							                                    BEGIN
								                                    insert INTO #resulttemp (id,TransCode,DetailID,Type,TransSequence,IssueQuantity,Quantity,
									                                    Amount,[User],[MTime],InvCode,InvName,InvStd,InvUnit,WHCode,ToWarehouseCode,LocationCode,LocationQty,isMatched,AmountUnit,lotNo,
									                                    WHName,ExtensionID,ProjectCode,BatchCode, Version,Brand,cFree1,cFree2,cFree3,cFree4,cFree5,cFree6,cFree7,cFree8,cFree9,cFree10) 
								                                    SELECT id,TransCode,DetailID,Type,TransSequence,IssueQuantity,Quantity,
									                                    ISNULL(Amount, 0),[User],[MTime],InvCode,InvName,ISNULL(InvStd, ''),InvUnit,isnull(@WHCode,''),isnull(ToWarehouseCode,''),isnull(@LocationCode,''),@qty,1,ISNULL(AmountUnit, ''),ISNULL(@lotno, ''),
									                                    WHName,ExtensionID,ProjectCode,BatchCode, Version,Brand,cFree1,cFree2,cFree3,cFree4,cFree5,cFree6,cFree7,cFree8,cFree9,cFree10 from #maintemp where #maintemp.transSequence = @transSequence
								                                    delete from #barcodetemp where lotno = @lotno
								                                    SET @needqty=@needqty-@qty
							                                    END
						                                    ELSE if(@needqty-@issueQuantity-@qty<0 and ISNULL(@lotno, '')<>''and @needqty-@issueQuantity>0) 
							                                    BEGIN
								
								                                    insert INTO #resulttemp (id,TransCode,DetailID,Type,TransSequence,IssueQuantity,Quantity,
									                                    Amount,[User],[MTime],InvCode,InvName,InvStd,InvUnit,WHCode,ToWarehouseCode,LocationCode,LocationQty,isMatched,AmountUnit,lotno,
									                                    WHName,ExtensionID,ProjectCode,BatchCode, Version,Brand,cFree1,cFree2,cFree3,cFree4,cFree5,cFree6,cFree7,cFree8,cFree9,cFree10) 
								                                    SELECT id,TransCode,DetailID,Type,TransSequence,IssueQuantity,Quantity,
									                                    ISNULL(Amount, 0),[User],[MTime],InvCode,InvName,ISNULL(InvStd, ''),InvUnit,isnull(@WHCode,''),isnull(ToWarehouseCode,''),isnull(@LocationCode,''),case WHEN ISNULL(@qty, 0)=0 THEN 0 else @needqty-@issueQuantity end ,1,ISNULL(AmountUnit, ''),ISNULL(@lotno, ''),
									                                    WHName,ExtensionID,ProjectCode,BatchCode, Version,Brand,cFree1,cFree2,cFree3,cFree4,cFree5,cFree6,cFree7,cFree8,cFree9,cFree10 from #maintemp where #maintemp.transSequence = @transSequence
									                                    update #barcodetemp set quantity = @qty-@needqty+-@issueQuantity  where lotno = @lotno
									                                    SET @needqty=@needqty-@issueQuantity-@qty

							                                    END
                                                            ELSE  
							                                    BEGIN
								
								                                    insert INTO #resulttemp (id,TransCode,DetailID,Type,TransSequence,IssueQuantity,Quantity,
									                                    Amount,[User],[MTime],InvCode,InvName,InvStd,InvUnit,WHCode,ToWarehouseCode,LocationCode,LocationQty,isMatched,AmountUnit,lotno,
									                                    WHName,ExtensionID,ProjectCode,BatchCode, Version,Brand,cFree1,cFree2,cFree3,cFree4,cFree5,cFree6,cFree7,cFree8,cFree9,cFree10) 
								                                    SELECT id,TransCode,DetailID,Type,TransSequence,IssueQuantity,Quantity,
									                                    ISNULL(Amount, 0),[User],[MTime],InvCode,InvName,ISNULL(InvStd, ''),InvUnit,isnull(@WHCode,''),isnull(ToWarehouseCode,''),isnull(@LocationCode,''),0 ,1,ISNULL(AmountUnit, ''),ISNULL(@lotno, ''),
									                                    WHName,ExtensionID,ProjectCode,BatchCode, Version,Brand,cFree1,cFree2,cFree3,cFree4,cFree5,cFree6,cFree7,cFree8,cFree9,cFree10 from #maintemp where #maintemp.transSequence = @transSequence
									                                  
									                                    SET @needqty=0

							                                    END
					                                    END
			                                    FETCH NEXT FROM tempCursor INTO @transSequence;
		                                    END
	                                    CLOSE tempCursor
	                                    DEALLOCATE tempCursor
                                    END

    
									select id,TransCode,DetailID,Type,TransSequence,IssueQuantity,Quantity,
									[User],[MTime],InvCode,InvName,InvStd,InvUnit,WHCode,ToWarehouseCode,LocationCode,sum(LocationQty)as LocationQty,isMatched,AmountUnit,--lotno,
									WHName,ExtensionID,ProjectCode,BatchCode, Version,Brand,cFree1,cFree2,cFree3,cFree4,cFree5,cFree6,cFree7,cFree8,cFree9,cFree10 from #resulttemp GROUP BY id,TransCode,DetailID,Type,TransSequence,IssueQuantity,Quantity,
									[User],[MTime],InvCode,InvName,InvStd,InvUnit,WHCode,ToWarehouseCode,LocationCode,isMatched,AmountUnit,--lotno,
									WHName,ExtensionID,ProjectCode,BatchCode, Version,Brand,cFree1,cFree2,cFree3,cFree4,cFree5,cFree6,cFree7,cFree8,cFree9,cFree10 ORDER BY locationcode ASC ,InvCode ASC


                                DROP table #maintemp
                                DROP table #resulttemp
                                DROP table #barcodetemp";
                    }
                    #endregion
                    if (isDeliveryNotice)//送货、到货、含委外
                    {
                        #region SLQ
                        sql = sqlCheck + @"SELECT a.ID,
                                    {0}
                                    a.InvCode,
                                    inv.InvName,
                                    inv.InvStd,
                                    inv.InvUnit,
                                    '' AS WHCode,
                                    inv.AmountUnit,
                                    '' AS WHName,
                                    a.ExtensionID,
                                    ext.ProjectCode,
                                    CASE WHEN ISNULL(inv.BatchEnable, '0')='1' THEN ext.BatchCode ELSE '' END AS BatchCode,
                                    ext.Version,
                                    ext.Brand,
                                    ext.cFree1,
                                    ext.cFree2,
                                    ext.cFree3,
                                    ext.cFree4,
                                    ext.cFree5,
                                    ext.cFree6,
                                    ext.cFree7,
                                    ext.cFree8,
                                    ext.cFree9,
                                    ext.cFree10
                                    FROM {1}
                                    INNER JOIN ICSExtension ext ON a.ExtensionID=ext.ID AND a.WorkPoint=ext.WorkPoint
                                    INNER JOIN ICSInventory inv ON a.InvCode=inv.InvCode AND a.WorkPoint=inv.WorkPoint
                                    WHERE {2} ";
                        #endregion
                    }
                    else if (isMerge)//合并发料
                    {
                        #region SLQ
                        string sqlMerge = "SELECT ID FROM ICSMOPickMerge WHERE MergeID='" + JsonData.TransCode + "' AND WorkPoint='" + JsonData.WorkPoint + "'";

                        DataTable sign = DBHelper.SQlReturnData(sqlMerge, cmd);
                        if (sign != null && sign.Rows.Count > 0)
                        {
                            string whereMerge = string.Format("mer.MergeID='{0}' AND mer.WorkPoint='{1}'", JsonData.TransCode, JsonData.WorkPoint);
                            sql = string.Format(sql, columnsMerge, tableNameMerge, whereMerge, JsonData.TransCode, excessQtySql);
                        }
                        else
                        {
                            sql = @" BEGIN
                                    IF EXISTS(SELECT a.ID FROM {1} INNER JOIN ICSMOPickMerge c ON a.ID=c.SourceID AND a.WorkPoint=c.WorkPoint WHERE {2})
                                    BEGIN
	                                    RAISERROR('" + language.GetNameByCode("WMSAPIInfo194") + @"',16,1);
                                        RETURN
                                    END
                                " + sqlCheck + sql + @"
                                END";
                        }
                        #endregion
                    }
                    else
                    {
                        sql = sqlCheck + sql;
                    }

                    where = string.Format(where, JsonData.TransCode, JsonData.WorkPoint);
                    sql = string.Format(sql, columns, tableName, where, JsonData.TransCode, excessQtySql);

                    sqls = string.Format(sqls, JsonData.TransCode, JsonData.WorkPoint);
                    Picksql = string.Format(Picksql, sqls, JsonData.WorkPoint);

                    //DataTable table2 = DBHelper.SQlReturnData(Picksql, cmd);
                    //return table2;

                    DataTable table = DBHelper.SQlReturnData(sql, cmd);
                    return table;
                }
                catch (Exception ex)
                {
                    log.Error(ex.Message);
                    throw new Exception(ex.Message);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                    }
                    conn.Dispose();
                }
            }
        }
        #endregion


        #region 源头单据信息(奥美专用)
        /// <summary>
        /// 源头单据信息(奥美专用)
        /// </summary>
        /// <param name="JsonData"></param>
        /// <returns></returns>
        public static DataTable AMTransInformationGet(WMSSourceDocumentModel JsonData)
        {
            var language = LanguageHelper.GetName("WMSAPIInfo");
            using (SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString))
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = conn;
                cmd.CommandTimeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["TimeOut"]);
                try
                {
                    if (string.IsNullOrEmpty(JsonData.TransCode))
                    {
                        throw new Exception(language.GetNameByCode("WMSAPIInfo001"));//"单据号不能为空!"
                    }
                    else if (string.IsNullOrEmpty(JsonData.TransType))
                    {
                        throw new Exception(language.GetNameByCode("WMSAPIInfo002"));//"单据类型不能为空!"
                    }
                    else if (!EnumHelper.HasDescriptions(typeof(TransTypeEnum), JsonData.TransType))
                    {
                        throw new Exception(language.GetNameByCode("WMSAPIInfo003"));//"单据类型不存在!"
                    }
                    else if (string.IsNullOrEmpty(JsonData.WorkPoint))
                    {
                        throw new Exception(language.GetNameByCode("WMSAPIInfo004"));//"站点不能为空!"
                    }

                    string TransType = JsonData.TransType;
                    #region SLQ
                    string sqlCheck = @"IF NOT EXISTS(SELECT a.ID FROM {1} WHERE {2})
                                    BEGIN
	                                    RAISERROR('" + language.GetNameByCode("WMSAPIInfo035") + @"',16,1);
                                        RETURN
                                    END
                                    ";
                    string sql = @"SELECT a.ID,
                                    {0}
                                    convert(varchar(100),'') AS LocationCode,
                                    convert(varchar(100),'') AS LotNo,
                                    convert(varchar(10),'') AS ToWarehouseCode,
									0 AS LocationQty,
                                    0 AS isMatched,
                                    a.InvCode,
                                    inv.InvName,
                                    inv.InvStd,
                                    a.Quantity,
                                    inv.InvUnit,
                                    a.Amount,
                                    a.WHCode,
                                    inv.AmountUnit,
                                    wh.WarehouseName AS WHName,
                                    ISNULL(ext.ProjectCode, '') AS ProjectCode,
                                    a.ExtensionID,
                                    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,
                                    a.MUSER AS [User],
                                    a.MTIME AS [MTime]
                                    {4}
                                    FROM {1}
                                    INNER JOIN ICSExtension ext ON a.ExtensionID=ext.ID AND a.WorkPoint=ext.WorkPoint
                                    INNER JOIN ICSInventory inv ON a.InvCode=inv.InvCode AND a.WorkPoint=inv.WorkPoint
                                    LEFT JOIN ICSWarehouse wh ON a.WHCode=wh.WarehouseCode AND a.WorkPoint=wh.WorkPoint
                                    LEFT JOIN ICSInventoryBatchEnable invBat ON a.InvCode=invBat.InvCode AND a.WHCode=invBat.WHCode AND a.WorkPoint=invBat.WorkPoint
                                    WHERE {2} ";

                    string Picksql = @"SELECT row_number() over (order by c.Code,c.InvCode,d.MTIME,d.LotNO) AS rowNo,
	                        c.Code,
	                        c.InvCode,
	                        c.InvName,
	                        c.InvStd,
c.InvUnit,
	                        FLOOR(c.iQuantity) AS iQuantity,
	                        d.WarehouseCode,
	                        d.LocationCode,
	                        d.LotNO,
	                        FLOOR(ISNULL(d.Quantity, 0)) AS QTY,
	                        CONVERT(varchar(100),d.MTIME, 23) MTIME,
	                        FLOOR(f.QTYTotal) QTYTotal  INTO #temp 
                        FROM
                        ({0}) c
                        LEFT JOIN ICSWareHouseLotInfo d ON c.InvCode=d.INVCode  AND ((LEN(ISNULL(c.WHCode,''))<=0) OR (LEN(ISNULL(c.WHCode,''))>0) AND c.WhCode=d.WarehouseCode)  AND d.WorkPoint='{1}' AND d.Quantity>0
                        left join ICSInventoryLot m on d.LotNo=m.LotNo and d.WorkPoint=m.WorkPoint and c.ExtensionID=m.ExtensionID
                        LEFT JOIN (SELECT INVCode,WarehouseCode,SUM(Quantity) AS QTYTotal FROM ICSWareHouseLotInfo  WHERE WorkPoint='{1}' GROUP BY INVCode,WarehouseCode) f ON c.InvCode=f.INVCode AND c.WhCode=f.WarehouseCode
                        

DECLARE @ItemCode VARCHAR(50),
	@QTY DECIMAL(18,3), 
	@ItemCodeCurrent VARCHAR(50),
	@QTYCurrent DECIMAL(18,3),
	@iQuantityCurrent DECIMAL(18,3),
	@CanDelete BIT,
	@Row INT,
	@rowCurrent INT
SET @Row = @@rowcount
SET @rowCurrent=1
SET @CanDelete=0
SET @ItemCode=''

WHILE @rowCurrent<=@Row
	BEGIN
		SELECT @ItemCodeCurrent=InvCode,@QTYCurrent=QTY,@iQuantityCurrent=iQuantity FROM #temp WHERE rowNo=@rowCurrent

PRINT(@rowCurrent)
		IF @ItemCode<>@ItemCodeCurrent
		BEGIN
			SET @ItemCode=@ItemCodeCurrent
			SET @QTY=0
			SET @CanDelete=0
		END

		IF @CanDelete=1 
		BEGIN
			DELETE FROM #temp WHERE rowNo=@rowCurrent
			SET @rowCurrent += 1
			CONTINUE
		END

		SET @QTY += @QTYCurrent
		IF @QTY>=@iQuantityCurrent
		BEGIN
			SET @CanDelete=1 
		END
		
		SET @rowCurrent += 1
	END
SELECT * FROM #temp
DROP TABLE #temp
";
                    #endregion

                    bool isDeliveryNotice = false;      //送货、到货、含委外
                    string columns = string.Empty;      //查询源头单据表的特殊列名
                    string tableName = string.Empty;    //查询源头单据表名
                    string where = string.Empty;        //查询源头单据的过滤条件
                    bool isMerge = false;               //合并发料
                    string columnsMerge = string.Empty;      //合并发料查询源头单据表的特殊列名
                    string tableNameMerge = string.Empty;    //合并发料查询源头单据表名
                    string sqls = string.Empty;
                    string sqlCheckSign = "";
                    DataTable flag = null;

                    #region 检料表信息
                    if (TransType == TransTypeEnum.MOIssueDoc.GetDescription())
                    {
                        enableCode = "Over001";
                        excessQtySql = ",(dbo.GetExcessQty(a.InvCode, b.Sequence+'~'+a.Sequence, b.MOCode, a.WorkPoint,'" + enableCode + "')) AS excessQty";
                        #region 工单备料sql
                        sqls = @" SELECT
	                        c.MOCode as Code,
	                        a.InvCode,
	                        b.InvName,
	                        b.InvStd,
	                        SUM(ISNULL(a.Quantity, 0)) AS iQuantity,
	                        a.WhCode,
b.InvUnit,
							a.ExtensionID
                        FROM
	                        ICSMOPick a
							inner join ICSMO c on a.MODetailID=c.MODetailID and a.WorkPoint=c.WorkPoint
                            LEFT JOIN ICSINVENTORY b ON a.InvCode = b.InvCode AND a.WorkPoint=b.WorkPoint
                            WHERE  c.MOCode  in ({0}) AND a.WorkPoint = '{1}'
                            GROUP BY c.MOCode,a.InvCode,b.InvName,b.InvStd,b.InvUnit,a.WhCode,a.ExtensionID";
                        #endregion
                    }
                    if (TransType == TransTypeEnum.MOApply.GetDescription())
                    {
                        enableCode = "Over002";
                        excessQtySql = ",(dbo.GetExcessQty(a.InvCode, a.Sequence, a.ApplyCode, a.WorkPoint,'" + enableCode + "')) AS excessQty";
                        #region 工单领料SQL
                        sqls = @"   select
	                        a.ApplyCode as Code,
	                        a.InvCode,
	                        b.InvName,
	                        b.InvStd,
b.InvUnit,
	                        SUM(ISNULL(a.Quantity, 0)) AS iQuantity,
	                        a.WhCode,
							a.ExtensionID
                        FROM
	                        ICSMOApply a
                        LEFT JOIN ICSINVENTORY b ON a.InvCode = b.InvCode AND a.WorkPoint=b.WorkPoint
                        WHERE a.ApplyCode in ({0}) AND a.WorkPoint = '{1}'
                        GROUP BY a.ApplyCode,a.InvCode,b.InvName,b.InvStd,b.InvUnit,a.WhCode,a.ExtensionID";
                        #endregion
                    }
                    if (TransType == TransTypeEnum.MOIssue.GetDescription())
                    {
                        //enableCode = "Over003";
                        excessQtySql = "";
                        #region 工单材料出库SQL
                        sqls = @"  select
	                        a.IssueCode as Code,
	                        a.InvCode,
	                        b.InvName,
	                        b.InvStd,
b.InvUnit,
	                        SUM(ISNULL(a.Quantity, 0)) AS iQuantity,
	                        a.WhCode,
							a.ExtensionID
                        FROM
	                        ICSMOIssue a
                        LEFT JOIN ICSINVENTORY b ON a.InvCode = b.InvCode AND a.WorkPoint=b.WorkPoint
                        WHERE a.IssueCode in ({0}) AND a.WorkPoint = '{1}'
                        GROUP BY a.IssueCode,a.InvCode,b.InvName,b.InvStd,b.InvUnit,a.WhCode,a.ExtensionID";
                        #endregion
                    }
                    if (TransType == TransTypeEnum.OutsourcingIssueDoc.GetDescription())
                    {
                        enableCode = "Over004";
                        excessQtySql = ",(dbo.GetExcessQty(a.InvCode, a.Sequence, b.OOCode, a.WorkPoint,'" + enableCode + "')) AS excessQty";
                        #region 委外备料SQL
                        sqls = @"   								select
	                        c.OOCode as Code,
	                        a.InvCode,
	                        b.InvName,
	                        b.InvStd,
b.InvUnit,
	                        SUM(ISNULL(a.Quantity, 0)) AS iQuantity,
	                        a.WhCode,
													a.ExtensionID
                        FROM
	                        ICSOOPick a
							left join ICSOutsourcingOrder c on a.OODetailID=c.OODetailID and a.WorkPoint=c.WorkPoint
                        LEFT JOIN ICSINVENTORY b ON a.InvCode = b.InvCode AND a.WorkPoint=b.WorkPoint
                     WHERE c.OOCode in ({0}) AND a.WorkPoint = '{1}'
                        GROUP BY c.OOCode,a.InvCode,b.InvName,b.InvStd,b.InvUnit,a.WhCode,	a.ExtensionID";
                        #endregion
                    }
                    if (TransType == TransTypeEnum.OOApply.GetDescription())
                    {
                        enableCode = "Over005";
                        excessQtySql = ",(dbo.GetExcessQty(a.InvCode, a.Sequence, a.ApplyCode, a.WorkPoint,'" + enableCode + "')) AS excessQty";
                        #region 委外领料SQL
                        sqls = @"   	select
	                        a.ApplyCode as Code,
	                        a.InvCode,
	                        b.InvName,
	                        b.InvStd,
b.InvUnit,
	                        SUM(ISNULL(a.Quantity, 0)) AS iQuantity,
	                        a.WhCode,
													a.ExtensionID
                        FROM
	                        ICSOApply a
                        LEFT JOIN ICSINVENTORY b ON a.InvCode = b.InvCode AND a.WorkPoint=b.WorkPoint
                        WHERE a.ApplyCode in ({0}) AND a.WorkPoint = '{1}'
                        GROUP BY a.ApplyCode,a.InvCode,b.InvName,b.InvStd,b.InvUnit,a.WhCode,a.ExtensionID";
                        #endregion
                    }
                    if (TransType == TransTypeEnum.OOIssue.GetDescription())
                    {
                        //enableCode = "Over006";
                        excessQtySql = "";
                        #region 委外材料出库SQL
                        sqls = @" 	select
	                        a.IssueCode as Code,
	                        a.InvCode,
	                        b.InvName,
	                        b.InvStd,
b.InvUnit,
	                        SUM(ISNULL(a.Quantity, 0)) AS iQuantity,
	                        a.WhCode,
a.ExtensionID
                        FROM
	                        ICSOIssue a
                        LEFT JOIN ICSINVENTORY b ON a.InvCode = b.InvCode AND a.WorkPoint=b.WorkPoint
                     WHERE a.IssueCode in ({0}) AND a.WorkPoint = '{1}'
                        GROUP BY a.IssueCode,a.InvCode,b.InvName,b.InvStd,b.InvUnit,a.WhCode,a.ExtensionID";
                        #endregion
                    }
                    if (TransType == TransTypeEnum.SalesShipmentDoc.GetDescription())
                    {
                        enableCode = "";
                        excessQtySql = "";
                        #region 销售发货SQL
                        sqls = @"   select
	                        a.SDNCode as Code,
	                        a.InvCode,
	                        b.InvName,
	                        b.InvStd,
b.InvUnit,
	                        SUM(ISNULL(a.Quantity, 0)) AS iQuantity,
	                        a.WhCode,
a.ExtensionID
                        FROM
	                        ICSSDN a
                        LEFT JOIN ICSINVENTORY b ON a.InvCode = b.InvCode AND a.WorkPoint=b.WorkPoint
                     WHERE a.SDNCode in ({0}) AND a.WorkPoint = '{1}'
                        GROUP BY a.SDNCode,a.InvCode,b.InvName,b.InvStd,b.InvUnit,a.WhCode,a.ExtensionID";
                        #endregion
                    }
                    if (TransType == TransTypeEnum.OtherOutDoc.GetDescription())
                    {
                        enableCode = "";
                        excessQtySql = "";
                        #region 其它出库SQL
                        sqls = @" select
	                        a.OutCode as Code,
	                        a.InvCode,
	                        b.InvName,
	                        b.InvStd,
b.InvUnit,
	                        SUM(ISNULL(a.Quantity, 0)) AS iQuantity,
	                        a.WhCode,
a.ExtensionID
                        FROM
	                        ICSOtherOut a
                        LEFT JOIN ICSINVENTORY b ON a.InvCode = b.InvCode AND a.WorkPoint=b.WorkPoint
                        WHERE a.OutCode in ({0}) AND a.WorkPoint = '{1}'
                        GROUP BY a.OutCode,a.InvCode,b.InvName,b.InvStd,b.InvUnit,a.WhCode,a.ExtensionID";
                        #endregion
                    }
                    if (TransType == TransTypeEnum.BrrowDoc.GetDescription())
                    {
                        enableCode = "";
                        excessQtySql = "";
                        #region 借用SQL
                        sqls = @"select
	                        a.BrrowCode as Code,
	                        a.InvCode,
						
	                        b.InvName,
	                        b.InvStd,
b.InvUnit,
	                        SUM(ISNULL(a.Quantity, 0)) AS iQuantity,
	                        a.WhCode,
a.ExtensionID
                        FROM
	                        ICSBrrow a
                        LEFT JOIN ICSINVENTORY b ON a.InvCode = b.InvCode AND a.WorkPoint=b.WorkPoint
                        WHERE a.BrrowCode in ({0}) AND a.WorkPoint = '{1}'
                        GROUP BY a.BrrowCode,a.InvCode,b.InvName,b.InvStd,b.InvUnit,a.WhCode,a.ExtensionID";
                        #endregion
                    }
                    if (TransType == TransTypeEnum.OneStepTransferDocIn.GetDescription())
                    {
                        enableCode = "";
                        excessQtySql = "";
                        #region 物料调拨
                        sqls = @"						select
	                        a.TransferNO as Code,
	                        a.InvCode,
						
	                        b.InvName,
	                        b.InvStd,
b.InvUnit,
	                        SUM(ISNULL(a.Quantity, 0)) AS iQuantity,
	                        a.FromWarehouseCode as WhCode,
a.ExtensionID
                        FROM
	                        ICSTransfer a
                        LEFT JOIN ICSINVENTORY b ON a.InvCode = b.InvCode AND a.WorkPoint=b.WorkPoint
						 WHERE a.TransferNO in ({0}) AND a.WorkPoint = '{1}'
                        GROUP BY a.TransferNO,a.InvCode,b.InvName,b.InvStd,b.InvUnit,a.FromWarehouseCode,a.ExtensionID";
                        #endregion
                    }
                    if (TransType == TransTypeEnum.TwoStepTransferDocOut.GetDescription())
                    {
                        enableCode = "";
                        excessQtySql = "";
                        #region 两步调出
                        sqls = @"select
	                        a.OutCode as Code,
	                        a.InvCode,
						
	                        b.InvName,
	                        b.InvStd,
b.InvUnit,
	                        SUM(ISNULL(a.Quantity, 0)) AS iQuantity,
	                        a.WHCode ,
a.ExtensionID
                     from  ICSOtherOut a
                        INNER JOIN ICSTransfer tra ON a.TransferDetailID=tra.TransferDetailID AND a.WorkPoint=tra.WorkPoint
                        LEFT JOIN ICSINVENTORY b ON a.InvCode = b.InvCode AND a.WorkPoint=b.WorkPoint
						 WHERE a.OutCode in ({0}) AND a.WorkPoint = '{1}'
                        GROUP BY a.OutCode,a.InvCode,b.InvName,b.InvStd,b.InvUnit,a.WHCode,a.ExtensionID";
                        #endregion
                    }
                    #endregion
                    #region 出库
                    #region 采购退货
                    if (TransType == TransTypeEnum.PurchaseReceiveDoctNegative.GetDescription())
                    {
                        isDeliveryNotice = true;
                        columns = @"a.DNCode AS TransCode,
                                    a.DNDetailID AS DetailID,
                                    a.DNType AS Type,
                                    a.Sequence AS TransSequence,
                                    a.RCVQuantity AS IssueQuantity,
                                    a.Quantity,
                                    a.Amount,
                                    a.MUSER AS [User],
                                    a.MTIME AS [MTime],";

                        tableName = @"ICSDeliveryNotice a ";

                        where = @" a.DNCode='{0}' AND a.WorkPoint='{1}' AND a.DNType='2' AND a.Status<>'3'";
                    }
                    #endregion
                    //#region 工单关联
                    //else if (TransType == TransTypeEnum.ICSMOReceive.GetDescription())
                    //{
                    //    isDeliveryNotice = true;
                    //    columns = @"a.MOCode AS TransCode,
                    //                a.Sequence AS TransSequence,";

                    //    tableName = @"ICSMO a ";

                    //    where = @" a.MOCode='{0}' AND a.WorkPoint='{1}' and a.ERPStatus<>'3'";
                    //}
                    //#endregion
                    #region 委外发料(合并发料)
                    else if (TransType == TransTypeEnum.OutsourcingIssueDoc.GetDescription())
                    {
                        sqlCheckSign = @"select * from ICSConfiguration where code = 'OutWithLocationCode004' and enable = '1'";
                        flag = DBHelper.SQlReturnData(sqlCheckSign, cmd);
                        isMerge = true;
                        columnsMerge = @"mer.MergeID+'~'+b.OOCode AS TransCode,
                                    a.PickID AS DetailID,
                                    a.SupplyType AS Type,
                                    b.Sequence+'~'+a.Sequence AS TransSequence,
                                    a.IssueQuantity AS IssueQuantity,";

                        tableNameMerge = @"ICSOOPick  a
                                INNER JOIN ICSOutsourcingOrder b ON  a.OODetailID=b.OODetailID AND a.WorkPoint=b.WorkPoint
                                    INNER JOIN ICSMOPickMerge mer ON a.PickID=mer.SourceID AND a.WorkPoint=mer.WorkPoint";

                        columns = @"b.OOCode AS TransCode,
                                    a.PickID AS DetailID,
                                    a.SupplyType AS Type,
                                    b.Sequence+'~'+a.Sequence AS TransSequence,
                                    ISNULL((select Sum(log.Quantity) from ICSOOPick  a
	                                INNER JOIN ICSOutsourcingOrder m ON  a.OODetailID=m.OODetailID AND a.WorkPoint=m.WorkPoint 
                                    INNER JOIN ICSWareHouseLotInfoLog log on m.oocode=log.transcode and m.Sequence=log.TransSequence
                                    where m.oocode=b.oocode and m.Sequence=b.Sequence  and log.TransType='15'),0) AS IssueQuantity,";

                        tableName = @"ICSOOPick  a
                                INNER JOIN ICSOutsourcingOrder b ON  a.OODetailID=b.OODetailID AND a.WorkPoint=b.WorkPoint ";

                        where = @" b.OOCode='{0}' AND a.WorkPoint='{1}' AND a.SupplyType='3' AND b.Status<>'3'";
                    }
                    #endregion
                    #region 委外退货
                    else if (TransType == TransTypeEnum.OutsourcingReturnBack.GetDescription())
                    {
                        isDeliveryNotice = true;
                        columns = @"a.ODNCode AS TransCode,
                                    a.ODNDetailID AS DetailID,
                                    a.ODNType AS Type,
                                    a.Sequence AS TransSequence,
                                    a.RCVQuantity AS IssueQuantity,
                                    a.Quantity,
                                    a.Amount,
                                    a.MUSER AS [User],
                                    a.MTIME AS [MTime],";

                        tableName = @"ICSODeliveryNotice a ";

                        where = @" a.ODNCode='{0}' AND a.WorkPoint='{1}' AND a.ODNType='2' AND a.Status<>'3'";
                    }
                    #endregion
                    #region 生产发料(合并发料)
                    else if (TransType == TransTypeEnum.MOIssueDoc.GetDescription())
                    {
                        sqlCheckSign = @"select * from ICSConfiguration where code = 'OutWithLocationCode001' and enable = '1'";
                        flag = DBHelper.SQlReturnData(sqlCheckSign, cmd);
                        isMerge = true;
                        columnsMerge = @"mer.MergeID+'~'+b.MOCode AS TransCode,
                                    a.PickID AS DetailID,
                                    a.SupplyType AS Type,
                                    b.Sequence+'~'+a.Sequence AS TransSequence,
                                    a.IssueQuantity AS IssueQuantity,";

                        tableNameMerge = @"ICSMOPick  a
	                                INNER JOIN ICSMO b ON  a.MODetailID=b.MODetailID AND a.WorkPoint=b.WorkPoint
                                    INNER JOIN ICSMOPickMerge mer ON a.PickID=mer.SourceID AND a.WorkPoint=mer.WorkPoint
                                    INNER JOIN ICSDepartment c on b.DepCode=c.DepCode and b.WorkPoint=c.WorkPoint";

                        columns = @"b.MOCode AS TransCode,
                                    a.PickID AS DetailID,
                                    a.SupplyType AS Type,
                                    b.Sequence+'~'+a.Sequence AS TransSequence,
                                    ISNULL((select Sum(log.Quantity) from ICSMOPick  a
	                                INNER JOIN ICSMO m ON  a.MODetailID=m.MODetailID AND a.WorkPoint=m.WorkPoint 
                                    INNER JOIN ICSWareHouseLotInfoLog log on m.mocode=log.transcode and m.Sequence=log.TransSequence
                                    where m.mocode=b.mocode and m.Sequence=b.Sequence  and log.TransType='15'),0) AS IssueQuantity,";

                        tableName = @"ICSMOPick  a
	                                INNER JOIN ICSMO b ON  a.MODetailID=b.MODetailID AND a.WorkPoint=b.WorkPoint 
                                    INNER JOIN ICSDepartment dd on b.DepCode=dd.DepCode and b.WorkPoint=dd.WorkPoint"; 

                        where = @" b.MOCode='{0}' AND a.WorkPoint='{1}' AND a.SupplyType='3' AND b.MOStatus<>'3' and a.EATTRIBUTE1<>'1'  AND dd.DepName =(SELECT SUBSTRING(F_RealName, 1, 2) FROM Sys_SRM_User WHERE F_Account='{2}' AND F_Location='{1}')";
                    }
                    #endregion
                    #region 销售出库(合并发料)
                    else if (TransType == TransTypeEnum.SalesShipmentDoc.GetDescription())
                    {
                        sqlCheckSign = @"select * from ICSConfiguration where code = 'OutWithLocationCode007' and enable = '1'";
                        flag = DBHelper.SQlReturnData(sqlCheckSign, cmd);
                        isMerge = true;
                        columnsMerge = @"mer.MergeID+'~'+a.SDNCode AS TransCode,
                                    a.SDNDetailID AS DetailID,
                                    a.SOCode,
                                    a.Type,
                                    a.Sequence AS TransSequence,
                                    a.SDNQuantity AS IssueQuantity,";

                        tableNameMerge = @"ICSSDN a 
                                    INNER JOIN ICSMOPickMerge mer ON a.SDNDetailID=mer.SourceID AND a.WorkPoint=mer.WorkPoint";

                        columns = @"a.SDNCode AS TransCode,
                                    a.SDNDetailID AS DetailID,
                                    a.SOCode,
                                    a.Type,
                                    a.Sequence AS TransSequence,
                                   ISNULL((select Sum(b.Quantity) from ICSSDN sdn 
                                    INNER JOIN ICSWareHouseLotInfoLog b on sdn.sdncode=b.transcode and sdn.Sequence=b.TransSequence
                                    where sdn.sdncode=a.sdncode and sdn.Sequence=a.Sequence  and b.TransType='15'),0) AS IssueQuantity,";

                        tableName = @"ICSSDN a ";

                        where = @" a.SDNCode='{0}' AND a.WorkPoint='{1}' AND a.Type='1' AND a.Status<>'3'";
                    }
                    #endregion
                    #region 盘点
                    else if (TransType == TransTypeEnum.Check.GetDescription())
                    {
                        #region SLQ
                        sql = @"SELECT a.ID,
                                    {0}
                                    a.Quantity,
                                    a.SelectLevel AS LocationCode,
                                    a.Amount,
                                    a.MUSER AS [User],
                                    a.MTIME AS [MTime]
                                    FROM {1} 
                                    WHERE {2} ";
                        #endregion

                        columns = @"a.CheckCode AS TransCode,
                                    a.ID,
                                    '' AS Type,";

                        tableName = @"ICSCheck a ";

                        where = @" a.CheckCode='{0}' AND a.WorkPoint='{1}' ";
                    }
                    #endregion
                    #region 一步调拨(合并发料)
                    else if (TransType == TransTypeEnum.OneStepTransferDocIn.GetDescription())
                    {
                        sqlCheckSign = @"select * from ICSConfiguration where code = 'OutWithLocationCode009' and enable = '1'";
                        flag = DBHelper.SQlReturnData(sqlCheckSign, cmd);
                        isMerge = true;
                        columnsMerge = @"mer.MergeID+'~'+a.TransferNO AS TransCode,
                                    a.TransferDetailID AS DetailID,
                                    '' AS Type,
                                    a.Sequence AS TransSequence,
                                    a.TransferQuantity AS IssueQuantity,
                                    a.ToWarehouseCode,";

                        tableNameMerge = @"ICSTransfer a 
                                    INNER JOIN ICSMOPickMerge mer ON a.TransferDetailID=mer.SourceID AND a.WorkPoint=mer.WorkPoint";

                        #region SLQ
                        sql = @"SELECT a.ID,
                                    {0}
                                    convert(varchar(100),'') AS LocationCode,
                                    convert(varchar(100),'') AS LotNo,
									0 AS LocationQty,
                                    0 AS isMatched,
                                    a.InvCode,
                                    inv.InvName,
                                    inv.InvStd,
                                    a.Quantity,
                                    inv.InvUnit,
                                    a.Amount,
                                    a.FromWarehouseCode AS WHCode,
                                    inv.AmountUnit,
                                    wh.WarehouseName AS WHName,
                                    a.ExtensionID,
                                    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 AS BatchCode,
                                    ext.Version,
                                    ext.Brand,
                                    ext.cFree1,
                                    ext.cFree2,
                                    ext.cFree3,
                                    ext.cFree4,
                                    ext.cFree5,
                                    ext.cFree6,
                                    ext.cFree7,
                                    ext.cFree8,
                                    ext.cFree9,
                                    ext.cFree10,
                                    a.MUSER AS [User],
                                    a.MTIME AS [MTime]
                                    FROM {1}
                                    INNER JOIN ICSExtension ext ON a.ExtensionID=ext.ID AND a.WorkPoint=ext.WorkPoint
                                    INNER JOIN ICSInventory inv ON a.InvCode=inv.InvCode AND a.WorkPoint=inv.WorkPoint
                                    LEFT JOIN ICSWarehouse wh ON a.FromWarehouseCode=wh.WarehouseCode AND a.WorkPoint=wh.WorkPoint
                                    LEFT JOIN ICSInventoryBatchEnable invBat ON a.InvCode=invBat.InvCode AND a.FromWarehouseCode=invBat.WHCode AND a.WorkPoint=invBat.WorkPoint
                                    WHERE {2} ";
                        #endregion

                        columns = @"a.TransferNO AS TransCode,
                                    a.TransferDetailID AS DetailID,
                                    '' AS Type,
                                    a.Sequence AS TransSequence,
                                    a.TransferQuantity AS IssueQuantity,
                                    a.ToWarehouseCode,";

                        tableName = @"ICSTransfer a ";

                        where = @" a.TransferNO='{0}' AND a.WorkPoint='{1}' AND a.Status='1' AND a.Status<>'3'";
                    }
                    #endregion
                    #region 调拨申请单(领料)
                    else if (TransType == TransTypeEnum.StepTransferApplicationIn.GetDescription())
                    {
                        isMerge = true;
                        columnsMerge = @"mer.MergeID+'~'+a.TransferNO AS TransCode,
                                    a.TransferDetailID AS DetailID,
                                    '' AS Type,
                                    a.Sequence AS TransSequence,
                                    a.TransferQuantity AS IssueQuantity,
                                    a.ToWarehouseCode,";

                        tableNameMerge = @"ICSTransferApplication a 
                                    INNER JOIN ICSMOPickMerge mer ON a.TransferDetailID=mer.SourceID AND a.WorkPoint=mer.WorkPoint";

                        #region SLQ
                        sql = @"SELECT a.ID,
                                    {0}
                                    convert(varchar(100),'') AS LocationCode,
                                    convert(varchar(100),'') AS LotNo,
									0 AS LocationQty,
                                    0 AS isMatched,
                                    a.InvCode,
                                    inv.InvName,
                                    inv.InvStd,
                                    a.Quantity,
                                    inv.InvUnit,
                                    a.Amount,
                                    a.FromWarehouseCode AS WHCode,
                                    inv.AmountUnit,
                                    wh.WarehouseName AS WHName,
                                    a.ExtensionID,
                                    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 AS BatchCode,
                                    ext.Version,
                                    ext.Brand,
                                    ext.cFree1,
                                    ext.cFree2,
                                    ext.cFree3,
                                    ext.cFree4,
                                    ext.cFree5,
                                    ext.cFree6,
                                    ext.cFree7,
                                    ext.cFree8,
                                    ext.cFree9,
                                    ext.cFree10,
                                    a.MUSER AS [User],
                                    a.MTIME AS [MTime]
                                    FROM {1}
                                    INNER JOIN ICSExtension ext ON a.ExtensionID=ext.ID AND a.WorkPoint=ext.WorkPoint
                                    INNER JOIN ICSInventory inv ON a.InvCode=inv.InvCode AND a.WorkPoint=inv.WorkPoint
                                    LEFT JOIN ICSWarehouse wh ON a.FromWarehouseCode=wh.WarehouseCode AND a.WorkPoint=wh.WorkPoint
                                    LEFT JOIN ICSInventoryBatchEnable invBat ON a.InvCode=invBat.InvCode AND a.FromWarehouseCode=invBat.WHCode AND a.WorkPoint=invBat.WorkPoint
                                    WHERE {2} ";
                        #endregion

                        columns = @"a.TransferNO AS TransCode,
                                    a.TransferDetailID AS DetailID,
                                    '' AS Type,
                                    a.Sequence AS TransSequence,
                                    a.TransferQuantity AS IssueQuantity,
                                    a.ToWarehouseCode,";

                        tableName = @"ICSTransferApplication a ";

                        where = @" a.TransferNO='{0}' AND a.WorkPoint='{1}' AND a.Status='1' AND a.Status<>'3'";
                    }
                    #endregion
                    #region 调拨(合并发料)
                    else if (TransType == TransTypeEnum.StepTransferDocIn.GetDescription())
                    {
                    }
                    #endregion
                    #region 两步调出(合并发料)
                    else if (TransType == TransTypeEnum.TwoStepTransferDocOut.GetDescription())
                    {
                        sqlCheckSign = @"select * from ICSConfiguration where code = 'OutWithLocationCode010' and enable = '1'";
                        flag = DBHelper.SQlReturnData(sqlCheckSign, cmd);
                        isMerge = true;
                        columnsMerge = @"mer.MergeID+'~'+a.OutCode AS TransCode,
                                    a.OutDetailID AS DetailID,
                                    '' AS Type,
                                    a.Sequence AS TransSequence,
                                    a.OutQuantity AS IssueQuantity,";

                        tableNameMerge = @"ICSOtherOut a
                                    INNER JOIN ICSTransfer tra ON a.TransferDetailID=tra.TransferDetailID AND a.WorkPoint=tra.WorkPoint
                                    INNER JOIN ICSMOPickMerge mer ON a.OutDetailID=mer.SourceID AND a.WorkPoint=mer.WorkPoint";

                        columns = @"a.OutCode AS TransCode,
                                    a.OutDetailID AS DetailID,
                                    '' AS Type,
                                    a.Sequence AS TransSequence,
                                    a.OutQuantity AS IssueQuantity,";

                        tableName = @"ICSOtherOut a
                                    INNER JOIN ICSTransfer tra ON a.TransferDetailID=tra.TransferDetailID AND a.WorkPoint=tra.WorkPoint ";

                        where = @" a.OutCode='{0}' AND a.WorkPoint='{1}' AND a.Status<>'3'";
                    }
                    #endregion
                    #region 其他出库(合并发料)
                    else if (TransType == TransTypeEnum.OtherOutDoc.GetDescription())
                    {
                        sqlCheckSign = @"select * from ICSConfiguration where code = 'OutWithLocationCode008' and enable = '1'";
                        flag = DBHelper.SQlReturnData(sqlCheckSign, cmd);
                        isMerge = true;
                        columnsMerge = @"mer.MergeID+'~'+a.OutCode AS TransCode,
                                    a.OutDetailID AS DetailID,
                                    '' AS Type,
                                    a.Sequence AS TransSequence,
                                    a.OutQuantity AS IssueQuantity,";

                        tableNameMerge = @"ICSOtherOut a 
                                    INNER JOIN ICSMOPickMerge mer ON a.OutDetailID=mer.SourceID AND a.WorkPoint=mer.WorkPoint";

                        columns = @"a.OutCode AS TransCode,
                                    a.OutDetailID AS DetailID,
                                    '' AS Type,
                                    a.Sequence AS TransSequence,
                                    a.OutQuantity AS IssueQuantity,";

                        tableName = @"ICSOtherOut a ";

                        where = @" a.OutCode='{0}' AND a.WorkPoint='{1}' AND a.Status<>'3'";
                    }
                    #endregion
                    #region 领料申请单发料(合并发料)
                    else if (TransType == TransTypeEnum.MOApply.GetDescription())
                    {
                        sqlCheckSign = @"select * from ICSConfiguration where code = 'OutWithLocationCode002' and enable = '1'";
                        flag = DBHelper.SQlReturnData(sqlCheckSign, cmd);
                        isMerge = true;
                        columnsMerge = @"mer.MergeID+'~'+a.ApplyCode AS TransCode,
                                    a.ApplyDetailID AS DetailID,
                                    a.Type,
                                    a.Sequence AS TransSequence,
                                    a.IssueQuantity AS IssueQuantity,";

                        tableNameMerge = @"ICSMOApply a 
                                    INNER JOIN ICSMOPickMerge mer ON a.ID=mer.SourceID AND a.WorkPoint=mer.WorkPoint";

                        columns = @"a.ApplyCode AS TransCode,
                                    a.ApplyDetailID AS DetailID,
                                    a.Type,
                                    a.Sequence AS TransSequence,
                                    a.IssueQuantity AS IssueQuantity,";

                        tableName = @"ICSMOApply a ";

                        where = @" a.ApplyCode='{0}' AND a.WorkPoint='{1}' AND a.Status<>'3'";
                    }
                    #endregion
                    #region 补料申请单发料(合并发料)
                    else if (TransType == TransTypeEnum.MOReplenishment.GetDescription())
                    {
                        sqlCheckSign = @"select * from ICSConfiguration where code = 'OutWithLocationCode012' and enable = '1'";
                        flag = DBHelper.SQlReturnData(sqlCheckSign, cmd);
                        isMerge = true;
                        columnsMerge = @"mer.MergeID+'~'+a.ApplyCode AS TransCode,
                                    a.ApplyDetailID AS DetailID,
                                    a.Type,
                                    a.Sequence AS TransSequence,
                                    a.IssueQuantity AS IssueQuantity,";

                        tableNameMerge = @"ICSMOReplenishment a 
                                    INNER JOIN ICSMOPickMerge mer ON a.ID=mer.SourceID AND a.WorkPoint=mer.WorkPoint";

                        columns = @"a.ReplenishmentCode AS TransCode,
                                    a.ReplenishmentDetailID AS DetailID,
                                    a.Type,
                                    a.Sequence AS TransSequence,
                                    a.IssueQuantity AS IssueQuantity,";

                        tableName = @"ICSMOReplenishment a ";

                        where = @" a.ReplenishmentCode='{0}' AND a.WorkPoint='{1}' AND a.Status<>'3'";
                    }
                    #endregion
                    #region 委外领料申请单发料(合并发料)
                    else if (TransType == TransTypeEnum.OOApply.GetDescription())
                    {
                        sqlCheckSign = @"select * from ICSConfiguration where code = 'OutWithLocationCode005' and enable = '1'";
                        flag = DBHelper.SQlReturnData(sqlCheckSign, cmd);
                        isMerge = true;
                        columnsMerge = @"mer.MergeID+'~'+a.ApplyCode AS TransCode,
                                    a.ApplyDetailID AS DetailID,
                                    a.Type,
                                    a.Sequence AS TransSequence,
                                    a.IssueQuantity AS IssueQuantity,";

                        tableNameMerge = @"ICSOApply a 
                                    INNER JOIN ICSMOPickMerge mer ON a.ID=mer.SourceID AND a.WorkPoint=mer.WorkPoint";

                        columns = @"a.ApplyCode AS TransCode,
                                    a.ApplyDetailID AS DetailID,
                                    a.Type,
                                    a.Sequence AS TransSequence,
                                    a.IssueQuantity AS IssueQuantity,";

                        tableName = @"ICSOApply a  ";

                        where = @" a.ApplyCode='{0}' AND a.WorkPoint='{1}' AND a.Status<>'3'";
                    }
                    #endregion
                    #region 开立材料出库(合并发料)
                    else if (TransType == TransTypeEnum.MOIssue.GetDescription())
                    {
                        sqlCheckSign = @"select * from ICSConfiguration where code = 'OutWithLocationCode003' and enable = '1'";
                        flag = DBHelper.SQlReturnData(sqlCheckSign, cmd);
                        isMerge = true;
                        columnsMerge = @"mer.MergeID+'~'+a.IssueCode AS TransCode,
                                    a.IssueDetailID AS DetailID,
                                    a.Type,
                                    a.Sequence AS TransSequence,
                                    a.IssueQuantity AS IssueQuantity,";

                        tableNameMerge = @"ICSMOIssue a 
                                    INNER JOIN ICSMOPickMerge mer ON a.IssueDetailID=mer.SourceID AND a.WorkPoint=mer.WorkPoint";

                        columns = @"a.IssueCode AS TransCode,
                                    a.IssueDetailID AS DetailID,
                                    a.Type,
                                    a.Sequence AS TransSequence,
                                    a.IssueQuantity AS IssueQuantity,";

                        tableName = @"ICSMOIssue a ";

                        where = @" a.IssueCode='{0}' AND a.WorkPoint='{1}' AND a.Status<>'3'";
                    }
                    #endregion
                    #region 开立委外材料出库(合并发料)
                    else if (TransType == TransTypeEnum.OOIssue.GetDescription())
                    {
                        sqlCheckSign = @"select * from ICSConfiguration where code = 'OutWithLocationCode006' and enable = '1'";
                        flag = DBHelper.SQlReturnData(sqlCheckSign, cmd);
                        isMerge = true;
                        columnsMerge = @"mer.MergeID+'~'+a.IssueCode AS TransCode,
                                    a.IssueDetailID AS DetailID,
                                    a.Type,
                                    a.Sequence AS TransSequence,
                                    a.IssueQuantity AS IssueQuantity,";

                        tableNameMerge = @"ICSOIssue a 
                                    INNER JOIN ICSMOPickMerge mer ON a.IssueDetailID=mer.SourceID AND a.WorkPoint=mer.WorkPoint";

                        columns = @"a.IssueCode AS TransCode,
                                    a.IssueDetailID AS DetailID,
                                    a.Type,
                                    a.Sequence AS TransSequence,
                                    a.IssueQuantity AS IssueQuantity,";

                        tableName = @"ICSOIssue a ";

                        where = @" a.IssueCode='{0}' AND a.WorkPoint='{1}' AND a.Status<>'3'";
                    }
                    #endregion
                    #region 开立红字入库单
                    else if (TransType == TransTypeEnum.PurchaseReceive.GetDescription())
                    {
                        columns = @"a.RCVCode AS TransCode,
                                    a.RCVDetailID AS DetailID,
                                    a.Type,
                                    a.Sequence AS TransSequence,
                                    a.RCVQuantity AS IssueQuantity,";

                        tableName = @"ICSPurchaseReceive a ";

                        where = @" a.RCVCode='{0}' AND a.WorkPoint='{1}' AND a.Type='2' AND a.Status<>'3'";
                    }
                    #endregion
                    #region 开立委外红字入库单
                    else if (TransType == TransTypeEnum.OutsourcingReceiveDocNegative.GetDescription())
                    {
                        columns = @"a.RCVCode AS TransCode,
                                    a.RCVDetailID AS DetailID,
                                    a.Type,
                                    a.Sequence AS TransSequence,
                                    a.RCVQuantity AS IssueQuantity,";

                        tableName = @"ICSOutsourcingReceive a ";

                        where = @" a.RCVCode='{0}' AND a.WorkPoint='{1}' AND a.Type='2' AND a.Status<>'3'";
                    }
                    #endregion
                    #region 借用(合并发料)
                    else if (TransType == TransTypeEnum.BrrowDoc.GetDescription())
                    {
                        sqlCheckSign = @"select * from ICSConfiguration where code = 'OutWithLocationCode011' and enable = '1'";
                        flag = DBHelper.SQlReturnData(sqlCheckSign, cmd);
                        isMerge = true;
                        columnsMerge = @"mer.MergeID+'~'+a.BrrowCode AS TransCode,
                                    a.BrrowDetailID AS DetailID,
                                    '' AS Type,
                                    a.Sequence AS TransSequence,
                                    a.BrrowQuantity AS IssueQuantity,";

                        tableNameMerge = @"ICSBrrow a 
                                    INNER JOIN ICSMOPickMerge mer ON a.BrrowDetailID=mer.SourceID AND a.WorkPoint=mer.WorkPoint";

                        columns = @"a.BrrowCode AS TransCode,
                                    a.BrrowDetailID AS DetailID,
                                    '' AS Type,
                                    a.Sequence AS TransSequence,
                                    a.BrrowQuantity AS IssueQuantity,";

                        tableName = @"ICSBrrow a ";

                        where = @" a.BrrowCode='{0}' AND a.WorkPoint='{1}' AND a.Status<>'3'";
                    }
                    #endregion
                    #region 送货单
                    else if (TransType == TransTypeEnum.ASN.GetDescription())
                    {
                        isDeliveryNotice = true;
                        columns = @"asn.ASNCode AS TransCode,
                                    asn.ID AS DetailID,
                                    asn.LotNo,
                                    '' AS Type,
                                    asn.Sequence AS TransSequence,
                                    asn.DNQuantity AS IssueQuantity,
                                    asn.Quantity,
                                    asn.Quantity*(a.Amount/a.Quantity) AS Amount,
                                    asn.MUSER AS [User],
                                    asn.MTIME AS [MTime],";

                        tableName = @"ICSInventoryLot a 
                                    INNER JOIN ICSASNDetail asn ON a.LotNo=asn.LotNo AND a.WorkPoint=asn.WorkPoint ";

                        where = @" asn.ASNCode='{0}' AND a.WorkPoint='{1}' ";
                    }
                    #endregion
                    #region 委外送货单
                    else if (TransType == TransTypeEnum.OASN.GetDescription())
                    {
                        isDeliveryNotice = true;
                        columns = @"asn.OASNCode AS TransCode,
                                    asn.ID AS DetailID,
                                    asn.LotNo,
                                    '' AS Type,
                                    asn.Sequence AS TransSequence,
                                    asn.ODNQuantity AS IssueQuantity,
                                    asn.Quantity,
                                    asn.Quantity*(a.Amount/a.Quantity) AS Amount,
                                    asn.MUSER AS [User],
                                    asn.MTIME AS [MTime],";

                        tableName = @"ICSInventoryLot a 
                                    INNER JOIN ICSOASNDetail asn ON a.LotNo=asn.LotNo AND a.WorkPoint=asn.WorkPoint ";

                        where = @" asn.OASNCode='{0}' AND a.WorkPoint='{1}' ";
                    }
                    #endregion
                    #endregion
                    #region 入库
                    #region 采购入库
                    else if (TransType == TransTypeEnum.PurchaseReceiveDoc.GetDescription())
                    {
                    }
                    #endregion
                    #region 审核的到货单
                    else if (TransType == TransTypeEnum.DeliveryNotice.GetDescription())
                    {
                    }
                    #endregion
                    #region 采购拒收
                    else if (TransType == TransTypeEnum.PurchaseRejectDoc.GetDescription())
                    {
                    }
                    #endregion
                    #region 审核的委外到货单
                    else if (TransType == TransTypeEnum.ODeliveryNotice.GetDescription())
                    {
                    }
                    #endregion
                    #region 委外拒收
                    else if (TransType == TransTypeEnum.OutsourcingRejectDoc.GetDescription())
                    {
                    }
                    #endregion
                    #region 委外退料
                    else if (TransType == TransTypeEnum.ICSOutsourcingIssueDoNegative.GetDescription()
                            || TransType == TransTypeEnum.ICSOutsourcingIssueDoNegativeApply.GetDescription()
                            || TransType == TransTypeEnum.ICSOutsourcingIssueDoNegativeIssue.GetDescription())
                    {
                    }
                    #endregion
                    #region 委外入库
                    else if (TransType == TransTypeEnum.OutsourcingReceiveDoc.GetDescription())
                    {
                    }
                    #endregion
                    #region 生产退料
                    else if (TransType == TransTypeEnum.MOIssueDocNegative.GetDescription()
                        || TransType == TransTypeEnum.MOIssueDocNegativeApply.GetDescription()
                        || TransType == TransTypeEnum.MOIssueDocNegativeIssue.GetDescription())
                    {
                    }
                    #endregion
                    #region 生产入库
                    else if (TransType == TransTypeEnum.ManufactureReceiveDoc.GetDescription())
                    {
                    }
                    #endregion
                    #region 开立的生产入库单
                    else if (TransType == TransTypeEnum.ManufactureReceive.GetDescription())
                    {
                    }
                    #endregion
                    #region 返工工单
                    else if (TransType == TransTypeEnum.ReWorkReceiveMo.GetDescription())
                    {
                    }
                    #endregion
                    #region 销售退货
                    else if (TransType == TransTypeEnum.SalesShipmentDocNegative.GetDescription())
                    {
                    }
                    #endregion
                    #region 两步调入
                    else if (TransType == TransTypeEnum.TwoStepTransferDocIn.GetDescription())
                    {
                        columns = @"a.InCode AS TransCode,
                                    a.InDetailID AS DetailID,
                                    '' AS Type,
                                    a.Sequence AS TransSequence,
                                    a.InQuantity AS IssueQuantity,";

                        tableName = @"ICSOtherIn a
                                    INNER JOIN ICSTransfer tra ON a.TransferDetailID=tra.TransferDetailID AND a.WorkPoint=tra.WorkPoint ";

                        where = @" a.InCode='{0}' AND a.WorkPoint='{1}' AND a.Status<>'3'";
                    }
                    #endregion
                    #region 销售退货-原条码
                    else if (TransType == TransTypeEnum.SalesReturnBack.GetDescription())
                    {
                        columns = @"a.SDNCode AS TransCode,
                                    a.SDNDetailID AS DetailID,
                                    a.Type,
                                    a.Sequence AS TransSequence,
                                    a.SDNQuantity AS IssueQuantity,";

                        tableName = @"ICSSDN a ";

                        where = @" a.SDNCode='{0}' AND a.WorkPoint='{1}' AND a.Type='2' AND a.Status<>'3'";
                    }
                    #endregion
                    #region 其他入库
                    else if (TransType == TransTypeEnum.OtherInDoc.GetDescription())
                    {
                    }
                    #endregion
                    #region 拆卸单
                    else if (TransType == TransTypeEnum.DisassemblyDoc.GetDescription())
                    {
                        columns = @"a.DABDOCCode AS TransCode,
                                    a.DABDOCDetailID AS DetailID,
                                    a.DABDOCType AS Type,
                                    a.Sequence AS TransSequence,
                                    a.DABDOCQuantity AS IssueQuantity,";

                        tableName = @"ICSDisassemblyDoc a";

                        where = @" a.DABDOCCode='{0}' AND a.WorkPoint='{1}' AND a.DABDOCType='2' AND a.Status<>'3' ";
                    }
                    #endregion
                    #region 归还
                    else if (TransType == TransTypeEnum.ReturnDoc.GetDescription())
                    {
                    }
                    #endregion
                    #endregion
                    if (string.IsNullOrWhiteSpace(columns) || string.IsNullOrWhiteSpace(tableName) || string.IsNullOrWhiteSpace(where))
                        throw new Exception(language.GetNameByCode("WMSAPIInfo003"));
                    #region 判断是否启用匹配库位

                    if (flag != null && flag.Rows.Count > 0)
                    //if (true)
                    {
                        sql = @"select * into #maintemp from  (" + sql + @")a 
                                    select * into #resulttemp from #maintemp 
                                    truncate table #resulttemp
                                    select a.lotno,a.locationcode,a.invcode,(a.quantity-a.lockQuantity) as quantity ,a.mtime,a.warehousecode,isnull(ext.ProjectCode,'')as ProjectCode, isnull(ext.Version,'')as Version,
                                    isnull(ext.Brand,'')as Brand,
                                    isnull(ext.cFree1,'')as cFree1,
                                    isnull(ext.cFree2,'') cFree2,
                                    isnull(ext.cFree3,'') cFree3,
                                    isnull(ext.cFree4,'') cFree4,
                                    isnull(ext.cFree5,'') cFree5,
                                    isnull(ext.cFree6,'') cFree6,
                                    isnull(ext.cFree7,'') cFree7,
                                    isnull(ext.cFree8,'') cFree8,
                                    isnull(ext.cFree9,'') cFree9,
                                    isnull(ext.cFree10,'') cFree10,ISNULL(ext.BatchCode, '') BatchCode  into #barcodetemp 
                                    from ICSWareHouseLotInfo 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 
                                    LEFT JOIN
                                    (select invcode,ProjectCode,BatchCode,Version,Brand,cFree1,cFree2,cFree3,cFree4,cFree5,cFree6,cFree7,cFree8,cFree9,cFree10,WHCODE from #maintemp 
                                    group by invcode,ProjectCode,BatchCode,Version,Brand,cFree1,cFree2,cFree3,cFree4,cFree5,cFree6,cFree7,cFree8,cFree9,cFree10,WHCODE) b on a.invcode = b.invcode  
                                    where (a.warehousecode = b.whcode or ISNULL(b.whcode,'')='') and  a.Quantity-a.lockQuantity>0 and 
                                                           
                                    isnull(ext.ProjectCode,'') = b.ProjectCode and  isnull(ext.Version,'')=b.Version and 
                                    isnull(ext.Brand,'') =b.Brand and 
                                    isnull(ext.cFree1,'')=b.cFree1 and 
                                    isnull(ext.cFree2,'')=b.cFree2 and 
                                    isnull(ext.cFree3,'')=b.cFree3 and 
                                    isnull(ext.cFree4,'')=b.cFree4 and 
                                    isnull(ext.cFree5,'')=b.cFree5 and 
                                    isnull(ext.cFree6,'')=b.cFree6 and 
                                    isnull(ext.cFree7,'')=b.cFree7 and 
                                    isnull(ext.cFree8,'')=b.cFree8 and 
                                    isnull(ext.cFree9,'')=b.cFree9 and
                                    isnull(ext.cFree10,'')=b.cFree10 and  
									((isnull(b.BatchCode,'')<>'' and b.BatchCode  =ext.BatchCode) or isnull(b.BatchCode,'') ='')

                                    BEGIN
                                    DECLARE @transSequence VARCHAR(50);--当前循环的行号
                                    DECLARE @qty decimal(18, 4);--条码表数量
                                    DECLARE @needqty decimal(18, 4);--本行所需数量
                                    DECLARE @lotno VARCHAR(50);--本行所需数量
                                    DECLARE @locationcode VARCHAR(50);--本行所在库位
                                    DECLARE @WHCode VARCHAR(50);--本行所在仓库
                                    DECLARE @invcode VARCHAR(50);--本行条码
                                    DECLARE @issueQuantity decimal(18, 4);
                                    DECLARE tempCursor CURSOR FOR (select transSequence from #maintemp);   --创建游标tempCursor,并定义游标所指向的集合	
	                                    OPEN tempCursor;                              --打开游标
	                                    FETCH NEXT FROM tempCursor INTO @transSequence;          --游标读取下一个数据
	                                    WHILE @@fetch_status=0  
		                                    BEGIN
			                                    select @needqty=Quantity,@issueQuantity=issueQuantity from #maintemp where transSequence = @transSequence
				                                    PRINT @transSequence
				                                    WHILE @needqty>0
					                                    BEGIN

						                                    select top 1 @qty = isnull(a.quantity,0), @locationcode = isnull(a.locationcode,''),@lotno = isnull(a.lotno,''),@WHCode = isnull(a.warehousecode,''),@invcode = b.invcode from #barcodetemp a
						                                    right JOIN(select invcode,ProjectCode,BatchCode,Version,Brand,cFree1,cFree2,cFree3,cFree4,cFree5,cFree6,cFree7,cFree8,cFree9,cFree10,WHCODE from #maintemp where transSequence=@transSequence)b on a.invcode = b.invcode 
						                                    and ((isnull(b.ProjectCode,'')<>'' and b.ProjectCode = a.ProjectCode) or isnull(b.ProjectCode,'') ='') and  
                                                            ((isnull(b.Version,'')<>'' and b.Version = a.Version) or isnull(b.Version,'') ='') and 
                                                            ((isnull(b.Brand,'')<>'' and b.Brand = a.Brand )or isnull(b.Brand,'') ='') and 
                                                            ((isnull(b.cFree1,'')<>'' and b.cFree1  =a.cFree1) or isnull(b.cFree1,'') ='') and 
                                                            ((isnull(b.cFree2,'')<>'' and b.cFree2  =a.cFree2 )or isnull(b.cFree2,'') ='') and 
                                                            ((isnull(b.cFree3,'')<>'' and b.cFree3  =a.cFree3 )or isnull(b.cFree3,'') ='') and 
                                                            ((isnull(b.cFree4,'')<>'' and b.cFree4  =a.cFree4 )or isnull(b.cFree4,'') ='') and 
                                                            ((isnull(b.cFree5,'')<>'' and b.cFree5  =a.cFree5) or isnull(b.cFree5,'') ='') and 
                                                            ((isnull(b.cFree6,'')<>'' and b.cFree6  =a.cFree6 )or isnull(b.cFree6,'') ='') and 
                                                            ((isnull(b.cFree7,'')<>'' and b.cFree7  =a.cFree7) or isnull(b.cFree7,'') ='') and 
                                                            ((isnull(b.cFree8,'')<>'' and b.cFree8  =a.cFree8) or isnull(b.cFree8,'') ='') and 
                                                            ((isnull(b.cFree9,'')<>'' and b.cFree9  =a.cFree9) or isnull(b.cFree9,'') ='') and
                                                            ((isnull(b.cFree10,'')<>'' and b.cFree10  =a.cFree10) or isnull(b.cFree10,'') ='') and 
															((isnull(b.BatchCode,'')<>'' and b.BatchCode  =a.BatchCode) or isnull(b.BatchCode,'') ='')ORDER BY mtime,locationcode
						                                     IF(@needqty-@issueQuantity-@qty>=0 and ISNULL(@lotno, '')<>'')  
							                                    BEGIN
								                                    insert INTO #resulttemp (id,TransCode,DetailID,Type,TransSequence,IssueQuantity,Quantity,
									                                    Amount,[User],[MTime],InvCode,InvName,InvStd,InvUnit,WHCode,ToWarehouseCode,LocationCode,LocationQty,isMatched,AmountUnit,lotNo,
									                                    WHName,ExtensionID,ProjectCode,BatchCode, Version,Brand,cFree1,cFree2,cFree3,cFree4,cFree5,cFree6,cFree7,cFree8,cFree9,cFree10) 
								                                    SELECT id,TransCode,DetailID,Type,TransSequence,IssueQuantity,Quantity,
									                                    ISNULL(Amount, 0),[User],[MTime],InvCode,InvName,ISNULL(InvStd, ''),InvUnit,isnull(@WHCode,''),isnull(ToWarehouseCode,''),isnull(@LocationCode,''),@qty,1,ISNULL(AmountUnit, ''),ISNULL(@lotno, ''),
									                                    WHName,ExtensionID,ProjectCode,BatchCode, Version,Brand,cFree1,cFree2,cFree3,cFree4,cFree5,cFree6,cFree7,cFree8,cFree9,cFree10 from #maintemp where #maintemp.transSequence = @transSequence
								                                    delete from #barcodetemp where lotno = @lotno
								                                    SET @needqty=@needqty-@qty
							                                    END
						                                    ELSE if(@needqty-@issueQuantity-@qty<0 and ISNULL(@lotno, '')<>''and @needqty-@issueQuantity>0) 
							                                    BEGIN
								
								                                    insert INTO #resulttemp (id,TransCode,DetailID,Type,TransSequence,IssueQuantity,Quantity,
									                                    Amount,[User],[MTime],InvCode,InvName,InvStd,InvUnit,WHCode,ToWarehouseCode,LocationCode,LocationQty,isMatched,AmountUnit,lotno,
									                                    WHName,ExtensionID,ProjectCode,BatchCode, Version,Brand,cFree1,cFree2,cFree3,cFree4,cFree5,cFree6,cFree7,cFree8,cFree9,cFree10) 
								                                    SELECT id,TransCode,DetailID,Type,TransSequence,IssueQuantity,Quantity,
									                                    ISNULL(Amount, 0),[User],[MTime],InvCode,InvName,ISNULL(InvStd, ''),InvUnit,isnull(@WHCode,''),isnull(ToWarehouseCode,''),isnull(@LocationCode,''),case WHEN ISNULL(@qty, 0)=0 THEN 0 else @needqty-@issueQuantity end ,1,ISNULL(AmountUnit, ''),ISNULL(@lotno, ''),
									                                    WHName,ExtensionID,ProjectCode,BatchCode, Version,Brand,cFree1,cFree2,cFree3,cFree4,cFree5,cFree6,cFree7,cFree8,cFree9,cFree10 from #maintemp where #maintemp.transSequence = @transSequence
									                                    update #barcodetemp set quantity = @qty-@needqty+-@issueQuantity  where lotno = @lotno
									                                    SET @needqty=@needqty-@issueQuantity-@qty

							                                    END
                                                            ELSE  
							                                    BEGIN
								
								                                    insert INTO #resulttemp (id,TransCode,DetailID,Type,TransSequence,IssueQuantity,Quantity,
									                                    Amount,[User],[MTime],InvCode,InvName,InvStd,InvUnit,WHCode,ToWarehouseCode,LocationCode,LocationQty,isMatched,AmountUnit,lotno,
									                                    WHName,ExtensionID,ProjectCode,BatchCode, Version,Brand,cFree1,cFree2,cFree3,cFree4,cFree5,cFree6,cFree7,cFree8,cFree9,cFree10) 
								                                    SELECT id,TransCode,DetailID,Type,TransSequence,IssueQuantity,Quantity,
									                                    ISNULL(Amount, 0),[User],[MTime],InvCode,InvName,ISNULL(InvStd, ''),InvUnit,isnull(@WHCode,''),isnull(ToWarehouseCode,''),isnull(@LocationCode,''),0 ,1,ISNULL(AmountUnit, ''),ISNULL(@lotno, ''),
									                                    WHName,ExtensionID,ProjectCode,BatchCode, Version,Brand,cFree1,cFree2,cFree3,cFree4,cFree5,cFree6,cFree7,cFree8,cFree9,cFree10 from #maintemp where #maintemp.transSequence = @transSequence
									                                  
									                                    SET @needqty=0

							                                    END
					                                    END
			                                    FETCH NEXT FROM tempCursor INTO @transSequence;
		                                    END
	                                    CLOSE tempCursor
	                                    DEALLOCATE tempCursor
                                    END

    
									select id,TransCode,DetailID,Type,TransSequence,IssueQuantity,Quantity,
									[User],[MTime],InvCode,InvName,InvStd,InvUnit,WHCode,ToWarehouseCode,LocationCode,sum(LocationQty)as LocationQty,isMatched,AmountUnit,--lotno,
									WHName,ExtensionID,ProjectCode,BatchCode, Version,Brand,cFree1,cFree2,cFree3,cFree4,cFree5,cFree6,cFree7,cFree8,cFree9,cFree10 from #resulttemp GROUP BY id,TransCode,DetailID,Type,TransSequence,IssueQuantity,Quantity,
									[User],[MTime],InvCode,InvName,InvStd,InvUnit,WHCode,ToWarehouseCode,LocationCode,isMatched,AmountUnit,--lotno,
									WHName,ExtensionID,ProjectCode,BatchCode, Version,Brand,cFree1,cFree2,cFree3,cFree4,cFree5,cFree6,cFree7,cFree8,cFree9,cFree10 ORDER BY locationcode ASC ,InvCode ASC


                                DROP table #maintemp
                                DROP table #resulttemp
                                DROP table #barcodetemp";
                    }
                    #endregion
                    if (isDeliveryNotice)//送货、到货、含委外
                    {
                        #region SLQ
                        sql = sqlCheck + @"SELECT a.ID,
                                    {0}
                                    a.InvCode,
                                    inv.InvName,
                                    inv.InvStd,
                                    inv.InvUnit,
                                    '' AS WHCode,
                                    inv.AmountUnit,
                                    '' AS WHName,
                                    a.ExtensionID,
                                    ext.ProjectCode,
                                    CASE WHEN ISNULL(inv.BatchEnable, '0')='1' THEN ext.BatchCode ELSE '' END AS BatchCode,
                                    ext.Version,
                                    ext.Brand,
                                    ext.cFree1,
                                    ext.cFree2,
                                    ext.cFree3,
                                    ext.cFree4,
                                    ext.cFree5,
                                    ext.cFree6,
                                    ext.cFree7,
                                    ext.cFree8,
                                    ext.cFree9,
                                    ext.cFree10
                                    FROM {1}
                                    INNER JOIN ICSExtension ext ON a.ExtensionID=ext.ID AND a.WorkPoint=ext.WorkPoint
                                    INNER JOIN ICSInventory inv ON a.InvCode=inv.InvCode AND a.WorkPoint=inv.WorkPoint
                                    WHERE {2} ";
                        #endregion
                    }
                    else if (isMerge)//合并发料
                    {
                        #region SLQ
                        string sqlMerge = "SELECT ID FROM ICSMOPickMerge WHERE MergeID='" + JsonData.TransCode + "' AND WorkPoint='" + JsonData.WorkPoint + "'";

                        DataTable sign = DBHelper.SQlReturnData(sqlMerge, cmd);
                        if (sign != null && sign.Rows.Count > 0)
                        {
                            string whereMerge = string.Format("mer.MergeID='{0}' AND mer.WorkPoint='{1}'", JsonData.TransCode, JsonData.WorkPoint);
                            sql = string.Format(sql, columnsMerge, tableNameMerge, whereMerge, JsonData.TransCode, excessQtySql);
                        }
                        else
                        {
                            sql = @" BEGIN
                                    IF EXISTS(SELECT a.ID FROM {1} INNER JOIN ICSMOPickMerge c ON a.ID=c.SourceID AND a.WorkPoint=c.WorkPoint WHERE {2})
                                    BEGIN
	                                    RAISERROR('" + language.GetNameByCode("WMSAPIInfo194") + @"',16,1);
                                        RETURN
                                    END
                                " + sqlCheck + sql + @"
                                END";
                        }
                        #endregion
                    }
                    else
                    {
                        sql = sqlCheck + sql;
                    }

                    where = string.Format(where, JsonData.TransCode, JsonData.WorkPoint,JsonData.User,JsonData.TransSequence);
                    sql = string.Format(sql, columns, tableName, where, JsonData.TransCode, excessQtySql);

                    sqls = string.Format(sqls, JsonData.TransCode, JsonData.WorkPoint);
                    Picksql = string.Format(Picksql, sqls, JsonData.WorkPoint);

                    //DataTable table2 = DBHelper.SQlReturnData(Picksql, cmd);
                    //return table2;
                    log.Debug("源头单据信息sql:" + sql);
                    DataTable table = DBHelper.SQlReturnData(sql, cmd);
                    return table;
                }
                catch (Exception ex)
                {
                    log.Error(ex.Message);
                    throw new Exception(ex.Message);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                    }
                    conn.Dispose();
                }
            }
        }
        #endregion

        /// <summary>
        /// 所有未完成单据号
        /// </summary>
        /// <param name="JsonData"></param>
        /// <returns></returns>
        public static DataTable AMTransCodeGet(WMSSourceDocumentModel JsonData)
        {
            var language = LanguageHelper.GetName("WMSAPIInfo");
            using (SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString))
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = conn;
                cmd.CommandTimeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["TimeOut"]);
                try
                {
                    if (string.IsNullOrEmpty(JsonData.TransType))
                    {
                        throw new Exception(language.GetNameByCode("WMSAPIInfo002"));//"单据类型不能为空!"
                    }
                    else if (!EnumHelper.HasDescriptions(typeof(TransTypeEnum), JsonData.TransType))
                    {
                        throw new Exception(language.GetNameByCode("WMSAPIInfo003"));//"单据类型不存在!"
                    }
                    else if (string.IsNullOrEmpty(JsonData.WorkPoint))
                    {
                        throw new Exception(language.GetNameByCode("WMSAPIInfo004"));//"站点不能为空!"
                    }

                    string TransType = JsonData.TransType;
                    #region SLQ
                    //string sqlCheck = @"IF NOT EXISTS(SELECT a.ID FROM {1} WHERE {2})
                    //                BEGIN
                    //                 RAISERROR('" + language.GetNameByCode("WMSAPIInfo035") + @"',16,1);
                    //                    RETURN
                    //                END
                    //                ";
                    string sql = @"SELECT 
                                    {0}
                                    FROM {1}
                                    WHERE {2} 
                                    order by TransCode asc";
                    #endregion

                    bool isDeliveryNotice = false;      //送货、到货、含委外
                    bool MOApplyWithBin = false;      //生产领料-库位
                    bool OtherOutDocWithBin = false;      //杂发-库位
                    string columns = string.Empty;      //查询源头单据表的特殊列名
                    string tableName = string.Empty;    //查询源头单据表名
                    string where = string.Empty;        //查询源头单据的过滤条件
                    bool isMerge = false;               //合并发料
                    string columnsMerge = string.Empty;      //合并发料查询源头单据表的特殊列名
                    string tableNameMerge = string.Empty;    //合并发料查询源头单据表名
                    #region 出库
                    #region 采购退货
                    if (TransType == TransTypeEnum.PurchaseReceiveDoctNegative.GetDescription())
                    {
                        columns = @" DISTINCT a.DNCode AS TransCode";

                        tableName = @"ICSDeliveryNotice a ";

                        where = @" a.WorkPoint='{1}' AND a.DNType='2' AND a.Status='2' AND (a.Quantity-a.RCVQuantity)>0";
                    }
                    #endregion
                    #region 其他出库
                    else if (TransType == TransTypeEnum.OtherOutDoc.GetDescription())
                    {
                        columns = @" DISTINCT a.OutCode AS TransCode";

                        tableName = @"ICSOtherOut a ";

                        where = @" a.Status='1' AND a.WorkPoint='{1}' and a.Quantity>a.OutQuantity";
                    }
                    #endregion
                    #region 一步调拨(合并发料)
                    else if (TransType == TransTypeEnum.OneStepTransferDocIn.GetDescription())
                    {
                        columns = @" DISTINCT a.TransferNO AS TransCode";

                        tableName = @"ICSTransfer a ";

                        where = @"  a.WorkPoint='{1}' AND a.Status='1' AND a.Quantity>a.TransferQuantity AND Type='1'";
                    }
                    #endregion
                    #region 生产发料(合并发料)
                    else if (TransType == TransTypeEnum.MOIssueDoc.GetDescription())
                    {
                        columns = @" DISTINCT b.MOCode AS TransCode";

                        tableName = @" ICSMOPick  a
	                                INNER JOIN ICSMO b ON  a.MODetailID=b.MODetailID AND a.WorkPoint=b.WorkPoint 
                                    INNER JOIN ICSDepartment c on b.DepCode=c.DepCode and b.WorkPoint=c.WorkPoint";

                        where = @" a.WorkPoint='{1}' AND a.SupplyType='3' AND b.MOStatus<>'3' and a.EATTRIBUTE1<>'1' and a.Quantity-a.IssueQuantity>0 
                                    AND c.DepName =(SELECT SUBSTRING(F_RealName, 1, 2) FROM Sys_SRM_User WHERE F_Account='{2}' AND F_Location='{1}') ";
                    }
                    #endregion
                    #region 开立材料出库(合并发料)
                    else if (TransType == TransTypeEnum.MOIssue.GetDescription())
                    {
                        columns = @" DISTINCT a.IssueCode AS TransCode";

                        tableName = @" ICSMOIssue a ";

                        where = @" a.WorkPoint='{1}' AND a.Status<>'3' and a.Quantity-a.IssueQuantity>0";
                    }
                    #endregion
                    #region 生产发料-领料申请单
                    else if (TransType == TransTypeEnum.MOApply.GetDescription())
                    {
                        columns = @" DISTINCT a.ApplyCode AS TransCode";

                        tableName = @" ICSMOApply a
									    INNER JOIN ICSMO b ON b.MOCode=a.SourceCode and a.SourceSequence =  b.Sequence AND a.WorkPoint=b.WorkPoint";

                        where = @" a.Status='2' AND a.WorkPoint='{1}' and a.Quantity-a.IssueQuantity>0";
                    }
                    #endregion
                    #region 开立委外材料出库(合并发料)
                    else if (TransType == TransTypeEnum.OOIssue.GetDescription())
                    {
                        columns = @" DISTINCT a.IssueCode AS TransCode";

                        tableName = @" ICSOIssue a ";

                        where = @" a.WorkPoint='{1}' AND a.Status<>'3' and a.Quantity-a.IssueQuantity>0";
                    }
                    #endregion
                    #region 委外领料申请单发料(合并发料)
                    else if (TransType == TransTypeEnum.OOApply.GetDescription())
                    {
                        columns = @" DISTINCT a.ApplyCode AS TransCode";

                        tableName = @" ICSOApply a  ";

                        where = @" a.WorkPoint='{1}' AND a.Status<>'3' and a.Quantity-a.IssueQuantity>0";
                    }
                    #endregion
                    #region 委外发料(合并发料)
                    else if (TransType == TransTypeEnum.OutsourcingIssueDoc.GetDescription())
                    {
                        columns = @" DISTINCT b.OOCode AS TransCode";

                        tableName = @" ICSOOPick  a
                                INNER JOIN ICSOutsourcingOrder b ON  a.OODetailID=b.OODetailID AND a.WorkPoint=b.WorkPoint ";

                        where = @" a.WorkPoint='{1}' AND a.SupplyType='3' AND b.Status<>'3' and a.Quantity-a.IssueQuantity>0";
                    }
                    #endregion
                    #region 销售出库(合并发料)
                    else if (TransType == TransTypeEnum.SalesShipmentDoc.GetDescription())
                    {
                        columns = @" DISTINCT a.SDNCode AS TransCode";

                        tableName = @"ICSSDN a ";

                        where = @" a.WorkPoint='{1}' AND a.Type='1' AND a.Status<>'3' and a.Quantity-a.SDNQuantity>0";
                    }
                    #endregion
                    #region 盘点
                    else if (TransType == TransTypeEnum.Check.GetDescription())
                    {

                        columns = @" DISTINCT a.CheckCode AS TransCode";

                        tableName = @"ICSCheck a ";

                        where = @" a.WorkPoint='{1}' ";
                    }
                    #endregion
                    where = string.Format(where, JsonData.TransCode, JsonData.WorkPoint,JsonData.User);
                    sql = string.Format(sql, columns, tableName, where, JsonData.TransCode);
                    log.Debug("源头单据sql : " + sql);
                    DataTable table = DBHelper.SQlReturnData(sql, cmd);
                    return table;
                    #endregion
                }
                catch (Exception ex)
                {
                    log.Error(ex.Message);
                    throw new Exception(ex.Message);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                    }
                    conn.Dispose();
                }
            }
        }


        public static Result AMBarCodeInformationGet(BarCodeModel JsonData)
        {
            var language = LanguageHelper.GetName("WMSAPIInfo");
            DataTable table = new DataTable();
            DataTable ZLtable = new DataTable();
            using (SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString))
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = conn;
                cmd.CommandTimeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["TimeOut"]);
                try
                {
                    string ScanType = DBHelper.ScanTypeCheck(JsonData.Code, JsonData.WorkPoint, cmd);
                    if (string.IsNullOrEmpty(JsonData.Code))
                    {
                        throw new Exception(language.GetNameByCode("WMSAPIInfo005"));//"条码不能为空!"
                    }
                    else if (string.IsNullOrEmpty(JsonData.TransType))
                    {
                        throw new Exception(language.GetNameByCode("WMSAPIInfo002"));//"单据类型不能为空!"
                    }
                    else if (!EnumHelper.HasDescriptions(typeof(TransTypeEnum), JsonData.TransType))
                    {
                        throw new Exception(language.GetNameByCode("WMSAPIInfo003"));//"单据类型不存在!"
                    }
                    else if (string.IsNullOrEmpty(JsonData.WorkPoint))
                    {
                        throw new Exception(language.GetNameByCode("WMSAPIInfo004"));//"站点不能为空!"
                    }

                    string TransType = JsonData.TransType;
                    string sql = "";
                    string LotTypesql = "";
                    string Losql = "";
                    string sqlNew = "";
                    string LotType = "";
                    string UserName = "";
                    string UName = "";
                    bool iszl = false;
                    string zlqty = "0";
                    #region SLQ
                    if (TransType == TransTypeEnum.LocationSeatch.GetDescription())
                    {
                        //Losql = @"SELECT a.ID,
                        //            con.ContainerCode,
                        //            con.ContainerName,
                        //            a.LotNo,
                        //            a.InvCode,
                        //            inv.InvName,
                        //            inv.InvStd,
                        //            inv.InvUnit,
                        //            inv.LotEnable,
                        //            {0}
                        //            inv.AmountUnit,
                        //            ext.ID AS ExtensionID,
                        //            ext.ProjectCode,
                        //            ext.Version,
                        //            ext.Brand,
                        //            ext.cFree1,
                        //            ext.cFree2,
                        //            ext.cFree3,
                        //            ext.cFree4,
                        //            ext.cFree5,
                        //            ext.cFree6,
                        //            ext.cFree7,
                        //            ext.cFree8,
                        //            ext.cFree9,
                        //            ext.cFree10,
                        //            a.MUSER AS [User],
                        //            a.MTIME AS [MTime]
                        //            FROM {1}
                        //            LEFT JOIN ICSContainerLot conlot ON a.LotNo=conlot.LotNo AND a.WorkPoint=conlot.WorkPoint
                        //            LEFT JOIN ICSContainer con ON conlot.ContainerID=con.ID AND conlot.WorkPoint=con.WorkPoint
                        //            INNER JOIN ICSInventory inv ON a.InvCode=inv.InvCode AND a.WorkPoint=inv.WorkPoint
                        //            WHERE a.Quantity>0 and a.WorkPoint='{3}'";
                        Losql = @"  DECLARE @wheresql VARCHAR(MAX)
								    DECLARE @groupsql VARCHAR(MAX)
								    DECLARE @aa VARCHAR(MAX)
								    DECLARE @bb VARCHAR(MAX)
								    DECLARE @cc VARCHAR(MAX)
								    DECLARE @dd VARCHAR(MAX)
								    DECLARE @b VARCHAR(MAX)

								    select @aa=id from ICSWareHouseLotInfo where LotNo='{2}'
										    IF @aa IS NOT NULL
											    BEGIN
											    set @wheresql='and a.lotno=''{2}''  and s.invcode IN(SELECT invcode FROM ICSWareHouseLotInfo where LotNo=''{2}'') and a.invcode=s.invcode '
											    set @groupsql=' group by inv.LotEnable,a.ID,con.ContainerCode,con.ContainerName,a.LotNo,a.InvCode,inv.InvName,inv.InvStd,inv.InvUnit,inv.LotEnable,a.warehouseCode,a.LocationCode, inv.INVCODE,inv.INVNAME,inv.INVSTD,a.Quantity,inv.AmountUnit,
								    ext.ID,ext.ProjectCode,ext.Version,ext.Brand,ext.cFree1,ext.cFree2,ext.cFree3,ext.cFree4,ext.cFree5,ext.cFree6,ext.cFree7,ext.cFree8,ext.cFree9,ext.cFree10,a.MUSER ,a.MTIME'
										    END
											
								    select @bb=id from ICSLocation where LocationCode='{2}'
									    IF @bb IS not NULL
										    BEGIN
											    set @wheresql='and a.locationcode=s.locationcode and  a.LocationCode=''{2}'' '
											    set @groupsql = 'group by inv.LotEnable,a.ID,con.ContainerCode,con.ContainerName,a.LotNo,a.InvCode,inv.InvName,inv.InvStd,inv.InvUnit,inv.LotEnable,a.warehouseCode,a.LocationCode, inv.INVCODE,inv.INVNAME,inv.INVSTD,a.Quantity,inv.AmountUnit,
								    ext.ID,ext.ProjectCode,ext.Version,ext.Brand,ext.cFree1,ext.cFree2,ext.cFree3,ext.cFree4,ext.cFree5,ext.cFree6,ext.cFree7,ext.cFree8,ext.cFree9,ext.cFree10,a.MUSER ,a.MTIME'
									        END
										
								    select @cc=id from ICSInventory where invcode='{2}'
										    IF @cc IS not NULL
											    BEGIN
												    set @wheresql='and  inv.invcode=''{2}'' and a.invcode=s.invcode '
												    set @groupsql='group by inv.LotEnable,a.ID,con.ContainerCode,con.ContainerName,a.LotNo,a.InvCode,inv.InvName,inv.InvStd,inv.InvUnit,inv.LotEnable,a.WarehouseCode,a.LocationCode, inv.INVCODE,inv.INVNAME,inv.INVSTD,a.Quantity,inv.AmountUnit,
								    ext.ID,ext.ProjectCode,ext.Version,ext.Brand,ext.cFree1,ext.cFree2,ext.cFree3,ext.cFree4,ext.cFree5,ext.cFree6,ext.cFree7,ext.cFree8,ext.cFree9,ext.cFree10,a.MUSER ,a.MTIME'
										    END
												
								    select @dd=id from ICSInventory where InvStd LIKE '%{2}%'
										    IF @dd IS not NULL
											    BEGIN
												    set @wheresql='and inv.InvStd LIKE ''%{2}%'' '
												    set @groupsql='group by inv.LotEnable,a.ID,con.ContainerCode,con.ContainerName,a.LotNo,a.InvCode,inv.InvName,inv.InvStd,inv.InvUnit,inv.LotEnable,a.WarehouseCode,a.LocationCode, inv.INVCODE,inv.INVNAME,inv.INVSTD,a.Quantity,inv.AmountUnit,
								    ext.ID,ext.ProjectCode,ext.Version,ext.Brand,ext.cFree1,ext.cFree2,ext.cFree3,ext.cFree4,ext.cFree5,ext.cFree6,ext.cFree7,ext.cFree8,ext.cFree9,ext.cFree10,a.MUSER ,a.MTIME'
										    END
												
								    IF @aa IS NULL and @bb IS NULL and @cc IS NULL and @dd IS NULL
								    BEGIN
									    RAISERROR('" + language.GetNameByCode("WMSAPIInfo478") + @"',16,1)
								    END
								    ELSE
								    BEGIN
													
									    set @b =
										    'SELECT a.ID,con.ContainerCode,con.ContainerName,a.LotNo,a.InvCode,
																    inv.InvName,
																    inv.InvStd,
																    inv.InvUnit,
																    inv.LotEnable,
																    a.WarehouseCode,a.LocationCode,a.Quantity as Qty,SUM(s.sumQty) sumQty,
																    inv.AmountUnit,
																    ext.ID AS ExtensionID,
																    ext.ProjectCode,
																    ext.Version,
																    ext.Brand,
																    ext.cFree1,
																    ext.cFree2,
																    ext.cFree3,
																    ext.cFree4,
																    ext.cFree5,
																    ext.cFree6,
																    ext.cFree7,
																    ext.cFree8,
																    ext.cFree9,
																    ext.cFree10,
																    a.MUSER AS [User],
																    a.MTIME AS [MTime]
																    FROM ICSWareHouseLotInfo a 
										    LEFT JOIN ICSLocation b ON a.LocationCode = b.LocationCode and a.WorkPoint=b.WorkPoint
										    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
										    LEFT JOIN (select SUM(Quantity) AS sumQty,WarehouseCode,INVCode,LocationCode,workpoint from ICSWareHouseLotInfo where quantity>0  group by WarehouseCode,INVCode,LocationCode,workpoint)s ON a.workpoint=s.workpoint 
										    LEFT JOIN ICSContainerLot conlot ON a.LotNo=conlot.LotNo AND a.WorkPoint=conlot.WorkPoint
										    LEFT JOIN ICSContainer con ON conlot.ContainerID=con.ID AND conlot.WorkPoint=con.WorkPoint
										    INNER JOIN ICSInventory inv ON a.InvCode=inv.InvCode AND a.WorkPoint=inv.WorkPoint
										    WHERE   a.Quantity>0 and a.WorkPoint=''{3}'' ' + @wheresql + @groupsql
								    END
												
								exec(@b)				
										
				
										
";
                    }
                    else
                    {
                        if (ScanType == "LOTNO")
                        {
                            sql = @"SELECT a.ID,
                                    con.ContainerCode,
                                    con.ContainerName,
                                    a.LotNo,
                                    a.InvCode,
                                    inv.InvName,
                                    inv.InvStd,
                                    inv.InvUnit,
                                    inv.LotEnable,
                                    {0}
                                    inv.AmountUnit,
                                    inv.AmountEnable,
                                    ext.ID AS ExtensionID,
                                    ext.ProjectCode,
                                    ext.Version,
                                    ext.Brand,
                                    ext.cFree1,
                                    ext.cFree2,
                                    ext.cFree3,
                                    ext.cFree4,
                                    ext.cFree5,
                                    ext.cFree6,
                                    ext.cFree7,
                                    ext.cFree8,
                                    ext.cFree9,
                                    ext.cFree10,
                                    a.MUSER AS [User],
                                    a.MTIME AS [MTime]
                                    FROM {1}
                                    LEFT JOIN ICSContainerLot conlot ON a.LotNo=conlot.LotNo AND a.WorkPoint=conlot.WorkPoint
                                    LEFT JOIN ICSContainer con ON conlot.ContainerID=con.ID AND conlot.WorkPoint=con.WorkPoint
                                    INNER JOIN ICSInventory inv ON a.InvCode=inv.InvCode AND a.WorkPoint=inv.WorkPoint
                                    WHERE  a.LotNo='{2}' AND a.WorkPoint='{3}' ";
                        }
                        else
                        {
                            sql = @"SELECT a.ID,
                                    con.ContainerCode,
                                    con.ContainerName,
                                    a.LotNo,
                                    a.InvCode,
                                    inv.InvName,
                                    inv.InvStd,
                                    inv.InvUnit,
                                    {0}
                                    inv.AmountUnit,
                                    inv.AmountEnable,
                                    ext.ID AS ExtensionID,
                                    ext.ProjectCode,
                                    ext.Version,
                                    ext.Brand,
                                    ext.cFree1,
                                    ext.cFree2,
                                    ext.cFree3,
                                    ext.cFree4,
                                    ext.cFree5,
                                    ext.cFree6,
                                    ext.cFree7,
                                    ext.cFree8,
                                    ext.cFree9,
                                    ext.cFree10,
                                    a.MUSER AS [User],
                                    a.MTIME AS [MTime]
                                    FROM {1}
                                    LEFT JOIN ICSContainerLot conlot ON a.LotNo=conlot.LotNo AND a.WorkPoint=conlot.WorkPoint
                                    LEFT JOIN ICSBomALL bom ON bom.ID=conlot.ContainerID
                                    LEFT JOIN ICSContainer con ON conlot.ContainerID=con.ID AND conlot.WorkPoint=con.WorkPoint
                                    INNER JOIN ICSInventory inv ON a.InvCode=inv.InvCode AND a.WorkPoint=inv.WorkPoint
                                    WHERE  bom.ContainerCode='{2}' AND a.WorkPoint='{3}' ";
                        }
                    }




                    #endregion
                    bool isOut = false;                 //出库标记
                    string columns = string.Empty;      //查询源头单据表的特殊列名
                    string columnsLOCODE = string.Empty;
                    string columnsLONAME = string.Empty;
                    string columnsWHCODE = string.Empty;
                    string columnsWHNAME = string.Empty;
                    string tableName = string.Empty;    //查询源头单据表名
                    string where = string.Empty;    //排序
                    if (TransType == TransTypeEnum.PurchaseReceiveDoctNegative.GetDescription()    //采购退货
                        || TransType == TransTypeEnum.OutsourcingIssueDoc.GetDescription()         //委外发料
                        || TransType == TransTypeEnum.OutsourcingReturnBack.GetDescription()       //委外退货
                        || TransType == TransTypeEnum.MOIssueDoc.GetDescription()                  //生产发料
                        || TransType == TransTypeEnum.SalesShipmentDoc.GetDescription()            //销售出库
                        || TransType == TransTypeEnum.OneStepTransferDocIn.GetDescription()        //一步调拨
                        || TransType == TransTypeEnum.StepTransferApplicationIn.GetDescription()        //调拨申请单
                        || TransType == TransTypeEnum.StepTransferDocIn.GetDescription()        //调拨
                        || TransType == TransTypeEnum.StepNoTransferDocIn.GetDescription()        //无源头调拨
                        || TransType == TransTypeEnum.TwoStepTransferDocOut.GetDescription()       //两步调出
                        || TransType == TransTypeEnum.OtherOutDoc.GetDescription()                 //其他出库
                        || TransType == TransTypeEnum.Check.GetDescription()                       //盘点
                        || TransType == TransTypeEnum.MOApply.GetDescription()                     //领料申请单
                        || TransType == TransTypeEnum.MOReplenishment.GetDescription()                     //领料申请单
                        || TransType == TransTypeEnum.OOApply.GetDescription()                     //委外领料申请单
                        || TransType == TransTypeEnum.MOIssue.GetDescription()                     //开立材料出库单
                        || TransType == TransTypeEnum.OOIssue.GetDescription()                     //开立委外材料出库单
                        || TransType == TransTypeEnum.PurchaseReceive.GetDescription()             //开立红字入库单
                        || TransType == TransTypeEnum.OutsourcingReceiveDocNegative.GetDescription()//开立委外红字入库单
                        || TransType == TransTypeEnum.BrrowDoc.GetDescription()                    //借用
                        || TransType == TransTypeEnum.TransferLibrary.GetDescription()             //移库
                                                                                                   //|| TransType == TransTypeEnum.DisassemblyDoc.GetDescription()             //拆卸单(散件生成条码入库)
                        )
                    {
                        isOut = true;
                    }
                    //库位查询
                    if (TransType == TransTypeEnum.LocationSeatch.GetDescription())
                    {
                        //             Losql = @"" + Losql + "group by a.ID,con.ContainerCode,con.ContainerName,a.LotNo,a.InvCode,inv.InvName,inv.InvStd,inv.InvUnit,inv.LotEnable,s.WarehouseCode, inv.INVCODE,inv.INVNAME,inv.INVSTD,s.sumQty,inv.AmountUnit,ext.ID,ext.ProjectCode,ext.Version,ext.Brand, " +
                        //                 "ext.cFree1,ext.cFree2,ext.cFree3,ext.cFree4,ext.cFree5,ext.cFree6,ext.cFree7,ext.cFree8,ext.cFree9,ext.cFree10,a.MUSER ,a.MTIME";

                        //             columns = @"s.WarehouseCode, inv.INVCODE,inv.INVNAME,inv.INVSTD,sum(a.Quantity) as Qty,s.sumQty,";

                        //             tableName = @"ICSWareHouseLotInfo a 
                        //LEFT JOIN ICSLocation b ON a.LocationCode = b.LocationCode and a.WorkPoint=b.WorkPoint
                        //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
                        //LEFT JOIN (select SUM(Quantity) AS sumQty,WarehouseCode,INVCode from ICSWareHouseLotInfo  group by WarehouseCode,INVCode)s 
                        //ON a.INVCode=s.INVCode ";

                    }
                    else
                    {
                        //两步调入条码
                        if (TransType == TransTypeEnum.TwoStepTransferDocIn.GetDescription())
                        {
                            if (string.IsNullOrEmpty(JsonData.TransCode))
                            {
                                throw new Exception(language.GetNameByCode("WMSAPIInfo001"));//"单据号不能为空!"
                            }
                            if (ScanType == "LOTNO")
                            {
                                sql = @"IF NOT EXISTS(SELECT a.ID FROM ICSOtherIn Otin
                                            INNER JOIN ICSTransfer tra ON Otin.TransferDetailID=tra.TransferDetailID AND Otin.WorkPoint=tra.WorkPoint
                                            INNER JOIN ICSOtherOut out ON out.TransferDetailID=tra.TransferDetailID AND out.WorkPoint=tra.WorkPoint
                                            INNER JOIN ICSWareHouseLotInfoLog log ON out.OutCode=log.TransCode AND out.Sequence=log.TransSequence AND out.WorkPoint=log.WorkPoint
                                            INNER JOIN ICSWareHouseLotInfo a ON a.LotNo=log.LotNo AND a.WorkPoint=log.WorkPoint
                                            WHERE a.LotNo='{2}' AND a.WorkPoint='{3}' AND Otin.InCode = '" + JsonData.TransCode + @"')
                                    BEGIN
	                                    RAISERROR('" + language.GetNameByCode("WMSAPIInfo036") + @"',16,1);
                                        RETURN
                                    END
                                    " + sql + "AND Otin.InCode = '" + JsonData.TransCode + @"'
                                    GROUP BY inv.LotEnable,a.ID,con.ContainerCode,con.ContainerName,a.LotNo,a.InvCode,inv.InvName,inv.InvStd,inv.InvUnit,a.WarehouseCode,
                                    wh.WarehouseName,a.LocationCode,loc.LocationName,CASE WHEN (invBat.BatchEnable IS NULL AND ISNULL(inv.BatchEnable, '0')='1') OR ISNULL(invBat.BatchEnable, '0')='1' THEN ISNULL(ext.BatchCode, '') ELSE '' END,inv.AmountUnit,
                                    ext.ID,ext.ProjectCode,ext.Version,ext.Brand,ext.cFree1,ext.cFree2,ext.cFree3,ext.cFree4,ext.cFree5,ext.cFree6,ext.cFree7,ext.cFree8,ext.cFree9,ext.cFree10,a.MUSER,a.MTIME";

                                columns = @"SUM(log.Quantity) AS Quantity,
                                    SUM(log.Quantity*(lot.Amount/lot.Quantity)) AS Amount,
                                    a.WarehouseCode AS WHCode,
                                    wh.WarehouseName AS WHName,
                                    a.LocationCode,
                                    loc.LocationName,
                                    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,";

                                tableName = @"ICSOtherIn Otin
                                    INNER JOIN ICSTransfer tra ON Otin.TransferDetailID=tra.TransferDetailID AND Otin.WorkPoint=tra.WorkPoint
                                    INNER JOIN ICSOtherOut out ON out.TransferDetailID=tra.TransferDetailID AND out.WorkPoint=tra.WorkPoint
                                    INNER JOIN ICSWareHouseLotInfoLog log ON out.OutCode=log.TransCode AND out.Sequence=log.TransSequence AND out.WorkPoint=log.WorkPoint
                                    INNER JOIN ICSWareHouseLotInfo a ON a.LotNo=log.LotNo AND a.WorkPoint=log.WorkPoint
                                    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 ICSWarehouse wh ON a.WarehouseCode=wh.WarehouseCode AND a.WorkPoint=wh.WorkPoint
                                    INNER JOIN ICSLocation loc ON a.LocationCode=loc.LocationCode AND a.WorkPoint=loc.WorkPoint
                                    LEFT JOIN ICSInventoryBatchEnable invBat ON a.InvCode=invBat.InvCode AND a.WarehouseCode=invBat.WHCode AND a.WorkPoint=invBat.WorkPoint";
                            }
                            else
                            {
                                sql = @"WITH ICSBomALL AS
                                    (
	                                    SELECT
		                                    ContainerCode AS TContainerCode,
		                                    ContainerCode AS PContainerCode,
		                                    ContainerCode AS ContainerCode,
		                                    ID,
		                                    ContainerID,
		                                    0 AS [Level],
		                                    CAST(1 AS nvarchar(MAX)) AS SortSeq,
		                                    CAST('00001' AS nvarchar(MAX)) AS Sort
	                                    FROM ICSContainer
	                                    WHERE ContainerCode='{2}'
                                    UNION ALL
	                                    SELECT
		                                    b.TContainerCode,
		                                    b.ContainerCode AS PContainerCode,
		                                    a.ContainerCode,
		                                    a.ID,
		                                    a.ContainerID,
		                                    b.[Level]+1 AS [Level],
		                                    CAST(b.SortSeq AS nvarchar(MAX))+'.'+CAST(row_number() over (order by a.ContainerCode) AS nvarchar(MAX)) AS SortSeq,
		                                    CAST(b.Sort+'.'+REPLICATE('0',5-len(row_number() over (order by a.ContainerCode)))+CAST(row_number() over (order by a.ContainerCode) AS nvarchar(MAX)) AS nvarchar(MAX)) AS Sort
	                                    FROM
		                                    ICSContainer a
	                                    INNER JOIN ICSBomALL b ON a.ID=b.ContainerID
                                    )
                                    " + sql + "AND Otin.InCode = '" + JsonData.TransCode + @"'
                                    GROUP BY inv.LotEnable,a.ID,con.ContainerCode,con.ContainerName,a.LotNo,a.InvCode,inv.InvName,inv.InvStd,inv.InvUnit,a.WarehouseCode,
                                    wh.WarehouseName,a.LocationCode,loc.LocationName,CASE WHEN (invBat.BatchEnable IS NULL AND ISNULL(inv.BatchEnable, '0')='1') OR ISNULL(invBat.BatchEnable, '0')='1' THEN ISNULL(ext.BatchCode, '') ELSE '' END,inv.AmountUnit,
                                    ext.ID,ext.ProjectCode,ext.Version,ext.Brand,ext.cFree1,ext.cFree2,ext.cFree3,ext.cFree4,ext.cFree5,ext.cFree6,ext.cFree7,ext.cFree8,ext.cFree9,ext.cFree10,a.MUSER,a.MTIME";

                                columns = @"SUM(log.Quantity) AS Quantity,
                                    SUM(log.Quantity*(lot.Amount/lot.Quantity)) AS Amount,
                                    a.WarehouseCode AS WHCode,
                                    wh.WarehouseName AS WHName,
                                    a.LocationCode,
                                    loc.LocationName,
                                    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,";

                                tableName = @"ICSOtherIn Otin
                                    INNER JOIN ICSTransfer tra ON Otin.TransferDetailID=tra.TransferDetailID AND Otin.WorkPoint=tra.WorkPoint
                                    INNER JOIN ICSOtherOut out ON out.TransferDetailID=tra.TransferDetailID AND out.WorkPoint=tra.WorkPoint
                                    INNER JOIN ICSWareHouseLotInfoLog log ON out.OutCode=log.TransCode AND out.Sequence=log.TransSequence AND out.WorkPoint=log.WorkPoint
                                    INNER JOIN ICSWareHouseLotInfo a ON a.LotNo=log.LotNo AND a.WorkPoint=log.WorkPoint
                                    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 ICSWarehouse wh ON a.WarehouseCode=wh.WarehouseCode AND a.WorkPoint=wh.WorkPoint
                                    INNER JOIN ICSLocation loc ON a.LocationCode=loc.LocationCode AND a.WorkPoint=loc.WorkPoint
                                    LEFT JOIN ICSInventoryBatchEnable invBat ON a.InvCode=invBat.InvCode AND a.WarehouseCode=invBat.WHCode AND a.WorkPoint=invBat.WorkPoint";
                            }


                        }
                        //销售退货-原条码(可支持一个条码多次发货,汇总数量,目前加了限制:785-793行)
                        else if (TransType == TransTypeEnum.SalesReturnBack.GetDescription())
                        {
                            if (string.IsNullOrEmpty(JsonData.TransCode))
                            {
                                throw new Exception(language.GetNameByCode("WMSAPIInfo001"));//"单据号不能为空!"
                            }
                            if (ScanType == "LOTNO")
                            {
                                sql = @"IF NOT EXISTS(SELECT a.ID FROM ICSSDN sdn
                                            INNER JOIN ICSWareHouseLotInfoLog log ON sdn.SDNCode=log.TransCode AND sdn.Sequence=log.TransSequence AND sdn.WorkPoint=log.WorkPoint
                                            INNER JOIN ICSWareHouseLotInfo a ON a.LotNo=log.LotNo AND a.WorkPoint=log.WorkPoint
                                            WHERE a.LotNo='{2}' AND a.WorkPoint='{3}' AND sdn.Type='1')
                                    BEGIN
	                                    RAISERROR('" + language.GetNameByCode("WMSAPIInfo037") + @"',16,1);
                                        RETURN
                                    END
                                IF EXISTS(SELECT log.LotNo FROM ICSSDN sdn
                                            INNER JOIN ICSWareHouseLotInfoLog log ON sdn.SDNCode=log.TransCode AND sdn.Sequence=log.TransSequence AND sdn.WorkPoint=log.WorkPoint
                                            INNER JOIN ICSWareHouseLotInfo a ON a.LotNo=log.LotNo AND a.WorkPoint=log.WorkPoint
                                            WHERE a.LotNo='{2}' AND a.WorkPoint='{3}' AND sdn.Type='1' AND log.BusinessCode='19'
                                            GROUP BY log.LotNo HAVING COUNT(log.LotNo)>=2)
                                    BEGIN
	                                    RAISERROR('" + string.Format(language.GetNameByCode("WMSAPIInfo191"), "{2}") + @"',16,1);
                                        RETURN
                                    END
                                    " + sql + @"AND sdn.Type='1'
                                    GROUP BY inv.LotEnable,a.ID,con.ContainerCode,con.ContainerName,a.LotNo,a.InvCode,inv.InvName,inv.InvStd,inv.InvUnit,a.WarehouseCode,
                                    wh.WarehouseName,a.LocationCode,loc.LocationName,CASE WHEN (invBat.BatchEnable IS NULL AND ISNULL(inv.BatchEnable, '0')='1') OR ISNULL(invBat.BatchEnable, '0')='1' THEN ISNULL(ext.BatchCode, '') ELSE '' END,inv.AmountUnit,
                                    ext.ID,ext.ProjectCode,ext.Version,ext.Brand,ext.cFree1,ext.cFree2,ext.cFree3,ext.cFree4,ext.cFree5,ext.cFree6,ext.cFree7,ext.cFree8,ext.cFree9,ext.cFree10,a.MUSER,a.MTIME";

                                columns = @"SUM(log.Quantity) AS Quantity,
                                    SUM(log.Quantity*(lot.Amount/lot.Quantity)) AS Amount,
                                    a.WarehouseCode AS WHCode,
                                    wh.WarehouseName AS WHName,
                                    a.LocationCode,
                                    loc.LocationName,
                                    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,";

                                tableName = @"ICSSDN sdn
                                    INNER JOIN ICSWareHouseLotInfoLog log ON sdn.SDNCode=log.TransCode AND sdn.Sequence=log.TransSequence AND sdn.WorkPoint=log.WorkPoint
                                    INNER JOIN ICSWareHouseLotInfo a ON a.LotNo=log.LotNo AND a.WorkPoint=log.WorkPoint
                                    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 ICSWarehouse wh ON a.WarehouseCode=wh.WarehouseCode AND a.WorkPoint=wh.WorkPoint
                                    INNER JOIN ICSLocation loc ON a.LocationCode=loc.LocationCode AND a.WorkPoint=loc.WorkPoint
                                    LEFT JOIN ICSInventoryBatchEnable invBat ON a.InvCode=invBat.InvCode AND a.WarehouseCode=invBat.WHCode AND a.WorkPoint=invBat.WorkPoint";
                            }
                            else
                            {
                                sql = @"WITH ICSBomALL AS
                                    (
	                                    SELECT
		                                    ContainerCode AS TContainerCode,
		                                    ContainerCode AS PContainerCode,
		                                    ContainerCode AS ContainerCode,
		                                    ID,
		                                    ContainerID,
		                                    0 AS [Level],
		                                    CAST(1 AS nvarchar(MAX)) AS SortSeq,
		                                    CAST('00001' AS nvarchar(MAX)) AS Sort
	                                    FROM ICSContainer
	                                    WHERE ContainerCode='{2}'
                                    UNION ALL
	                                    SELECT
		                                    b.TContainerCode,
		                                    b.ContainerCode AS PContainerCode,
		                                    a.ContainerCode,
		                                    a.ID,
		                                    a.ContainerID,
		                                    b.[Level]+1 AS [Level],
		                                    CAST(b.SortSeq AS nvarchar(MAX))+'.'+CAST(row_number() over (order by a.ContainerCode) AS nvarchar(MAX)) AS SortSeq,
		                                    CAST(b.Sort+'.'+REPLICATE('0',5-len(row_number() over (order by a.ContainerCode)))+CAST(row_number() over (order by a.ContainerCode) AS nvarchar(MAX)) AS nvarchar(MAX)) AS Sort
	                                    FROM
		                                    ICSContainer a
	                                    INNER JOIN ICSBomALL b ON a.ID=b.ContainerID
                                    )
                                    " + sql + @"AND sdn.Type='1'
                                    GROUP BY inv.LotEnable,a.ID,con.ContainerCode,con.ContainerName,a.LotNo,a.InvCode,inv.InvName,inv.InvStd,inv.InvUnit,a.WarehouseCode,
                                    wh.WarehouseName,a.LocationCode,loc.LocationName,CASE WHEN (invBat.BatchEnable IS NULL AND ISNULL(inv.BatchEnable, '0')='1') OR ISNULL(invBat.BatchEnable, '0')='1' THEN ISNULL(ext.BatchCode, '') ELSE '' END,inv.AmountUnit,
                                    ext.ID,ext.ProjectCode,ext.Version,ext.Brand,ext.cFree1,ext.cFree2,ext.cFree3,ext.cFree4,ext.cFree5,ext.cFree6,ext.cFree7,ext.cFree8,ext.cFree9,ext.cFree10,a.MUSER,a.MTIME";

                                columns = @"SUM(log.Quantity) AS Quantity,
                                    SUM(log.Quantity*(lot.Amount/lot.Quantity)) AS Amount,
                                    a.WarehouseCode AS WHCode,
                                    wh.WarehouseName AS WHName,
                                    a.LocationCode,
                                    loc.LocationName,
                                    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,";

                                tableName = @"ICSSDN sdn
                                    INNER JOIN ICSWareHouseLotInfoLog log ON sdn.SDNCode=log.TransCode AND sdn.Sequence=log.TransSequence AND sdn.WorkPoint=log.WorkPoint
                                    INNER JOIN ICSWareHouseLotInfo a ON a.LotNo=log.LotNo AND a.WorkPoint=log.WorkPoint
                                    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 ICSWarehouse wh ON a.WarehouseCode=wh.WarehouseCode AND a.WorkPoint=wh.WorkPoint
                                    INNER JOIN ICSLocation loc ON a.LocationCode=loc.LocationCode AND a.WorkPoint=loc.WorkPoint
                                    LEFT JOIN ICSInventoryBatchEnable invBat ON a.InvCode=invBat.InvCode AND a.WarehouseCode=invBat.WHCode AND a.WorkPoint=invBat.WorkPoint";
                            }

                        }
                        //生产(委外)退料-原条码+新条码
                        //先校验日志里面是否有原条码(同一种类型的条码只能发一次料才能原条码退,不然更新源头单据数量有问题,根据LogID判断是否原条码退回),如果没有查询新条码
                        else if (TransType == TransTypeEnum.MOIssueDocNegative.GetDescription()
                            || TransType == TransTypeEnum.MOIssueDocNegativeApply.GetDescription()
                            || TransType == TransTypeEnum.MOIssueDocNegativeIssue.GetDescription()
                            || TransType == TransTypeEnum.ICSOutsourcingIssueDoNegative.GetDescription()
                            || TransType == TransTypeEnum.ICSOutsourcingIssueDoNegativeApply.GetDescription()
                            || TransType == TransTypeEnum.ICSOutsourcingIssueDoNegativeIssue.GetDescription())
                        {
                            string type = "13";
                            string msglanguage = "WMSAPIInfo185";
                            if (TransType == TransTypeEnum.MOIssueDocNegativeApply.GetDescription())
                            {
                                type = "14";
                                msglanguage = "WMSAPIInfo186";
                            }
                            else if (TransType == TransTypeEnum.MOIssueDocNegativeIssue.GetDescription())
                            {
                                type = "15";
                                msglanguage = "WMSAPIInfo187";
                            }
                            else if (TransType == TransTypeEnum.ICSOutsourcingIssueDoNegative.GetDescription())
                            {
                                type = "5";
                                msglanguage = "WMSAPIInfo188";
                            }
                            else if (TransType == TransTypeEnum.ICSOutsourcingIssueDoNegativeApply.GetDescription())
                            {
                                type = "6";
                                msglanguage = "WMSAPIInfo189";
                            }
                            else if (TransType == TransTypeEnum.ICSOutsourcingIssueDoNegativeIssue.GetDescription())
                            {
                                type = "7";
                                msglanguage = "WMSAPIInfo190";
                            }
                            #region 新条码
                            if (ScanType == "LOTNO")
                            {
                                sqlNew = @"IF NOT EXISTS(SELECT a.ID FROM ICSInventoryLot a WHERE a.LotNo='{2}' AND a.WorkPoint='{3}')
                                    BEGIN
	                                    RAISERROR('" + string.Format(language.GetNameByCode("WMSAPIInfo038"), "{2}") + @"',16,1);
                                        RETURN
                                    END
                                IF EXISTS(SELECT a.ID FROM ICSWareHouseLotInfo a WHERE a.LotNo='{2}' AND a.WorkPoint='{3}')
                                    BEGIN
	                                    RAISERROR('" + language.GetNameByCode("WMSAPIInfo039") + @"',16,1);
                                        RETURN
                                    END
                                IF EXISTS(SELECT a.ID FROM ICSInventoryLot a 
                                        INNER JOIN ICSInventory b ON a.InvCode=b.InvCode AND a.WorkPoint=b.WorkPoint
                                        LEFT JOIN ICSInspection ins ON a.LotNo=ins.LotNo AND a.WorkPoint=ins.WorkPoint
                                        WHERE a.LotNo='{2}' AND a.WorkPoint='{3}' AND (b.InvIQC='1'AND ins.LotNo IS NULL))
                                    BEGIN
	                                    RAISERROR('" + language.GetNameByCode("WMSAPIInfo040") + @"',16,1);
                                        RETURN
                                    END
                                    " + sql;

                                if (TransType == TransTypeEnum.MOIssueDocNegative.GetDescription()
                            || TransType == TransTypeEnum.MOIssueDocNegativeApply.GetDescription()
                            || TransType == TransTypeEnum.MOIssueDocNegativeIssue.GetDescription())
                                {
                                    columns = @"ISNULL(ins.QualifiedQuantity+ins.WaiveQuantity, a.Quantity) AS Quantity,
                                    a.Quantity*(a.Amount/a.Quantity) AS Amount,
                                    (select negg.WHCode from ICSMOApplyNegDetail neg 
                                    INNER JOIN ICSMOApplyNeg negg ON neg.ApplyNegCode=negg.ApplyNegCode
									inner join ICSInventoryLotDetail lotdetail on neg.ApplyNegCode=lotdetail.TransCode
									and neg.Sequence=lotdetail.TransSequence 
									where lotdetail.LotNo=a.LotNo and lotdetail.WorkPoint=a.WorkPoint) AS WHCode,
                                    '' AS WHName,
                                    '' AS LocationCode,
                                    '' AS LocationName,
                                    '' AS LogID,
                                    ext.BatchCode AS BatchCode,";
                                }

                                if (TransType == TransTypeEnum.ICSOutsourcingIssueDoNegative.GetDescription()
                            || TransType == TransTypeEnum.ICSOutsourcingIssueDoNegativeApply.GetDescription()
                            || TransType == TransTypeEnum.ICSOutsourcingIssueDoNegativeIssue.GetDescription())
                                {
                                    columns = @"ISNULL(ins.QualifiedQuantity+ins.WaiveQuantity, a.Quantity) AS Quantity,
                                    a.Quantity*(a.Amount/a.Quantity) AS Amount,
                                    (select negg.WHCode from ICSOApplyNegDetail neg 
                                    INNER JOIN ICSOApplyNeg negg ON neg.OApplyNegCode=negg.OApplyNegCode
									inner join ICSInventoryLotDetail lotdetail on neg.OApplyNegCode=lotdetail.TransCode
									and neg.Sequence=lotdetail.TransSequence 
									where lotdetail.LotNo=a.LotNo and lotdetail.WorkPoint=a.WorkPoint) AS WHCode,
                                    '' AS WHName,
                                    '' AS LocationCode,
                                    '' AS LocationName,
                                    '' AS LogID,
                                    ext.BatchCode AS BatchCode,";
                                }


                                tableName = @"ICSInventoryLot a
                                    INNER JOIN ICSExtension ext ON a.ExtensionID=ext.ID AND a.WorkPoint=ext.WorkPoint
                                    LEFT JOIN ICSInspection ins ON a.LotNo=ins.LotNo AND a.WorkPoint=ins.WorkPoint";
                            }
                            else
                            {
                                sqlNew = @"WITH ICSBomALL AS
                                    (
	                                    SELECT
		                                    ContainerCode AS TContainerCode,
		                                    ContainerCode AS PContainerCode,
		                                    ContainerCode AS ContainerCode,
		                                    ID,
		                                    ContainerID,
		                                    0 AS [Level],
		                                    CAST(1 AS nvarchar(MAX)) AS SortSeq,
		                                    CAST('00001' AS nvarchar(MAX)) AS Sort
	                                    FROM ICSContainer
	                                    WHERE ContainerCode='{2}'
                                    UNION ALL
	                                    SELECT
		                                    b.TContainerCode,
		                                    b.ContainerCode AS PContainerCode,
		                                    a.ContainerCode,
		                                    a.ID,
		                                    a.ContainerID,
		                                    b.[Level]+1 AS [Level],
		                                    CAST(b.SortSeq AS nvarchar(MAX))+'.'+CAST(row_number() over (order by a.ContainerCode) AS nvarchar(MAX)) AS SortSeq,
		                                    CAST(b.Sort+'.'+REPLICATE('0',5-len(row_number() over (order by a.ContainerCode)))+CAST(row_number() over (order by a.ContainerCode) AS nvarchar(MAX)) AS nvarchar(MAX)) AS Sort
	                                    FROM
		                                    ICSContainer a
	                                    INNER JOIN ICSBomALL b ON a.ID=b.ContainerID
                                    )
                                    " + sql;

                                columns = @"ISNULL(ins.QualifiedQuantity+ins.WaiveQuantity, a.Quantity) AS Quantity,
                                    a.Quantity*(a.Amount/a.Quantity) AS Amount,
                                    '' AS WHCode,
                                    '' AS WHName,
                                    '' AS LocationCode,
                                    '' AS LocationName,
                                    ext.BatchCode AS BatchCode,";

                                tableName = @"ICSInventoryLot a
                                    INNER JOIN ICSExtension ext ON a.ExtensionID=ext.ID AND a.WorkPoint=ext.WorkPoint
                                    LEFT JOIN ICSInspection ins ON a.LotNo=ins.LotNo AND a.WorkPoint=ins.WorkPoint";
                            }

                            sqlNew = string.Format(sqlNew, columns, tableName, JsonData.Code, JsonData.WorkPoint, zlqty);
                            #endregion
                            #region 原条码
                            if (ScanType == "LOTNO")
                            {
                                sql = sql + @" AND log.BusinessCode IN('" + type + @"') GROUP BY inv.AmountEnable,inv.LotEnable,log.ID,a.ID,con.ContainerCode,con.ContainerName,a.LotNo,a.InvCode,inv.InvName,inv.InvStd,inv.InvUnit,a.WarehouseCode,
                                wh.WarehouseName,a.LocationCode,loc.LocationName,CASE WHEN(invBat.BatchEnable IS NULL AND ISNULL(inv.BatchEnable, '0')= '1') OR ISNULL(invBat.BatchEnable, '0')= '1' THEN ISNULL(ext.BatchCode, '') ELSE '' END,inv.AmountUnit,
                                ext.ID,ext.ProjectCode,ext.Version,ext.Brand,ext.cFree1,ext.cFree2,ext.cFree3,ext.cFree4,ext.cFree5,ext.cFree6,ext.cFree7,ext.cFree8,ext.cFree9,ext.cFree10,a.MUSER,a.MTIME
                                ";
                                sql = @"IF EXISTS(" + sql + @")
                                BEGIN
                                " + sql + @"
                                END
                                ELSE
                                BEGIN
                                " + sqlNew + @"
                                END";
                                //sql = @"IF EXISTS(SELECT log.LotNo FROM ICSWareHouseLotInfoLog log
                                //        INNER JOIN ICSWareHouseLotInfo a ON a.LotNo=log.LotNo AND a.WorkPoint=log.WorkPoint
                                //        WHERE a.LotNo='{2}' AND a.WorkPoint='{3}' AND log.TransCode='{5}' AND log.TransSequence='{6}' AND log.BusinessCode='" + type + @"'
                                //        GROUP BY log.LotNo HAVING COUNT(log.LotNo)>=2)
                                //BEGIN
	                               // RAISERROR('" + string.Format(language.GetNameByCode(msglanguage), "{2}") + @"',16,1);
                                //    RETURN
                                //END
                                //" + sql;

                                columns = @"SUM(log.Quantity) AS Quantity,
                                    SUM(log.Quantity*(lot.Amount/lot.Quantity)) AS Amount,
                                    a.WarehouseCode AS WHCode,
                                    wh.WarehouseName AS WHName,
                                    a.LocationCode,
                                    loc.LocationName,
                                    log.ID AS LogID,
                                    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,";

                                tableName = @"ICSWareHouseLotInfoLog log
                                    INNER JOIN ICSWareHouseLotInfo a ON a.LotNo=log.LotNo AND a.WorkPoint=log.WorkPoint
                                    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 ICSWarehouse wh ON a.WarehouseCode=wh.WarehouseCode AND a.WorkPoint=wh.WorkPoint
                                    INNER JOIN ICSLocation loc ON a.LocationCode=loc.LocationCode AND a.WorkPoint=loc.WorkPoint
                                    LEFT JOIN ICSInventoryBatchEnable invBat ON a.InvCode=invBat.InvCode AND a.WarehouseCode=invBat.WHCode AND a.WorkPoint=invBat.WorkPoint";
                            }
                            else
                            {
                                sql = sql + @" AND log.BusinessCode IN('" + type + @"') GROUP BY inv.AmountEnable,inv.LotEnable,log.ID,a.ID,con.ContainerCode,con.ContainerName,a.LotNo,a.InvCode,inv.InvName,inv.InvStd,inv.InvUnit,a.WarehouseCode,
                                wh.WarehouseName,a.LocationCode,loc.LocationName,CASE WHEN(invBat.BatchEnable IS NULL AND ISNULL(inv.BatchEnable, '0')= '1') OR ISNULL(invBat.BatchEnable, '0')= '1' THEN ISNULL(ext.BatchCode, '') ELSE '' END,inv.AmountUnit,
                                ext.ID,ext.ProjectCode,ext.Version,ext.Brand,ext.cFree1,ext.cFree2,ext.cFree3,ext.cFree4,ext.cFree5,ext.cFree6,ext.cFree7,ext.cFree8,ext.cFree9,ext.cFree10,a.MUSER,a.MTIME
                                ";
                                sql = @"IF EXISTS(" + sql + @")
                                BEGIN
                                " + sql + @"
                                END
                                ELSE
                                BEGIN
                                " + sqlNew + @"
                                END";
                                sql = @"WITH ICSBomALL AS
                                    (
	                                    SELECT
		                                    ContainerCode AS TContainerCode,
		                                    ContainerCode AS PContainerCode,
		                                    ContainerCode AS ContainerCode,
		                                    ID,
		                                    ContainerID,
		                                    0 AS [Level],
		                                    CAST(1 AS nvarchar(MAX)) AS SortSeq,
		                                    CAST('00001' AS nvarchar(MAX)) AS Sort
	                                    FROM ICSContainer
	                                    WHERE ContainerCode='{2}'
                                    UNION ALL
	                                    SELECT
		                                    b.TContainerCode,
		                                    b.ContainerCode AS PContainerCode,
		                                    a.ContainerCode,
		                                    a.ID,
		                                    a.ContainerID,
		                                    b.[Level]+1 AS [Level],
		                                    CAST(b.SortSeq AS nvarchar(MAX))+'.'+CAST(row_number() over (order by a.ContainerCode) AS nvarchar(MAX)) AS SortSeq,
		                                    CAST(b.Sort+'.'+REPLICATE('0',5-len(row_number() over (order by a.ContainerCode)))+CAST(row_number() over (order by a.ContainerCode) AS nvarchar(MAX)) AS nvarchar(MAX)) AS Sort
	                                    FROM
		                                    ICSContainer a
	                                    INNER JOIN ICSBomALL b ON a.ID=b.ContainerID
                                    )
                                " + sql;

                                columns = @"SUM(log.Quantity) AS Quantity,
                                    SUM(log.Quantity*(lot.Amount/lot.Quantity)) AS Amount,
                                    a.WarehouseCode AS WHCode,
                                    wh.WarehouseName AS WHName,
                                    a.LocationCode,
                                    loc.LocationName,
                                    log.ID AS LogID,
                                    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,";

                                tableName = @"ICSWareHouseLotInfoLog log
                                    INNER JOIN ICSWareHouseLotInfo a ON a.LotNo=log.LotNo AND a.WorkPoint=log.WorkPoint
                                    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 ICSWarehouse wh ON a.WarehouseCode=wh.WarehouseCode AND a.WorkPoint=wh.WorkPoint
                                    INNER JOIN ICSLocation loc ON a.LocationCode=loc.LocationCode AND a.WorkPoint=loc.WorkPoint
                                    LEFT JOIN ICSInventoryBatchEnable invBat ON a.InvCode=invBat.InvCode AND a.WarehouseCode=invBat.WHCode AND a.WorkPoint=invBat.WorkPoint";
                            }

                            #endregion
                        }
                        //分批
                        else if (TransType == TransTypeEnum.LOTSplit.GetDescription() || TransType == TransTypeEnum.LOTMerge.GetDescription())
                        {
                            sql = @"IF NOT EXISTS(SELECT a.ID FROM ICSWareHouseLotInfo a WHERE a.LotNo='{2}' AND a.WorkPoint='{3}' AND a.Quantity>0)
                                    BEGIN
	                                    RAISERROR('" + string.Format(language.GetNameByCode("WMSAPIInfo038"), "{2}") + @"',16,1);
                                        RETURN
                                    END
                                    " + sql;

                            columns = @"a.Quantity,
                                    a.Quantity*(lot.Amount/lot.Quantity) AS Amount,
                                    a.WarehouseCode AS WHCode,
                                    wh.WarehouseName AS WHName,
                                    a.LocationCode,
                                    loc.LocationName,
                                    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(split.SplitLotNo, a.LotNo+'-1') AS SplitLotNo,";

                            tableName = @"ICSWareHouseLotInfo 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 ICSWarehouse wh ON a.WarehouseCode=wh.WarehouseCode AND a.WorkPoint=wh.WorkPoint
                                    INNER JOIN ICSLocation loc ON a.LocationCode=loc.LocationCode AND a.WorkPoint=loc.WorkPoint
                                    LEFT JOIN (SELECT EATTRIBUTE1 AS LotNo,WorkPoint,EATTRIBUTE1+'-'+CAST((MAX(CAST(reverse(substring(reverse(LotNo),1,charindex('-',reverse(LotNo)) - 1)) AS INT))+1) AS VARCHAR) AS SplitLotNo FROM ICSInventoryLot GROUP BY EATTRIBUTE1,WorkPoint) split ON a.LotNo=split.LotNo AND a.WorkPoint=split.WorkPoint
                                    LEFT JOIN ICSInventoryBatchEnable invBat ON a.InvCode=invBat.InvCode AND a.WarehouseCode=invBat.WHCode AND a.WorkPoint=invBat.WorkPoint";
                        }
                        //出库条码
                        else if (isOut)
                        {
                            if (TransType == TransTypeEnum.MOIssueDoc.GetDescription() || TransType == TransTypeEnum.MOApply.GetDescription()
                                   || TransType == TransTypeEnum.MOIssue.GetDescription() || TransType == TransTypeEnum.OutsourcingIssueDoc.GetDescription()
                                   || TransType == TransTypeEnum.OOApply.GetDescription() || TransType == TransTypeEnum.OOIssue.GetDescription()
                                   || TransType == TransTypeEnum.SalesShipmentDoc.GetDescription() || TransType == TransTypeEnum.OtherOutDoc.GetDescription()
                                   || TransType == TransTypeEnum.BrrowDoc.GetDescription() || TransType == TransTypeEnum.StepTransferDocIn.GetDescription()
                                   || TransType == TransTypeEnum.TwoStepTransferDocOut.GetDescription() || TransType == TransTypeEnum.MOReplenishment.GetDescription())
                            {

                                if (TransType == TransTypeEnum.MOIssueDoc.GetDescription()&& JsonData.User!="admin")
                                {
                                    string uersql = @"SELECT F_RealName from  Sys_SRM_User  Where F_Account='{0}' AND F_Location='{1}'
                         ";
                                    uersql = string.Format(uersql, JsonData.User, JsonData.WorkPoint);
                                    DataTable dt = DBHelper.SQlReturnData(uersql, cmd);
                                    if (dt.Rows.Count >= 0)
                                    {
                                        UserName = dt.Rows[0]["F_RealName"].ToString();
                                    }
                                    UName = UserName.Substring(0, 2);

                                    string waresql = @"select WarehouseCode,WarehouseName from ICSWarehouse
                                where SUBSTRING(WarehouseName,1,2)='{0}' and WorkPoint='{1}'";
                                    waresql = string.Format(waresql, UName, JsonData.WorkPoint);
                                    DataTable dta = DBHelper.SQlReturnData(waresql, cmd);
                                    if (dta.Rows.Count >= 0)
                                    {
                                        UName = dta.Rows[0]["WarehouseCode"].ToString();
                                    }
                                }
                                    
                                //switch (UName)
                                //{
                                //    case "L1":
                                //        UName = "021";
                                //        break;
                                //    case "L2":
                                //        UName = "022";
                                //        break;
                                //    case "L3":
                                //        UName = "023";
                                //        break;
                                //    case "L4":
                                //        UName = "024";
                                //        break;
                                //    case "L5":
                                //        UName = "025";
                                //        break;
                                //    case "L6":
                                //        UName = "026";
                                //        break;
                                //    case "L7":
                                //        UName = "025";
                                //        break;
                                //    case "C1":
                                //        UName = "015";
                                //        break;
                                //}

                                ZLtable = ICSControlModeService.GetZL();
                                if (ZLtable == null)
                                {
                                    throw new Exception(language.GetNameByCode("WMSAPIInfo471"));
                                }

                                for (int i = 0; i < ZLtable.Rows.Count; i++)
                                {

                                    string zlName = ZLtable.Rows[i]["Name"].ToString();
                                    string zlTransCode = ZLtable.Rows[i]["BusinessCode"].ToString();
                                    string Enable = ZLtable.Rows[i]["Enable"].ToString();
                                    if (JsonData.TransType.Equals(zlName))
                                    {
                                        if (Enable.Equals("True"))
                                        {
                                            string zlsql = @"IF NOT EXISTS(select a.Quantity,c.Name from ICSWareHouseLotInfoLog a 
                                            left join ICSInventoryLot b on a.LotNo=b.LotNo and a.WorkPoint=b.WorkPoint and a.InvCode=b.InvCode
                                            left join ICSType c on a.BusinessCode=c.Code and c.tablecode='ICSWareHouseLotInfoLog' and c.ColumnCode='BusinessCode'
                                            where b.LotNo='{0}' and b.WorkPoint='{1}' and a.TransType='15' and c.name='{2}' and a.TransCode='{3}')
                                            BEGIN
	                                            RAISERROR('" + language.GetNameByCode("WMSAPIInfo469") + @"',16,1);
                                                RETURN
                                            END
                                            select a.Quantity,c.Name from ICSWareHouseLotInfoLog a 
                                            left join ICSInventoryLot b on a.LotNo=b.LotNo and a.WorkPoint=b.WorkPoint and a.InvCode=b.InvCode
                                            left join ICSType c on a.BusinessCode=c.Code and c.tablecode='ICSWareHouseLotInfoLog' and c.ColumnCode='BusinessCode'
                                            where b.LotNo='{0}' and b.WorkPoint='{1}' and a.TransType='15' and c.name='{2}' and a.TransCode='{3}'";
                                            zlsql = string.Format(zlsql, JsonData.Code, JsonData.WorkPoint, JsonData.TransType, JsonData.TransCode);
                                            DataTable zlltable = DBHelper.SQlReturnData(zlsql, cmd);
                                            if (zlltable != null || zlltable.Rows.Count > 0)
                                            {

                                                zlqty = zlltable.Rows[0]["Quantity"].ToString();
                                                iszl = true;
                                            }
                                        }
                                    }
                                }
                            }


                            if (ScanType == "LOTNO")
                            {
                                if (TransType == TransTypeEnum.MOIssueDoc.GetDescription() )
                                {
                                    sql = @"IF NOT EXISTS(SELECT a.ID FROM ICSWareHouseLotInfo a WHERE a.LotNo='{2}' AND a.WorkPoint='{3}' AND a.Quantity>0)
                                    BEGIN
	                                    RAISERROR('" + string.Format(language.GetNameByCode("WMSAPIInfo038"), "{2}") + @"',16,1);
                                        RETURN
                                    END
                                    IF NOT EXISTS(SELECT a.ID FROM ICSWareHouseLotInfo a WHERE a.LotNo='{2}' AND a.WorkPoint='{3}' AND a.Quantity>0 AND a.WareHouseCode='{5}')
                                    BEGIN
	                                    RAISERROR('登录人员产线与目标仓库不一致,请确认!',16,1)
                                        RETURN
                                    END
                                    " + sql;
                                }

                                if (TransType == TransTypeEnum.Check.GetDescription())
                                {
                                    sql = @"IF EXISTS(SELECT LotNo FROM ICSCheckDetail a
                                            LEFT JOIN ICSCheck b ON a.CheckID=b.ID AND  a.WorkPoint=b.WorkPoint
                                            WHERE b.CheckCode='{6}' AND a.LotNo='{2}' AND a.WorkPoint='{3}')
                                    BEGIN
                                        IF ('{8}'='初盘')
                                        BEGIN
                                            IF EXISTS(SELECT LotNo FROM ICSCheckDetail a
                                            LEFT JOIN ICSCheck b ON a.CheckID=b.ID AND  a.WorkPoint=b.WorkPoint
                                            WHERE b.CheckCode='{6}' AND a.LotNo='{2}' AND a.WorkPoint='{3}' AND a.PrimaryQuantity>0)
                                            BEGIN
                                                RAISERROR('当前条码已初盘,请确认!', 16, 1);
		                                                        RETURN;
                                            END
                                        END
                                        ELSE IF ('{8}'='抽盘')
                                        BEGIN
                                            IF EXISTS(SELECT LotNo FROM ICSCheckDetail a
                                            LEFT JOIN ICSCheck b ON a.CheckID=b.ID AND  a.WorkPoint=b.WorkPoint
                                            WHERE b.CheckCode='{6}' AND a.LotNo='{2}' AND a.WorkPoint='{3}' AND a.CheckQuantity>0)
                                            BEGIN
                                                RAISERROR('当前条码已抽盘,请确认!', 16, 1);
		                                                        RETURN;
                                            END
                                        END
                                        ELSE
                                        BEGIN
                                            IF EXISTS(SELECT LotNo FROM ICSCheckDetail a
                                            LEFT JOIN ICSCheck b ON a.CheckID=b.ID AND  a.WorkPoint=b.WorkPoint
                                            WHERE b.CheckCode='{6}' AND a.LotNo='{2}' AND a.WorkPoint='{3}' AND a.ReplayQuantity>0)
                                            BEGIN
                                                RAISERROR('当前条码已复盘,请确认!', 16, 1);
		                                                        RETURN;
                                            END
                                        END
                                    END
                                    " + sql;
                                }


                                if (iszl)
                                {
                                    columns = @"{0} as Quantity,
                                    {0}*(lot.Amount/lot.Quantity) AS Amount,
                                    a.id AS LogID,
                                    a.FromWarehouseCode AS WHCode,
                                    wh.WarehouseName AS WHName,
                                    inv.LotEnable,     
                                    a.FromLocationCode,   
                                    lot.ProductDate,
                                    loc.LocationName,     
                                    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,";
                                    columns = string.Format(columns, zlqty);

                                    tableName = @"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 ICSWarehouse wh ON a.FromWarehouseCode=wh.WarehouseCode AND a.WorkPoint=wh.WorkPoint
                                    INNER JOIN ICSLocation loc ON a.FromLocationCode=loc.LocationCode AND a.WorkPoint=loc.WorkPoint
                                    LEFT JOIN ICSInventoryBatchEnable invBat ON a.InvCode=invBat.InvCode AND a.FromWarehouseCode=invBat.WHCode AND a.WorkPoint=invBat.WorkPoint";
                                }
                                else
                                {
                                    if (TransType == TransTypeEnum.Check.GetDescription())
                                    {
                                        columns = @"case when inv.AmountEnable='1' then (a.Quantity-a.lockQuantity)*(lot.Amount/lot.Quantity) else (a.Quantity-a.lockQuantity) end AS Quantity,
                                        (a.Quantity-a.lockQuantity)*(lot.Amount/lot.Quantity) AS Amount,
                                        '' AS LogID,
                                        a.WarehouseCode AS WHCode,
                                        wh.WarehouseName AS WHName,
                                        inv.LotEnable,     
                                        a.LocationCode,    
                                        loc.LocationName,     
                                        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,";

                                        tableName = @"ICSWareHouseLotInfo 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 ICSWarehouse wh ON a.WarehouseCode=wh.WarehouseCode AND a.WorkPoint=wh.WorkPoint
                                        INNER JOIN ICSLocation loc ON a.LocationCode=loc.LocationCode AND a.WorkPoint=loc.WorkPoint
                                        LEFT JOIN ICSInventoryBatchEnable invBat ON a.InvCode=invBat.InvCode AND a.WarehouseCode=invBat.WHCode AND a.WorkPoint=invBat.WorkPoint";
                                    }
                                    else
                                    {
                                        columns = @"(a.Quantity-a.lockQuantity) AS Quantity,
                                        (a.Quantity-a.lockQuantity)*(lot.Amount/lot.Quantity) AS Amount,
                                        '' AS LogID,
                                        a.WarehouseCode AS WHCode,
                                        wh.WarehouseName AS WHName,
                                        inv.LotEnable,     
                                        a.LocationCode,    
                                        loc.LocationName,     
                                        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,";

                                        tableName = @"ICSWareHouseLotInfo 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 ICSWarehouse wh ON a.WarehouseCode=wh.WarehouseCode AND a.WorkPoint=wh.WorkPoint
                                        INNER JOIN ICSLocation loc ON a.LocationCode=loc.LocationCode AND a.WorkPoint=loc.WorkPoint
                                        LEFT JOIN ICSInventoryBatchEnable invBat ON a.InvCode=invBat.InvCode AND a.WarehouseCode=invBat.WHCode AND a.WorkPoint=invBat.WorkPoint";
                                    }
                                }



                            }
                            else
                            {
                                sql = @"
                                    WITH ICSBomALL AS
                                    (
	                                    SELECT
		                                    ContainerCode AS TContainerCode,
		                                    ContainerCode AS PContainerCode,
		                                    ContainerCode AS ContainerCode,
		                                    ID,
		                                    ContainerID,
		                                    0 AS [Level],
		                                    CAST(1 AS nvarchar(MAX)) AS SortSeq,
		                                    CAST('00001' AS nvarchar(MAX)) AS Sort
	                                    FROM ICSContainer
	                                    WHERE ContainerCode='{2}'
                                    UNION ALL
	                                    SELECT
		                                    b.TContainerCode,
		                                    b.ContainerCode AS PContainerCode,
		                                    a.ContainerCode,
		                                    a.ID,
		                                    a.ContainerID,
		                                    b.[Level]+1 AS [Level],
		                                    CAST(b.SortSeq AS nvarchar(MAX))+'.'+CAST(row_number() over (order by a.ContainerCode) AS nvarchar(MAX)) AS SortSeq,
		                                    CAST(b.Sort+'.'+REPLICATE('0',5-len(row_number() over (order by a.ContainerCode)))+CAST(row_number() over (order by a.ContainerCode) AS nvarchar(MAX)) AS nvarchar(MAX)) AS Sort
	                                    FROM
		                                    ICSContainer a
	                                    INNER JOIN ICSBomALL b ON a.ID=b.ContainerID
                                    )
                                    " + sql;

                                columns = @"(a.Quantity-a.lockQuantity) AS Quantity,
                                    (a.Quantity-a.lockQuantity)*(lot.Amount/lot.Quantity) AS Amount,
                                    a.WarehouseCode AS WHCode,
                                    wh.WarehouseName AS WHName,
                                    a.LocationCode,
                                    lot.ProductDate,
                                    loc.LocationName,
                                    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,";

                                tableName = @"ICSWareHouseLotInfo 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 ICSWarehouse wh ON a.WarehouseCode=wh.WarehouseCode AND a.WorkPoint=wh.WorkPoint
                                    INNER JOIN ICSLocation loc ON a.LocationCode=loc.LocationCode AND a.WorkPoint=loc.WorkPoint
                                    LEFT JOIN ICSInventoryBatchEnable invBat ON a.InvCode=invBat.InvCode AND a.WarehouseCode=invBat.WHCode AND a.WorkPoint=invBat.WorkPoint
                                    ";
                            }


                        }
                        //入库条码
                        else
                        {

                            if (ScanType == "LOTNO")
                            {

                                if (TransType == TransTypeEnum.PurchaseReceiveDoc.GetDescription() || TransType == TransTypeEnum.DeliveryNotice.GetDescription()
                                    || TransType == TransTypeEnum.OutsourcingReceiveDoc.GetDescription() || TransType == TransTypeEnum.ODeliveryNotice.GetDescription()
                                    || TransType == TransTypeEnum.ManufactureReceiveDoc.GetDescription() || TransType == TransTypeEnum.ManufactureReceive.GetDescription()
                                    || TransType == TransTypeEnum.UnqualifiedIN.GetDescription() || TransType == TransTypeEnum.MOStockINByProduct.GetDescription()
                                    || TransType == TransTypeEnum.OOStockINByProduct.GetDescription())
                                {
                                    //联产品入库(有来源单据)不可扫入无来源条码
                                    if (TransType == TransTypeEnum.MOStockINByProduct.GetDescription())
                                    {
                                        sql = @"
                                                IF EXISTS(SELECT a.ID FROM ICSInventoryLot a WHERE a.LotNo = '{2}' AND a.WorkPoint = '{3}' AND a.Type = 19 )
		                                                BEGIN
				                                                RAISERROR('当前扫描的是无来源条码', 16, 1);
		                                                        RETURN;
		                                                END
                                                " + sql;
                                    }
                                    sql = @" 
                                IF NOT EXISTS(SELECT a.ID FROM ICSInventoryLot a WHERE a.LotNo = '{2}' AND a.WorkPoint = '{3}')
                                            BEGIN

                                                RAISERROR('" + string.Format(language.GetNameByCode("WMSAPIInfo038"), "{2}") + @"', 16, 1);
                                RETURN
                                END
                                IF EXISTS(SELECT a.ID FROM ICSWareHouseLotInfo a WHERE a.LotNo='{2}' AND a.WorkPoint='{3}')
                                    BEGIN
	                                    RAISERROR('" + language.GetNameByCode("WMSAPIInfo039") + @"',16,1);
                                        RETURN
                                    END
                                IF EXISTS(SELECT a.ID FROM ICSInventoryLot a 
                                        INNER JOIN ICSInventory b ON a.InvCode=b.InvCode AND a.WorkPoint=b.WorkPoint
										LEFT JOIN ICSInspection ins ON a.LotNo=ins.LotNo AND a.WorkPoint=ins.WorkPoint
                                        WHERE a.LotNo='{2}' AND a.WorkPoint='{3}' AND   (b.InvIQC='1' AND ins.LotNo IS NULL))
                                    BEGIN
	                                    RAISERROR('" + language.GetNameByCode("WMSAPIInfo040") + @"',16,1);
                                        RETURN
                                    END
                                    " + sql;
                                }
                                else
                                {
                                    sql = @" 
                                IF NOT EXISTS(SELECT a.ID FROM ICSInventoryLot a WHERE a.LotNo = '{2}' AND a.WorkPoint = '{3}')
                                            BEGIN

                                                RAISERROR('" + string.Format(language.GetNameByCode("WMSAPIInfo038"), "{2}") + @"', 16, 1);
                                RETURN
                                END
                                IF EXISTS(SELECT a.ID FROM ICSWareHouseLotInfo a WHERE a.LotNo='{2}' AND a.WorkPoint='{3}')
                                    BEGIN
	                                    RAISERROR('" + language.GetNameByCode("WMSAPIInfo039") + @"',16,1);
                                        RETURN
                                    END
                                    " + sql;
                                }




                                ControlMode mode = ICSControlModeService.GetSuLocation();

                                //获取条码类型
                                LotTypesql = @"IF NOT EXISTS(SELECT Type FROM ICSInventoryLot WHERE LotNo='{0}' AND WorkPoint='{1}')
                                    BEGIN
	                                    RAISERROR('" + language.GetNameByCode("WMSAPIInfo461") + @"',16,1);
                                        RETURN
                                    END
                                        SELECT Type FROM ICSInventoryLot WHERE LotNo='{0}' AND WorkPoint='{1}'";
                                LotTypesql = string.Format(LotTypesql, JsonData.Code, JsonData.WorkPoint);
                                DataTable dt = DBHelper.SQlReturnData(LotTypesql, cmd);
                                if (dt != null && dt.Rows.Count > 0)
                                {
                                    LotType = dt.Rows[0]["Type"].ToString();
                                }

                                if (mode != null)
                                {
                                    if (mode.itemCode.Equals("LocationRemind01"))//固定库位:物料和库位绑定,显示库位名称列表
                                    {
                                        columnsLONAME = @"
                                                (SELECT locat.LocationName from ICSWareHouseLotInfo loinfo
                                                LEFT JOIN ICSLocation locat on locat.LocationCode=loinfo.LocationCode and loinfo.WorkPoint=locat.WorkPoint
                                                where loinfo.lotno=a.lotno and  loinfo.invcode=a.invcode and a.WorkPoint=loinfo.WorkPoint) AS LocationName,";

                                        columnsLOCODE = @"
                                                (SELECT locat.LocationCode from ICSWareHouseLotInfo loinfo
                                                LEFT JOIN ICSLocation locat on locat.LocationCode=loinfo.LocationCode and loinfo.WorkPoint=locat.WorkPoint
                                                where loinfo.lotno=a.lotno and loinfo.invcode=a.invcode and a.WorkPoint=loinfo.WorkPoint) AS LocationCode,";

                                    }
                                    else if (mode.itemCode.Equals("LocationRemind02"))//在库库位:物料有库存的对应库位,显示库位名称列表
                                    {
                                        columnsLONAME = @"
                                            STUFF(
											    (SELECT DISTINCT ',' + LocationName
												    from ICSLocation  wh
												    LEFT JOIN ICSWareHouseLotInfo lotinfo on wh.LocationCode=lotinfo.LocationCode and wh.WorkPoint=lotinfo.WorkPoint 
												    WHERE a.InvCode=lotinfo.InvCode AND a.WorkPoint=lotinfo.WorkPoint and lotinfo.Quantity>0
												    FOR xml path('')
											    ),1,1,''
											    ) AS LocationName,";

                                        columnsLOCODE = @"
                                            STUFF(
											    (SELECT DISTINCT ',' + LocationCode
												    from ICSLocation  wh
												    LEFT JOIN ICSWareHouseLotInfo lotinfo on wh.LocationCode=lotinfo.LocationCode and wh.WorkPoint=lotinfo.WorkPoint 
												    WHERE a.InvCode=lotinfo.InvCode AND a.WorkPoint=lotinfo.WorkPoint and lotinfo.Quantity>0
												    FOR xml path('')
											    ),1,1,''
											    ) AS LocationCode,";
                                    }
                                    else if (mode.itemCode.Equals("LocationRemind03"))//最近一次出入库的库位,显示库位名称
                                    {
                                        columnsLONAME = @"
                                                (SELECT Top 1 locat.LocationName from ICSWareHouseLotInfoLog log 
											LEFT JOIN ICSLocation locat on locat.LocationCode=log.ToLocationCode and log.WorkPoint=locat.WorkPoint where log.TransType='2' and a.InvCode=log.InvCode AND a.WorkPoint=log.WorkPoint
											ORDER BY log.Mtime desc) AS LocationName,";

                                        columnsLOCODE = @"
                                                (SELECT Top 1 locat.LocationCode from ICSWareHouseLotInfoLog log 
											LEFT JOIN ICSLocation locat on locat.LocationCode=log.ToLocationCode and log.WorkPoint=locat.WorkPoint where log.TransType='2' and a.InvCode=log.InvCode AND a.WorkPoint=log.WorkPoint
											ORDER BY log.Mtime desc) AS LocationCode,";
                                    }

                                }
                                else
                                {
                                    columnsLONAME = @"
                                        STUFF(
											(SELECT DISTINCT ',' + LocationName
												from ICSLocation  wh
												LEFT JOIN ICSWareHouseLotInfoLog lotinfo on wh.LocationCode=lotinfo.ToLocationCode and wh.WorkPoint=lotinfo.WorkPoint 
												WHERE a.InvCode=lotinfo.InvCode AND a.WorkPoint=lotinfo.WorkPoint and (lotinfo.TransType='2' OR lotinfo.TransType='3')
												FOR xml path('')
											),1,1,''
											) AS LocationName,";
                                    columnsLOCODE = @"
                                        STUFF(
											(SELECT DISTINCT ',' + LocationCode
												from ICSLocation  wh
												LEFT JOIN ICSWareHouseLotInfoLog lotinfo on wh.LocationCode=lotinfo.ToLocationCode and wh.WorkPoint=lotinfo.WorkPoint 
												WHERE a.InvCode=lotinfo.InvCode AND a.WorkPoint=lotinfo.WorkPoint and (lotinfo.TransType='2' OR lotinfo.TransType='3')
												FOR xml path('')
											),1,1,''
											) AS LocationCode,";

                                }

                                #region 根据条码类型找到单据仓库信息
                                if (LotType.Equals("1"))
                                {//生产退料
                                    columnsWHCODE = @"ISNULL((SELECT negg.WHCODE FROM ICSMOApplyNegDetail neg LEFT JOIN ICSMOApplyNeg negg ON neg.ApplyNegCode=negg.ApplyNegCode 
                                                        WHERE  lotdd.TransCode=neg.ApplyNegCode AND lotdd.TransSequence=neg.Sequence AND lotdd.WorkPoint=neg.WorkPoint and negg.Type='1'),'') AS WHCode";
                                    columnsWHNAME = @"ISNULL((SELECT WarehouseName from ICSWareHouse where WarehouseCode in (SELECT negg.WHCODE FROM ICSMOApplyNegDetail neg LEFT JOIN ICSMOApplyNeg negg ON neg.ApplyNegCode=negg.ApplyNegCode 
                                                        WHERE  lotdd.TransCode=neg.ApplyNegCode AND lotdd.TransSequence=neg.Sequence AND lotdd.WorkPoint=neg.WorkPoint and negg.Type='1') AND WorkPoint=a.WorkPoint),'') AS WHName";
                                }
                                else if (LotType.Equals("2"))
                                {//委外退料
                                    columnsWHCODE = @"ISNULL((SELECT negg.WHCODE FROM ICSOApplyNegDetail neg LEFT JOIN ICSOApplyNeg negg ON neg.OApplyNegCode=negg.OApplyNegCode 
                                                        WHERE  lotdd.TransCode=neg.OApplyNegCode AND lotdd.TransSequence=neg.Sequence AND lotdd.WorkPoint=neg.WorkPoint and negg.Type='1'),'') AS WHCode";
                                    columnsWHNAME = @"ISNULL((SELECT WarehouseName from ICSWareHouse where WarehouseCode in (SELECT negg.WHCODE FROM ICSOApplyNegDetail neg LEFT JOIN ICSOApplyNeg negg ON neg.OApplyNegCode=negg.OApplyNegCode 
                                                        WHERE  lotdd.TransCode=neg.OApplyNegCode AND lotdd.TransSequence=neg.Sequence AND lotdd.WorkPoint=neg.WorkPoint and negg.Type='1') AND WorkPoint=a.WorkPoint),'') AS WHName";
                                }
                                else if (LotType.Equals("3"))
                                {//工单
                                    columnsWHCODE = @"ISNULL((SELECT a.WHCode FROM ICSMO a WHERE a.MOCode=lotdd.TransCode AND a.Sequence=lotdd.TransSequence AND a.WorkPoint=lotdd.WorkPoint),'') AS WHCode";
                                    columnsWHNAME = @"ISNULL((SELECT WarehouseName from ICSWareHouse where WarehouseCode in (SELECT a.WHCode FROM ICSMO a WHERE a.MOCode=lotdd.TransCode AND a.Sequence=lotdd.TransSequence AND a.WorkPoint=lotdd.WorkPoint) AND WorkPoint=a.WorkPoint),'') AS WHName";
                                }
                                else if (LotType.Equals("4"))
                                {//销售退货
                                    columnsWHCODE = @"ISNULL((SELECT a.WHCode FROM ICSSDN a WHERE a.SDNCode=lotdd.TransCode AND a.Sequence=lotdd.TransSequence AND a.WorkPoint=lotdd.WorkPoint),'') AS WHCode";
                                    columnsWHNAME = @"ISNULL((SELECT WarehouseName from ICSWareHouse where WarehouseCode in (SELECT a.WHCode FROM ICSSDN a WHERE a.SDNCode=lotdd.TransCode AND a.Sequence=lotdd.TransSequence AND a.WorkPoint=lotdd.WorkPoint) AND WorkPoint=a.WorkPoint),'') AS WHName";
                                }
                                else if (LotType.Equals("5"))
                                {//其他入库
                                    columnsWHCODE = @"ISNULL((SELECT a.WHCode FROM ICSOtherIn a WHERE a.InCode=lotdd.TransCode AND a.Sequence=lotdd.TransSequence AND a.WorkPoint=lotdd.WorkPoint),'') AS WHCode";
                                    columnsWHNAME = @"ISNULL((SELECT WarehouseName from ICSWareHouse where WarehouseCode in (SELECT a.WHCode FROM ICSOtherIn a WHERE a.InCode=lotdd.TransCode AND a.Sequence=lotdd.TransSequence AND a.WorkPoint=lotdd.WorkPoint) AND WorkPoint=a.WorkPoint),'') AS WHName";
                                }
                                else if (LotType.Equals("6"))
                                {//归还单
                                    columnsWHCODE = @"ISNULL((SELECT a.WHCode FROM ICSReturn a WHERE a.ReturnCode=lotdd.TransCode AND a.Sequence=lotdd.TransSequence AND a.WorkPoint=lotdd.WorkPoint),'') AS WHCode";
                                    columnsWHNAME = @"ISNULL((SELECT WarehouseName from ICSWareHouse where WarehouseCode in (SELECT a.WHCode FROM ICSReturn a WHERE a.ReturnCode=lotdd.TransCode AND a.Sequence=lotdd.TransSequence AND a.WorkPoint=lotdd.WorkPoint) AND WorkPoint=a.WorkPoint),'') AS WHName";
                                }
                                else if (LotType.Equals("7"))
                                {//采购到货单
                                    columnsWHCODE = @"ISNULL((SELECT a.WHCode FROM ICSDeliveryNotice a WHERE a.DNCode=lotdd.TransCode AND a.Sequence=lotdd.TransSequence AND a.WorkPoint=lotdd.WorkPoint AND a.DNType='1'),'') AS WHCode";
                                    columnsWHNAME = @"ISNULL((SELECT WarehouseName from ICSWareHouse where WarehouseCode in (SELECT a.WHCode FROM ICSDeliveryNotice a WHERE a.DNCode=lotdd.TransCode AND a.Sequence=lotdd.TransSequence AND a.WorkPoint=lotdd.WorkPoint AND a.DNType='1') AND WorkPoint=a.WorkPoint),'') AS WHName";
                                }
                                else if (LotType.Equals("8"))
                                {//委外到货单
                                    columnsWHCODE = @"ISNULL((SELECT a.WHCode FROM ICSODeliveryNotice a WHERE a.ODNCode=lotdd.TransCode AND a.Sequence=lotdd.TransSequence AND a.WorkPoint=lotdd.WorkPoint and a.ODNType='1'),'') AS WHCode";
                                    columnsWHNAME = @"ISNULL((SELECT WarehouseName from ICSWareHouse where WarehouseCode in (SELECT a.WHCode FROM ICSODeliveryNotice a WHERE a.ODNCode=lotdd.TransCode AND a.Sequence=lotdd.TransSequence AND a.WorkPoint=lotdd.WorkPoint and a.ODNType='1') AND WorkPoint=a.WorkPoint),'') AS WHName";
                                }
                                else if (LotType.Equals("9"))
                                {//成品入库单
                                    columnsWHCODE = @"ISNULL((SELECT a.WHCode FROM ICSManufactureReceive a WHERE a.RCVCode=lotdd.TransCode AND a.Sequence=lotdd.TransSequence AND a.WorkPoint=lotdd.WorkPoint),'') AS WHCode";
                                    columnsWHNAME = @"ISNULL((SELECT WarehouseName from ICSWareHouse where WarehouseCode in (SELECT a.WHCode FROM ICSManufactureReceive a WHERE a.RCVCode=lotdd.TransCode AND a.Sequence=lotdd.TransSequence AND a.WorkPoint=lotdd.WorkPoint) AND WorkPoint=a.WorkPoint),'') AS WHName";
                                }
                                else if (LotType.Equals("10"))
                                {//拒收单
                                    columnsWHCODE = @"ISNULL((SELECT a.WHCode FROM ICSDeliveryNotice a WHERE a.DNCode=lotdd.TransCode AND a.Sequence=lotdd.TransSequence AND a.WorkPoint=lotdd.WorkPoint AND a.DNType='3'),'') AS WHCode";
                                    columnsWHNAME = @"ISNULL((SELECT WarehouseName from ICSWareHouse where WarehouseCode in (SELECT a.WHCode FROM ICSDeliveryNotice a WHERE a.DNCode=lotdd.TransCode AND a.Sequence=lotdd.TransSequence AND a.WorkPoint=lotdd.WorkPoint AND a.DNType='3') AND WorkPoint=a.WorkPoint),'') AS WHName";
                                }
                                else if (LotType.Equals("11"))
                                {//委外拒收单
                                    columnsWHCODE = @"ISNULL((SELECT a.WHCode FROM ICSODeliveryNotice a WHERE a.ODNCode=lotdd.TransCode AND a.Sequence=lotdd.TransSequence AND a.WorkPoint=lotdd.WorkPoint and a.ODNType='3'),'') AS WHCode";
                                    columnsWHNAME = @"ISNULL((SELECT WarehouseName from ICSWareHouse where WarehouseCode in (SELECT a.WHCode FROM ICSODeliveryNotice a WHERE a.ODNCode=lotdd.TransCode AND a.Sequence=lotdd.TransSequence AND a.WorkPoint=lotdd.WorkPoint and a.ODNType='3') AND WorkPoint=a.WorkPoint),'') AS WHName";
                                }
                                else if (LotType.Equals("12"))
                                {//领料申请退料
                                    columnsWHCODE = @"ISNULL((SELECT negg.WHCODE FROM ICSMOApplyNegDetail neg LEFT JOIN ICSMOApplyNeg negg ON neg.ApplyNegCode=negg.ApplyNegCode 
                                                        WHERE  lotdd.TransCode=neg.ApplyNegCode AND lotdd.TransSequence=neg.Sequence AND lotdd.WorkPoint=neg.WorkPoint and negg.Type='2'),'') AS WHCode";
                                    columnsWHNAME = @"ISNULL((SELECT WarehouseName from ICSWareHouse where WarehouseCode in (SELECT negg.WHCODE FROM ICSMOApplyNegDetail neg LEFT JOIN ICSMOApplyNeg negg ON neg.ApplyNegCode=negg.ApplyNegCode 
                                                        WHERE  lotdd.TransCode=neg.ApplyNegCode AND lotdd.TransSequence=neg.Sequence AND lotdd.WorkPoint=neg.WorkPoint and negg.Type='2') AND WorkPoint=a.WorkPoint),'') AS WHName";
                                }
                                else if (LotType.Equals("13"))
                                {//材料出库退料
                                    columnsWHCODE = @"ISNULL((SELECT negg.WHCODE FROM ICSMOApplyNegDetail neg LEFT JOIN ICSMOApplyNeg negg ON neg.ApplyNegCode=negg.ApplyNegCode 
                                                        WHERE  lotdd.TransCode=neg.ApplyNegCode AND lotdd.TransSequence=neg.Sequence AND lotdd.WorkPoint=neg.WorkPoint and negg.Type='3'),'') AS WHCode";
                                    columnsWHNAME = @"ISNULL((SELECT WarehouseName from ICSWareHouse where WarehouseCode in (SELECT negg.WHCODE FROM ICSMOApplyNegDetail neg LEFT JOIN ICSMOApplyNeg negg ON neg.ApplyNegCode=negg.ApplyNegCode 
                                                        WHERE  lotdd.TransCode=neg.ApplyNegCode AND lotdd.TransSequence=neg.Sequence AND lotdd.WorkPoint=neg.WorkPoint and negg.Type='3') AND WorkPoint=a.WorkPoint),'') AS WHName";
                                }
                                else if (LotType.Equals("14"))
                                {//委外领料申请退料
                                    columnsWHCODE = @"ISNULL((SELECT negg.WHCODE FROM ICSOApplyNegDetail neg LEFT JOIN ICSOApplyNeg negg ON neg.OApplyNegCode=negg.OApplyNegCode 
                                                        WHERE  lotdd.TransCode=neg.OApplyNegCode AND lotdd.TransSequence=neg.Sequence AND lotdd.WorkPoint=neg.WorkPoint and negg.Type='2'),'') AS WHCode";
                                    columnsWHNAME = @"ISNULL((SELECT WarehouseName from ICSWareHouse where WarehouseCode in (SELECT negg.WHCODE FROM ICSOApplyNegDetail neg LEFT JOIN ICSOApplyNeg negg ON neg.OApplyNegCode=negg.OApplyNegCode 
                                                        WHERE  lotdd.TransCode=neg.OApplyNegCode AND lotdd.TransSequence=neg.Sequence AND lotdd.WorkPoint=neg.WorkPoint and negg.Type='2') AND WorkPoint=a.WorkPoint),'') AS WHName";
                                }
                                else if (LotType.Equals("15"))
                                {//委外材料出库退料
                                    columnsWHCODE = @"ISNULL((SELECT negg.WHCODE FROM ICSOApplyNegDetail neg LEFT JOIN ICSOApplyNeg negg ON neg.OApplyNegCode=negg.OApplyNegCode 
                                                        WHERE  lotdd.TransCode=neg.OApplyNegCode AND lotdd.TransSequence=neg.Sequence AND lotdd.WorkPoint=neg.WorkPoint and negg.Type='3'),'') AS WHCode";
                                    columnsWHNAME = @"ISNULL((SELECT WarehouseName from ICSWareHouse where WarehouseCode in (SELECT negg.WHCODE FROM ICSOApplyNegDetail neg LEFT JOIN ICSOApplyNeg negg ON neg.OApplyNegCode=negg.OApplyNegCode 
                                                        WHERE  lotdd.TransCode=neg.OApplyNegCode AND lotdd.TransSequence=neg.Sequence AND lotdd.WorkPoint=neg.WorkPoint and negg.Type='3') AND WorkPoint=a.WorkPoint),'') AS WHName";
                                }
                                else if (LotType.Equals("16"))
                                {//返工工单
                                    columnsWHCODE = @"ISNULL((SELECT pick.WHCode FROM ICSMOPick pick LEFT JOIN ICSMO moo ON pick.MODetailID=moo.MODetailID AND pick.WorkPoint=moo.WorkPoint  
                                                        WHERE moo.MOCode=lotdd.TransCode AND pick.Sequence=lotdd.TransSequence AND pick.WorkPoint=lotdd.WorkPoint),'') AS WHCode  ";
                                    columnsWHNAME = @"ISNULL((SELECT WarehouseName from ICSWareHouse where WarehouseCode in (SELECT pick.WHCode FROM ICSMOPick pick LEFT JOIN ICSMO moo ON pick.MODetailID=moo.MODetailID AND pick.WorkPoint=moo.WorkPoint  
                                                        WHERE moo.MOCode=lotdd.TransCode AND pick.Sequence=lotdd.TransSequence AND pick.WorkPoint=lotdd.WorkPoint) AND WorkPoint=a.WorkPoint),'') AS WHName  ";
                                }
                                else
                                {
                                    columnsWHCODE = @"'' AS WHCode";
                                    columnsWHNAME = @"'' AS WHName";
                                }
                                #endregion

                                if (TransType == TransTypeEnum.PurchaseReceiveDoc.GetDescription() || TransType == TransTypeEnum.DeliveryNotice.GetDescription()
                                   || TransType == TransTypeEnum.OutsourcingReceiveDoc.GetDescription() || TransType == TransTypeEnum.ODeliveryNotice.GetDescription()
                                   || TransType == TransTypeEnum.ManufactureReceiveDoc.GetDescription() || TransType == TransTypeEnum.ManufactureReceive.GetDescription()
                                   || TransType == TransTypeEnum.UnqualifiedIN.GetDescription() || TransType == TransTypeEnum.MOStockINByProduct.GetDescription()
                                   || TransType == TransTypeEnum.OOStockINByProduct.GetDescription())
                                {
                                    columns = @"ISNULL(ins.QualifiedQuantity+ins.WaiveQuantity, a.Quantity) AS Quantity,
                                                a.Quantity*(a.Amount/a.Quantity) AS Amount,a.Type,
                                                {0},{2},
                                                lotdd.TransCode,lotdd.TransSequence,
                                                {3}
                                                {1}
                                                ext.BatchCode AS BatchCode,";

                                    tableName = @"ICSInventoryLot a
                                            INNER JOIN ICSExtension ext ON a.ExtensionID=ext.ID AND a.WorkPoint=ext.WorkPoint
                                            LEFT JOIN ICSInventoryLotDetail lotdd ON lotdd.LotNo=a.LotNo AND a.WorkPoint=lotdd.WorkPoint
                                            LEFT JOIN ICSInspection ins ON a.LotNo=ins.LotNo AND a.WorkPoint=ins.WorkPoint";
                                }
                                else
                                {
                                    columns = @"a.Quantity AS Quantity,
                                                a.Quantity*(a.Amount/a.Quantity) AS Amount,a.Type,
                                                {0},{2},
                                                {3}
                                                {1}
                                                ext.BatchCode AS BatchCode,";

                                    tableName = @"ICSInventoryLot a
                                            INNER JOIN ICSExtension ext ON a.ExtensionID=ext.ID AND a.WorkPoint=ext.WorkPoint
                                            LEFT JOIN ICSInventoryLotDetail lotdd ON lotdd.LotNo=a.LotNo AND a.WorkPoint=lotdd.WorkPoint";
                                }



                                columns = string.Format(columns, columnsWHCODE, columnsLONAME, columnsWHNAME, columnsLOCODE);


                            }
                            else
                            {
                                sql = @"
                                    WITH ICSBomALL AS
                                    (
	                                    SELECT
		                                    ContainerCode AS TContainerCode,
		                                    ContainerCode AS PContainerCode,
		                                    ContainerCode AS ContainerCode,
		                                    ID,
		                                    ContainerID,
		                                    0 AS [Level],
		                                    CAST(1 AS nvarchar(MAX)) AS SortSeq,
		                                    CAST('00001' AS nvarchar(MAX)) AS Sort
	                                    FROM ICSContainer
	                                    WHERE ContainerCode='{2}'
                                    UNION ALL
	                                    SELECT
		                                    b.TContainerCode,
		                                    b.ContainerCode AS PContainerCode,
		                                    a.ContainerCode,
		                                    a.ID,
		                                    a.ContainerID,
		                                    b.[Level]+1 AS [Level],
		                                    CAST(b.SortSeq AS nvarchar(MAX))+'.'+CAST(row_number() over (order by a.ContainerCode) AS nvarchar(MAX)) AS SortSeq,
		                                    CAST(b.Sort+'.'+REPLICATE('0',5-len(row_number() over (order by a.ContainerCode)))+CAST(row_number() over (order by a.ContainerCode) AS nvarchar(MAX)) AS nvarchar(MAX)) AS Sort
	                                    FROM
		                                    ICSContainer a
	                                    INNER JOIN ICSBomALL b ON a.ID=b.ContainerID
                                    )
                                    " + sql;

                                if (TransType == TransTypeEnum.PurchaseReceiveDoc.GetDescription() || TransType == TransTypeEnum.DeliveryNotice.GetDescription()
                                   || TransType == TransTypeEnum.OutsourcingReceiveDoc.GetDescription() || TransType == TransTypeEnum.ODeliveryNotice.GetDescription()
                                   || TransType == TransTypeEnum.ManufactureReceiveDoc.GetDescription() || TransType == TransTypeEnum.ManufactureReceive.GetDescription()
                                   || TransType == TransTypeEnum.UnqualifiedIN.GetDescription() || TransType == TransTypeEnum.MOStockINByProduct.GetDescription()
                                   || TransType == TransTypeEnum.OOStockINByProduct.GetDescription())
                                {
                                    columns = @"ISNULL(ins.QualifiedQuantity+ins.WaiveQuantity, a.Quantity) AS Quantity,
                                    a.Quantity*(a.Amount/a.Quantity) AS Amount,a.Type,
                                    '' AS WHCode,
                                    '' AS WHName,
                                    '' AS LocationCode,
                                    '' AS LocationName,
                                    ext.BatchCode AS BatchCode,";

                                    tableName = @"ICSInventoryLot a
                                    INNER JOIN ICSExtension ext ON a.ExtensionID=ext.ID AND a.WorkPoint=ext.WorkPoint
                                    LEFT JOIN ICSInspection ins ON a.LotNo=ins.LotNo AND a.WorkPoint=ins.WorkPoint";
                                }
                                else
                                {
                                    columns = @"a.Quantity AS Quantity,
                                    a.Quantity*(a.Amount/a.Quantity) AS Amount,a.Type,
                                    '' AS WHCode,
                                    '' AS WHName,
                                    '' AS LocationCode,
                                    '' AS LocationName,
                                    ext.BatchCode AS BatchCode,";

                                    tableName = @"ICSInventoryLot a
                                    INNER JOIN ICSExtension ext ON a.ExtensionID=ext.ID AND a.WorkPoint=ext.WorkPoint";
                                }

                            }

                        }
                    }


                    if (TransType != TransTypeEnum.LocationSeatch.GetDescription())
                    {
                        if (string.IsNullOrWhiteSpace(columns) || string.IsNullOrWhiteSpace(tableName))
                            throw new Exception(language.GetNameByCode("WMSAPIInfo003"));
                    }


                    if (TransType == TransTypeEnum.LocationSeatch.GetDescription())
                    {
                        Losql = string.Format(Losql, columns, tableName, JsonData.Code, JsonData.WorkPoint);

                        table = DBHelper.SQlReturnData(Losql, cmd);
                    }
                    else
                    {
                        
                        sql = string.Format(sql, columns, tableName, JsonData.Code, JsonData.WorkPoint, zlqty, UName,JsonData.TransCode,JsonData.TransSequence,JsonData.CheckKind);
                        log.Debug("条码sql:" + sql);
                        table = DBHelper.SQlReturnData(sql, cmd);
                    }

                    if (table == null || table.Rows.Count <= 0)
                        throw new Exception(language.GetNameByCode("WMSAPIInfo008"));//"未查询到条码数据!"

                    #region 出库检验是否符合源头单据

                    string msg = string.Empty;
                    bool isLimit = false;
                    string sqlCheckSign = @"select F_EnabledMark  from Sys_SRM_Items where F_EnCode = 'OutWithLocationCode' and F_EnabledMark = '1'";
                    DataTable flag = DBHelper.SQlReturnData(sqlCheckSign, cmd);
                    if (isOut)   // && TransType != TransTypeEnum.LOTSplit.GetDescription()
                    {//&& TransType != TransTypeEnum.TransferLibrary.GetDescription()
                        string Lot = "";
                        string workP = "";
                        if (TransType == TransTypeEnum.TransferLibrary.GetDescription())
                        {
                            foreach (DataRow drLot in table.Rows)
                            {
                                Lot = drLot["LotNo"].ToString();
                                sql = @"SELECT WarehouseCode FROM ICSWareHouseLotInfo a WHERE LotNo='{0}' AND WorkPoint='{1}'";
                                sql = string.Format(sql, Lot, JsonData.WorkPoint);
                                DataTable dt = DBHelper.SQlReturnData(sql, cmd);
                                if (dt == null || dt.Rows.Count <= 0)
                                {
                                    throw new Exception(string.Format(language.GetNameByCode("WMSAPIInfo171"), Lot));
                                }
                                string whcode = dt.Rows[0]["WarehouseCode"].ToString();
                                if (!JsonData.WHCode.Equals(whcode))
                                {
                                    throw new Exception(string.Format(language.GetNameByCode("WMSAPIInfo395"), JsonData.WHCode, whcode));
                                }
                            }

                        }
                        else if (TransType != TransTypeEnum.LocationSeatch.GetDescription() && TransType != TransTypeEnum.StepNoTransferDocIn.GetDescription())
                        {
                            string seq = string.Empty;
                            if (TransType == TransTypeEnum.MOIssueDoc.GetDescription())
                            {
                                string chekkksql = @"select a.Sequence,a.InvCode FROM ICSMOPick  a
                                INNER JOIN ICSMO b ON  a.MODetailID=b.MODetailID AND a.WorkPoint=b.WorkPoint
                                WHERE b.MOCode='{0}' AND b.Sequence='{2}' AND a.WorkPoint='{1}' ";
                                chekkksql = string.Format(chekkksql, JsonData.TransCode, JsonData.WorkPoint, JsonData.TransSequence);
                                log.Debug("工单行查子件信息" + chekkksql);
                                DataTable dtaa = DBHelper.SQlReturnData(chekkksql, cmd);
                                //查询条码的物料
                                string cheklotsql = @"select a.InvCode FROM ICSInventoryLot  a
                                WHERE a.LotNo='{0}'  AND a.WorkPoint='{1}' ";
                                cheklotsql = string.Format(cheklotsql, table.Rows[0]["LotNo"].ToString(), JsonData.WorkPoint);
                                log.Debug("查询条码的物料" + cheklotsql);
                                DataTable lotdata = DBHelper.SQlReturnData(cheklotsql, cmd);

                                //DataTable ad0=dtaa.Select(a => a.invcode == lotdata.Rows[0]["InvCode"].ToString());
                                DataRow[] drs = dtaa.Select("InvCode ='" + lotdata.Rows[0]["InvCode"].ToString() + "'");
                                if (drs == null || drs.Length == 0)
                                {
                                    throw new Exception("当前扫描的条码物料和单据子件物料没有匹配的行,请确认!");
                                }
                                //DataTable ad0 = dtaa.AsEnumerable()
                                //.Where(a => a.Field<string>("InvCode") == lotdata.Rows[0]["InvCode"].ToString())
                                //.CopyToDataTable();
                                //if (ad0 == null || ad0.Rows.Count == 0)
                                //{
                                //    throw new Exception("当前扫描的条码物料和单据子件物料没有匹配的行,请确认!");
                                //}
                                seq= JsonData.TransSequence + "~" + drs[0]["Sequence"].ToString();
                                log.Debug("工单子件行号:" + seq);

                                if (string.IsNullOrEmpty(JsonData.TransCode))
                                {
                                    throw new Exception(language.GetNameByCode("WMSAPIInfo001"));//"单据号不能为空!"
                                }
                            }
                            else if (TransType == TransTypeEnum.SalesShipmentDoc.GetDescription())
                            {
                                string chekkksql = @"select a.Sequence,a.InvCode FROM ICSSDN a
                                WHERE a.SDNCode='{0}' AND a.WorkPoint='{1}' ";
                                chekkksql = string.Format(chekkksql, JsonData.TransCode, JsonData.WorkPoint);
                                log.Debug("销售发货单行信息" + chekkksql);
                                DataTable dtaa = DBHelper.SQlReturnData(chekkksql, cmd);
                                //查询条码的物料
                                string cheklotsql = @"select a.InvCode FROM ICSInventoryLot  a
                                WHERE a.LotNo='{0}'  AND a.WorkPoint='{1}' ";
                                cheklotsql = string.Format(cheklotsql, table.Rows[0]["LotNo"].ToString(), JsonData.WorkPoint);
                                log.Debug("查询条码的物料" + cheklotsql);
                                DataTable lotdata = DBHelper.SQlReturnData(cheklotsql, cmd);

                                //DataTable ad0=dtaa.Select(a => a.invcode == lotdata.Rows[0]["InvCode"].ToString());
                                DataRow[] drs = dtaa.Select("InvCode ='" + lotdata.Rows[0]["InvCode"].ToString() + "'");
                                if (drs == null || drs.Length == 0)
                                {
                                    throw new Exception("当前扫描的条码物料和单据物料没有匹配的行,请确认!");
                                }
                                //DataTable ad0 = dtaa.AsEnumerable()
                                //.Where(a => a.Field<string>("InvCode") == lotdata.Rows[0]["InvCode"].ToString())
                                //.CopyToDataTable();
                                //if (ad0 == null || ad0.Rows.Count == 0)
                                //{
                                //    throw new Exception("当前扫描的条码物料和单据子件物料没有匹配的行,请确认!");
                                //}
                                seq = drs[0]["Sequence"].ToString();
                                log.Debug("销售发货单行号:" + seq);

                                if (string.IsNullOrEmpty(JsonData.TransCode))
                                {
                                    throw new Exception(language.GetNameByCode("WMSAPIInfo001"));//"单据号不能为空!"
                                }
                            }

                            WMSSourceDocumentModel model = new WMSSourceDocumentModel();
                            model.TransCode = JsonData.TransCode;
                            model.TransSequence = seq;
                            model.TransType = JsonData.TransType;
                            model.WorkPoint = JsonData.WorkPoint;
                            model.User = JsonData.User;
                            DataTable TransData = AMTransInformationGet(model);
                            DataView dataView = TransData.DefaultView;
                            foreach (DataRow drLot in table.Rows)
                            {
                                Lot = drLot["LotNo"].ToString();
                                //盘点不需要对比以下属性
                                if (TransType == TransTypeEnum.Check.GetDescription())
                                    continue;

                                string rowFilter = "InvCode='" + drLot["InvCode"] + "'";
                                CheckTrans(dataView, rowFilter, string.Format(language.GetNameByCode("WMSAPIInfo041"), Lot, drLot["InvCode"]));
                                if (TransType != TransTypeEnum.MOIssueDoc.GetDescription())
                                {
                                    rowFilter += " AND (LEN(ISNULL(WHCode,''))<=0 OR (LEN(ISNULL(WHCode,''))>0 AND WHCode='" + drLot["WHCode"] + "'))";
                                    CheckTrans(dataView, rowFilter, string.Format(language.GetNameByCode("WMSAPIInfo042"), Lot, drLot["WHCode"]));
                                }
                                

                                rowFilter += " AND (LEN(ISNULL(ProjectCode,''))<=0 OR (LEN(ISNULL(ProjectCode,''))>0 AND ProjectCode='" + drLot["ProjectCode"] + "'))";

                                CheckTrans(dataView, rowFilter, string.Format(language.GetNameByCode("WMSAPIInfo500"), Lot, drLot["ProjectCode"], GetExtentionName("ProjectCode", JsonData.WorkPoint, cmd, language)));

                                rowFilter += "AND (LEN(ISNULL(BatchCode,''))<=0 OR (LEN(ISNULL(BatchCode,''))>0 AND BatchCode='" + drLot["BatchCode"] + "'))";
                                CheckTrans(dataView, rowFilter, string.Format(language.GetNameByCode("WMSAPIInfo500"), Lot, drLot["BatchCode"], GetExtentionName("BatchCode", JsonData.WorkPoint, cmd, language)));
                                rowFilter += "AND (LEN(ISNULL(Version,''))<=0 OR (LEN(ISNULL(Version,''))>0 AND Version='" + drLot["Version"] + "'))";
                                CheckTrans(dataView, rowFilter, string.Format(language.GetNameByCode("WMSAPIInfo500"), Lot, drLot["Version"], GetExtentionName("Version", JsonData.WorkPoint, cmd, language)));
                                rowFilter += "AND (LEN(ISNULL(Brand,''))<=0 OR (LEN(ISNULL(Brand,''))>0 AND Brand='" + drLot["Brand"] + "'))";
                                CheckTrans(dataView, rowFilter, string.Format(language.GetNameByCode("WMSAPIInfo500"), Lot, drLot["Brand"], GetExtentionName("Brand", JsonData.WorkPoint, cmd, language)));
                                rowFilter += "AND (LEN(ISNULL(cFree1,''))<=0 OR (LEN(ISNULL(cFree1,''))>0 AND cFree1='" + drLot["cFree1"] + "'))";
                                CheckTrans(dataView, rowFilter, string.Format(language.GetNameByCode("WMSAPIInfo500"), Lot, drLot["cFree1"], GetExtentionName("cFree1", JsonData.WorkPoint, cmd, language)));
                                rowFilter += "AND (LEN(ISNULL(cFree2,''))<=0 OR (LEN(ISNULL(cFree2,''))>0 AND cFree2='" + drLot["cFree2"] + "'))";
                                CheckTrans(dataView, rowFilter, string.Format(language.GetNameByCode("WMSAPIInfo500"), Lot, drLot["cFree2"], GetExtentionName("cFree2", JsonData.WorkPoint, cmd, language)));
                                rowFilter += "AND (LEN(ISNULL(cFree3,''))<=0 OR (LEN(ISNULL(cFree3,''))>0 AND cFree3='" + drLot["cFree3"] + "'))";
                                CheckTrans(dataView, rowFilter, string.Format(language.GetNameByCode("WMSAPIInfo500"), Lot, drLot["cFree3"], GetExtentionName("cFree3", JsonData.WorkPoint, cmd, language)));
                                rowFilter += "AND (LEN(ISNULL(cFree4,''))<=0 OR (LEN(ISNULL(cFree4,''))>0 AND cFree4='" + drLot["cFree4"] + "'))";
                                CheckTrans(dataView, rowFilter, string.Format(language.GetNameByCode("WMSAPIInfo500"), Lot, drLot["cFree4"], GetExtentionName("cFree4", JsonData.WorkPoint, cmd, language)));
                                rowFilter += "AND (LEN(ISNULL(cFree5,''))<=0 OR (LEN(ISNULL(cFree5,''))>0 AND cFree5='" + drLot["cFree5"] + "'))";
                                CheckTrans(dataView, rowFilter, string.Format(language.GetNameByCode("WMSAPIInfo500"), Lot, drLot["cFree5"], GetExtentionName("cFree5", JsonData.WorkPoint, cmd, language)));
                                rowFilter += "AND (LEN(ISNULL(cFree6,''))<=0 OR (LEN(ISNULL(cFree6,''))>0 AND cFree6='" + drLot["cFree6"] + "'))";
                                CheckTrans(dataView, rowFilter, string.Format(language.GetNameByCode("WMSAPIInfo500"), Lot, drLot["cFree6"], GetExtentionName("cFree6", JsonData.WorkPoint, cmd, language)));
                                rowFilter += "AND (LEN(ISNULL(cFree7,''))<=0 OR (LEN(ISNULL(cFree7,''))>0 AND cFree7='" + drLot["cFree7"] + "'))";
                                CheckTrans(dataView, rowFilter, string.Format(language.GetNameByCode("WMSAPIInfo500"), Lot, drLot["cFree7"], GetExtentionName("cFree7", JsonData.WorkPoint, cmd, language)));
                                rowFilter += "AND (LEN(ISNULL(cFree8,''))<=0 OR (LEN(ISNULL(cFree8,''))>0 AND cFree8='" + drLot["cFree8"] + "'))";
                                CheckTrans(dataView, rowFilter, string.Format(language.GetNameByCode("WMSAPIInfo500"), Lot, drLot["cFree8"], GetExtentionName("cFree8", JsonData.WorkPoint, cmd, language)));
                                rowFilter += "AND (LEN(ISNULL(cFree9,''))<=0 OR (LEN(ISNULL(cFree9,''))>0 AND cFree9='" + drLot["cFree9"] + "'))";
                                CheckTrans(dataView, rowFilter, string.Format(language.GetNameByCode("WMSAPIInfo500"), Lot, drLot["cFree9"], GetExtentionName("cFree9", JsonData.WorkPoint, cmd, language)));
                                rowFilter += "AND (LEN(ISNULL(cFree10,''))<=0 OR (LEN(ISNULL(cFree10,''))>0 AND cFree10='" + drLot["cFree10"] + "'))";
                                CheckTrans(dataView, rowFilter, string.Format(language.GetNameByCode("WMSAPIInfo500"), Lot, drLot["cFree10"], GetExtentionName("cFree10", JsonData.WorkPoint, cmd, language)));
                                if (flag != null && flag.Rows.Count > 0)
                                {
                                    rowFilter += " AND LocationCode='" + drLot["LocationCode"] + "'";
                                    CheckTrans(dataView, rowFilter, string.Format(language.GetNameByCode("WMSAPIInfo042"), Lot, drLot["LocationCode"]));
                                }

                                //保质期管理
                                var resultEffective = Effective(Lot, JsonData.WorkPoint, cmd, language);
                                //0 - 已经是最早的批次
                                //1 - 不管控
                                //2 - 提醒
                                //3 - 限制
                                if (resultEffective == "2")
                                {
                                    msg += string.Format(language.GetNameByCode("WMSAPIInfo181"), Lot) + Environment.NewLine;
                                }
                                else if (resultEffective == "3")
                                {
                                    msg += string.Format(language.GetNameByCode("WMSAPIInfo182"), Lot) + Environment.NewLine;
                                    isLimit = true;
                                }

                                string rowFilternew = rowFilter + " AND LEN(ISNULL(ProjectCode,''))>0";
                                string sqlnew = CheckTransnew(dataView, rowFilternew, "ProjectCode");
                                rowFilternew = rowFilter + " AND  LEN(ISNULL(BatchCode,''))>0";
                                sqlnew += CheckTransnew(dataView, rowFilternew, "BatchCode");
                                rowFilternew = rowFilter + " AND LEN(ISNULL(Version,''))>0";
                                sqlnew += CheckTransnew(dataView, rowFilternew, "Version");
                                rowFilternew = rowFilter + " AND LEN(ISNULL(Brand,''))>0";
                                sqlnew += CheckTransnew(dataView, rowFilternew, "Brand");
                                rowFilternew = rowFilter + " AND LEN(ISNULL(cFree1,''))>0";
                                sqlnew += CheckTransnew(dataView, rowFilternew, "cFree1");
                                rowFilternew = rowFilter + " AND LEN(ISNULL(cFree2,''))>0";
                                sqlnew += CheckTransnew(dataView, rowFilternew, "cFree2");
                                rowFilternew = rowFilter + " AND LEN(ISNULL(cFree3,''))>0";
                                sqlnew += CheckTransnew(dataView, rowFilternew, "cFree3");
                                rowFilternew = rowFilter + " AND LEN(ISNULL(cFree4,''))>0";
                                sqlnew += CheckTransnew(dataView, rowFilternew, "cFree4");
                                rowFilternew = rowFilter + " AND LEN(ISNULL(cFree5,''))>0";
                                sqlnew += CheckTransnew(dataView, rowFilternew, "cFree5");
                                rowFilternew = rowFilter + " AND LEN(ISNULL(cFree6,''))>0";
                                sqlnew += CheckTransnew(dataView, rowFilternew, "cFree6");
                                rowFilternew = rowFilter + " AND LEN(ISNULL(cFree7,''))>0";
                                sqlnew += CheckTransnew(dataView, rowFilternew, "cFree7");
                                rowFilternew = rowFilter + " AND LEN(ISNULL(cFree8,''))>0 ";
                                sqlnew += CheckTransnew(dataView, rowFilternew, "cFree8");
                                rowFilternew = rowFilter + " AND LEN(ISNULL(cFree9,''))>0";
                                sqlnew += CheckTransnew(dataView, rowFilternew, "cFree9");
                                rowFilternew = rowFilter + " AND LEN(ISNULL(cFree10,''))>0";
                                sqlnew += CheckTransnew(dataView, rowFilternew, "cFree10");



                                //先进先出判断
                                var result = CanOut(Lot, JsonData.WorkPoint, JsonData.ScanLotCode, sqlnew, cmd, language);
                                //0 - 已经是最早的批次
                                //1 - 不管控
                                //2 - 提醒
                                //3 - 限制
                                if (result == "2")
                                {
                                    msg += string.Format(language.GetNameByCode("WMSAPIInfo178"), Lot) + Environment.NewLine;
                                }
                                else if (result == "3")
                                {
                                    msg += string.Format(language.GetNameByCode("WMSAPIInfo179"), Lot) + Environment.NewLine;
                                    isLimit = true;
                                }
                            }
                        }

                    }
                    #endregion
                    //return table;
                    Result res = new Result();
                    res.Success = true;
                    res.Message = msg;// "接口调用成功!";
                    if (!isLimit)
                        res.Data = table;
                    return res;
                    //出库时
                    //Message无值、Data有值,可直接处理
                    //Message有值、Data有值,弹出提醒框(可点击确定、取消,确定后继续出库,取消后不处理这批条码),显示Message信息
                    //Message有值、Data无值,弹出警告框(只能点击确定,且不处理这批条码),显示Message信息
                }
                catch (Exception ex)
                {
                    log.Error(ex.Message);
                    throw new Exception(ex.Message);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                    }
                    conn.Dispose();
                }
            }
        }



        /// <summary>
        /// 拣配
        /// </summary>
        /// <param name="JsonData"></param>
        /// <returns></returns>
        public static DataTable PickMerge(List<LOTStockModel> JsonData)
        {
            String PrintEnable = "";
            var language = LanguageHelper.GetName("WMSAPIInfo");
            if (JsonData.Count <= 0)
            {
                throw new Exception(language.GetNameByCode("WMSAPIInfo007"));//"传送数据为空!"
            }
            List<LOTStockModelList> model = new List<LOTStockModelList>();
            DataTable printTable = new DataTable();
            using (SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString))
            {
                conn.Open();
                SqlTransaction sqlTran = conn.BeginTransaction();
                SqlCommand cmd = new SqlCommand();
                cmd.Transaction = sqlTran;
                cmd.Connection = conn;
                cmd.CommandTimeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["TimeOut"]);
                string BusinessCode = string.Empty;
                try
                {
                    string TransType = string.Empty;
                    string pikTbLogsql = "";
                    string Identification = Guid.NewGuid().ToString();
                    foreach (var item in JsonData)
                    {
                        TransType = item.TransType;
                        if (!EnumHelper.HasDescriptions(typeof(TransTypeEnum), TransType))
                        {
                            throw new Exception(LanguageHelper.GetNameSingle("WMSAPIInfo003"));//"单据类型不存在!"
                        }
                        else if (string.IsNullOrEmpty(item.TransCode))
                        {
                            throw new Exception(language.GetNameByCode("WMSAPIInfo001"));//"单据号不能为空!"
                        }
                        string[] trans = item.TransCode.Split('~');
                        string MergeID = "";
                        if (trans.Length == 2)
                        {
                            MergeID = trans[0];
                            item.TransCode = trans[1];
                        }
                        #region 销售出库
                        else if (TransType == TransTypeEnum.SalesShipmentDoc.GetDescription()
                            || TransType == TransTypeEnum.MOIssueDoc.GetDescription()
                            || TransType == TransTypeEnum.OutsourcingIssueDoc.GetDescription())
                        {
                            BusinessCode = TransTypeEnum.SalesShipmentDoc.GetDescription<DBValue>();
//                            //更新源头单据数量
//                            pikTbLogsql = @"update b  set b.LockQuantity=convert(decimal(18,6),b.LockQuantity)-convert(decimal(18,6),c.Quantity ) 
//									from  dbo.ICSWareHouseLotInfo b 
//							        inner join (select sum(Quantity) as Quantity, LotNo from ICSWareHouseLotInfolog  
//                                    where  TransCode ='{0}' AND TransSequence='{1}' and TransType='15' and WorkPoint='{2}'	 group by LotNo) c 
//							        on c.LotNo =b.LotNo
//";
//                            pikTbLogsql = string.Format(pikTbLogsql, item.TransCode, item.TransSequence, item.WorkPoint);
//                            if (!DBHelper.ExecuteNonQuery(pikTbLogsql, cmd))
//                            {
//                                throw new Exception("更新库存锁定数量失败!");
//                            }

                            foreach (var itemInfo in item.detail)
                            {
                                pikTbLogsql += @" 
                               IF EXISTS(SELECT a.LotNo FROM ICSWareHouseLotInfo a WHERE a.LotNo='{7}' AND a.WorkPoint='{6}' AND Quantity-LockQuantity-'{3}'<0)
                                BEGIN
                                    RAISERROR('条码:" +"{7}"  + @"库存数量不足!',16,1);
                                    RETURN
                                END
                                IF NOT EXISTS(SELECT TransCode FROM ICSWareHouseLotInfoLog WHERE TransCode='{1}' AND TransSequence='{2}' AND LotNo='{7}' AND WorkPoint='{6}' AND TransType='15')
                            BEGIN
	                            INSERT INTO ICSWareHouseLotInfoLog(ID,Identification,TransCode,TransSequence,LotNo,InvCode,
							    FromWarehouseCode,FromLocationCode,ToWarehouseCode,ToLocationCode,Quantity,
							    Memo,Lock,TransType,BusinessCode,ERPUpload,ERPID,
							    ERPDetailID,ERPCode,ERPSequence,MUSER,MUSERName,
							    MTIME,WorkPoint,EATTRIBUTE1)
							    SELECT NEWID(),'{0}','{1}','{2}',a.LotNo ,a.InvCode ,
							    a.WarehouseCode,a.LocationCode,'','','{3}',
							    '','1','15','{4}','0','',
							    '','','','{5}' ,(select Top 1 f.F_RealName FROM ICSInventoryLot a INNER JOIN Sys_SRM_User f ON f.F_Account='{5}' AND a.WorkPoint=f.F_Location) ,
							    SYSDATETIME() ,'{6}' ,''
							    FROM ICSWareHouseLotInfo a
							    WHERE a.LotNo='{7}' AND a.WorkPoint='{6}'
                        
							    update ICSWareHouseLotInfo set LockQuantity=LockQuantity+'{3}' where LotNo='{7}' AND WorkPoint='{6}'
						    END 
                             UPDATE ICSMOApply SET MUSER='{5}' WHERE ApplyCode='{1}' and Sequence='{2}' ;  ";
                                pikTbLogsql = string.Format(pikTbLogsql, Identification, item.TransCode, item.TransSequence, itemInfo.CurrentQuantity
                                    , BusinessCode, item.User,  item.WorkPoint, itemInfo.LotNo);
                                log.Debug("1");

                                if (!DBHelper.ExecuteNonQuery(pikTbLogsql, cmd))
                                {
                                    throw new Exception("拣料失败!");
                                }
                            }
                        }
                        #endregion
                        else
                        {
                            throw new Exception(LanguageHelper.GetNameSingle("WMSAPIInfo003"));//"单据类型不存在!"
                        }
                    }
                    DataTable table = null;
                    cmd.Transaction.Commit();
                    return table;
                }
                catch (Exception ex)
                {
                    if (cmd.Transaction != null)
                        cmd.Transaction.Rollback();
                    log.Error(ex.Message);
                    throw new Exception(ex.Message);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                    }
                    conn.Dispose();
                }
            }
        }


        /// <summary>
        /// 回撤拣配
        /// </summary>
        /// <param name="JsonData"></param>
        /// <returns></returns>
        public static DataTable BackPickMerge(List<LOTStockModel> JsonData)
        {
            String PrintEnable = "";
            var language = LanguageHelper.GetName("WMSAPIInfo");
            if (JsonData.Count <= 0)
            {
                throw new Exception(language.GetNameByCode("WMSAPIInfo007"));//"传送数据为空!"
            }
            List<LOTStockModelList> model = new List<LOTStockModelList>();
            DataTable printTable = new DataTable();
            using (SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString))
            {
                conn.Open();
                SqlTransaction sqlTran = conn.BeginTransaction();
                SqlCommand cmd = new SqlCommand();
                cmd.Transaction = sqlTran;
                cmd.Connection = conn;
                cmd.CommandTimeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["TimeOut"]);
                string BusinessCode = string.Empty;
                try
                {
                    string TransType = string.Empty;
                    string pikTbLogsql = "";
                    string Identification = Guid.NewGuid().ToString();
                    foreach (var item in JsonData)
                    {
                        TransType = item.TransType;
                        if (!EnumHelper.HasDescriptions(typeof(TransTypeEnum), TransType))
                        {
                            throw new Exception(LanguageHelper.GetNameSingle("WMSAPIInfo003"));//"单据类型不存在!"
                        }
                        else if (string.IsNullOrEmpty(item.TransCode))
                        {
                            throw new Exception(language.GetNameByCode("WMSAPIInfo001"));//"单据号不能为空!"
                        }
                        string[] trans = item.TransCode.Split('~');
                        string MergeID = "";
                        if (trans.Length == 2)
                        {
                            MergeID = trans[0];
                            item.TransCode = trans[1];
                        }
                        #region 销售出库
                        else if (TransType == TransTypeEnum.SalesShipmentDoc.GetDescription()
                            || TransType == TransTypeEnum.MOIssueDoc.GetDescription()
                            || TransType == TransTypeEnum.OutsourcingIssueDoc.GetDescription())
                        {
                            BusinessCode = TransTypeEnum.SalesShipmentDoc.GetDescription<DBValue>();
                            //更新源头单据数量
                            pikTbLogsql += string.Format(@"		update b  set b.LockQuantity=convert(decimal(18,6),b.LockQuantity)-convert(decimal(18,6),c.Quantity ) 
												from  dbo.ICSWareHouseLotInfo b 
							inner join (select sum(Quantity) as Quantity, LotNo from ICSWareHouseLotInfolog  where  TransCode ='{0}' AND TransSequence='{1}' and TransType='15' and WorkPoint='{2}'	 group by LotNo) c 
							on c.LotNo =b.LotNo ", item.TransCode, item.TransSequence,item.WorkPoint);

                            pikTbLogsql += string.Format(@"	delete dbo.ICSWareHouseLotInfoLog where TransCode ='{0}' AND TransSequence='{1}' and TransType='15' and WorkPoint='{2}'", item.TransCode, item.TransSequence, item.WorkPoint);
                            if (!DBHelper.ExecuteNonQuery(pikTbLogsql, cmd))
                            {
                                throw new Exception("回撤拣料失败!");
                            }
                        }
                        #endregion
                        else
                        {
                            throw new Exception(LanguageHelper.GetNameSingle("WMSAPIInfo003"));//"单据类型不存在!"
                        }
                    }
                    DataTable table = null;
                    cmd.Transaction.Commit();
                    return table;
                }
                catch (Exception ex)
                {
                    if (cmd.Transaction != null)
                        cmd.Transaction.Rollback();
                    log.Error(ex.Message);
                    throw new Exception(ex.Message);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                    }
                    conn.Dispose();
                }
            }
        }


        /// <summary>
        /// 回撤拣配
        /// </summary>
        /// <param name="JsonData"></param>
        /// <returns></returns>
        public static DataTable BackPickMergeALL(List<LOTStockModel> JsonData)
        {
            String PrintEnable = "";
            var language = LanguageHelper.GetName("WMSAPIInfo");
            if (JsonData.Count <= 0)
            {
                throw new Exception(language.GetNameByCode("WMSAPIInfo007"));//"传送数据为空!"
            }
            List<LOTStockModelList> model = new List<LOTStockModelList>();
            DataTable printTable = new DataTable();
            using (SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString))
            {
                conn.Open();
                SqlTransaction sqlTran = conn.BeginTransaction();
                SqlCommand cmd = new SqlCommand();
                cmd.Transaction = sqlTran;
                cmd.Connection = conn;
                cmd.CommandTimeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["TimeOut"]);
                string BusinessCode = string.Empty;
                try
                {
                    string TransType = string.Empty;
                    string pikTbLogsql = "";
                    string Identification = Guid.NewGuid().ToString();
                    foreach (var item in JsonData)
                    {
                        TransType = item.TransType;
                        if (!EnumHelper.HasDescriptions(typeof(TransTypeEnum), TransType))
                        {
                            throw new Exception(LanguageHelper.GetNameSingle("WMSAPIInfo003"));//"单据类型不存在!"
                        }
                        else if (string.IsNullOrEmpty(item.TransCode))
                        {
                            throw new Exception(language.GetNameByCode("WMSAPIInfo001"));//"单据号不能为空!"
                        }
                        string[] trans = item.TransCode.Split('~');
                        string MergeID = "";
                        if (trans.Length == 2)
                        {
                            MergeID = trans[0];
                            item.TransCode = trans[1];
                        }
                        #region 销售出库
                        else if (TransType == TransTypeEnum.SalesShipmentDoc.GetDescription()
                            || TransType == TransTypeEnum.MOIssueDoc.GetDescription()
                            || TransType == TransTypeEnum.OutsourcingIssueDoc.GetDescription())
                        {
                            BusinessCode = TransTypeEnum.SalesShipmentDoc.GetDescription<DBValue>();
                            //更新源头单据数量
                            pikTbLogsql += string.Format(@"		update b  set b.LockQuantity=convert(decimal(18,6),b.LockQuantity)-convert(decimal(18,6),c.Quantity ) 
												from  dbo.ICSWareHouseLotInfo b 
							inner join (select sum(Quantity) as Quantity, LotNo from ICSWareHouseLotInfolog  where  TransCode ='{0}' and TransType='15' and WorkPoint='{1}'	 group by LotNo) c 
							on c.LotNo =b.LotNo ", item.TransCode,  item.WorkPoint);

                            pikTbLogsql += string.Format(@"	delete dbo.ICSWareHouseLotInfoLog where TransCode ='{0}'  and TransType='15' and WorkPoint='{1}'", item.TransCode, item.WorkPoint);
                            if (!DBHelper.ExecuteNonQuery(pikTbLogsql, cmd))
                            {
                                throw new Exception("整单回撤拣料失败!");
                            }
                        }
                        #endregion
                        else
                        {
                            throw new Exception(LanguageHelper.GetNameSingle("WMSAPIInfo003"));//"单据类型不存在!"
                        }
                    }
                    DataTable table = null;
                    cmd.Transaction.Commit();
                    return table;
                }
                catch (Exception ex)
                {
                    if (cmd.Transaction != null)
                        cmd.Transaction.Rollback();
                    log.Error(ex.Message);
                    throw new Exception(ex.Message);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                    }
                    conn.Dispose();
                }
            }
        }

        /// <summary>
        /// 获取周转箱信息(安多诚专用)
        /// </summary>
        /// <param name="JsonData"></param>
        /// <returns></returns>
        public static DataTable WorkingCapitalBoxGet(BarCodeModel JsonData)
        {
            var language = LanguageHelper.GetName("WMSAPIInfo");
            using (SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString))
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = conn;
                cmd.CommandTimeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["TimeOut"]);
                try
                {
                    if (string.IsNullOrEmpty(JsonData.WorkPoint))
                    {
                        throw new Exception(language.GetNameByCode("WMSAPIInfo004"));//"站点不能为空!"
                    }
                    
                    #region SLQ
                    string sql = @"";
                    #endregion
                    
                    log.Debug("查询周转箱sql : " + sql);
                    DataTable table = DBHelper.SQlReturnData(sql, cmd);
                    return table;
                }
                catch (Exception ex)
                {
                    log.Error(ex.Message);
                    throw new Exception(ex.Message);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                    }
                    conn.Dispose();
                }
            }
        }

        #region

        /// <summary>
        /// 成品入库单 新建
        /// </summary>
        /// <param name="JsonData"></param>
        /// <returns></returns>
        public static DataTable FinishedProductWarehouseEntryCreate(List<FinishedProductWarehouseEntry> JsonData)
        {
            var language = LanguageHelper.GetName("WMSAPIInfo");
            if (JsonData.Count <= 0)
            {
                throw new Exception(language.GetNameByCode("WMSAPIInfo007"));//"传送数据为空!"
            }
            using (SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString))
            {
                conn.Open();
                SqlTransaction sqlTran = conn.BeginTransaction();
                SqlCommand cmd = new SqlCommand();
                cmd.Transaction = sqlTran;
                cmd.Connection = conn;
                cmd.CommandTimeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["TimeOut"]);
                try
                {
                    string codes = string.Empty;
                    string sql = string.Empty;

                    foreach (var item in JsonData)
                    {
                        //获取单号
                        sql = @"DECLARE @MaxNO INT,@date varchar(20)='FRWE'+SUBSTRING(CONVERT(varchar(8), GETDATE(), 112), 1, 8)
                                SELECT @MaxNO=SUBSTRING(MAX(RCVCode),LEN(@date)+1,LEN(MAX(RCVCode))-LEN(@date))+1 FROM ICSWMSManufactureReceive 
                                    WHERE SUBSTRING(RCVCode, 1, LEN(@date))=@date
                                IF @MaxNO IS NULL
                                BEGIN
	                                SELECT @date+'00001' AS Code
                                END
                                ELSE
                                BEGIN
	                                SELECT @date+REPLICATE('0',5-LEN(@MaxNO))+CAST(@MaxNO AS nvarchar(10))  AS Code
                                END ";
                        string Code = DBHelper.ExecuteScalar(sql, cmd).ToString();
                        //创建主表
                        sql = @"IF NOT EXISTS(SELECT F_Account FROM Sys_SRM_User WHERE F_Account='{4}' AND F_Location='{6}')
                                BEGIN
	                                RAISERROR('" + string.Format(language.GetNameByCode("WMSAPIInfo060"), "{4}") + @"',16,1);
                                    RETURN
                                END

                                INSERT INTO [dbo].[ICSWMSManufactureReceive] 
                                ([ID], [RCVCode], [Type], [Status], [WHCode], [CreatePerson], [MUSER], [MUSERName], [CreateDateTime], [MTIME], [WorkPoint], [EATTRIBUTE1], [EATTRIBUTE2], [EATTRIBUTE3], [EATTRIBUTE4], [EATTRIBUTE5], [EATTRIBUTE6], [EATTRIBUTE7], [EATTRIBUTE8], [EATTRIBUTE9], [EATTRIBUTE10], [ExtensionID]) 
                                VALUES 
                                (NEWID(), '{0}', '{1}', '{2}','{3}', '{4}', '{4}',(select F_RealName from Sys_SRM_User where F_Account='{4}' and F_Location='{6}'), '{5}', '{5}', '{6}', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL)";
                        sql = string.Format(sql, Code, item.Type, item.Status, item.WHCode, item.MUSER,item.MTIME,item.WorkPoint );
                        log.Debug("成品入库单主表:" + sql);

                        if (!DBHelper.ExecuteNonQuery(sql, cmd))
                        {
                            throw new Exception(language.GetNameByCode("WMSAPIInfo022"));//"生产退料单信息创建失败!");
                        }
                        foreach (var itemInfo in item.detail)
                        {
                            //创建子表
                            sql = @"INSERT INTO [dbo].[ICSWMSManufactureReceiveDetail] 
                                    ([ID], [RCVCode], [Sequence], [LotNo], [SourceCode], [SourceSequence], [InvCode], [Quantity], [ExtensionID], [MUSER], [MUSERName], [MTIME], [WorkPoint], [EATTRIBUTE1], [EATTRIBUTE2], [EATTRIBUTE3], [EATTRIBUTE4], [EATTRIBUTE5], [EATTRIBUTE6], [EATTRIBUTE7], [EATTRIBUTE8], [EATTRIBUTE9], [EATTRIBUTE10]) 
                                    VALUES 
                                    (NEWID(), '{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}', '{7}', '{8}', (select F_RealName from Sys_SRM_User where F_Account='{8}' and F_Location='{10}'), '{9}', '{10}', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL)";
                            sql = string.Format(sql, Code, itemInfo.Sequence,itemInfo.LotNo,itemInfo.SourceCode,itemInfo.SourceSequence,itemInfo.InvCode,itemInfo.Quantity,itemInfo.ExtensionID,item.MUSER,item.MTIME,item.WorkPoint );

                            log.Debug("成品入库单子表:" + sql);
                            if (!DBHelper.ExecuteNonQuery(sql, cmd))
                            {
                                throw new Exception(language.GetNameByCode("WMSAPIInfo023"));//"生产退料单子表信息创建失败!");
                            }
                        }
                        ////校验退料数量是否超出领料数量
                        //sql = CheckMOIssueDoc(item.Type, item.ID, item.WorkPoint, language);
                        //DBHelper.ExecuteNonQuery(sql, cmd);
                        codes += "'" + Code + item.WorkPoint + "',";
                    }
                    if (string.IsNullOrWhiteSpace(codes))
                    {
                        throw new Exception(language.GetNameByCode("WMSAPIInfo001"));//"单据号不能为空!"
                    }
                    #region 查询返回数据
                    sql = @"SELECT a.RCVCode,
	                            c.WHCode,
	                            c.Status,
	                            a.Sequence,
	                            a.InvCode,
	                            inv.InvName,
	                            inv.InvStd,
	                            a.Quantity,
	                            inv.InvUnit,
	                            a.Amount,
	                            inv.AmountUnit,
	                            ext.ProjectCode,
	                            ext.BatchCode,
	                            ext.Version,
	                            ext.Brand,
	                            ext.cFree1,
	                            ext.cFree2,
	                            ext.cFree3,
	                            ext.cFree4,
	                            ext.cFree5,
	                            ext.cFree6,
	                            ext.cFree7,
	                            ext.cFree8,
	                            ext.cFree9,
	                            ext.cFree10,
	                            a.MUSER AS [User],
	                            a.MTIME AS [MTime]
                            FROM ICSWMSManufactureReceiveDetail a 
                            INNER JOIN ICSWMSManufactureReceive c ON a.RCVCode=c.RCVCode AND a.WorkPoint=c.WorkPoint
                            INNER JOIN ICSExtension ext ON a.ExtensionID=ext.ID AND a.WorkPoint=ext.WorkPoint
                            INNER JOIN ICSInventory inv ON a.InvCode=inv.InvCode AND a.WorkPoint=inv.WorkPoint
                            WHERE a.RCVCode+a.WorkPoint IN ({0})";
                    sql = string.Format(sql, codes.Substring(0, codes.Length - 1));
                    DataTable data = DBHelper.SQlReturnData(sql, cmd);
                    #endregion
                    cmd.Transaction.Commit();
                    return data;
                }
                catch (Exception ex)
                {
                    if (cmd.Transaction != null)
                        cmd.Transaction.Rollback();
                    log.Error(ex.Message);
                    throw new Exception(ex.Message);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                    }
                    conn.Dispose();
                }
            }
        }

        #endregion

    }
}