using ICS.CreateLotMaster;
using ICS.WCF.Base;
using ICSSoft.Entity;
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 UFIDA.ISV.CreateLotMaster;
using UFIDA.ISV.RcvRptApprove;
using UFIDA.ISV.RcvRptDelete;
using UFSoft.UBF.Service;
using UFSoft.UBF.Util.Context;
using www.ufida.org.EntityData;

namespace UFIDA.ISV.CreateRcvRpt
{

    public class CustCreateRcvRptSrv
    {
        /// <summary>
        /// 根据工单创建成品入库/联副产品入库单
        /// </summary>
        /// <param name="InfoList"></param>
        /// <returns></returns>
        public rtnRcvInfo CustCreateRcvRpt(List<RcvRptInfo> InfoList)
        {
            StringBuilder beginstrlog = new StringBuilder();
            beginstrlog.AppendLine("创建成品入库单(传入数据开始)");
            beginstrlog.AppendLine("*****************************************************");
            foreach (var item in InfoList)
            {
                beginstrlog.AppendLine("生产订单号:" + item.MOCode);
                beginstrlog.AppendLine("存储地点:" + item.WHCode);
                beginstrlog.AppendLine("组织编码:" + item.WorkPoint);
                beginstrlog.AppendLine("--------------------------------------------------");
                foreach (var line in item.details)
                {
                    beginstrlog.AppendLine("物料编码:" + line.InvCode);
                    beginstrlog.AppendLine("入库批号:" + line.BatchCode);
                    beginstrlog.AppendLine("入库数量:" + line.Quantity);
                    beginstrlog.AppendLine("LogId:" + line.LogId);
                }
                beginstrlog.AppendLine("--------------------------------------------------");

            }
            beginstrlog.AppendLine("*****************************************************");
            beginstrlog.AppendLine("创建成品入库单(传入数据结束)");
            Appconfig.WriteLogFile(beginstrlog.ToString(), "创建成品入库单");
            #region 服务调用框架结构
            UFIDAU9ISVMOICreateRcvRptDocClient client = new UFIDAU9ISVMOICreateRcvRptDocClient();
            //服务返回结果
            UFIDAU9ISVMOWOKeyData[] returnItems;
            //返回异常信息，目前还没有使用此属性
            UFSoft.UBF.Exceptions.MessageBase[] returnMsg;
            //上下文信息
            object context;
            //传入 参数
            UFIDAU9ISVMOCompleteDocInfoDTOData[] RcvRptList;
            //空
            string[] splitBy = new string[] { };
            string UserID = "";
            string UserCode = "";
            string UserName = "";
            string OrgID = "";
            int StorageType = 0;
            string DeptID = "";
            long WHID = 0;
            long ItemID = 0;
            long MOID = 0;
            try
            {
                rtnRcvInfo rtnpo = new rtnRcvInfo();
                if (InfoList == null || InfoList.Count == 0)
                {
                    rtnpo = new rtnRcvInfo();
                    rtnpo.IsSuccess = false;
                    rtnpo.Message = "传入参数不能为空";
                    return rtnpo;
                }

                foreach (var item in InfoList)
                {
                    string orgsql = @"select ID from Base_Organization
                                  where Code='{0}'";
                    orgsql = string.Format(orgsql, item.WorkPoint);
                    DataTable orgdt = DBhlper.Query(orgsql, Appconfig.GetU9ConnStr());
                    if (orgdt.Rows.Count != 0)
                    {
                        OrgID = orgdt.Rows[0]["ID"].ToString();
                    }
                    else
                    {
                        rtnpo.Message = "传入的组织编码有误！";
                        rtnpo.IsSuccess = false;
                        return rtnpo;
                    }
                    if (item.MOCode == "")
                    {
                        rtnpo = new rtnRcvInfo();
                        rtnpo.IsSuccess = false;
                        rtnpo.Message = "传入生产订单不能为空";
                        return rtnpo;
                    }
                    if (item.WHCode == "")
                    {
                        rtnpo = new rtnRcvInfo();
                        rtnpo.IsSuccess = false;
                        rtnpo.Message = "传入存储地点不能为空";
                        return rtnpo;
                    }
                    foreach (var line in item.details)
                    {
                        if (line.InvCode == "")
                        {
                            rtnpo = new rtnRcvInfo();
                            rtnpo.IsSuccess = false;
                            rtnpo.Message = "传入物料编码不能为空";
                            return rtnpo;
                        }
                        if (line.Quantity == 0)
                        {
                            rtnpo = new rtnRcvInfo();
                            rtnpo.IsSuccess = false;
                            rtnpo.Message = "传入入库数量不能为0";
                            return rtnpo;
                        }
                    }
                }


                //给传入参数赋值

                //pOList = SetrCVDtos(rCVInfoList);
                StringBuilder strlog = new StringBuilder();
                strlog.AppendLine("创建成品入库单");
                strlog.AppendLine("*****************************************************");

                List<UFIDAU9ISVMOCompleteDocInfoDTOData> rptInfoList = new List<UFIDAU9ISVMOCompleteDocInfoDTOData>();
                UFIDAU9ISVMOCompleteDocInfoDTOData rptInfo = new UFIDAU9ISVMOCompleteDocInfoDTOData();
                rptInfo.m_docType = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                string typesql = @"select BusinessType from MO_MO
                                   WHERE DocNo='{0}' AND Org='{1}'";
                typesql = string.Format(typesql, InfoList[0].MOCode, OrgID);
                DataTable typedt = DBhlper.Query(typesql, Appconfig.GetU9ConnStr());
                if (typedt.Rows.Count != 0)
                {
                    //if (typedt.Rows[0]["BusinessType"].ToString() == "2417")
                    //{
                    //    rptInfo.m_docType.m_iD = 1002104250000186;
                    //    rptInfo.m_docType.m_code = "8";
                    //}
                    //else
                    //{
                    //    rptInfo.m_docType.m_iD = 1002104250000203;
                    //    rptInfo.m_docType.m_code = "9";
                    //}
                    string ReptSQL = @"select cc.id,cc.code,BusinessType,dbo.F_GetEnumName('UFIDA.U9.Base.Doc.BusinessTypeEnum', BusinessType ,'zh-CN') 业务类型名称 ,ccc.Name
                            from Complete_RcvRptDocType cc
                            LEFT JOIN Complete_RcvRptDocType_Trl ccc ON cc.id=ccc.id AND ccc.SysMLFlag='zh-CN'
                                        WHERE  cc.Org='{0}' and BusinessType='{1}' AND cc.code<>'6' ";
                    ReptSQL = string.Format(ReptSQL, OrgID, typedt.Rows[0]["BusinessType"].ToString());
                    DataTable ReptDT = DBhlper.Query(ReptSQL, Appconfig.GetU9ConnStr());
                    if (ReptDT != null && ReptDT.Rows.Count > 0)
                    {
                        foreach (DataRow item in ReptDT.Rows)
                        {
                            if (item["业务类型名称"].ToString() == "标准生产")
                            {
                                foreach (var item__ in InfoList)
                                {
                                    foreach (var ite in item__.details)
                                    {
                                        //成品
                                        if (ite.OutType == 0 && item["Name"].ToString() == "成品入库单")
                                        {
                                            rptInfo.m_docType.m_code = item["code"].ToString();
                                        }

                                        if (ite.OutType == 2 && item["Name"].ToString() == "有BOM联副产品入库单")
                                        {
                                            rptInfo.m_docType.m_code = item["code"].ToString();
                                        }
                                    }
                                }
                            }
                            else
                            {
                                rptInfo.m_docType.m_code = item["code"].ToString();
                            }
                        }
                    }

                }
                else
                {
                    rtnpo = new rtnRcvInfo();
                    rtnpo.IsSuccess = false;
                    rtnpo.Message = "未获取到工单对应业务类型!";
                    return rtnpo;
                }
                rptInfo.m_businessDate = DateTime.Now;
                List<UFIDAU9ISVMOWOInfoDTOData> rptlinelist = new List<UFIDAU9ISVMOWOInfoDTOData>();
                foreach (var Info in InfoList)
                {
                    UFIDAU9ISVMOWOInfoDTOData rptlineinfo = new UFIDAU9ISVMOWOInfoDTOData();

                    strlog.AppendLine("生产订单号:" + Info.MOCode);
                    strlog.AppendLine("存储地点:" + Info.WHCode);
                    strlog.AppendLine("组织编码:" + Info.WorkPoint);
                    strlog.AppendLine("--------------------------------------------------");

                    if (!string.IsNullOrEmpty(Info.WorkPoint))
                    {
                        string orgsql = @"select ID from Base_Organization
                                          where Code='{0}'";
                        orgsql = string.Format(orgsql, Info.WorkPoint);
                        DataTable orgdt = DBhlper.Query(orgsql, Appconfig.GetU9ConnStr());
                        if (orgdt.Rows.Count != 0)
                        {
                            OrgID = orgdt.Rows[0]["ID"].ToString();
                        }
                        else
                        {
                            rtnpo = new rtnRcvInfo();
                            rtnpo.IsSuccess = false;
                            rtnpo.Message = "未获取到组织";
                            return rtnpo;
                        }
                        string whsql = @"select StorageType from CBO_Wh
                                 where Code='{0}' and Org='{1}'";
                        whsql = string.Format(whsql, Info.WHCode, OrgID);
                        DataTable whdt = DBhlper.Query(whsql, Appconfig.GetU9ConnStr());
                        if (whdt.Rows.Count != 0)
                        {
                            StorageType = Convert.ToInt32(whdt.Rows[0]["StorageType"]);
                        }
                        else
                        {
                            rtnpo = new rtnRcvInfo();
                            rtnpo.IsSuccess = false;
                            rtnpo.Message = "未获取到存储地点对应默认存储类型";
                            return rtnpo;
                        }
                    }
                    else
                    {
                        rtnpo = new rtnRcvInfo();
                        rtnpo.IsSuccess = false;
                        rtnpo.Message = "传入组织不能为空";
                        return rtnpo;
                    }
                    foreach (var line in Info.details)
                    {
                        rptlineinfo = new UFIDAU9ISVMOWOInfoDTOData();
                        strlog.AppendLine("物料编码:" + line.InvCode);
                        strlog.AppendLine("入库批号:" + line.BatchCode);
                        strlog.AppendLine("入库数量:" + line.Quantity);
                        strlog.AppendLine("--------------------------------------------------");
                        #region 获取料品信息
                        string sqlItem = @"select ID from CBO_ItemMaster
                                       WHERE Code='{0}' AND Org='{1}'";
                        sqlItem = string.Format(sqlItem, line.InvCode, OrgID);
                        DataTable _dtItem = DBhlper.Query(sqlItem, Appconfig.GetU9ConnStr());
                        if (_dtItem != null && _dtItem.Rows.Count > 0)
                        {
                            ItemID = long.Parse(_dtItem.Rows[0]["ID"].ToString());
                        }
                        else
                        {
                            rtnpo = new rtnRcvInfo();
                            rtnpo.IsSuccess = false;
                            rtnpo.Message = "传入料品编码未在U9获取到有效的料品ID";
                            return rtnpo;
                        }
                        #endregion
                        #region 获取仓库信息
                        string sqlWH = @"select ID from CBO_Wh
                                     WHERE Code='{0}' AND Org='{1}' ";
                        sqlWH = string.Format(sqlWH, Info.WHCode, OrgID);
                        DataTable _dtWH = DBhlper.Query(sqlWH, Appconfig.GetU9ConnStr());
                        string WHCode = string.Empty;
                        if (_dtWH != null && _dtWH.Rows.Count > 0)
                        {
                            WHID = long.Parse(_dtWH.Rows[0]["ID"].ToString());
                        }
                        else
                        {
                            rtnpo = new rtnRcvInfo();
                            rtnpo.IsSuccess = false;
                            rtnpo.Message = "传入存储地点未在U9获取到有效的存储地点ID";
                            return rtnpo;
                        }
                        #endregion
                        #region 获取生产订单信息
                        string sqlMO = @"select ID from MO_MO
                                     where DocNO='{0}' AND Org='{1}'";
                        sqlMO = string.Format(sqlMO, Info.MOCode, OrgID);
                        DataTable _dtMO = DBhlper.Query(sqlMO, Appconfig.GetU9ConnStr());
                        if (_dtMO != null && _dtMO.Rows.Count > 0)
                        {
                            MOID = long.Parse(_dtMO.Rows[0]["ID"].ToString());
                        }
                        else
                        {
                            rtnpo = new rtnRcvInfo();
                            rtnpo.IsSuccess = false;
                            rtnpo.Message = "传入工单编码未在U9获取到有效的工单编码ID";
                            return rtnpo;
                        }
                        #endregion
                        rptlineinfo.m_storageType = StorageType;
                        rptlineinfo.m_mOKey = new UFIDAU9ISVMOWOKeyData();
                        rptlineinfo.m_mOKey.m_docNo = Info.MOCode;
                        rptlineinfo.m_mOKey.m_iD = MOID;
                        rptlineinfo.m_item = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                        rptlineinfo.m_item.m_code = line.InvCode;
                        rptlineinfo.m_item.m_iD = ItemID;
                        if (typedt.Rows[0]["BusinessType"].ToString() == "2417")
                        {
                            rptlineinfo.m_outputType = 1;
                        }
                        else
                        {
                            rptlineinfo.m_outputType = 0;
                        }

                        rptlineinfo.m_outputType = line.OutType;

                        if (!string.IsNullOrEmpty(line.BatchCode))
                        {
                            #region 创建批号接口调用

                            string LotID = "";
                            if (true)
                            {
                                string sqlLot = @"SELECT ID FROM Lot_LotMaster WHERE ItemCode='{0}'  AND LotCode ='{1}'";
                                sqlLot = string.Format(sqlLot, line.InvCode, line.BatchCode);
                                DataTable dtLot = DBhlper.Query(sqlLot, Appconfig.GetU9ConnStr());
                                if (dtLot.Rows.Count > 0)
                                {
                                    LotID = dtLot.Rows[0]["ID"].ToString();
                                }
                            }

                            if (string.IsNullOrEmpty(LotID))
                            {
                                CustCreateLotMaster LotMasterCreate = new CustCreateLotMaster();
                                string lotWHCode = Info.WHCode;
                                string lotItemCode = line.InvCode;
                                string LotCode = line.BatchCode;
                                LotMasterCreate.CustCreateRCVLotMaster(lotWHCode, lotItemCode, LotCode, OrgID, ref LotID);
                            }
                            #endregion
                            rptlineinfo.m_lotMaster = long.Parse(LotID);
                            rptlineinfo.m_lotNo = line.BatchCode;
                        }
                        rptlineinfo.m_completeQty = line.Quantity;
                        rptlineinfo.m_completeQtyByCostUOM = line.Quantity;
                        rptlineinfo.m_completeQtyByWhUOM = line.Quantity;
                        rptlineinfo.m_wh = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                        rptlineinfo.m_wh.m_code = Info.WHCode;
                        rptlineinfo.m_wh.m_iD = WHID;
                        rptlinelist.Add(rptlineinfo);
                    }
                }
                rptInfo.m_completeList = rptlinelist.ToArray();
                rptInfoList.Add(rptInfo);
                RcvRptList = rptInfoList.ToArray();
                //给上下文信息赋值
                context = CreateContextObj(OrgID, "", "");
                (client.Endpoint.Binding as BasicHttpBinding).MaxReceivedMessageSize = int.MaxValue;
                (client.Endpoint.Binding as BasicHttpBinding).MaxBufferSize = int.MaxValue;

                returnItems = client.Do(context, RcvRptList, false, 0, out returnMsg);
                foreach (UFIDAU9ISVMOWOKeyData returnInfo in returnItems)
                {
                    strlog.AppendLine("返回信息(returnInfo.ID)：" + returnInfo.m_iD);
                    rtnpo = new rtnRcvInfo();
                    //行信息 服务不返回 sql查询
                    string sql = @"select A.DocNo as docNo,A1.LineNum as LineNum,A1.ID as lineID from Complete_RcvRptDoc A 
                                   left join Complete_RcvRptDocLine A1 on A.ID=A1.RcvRptDoc where A.ID='{0}'";
                    sql = string.Format(sql, returnInfo.m_iD);
                    DataTable dt = DBhlper.Query(sql, Appconfig.GetU9ConnStr());
                    if (dt.Rows.Count > 0)
                    {
                        rtnpo.DocNo = dt.Rows[0]["docNo"].ToString();
                        rtnpo.IsSuccess = true;
                        List<rtnRcvLine> pOLines = new List<rtnRcvLine>();
                        foreach (DataRow dr in dt.Rows)
                        {
                            rtnRcvLine line = new rtnRcvLine();
                            line.LineNo = int.Parse(dr["LineNum"].ToString());
                            line.LogId = "";
                            pOLines.Add(line);
                        }
                        rtnpo.rtnLines = pOLines.ToArray();
                    }
                }
                if (returnItems != null && returnItems.Length > 0)
                {
                    //获取返回信息得到创建的收货单信息
                    foreach (UFIDAU9ISVMOWOKeyData returnInfo in returnItems)
                    {
                        //审核收货单
                        string approvesql = @"select ID,DocNo from Complete_RcvRptDoc
                                              where ID='{0}' and Org='{1}'";
                        approvesql = string.Format(approvesql, returnInfo.m_iD, OrgID);
                        DataTable approvedt = DBhlper.Query(approvesql, Appconfig.GetU9ConnStr());
                        if (approvedt.Rows.Count > 0)
                        {
                            //strlog.AppendLine("开始调用审核成品入库单接口------------");
                            //CustRcvRptApprove rptapprove = new CustRcvRptApprove();

                            //List<RcvRptApproveModel> list = new List<RcvRptApproveModel>();

                            //UFIDA.ISV.RcvRptApprove.CustRcvRptApprove.OperationResult resultt = rptapprove.CustApproveRcvRpt(long.Parse(approvedt.Rows[0]["ID"].ToString()), OrgID.ToString());
                            ////bool approveresult = rptapprove.CustApproveRcvRpt(long.Parse(approvedt.Rows[0]["ID"].ToString()), OrgID.ToString());
                            //if (resultt.Success == true)
                            //{
                            //    strlog.AppendLine("成品入库单审核成功------------");
                            //}
                            //else
                            //{
                            //    strlog.AppendLine("成品入库单审核失败------------");
                            //    strlog.AppendLine("开始调用删除成品入库单接口------------");
                            //    CustDeleteRcvRpt rptDelete = new CustDeleteRcvRpt();
                            //    rptDelete.CustRcvRptDelete(long.Parse(approvedt.Rows[0]["ID"].ToString()), OrgID);
                            //    strlog.AppendLine("删除成品入库单结束------------");
                            //    rtnpo = new rtnRcvInfo();
                            //    rtnpo.IsSuccess = false;
                            //    rtnpo.Message = "成品入库单审核失败，生成的单据已经删除!";
                            //    return rtnpo;
                            //}
                        }
                    }
                }
                strlog.AppendLine("返回数据:");
                strlog.AppendLine("单号:" + rtnpo.DocNo);
                strlog.AppendLine("结果:" + rtnpo.IsSuccess);
                strlog.AppendLine("返回消息:" + rtnpo.Message);
                foreach (var _line in rtnpo.rtnLines)
                {
                    strlog.AppendLine("行号:" + _line.LineNo);
                }
                strlog.AppendLine("*****************************************************");
                Appconfig.WriteLogFile(strlog.ToString(), "创建成品入库单");

                return rtnpo;
            }
            catch (Exception ex)
            {
                //异常信息捕获
                rtnRcvInfo rtnpo = new rtnRcvInfo();
                rtnpo.IsSuccess = false;
                rtnpo.Message = GetExceptionMessage(ex);

                StringBuilder strlog = new StringBuilder();
                strlog.AppendLine("创建成品入库单");
                strlog.AppendLine("*****************************************************");
                foreach (var item in InfoList)
                {
                    strlog.AppendLine("生产订单号:" + item.MOCode);
                    strlog.AppendLine("存储地点:" + item.WHCode);
                    strlog.AppendLine("组织编码:" + item.WorkPoint);
                    strlog.AppendLine("--------------------------------------------------");
                    foreach (var line in item.details)
                    {
                        strlog.AppendLine("物料编码:" + line.InvCode);
                        strlog.AppendLine("入库批号:" + line.BatchCode);
                        strlog.AppendLine("入库数量:" + line.Quantity);
                    }
                    strlog.AppendLine("--------------------------------------------------");

                }
                strlog.AppendLine("返回消息：" + rtnpo.Message);
                strlog.AppendLine("*****************************************************");
                Appconfig.WriteLogFile(strlog.ToString(), "创建成品入库单");

                return rtnpo;
            }
            #endregion
        }

        /// <summary>
        /// 根据完工申报单创建成品入库单（内部调用，无API入口）
        /// </summary>
        /// <param name="InfoList"></param>
        /// <returns></returns>
        public Result CreateRcvRptByCompleteApplyDoc(List<RcvRptByCompleteApplyInfo> InfoList, string OrgID, string UserID, string UserCode, List<ICSManufactureReceiveDocComRcvRpt> datalist)
        {
            var res = new Result();
            try
            {
                UFIDAU9ISVMOICreateRcvRptDocClient client = new UFIDAU9ISVMOICreateRcvRptDocClient();
                //服务返回结果
                UFIDAU9ISVMOWOKeyData[] returnItems;
                //返回异常信息，目前还没有使用此属性
                UFSoft.UBF.Exceptions.MessageBase[] returnMsg;
                //上下文信息
                object context;
                //传入 参数
                UFIDAU9ISVMOCompleteDocInfoDTOData[] RcvRptList;
                //空
                string[] splitBy = new string[] { };
                int StorageType = 0;
                long WHID = 0;
                long ItemID = 0;
                long MOID = 0;

                string DocBusinessType = "";
                List<UFIDAU9ISVMOCompleteDocInfoDTOData> rptInfoList = new List<UFIDAU9ISVMOCompleteDocInfoDTOData>();
                UFIDAU9ISVMOCompleteDocInfoDTOData rptInfo = new UFIDAU9ISVMOCompleteDocInfoDTOData();
                List<UFIDAU9ISVMOWOInfoDTOData> rptlinelist = new List<UFIDAU9ISVMOWOInfoDTOData>();
                UFIDAU9ISVMOWOInfoDTOData rptlineinfo = new UFIDAU9ISVMOWOInfoDTOData();
                foreach (var Info in InfoList)
                {
                    string typesql = @"select B.BusinessType from Complete_CompleteApplyDoc A
                                    LEFT JOIN Complete_CompleteApplyDocType B ON B.ID=A.CompleteApplyDocType
                                    WHERE A.DocNo='{0}' AND A.Org='{1}'";
                    typesql = string.Format(typesql, Info.MOCode, OrgID);
                    DataTable typedt = DBhlper.Query(typesql, Appconfig.GetU9ConnStr());
                    if (typedt.Rows.Count != 0)
                    {
                        string ReptSQL = @"select cc.id,cc.code,BusinessType,dbo.F_GetEnumName('UFIDA.U9.Base.Doc.BusinessTypeEnum', BusinessType ,'zh-CN') 业务类型名称 ,ccc.Name
                                        from Complete_RcvRptDocType cc
                                        LEFT JOIN Complete_RcvRptDocType_Trl ccc ON cc.id=ccc.id AND ccc.SysMLFlag='zh-CN'
                                        WHERE  cc.Org='{0}' and BusinessType='{1}'";
                        ReptSQL = string.Format(ReptSQL, OrgID, typedt.Rows[0]["BusinessType"].ToString());
                        DataTable ReptDT = DBhlper.Query(ReptSQL, Appconfig.GetU9ConnStr());
                        if (ReptDT.Rows.Count > 0)
                        {
                            DocBusinessType = ReptDT.Rows[0]["BusinessType"].ToString();
                            rptInfo = new UFIDAU9ISVMOCompleteDocInfoDTOData();
                            rptInfo.m_docType = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                            rptInfo.m_businessDate = DateTime.Now;
                            rptInfo.m_docType.m_code = ReptDT.Rows[0]["code"].ToString();
                            rptlinelist = new List<UFIDAU9ISVMOWOInfoDTOData>();
                            rptlineinfo = new UFIDAU9ISVMOWOInfoDTOData();

                        }
                        else
                        {
                            throw new Exception("完工申报单业务类型未查询到对应的成品入库单单据类型信息");
                        }
                    }
                    else
                    {
                        throw new Exception("完工申报单未查询到业务类型信息");
                    }

                    foreach (var line in Info.details)
                    {
                        rptlineinfo = new UFIDAU9ISVMOWOInfoDTOData();

                        #region 获取料品信息
                        string sqlItem = @"select ID from CBO_ItemMaster
                                       WHERE Code='{0}' AND Org='{1}'";
                        sqlItem = string.Format(sqlItem, line.InvCode, OrgID);
                        DataTable _dtItem = DBhlper.Query(sqlItem, Appconfig.GetU9ConnStr());
                        if (_dtItem.Rows.Count > 0)
                        {
                            ItemID = long.Parse(_dtItem.Rows[0]["ID"].ToString());
                        }
                        else
                        {
                            throw new Exception("传入料品编码未在U9获取到有效的料品ID");
                        }
                        #endregion
                        #region 获取仓库信息
                        string sqlWH = @"select ID,StorageType from CBO_Wh
                                     WHERE Code='{0}' AND Org='{1}' ";
                        sqlWH = string.Format(sqlWH, line.WHCode, OrgID);
                        DataTable _dtWH = DBhlper.Query(sqlWH, Appconfig.GetU9ConnStr());
                        string WHCode = string.Empty;
                        if (_dtWH.Rows.Count > 0)
                        {
                            WHID = long.Parse(_dtWH.Rows[0]["ID"].ToString());
                            StorageType = Convert.ToInt32(_dtWH.Rows[0]["StorageType"]);
                        }
                        else
                        {
                            throw new Exception("传入存储地点未在U9获取到有效的存储地点ID");
                        }
                        #endregion


                        string sql = "select MO from Complete_CompleteApplyDocLine where ID =" + line.MODetailID;
                        DataTable dt = DBhlper.Query(sql, Appconfig.GetU9ConnStr());
                        if (dt.Rows.Count == 0)
                        {
                            throw new Exception("完工申报单行ID未查询到对应的生产订单");
                        }



                        MOID = long.Parse(dt.Rows[0]["MO"].ToString());
                        rptlineinfo.m_storageType = StorageType;
                        rptlineinfo.m_ownerOrg = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                        rptlineinfo.m_ownerOrg.m_iD = long.Parse(OrgID);
                        rptlineinfo.m_ownerOrg.m_code = Info.WorkPoint;
                        rptlineinfo.m_mOKey = new UFIDAU9ISVMOWOKeyData();
                        //rptlineinfo.m_mOKey.m_docNo = Info.MOCode;
                        rptlineinfo.m_mOKey.m_iD = MOID;
                        rptlineinfo.m_item = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                        rptlineinfo.m_item.m_code = line.InvCode;
                        rptlineinfo.m_item.m_iD = ItemID;
                        if (typedt.Rows[0]["BusinessType"].ToString() == "2417")
                        {
                            rptlineinfo.m_outputType = 1;
                        }
                        else
                        {
                            rptlineinfo.m_outputType = 0;
                        }

                        if (!string.IsNullOrEmpty(line.BatchCode))
                        {
                            #region 创建批号接口调用

                            string LotID = "";
                            if (true)
                            {
                                string sqlLot = @"SELECT ID,InvalidTime,CreatedOn FROM Lot_LotMaster WHERE ItemCode='{0}'  AND LotCode ='{1}'";
                                sqlLot = string.Format(sqlLot, line.InvCode, line.BatchCode);
                                DataTable dtLot = DBhlper.Query(sqlLot, Appconfig.GetU9ConnStr());
                                if (dtLot.Rows.Count > 0)
                                {
                                    if (string.IsNullOrEmpty(dtLot.Rows[0]["InvalidTime"].ToString()))
                                    {
                                        #region 因U9原因创建出的批号失效时间为空，需要更新批号并赋予失效时间
                                        CustCreateLotMaster LotMasterCreate = new CustCreateLotMaster();
                                        string BatchID = dtLot.Rows[0]["ID"].ToString();
                                        string lotWHCode = line.WHCode;
                                        string lotItemCode = line.InvCode;
                                        string LotCode = line.BatchCode;
                                        DateTime EffectiveDatetime = Convert.ToDateTime(dtLot.Rows[0]["CreatedOn"].ToString());
                                        LotMasterCreate.CreateRCVLotMasterSpecial(BatchID, lotWHCode, lotItemCode, LotCode, EffectiveDatetime, OrgID, ref LotID);
                                        #endregion
                                    }
                                    else
                                    {
                                        LotID = dtLot.Rows[0]["ID"].ToString();
                                    }
                                }
                            }

                            if (string.IsNullOrEmpty(LotID))
                            {
                                CustCreateLotMaster LotMasterCreate = new CustCreateLotMaster();
                                string lotWHCode = line.WHCode;
                                string lotItemCode = line.InvCode;
                                string LotCode = line.BatchCode;
                                LotMasterCreate.CustCreateRCVLotMaster(lotWHCode, lotItemCode, LotCode, OrgID, ref LotID);
                            }
                            #endregion
                            rptlineinfo.m_lotMaster = long.Parse(LotID);
                            rptlineinfo.m_lotNo = line.BatchCode;
                        }
                        rptlineinfo.m_completeQty = line.Quantity;
                        rptlineinfo.m_completeQtyByCostUOM = line.Quantity;
                        rptlineinfo.m_completeQtyByWhUOM = line.Quantity;
                        rptlineinfo.m_wh = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                        rptlineinfo.m_wh.m_code = line.WHCode;
                        rptlineinfo.m_wh.m_iD = WHID;
                        rptlineinfo.m_descFlexField = new UFIDAU9BaseFlexFieldDescFlexFieldDescFlexSegmentsData();
                        rptlineinfo.m_descFlexField.m_privateDescSeg30 = line.LogIds;
                        rptlinelist.Add(rptlineinfo);
                    }
                }

                rptInfo.m_completeList = rptlinelist.ToArray();
                rptInfoList.Add(rptInfo);
                RcvRptList = rptInfoList.ToArray();
                //给上下文信息赋值
                context = CreateContextObj(OrgID, UserID, UserCode);
                (client.Endpoint.Binding as BasicHttpBinding).MaxReceivedMessageSize = int.MaxValue;
                (client.Endpoint.Binding as BasicHttpBinding).MaxBufferSize = int.MaxValue;

                returnItems = client.Do(context, RcvRptList, false, 0, out returnMsg);
                if (returnItems != null && returnItems.Length > 0)
                {
                    //获取返回信息得到创建的收货单信息
                    foreach (UFIDAU9ISVMOWOKeyData returnInfo in returnItems)
                    {
                        try
                        {
                            //行信息 服务不返回 sql查询
                            string sql = @"select A.DocNo as docNo,A1.LineNum as LineNum,A1.ID as lineID from Complete_RcvRptDoc A 
                                   left join Complete_RcvRptDocLine A1 on A.ID=A1.RcvRptDoc where A.ID='{0}'";
                            sql = string.Format(sql, returnInfo.m_iD);
                            DataTable dt = DBhlper.Query(sql, Appconfig.GetU9ConnStr());
                            if (dt.Rows.Count > 0)
                            {
                                CustRcvRptApprove rptapprove = new CustRcvRptApprove();
                                Result resultt = rptapprove.CustApproveRcvRpt(new List<RcvRptApproveModel>
                            {
                                new RcvRptApproveModel
                                {
                                    ID = returnInfo.m_iD.ToString(),
                                    WorkPoint = InfoList[0].WorkPoint,
                                    User = InfoList[0].User
                                }
                            });

                                if (resultt.Success)
                                {
                                    sql = @"select distinct a.ID,a.DocNo,b.ID LineID,b.LineNum,c.Code,b.RcvQtyByWhUOM,b.MO,a.DocState,
                                            b.DescFlexField_PrivateDescSeg30,b.SourceDoc_SrcDocLine_EntityID 
                                            from Complete_RcvRptDoc a
                                            left join Complete_RcvRptDocLine b on a.ID = b.RcvRptDoc
                                            left join CBO_ItemMaster c on b.Item = c.ID
                                            where a.ID ='" + returnItems[0].m_iD + "'";
                                    dt = DBhlper.Query(sql, Appconfig.GetU9ConnStr());
                                    if (dt.Rows.Count == 0)
                                    {
                                        throw new Exception("U9标准服务返回的单据ID未查询到相关单据信息");
                                    }



                                    var linelist = new List<ICSManufactureReceiveDocsComRcvRpt>();
                                    foreach (DataRow dr in dt.Rows)
                                    {
                                        linelist.Add(new ICSManufactureReceiveDocsComRcvRpt
                                        {
                                            DetailID = dr["LineID"].ToString(),
                                            Sequence = dr["LineNum"].ToString(),
                                            InvCode = dr["Code"].ToString(),
                                            Quantity = decimal.Parse(dr["RcvQtyByWhUOM"].ToString()),
                                            CRTDetailID = dr["SourceDoc_SrcDocLine_EntityID"].ToString(),
                                            LogIds = dr["DescFlexField_PrivateDescSeg30"].ToString()
                                        });
                                    }


                                    datalist.Add(new ICSManufactureReceiveDocComRcvRpt
                                    {
                                        ID = dt.Rows[0]["ID"].ToString(),
                                        CRTCode = dt.Rows[0]["DocNo"].ToString(),
                                        IsSuccess = true,
                                        Message = "创建已审核的单据成功",
                                        details = linelist
                                    });

                                    res.Success = true;
                                    res.Message = "成功";
                                }
                            }
                            else
                            {
                                throw new Exception("服务返回的单据ID未查询到相关的单据信息");
                            }
                        }
                        catch (Exception ex)
                        {
                            try
                            {
                                CustDeleteRcvRpt rptDelete = new CustDeleteRcvRpt();
                                Result resulltdelete = rptDelete.CustRcvRptDelete(returnInfo.m_iD, OrgID);

                                if (!resulltdelete.Success)
                                {
                                    throw new Exception(resulltdelete.Message);
                                }

                                res.Success = false;
                                res.Message = "单据创建成功，审核失败，删除成功，审核异常：" + GetExceptionMessage(ex);
                                return res;
                            }
                            catch (Exception exdelete)
                            {
                                throw new Exception("单据创建成功，审核失败，删除失败，审核异常：" + ex.Message + "，删除异常：" + exdelete.Message);
                            }
                        }
                    }
                }
                else
                {
                    throw new Exception("服务返回对象为空");
                }

            }
            catch (Exception ex)
            {
                res.Success = false;
                res.Message = GetExceptionMessage(ex);
            }

            return res;

        }

        /// <summary>
        /// 根据工单创建成品入库单（内部调用，无API入口）
        /// </summary>
        /// <param name="InfoList"></param>
        /// <returns></returns>
        public Result CreateRcvRptByMo(List<RcvRptByCompleteApplyInfo> InfoList, string OrgID, string UserID, string UserCode, List<ICSManufactureReceiveDoc> datalist, string UserName)
        {
            #region 服务调用框架结构
            var res = new Result();
            try
            {
                UFIDAU9ISVMOICreateRcvRptDocClient client = new UFIDAU9ISVMOICreateRcvRptDocClient();
                //服务返回结果
                UFIDAU9ISVMOWOKeyData[] returnItems;
                //返回异常信息，目前还没有使用此属性
                UFSoft.UBF.Exceptions.MessageBase[] returnMsg;
                //上下文信息
                object context;
                //传入 参数
                UFIDAU9ISVMOCompleteDocInfoDTOData[] RcvRptList;
                //空
                string[] splitBy = new string[] { };
                int StorageType = 0;
                string DeptID = "";
                long WHID = 0;
                long ItemID = 0;
                long MOID = 0;


                if (InfoList == null || InfoList.Count == 0)
                {
                    throw new Exception("传入参数不能为空");
                }


                string DocBusinessType = "";
                List<UFIDAU9ISVMOCompleteDocInfoDTOData> rptInfoList = new List<UFIDAU9ISVMOCompleteDocInfoDTOData>();
                UFIDAU9ISVMOCompleteDocInfoDTOData rptInfo = new UFIDAU9ISVMOCompleteDocInfoDTOData();
                List<UFIDAU9ISVMOWOInfoDTOData> rptlinelist = new List<UFIDAU9ISVMOWOInfoDTOData>();
                UFIDAU9ISVMOWOInfoDTOData rptlineinfo = new UFIDAU9ISVMOWOInfoDTOData();
                foreach (var Info in InfoList)
                {
                    string typesql = @" select B.BusinessType from MO_MO A
                                    LEFT JOIN MO_MODocType B ON B.ID=A.MODocType AND B.Org=A.Org
                                    WHERE A.DocNo='{0}' AND A.Org='{1}'";
                    typesql = string.Format(typesql, Info.MOCode, OrgID);
                    DataTable typedt = DBhlper.Query(typesql, Appconfig.GetU9ConnStr());
                    if (typedt.Rows.Count != 0)
                    {
                        string ReptSQL = @"select cc.id,cc.code,BusinessType,dbo.F_GetEnumName('UFIDA.U9.Base.Doc.BusinessTypeEnum', BusinessType ,'zh-CN') 业务类型名称 ,ccc.Name
                                        from Complete_RcvRptDocType cc
                                        LEFT JOIN Complete_RcvRptDocType_Trl ccc ON cc.id=ccc.id AND ccc.SysMLFlag='zh-CN'
                                        WHERE  cc.Org='{0}' and BusinessType='{1}'";
                        ReptSQL = string.Format(ReptSQL, OrgID, typedt.Rows[0]["BusinessType"].ToString());
                        DataTable ReptDT = DBhlper.Query(ReptSQL, Appconfig.GetU9ConnStr());
                        if (ReptDT != null && ReptDT.Rows.Count > 0)
                        {
                            if (DocBusinessType == "")
                            {
                                DocBusinessType = ReptDT.Rows[0]["BusinessType"].ToString();
                                rptInfo = new UFIDAU9ISVMOCompleteDocInfoDTOData();
                                rptInfo.m_docType = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                                rptInfo.m_businessDate = DateTime.Now;
                                rptInfo.m_docType.m_code = ReptDT.Rows[0]["code"].ToString();

                                rptlinelist = new List<UFIDAU9ISVMOWOInfoDTOData>();
                                rptlineinfo = new UFIDAU9ISVMOWOInfoDTOData();
                            }
                            else
                            {
                                if (DocBusinessType != ReptDT.Rows[0]["BusinessType"].ToString())
                                {
                                    DocBusinessType = ReptDT.Rows[0]["BusinessType"].ToString();
                                    rptInfo.m_completeList = rptlinelist.ToArray();
                                    rptInfoList.Add(rptInfo);
                                    rptInfo = new UFIDAU9ISVMOCompleteDocInfoDTOData();
                                    rptInfo.m_docType = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                                    rptInfo.m_businessDate = DateTime.Now;
                                    rptInfo.m_docType.m_code = ReptDT.Rows[0]["code"].ToString();
                                    rptlinelist = new List<UFIDAU9ISVMOWOInfoDTOData>();
                                    rptlineinfo = new UFIDAU9ISVMOWOInfoDTOData();
                                }
                            }
                        }
                    }
                    else
                    {
                        throw new Exception("未获取到工单对应业务类型!");
                    }



                    foreach (var line in Info.details)
                    {
                        rptlineinfo = new UFIDAU9ISVMOWOInfoDTOData();
                        #region 获取料品信息
                        string sqlItem = @"select ID from CBO_ItemMaster
                                       WHERE Code='{0}' AND Org='{1}' and Version ='{2}'";
                        sqlItem = string.Format(sqlItem, line.InvCode, OrgID, line.Version);
                        DataTable _dtItem = DBhlper.Query(sqlItem, Appconfig.GetU9ConnStr());
                        if (_dtItem != null && _dtItem.Rows.Count > 0)
                        {
                            ItemID = long.Parse(_dtItem.Rows[0]["ID"].ToString());
                        }
                        else
                        {
                            throw new Exception("传入料品编码未在U9获取到有效的料品ID");
                        }
                        #endregion
                        #region 获取仓库信息
                        string sqlWH = @"select ID from CBO_Wh
                                     WHERE Code='{0}' AND Org='{1}' ";
                        sqlWH = string.Format(sqlWH, line.WHCode, OrgID);
                        DataTable _dtWH = DBhlper.Query(sqlWH, Appconfig.GetU9ConnStr());
                        string WHCode = string.Empty;
                        if (_dtWH != null && _dtWH.Rows.Count > 0)
                        {
                            WHID = long.Parse(_dtWH.Rows[0]["ID"].ToString());
                        }
                        else
                        {
                            throw new Exception("传入存储地点未在U9获取到有效的存储地点ID");
                        }


                        string whsql = @"select StorageType from CBO_Wh
                                 where Code='{0}' and Org='{1}'";
                        whsql = string.Format(whsql, line.WHCode, OrgID);
                        DataTable whdt = DBhlper.Query(whsql, Appconfig.GetU9ConnStr());
                        if (whdt.Rows.Count != 0)
                        {
                            StorageType = Convert.ToInt32(whdt.Rows[0]["StorageType"]);
                        }
                        else
                        {
                            throw new Exception("未获取到存储地点对应默认存储类型");
                        }
                        #endregion
                        MOID = long.Parse(line.MODetailID);
                        rptlineinfo.m_storageType = StorageType;
                        rptlineinfo.m_ownerOrg = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                        rptlineinfo.m_ownerOrg.m_iD = long.Parse(OrgID);
                        rptlineinfo.m_ownerOrg.m_code = Info.WorkPoint;
                        rptlineinfo.m_mOKey = new UFIDAU9ISVMOWOKeyData();
                        //rptlineinfo.m_mOKey.m_docNo = Info.MOCode;
                        rptlineinfo.m_mOKey.m_iD = MOID;
                        rptlineinfo.m_item = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                        rptlineinfo.m_item.m_code = line.InvCode;
                        rptlineinfo.m_item.m_iD = ItemID;
                        if (typedt.Rows[0]["BusinessType"].ToString() == "2417")
                        {
                            rptlineinfo.m_outputType = 1;
                        }
                        else
                        {
                            rptlineinfo.m_outputType = 0;
                        }

                        if (!string.IsNullOrEmpty(line.BatchCode))
                        {
                            #region 创建批号接口调用

                            string LotID = "";

                            string sqlLot = @"SELECT ID,InvalidTime,CreatedOn FROM Lot_LotMaster WHERE ItemCode='{0}'  AND LotCode ='{1}'";
                            sqlLot = string.Format(sqlLot, line.InvCode, line.BatchCode);
                            DataTable dtLot = DBhlper.Query(sqlLot, Appconfig.GetU9ConnStr());
                            if (dtLot.Rows.Count > 0)
                            {
                                if (string.IsNullOrEmpty(dtLot.Rows[0]["InvalidTime"].ToString()))
                                {
                                    #region 因U9原因创建出的批号失效时间为空，需要更新批号并赋予失效时间
                                    CustCreateLotMaster LotMasterCreate = new CustCreateLotMaster();
                                    string BatchID = dtLot.Rows[0]["ID"].ToString();
                                    string lotWHCode = line.WHCode;
                                    string lotItemCode = line.InvCode;
                                    string LotCode = line.BatchCode;
                                    DateTime EffectiveDatetime = Convert.ToDateTime(dtLot.Rows[0]["CreatedOn"].ToString());
                                    LotMasterCreate.CreateRCVLotMasterSpecial(BatchID, lotWHCode, lotItemCode, LotCode, EffectiveDatetime, OrgID, ref LotID);
                                    #endregion
                                }
                                else
                                {
                                    LotID = dtLot.Rows[0]["ID"].ToString();
                                }
                            }


                            if (string.IsNullOrEmpty(LotID))
                            {
                                CustCreateLotMaster LotMasterCreate = new CustCreateLotMaster();
                                string lotWHCode = line.WHCode;
                                string lotItemCode = line.InvCode;
                                string LotCode = line.BatchCode;
                                LotMasterCreate.CustCreateRCVLotMaster(lotWHCode, lotItemCode, LotCode, OrgID, ref LotID);
                            }
                            if (string.IsNullOrEmpty(LotID))
                            {
                                throw new Exception("创建批号失败");
                            }

                            #endregion
                            rptlineinfo.m_lotMaster = long.Parse(LotID);
                            rptlineinfo.m_lotNo = line.BatchCode;
                        }
                        rptlineinfo.m_completeQty = line.Quantity;
                        rptlineinfo.m_completeQtyByCostUOM = line.Quantity;
                        rptlineinfo.m_completeQtyByWhUOM = line.Quantity;
                        rptlineinfo.m_wh = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                        rptlineinfo.m_wh.m_code = line.WHCode;
                        rptlineinfo.m_wh.m_iD = WHID;

                        rptlineinfo.m_descFlexField = new UFIDAU9BaseFlexFieldDescFlexFieldDescFlexSegmentsData();
                        rptlineinfo.m_descFlexField.m_privateDescSeg30 = line.LogIds;

                        rptlinelist.Add(rptlineinfo);
                    }
                }
                rptInfo.m_completeList = rptlinelist.ToArray();
                rptInfoList.Add(rptInfo);
                RcvRptList = rptInfoList.ToArray();
                //给上下文信息赋值
                context = CreateContextObj(OrgID, UserID, UserCode);
                (client.Endpoint.Binding as BasicHttpBinding).MaxReceivedMessageSize = int.MaxValue;
                (client.Endpoint.Binding as BasicHttpBinding).MaxBufferSize = int.MaxValue;

                returnItems = client.Do(context, RcvRptList, false, 0, out returnMsg);

                if (returnItems != null && returnItems.Length > 0)
                {
                    //try
                    //{
                    #region 审核注释
                    //CustRcvRptApprove rptapprove = new CustRcvRptApprove();
                    //CustRcvRptApprove.OperationResult resultt = rptapprove.CustApproveRcvRpt(returnItems[0].m_iD, OrgID.ToString());

                    //if (resultt.Success == true)
                    //{
                    //    string sql = @"select distinct a.ID,a.DocNo,b.ID LineID,b.LineNum,c.Code,b.RcvQtyByWhUOM,b.MO,
                    //                    b.DescFlexField_PrivateDescSeg30 from Complete_RcvRptDoc a
                    //                    left join Complete_RcvRptDocLine b on a.ID = b.RcvRptDoc
                    //                    left join CBO_ItemMaster c on b.Item = c.ID
                    //                    where a.ID ='" + returnItems[0].m_iD + "'";
                    //    DataTable dt = DBhlper.Query(sql, Appconfig.GetU9ConnStr());
                    //    if (dt.Rows.Count == 0)
                    //    {
                    //        throw new Exception("U9标准服务返回的单据ID未查询到相关单据信息");
                    //    }
                    //    var linelist = new List<ICSManufactureReceiveDocs>();
                    //    foreach (DataRow dr in dt.Rows)
                    //    {
                    //        linelist.Add(new ICSManufactureReceiveDocs
                    //        {
                    //            DetailID = dr["LineID"].ToString(),
                    //            Sequence = dr["LineNum"].ToString(),
                    //            InvCode = dr["Code"].ToString(),
                    //            Quantity = decimal.Parse(dr["RcvQtyByWhUOM"].ToString()),
                    //            MODetailID = dr["MO"].ToString(),
                    //            LogIds = dr["DescFlexField_PrivateDescSeg30"].ToString()
                    //        });
                    //    }


                    //    datalist.Add(new ICSManufactureReceiveDoc
                    //    {
                    //        ID = dt.Rows[0]["ID"].ToString(),
                    //        MRCVCode = dt.Rows[0]["DocNo"].ToString(),
                    //        IsSuccess = true,
                    //        Message = "创建已审核的单据成功",
                    //        details = linelist
                    //    });

                    //    res.Success = true;
                    //    res.Message = "成功";
                    //}
                    //else
                    //{
                    //    throw new Exception(resultt.Message);
                    //}

                    #endregion

                    string sql = @"select distinct a.ID,a.DocNo,b.ID LineID,b.LineNum,c.Code,b.RcvQtyByWhUOM,b.MO,a.DocState,
                                            b.DescFlexField_PrivateDescSeg30 from Complete_RcvRptDoc a
                                            left join Complete_RcvRptDocLine b on a.ID = b.RcvRptDoc
                                            left join CBO_ItemMaster c on b.Item = c.ID
                                            where a.ID ='" + returnItems[0].m_iD + "'";
                    DataTable dt = DBhlper.Query(sql, Appconfig.GetU9ConnStr());
                    if (dt.Rows.Count == 0)
                    {
                        throw new Exception("U9标准服务返回的单据ID未查询到相关单据信息");
                    }


                    sql = "update Complete_RcvRptDoc set CreatedBy ='" + UserName + "',ApproveBy ='" + UserName + "' where id ='" + returnItems[0].m_iD + "'";
                    DBhlper.EXecute(sql, Appconfig.GetU9ConnStr());

                    //if (dt.Rows[0]["DocState"].ToString()=="2")//审核
                    //{
                    //    dic.Add(returnItems[0].m_iD.ToString(),"2");
                    //}
                    //else
                    //{
                    //    dic.Add(returnItems[0].m_iD.ToString(), "0");
                    //}


                    var linelist = new List<ICSManufactureReceiveDocs>();
                    foreach (DataRow dr in dt.Rows)
                    {
                        linelist.Add(new ICSManufactureReceiveDocs
                        {
                            DetailID = dr["LineID"].ToString(),
                            Sequence = dr["LineNum"].ToString(),
                            InvCode = dr["Code"].ToString(),
                            Quantity = decimal.Parse(dr["RcvQtyByWhUOM"].ToString()),
                            MODetailID = dr["MO"].ToString(),
                            LogIds = dr["DescFlexField_PrivateDescSeg30"].ToString()
                        });
                    }


                    datalist.Add(new ICSManufactureReceiveDoc
                    {
                        ID = dt.Rows[0]["ID"].ToString(),
                        MRCVCode = dt.Rows[0]["DocNo"].ToString(),
                        IsSuccess = true,
                        Message = "创建已审核的单据成功",
                        details = linelist
                    });

                    res.Success = true;
                    res.Message = "成功";
                    //}
                    //catch (Exception ex)
                    //{
                    //    try
                    //    {
                    //        CustDeleteRcvRpt rptDelete = new CustDeleteRcvRpt();
                    //        Result deleteres = rptDelete.CustRcvRptDelete(returnItems[0].m_iD, OrgID);
                    //        if (!deleteres.Success)
                    //        {
                    //            throw new Exception("单据创建成功，审核失败，删除失败，审核异常：" + ex.Message + "，删除异常：" + deleteres.Message);
                    //        }
                    //        else
                    //        {
                    //            throw new Exception("单据创建成功，审核失败，删除成功，审核异常：" + ex.Message);
                    //        }
                    //    }
                    //    catch (Exception exdelete)
                    //    {
                    //        throw new Exception("单据创建成功，审核失败，删除失败，审核异常：" + ex.Message + "，删除异常：" + exdelete.Message);
                    //    }
                    //}

                }
                else
                {
                    throw new Exception("创建失败");
                }
            }
            catch (Exception ex)
            {
                res.Success = false;
                res.Message = GetExceptionMessage(ex);
            }
            return res;
            #endregion
        }

        #region 传入参数类(联副产品/成品入库单)
        public class RcvRptInfo
        {
            private string _MOCode;

            private string _ItemCode;

            private string _WHCode;

            private string _Batch;

            private decimal _Quantity;

            private string _OrgCode;

            /// <summary>
            /// 来源生产订单
            /// </summary>
            public string MOCode
            {
                get { return _MOCode; }
                set { _MOCode = value; }
            }
            /// <summary>
            /// 传入物料编码
            /// </summary>
            public string InvCode
            {
                get { return _ItemCode; }
                set { _ItemCode = value; }
            }
            /// <summary>
            /// 入库存储地点
            /// </summary>
            public string WHCode
            {
                get { return _WHCode; }
                set { _WHCode = value; }
            }
            /// <summary>
            /// 传入入库批号
            /// </summary>
            public string BatchCode
            {
                get { return _Batch; }
                set { _Batch = value; }
            }
            /// <summary>
            /// 传入入库数量
            /// </summary>
            public decimal Quantity
            {
                get { return _Quantity; }
                set { _Quantity = value; }
            }
            /// <summary>
            /// 传入组织编码
            /// </summary>
            public string WorkPoint
            {
                get { return _OrgCode; }
                set { _OrgCode = value; }
            }
            public List<RcvRptLine> details { get; set; }
        }

        public class RcvRptLine
        {
            public string Sequence { get; set; }
            public string InvCode { get; set; }
            public int OutType { get; set; }


            public decimal Quantity { get; set; }

            public decimal Amount { get; set; }

            public string BatchCode { get; set; }

            public string LogId { get; set; }
        }
        #endregion

        #region 传入参数类(完工申报单生成成品入库单)
        public class RcvRptByCompleteApplyInfo
        {
            private string _MOCode;

            private string _ItemCode;

            private string _Batch;

            private decimal _Quantity;

            private string _OrgCode;

            /// <summary>
            /// 来源生产订单
            /// </summary>
            public string MOCode
            {
                get { return _MOCode; }
                set { _MOCode = value; }
            }
            /// <summary>
            /// 传入物料编码
            /// </summary>
            public string InvCode
            {
                get { return _ItemCode; }
                set { _ItemCode = value; }
            }
            /// <summary>
            /// 传入入库批号
            /// </summary>
            public string BatchCode
            {
                get { return _Batch; }
                set { _Batch = value; }
            }
            /// <summary>
            /// 传入入库数量
            /// </summary>
            public decimal Quantity
            {
                get { return _Quantity; }
                set { _Quantity = value; }
            }
            /// <summary>
            /// 传入组织编码
            /// </summary>
            public string WorkPoint
            {
                get { return _OrgCode; }
                set { _OrgCode = value; }
            }


            public string User { get; set; }
            public List<RcvRptByCompleteApplyInfoLine> details { get; set; }
        }

        public class RcvRptByCompleteApplyInfoLine
        {
            public string TransSequence { get; set; }
            public string MODetailID { get; set; }
            public string Sequence { get; set; }
            public string InvCode { get; set; }
            public int OutType { get; set; }


            public decimal Quantity { get; set; }

            public decimal Amount { get; set; }

            public string BatchCode { get; set; }

            public string WHCode { get; set; }

            public string Version { get; set; }

            public string LogIds { get; set; }
        }
        #endregion

        public class RptInfo
        {

            /// <summary>
            /// 来源入库单ID
            /// </summary>
            public string ID
            {
                get;
                set;
            }

            /// <summary>
            /// 传入组织编码
            /// </summary>
            public string WorkPoint
            {
                get;
                set;
            }

        }



        #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 给上下文信息赋值
        /// <summary>
        /// 给上下文信息赋值
        /// </summary>
        /// <returns></returns>
        private ThreadContext CreateContextObj(string OrgID, string UserID, string UserCode)
        {
            // 实例化应用上下文对象
            ThreadContext thContext = new ThreadContext();

            System.Collections.Generic.Dictionary<object, object> ns = new Dictionary<object, object>();
            ns.Add("OrgID", OrgID);
            ns.Add("UserID", UserID);
            ns.Add("UserCode", UserCode);
            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 时间戳方法
        private DateTime TimestampToDateTime(long timestamp)
        {
            DateTime dateTimeStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            long lTime = timestamp * 10000000;
            TimeSpan nowTimeSpan = new TimeSpan(lTime);
            DateTime resultDateTime = dateTimeStart.Add(nowTimeSpan);
            return resultDateTime;
        }
        #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 WorkPoint
        {
            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 rtnRcvInfo
    {
        public string DocNo { get; set; }
        public bool IsSuccess { get; set; }
        public string Message { get; set; }
        public rtnRcvLine[] rtnLines { get; set; }
    }

    public class rtnRcvLine
    {
        public int LineNo { get; set; }

        public string LogId { get; set; }

        //public string srcDocNo { get; set; }

        //public int srcLineNo { get; set; }

        //public decimal reqQty { get; set; }

        //public string proCode { get; set; }
    }
    #endregion


    #region 表体类
    //public class rCVLine
    //{
    //    /// <summary>
    //    ///  来源采购订单
    //    /// </summary>
    //    public string srcDocPONo { get; set; }

    //    private int _srcDocPOLineNo;
    //    private decimal _reqQty;
    //    public string WhCode { get; set; }

    //    /// <summary>
    //    /// 炉号
    //    /// </summary>
    //    public string FurnaceNo { get; set; }

    //    /// <summary>
    //    /// 数量
    //    /// </summary>
    //    public decimal ReqQty
    //    {
    //        get { return _reqQty; }
    //        set { _reqQty = value; }
    //    }

    //    /// <summary>
    //    /// 来源采购订单行
    //    /// </summary>
    //    public int srcDocPOLineNo
    //    {
    //        get { return _srcDocPOLineNo; }
    //        set { _srcDocPOLineNo = value; }
    //    }
    //}
    #endregion


}
