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"];

        #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();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = conn;
                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]
                                    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} ";
                    #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;    //合并发料查询源头单据表名
                    #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 形态转换
                    if (TransType == TransTypeEnum.MTDOC.GetDescription())
                    {
                        isDeliveryNotice = true;
                        columns = @"a.MTDOCCode AS TransCode,
                                    a.MTDOCType AS Type,
                                    a.Sequence AS TransSequence,
                                    a.MTDOCQuantity AS IssueQuantity,
                                    a.Quantity,
                                    a.Amount,
                                    a.MUSER AS [User],
                                    a.MTIME AS [MTime],";

                        tableName = @"ICSMTDOC a ";

                        where = @" a.MTDOCCode='{0}' AND a.WorkPoint='{1}' ";
                    }
                    #endregion
                    #region 委外发料(合并发料)
                    else if (TransType == TransTypeEnum.OutsourcingIssueDoc.GetDescription())
                    {
                        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())
                    {
                        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";

                        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' ";
                    }
                    #endregion
                    #region 销售出库(合并发料)
                    else if (TransType == TransTypeEnum.SalesShipmentDoc.GetDescription())
                    {
                        isMerge = true;
                        columnsMerge = @"mer.MergeID+'~'+a.SDNCode AS TransCode,
                                    a.SDNDetailID AS DetailID,
                                    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.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())
                    {
                        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,
                                    a.EATTRIBUTE1 AS WorkPoint,
                                    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}'  ";
                    }
                    #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,
                                    a.EATTRIBUTE1 AS WorkPoint, ";

                        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())
                    {
                        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())
                    {
                        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}' ";
                    }
                    #endregion
                    #region 领料申请单发料(合并发料)
                    else if (TransType == TransTypeEnum.MOApply.GetDescription())
                    {
                        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.OOApply.GetDescription())
                    {
                        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())
                    {
                        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())
                    {
                        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())
                    {
                        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())
                    {
                        columns = @"a.DNCode AS TransCode,
                                    '' AS Type,
                                    a.Sequence AS TransSequence,
                                    a.Quantity,
                                    a.Amount,
                                    a.RCVQuantity AS IssueQuantity,";

                        tableName = @"ICSDeliveryNotice a ";

                        where = @" a.DNCode='{0}' AND a.WorkPoint='{1}' AND DNType='1' ";
                    }
                    #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())
                    {
                        isDeliveryNotice = true;
                        columns = @"a.TransCode,
                                	a.DetailID,
                                    -- a.LotNo,
	                                '' AS Type,
	                                a.TransSequence,
	                                a.IssueQuantity,
	                                a.Quantity,
	                                a.Amount,
	                                a.MUSER AS [User],
	                                a.MTIME AS [MTime],";

                        tableName = @" (SELECT
                                       neg.ID AS ID,
			                           neg.ApplyNegCode AS TransCode,
			                           negDetail.ID AS DetailID,
			                           negDetail.ExtensionID,
			                           '' AS Type,
		                               negDetail.Sequence AS TransSequence,
			                           negDetail.IssueNegQuantity AS IssueQuantity,
			                           negDetail.Quantity,
			                           neg.MUSER ,
			                           neg.MTIME ,
			                           negDetail.InvCode,
			                           negDetail.Amount,
			                           neg.WorkPoint,
			                           negDetail.SourceDetailID AS WHCode
		                               FROM
			                              ICSMOApplyNegDetail negDetail
			                            INNER JOIN ICSMOApplyNeg neg ON neg.ApplyNegCode= negDetail.ApplyNegCode 
		                                ) a  ";

                        where = @" a.TransCode= '{0}' 
	                               AND a.WorkPoint= '{1}' ";
                    }
                    #endregion
                    #region 生产入库
                    else if (TransType == TransTypeEnum.ManufactureReceiveDoc.GetDescription())
                    {
                    }
                    #endregion
                    #region 开立的生产入库单
                    else if (TransType == TransTypeEnum.ManufactureReceive.GetDescription())
                    {
                        columns = @"a.RCVCode AS TransCode,
                                    '' AS Type,
                                    a.Sequence AS TransSequence,
                                    a.Quantity,
                                    a.Amount,
                                    a.RCVQuantity AS IssueQuantity,";

                        tableName = @"ICSManufactureReceive a ";

                        where = @" a.RCVCode='{0}' AND a.WorkPoint='{1}'  ";

                    }
                    #endregion
                    #region 返工工单
                    else if (TransType == TransTypeEnum.ReWorkReceiveMo.GetDescription())
                    {
                    }
                    #endregion
                    #region 销售退货
                    else if (TransType == TransTypeEnum.SalesShipmentDocNegative.GetDescription())
                    {
                        columns = @"a.SDNCode AS TransCode,
                                    '' AS Type,
                                    a.Sequence AS TransSequence,
                                    a.Quantity,
                                    a.Amount,
                                    a.SDNQuantity AS IssueQuantity,";

                        tableName = @"ICSSDN a ";

                        where = @" a.SDNCode='{0}' AND a.WorkPoint='{1}' AND Type='2' ";
                    }
                    #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())
                    {
                        columns = @"a.InCode AS TransCode,
                                    '' AS Type,
                                    a.Sequence AS TransSequence,
                                    a.Quantity,
                                    a.Amount,
                                    a.InQuantity AS IssueQuantity,";

                        tableName = @"ICSOtherIn a ";

                        where = @" a.InCode='{0}' AND a.WorkPoint='{1}' AND Type='2' ";
                    }
                    #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 判断是否启用匹配库位
                    string sqlCheckSign = @"select F_EnabledMark  from Sys_SRM_Items where F_EnCode = 'OutWithLocationCode'and F_EnabledMark = '1'";
                    DataTable flag = DBHelper.SQlReturnData(sqlCheckSign, cmd);
                    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, JsonData.WorkPoint);
                        }
                        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);

                    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 Result ContainerCheck(ICSContainerInfo JsonData)
        {
            var language = LanguageHelper.GetName("WMSAPIInfo");
            DataTable table = new DataTable();
            string msg = "";
            using (SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString))
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = conn;
                try
                {
                    string TransType = JsonData.TransType;
                    string ContainerID = "";
                    if (String.IsNullOrEmpty(JsonData.ContainerCode))
                    {
                        msg = string.Format(language.GetNameByCode("WMSAPIInfo007"));//"传入数据为空!"
                    }
                    if (String.IsNullOrEmpty(JsonData.WorkPoint))
                    {
                        msg = string.Format(language.GetNameByCode("WMSAPIInfo004"));//"站点不能为空!"
                    }
                    if (TransType != TransTypeEnum.ContainerBind.GetDescription() && TransType != TransTypeEnum.ContainerUnBind.GetDescription())
                    {
                        throw new Exception(language.GetNameByCode("WMSAPIInfo210"));//"操作类型错误!"
                    }
                    string chksql = @"select ID,ContainerCode from ICSContainer
                                      where ContainerCode='{0}' AND WorkPoint='{1}'";
                    chksql = string.Format(chksql, JsonData.ContainerCode, JsonData.WorkPoint);
                    DataTable chkdt = DBHelper.SQlReturnData(chksql, cmd);
                    if (chkdt.Rows.Count == 0)
                    {
                        msg = string.Format(language.GetNameByCode("WMSAPIInfo211"), JsonData.ContainerCode);//"容器不存在!"
                    }
                    else
                    {
                        ContainerID = chkdt.Rows[0]["ID"].ToString();
                    }
                    if (TransType == TransTypeEnum.ContainerBind.GetDescription())
                    {
                        chksql = @" select C.LotNo from ICSContainer A
                                INNER JOIN ICSContainerLot B ON B.ContainerID=A.ID AND B.WorkPoint=A.WorkPoint
                                INNER JOIN ICSWareHouseLotInfo C ON C.LotNo=B.LotNo AND C.WorkPoint=B.WorkPoint
                                WHERE A.ContainerCode='{0}' AND A.WorkPoint='{1}'";
                        chksql = string.Format(chksql, JsonData.ContainerCode, JsonData.WorkPoint);
                        chkdt = DBHelper.SQlReturnData(chksql, cmd);
                        if (chkdt.Rows.Count != 0)
                        {
                            msg = string.Format(language.GetNameByCode("WMSAPIInfo212"), JsonData.ContainerCode);//"容器已入库!"
                        }
                    }
                    else
                    {
                        chksql = @"select LotNo from ICSContainerLot
                                   where ContainerID='{0}' AND WorkPoint='{1}'";
                        chksql = string.Format(chksql, ContainerID, JsonData.WorkPoint);
                        chkdt = DBHelper.SQlReturnData(chksql, cmd);
                        if (chkdt.Rows.Count == 0)
                        {
                            msg = string.Format(language.GetNameByCode("WMSAPIInfo213"), JsonData.ContainerCode);//"容器未绑定条码!"
                        }
                        else
                        {
                            string sql = @"SELECT a.ID,
                                           con.ContainerCode,
                                           con.ContainerName,
                                           a.LotNo,
                                           a.InvCode,
                                           inv.InvName,
                                           inv.InvStd,
                                           a.Quantity,
                                           con.LocationCode
                                           FROM ICSWareHouseLotInfo a 
                                           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  bom.ContainerCode='{0}' AND a.WorkPoint='{1}' ";
                            sql = string.Format(sql, JsonData.ContainerCode, JsonData.WorkPoint);
                            log.Info("条码sql:" + sql);
                            table = DBHelper.SQlReturnData(sql, cmd);
                        }
                    }
                    Result res = new Result();
                    if (msg == "")
                    {
                        if (TransType == TransTypeEnum.ContainerBind.GetDescription())
                        {
                            res.Success = true;
                            res.Message = msg;// "接口调用成功!";
                        }
                        else
                        {
                            res.Success = true;
                            res.Message = msg;// "接口调用成功!";
                            res.Data = table;
                        }
                    }
                    else
                    {
                        res.Success = false;
                        res.Message = msg;// "返回错误信息!";
                    }
                    return res;
                }
                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 Result LocationRecommend(ICSLocationRecommend JsonData)
        {
            var language = LanguageHelper.GetName("WMSAPIInfo");
            DataTable table = new DataTable();
            string msg = "";
            using (SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString))
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = conn;
                try
                {
                    string ContainerID = "";
                    Result res = new Result();
                    if (String.IsNullOrEmpty(JsonData.WorkPoint))
                    {
                        msg = string.Format(language.GetNameByCode("WMSAPIInfo004"));//"站点不能为空!"
                    }
                    string chksql = "";
                    DataTable chkdt = new DataTable();
                    if (JsonData.NeedMerge == false)
                    {
                        chksql = @" select TOP 1 LocationCode from ICSLocation
                                    where ISNULL(EATTRIBUTE2,'')!='' AND ISNULL(EATTRIBUTE1,'')=''
                                    AND WorkPoint='{0}'
                                    Order by EATTRIBUTE2";
                        chksql = string.Format(chksql, JsonData.WorkPoint);
                        chkdt = DBHelper.SQlReturnData(chksql, cmd);
                        if (chkdt.Rows.Count == 0)
                        {
                            res.Success = false;
                            res.Message = string.Format(language.GetNameByCode("WMSAPIInfo202"));//"库位已被全部占用,暂无可以入库的库位!"
                        }
                        else
                        {
                            res.Success = true;
                            res.Message = chkdt.Rows[0]["LocationCode"].ToString();
                        }
                    }
                    else
                    {
                        chksql = @" select TOP 1 MergeLocationCode AS LocationCode from ICSLocationMerge A
                                    INNER JOIN ICSLocation B ON B.LocationCode=A.LocationCode AND B.WorkPoint=A.WorkPoint
                                    where ISNULL(B.EATTRIBUTE2,'')!='' AND ISNULL(B.EATTRIBUTE1,'')=''
                                    AND ISNULL(A.IsOccupied,'0')='0' AND ISNULL(A.OccupiedPallet,'')=''
                                    AND A.WorkPoint='{0}'
                                    Order by B.EATTRIBUTE2";
                        chksql = string.Format(chksql, ContainerID, JsonData.WorkPoint);
                        chkdt = DBHelper.SQlReturnData(chksql, cmd);
                        if (chkdt.Rows.Count == 0)
                        {
                            res.Success = false;
                            res.Message = string.Format(language.GetNameByCode("WMSAPIInfo202"));//"库位已被全部占用,暂无可以入库的库位!"
                        }
                        else
                        {
                            res.Success = true;
                            res.Message = chkdt.Rows[0]["LocationCode"].ToString();
                        }
                    }
                    return res;
                }
                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 Result BarCodeInformationGet(BarCodeModel JsonData)
        {
            var language = LanguageHelper.GetName("WMSAPIInfo");
            DataTable table = new DataTable();
            using (SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString))
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = conn;
                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 LotDetail = "";
                    string con = "";
                    #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 @aa VARCHAR(MAX)
                                DECLARE @bb VARCHAR(MAX)
                                DECLARE @cc VARCHAR(MAX)
                                    DECLARE @b VARCHAR(MAX)
                        set @b =
                        'SELECT a.ID,con.ContainerCode,con.ContainerName,a.LotNo,a.InvCode,
                                    inv.InvName,
                                    inv.InvStd,
                                    inv.InvUnit,
                                    inv.LotEnable,
                                    s.WarehouseCode,sum(a.Quantity) as Qty,s.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 from ICSWareHouseLotInfo  group by WarehouseCode,INVCode)s ON a.INVCode=s.INVCode 
                      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}'' and' 

					 

 
										select @aa=id from ICSWareHouseLotInfo where LotNo='{2}'
											
												IF @aa IS NOT NULL
												 BEGIN
														set @b = @b+' lot.invcode IN(SELECT invcode FROM ICSWareHouseLotInfo where LotNo=''{2}'') 
														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
'
												END
											
											
										select @bb=id from ICSLocation where LocationCode='{2}'
										
											IF @bb IS not NULL
											 BEGIN
													set @b = @b+' a.WarehouseCode=s.WarehouseCode and a.LocationCode=''{2}''
													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'
											END
										
											
										
										select @cc=id from ICSInventory where invcode='{2}'
												IF @cc IS not NULL
													BEGIN
														set @b = @b+' a.WarehouseCode=s.WarehouseCode and inv.invcode=''{2}''
														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'
												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,
                                    {5}
                                    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
                                    {4} 
                                    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 columnsWHNAME = string.Empty;
                    string columnsWHCODE = 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.TwoStepTransferDocOut.GetDescription()       //两步调出
                        || TransType == TransTypeEnum.OtherOutDoc.GetDescription()                 //其他出库
                        || TransType == TransTypeEnum.Check.GetDescription()                       //盘点
                        || TransType == TransTypeEnum.MOApply.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()             //拆卸单(散件生成条码入库)
                        || TransType == TransTypeEnum.MTDOC.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 a.ID,con.ContainerCode,con.ContainerName,a.LotNo,a.InvCode,inv.InvName,inv.InvStd,inv.InvUnit,inv.EATTRIBUTE1,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 a.ID,con.ContainerCode,con.ContainerName,a.LotNo,a.InvCode,inv.InvName,inv.InvStd,inv.InvUnit,inv.EATTRIBUTE1,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 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,inv.LotEnable";

                                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 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;

                                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";
                                LotDetail = $@"LEFT JOIN ICSInventoryDetail detail ON inv.InvCode= detail.INVCode AND (SELECT top 1 hh.FromWarehouseCode  FROM ICSWareHouseLotInfoLog hh WHERE hh.InvCode=a.InvCode AND hh.LotNo=a.LotNo) = detail.WHCode  AND a.WorkPoint = detail.WorkPoint ";
                                con = "detail.LocationCode AS Area,";
                            }
                            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, LotDetail, con);
                            #endregion
                            #region 原条码
                            if (ScanType == "LOTNO")
                            {
                                sql = sql + @" AND log.BusinessCode IN('" + type + @"') GROUP BY log.ID,a.ID,con.ContainerCode,con.ContainerName,a.LotNo,a.InvCode,inv.InvName,inv.InvStd,inv.InvUnit,inv.LotEnable,inv.EATTRIBUTE1,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,detail.LocationCode
                                ";
                                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 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(SUBSTRING(LotNo, CHARINDEX('-', LotNo)+1, LEN(LotNo)-CHARINDEX('-', LotNo)) 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 (TransType == TransTypeEnum.LOTInfoGet.GetDescription())
                        {
                            sql = @"IF 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("WMSAPIInfo039"), "{2}") + @"',16,1);
                                        RETURN
                                    END
                                    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
                                    " + sql;

                            columns = @"a.Quantity,";

                            tableName = @" ICSInventoryLot a
                                    INNER JOIN ICSExtension ext ON ext.ID=a.ExtensionID AND ext.WorkPoint=a.WorkPoint";
                        }
                        //出库条码
                        else if (isOut)
                        {

                            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;

                                columns = @"a.Quantity,
                                    a.Quantity*(lot.Amount/lot.Quantity) AS Amount,
                                    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";
                                LotDetail = $@"LEFT JOIN ICSInventoryDetail detail ON inv.InvCode= detail.INVCode AND a.WarehouseCode = detail.WHCode  AND a.WorkPoint = detail.WorkPoint ";
                                con = "detail.LocationCode AS Area,";
                            }
                            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.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 = @"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(TransType == TransTypeEnum.MTDOC.GetDescription())
                        //{

                        //}

                        //入库条码
                        else
                        {

                            if (ScanType == "LOTNO")
                            {
                                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('" + string.Format(language.GetNameByCode("WMSAPIInfo039"), "{2}") + @"', 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;



                                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);
                                LotType = dt.Rows[0]["Type"].ToString();

                                if (mode != null)
                                {
                                    if (mode.itemCode.Equals("LocationRemind01"))
                                    {
                                        columnsWHNAME = @"
                                                (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,";



                                    }
                                    else if (mode.itemCode.Equals("LocationRemind02"))
                                    {
                                        columnsWHNAME = @"
                                            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,";


                                    }
                                    else
                                    {
                                        columnsWHNAME = @"
                                        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,";

                                    }
                                }
                                else
                                {
                                    columnsWHNAME = @"
                                        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,";
                                }


                                #region 根据条码类型找到单据仓库信息
                                if (LotType.Equals("1"))
                                {//生产退料
                                    columnsWHCODE = @"(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";
                                }
                                else if (LotType.Equals("2"))
                                {//委外退料
                                    columnsWHCODE = @"(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";
                                }
                                else if (LotType.Equals("3"))
                                {//工单
                                    columnsWHCODE = @"(SELECT a.WHCode FROM ICSMO a WHERE a.MOCode=lotdd.TransCode AND a.Sequence=lotdd.TransSequence AND a.WorkPoint=lotdd.WorkPoint) AS WHCode";
                                }
                                else if (LotType.Equals("4"))
                                {//销售退货
                                    columnsWHCODE = @"(SELECT a.WHCode FROM ICSSDN a WHERE a.SDNCode=lotdd.TransCode AND a.Sequence=lotdd.TransSequence AND a.WorkPoint=lotdd.WorkPoint) AS WHCode";
                                }
                                else if (LotType.Equals("5"))
                                {//其他入库
                                    columnsWHCODE = @"(SELECT a.WHCode FROM ICSOtherIn a WHERE a.InCode=lotdd.TransCode AND a.Sequence=lotdd.TransSequence AND a.WorkPoint=lotdd.WorkPoint) AS WHCode";
                                }
                                else if (LotType.Equals("6"))
                                {//归还单
                                    columnsWHCODE = @"(SELECT a.WHCode FROM ICSReturn a WHERE a.ReturnCode=lotdd.TransCode AND a.Sequence=lotdd.TransSequence AND a.WorkPoint=lotdd.WorkPoint) AS WHCode";
                                }
                                else if (LotType.Equals("7"))
                                {//采购到货单
                                    columnsWHCODE = @"(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";
                                }
                                else if (LotType.Equals("8"))
                                {//委外到货单
                                    columnsWHCODE = @"(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";
                                }
                                else if (LotType.Equals("9"))
                                {//成品入库单
                                    columnsWHCODE = @"(SELECT a.WHCode FROM ICSManufactureReceive a WHERE a.RCVCode=lotdd.TransCode AND a.Sequence=lotdd.TransSequence AND a.WorkPoint=lotdd.WorkPoint) AS WHCode";
                                }
                                else if (LotType.Equals("10"))
                                {//拒收单
                                    columnsWHCODE = @"(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";
                                }
                                else if (LotType.Equals("11"))
                                {//委外拒收单
                                    columnsWHCODE = @"(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";
                                }
                                else if (LotType.Equals("12"))
                                {//领料申请退料
                                    columnsWHCODE = @"(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";
                                }
                                else if (LotType.Equals("13"))
                                {//材料出库退料
                                    columnsWHCODE = @"(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";
                                }
                                else if (LotType.Equals("14"))
                                {//委外领料申请退料
                                    columnsWHCODE = @"(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";
                                }
                                else if (LotType.Equals("15"))
                                {//委外材料出库退料
                                    columnsWHCODE = @"(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";
                                }
                                else if (LotType.Equals("16"))
                                {//返工工单
                                    columnsWHCODE = @"(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  ";
                                }
                                #endregion

                                columns = @"ISNULL(ins.QualifiedQuantity+ins.WaiveQuantity, a.Quantity) AS Quantity,
                                                a.Quantity*(a.Amount/a.Quantity) AS Amount,
                                                {0},'' AS WHName,
                                                '' AS LocationCode,
                                                {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";
                                LotDetail = $@" LEFT JOIN ICSInventoryDetail detail ON inv.InvCode= detail.INVCode AND  detail.WHCode ={columnsWHCODE.Replace("AS WHCode", " ")}
	                                           AND a.WorkPoint= detail.WorkPoint ";
                                con = " detail.LocationCode AS Area, ";

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


                            }
                            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 = @"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";
                            }

                        }
                    }


                    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, LotDetail, con);

                        table = DBHelper.SQlReturnData(Losql, cmd);
                    }
                    else
                    {
                        sql = string.Format(sql, columns, tableName, JsonData.Code, JsonData.WorkPoint, LotDetail, con);
                        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())
                        {
                            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("WMSAPIInfo043"), Lot, drLot["ProjectCode"]));
                                rowFilter += "AND (LEN(ISNULL(BatchCode,''))<=0 OR (LEN(ISNULL(BatchCode,''))>0 AND BatchCode='" + drLot["BatchCode"] + "'))";
                                CheckTrans(dataView, rowFilter, string.Format(language.GetNameByCode("WMSAPIInfo044"), Lot, drLot["BatchCode"]));
                                rowFilter += "AND (LEN(ISNULL(Version,''))<=0 OR (LEN(ISNULL(Version,''))>0 AND Version='" + drLot["Version"] + "'))";
                                CheckTrans(dataView, rowFilter, string.Format(language.GetNameByCode("WMSAPIInfo045"), Lot, drLot["Version"]));
                                rowFilter += "AND (LEN(ISNULL(Brand,''))<=0 OR (LEN(ISNULL(Brand,''))>0 AND Brand='" + drLot["Brand"] + "'))";
                                CheckTrans(dataView, rowFilter, string.Format(language.GetNameByCode("WMSAPIInfo046"), Lot, drLot["Brand"]));
                                rowFilter += "AND (LEN(ISNULL(cFree1,''))<=0 OR (LEN(ISNULL(cFree1,''))>0 AND cFree1='" + drLot["cFree1"] + "'))";
                                CheckTrans(dataView, rowFilter, string.Format(language.GetNameByCode("WMSAPIInfo047"), Lot, drLot["cFree1"]));
                                rowFilter += "AND (LEN(ISNULL(cFree2,''))<=0 OR (LEN(ISNULL(cFree2,''))>0 AND cFree2='" + drLot["cFree2"] + "'))";
                                CheckTrans(dataView, rowFilter, string.Format(language.GetNameByCode("WMSAPIInfo048"), Lot, drLot["cFree2"]));
                                rowFilter += "AND (LEN(ISNULL(cFree3,''))<=0 OR (LEN(ISNULL(cFree3,''))>0 AND cFree3='" + drLot["cFree3"] + "'))";
                                CheckTrans(dataView, rowFilter, string.Format(language.GetNameByCode("WMSAPIInfo049"), Lot, drLot["cFree3"]));
                                rowFilter += "AND (LEN(ISNULL(cFree4,''))<=0 OR (LEN(ISNULL(cFree4,''))>0 AND cFree4='" + drLot["cFree4"] + "'))";
                                CheckTrans(dataView, rowFilter, string.Format(language.GetNameByCode("WMSAPIInfo050"), Lot, drLot["cFree4"]));
                                rowFilter += "AND (LEN(ISNULL(cFree5,''))<=0 OR (LEN(ISNULL(cFree5,''))>0 AND cFree5='" + drLot["cFree5"] + "'))";
                                CheckTrans(dataView, rowFilter, string.Format(language.GetNameByCode("WMSAPIInfo051"), Lot, drLot["cFree5"]));
                                rowFilter += "AND (LEN(ISNULL(cFree6,''))<=0 OR (LEN(ISNULL(cFree6,''))>0 AND cFree6='" + drLot["cFree6"] + "'))";
                                CheckTrans(dataView, rowFilter, string.Format(language.GetNameByCode("WMSAPIInfo052"), Lot, drLot["cFree6"]));
                                rowFilter += "AND (LEN(ISNULL(cFree7,''))<=0 OR (LEN(ISNULL(cFree7,''))>0 AND cFree7='" + drLot["cFree7"] + "'))";
                                CheckTrans(dataView, rowFilter, string.Format(language.GetNameByCode("WMSAPIInfo053"), Lot, drLot["cFree7"]));
                                rowFilter += "AND (LEN(ISNULL(cFree8,''))<=0 OR (LEN(ISNULL(cFree8,''))>0 AND cFree8='" + drLot["cFree8"] + "'))";
                                CheckTrans(dataView, rowFilter, string.Format(language.GetNameByCode("WMSAPIInfo054"), Lot, drLot["cFree8"]));
                                rowFilter += "AND (LEN(ISNULL(cFree9,''))<=0 OR (LEN(ISNULL(cFree9,''))>0 AND cFree9='" + drLot["cFree9"] + "'))";
                                CheckTrans(dataView, rowFilter, string.Format(language.GetNameByCode("WMSAPIInfo055"), Lot, drLot["cFree9"]));
                                rowFilter += "AND (LEN(ISNULL(cFree10,''))<=0 OR (LEN(ISNULL(cFree10,''))>0 AND cFree10='" + drLot["cFree10"] + "'))";
                                CheckTrans(dataView, rowFilter, string.Format(language.GetNameByCode("WMSAPIInfo056"), Lot, drLot["cFree10"]));
                                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;
                                }
                                //先进先出判断
                                var result = CanOut(Lot, JsonData.WorkPoint, JsonData.ScanLotCode, 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 void CheckTrans(DataView dataView, string rowFilter, string message)
        {
            dataView.RowFilter = rowFilter;
            if (dataView == null || dataView.Count <= 0)
                throw new Exception(message);
        }
        #endregion

        /// <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;
                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"));//"单据类型不存在!"
                        }
                        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, 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())
                                {
                                    //更新源头单据数量
                                    ICSManufactureService.MOIssueDocNegative(TransType, itemInfo.LogID, itemInfo.LotNo, itemInfo.Quantity, item.WorkPoint, cmd, language);
                                    BusinessCode = TransTypeEnum.MOIssueDocNegative.GetDescription<DBValue>();
                                }
                                #endregion
                                #region 生产入库
                                else if (TransType == TransTypeEnum.ManufactureReceiveDoc.GetDescription())
                                {
                                    //更新源头单据数量
                                    //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
                                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);
                            }
                        }

                        #region 拆卸单
                        if (TransType == TransTypeEnum.DisassemblyDoc.GetDescription())
                        {
                            //更新套件锁定数量
                            ICSWareHouseService.DisassemblyDoc(Identification, cmd, language);
                        }
                        #endregion}
                    }
                    //上传ERP
                    if (Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["UploadERP"]))
                    {
                        //采购入库
                        if (TransType == TransTypeEnum.PurchaseReceiveDoc.GetDescription())
                            ICSPurchaseService.PurchaseReceiveDocERP(TransType, Identification, cmd, language, BusinessCode);
                        //审核的到货单
                        else if (TransType == TransTypeEnum.DeliveryNotice.GetDescription())
                            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.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);
                    }
                    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 LOTStockCreateHG(LOTStockUpHGModel 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;
                string BusinessCode = string.Empty;
                try
                {
                    string TransType = string.Empty;
                    string Identification = Guid.NewGuid().ToString();
                    TransType = JsonData.DATA.Head[0].TransType;
                    if (!EnumHelper.HasDescriptions(typeof(TransTypeEnum), TransType))
                    {
                        throw new Exception(LanguageHelper.GetNameSingle("WMSAPIInfo003"));//"单据类型不存在!"
                    }
                    string WHTransType = "2";
                    foreach (var itemInfo in JsonData.DATA.Detail)
                    {
                        #region 审核的到货单
                        if (TransType == TransTypeEnum.DeliveryNotice.GetDescription())
                        {
                            //更新源头单据数量
                            ICSPurchaseService.DeliveryNoticeIn(itemInfo.LotNo, itemInfo.Quantity, JsonData.DATA.Head[0].WorkPoint, cmd, language);
                            BusinessCode = TransTypeEnum.DeliveryNotice.GetDescription<DBValue>();
                        }
                        #endregion
                        else
                        {
                            throw new Exception(LanguageHelper.GetNameSingle("WMSAPIInfo003"));//"单据类型不存在!"
                        }
                        //入库
                        ICSWareHouseLotInfoService.WareHouseLotInfoUp(Identification, itemInfo.LocationCode, itemInfo.LotNo, itemInfo.Quantity,
                            itemInfo.User, JsonData.DATA.Head[0].WorkPoint, WHTransType, BusinessCode, cmd, language, itemInfo.LogID, itemInfo.InvCode + itemInfo.WarehouseCode);
                    }
                    //上传ERP
                    if (Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["UploadERP"]))
                    {
                        //审核的到货单
                        if (TransType == TransTypeEnum.DeliveryNotice.GetDescription())
                            ICSPurchaseService.DeliveryNoticeInERP(TransType, Identification, cmd, language, BusinessCode);
                    }
                    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 LOTStockChangeForkLift(LOTStockForkLiftModel 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;
                string BusinessCode = string.Empty;
                try
                {
                    string TransType = string.Empty;
                    string Identification = Guid.NewGuid().ToString();
                    TransType = JsonData.TaskType;
                    if (TransType == "PTWY")
                    {
                        //更新源头单据数量
                        ICSPurchaseService.DeliveryNoticeForkLift(JsonData.PalletID, cmd, language);
                        BusinessCode = TransTypeEnum.DeliveryNotice.GetDescription<DBValue>();
                        //入库
                        ICSWareHouseLotInfoService.WareHouseLotInfoUpForkLift(Identification, JsonData.DestBin, JsonData.PalletID,
                            "叉车", "采购入库-采购到货单", "2", cmd, language);
                    }
                    //上传ERP
                    if (Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["UploadERP"]))
                    {
                        //审核的到货单
                        if (TransType == TransTypeEnum.DeliveryNotice.GetDescription())
                            ICSPurchaseService.DeliveryNoticeInERP(TransType, Identification, cmd, language, "2");
                    }
                    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;
                string BusinessCode = string.Empty;
                try
                {
                    string TransType = string.Empty;
                    string Identification = Guid.NewGuid().ToString();
                    string SAPGZCode = string.Empty;
                    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);
                            }
                        }
                        #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);

                            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, 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);
                            }
                        }
                        #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);

                            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, 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, 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, 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, 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);

                            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, MergeID);
                            }
                        }
                        #endregion
                        #region 领料申请单确认(更新确认人员到单据)
                        else if (TransType == TransTypeEnum.MOApplyToSAP.GetDescription())
                        {
                            //记录过账人员编码到单据表的MUSERNAME字段
                            ICSManufactureService.MOApplySaveUser(item.TransCode, item.User, item.WorkPoint, cmd, language);
                        }
                        #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);

                            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, 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, 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, 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);
                            }
                        }
                        #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);
                            }
                        }
                        #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, 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())
                            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())
                            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())
                            ICSWareHouseService.OtherOutDocERP(TransType, Identification, cmd, language, BusinessCode);
                        //领料申请单发料
                        if (TransType == TransTypeEnum.MOApply.GetDescription())
                            ICSManufactureService.MOApplyERP(TransType, Identification, cmd, language, BusinessCode);
                        //领料申请单发料(过账SAP)
                        if (TransType == TransTypeEnum.MOApplyToSAP.GetDescription())
                            ICSManufactureService.MOApplySAPGZ(JsonData[0].TransCode, JsonData[0].User, JsonData[0].WorkPoint, cmd, language);
                        //委外领料申请单发料
                        if (TransType == TransTypeEnum.OOApply.GetDescription())
                            ICSOutsourcingService.OOApplyERP(TransType, Identification, cmd, language, BusinessCode);
                        //开立材料出库
                        if (TransType == TransTypeEnum.MOIssue.GetDescription())
                            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 LOTStockDownHGCreate(LOTStockDownHGModel JsonData, object InputJson)
        {
            String PrintEnable = "";
            var language = LanguageHelper.GetName("WMSAPIInfo");
            if (JsonData == null)
            {
                throw new Exception(language.GetNameByCode("WMSAPIInfo007"));//"传送数据为空!"
            }
            List<LOTStockDownHGModel> model = new List<LOTStockDownHGModel>();
            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;
                string BusinessCode = string.Empty;
                try
                {
                    string TransType = string.Empty;
                    string Identification = Guid.NewGuid().ToString();
                    string SAPGZCode = string.Empty;
                    TransType = JsonData.DATA.EXP_ORDINI[0].ORD_DES;
                    if (!EnumHelper.HasDescriptions(typeof(TransTypeEnum), TransType))
                    {
                        throw new Exception(LanguageHelper.GetNameSingle("WMSAPIInfo003"));//"单据类型不存在!"
                    }
                    else if (string.IsNullOrEmpty(JsonData.DATA.EXP_ORDINI[0].ORD_ORDINE))
                    {
                        throw new Exception(language.GetNameByCode("WMSAPIInfo001"));//"单据号不能为空!"
                    }
                    string[] trans = JsonData.DATA.EXP_ORDINI[0].ORD_ORDINE.Split('~');
                    string MergeID = "";
                    if (trans.Length == 2)
                    {
                        MergeID = trans[0];
                        JsonData.DATA.EXP_ORDINI[0].ORD_ORDINE = trans[1];
                    }
                    #region 审核的到货单
                    if (TransType == TransTypeEnum.DeliveryNotice.GetDescription())
                    {
                        foreach (var itemInfo in JsonData.DATA.EXP_ORDINI_RIGHE_STO)
                        {
                            //更新源头单据数量
                            ICSPurchaseService.DeliveryNoticeIn(itemInfo.STO_EFF_SUB1, itemInfo.STO_QTAR, JsonData.DATA.EXP_ORDINI[0].ORD_CLIENTE, cmd, language);
                            BusinessCode = TransTypeEnum.DeliveryNotice.GetDescription<DBValue>();
                            //入库
                            ICSWareHouseLotInfoService.WareHouseLotInfoUpForHG(Identification, itemInfo.STO_EFF_SUB1, itemInfo.STO_QTAR,
                                itemInfo.STO_EXE_OPERATORE, JsonData.DATA.EXP_ORDINI[0].ORD_CLIENTE, itemInfo.STO_CORRIDOIO, "2", BusinessCode, cmd, language);
                        }
                    }
                    #endregion
                    #region 采购退货
                    else if (TransType == TransTypeEnum.PurchaseReceiveDoctNegative.GetDescription())
                    {
                        BusinessCode = TransTypeEnum.PurchaseReceiveDoctNegative.GetDescription<DBValue>();

                        foreach (var itemInfo in JsonData.DATA.EXP_ORDINI_RIGHE_STO)
                        {
                            //更新源头单据数量
                            ICSPurchaseService.PurchaseReceiveDoctNegative(JsonData.DATA.EXP_ORDINI[0].ORD_ORDINE, itemInfo.STO_HOSTINF, itemInfo.STO_QTAR, JsonData.DATA.EXP_ORDINI[0].ORD_ORDINE, cmd, language);
                            //出库
                            printTable = ICSWareHouseLotInfoService.WareHouseLotInfoDown(Identification, JsonData.DATA.EXP_ORDINI[0].ORD_ORDINE, itemInfo.STO_HOSTINF, itemInfo.STO_EFF_SUB1, itemInfo.STO_EFF_QTA,
                                itemInfo.STO_EXE_OPERATORE, JsonData.DATA.EXP_ORDINI[0].ORD_CLIENTE, "3", TransTypeEnum.PurchaseReceiveDoctNegative.GetDescription<DBValue>(), cmd, language);
                        }
                    }
                    #endregion
                    #region 领料申请单发料
                    else if (TransType == TransTypeEnum.MOApply.GetDescription())
                    {
                        BusinessCode = TransTypeEnum.MOApply.GetDescription<DBValue>();

                        foreach (var itemInfo in JsonData.DATA.EXP_ORDINI_RIGHE_STO)
                        {
                            //更新源头单据数量
                            ICSManufactureService.MOApply(JsonData.DATA.EXP_ORDINI[0].ORD_ORDINE, itemInfo.STO_HOSTINF, itemInfo.STO_QTAR, JsonData.DATA.EXP_ORDINI[0].ORD_CLIENTE, cmd, language);
                            //出库
                            printTable = ICSWareHouseLotInfoService.WareHouseLotInfoDown(Identification, JsonData.DATA.EXP_ORDINI[0].ORD_ORDINE, itemInfo.STO_HOSTINF, itemInfo.STO_EFF_SUB1, itemInfo.STO_EFF_QTA,
                                itemInfo.STO_EXE_OPERATORE, JsonData.DATA.EXP_ORDINI[0].ORD_CLIENTE, "3", TransTypeEnum.MOApply.GetDescription<DBValue>(), cmd, language, MergeID);
                        }
                    }
                    #endregion
                    #region 委外领料申请单发料
                    else if (TransType == TransTypeEnum.OOApply.GetDescription())
                    {
                        BusinessCode = TransTypeEnum.OOApply.GetDescription<DBValue>();

                        foreach (var itemInfo in JsonData.DATA.EXP_ORDINI_RIGHE_STO)
                        {
                            //更新源头单据数量
                            ICSOutsourcingService.OOApply(JsonData.DATA.EXP_ORDINI[0].ORD_ORDINE, itemInfo.STO_HOSTINF, itemInfo.STO_QTAR, JsonData.DATA.EXP_ORDINI[0].ORD_CLIENTE, cmd, language);
                            //出库
                            printTable = ICSWareHouseLotInfoService.WareHouseLotInfoDown(Identification, JsonData.DATA.EXP_ORDINI[0].ORD_ORDINE, itemInfo.STO_HOSTINF, itemInfo.STO_EFF_SUB1, itemInfo.STO_EFF_QTA,
                                itemInfo.STO_EXE_OPERATORE, JsonData.DATA.EXP_ORDINI[0].ORD_CLIENTE, "3", TransTypeEnum.OOApply.GetDescription<DBValue>(), cmd, language, 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);
                        //领料申请单发料
                        if (TransType == TransTypeEnum.MOApply.GetDescription())
                            ICSManufactureService.MOApplyERP(TransType, Identification, cmd, language, BusinessCode);
                        //委外领料申请单发料
                        if (TransType == TransTypeEnum.OOApply.GetDescription())
                            ICSOutsourcingService.OOApplyERP(TransType, Identification, cmd, language, BusinessCode);
                        //审核的到货单
                        if (TransType == TransTypeEnum.DeliveryNotice.GetDescription())
                            ICSPurchaseService.DeliveryNoticeInERP(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);
                    #region 保存传入JSON及报错信息
                    string errorsql = @"Insert into ICSHG_WMSEorrorLog
                                        Values
                                        (NEWID(),'{0}','{1}','{2}','{3}',GETDATE(),'{4}','{4}','{5}','未完成','','')";
                    errorsql = string.Format(errorsql, JsonData.DATA.EXP_ORDINI[0].ORD_ORDINE, JsonData.DATA.EXP_ORDINI[0].ORD_DES, InputJson
                                           , ex.Message, JsonData.DATA.EXP_ORDINI_RIGHE_STO[0].STO_EXE_OPERATORE, JsonData.DATA.EXP_ORDINI[0].ORD_CLIENTE);
                    DBHelper.ExecuteNonQuery(connString, CommandType.Text, errorsql);
                    #endregion
                    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;
                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")); //"到货单信息创建失败!");
                        }
                        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;
                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, b.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=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.DNCode='{0}' and b.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 + "',";
                        }
                        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();
                }
            }
        }

        #endregion

        #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;
                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"));//"委外退料单信息创建失败!");
                        }
                        foreach (var itemInfo in item.detail)
                        {
                            //创建子表
                            sql = @"INSERT INTO ICSOApplyNegDetail(ID,OApplyNegCode,Sequence,SourceDetailID,InvCode,
                                        Quantity,Amount,IssueNegQuantity,ExtensionID,MUSER,
                                        MUSERName,MTIME,WorkPoint,EATTRIBUTE)
                                        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;
                try
                {
                    string sql = string.Empty;
                    string Code = string.Empty;
                    string ids = 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();
                        }
                        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,EATTRIBUTE)
                                        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"));//"委外退料单子表信息修改失败!");
                            }
                        }
                        //校验退料数量是否超出领料数量
                        sql = CheckOutsourcingIssueDoc(item.Type, Code, item.WorkPoint, language);
                        DBHelper.ExecuteNonQuery(sql, cmd);
                        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 OutsourcingIssueDoNegativeApplyApprove(List<ICSUser> 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 ids = string.Empty;
                    foreach (var item in JsonData)
                    {
                        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"));//"操作时间不能为空!");
                        }

                        //获取单号
                        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 + "',";
                    }
                    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;
                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")); //"到货单信息创建失败!");
                        }
                        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;
                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();
                }
            }
        }

        #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;
                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"));//"生产退料单信息创建失败!");
                        }
                        foreach (var itemInfo in item.detail)
                        {
                            //创建子表
                            sql = @"INSERT INTO ICSMOApplyNegDetail(ID,ApplyNegCode,Sequence,SourceDetailID,InvCode,
                                        Quantity,Amount,IssueNegQuantity,ExtensionID,MUSER,
                                        MUSERName,MTIME,WorkPoint,EATTRIBUTE)
                                        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"));//"生产退料单子表信息创建失败!");
                            }
                        }
                        //校验退料数量是否超出领料数量
                        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;
                try
                {
                    string sql = string.Empty;
                    string Code = string.Empty;
                    string ids = 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();
                        }
                        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,EATTRIBUTE)
                                        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"));//"生产退料单子表信息修改失败!");
                            }
                        }
                        //校验退料数量是否超出领料数量
                        sql = CheckMOIssueDoc(item.Type, item.ID, item.WorkPoint, language);
                        DBHelper.ExecuteNonQuery(sql, cmd);
                        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();
                }
            }
        }

        /// <summary>
        /// 生产退料审核
        /// </summary>
        /// <param name="JsonData"></param>
        /// <returns></returns>
        public static DataTable MOIssueDocNegativeApplyApprove(List<ICSUser> 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 ids = string.Empty;
                    foreach (var item in JsonData)
                    {
                        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"));//"操作时间不能为空!");
                        }

                        //获取单号
                        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 + "',";
                    }
                    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;
                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);
                        }
                    }
                    //上传ERP
                    if (Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["UploadERP"]))
                    {
                        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;
                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)
                        {

                            var tranferWorkpoint=string.Empty;
                            var checksql= $@"SELECT
	                             top 1 a.EATTRIBUTE1 
                            FROM
	                            ICSTransfer a 
                            WHERE
	                            TransferNO = '{item.TransCode}' 
	                            AND Sequence = '{item.TransSequence}' 
	                            AND WorkPoint = '{item.WorkPoint}' 
	                            AND Type = '{item.TransType}'";
                            var workPoint=DBHelper.ExecuteScalar(checksql, cmd);
                            if (workPoint == null)
                            {
                                tranferWorkpoint = item.WorkPoint;
                            }
                            else 
                            {
                                tranferWorkpoint = workPoint.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 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, tranferWorkpoint, 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, item.TransType, TransTypeEnum.OneStepTransferDocIn.GetDescription<DBValue>(), cmd, language, MergeID);
                        }
                    }
                    //上传ERP
                    if (Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["UploadERP"]))
                    {
                        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;
                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 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;
                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;
                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
                                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);

                            //更新条码信息
                            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.StepTransferApplicationERP(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 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;
                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");
            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 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, "5",
                            TransTypeEnum.LOTMergeBefore.GetDescription<DBValue>(), cmd, language);

                        foreach (var info in item.detail)
                        {
                            //合并前日志
                            ICSWareHouseLotInfoService.WareHouseLotInfoLog(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);
                        }

                        //合并后日志
                        ICSWareHouseLotInfoService.WareHouseLotInfoLog(Identification, item.LotNo, item.User, item.WorkPoint, "5",
                            TransTypeEnum.LOTMergeAfter.GetDescription<DBValue>(), cmd, language);
                    }
                    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");
            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 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)
                        {
                            //更新条码信息
                            ICSWareHouseLotInfoService.WareHouseLotInfoSplit(Identification, item.LotNo, info.CurrentLotNo, info.CurrentQuantity, item.User, item.WorkPoint, "4",
                                TransTypeEnum.LOTSplitAfter.GetDescription<DBValue>(), cmd, language);
                        }

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

                    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, SqlCommand cmd, Dictionary<string, string> language)
        {
            try
            {
                //根据Sys_SRM_Items.F_Description备注列维护的提前天数,比如维护的是1,最早条码是2022.5.16,现在扫描2022.5.17的条码也能出库,扫描2022.5.18的条码不能直接出,需要校验以下逻辑
                string 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
	                                WHERE  a.WorkPoint='{1}' AND ISNULL(a.Quantity,0)>0  AND 1=1
	                                AND CONVERT(varchar(100), a.InDate, 23)<
	                                (SELECT DATEADD(DAY, -@Days, CONVERT(varchar(100), x.InDate, 23)) FROM ICSWareHouseLotInfo x
		                                INNER JOIN ICSInventoryLot y ON x.LotNO=y.LotNO AND x.WorkPoint=y.WorkPoint
		                                WHERE x.LotNO='{0}' AND x.WorkPoint='{1}' AND y.INVCode=b.INVCode AND y.ExtensionID=b.ExtensionID)
                                )
                                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 - 限制
                sql = string.Format(sql, LotNo, WorkPoitCode);
                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 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;
                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;
                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;
                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}','2',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;
                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)
                        {
                            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()
                                            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()
                                            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()
                                            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)
                                            SELECT  NEWID(),c.ID,a.LotNo,a.Quantity,'0','{4}','0','0','0','0','0',b.F_Account,b.F_RealName,GETDATE(),a.WorkPoint
                                            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)
                                            SELECT  NEWID(),c.ID,a.LotNo,a.Quantity,'0','0','0','0','0','{4}','0',b.F_Account,b.F_RealName,GETDATE(),a.WorkPoint
                                            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)
                                            SELECT  NEWID(),c.ID,a.LotNo,a.Quantity,'0','0','0','{4}','0','0','0',b.F_Account,b.F_RealName,GETDATE(),a.WorkPoint
                                            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"));//"盘点扫描创建失败!");
                            }

                            #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;
                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;
                try
                {
                    string sql = @"IF NOT EXISTS(SELECT LocationCode FROM ICSLocation a where LocationCode='{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='{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='{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='{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();
                }
            }
        }
        #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;
                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 用户确认
        public static object UserCheck(Sys_SRM_User userModel)
        {
            using (SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString))
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = conn;
                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 json = JsonConvert.SerializeObject(dt);
                            List<Sys_SRM_User> userLogOnEntity = JsonConvert.DeserializeObject<List<Sys_SRM_User>>(json);
                            return userLogOnEntity;
                        }
                    }
                    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;
                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 Result ContainerBindCreate(List<ICSContainerBind> JsonData)
        {
            var language = LanguageHelper.GetName("WMSAPIInfo");
            DataTable table = new DataTable();
            string msg = "";
            using (SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString))
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = conn;
                try
                {
                    Result res = new Result();
                    foreach (ICSContainerBind item in JsonData)
                    {
                        string TransType = item.TransType;
                        if (JsonData.Count <= 0)
                        {
                            msg = string.Format(language.GetNameByCode("WMSAPIInfo007"));//"传入数据为空!"
                        }
                        if (String.IsNullOrEmpty(item.WorkPoint))
                        {
                            msg = string.Format(language.GetNameByCode("WMSAPIInfo004"));//"站点不能为空!"
                        }
                        if (String.IsNullOrEmpty(item.LotNo))
                        {
                            msg = string.Format(language.GetNameByCode("WMSAPIInfo005"));//"条码不能为空!"
                        }
                        if (String.IsNullOrEmpty(item.ContainerCode))
                        {
                            msg = string.Format(language.GetNameByCode("WMSAPIInfo197"));//"料架不能为空!"
                        }
                        if (TransType != TransTypeEnum.ContainerBind.GetDescription() && TransType != TransTypeEnum.ContainerUnBind.GetDescription())
                        {
                            msg = string.Format(language.GetNameByCode("WMSAPIInfo199"));//"操作类型错误!"
                        }
                        if (item.ContainerType == "窄巷道叉车(木托盘)" && item.RecomendBinCode == "")
                        {
                            msg = string.Format(language.GetNameByCode("WMSAPIInfo203"));//"推荐库位不能为空!"
                        }
                        if (item.LocationCode == "" && item.ContainerType != "窄巷道叉车(木托盘)")
                        {
                            msg = string.Format(language.GetNameByCode("WMSAPIInfo206"));//"位置编码不能为空!"
                        }
                        if (msg != "")
                        {
                            res.Success = false;
                            res.Message = msg;// "接口调用失败!";
                            return res;
                        }
                        else
                        {
                            if (TransType == TransTypeEnum.ContainerBind.GetDescription())
                            {
                                //料架条码绑定
                                ICSWareHouseLotInfoService.ContainerBind(item.LotNo, item.ContainerCode, item.ContainerType, item.LocationCode, item.RecomendBinCode, item.User, item.WorkPoint, cmd, language);
                            }
                            else
                            {
                                //料架条码解绑
                                ICSWareHouseLotInfoService.ContainerUnBind(item.ContainerCode, item.WorkPoint, cmd, language);
                            }
                        }
                    }
                    res.Success = true;
                    res.Message = msg;// "接口调用成功!";
                    return res;
                }
                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 通知AGV搬运
        public static Result StartAGVTask(List<ICSContainerBind> JsonData)
        {
            var language = LanguageHelper.GetName("WMSAPIInfo");
            DataTable table = new DataTable();
            string msg = "";
            using (SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString))
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = conn;
                try
                {
                    Result res = new Result();
                    foreach (ICSContainerBind item in JsonData)
                    {
                        string TransType = item.TransType;
                        if (JsonData.Count <= 0)
                        {
                            msg = string.Format(language.GetNameByCode("WMSAPIInfo007"));//"传入数据为空!"
                        }
                        if (String.IsNullOrEmpty(item.WorkPoint))
                        {
                            msg = string.Format(language.GetNameByCode("WMSAPIInfo004"));//"站点不能为空!"
                        }
                        if (item.LocationCode == "")
                        {
                            msg = string.Format(language.GetNameByCode("WMSAPIInfo206"));//"位置编码不能为空!"
                        }
                        if (msg != "")
                        {
                            res.Success = false;
                            res.Message = msg;// "接口调用失败!";
                            return res;
                        }
                        else
                        {
                            //呼叫AGV开始搬运任务
                            ICSWareHouseLotInfoService.CallAGVStartTask(item.ContainerCode, item.TransType, item.LocationCode, item.User, item.WorkPoint, cmd, language);
                        }
                    }
                    res.Success = true;
                    res.Message = msg;// "接口调用成功!";
                    return res;
                }
                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 获取AGV绑定接口地址
        public static string GetAGVBindUrl()
        {
            try
            {
                return ERPUrl.AGVBineURL;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        #endregion 

        #region 获取AGV搬运接口地址
        public static string GetAGVStartUrl()
        {
            try
            {
                return ERPUrl.AGVTaskStart;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        #endregion 

        #region 获取AGV搬运的目标位置
        public static Result GetAGVTaskPosition(List<ICSContainerBind> JsonData)
        {
            var language = LanguageHelper.GetName("WMSAPIInfo");
            DataTable table = new DataTable();
            string msg = "";
            using (SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString))
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = conn;
                try
                {
                    Result res = new Result();
                    string PostionCode = "";
                    foreach (ICSContainerBind item in JsonData)
                    {
                        string TransType = item.TransType;
                        if (JsonData.Count <= 0)
                        {
                            msg = string.Format(language.GetNameByCode("WMSAPIInfo007"));//"传入数据为空!"
                        }
                        if (String.IsNullOrEmpty(item.WorkPoint))
                        {
                            msg = string.Format(language.GetNameByCode("WMSAPIInfo004"));//"站点不能为空!"
                        }
                        if (item.LocationCode == "")
                        {
                            msg = string.Format(language.GetNameByCode("WMSAPIInfo206"));//"位置编码不能为空!"
                        }
                        if (msg != "")
                        {
                            res.Success = false;
                            res.Message = msg;// "接口调用失败!";
                            return res;
                        }
                        else
                        {
                            //呼叫AGV开始搬运任务
                            PostionCode = ICSWareHouseLotInfoService.GetAGVTaskPosition(item.LocationCode, item.User, item.WorkPoint, cmd, language);
                        }
                    }
                    res.Success = true;
                    res.Message = PostionCode;// "接口调用成功!";
                    return res;
                }
                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 MTTransInformationGet(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;
                try
                {
                    if (string.IsNullOrEmpty(JsonData.TransCode))
                    {
                        throw new Exception(language.GetNameByCode("WMSAPIInfo001"));//"单据号不能为空!"
                    }
                    else if (string.IsNullOrEmpty(JsonData.WorkPoint))
                    {
                        throw new Exception(language.GetNameByCode("WMSAPIInfo004"));//"站点不能为空!"
                    }
                    string information = String.Format(language.GetNameByCode("WMSAPIInfo035"), "", "", "", JsonData.TransCode);
                    #region SLQ
                    string sql = $@"IF NOT EXISTS(SELECT a.ID FROM ICSMTDOC a WHERE  a.MTDOCCode= '{JsonData.TransCode}' 
	                               AND a.WorkPoint= '{JsonData.WorkPoint}')
                                    BEGIN 
	                                    RAISERROR('{information}',16,1); 
                                        RETURN 
                                    END ;
                                    SELECT a.ID,
                                    a.MTDOCCode AS TransCode,
                                    a.EATTRIBUTE1 AS Type,
                                    a.MTDOCType,
                                    a.Sequence AS TransSequence,
                                    a.MTDOCQuantity AS IssueQuantity,
                                    convert(varchar(100),'') AS LocationCode,
                                    convert(varchar(100),'') AS LotNo,
                                    convert(varchar(10),'') AS ToWarehouseCode,
									0 AS LocationQty,
                                    0 AS isMatched,
                                    a.INVCode AS 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]
                                    FROM ICSMTDOC a
                                    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  a.MTDOCCode= '{JsonData.TransCode}' 
	                               AND a.WorkPoint= '{JsonData.WorkPoint}' ";
                    #endregion

                    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 GetICSMOPickMergeTemp(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;
                try
                {
                    if (string.IsNullOrEmpty(JsonData.TransCode))
                    {
                        throw new Exception(language.GetNameByCode("WMSAPIInfo001"));//"单据号不能为空!"
                    }
                    else if (string.IsNullOrEmpty(JsonData.WorkPoint))
                    {
                        throw new Exception(language.GetNameByCode("WMSAPIInfo004"));//"站点不能为空!"
                    }
                    string information = String.Format(language.GetNameByCode("WMSAPIInfo035"), "", "", "", JsonData.TransCode);
                    #region SLQ
                    string sqls = "";
                    #region 工单领料
                    if (JsonData.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,c.LocationCode
                        FROM

                            ICSMOApply a
                        LEFT JOIN ICSINVENTORY b ON a.InvCode = b.InvCode AND a.WorkPoint = b.WorkPoint
                        LEFT JOIN ICSInventoryDetail c ON b.InvCode=c.INVCode AND a.WHCode=c.WHCode AND a.WorkPoint=c.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,c.LocationCode ";
                        #endregion
                    }
                    #endregion

                    #region 委外领料
                    if (JsonData.TransType == TransTypeEnum.OOApply.GetDescription())
                    {
                        #region 委外领料SQL
                        sqls = 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,
                            c.LocationCode
                        FROM
	                        ICSOApply a
                        LEFT JOIN ICSINVENTORY b ON a.InvCode = b.InvCode AND a.WorkPoint=b.WorkPoint
                        LEFT JOIN ICSInventoryDetail c ON b.InvCode=c.INVCode AND a.WHCode=c.WHCode AND a.WorkPoint=c.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,c.LocationCode";
                        #endregion
                    }
                    #endregion

                    #region 销售发货
                    if (JsonData.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,
                            c.LocationCode
                        FROM
	                        ICSSDN a
                        LEFT JOIN ICSINVENTORY b ON a.InvCode = b.InvCode AND a.WorkPoint=b.WorkPoint
                        LEFT JOIN ICSInventoryDetail c ON b.InvCode=c.INVCode AND a.WHCode=c.WHCode AND a.WorkPoint=c.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,c.LocationCode";
                        #endregion
                    }
                    #endregion

                    #region 其他出库
                    if (JsonData.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,
                            c.LocationCode
                        FROM
	                        ICSOtherOut a
                        LEFT JOIN ICSINVENTORY b ON a.InvCode = b.InvCode AND a.WorkPoint=b.WorkPoint
                        LEFT JOIN ICSInventoryDetail c ON b.InvCode=c.INVCode AND a.WHCode=c.WHCode AND a.WorkPoint=c.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,c.LocationCode";
                        #endregion
                    }
                    #endregion

                    #region 物料调拨
                    if (JsonData.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,
                            c.LocationCode
                        FROM
	                        ICSTransfer a
                        LEFT JOIN ICSINVENTORY b ON a.InvCode = b.InvCode AND a.WorkPoint=b.WorkPoint
                        LEFT JOIN ICSInventoryDetail c ON b.InvCode=c.INVCode AND a.FromWarehouseCode=c.WHCode AND a.WorkPoint=c.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,c.LocationCode";
                        #endregion
                    }
                    #endregion

                    sqls = string.Format(sqls, JsonData.TransCode.ToString(), JsonData.WorkPoint.ToString());
                    #region sql
                    string sql = $@"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,
	                        c.WHCode AS WarehouseCode, 
	                        d.LotNO,
                            FLOOR(ISNULL(d.Quantity, 0)) AS QTY,
                            d.LocationCode AS LocationCode,
	                        CONVERT(varchar(100),d.MTIME, 23) MTIME,
	                        FLOOR(f.QTYTotal) QTYTotal
                        FROM
                        ({sqls}) c
                        left join (select d.WarehouseCode,d.Quantity,d.INVCode, m.LotNo, d.MTIME,d.LocationCode,m.ExtensionID 
                                     from ICSWareHouseLotInfo d ,ICSInventoryLot m 
					                where d.LotNo=m.LotNo and d.WorkPoint=m.WorkPoint
								      and d.WorkPoint='{JsonData.WorkPoint.ToString()}' AND d.Quantity>0 
                                     --AND SUBSTRING(SUBSTRING(d.LocationCode, CHARINDEX('-',d.LocationCode)+1, LEN(d.LocationCode)),0,CHARINDEX('-', SUBSTRING(d.LocationCode, CHARINDEX('-',d.LocationCode)+1, LEN(d.LocationCode)))) 
                                     --Not IN(SELECT F_Define2 FROM Sys_SRM_ItemsDetail WHERE F_Define3='HGAreaConfig' AND F_Define1=d.WarehouseCode AND F_Define4=d.WorkPoint) 
                                     ) d 
                               on c.InvCode=d.INVCode AND c.WhCode=d.WarehouseCode and d.ExtensionID=c.ExtensionID
                         LEFT JOIN (SELECT INVCode,WarehouseCode,SUM(Quantity) AS QTYTotal FROM ICSWareHouseLotInfo  WHERE WorkPoint='{JsonData.WorkPoint.ToString()}' GROUP BY INVCode,WarehouseCode) f ON c.InvCode=f.INVCode AND c.WhCode=f.WarehouseCode
                     order by c.Code,c.InvCode,d.MTIME ";
                    #endregion   
                    var dataset = DBHelper.SQlReturnDataSet(sql, cmd); 
                    if (dataset.Tables.Count == 0)
                        return null;
                    DataTable table = dataset.Tables[0];
                    decimal qtyCount = 0;
                    bool remove = false;
                    List<int> removeList = new List<int>();
                    for (int i = 0; i < table.Rows.Count; i++)
                    {

                        if (i != 0
                         && (!table.Rows[i]["InvCode"].ToString().Equals(table.Rows[i - 1]["InvCode"].ToString())
                          || !table.Rows[i]["Code"].ToString().Equals(table.Rows[i - 1]["Code"].ToString()))
                         )
                        {
                            qtyCount = 0;
                            remove = false;
                        }
                        if (remove)
                        {
                            removeList.Add(i);
                        }
                        else
                        {
                            var lotQty =decimal.Parse(table.Rows[i]["QTY"].ToString());
                            var orderQty =decimal.Parse( table.Rows[i]["iQuantity"].ToString());
                            qtyCount += lotQty;
                            if (qtyCount >= orderQty)
                            {
                                remove = true;
                            }
                        }
                    }
                    if (removeList.Count > 0)
                    {
                        removeList.Reverse();
                        foreach (var item in removeList)
                        {
                            table.Rows.RemoveAt(item);
                        }
                    }

                    #endregion

                    //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>
        /// 形态转换
        /// <param name="JsonData"></param>
        /// <returns></returns>
        public static DataTable MTDocCreate(List<ICSMTDocModel> 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;
                string BusinessCode = string.Empty;
                try
                {
                    string TransType = string.Empty;
                    string Identification = Guid.NewGuid().ToString();
                    StringBuilder sql = new StringBuilder();
                    foreach (var item in JsonData)
                    {
                        foreach (var data in item.DetailModels)
                        {
                            //修改源头单据
                            ICSWareHouseService.MTDoc(item.TransCode, item.TransSequence, data.Quantity, item.WorkPoint, cmd, language);
                            TransType = item.Type;
                            //单据类型 12:按单转移 13:按物料转移
                            if (TransType == "13")
                            {
                                //形态转换
                                sql.Append($@"UPDATE ICSWareHouseLotInfo SET InvCode='{item.AfterInvCode}' WHERE LotNo='{data.LotNo}' AND WorkPoint='{item.WorkPoint}' AND InvCode='{item.BeforInvCode}' AND WarehouseCode='{item.WHCode}';
                                     UPDATE ICSWareHouseLotInfoLog SET InvCode='' WHERE  LotNo='{data.LotNo}' AND WorkPoint='{item.WorkPoint}' AND InvCode='{item.BeforInvCode}' ;
                                     UPDATE ICSInventoryLot SET InvCode='{item.AfterInvCode}' WHERE LotNo='{data.LotNo}' AND InvCode='{item.BeforInvCode}' AND WorkPoint='{item.WorkPoint}'  AND ExtensionID='{item.BeforExtensionID}';");

                            }
                            else if (TransType == "12")
                            {
                                sql.Append($@"UPDATE ICSInventoryLot SET ExtensionID='{item.AfterExtensionID}' WHERE LotNo='{data.LotNo}' AND InvCode='{item.BeforInvCode}' AND WorkPoint='{item.WorkPoint}'  AND ExtensionID='{item.BeforExtensionID}';");
                            }
                            else
                            {
                                throw new Exception("单据类型不存在");
                            }
                        }
                    }
                    DataTable table = DBHelper.SQlReturnData(sql.ToString(), 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();
                }
            }
        }
    }
}