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

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

        #region 销售出库
        /// <summary>
        /// 销售出库
        /// </summary>
        /// <param name="TransCode"></param>
        /// <param name="TransSequence"></param>
        /// <param name="Quantity"></param>
        /// <param name="WorkPoint"></param>
        /// <param name="cmd"></param>
        public static void SalesShipmentDoc(string TransCode, string TransSequence, string Quantity, string WorkPoint, SqlCommand cmd, Dictionary<string, string> language)
        {
            try
            {

                //string chekksql = @"select c.EATTRIBUTE1 FROM ICSSDN  a
                //                INNER JOIN ICSInventory c on a.InvCode=c.InvCode and a.WorkPoint=c.WorkPoint
                //                WHERE a.Sequence='{2}' AND a.SDNCode='{0}' AND a.WorkPoint='{1}' and c.AmountEnable='1'";
                //chekksql = string.Format(chekksql, TransCode, WorkPoint,  TransSequence);
                //DataTable dta = DBHelper.SQlReturnData(chekksql, cmd);
                //if (dta.Rows.Count > 0)
                //{
                //    Quantity = (decimal.Parse(Quantity) * decimal.Parse(dta.Rows[0]["EATTRIBUTE1"].ToString())).ToString();
                //}
                string sql = @"DECLARE @Status VARCHAR(10)
                                SELECT @Status=a.Status FROM ICSSDN  a
                                WHERE a.SDNCode='{0}' AND a.Sequence='{3}' AND a.WorkPoint='{1}' AND  a.Type='1'

                                IF (@Status IS NULL)
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo139") + @"',16,1);
                                    RETURN
                                END
                                ELSE IF (@Status!='2')
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo140") + @"',16,1);
                                    RETURN
                                END
                                UPDATE a SET SDNQuantity=ISNULL(SDNQuantity,0)+'{2}'
                                FROM ICSSDN  a
                                WHERE a.SDNCode='{0}' AND a.Sequence='{3}' AND a.WorkPoint='{1}' AND  a.Type='1'

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

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

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


        /// <summary>
        /// 销售出库
        /// </summary>
        /// <param name="TransCode"></param>
        /// <param name="TransSequence"></param>
        /// <param name="Quantity"></param>
        /// <param name="WorkPoint"></param>
        /// <param name="cmd"></param>
        public static void AMSalesShipmentDoc(string TransCode, string TransSequence, string Quantity, string WorkPoint, SqlCommand cmd, Dictionary<string, string> language)
        {
            try
            {

                string chekksql = @"select c.EATTRIBUTE1 FROM ICSSDN  a
                                INNER JOIN ICSInventory c on a.InvCode=c.InvCode and a.WorkPoint=c.WorkPoint
                                WHERE a.Sequence='{2}' AND a.SDNCode='{0}' AND a.WorkPoint='{1}' and c.AmountEnable='1'";
                chekksql = string.Format(chekksql, TransCode, WorkPoint, TransSequence);
                DataTable dta = DBHelper.SQlReturnData(chekksql, cmd);
                if (dta.Rows.Count > 0)
                {
                    Quantity = (decimal.Parse(Quantity) * decimal.Parse(dta.Rows[0]["EATTRIBUTE1"].ToString())).ToString();
                }
                string sql = @"DECLARE @Status VARCHAR(10)
                                SELECT @Status=a.Status FROM ICSSDN  a
                                WHERE a.SDNCode='{0}' AND a.Sequence='{3}' AND a.WorkPoint='{1}' AND  a.Type='1'

                                IF (@Status IS NULL)
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo139") + @"',16,1);
                                    RETURN
                                END
                                ELSE IF (@Status!='2')
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo140") + @"',16,1);
                                    RETURN
                                END
                                UPDATE a SET SDNQuantity=ISNULL(SDNQuantity,0)+'{2}'
                                FROM ICSSDN  a
                                WHERE a.SDNCode='{0}' AND a.Sequence='{3}' AND a.WorkPoint='{1}' AND  a.Type='1'

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

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

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

        /// <summary>
        /// 销售出库接口
        /// </summary>
        /// <param name="TransType"></param>
        /// <param name="Identification"></param>
        /// <param name="cmd"></param>
        public static void SalesShipmentDocERP(string TransType, string Identification, SqlCommand cmd, Dictionary<string, string> language,string BusinessCode)
        {
            try
            {
                #region ERP
                string sql = @"SELECT b.CusCode+a.FromWarehouseCode+b.SDNCode+a.MUSER AS Costre,b.CusCode,a.FromWarehouseCode AS WarehouseCode,b.SDNCode,a.MUSER,ROW_NUMBER() OVER (ORDER BY b.CusCode,a.FromWarehouseCode,b.SDNCode,b.SDNDetailID,a.InvCode) AS Sequence,
                                    a.InvCode,SUM(a.Quantity) AS Quantity,CASE inv.AmountEnable WHEN '1' THEN SUM(a.Quantity*(b.Amount/b.Quantity)) ELSE '0' END AS Amount, b.SDNDetailID,con.Enable AS UpdateTodoQuantity,conStock.Enable AS UpdateStock
	                            ,a.WorkPoint,ISNULL(ext.ProjectCode, '') AS ProjectCode,CASE WHEN (invBat.BatchEnable IS NULL AND ISNULL(inv.BatchEnable, '0')='1') OR ISNULL(invBat.BatchEnable, '0')='1' THEN ISNULL(ext.BatchCode, '') ELSE '' END AS BatchCode,ISNULL(ext.Version, '') AS Version,ISNULL(ext.Brand, '') AS Brand,
	                            ISNULL(ext.cFree1, '') AS cFree1,ISNULL(ext.cFree2, '') AS cFree2,ISNULL(ext.cFree3, '') AS cFree3,ISNULL(ext.cFree4, '') AS cFree4,ISNULL(ext.cFree5, '') AS cFree5,ISNULL(ext.cFree6, '') AS cFree6,ISNULL(ext.cFree7, '') AS cFree7,ISNULL(ext.cFree8, '') AS cFree8,ISNULL(ext.cFree9, '') AS cFree9,ISNULL(ext.cFree10, '') AS cFree10                                   
                                INTO #TempERP
                                FROM ICSWareHouseLotInfoLog a
                                INNER JOIN ICSInventoryLot lot ON a.LotNo=lot.LotNo AND a.WorkPoint=lot.WorkPoint
                                INNER JOIN ICSExtension ext ON lot.ExtensionID=ext.ID AND lot.WorkPoint=ext.WorkPoint
                                INNER JOIN ICSInventory inv ON a.InvCode=inv.InvCode AND a.WorkPoint=inv.WorkPoint
                                LEFT JOIN ICSInventoryBatchEnable invBat ON a.InvCode=invBat.InvCode AND a.FromWarehouseCode=invBat.WHCode AND a.WorkPoint=invBat.WorkPoint
                                INNER JOIN ICSSDN b ON a.TransCode=b.SDNCode AND a.TransSequence=b.Sequence AND a.WorkPoint=b.WorkPoint
                                INNER JOIN ICSConfiguration con ON con.Code='Stock002' AND a.WorkPoint=con.WorkPoint
INNER JOIN ICSConfiguration conStock ON conStock.Code='UpdateStock005' AND a.WorkPoint=conStock.WorkPoint
                                WHERE a.Identification='{0}' AND  ERPUpload='0' AND  b.Type='1' AND a.BusinessCode = '19' 
                                GROUP BY inv.AmountEnable,b.CusCode,a.FromWarehouseCode,b.SDNCode,a.MUSER,a.InvCode,b.SDNDetailID,con.Enable,conStock.Enable
                                ,a.WorkPoint,ISNULL(ext.ProjectCode, ''),CASE WHEN (invBat.BatchEnable IS NULL AND ISNULL(inv.BatchEnable, '0')='1') OR ISNULL(invBat.BatchEnable, '0')='1' THEN ISNULL(ext.BatchCode, '') ELSE '' END,ISNULL(ext.Version, ''),ISNULL(ext.Brand, ''),
                                ISNULL(ext.cFree1, ''),ISNULL(ext.cFree2, ''),ISNULL(ext.cFree3, ''),ISNULL(ext.cFree4, ''),ISNULL(ext.cFree5, ''),ISNULL(ext.cFree6, ''),ISNULL(ext.cFree7, ''),ISNULL(ext.cFree8, ''),ISNULL(ext.cFree9, ''),ISNULL(ext.cFree10, '')

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

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

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

        public static void U9SalesShipmentDocERP(string TransType, string Identification, SqlCommand cmd, Dictionary<string, string> language, string BusinessCode)
        {
            try
            {
                #region ERP
                string sql = @"SELECT b.CusCode+a.FromWarehouseCode+b.SDNCode+a.MUSER AS Costre,b.CusCode,a.FromWarehouseCode AS WarehouseCode,b.SDNCode,a.MUSER,ROW_NUMBER() OVER (ORDER BY b.CusCode,a.FromWarehouseCode,b.SDNCode,b.SDNDetailID,a.InvCode) AS Sequence,
                                    a.InvCode,SUM(a.Quantity) AS Quantity,CASE inv.AmountEnable WHEN '1' THEN SUM(a.Quantity*(b.Amount/b.Quantity)) ELSE '0' END AS Amount, b.SDNDetailID,con.Enable AS UpdateTodoQuantity,conStock.Enable AS UpdateStock
	                            ,a.WorkPoint,ISNULL(ext.ProjectCode, '') AS ProjectCode,CASE WHEN (invBat.BatchEnable IS NULL AND ISNULL(inv.BatchEnable, '0')='1') OR ISNULL(invBat.BatchEnable, '0')='1' THEN ISNULL(ext.BatchCode, '') ELSE '' END AS BatchCode,ISNULL(ext.Version, '') AS Version,ISNULL(ext.Brand, '') AS Brand,
	                            ISNULL(ext.cFree1, '') AS cFree1,ISNULL(ext.cFree2, '') AS cFree2,ISNULL(ext.cFree3, '') AS cFree3,ISNULL(ext.cFree4, '') AS cFree4,ISNULL(ext.cFree5, '') AS cFree5,ISNULL(ext.cFree6, '') AS cFree6,ISNULL(ext.cFree7, '') AS cFree7,ISNULL(ext.cFree8, '') AS cFree8,ISNULL(ext.cFree9, '') AS cFree9,ISNULL(ext.cFree10, '') AS cFree10 ,b.SOCode,b.SOSequence as SrcDocSubLineNo                                
                                INTO #TempERP
                                FROM ICSWareHouseLotInfoLog a
                                INNER JOIN ICSInventoryLot lot ON a.LotNo=lot.LotNo AND a.WorkPoint=lot.WorkPoint
                                INNER JOIN ICSExtension ext ON lot.ExtensionID=ext.ID AND lot.WorkPoint=ext.WorkPoint
                                INNER JOIN ICSInventory inv ON a.InvCode=inv.InvCode AND a.WorkPoint=inv.WorkPoint
                                LEFT JOIN ICSInventoryBatchEnable invBat ON a.InvCode=invBat.InvCode AND a.FromWarehouseCode=invBat.WHCode AND a.WorkPoint=invBat.WorkPoint
                                INNER JOIN ICSSDN b ON a.TransCode=b.SDNCode AND a.TransSequence=b.Sequence AND a.WorkPoint=b.WorkPoint
                                INNER JOIN ICSConfiguration con ON con.Code='Stock002' AND a.WorkPoint=con.WorkPoint
INNER JOIN ICSConfiguration conStock ON conStock.Code='UpdateStock005' AND a.WorkPoint=conStock.WorkPoint
                                WHERE a.Identification='{0}' AND  ERPUpload='0' AND  b.Type='1' AND a.BusinessCode = '19' 
                                GROUP BY inv.AmountEnable,b.CusCode,a.FromWarehouseCode,b.SDNCode,a.MUSER,a.InvCode,b.SDNDetailID,con.Enable,conStock.Enable
                                ,a.WorkPoint,ISNULL(ext.ProjectCode, ''),CASE WHEN (invBat.BatchEnable IS NULL AND ISNULL(inv.BatchEnable, '0')='1') OR ISNULL(invBat.BatchEnable, '0')='1' THEN ISNULL(ext.BatchCode, '') ELSE '' END,ISNULL(ext.Version, ''),ISNULL(ext.Brand, ''),
                                ISNULL(ext.cFree1, ''),ISNULL(ext.cFree2, ''),ISNULL(ext.cFree3, ''),ISNULL(ext.cFree4, ''),ISNULL(ext.cFree5, ''),ISNULL(ext.cFree6, ''),ISNULL(ext.cFree7, ''),ISNULL(ext.cFree8, ''),ISNULL(ext.cFree9, ''),ISNULL(ext.cFree10, ''),b.SOCode,b.SOSequence

                                SELECT DISTINCT Costre,WorkPoint,CusCode,WarehouseCode AS WHCode,SOCode AS SDNCode,SrcDocSubLineNo,MUSER AS [User],SYSDATETIME() AS ShipDate,'ST1' as ShipDocTypeCode ,cast(0 as bit) as SOIsConsign,UpdateTodoQuantity,UpdateStock,InvCode,Quantity,Amount,SDNDetailID,ProjectCode,BatchCode,Version,Brand,cFree1,cFree2,cFree3,cFree4,cFree5,cFree6,cFree7,cFree8,cFree9,cFree10 FROM #TempERP
                                
                                DROP TABLE #TempERP";
                sql = string.Format(sql, Identification);
                DataSet ds = DBHelper.SQlReturnDataSet(sql, cmd);

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

        #region 销售退货
        /// <summary>
        /// 销售退货
        /// </summary>
        /// <param name="TransCode"></param>
        /// <param name="TransSequence"></param>
        /// <param name="Quantity"></param>
        /// <param name="WorkPoint"></param>
        /// <param name="cmd"></param>
        public static void SalesShipmentDocNegative(string LotNo, string Quantity, string WorkPoint, SqlCommand cmd, Dictionary<string, string> language)
        {
            try
            {
                string sql = @"DECLARE @Status VARCHAR(10)
                                SELECT @Status=c.Status FROM ICSInventoryLot a
                                INNER JOIN ICSInventoryLotDetail b ON a.LotNo=b.LotNo AND a.WorkPoint=b.WorkPoint
                                INNER JOIN ICSSDN c ON b.TransCode=c.SDNCode AND b.TransSequence=c.Sequence AND b.WorkPoint=c.WorkPoint
                                WHERE a.LotNo='{0}' AND a.WorkPoint='{1}' AND c.Type='2'

                                IF (@Status IS NULL)
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo081") + @"',16,1);
                                    RETURN
                                END
                                ELSE IF (@Status!='2')
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo142") + @"',16,1);
                                    RETURN
                                END
                                UPDATE c SET SDNQuantity=ISNULL(SDNQuantity,0)+'{2}'
                                FROM ICSInventoryLot a
                                INNER JOIN ICSInventoryLotDetail b ON a.LotNo=b.LotNo AND a.WorkPoint=b.WorkPoint
                                INNER JOIN ICSSDN c ON b.TransCode=c.SDNCode AND b.TransSequence=c.Sequence AND b.WorkPoint=c.WorkPoint
                                WHERE a.LotNo='{0}' AND a.WorkPoint='{1}' AND c.Type='2'
                                IF EXISTS(SELECT a.LotNo FROM ICSInventoryLot a
                                    INNER JOIN ICSInventoryLotDetail b ON a.LotNo=b.LotNo AND a.WorkPoint=b.WorkPoint
                                    INNER JOIN ICSSDN c ON b.TransCode=c.SDNCode AND b.TransSequence=c.Sequence AND b.WorkPoint=c.WorkPoint
                                    WHERE a.LotNo='{0}' AND a.WorkPoint='{1}' AND c.Type='2' AND c.Quantity<c.SDNQuantity)
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo114") + @"',16,1);
                                END";
                sql = string.Format(sql, LotNo, WorkPoint, Quantity);
                if (!DBHelper.ExecuteNonQuery(sql, cmd))
                {
                    throw new Exception("销售退货单更新失败!");
                }
            }
            catch (Exception)
            {
                throw;
            }
        }

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

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

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

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

        #region 销售退货-原条码
        /// <summary>
        /// 销售退货-原条码
        /// </summary>
        /// <param name="TransCode"></param>
        /// <param name="TransSequence"></param>
        /// <param name="Quantity"></param>
        /// <param name="WorkPoint"></param>
        /// <param name="cmd"></param>
        public static void SalesReturnBackIn(string TransCode, string TransSequence, string LotNo, string Quantity, string WorkPoint, SqlCommand cmd, Dictionary<string, string> language)
        {
            try
            {
                string sql = @"DECLARE @Status VARCHAR(10)
                                SELECT @Status=sdn.Status FROM ICSSDN sdn
                                INNER JOIN ICSWareHouseLotInfoLog log ON sdn.WorkPoint=log.WorkPoint
                                INNER JOIN ICSWareHouseLotInfo a ON a.LotNo=log.LotNo AND a.WorkPoint=log.WorkPoint
                                WHERE a.LotNo='{0}' AND a.WorkPoint='{1}' AND sdn.SDNCode='{2}' AND sdn.Sequence='{3}' AND sdn.Type='2'

                                IF (@Status IS NULL)
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo081") + @"',16,1);
                                    RETURN
                                END
                                ELSE IF (@Status!='2')
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo142") + @"',16,1);
                                    RETURN
                                END
                                UPDATE sdn SET SDNQuantity=ISNULL(SDNQuantity,0)+'{4}'
                                FROM ICSSDN sdn
                                INNER JOIN ICSWareHouseLotInfoLog log ON sdn.WorkPoint=log.WorkPoint
                                INNER JOIN ICSWareHouseLotInfo a ON a.LotNo=log.LotNo AND a.WorkPoint=log.WorkPoint
                                WHERE a.LotNo='{0}' AND a.WorkPoint='{1}' AND sdn.SDNCode='{2}' AND sdn.Sequence='{3}' AND sdn.Type='2'
                                IF EXISTS(SELECT a.LotNo FROM ICSSDN sdn
                                    INNER JOIN ICSWareHouseLotInfoLog log ON sdn.WorkPoint=log.WorkPoint
                                    INNER JOIN ICSWareHouseLotInfo a ON a.LotNo=log.LotNo AND a.WorkPoint=log.WorkPoint
                                    WHERE a.LotNo='{0}' AND a.WorkPoint='{1}' AND sdn.SDNCode='{2}' AND sdn.Sequence='{3}' AND sdn.Type='2' AND sdn.Quantity<sdn.SDNQuantity)
                                BEGIN
	                                RAISERROR('" + language.GetNameByCode("WMSAPIInfo114") + @"',16,1);
                                END";
                sql = string.Format(sql, LotNo, WorkPoint, TransCode, TransSequence, Quantity);
                if (!DBHelper.ExecuteNonQuery(sql, cmd))
                {
                    throw new Exception(language.GetNameByCode("WMSAPIInfo143"));//"销售退货单更新失败!");
                }
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 销售退货-原条码接口
        /// </summary>
        /// <param name="TransType"></param>
        /// <param name="Identification"></param>
        /// <param name="cmd"></param>
        public static void SalesReturnBackInERP(string TransType, string Identification, SqlCommand cmd, Dictionary<string, string> language,string BusinessCode)
        {
            try
            {
                #region ERP
                string sql = @"SELECT c.CusCode+a.ToWarehouseCode+c.SDNCode+a.MUSER AS Costre,c.CusCode,a.ToWarehouseCode AS WarehouseCode,c.SDNCode,a.MUSER,ROW_NUMBER() OVER (ORDER BY c.CusCode,a.ToWarehouseCode,c.SDNCode,c.SDNDetailID,a.InvCode) AS Sequence,
                                    a.InvCode,SUM(a.Quantity) AS Quantity,CASE inv.AmountEnable WHEN '1' THEN SUM(a.Quantity*(lot.Amount/lot.Quantity)) ELSE '0' END AS Amount,c.SDNDetailID,Enable AS UpdateTodoQuantity,conStock.Enable AS UpdateStock
	                            ,a.WorkPoint,ISNULL(ext.ProjectCode, '') AS ProjectCode,CASE WHEN (invBat.BatchEnable IS NULL AND ISNULL(inv.BatchEnable, '0')='1') OR ISNULL(invBat.BatchEnable, '0')='1' THEN ISNULL(ext.BatchCode, '') ELSE '' END AS BatchCode,ISNULL(ext.Version, '') AS Version,ISNULL(ext.Brand, '') AS Brand,
	                            ISNULL(ext.cFree1, '') AS cFree1,ISNULL(ext.cFree2, '') AS cFree2,ISNULL(ext.cFree3, '') AS cFree3,ISNULL(ext.cFree4, '') AS cFree4,ISNULL(ext.cFree5, '') AS cFree5,ISNULL(ext.cFree6, '') AS cFree6,ISNULL(ext.cFree7, '') AS cFree7,ISNULL(ext.cFree8, '') AS cFree8,ISNULL(ext.cFree9, '') AS cFree9,ISNULL(ext.cFree10, '') AS cFree10                                   
                                INTO #TempERP
                                FROM ICSWareHouseLotInfoLog a
                                INNER JOIN ICSInventoryLot lot ON a.LotNo=lot.LotNo AND a.WorkPoint=lot.WorkPoint
                                INNER JOIN ICSExtension ext ON lot.ExtensionID=ext.ID AND lot.WorkPoint=ext.WorkPoint
                                INNER JOIN ICSInventory inv ON a.InvCode=inv.InvCode AND a.WorkPoint=inv.WorkPoint
                                LEFT JOIN ICSInventoryBatchEnable invBat ON a.InvCode=invBat.InvCode AND a.ToWarehouseCode=invBat.WHCode AND a.WorkPoint=invBat.WorkPoint
                                INNER JOIN ICSSDN c ON a.TransCode=c.SDNCode AND a.TransSequence=c.Sequence AND a.WorkPoint=c.WorkPoint
                                INNER JOIN ICSConfiguration con ON con.Code='Stock001' AND a.WorkPoint=con.WorkPoint
INNER JOIN ICSConfiguration conStock ON conStock.Code='UpdateStock005' AND a.WorkPoint=conStock.WorkPoint
                                WHERE a.Identification='{0}' AND  ERPUpload='0' AND c.Type='2'  AND BusinessCode='{1}'
                                GROUP BY inv.AmountEnable,c.CusCode,a.ToWarehouseCode,c.SDNCode,a.MUSER,a.InvCode,c.SDNDetailID,Enable,conStock.Enable
                                ,a.WorkPoint,ISNULL(ext.ProjectCode, ''),CASE WHEN (invBat.BatchEnable IS NULL AND ISNULL(inv.BatchEnable, '0')='1') OR ISNULL(invBat.BatchEnable, '0')='1' THEN ISNULL(ext.BatchCode, '') ELSE '' END,ISNULL(ext.Version, ''),ISNULL(ext.Brand, ''),
                                ISNULL(ext.cFree1, ''),ISNULL(ext.cFree2, ''),ISNULL(ext.cFree3, ''),ISNULL(ext.cFree4, ''),ISNULL(ext.cFree5, ''),ISNULL(ext.cFree6, ''),ISNULL(ext.cFree7, ''),ISNULL(ext.cFree8, ''),ISNULL(ext.cFree9, ''),ISNULL(ext.cFree10, '')

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

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

                string Inputstr = DataToJsonHelper.DataSetToJson(ds, "details", "Costre");

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

    }
}