using ICS.CreateLotMaster;
using ICS.WCF.Base;
using ICSSoft.APIApproveTransferIN;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks;
using UFSoft.UBF.Exceptions1;
using UFSoft.UBF.Service;
using UFSoft.UBF.Util.Context;
using www.ufida.org.EntityData;

namespace UFIDA.ISV.ModifyTransferIN
{
    public class CustModifyTransferIN
    {
        public bool ModifyTransferINDoc(List<TransferINInfo> InfoList)
        {
            #region 服务调用框架结构
            UFIDAU9ISVTransferInISVICommonModifyTransferInSVClient client = new UFIDAU9ISVTransferInISVICommonModifyTransferInSVClient();
            //返回异常信息，目前还没有使用此属性
            MessageBase[] returnMsg;

            string OrgID = "";
            string TransferDocNo = "";
            long TransferDocID = 0;
            //上下文信息
            object context;
            try
            {
                StringBuilder firststr = new StringBuilder();
                firststr.AppendLine("传入数据记录开始");
                foreach (TransferINInfo info in InfoList)
                {
                    firststr.AppendLine("组织：" + info.OrgCode);
                    firststr.AppendLine("调入单行ID:" + info.DocLineID);
                    firststr.AppendLine("行调入批号:" + info.TransferBatchCode);
                }
                firststr.AppendLine("传入数据记录结束");
                Appconfig.WriteLogFile(firststr.ToString(), "修改U9调入单调入数量");
                //返回信息

                //给上下文信息赋值
                context = CreateContextObj();
                //给传入参数赋值

                #region 根据传入调入单行ID查询调入单号及调入单ID
                string orgsql = @"select ID from Base_Organization
                                              where Code='{0}'";
                orgsql = string.Format(orgsql, InfoList[0].OrgCode);
                DataTable orgdt = DBhlper.Query(orgsql, Appconfig.GetU9ConnStr());
                if (orgdt.Rows.Count != 0)
                {
                    OrgID = orgdt.Rows[0]["ID"].ToString();
                }
                else
                {
                    throw new Exception("传入组织不存在");
                }
                string docsql = @"select A.ID,A.DocNo,A.TransferInType,A.TransInDocType,A.Status,A.BusinessDate
                                  ,A.SrcDocType,A.TransferDirection,A.OnlyUpdateCost,A.OnlyUpdateQty,C.Memo
                                  from InvDoc_TransferIn A
                                  LEFT JOIN InvDoc_TransINLine B
                                  ON B.TransferIN=A.ID AND B.Org=A.Org
                                  LEFT JOIN InvDoc_TransferIn_Trl C
                                  ON C.ID=A.ID
                                  where B.ID='{0}' And A.Org='{1}'";
                docsql = string.Format(docsql, InfoList[0].DocLineID, OrgID);
                DataTable docdt = DBhlper.Query(docsql, Appconfig.GetU9ConnStr());
                if (docdt.Rows.Count == 0)
                {
                    throw new Exception("传入行ID错误，调入单查询失败");
                }
                else
                {
                    TransferDocNo = docdt.Rows[0]["DocNo"].ToString();
                    TransferDocID = long.Parse(docdt.Rows[0]["ID"].ToString());
                }
                #endregion
                List<long> LineIDList = new List<long>();
                List<UFIDAU9ISVTransferInISVIC_TransferInDTOData> TransferINList = new List<UFIDAU9ISVTransferInISVIC_TransferInDTOData>();
                UFIDAU9ISVTransferInISVIC_TransferInDTOData TransferIN = new UFIDAU9ISVTransferInISVIC_TransferInDTOData();
                TransferIN.m_docNo = TransferDocNo;
                TransferIN.m_iD = TransferDocID;
                TransferIN.m_operationType = 2;
                TransferIN.m_businessDate = Convert.ToDateTime(docdt.Rows[0]["BusinessDate"].ToString());
                TransferIN.m_transferDirection = Convert.ToInt32(docdt.Rows[0]["TransferDirection"].ToString());
                TransferIN.m_transferType = -1;
                TransferIN.m_transInDocType = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                TransferIN.m_transInDocType.m_iD = long.Parse(docdt.Rows[0]["TransInDocType"].ToString());
                TransferIN.m_memo = docdt.Rows[0]["Memo"].ToString();
                List<UFIDAU9ISVTransferInISVIC_TransInLineDTOData> TransferInLineList = new List<UFIDAU9ISVTransferInISVIC_TransInLineDTOData>();
                foreach (TransferINInfo info in InfoList)
                {
                    bool NeedSplit = false;
                    if (LineIDList.Count == 0)
                    {
                        LineIDList.Add(info.DocLineID);
                    }
                    else
                    {
                        if (LineIDList.Contains(info.DocLineID))
                        {
                            NeedSplit = true;
                        }
                        else
                        {
                            LineIDList.Add(info.DocLineID);
                        }
                    }
                    string transInSubLineID = "";
                    #region 查询调入单行信息
                    string linesql = @"select A.ItemInfo_ItemID,A.ItemInfo_ItemCode,A.ItemInfo_ItemName,A.CostCurrency,A.CostMoney,A.CostPrice
                                        ,A.DocLineNo,A.StorageType,A.TransInWh,A.ItemInfo_ItemGrade,A.ItemInfo_ItemPotency
                                        ,A.ItemInfo_ItemVersion,A.LotInfo_LotCode,A.LotInfo_LotMaster
                                        ,A.StoreUOM,A.CostUOM,A.StoreUOMQty,A.CostUOMQty,B.ID AS SubLineID
                                        from InvDoc_TransINLine A
										LEFT JOIN InvDoc_TransInSubLine B ON B.TransInLine=A.ID
                                        where A.ID='{0}' AND A.Org='{1}'";
                    linesql = string.Format(linesql, info.DocLineID, OrgID);
                    DataTable linedt = DBhlper.Query(linesql, Appconfig.GetU9ConnStr());
                    if (linedt.Rows.Count == 0)
                    {
                        throw new Exception("传入行ID错误，调入单子行信息查询失败!");
                    }
                    else
                    {
                        transInSubLineID = linedt.Rows[0]["SubLineID"].ToString();
                    }
                    #endregion
                    #region 查询调入单调出明细信息
                    string sublinesql = @"SELECT ItemInfo_ItemID,ItemInfo_ItemCode,ItemInfo_ItemName,CostCurrency,CostMoney,CostPrice
                                          ,DocLineNo,StorageType,TransOutWh ,LotInfo_LotCode,LotInfo_LotMaster
                                          ,StoreUOM,CostUOM,StoreUOMQty,CostUOMQty
                                          FROM InvDoc_TransINSubLine
                                          WHERE ID='{0}' AND Org='{1}'";
                    sublinesql = string.Format(sublinesql, transInSubLineID, OrgID);
                    DataTable sublinedt = DBhlper.Query(sublinesql, Appconfig.GetU9ConnStr());
                    if (sublinedt.Rows.Count == 0)
                    {
                        throw new Exception("调入单调出明细信息查询失败,请确认数据!");
                    }
                    #endregion
                    #region 查询调入单行库位信息
                    string binid = "0";
                    string binsql = @"select ID from InvDoc_TransInBin
                                      where TransInLine='{0}' and Org='{1}'";
                    binsql = string.Format(binsql, info.DocLineID, OrgID);
                    DataTable bindt = DBhlper.Query(binsql, Appconfig.GetU9ConnStr());
                    if (bindt.Rows.Count == 0)
                    {
                        throw new Exception("传入行ID错误，调入单行库位信息查询失败!");
                    }
                    else
                    {
                        binid = bindt.Rows[0]["ID"].ToString();
                    }
                    #endregion
                    if (NeedSplit == false)
                    {
                        UFIDAU9ISVTransferInISVIC_TransInLineDTOData TransferInLine = new UFIDAU9ISVTransferInISVIC_TransInLineDTOData();
                        TransferInLine.m_iD = info.DocLineID;
                        TransferInLine.m_operationType = 2;
                        TransferInLine.m_storeUOMQty = info.TransferQTY;
                        TransferInLine.m_costUOMQty = info.TransferQTY;
                        TransferInLine.m_docLineNo = Convert.ToInt32(linedt.Rows[0]["DocLineNo"].ToString());
                        TransferInLine.m_transInWh = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                        TransferInLine.m_transInWh.m_iD = long.Parse(linedt.Rows[0]["TransInWh"].ToString());
                        TransferInLine.m_storageType = Convert.ToInt32(linedt.Rows[0]["StorageType"].ToString());
                        //TransferInLine.m_costPrice = Convert.ToDecimal(linedt.Rows[0]["CostPrice"].ToString());
                        //TransferInLine.m_costMoney = Convert.ToDecimal(linedt.Rows[0]["CostMoney"].ToString());
                        TransferInLine.m_costCurrency = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                        TransferInLine.m_costCurrency.m_code = linedt.Rows[0]["CostCurrency"].ToString();
                        TransferInLine.m_itemInfo = new UFIDAU9CBOSCMItemItemInfoData();
                        TransferInLine.m_itemInfo.m_itemName = linedt.Rows[0]["ItemInfo_ItemName"].ToString();
                        TransferInLine.m_itemInfo.m_itemCode = linedt.Rows[0]["ItemInfo_ItemCode"].ToString();
                        TransferInLine.m_itemInfo.ItemID = long.Parse(linedt.Rows[0]["ItemInfo_ItemID"].ToString());
                        TransferInLine.m_itemInfo.ItemID_SKey = new UFSoft.UBF.Business.BusinessEntity.EntityKey();
                        TransferInLine.m_itemInfo.ItemID_SKey.ID = long.Parse(linedt.Rows[0]["ItemInfo_ItemID"].ToString());
                        TransferInLine.m_itemInfo.m_itemGrade = Convert.ToInt32(linedt.Rows[0]["ItemInfo_ItemGrade"].ToString());
                        TransferInLine.m_itemInfo.m_itemPotency = -1;
                        if (info.TransferBatchCode != "")
                        {
                            #region 创建批号接口调用
                            string LotID = "";
                            CustCreateLotMaster LotMasterCreate = new CustCreateLotMaster();
                            string lotWHCode = "";//创建批号接口没用到仓库，传空
                            string lotItemCode = linedt.Rows[0]["ItemInfo_ItemCode"].ToString();
                            string LotCode = info.TransferBatchCode;
                            #region 查询批号是否已经存在，如果不存在，则需要创建批号
                            string lotsql = @"  select A.ID,A.LotCode,a.EffectiveDatetime,a.InvalidTime,a.ValidDate from Lot_LotMaster A
                                            LEFT JOIN CBO_ItemMaster B ON B.ID=A.Item AND B.Org=A.ItemOwnerOrg
                                            WHERE A.LotCode='{0}' AND B.Code='{1}'";
                            lotsql = string.Format(lotsql, LotCode, lotItemCode, OrgID);
                            DataTable sqldt = DBhlper.Query(lotsql, Appconfig.GetU9ConnStr());
                            if (sqldt.Rows.Count != 0)
                            {
                                TransferInLine.m_lotInfo = new UFIDAU9CBOSCMPropertyTypesLotInfoData();
                                TransferInLine.m_lotInfo.m_lotCode = LotCode;
                                TransferInLine.m_lotInfo.m_lotMaster = new UFIDAU9BasePropertyTypesBizEntityKeyData();
                                TransferInLine.m_lotInfo.m_lotMaster.m_entityID = long.Parse(sqldt.Rows[0]["ID"].ToString());
                                TransferInLine.m_lotInfo.m_disabledDatetime = Convert.ToDateTime(sqldt.Rows[0]["InvalidTime"].ToString());
                                TransferInLine.m_lotInfo.m_lotValidDate = int.Parse(sqldt.Rows[0]["ValidDate"].ToString());
                            }
                            else
                            {
                                LotMasterCreate.CustCreateRCVLotMasterPN(lotWHCode, lotItemCode, LotCode, OrgID, ref LotID);
                                if (LotID != "")
                                {
                                    lotsql = @"  select A.ID,A.LotCode,a.EffectiveDatetime,a.InvalidTime,a.ValidDate from Lot_LotMaster A
                                            LEFT JOIN CBO_ItemMaster B ON B.ID=A.Item AND B.Org=A.ItemOwnerOrg
                                            WHERE A.ID='{0}'";
                                    lotsql = string.Format(lotsql, LotID);
                                    sqldt = DBhlper.Query(lotsql, Appconfig.GetU9ConnStr());
                                    TransferInLine.m_lotInfo = new UFIDAU9CBOSCMPropertyTypesLotInfoData();
                                    TransferInLine.m_lotInfo.m_lotCode = LotCode;
                                    TransferInLine.m_lotInfo.m_lotMaster = new UFIDAU9BasePropertyTypesBizEntityKeyData();
                                    TransferInLine.m_lotInfo.m_lotMaster.m_entityID = long.Parse(LotID);
                                    TransferInLine.m_lotInfo.m_disabledDatetime = Convert.ToDateTime(sqldt.Rows[0]["InvalidTime"].ToString());
                                    TransferInLine.m_lotInfo.m_lotValidDate = int.Parse(sqldt.Rows[0]["ValidDate"].ToString());
                                }
                            }
                            #endregion
                            #endregion
                        }
                        else
                        {
                            TransferInLine.m_lotInfo = new UFIDAU9CBOSCMPropertyTypesLotInfoData();
                            TransferInLine.m_lotInfo.m_lotMaster = new UFIDAU9BasePropertyTypesBizEntityKeyData();
                        }
                        TransferInLine.m_storeUOM = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                        TransferInLine.m_storeUOM.m_iD = long.Parse(linedt.Rows[0]["StoreUOM"].ToString());
                        TransferInLine.m_costUOM = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                        TransferInLine.m_costUOM.m_iD = long.Parse(linedt.Rows[0]["CostUOM"].ToString());
                        List<UFIDAU9ISVTransferInISVIC_TransInSubLineDTOData> TransferInSubLineList = new List<UFIDAU9ISVTransferInISVIC_TransInSubLineDTOData>();
                        UFIDAU9ISVTransferInISVIC_TransInSubLineDTOData TransferInSubLine = new UFIDAU9ISVTransferInISVIC_TransInSubLineDTOData();
                        TransferInSubLine.m_iD = long.Parse(transInSubLineID);
                        TransferInSubLine.m_operationType = 2;
                        TransferInSubLine.m_storeUOMQty = info.TransferQTY;
                        TransferInSubLine.m_costUOMQty = info.TransferQTY;
                        TransferInSubLine.m_docLineNo = Convert.ToInt32(sublinedt.Rows[0]["DocLineNo"].ToString());
                        TransferInSubLine.m_transOutWh = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                        TransferInSubLine.m_transOutWh.m_iD = long.Parse(sublinedt.Rows[0]["TransOutWh"].ToString());
                        TransferInSubLine.m_storageType = Convert.ToInt32(sublinedt.Rows[0]["StorageType"].ToString());
                        //TransferInSubLine.m_costPrice = Convert.ToDecimal(sublinedt.Rows[0]["CostPrice"].ToString());
                        //TransferInSubLine.m_costMoney = Convert.ToDecimal(sublinedt.Rows[0]["CostMoney"].ToString());
                        TransferInSubLine.m_transOutOrg = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                        TransferInSubLine.m_transOutOrg.m_iD = long.Parse(OrgID);
                        if (sublinedt.Rows[0]["LotInfo_LotCode"].ToString() != "")
                        {
                            TransferInSubLine.m_lotInfo = new UFIDAU9CBOSCMPropertyTypesLotInfoData();
                            TransferInSubLine.m_lotInfo.m_lotCode = sublinedt.Rows[0]["LotInfo_LotCode"].ToString();
                            TransferInSubLine.m_lotInfo.m_lotMaster = new UFIDAU9BasePropertyTypesBizEntityKeyData();
                            TransferInSubLine.m_lotInfo.m_lotMaster.m_entityID = long.Parse(sublinedt.Rows[0]["LotInfo_LotMaster"].ToString());
                        }
                        TransferInSubLine.m_storeUOM = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                        TransferInSubLine.m_storeUOM.m_iD = long.Parse(sublinedt.Rows[0]["StoreUOM"].ToString());
                        TransferInSubLineList.Add(TransferInSubLine);
                        TransferInLine.m_transInSubLines = TransferInSubLineList.ToArray();
                        TransferInLineList.Add(TransferInLine);
                        TransferIN.m_transInLines = TransferInLineList.ToArray();
                    }
                    else
                    {
                        UFIDAU9ISVTransferInISVIC_TransInLineDTOData TransferInLine = new UFIDAU9ISVTransferInISVIC_TransInLineDTOData();
                        //TransferInLine.m_iD = info.DocLineID;
                        //TransferInLine.m_operationType = 2;
                        TransferInLine.m_storeUOMQty = info.TransferQTY;
                        TransferInLine.m_costUOMQty = info.TransferQTY;
                        //TransferInLine.m_docLineNo = 20;
                        TransferInLine.m_transInWh = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                        TransferInLine.m_transInWh.m_iD = long.Parse(linedt.Rows[0]["TransInWh"].ToString());
                        TransferInLine.m_storageType = Convert.ToInt32(linedt.Rows[0]["StorageType"].ToString());
                        //TransferInLine.m_costPrice = Convert.ToDecimal(linedt.Rows[0]["CostPrice"].ToString());
                        //TransferInLine.m_costMoney = Convert.ToDecimal(linedt.Rows[0]["CostMoney"].ToString());
                        TransferInLine.m_costCurrency = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                        TransferInLine.m_costCurrency.m_code = linedt.Rows[0]["CostCurrency"].ToString();
                        TransferInLine.m_itemInfo = new UFIDAU9CBOSCMItemItemInfoData();
                        TransferInLine.m_itemInfo.m_itemName = linedt.Rows[0]["ItemInfo_ItemName"].ToString();
                        TransferInLine.m_itemInfo.m_itemCode = linedt.Rows[0]["ItemInfo_ItemCode"].ToString();
                        TransferInLine.m_itemInfo.ItemID = long.Parse(linedt.Rows[0]["ItemInfo_ItemID"].ToString());
                        TransferInLine.m_itemInfo.ItemID_SKey = new UFSoft.UBF.Business.BusinessEntity.EntityKey();
                        TransferInLine.m_itemInfo.ItemID_SKey.ID = long.Parse(linedt.Rows[0]["ItemInfo_ItemID"].ToString());
                        TransferInLine.m_itemInfo.m_itemGrade = Convert.ToInt32(linedt.Rows[0]["ItemInfo_ItemGrade"].ToString());
                        TransferInLine.m_itemInfo.m_itemPotency = -1;
                        if (info.TransferBatchCode != "")
                        {
                            #region 创建批号接口调用
                            string LotID = "";
                            CustCreateLotMaster LotMasterCreate = new CustCreateLotMaster();
                            string lotWHCode = "";//创建批号接口没用到仓库，传空
                            string lotItemCode = linedt.Rows[0]["ItemInfo_ItemCode"].ToString();
                            string LotCode = info.TransferBatchCode;
                            #region 查询批号是否已经存在，如果不存在，则需要创建批号
                            string lotsql = @"  select A.ID,A.LotCode,a.EffectiveDatetime,a.InvalidTime,a.ValidDate from Lot_LotMaster A
                                            LEFT JOIN CBO_ItemMaster B ON B.ID=A.Item AND B.Org=A.ItemOwnerOrg
                                            WHERE A.LotCode='{0}' AND B.Code='{1}'";
                            lotsql = string.Format(lotsql, LotCode, lotItemCode, OrgID);
                            DataTable sqldt = DBhlper.Query(lotsql, Appconfig.GetU9ConnStr());
                            if (sqldt.Rows.Count != 0)
                            {
                                TransferInLine.m_lotInfo = new UFIDAU9CBOSCMPropertyTypesLotInfoData();
                                TransferInLine.m_lotInfo.m_lotCode = LotCode;
                                TransferInLine.m_lotInfo.m_lotMaster = new UFIDAU9BasePropertyTypesBizEntityKeyData();
                                TransferInLine.m_lotInfo.m_lotMaster.m_entityID = long.Parse(sqldt.Rows[0]["ID"].ToString());
                                TransferInLine.m_lotInfo.m_disabledDatetime = Convert.ToDateTime(sqldt.Rows[0]["InvalidTime"].ToString());
                                TransferInLine.m_lotInfo.m_lotValidDate = int.Parse(sqldt.Rows[0]["ValidDate"].ToString());
                            }
                            else
                            {
                                LotMasterCreate.CustCreateRCVLotMasterPN(lotWHCode, lotItemCode, LotCode, OrgID, ref LotID);
                                if (LotID != "")
                                {
                                    lotsql = @"  select A.ID,A.LotCode,a.EffectiveDatetime,a.InvalidTime,a.ValidDate from Lot_LotMaster A
                                            LEFT JOIN CBO_ItemMaster B ON B.ID=A.Item AND B.Org=A.ItemOwnerOrg
                                            WHERE A.ID='{0}'";
                                    lotsql = string.Format(lotsql, LotID);
                                    sqldt = DBhlper.Query(lotsql, Appconfig.GetU9ConnStr());
                                    TransferInLine.m_lotInfo = new UFIDAU9CBOSCMPropertyTypesLotInfoData();
                                    TransferInLine.m_lotInfo.m_lotCode = LotCode;
                                    TransferInLine.m_lotInfo.m_lotMaster = new UFIDAU9BasePropertyTypesBizEntityKeyData();
                                    TransferInLine.m_lotInfo.m_lotMaster.m_entityID = long.Parse(LotID);
                                    TransferInLine.m_lotInfo.m_disabledDatetime = Convert.ToDateTime(sqldt.Rows[0]["InvalidTime"].ToString());
                                    TransferInLine.m_lotInfo.m_lotValidDate = int.Parse(sqldt.Rows[0]["ValidDate"].ToString());
                                }
                            }
                            #endregion
                            #endregion
                        }
                        else
                        {
                            TransferInLine.m_lotInfo = new UFIDAU9CBOSCMPropertyTypesLotInfoData();
                            TransferInLine.m_lotInfo.m_lotMaster = new UFIDAU9BasePropertyTypesBizEntityKeyData();
                        }
                        TransferInLine.m_storeUOM = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                        TransferInLine.m_storeUOM.m_iD = long.Parse(linedt.Rows[0]["StoreUOM"].ToString());
                        TransferInLine.m_costUOM = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                        TransferInLine.m_costUOM.m_iD = long.Parse(linedt.Rows[0]["CostUOM"].ToString());
                        List<UFIDAU9ISVTransferInISVIC_TransInSubLineDTOData> TransferInSubLineList = new List<UFIDAU9ISVTransferInISVIC_TransInSubLineDTOData>();
                        UFIDAU9ISVTransferInISVIC_TransInSubLineDTOData TransferInSubLine = new UFIDAU9ISVTransferInISVIC_TransInSubLineDTOData();
                        //TransferInSubLine.m_iD = long.Parse(transInSubLineID);
                        //TransferInSubLine.m_operationType = 2;
                        TransferInSubLine.m_storeUOMQty = info.TransferQTY;
                        TransferInSubLine.m_costUOMQty = info.TransferQTY;
                        //TransferInSubLine.m_docLineNo = 10;
                        TransferInSubLine.m_transOutWh = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                        TransferInSubLine.m_transOutWh.m_iD = long.Parse(sublinedt.Rows[0]["TransOutWh"].ToString());
                        TransferInSubLine.m_storageType = Convert.ToInt32(sublinedt.Rows[0]["StorageType"].ToString());
                        //TransferInSubLine.m_costPrice = Convert.ToDecimal(sublinedt.Rows[0]["CostPrice"].ToString());
                        //TransferInSubLine.m_costMoney = Convert.ToDecimal(sublinedt.Rows[0]["CostMoney"].ToString());
                        TransferInSubLine.m_transOutOrg = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                        TransferInSubLine.m_transOutOrg.m_iD = long.Parse(OrgID);
                        if (sublinedt.Rows[0]["LotInfo_LotCode"].ToString() != "")
                        {
                            TransferInSubLine.m_lotInfo = new UFIDAU9CBOSCMPropertyTypesLotInfoData();
                            TransferInSubLine.m_lotInfo.m_lotCode = sublinedt.Rows[0]["LotInfo_LotCode"].ToString();
                            TransferInSubLine.m_lotInfo.m_lotMaster = new UFIDAU9BasePropertyTypesBizEntityKeyData();
                            TransferInSubLine.m_lotInfo.m_lotMaster.m_entityID = long.Parse(sublinedt.Rows[0]["LotInfo_LotMaster"].ToString());
                        }
                        TransferInSubLine.m_storeUOM = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                        TransferInSubLine.m_storeUOM.m_iD = long.Parse(sublinedt.Rows[0]["StoreUOM"].ToString());
                        TransferInSubLineList.Add(TransferInSubLine);
                        TransferInLine.m_transInSubLines = TransferInSubLineList.ToArray();
                        TransferInLineList.Add(TransferInLine);
                        TransferIN.m_transInLines = TransferInLineList.ToArray();
                    }
                }
                TransferINList.Add(TransferIN);
                (client.Endpoint.Binding as BasicHttpBinding).MaxReceivedMessageSize = int.MaxValue;
                (client.Endpoint.Binding as BasicHttpBinding).MaxBufferSize = int.MaxValue;

                returnMsg = client.Do(context, TransferINList.ToArray());

                #region 调用接口后直接修改调入行库位数量
                string binupdatesql = @"UPDATE A SET A.StoreUOMQty=B.StoreUOMQty
                                         FROM InvDoc_TransInBin A
                                         INNER JOIN InvDoc_TransInLine B ON B.ID=A.TransInLine
                                         INNER JOIN InvDoc_TransferIn C ON C.ID=B.TransferIn
                                         WHERE C.ID='{0}' AND C.Org='{1}'";
                binupdatesql = string.Format(binupdatesql, TransferDocID, OrgID);
                DBhlper.EXecute(binupdatesql, Appconfig.GetU9ConnStr());
                #endregion

                #region 修改后调用接口审核调入单
                ApproveTransferIN approveService = new ApproveTransferIN();
                List<string> DocID = new List<string>();
                DocID.Add(TransferDocID.ToString());
                approveService.Approve(DocID, InfoList[0].OrgCode, "");
                #endregion

                if (returnMsg != null && returnMsg.Length != 0)
                {
                    return true;
                }
                return true;
            }
            catch (Exception ex)
            {
                //异常信息捕获
                ReturnValue rtnpo = new ReturnValue();
                rtnpo.IsSuccess = false;
                rtnpo.Message = GetExceptionMessage(ex);

                StringBuilder strlog = new StringBuilder();
                strlog.AppendLine("修改U9调入单调入批号");
                strlog.AppendLine("*****************************************************");
                foreach (TransferINInfo info in InfoList)
                {
                    strlog.AppendLine("组织：" + info.OrgCode);
                    strlog.AppendLine("调入单行ID:" + info.DocLineID);
                    strlog.AppendLine("行调入批号:" + info.TransferBatchCode);
                }
                strlog.AppendLine("返回消息：" + rtnpo.Message);
                strlog.AppendLine("*****************************************************");
                Appconfig.WriteLogFile(strlog.ToString(), "修改U9调入单调入批号");

                return false;
            }
            #endregion
        }

        #region 给上下文信息赋值
        /// <summary>
        /// 给上下文信息赋值
        /// </summary>
        /// <returns></returns>
        private ThreadContext CreateContextObj()
        {
            // 实例化应用上下文对象
            ThreadContext thContext = new ThreadContext();

            System.Collections.Generic.Dictionary<object, object> ns = new Dictionary<object, object>();
            ns.Add("OrgID", ConfigurationManager.AppSettings["orgID"].ToString());
            ns.Add("UserID", ConfigurationManager.AppSettings["userID"].ToString());
            ns.Add("UserCode", ConfigurationManager.AppSettings["userCode"].ToString());
            ns.Add("Datetime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            ns.Add("CultureName", ConfigurationManager.AppSettings["cultureName"].ToString());
            ns.Add("EnterpriseID", ConfigurationManager.AppSettings["enterpriseID"].ToString());
            ns.Add("DefaultCultureName", ConfigurationManager.AppSettings["cultureName"].ToString());
            thContext.nameValueHas = ns;

            return thContext;
        }
        #endregion


        #region 提取异常信息
        /// <summary>
        /// 提取异常信息
        /// </summary>
        /// <param name="ex"></param>
        private string GetExceptionMessage(Exception ex)
        {
            string faultMessage = "未知错误，请查看ERP日志！";

            System.TimeoutException timeoutEx = ex as System.TimeoutException;
            if (timeoutEx != null)
            {
                faultMessage = "访问服务超时，请修改配置信息！";
            }
            else
            {
                FaultException<ServiceException> faultEx = ex as FaultException<ServiceException>;
                if (faultEx == null)
                {
                    faultMessage = ex.Message;
                }
                else
                {
                    ServiceException serviceEx = faultEx.Detail;
                    if (serviceEx != null && !string.IsNullOrEmpty(serviceEx.Message)
                        && !serviceEx.Message.Equals("fault", StringComparison.OrdinalIgnoreCase))
                    {
                        // 错误信息在faultEx.Message中，请提取，
                        // 格式为"Fault:料品不能为空，请录入\n 在....."
                        int startIndex = serviceEx.Message.IndexOf(":");
                        int endIndex = serviceEx.Message.IndexOf("\n");
                        if (endIndex == -1)
                            endIndex = serviceEx.Message.Length;
                        if (endIndex > 0 && endIndex > startIndex + 1)
                        {
                            faultMessage = serviceEx.Message.Substring(startIndex + 1, endIndex - startIndex - 1);
                        }
                        else
                        {
                            faultMessage = serviceEx.Message;
                        }
                    }
                }
            }
            return faultMessage;
        }
        #endregion


        #region 上下文类信息
        public class contextInfo
        {
            private long _OrgID;
            private string _OrgCode;
            private long _UserID;
            private string _UserCode;
            private DateTime _Datetime;
            private string _CultureName;
            private string _EnterpriseID;


            /// <summary>
            /// 组织ID
            /// </summary>
            public long OrgID
            {
                get { return _OrgID; }
                set { _OrgID = value; }
            }

            /// <summary>
            /// 组织编码
            /// </summary>
            public string OrgCode
            {
                get { return _OrgCode; }
                set { _OrgCode = value; }
            }

            /// <summary>
            /// 操作员ID
            /// </summary>
            public long UserID
            {
                get { return _UserID; }
                set { _UserID = value; }
            }

            /// <summary>
            /// 操作员编码
            /// </summary>
            public string UserCode
            {
                get { return _UserCode; }
                set { _UserCode = value; }
            }

            /// <summary>
            /// 时间
            /// </summary>
            public DateTime Datetime
            {
                get { return _Datetime; }
                set { _Datetime = value; }
            }

            /// <summary>
            /// 语言
            /// </summary>
            public string CultureName
            {
                get { return _CultureName; }
                set { _CultureName = value; }
            }

            /// <summary>
            /// 企业ID号
            /// </summary>
            public string EnterpriseID
            {
                get { return _EnterpriseID; }
                set { _EnterpriseID = value; }
            }

            public contextInfo()
            {
                CultureName = "zh_CN";
                Datetime = DateTime.Now;
            }
        }
        #endregion

        #region 传入参数类
        public class TransferINInfo
        {
            private string _OrgCode;

            private long _DocLineID;

            private decimal _TransferQTY;

            private string _TransferBatchCode;

            public string LogId { get; set; }

            /// <summary>
            /// 传入组织编码
            /// </summary>
            public string OrgCode
            {
                get { return _OrgCode; }
                set { _OrgCode = value; }
            }
            /// <summary>
            /// 调入单行ID
            /// </summary>
            public long DocLineID
            {
                get { return _DocLineID; }
                set { _DocLineID = value; }
            }
            /// <summary>
            /// 调入单行批号
            /// </summary>
            public string TransferBatchCode
            {
                get { return _TransferBatchCode; }
                set { _TransferBatchCode = value; }
            }
            /// <summary>
            /// 行调拨数量
            /// </summary>
            public decimal TransferQTY
            {
                get { return _TransferQTY; }
                set { _TransferQTY = value; }
            }
        }
        #endregion

        #region 返回信息类
        public class ReturnValue
        {
            public bool IsSuccess { get; set; }
            public string Message { get; set; }
        }
        #endregion
    }
}
