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

namespace UFIDA.ISV.CreateBFPMRecede
{

    public class CustCreateBFPMRecedeSrvSub
    {
        public List<rtnRcvInfo> CustCreateBFPMRecede(List<rCVhead> rCVInfoList)
        {
            #region 接口传入参数日志
            StringBuilder firststrlog = new StringBuilder();
            firststrlog.AppendLine("传入数据开始");
            firststrlog.AppendLine("*****************************************************");
            foreach (var item in rCVInfoList)
            {
                firststrlog.AppendLine("来源委外采购订单号:" + item.SourceCode);
                firststrlog.AppendLine("组织编码:" + item.WorkPoint);
                foreach (var line in item.details)
                {
                    firststrlog.AppendLine("来源委外采购订单行:" + line.Sequence);
                    firststrlog.AppendLine("料品编码:" + line.InvCode);
                    firststrlog.AppendLine("料品数量:" + line.Quantity);
                    firststrlog.AppendLine("批号:" + line.BatchCode);
                    firststrlog.AppendLine("仓库:" + line.WHCode);
                }
            }
            firststrlog.AppendLine("*****************************************************");
            firststrlog.AppendLine("传入数据结束");
            Appconfig.WriteLogFile(firststrlog.ToString(), "创建委外退料单");
            #endregion
            #region 服务调用框架结构
            UFIDAU9ISVPMIssueICreatPMRecedeIssueDocSVClient client = new UFIDAU9ISVPMIssueICreatPMRecedeIssueDocSVClient();
            //服务返回结果
            string[] returnItems;
            //返回异常信息，目前还没有使用此属性
            UFSoft.UBF.Exceptions1.MessageBase[] returnMsg;
            //上下文信息
            object context;
            //传入 参数
            UFIDAU9ISVPMIssuePMRecedeItemAndSnDTOData[] pOList;
            //空
            string[] splitBy = new string[] { };

            try
            {
                string OrgID = "";
                List<rtnRcvInfo> rtnpos = new List<rtnRcvInfo>();
                long PickID = 0;
                long ItemID = 0;
                if (rCVInfoList == null || rCVInfoList.Count == 0)
                {
                    StringBuilder errormsg = new StringBuilder();
                    errormsg.AppendLine("*********************报错记录开始*********************");
                    errormsg.AppendLine("传入参数不能为空！");
                    errormsg.AppendLine("*********************报错记录结束*********************");
                    Appconfig.WriteLogFile(errormsg.ToString(), "创建委外退料单");
                    rtnRcvInfo rtnpo = new rtnRcvInfo();
                    rtnpo.Success = false;
                    rtnpo.Message = "传入参数不能为空";
                    rtnpos.Add(rtnpo);
                    return rtnpos;
                }

                foreach (var item in rCVInfoList)
                {
                    if (item.details == null || item.details.Count() == 0)
                    {
                        StringBuilder errormsg = new StringBuilder();
                        errormsg.AppendLine("*********************报错记录开始*********************");
                        errormsg.AppendLine("传入行信息不能为空！");
                        errormsg.AppendLine("*********************报错记录结束*********************");
                        Appconfig.WriteLogFile(errormsg.ToString(), "创建委外退料单");
                        rtnRcvInfo rtnpo = new rtnRcvInfo();
                        rtnpo.Success = false;
                        rtnpo.Message = "传入行信息不能为空";
                        rtnpos.Add(rtnpo);
                        return rtnpos;
                    }
                    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
                    {
                        StringBuilder errormsg = new StringBuilder();
                        errormsg.AppendLine("*********************报错记录开始*********************");
                        errormsg.AppendLine("传入组织编码:" + item.WorkPoint + "不存在！");
                        errormsg.AppendLine("*********************报错记录结束*********************");
                        Appconfig.WriteLogFile(errormsg.ToString(), "创建委外退料单");
                        rtnRcvInfo rtnpo = new rtnRcvInfo();
                        rtnpo.Success = false;
                        rtnpo.Message = "传入组织编码:" + item.WorkPoint + "不存在！";
                        rtnpos.Add(rtnpo);
                        return rtnpos;
                    }
                    foreach (var _item in item.details)
                    {
                        if (_item.Sequence == 0)
                        {
                            StringBuilder errormsg = new StringBuilder();
                            errormsg.AppendLine("*********************报错记录开始*********************");
                            errormsg.AppendLine("请传入来源单据行号！");
                            errormsg.AppendLine("*********************报错记录结束*********************");
                            Appconfig.WriteLogFile(errormsg.ToString(), "创建委外退料单");
                            rtnRcvInfo rtnpo = new rtnRcvInfo();
                            rtnpo.Success = false;
                            rtnpo.Message = "请传入来源单据行号";
                            rtnpos.Add(rtnpo);
                            return rtnpos;
                        }
                        if (_item.Quantity == 0)
                        {
                            StringBuilder errormsg = new StringBuilder();
                            errormsg.AppendLine("*********************报错记录开始*********************");
                            errormsg.AppendLine("传入数量不能为空！");
                            errormsg.AppendLine("*********************报错记录结束*********************");
                            Appconfig.WriteLogFile(errormsg.ToString(), "创建委外退料单");
                            rtnRcvInfo rtnpo = new rtnRcvInfo();
                            rtnpo.Success = false;
                            rtnpo.Message = "传入数量不能为空";
                            rtnpos.Add(rtnpo);
                            return rtnpos;
                        }
                    }
                }
                //给传入参数赋值

                //pOList = SetrCVDtos(rCVInfoList);
                StringBuilder strlog = new StringBuilder();
                strlog.AppendLine("创建委外退料单");
                strlog.AppendLine("*****************************************************");

                List<UFIDAU9ISVPMIssuePMRecedeItemAndSnDTOData> rCVList = new List<UFIDAU9ISVPMIssuePMRecedeItemAndSnDTOData>();
                foreach (var rCVhead in rCVInfoList)
                {
                    strlog.AppendLine("来源委外发料单号:" + rCVhead.SourceCode);
                    foreach (rCVLine line in rCVhead.details)
                    {
                        UFIDAU9ISVPMIssuePMRecedeItemAndSnDTOData rCV = new UFIDAU9ISVPMIssuePMRecedeItemAndSnDTOData();

                        #region 获取委外发料单ID
                        string sqlPick = @"select B.ID,B.POPick,B.IsIssued from PM_IssueDoc A
                                           LEFT JOIN PM_IssueDocLine B
                                           ON B.PMIssueDoc=A.ID
                                           where A.DocNo='" + rCVhead.SourceCode + "' AND B.LineNum='" + line.Sequence + "' AND A.Org='" + OrgID + "'";
                        sqlPick = string.Format(sqlPick);
                        DataTable dtPick = DBhlper.Query(sqlPick, Appconfig.GetU9ConnStr());
                        if (dtPick.Rows.Count > 0)
                        {
                            if (dtPick.Rows[0]["IsIssued"].ToString() == "0")
                            {
                                rtnRcvInfo rtnpo = new rtnRcvInfo();
                                rtnpo.Success = false;
                                rtnpo.Message = "委外发料单" + rCVhead.SourceCode + "尚未进行发料确认，无法退料!";
                                rtnpos.Add(rtnpo);
                                return rtnpos;
                            }
                            else
                            {

                                rCV.m_pickID = long.Parse(dtPick.Rows[0]["POPick"].ToString());
                            }
                        }
                        else
                        {
                            rtnRcvInfo rtnpo = new rtnRcvInfo();
                            rtnpo.Success = false;
                            rtnpo.Message = "委外发料单行不存在!";
                            rtnpos.Add(rtnpo);
                            return rtnpos;
                        }
                        #endregion
                        #region 获取退料料品ID
                        string sqlitem = @"select ID from CBO_ItemMaster 
                                           where Code='" + line.InvCode + "' AND Org='" + OrgID + "'";
                        sqlitem = string.Format(sqlitem);
                        DataTable dtitem = DBhlper.Query(sqlitem, Appconfig.GetU9ConnStr());
                        if (dtitem.Rows.Count > 0)
                        {
                            ItemID = long.Parse(dtitem.Rows[0]["ID"].ToString());
                        }
                        else
                        {
                            rtnRcvInfo rtnpo = new rtnRcvInfo();
                            rtnpo.Success = false;
                            rtnpo.Message = "料品不存在!";
                            rtnpos.Add(rtnpo);
                            return rtnpos;
                        }
                        #endregion
                        rCV.m_itemCode = line.InvCode;
                        rCV.m_recedeQty = line.Quantity;
                        rCV.m_recedeReason = 1;
                        string sqlWH = @"select ID,Code from CBO_Wh
                                         WHERE Code='" + line.WHCode + "' AND Org='" + OrgID + "' ";
                        sqlWH = string.Format(sqlWH);
                        DataTable _dtWH = DBhlper.Query(sqlWH, Appconfig.GetU9ConnStr());
                        string WHCode = string.Empty;
                        long WHID = 0;
                        if (_dtWH != null && _dtWH.Rows.Count > 0)
                        {
                            WHCode = _dtWH.Rows[0]["Code"].ToString();
                            WHID = long.Parse(_dtWH.Rows[0]["ID"].ToString());
                        }
                        if (string.IsNullOrWhiteSpace(WHCode))
                        {
                            rtnRcvInfo rtnpo = new rtnRcvInfo();
                            rtnpo.Success = false;
                            rtnpo.Message = "未获取到仓库";
                            rtnpos.Add(rtnpo);
                            return rtnpos;

                        }
                        //仓库
                        rCV.m_whCode = WHCode;
                        rCV.m_wh = WHID;
                        #region 创建批号接口调用
                        string LotID = "";
                        if (line.BatchCode != "")
                        {
                            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 (LotID != "")
                            {
                                rCV.m_lotMaster = long.Parse(LotID);
                                rCV.m_lotNo = line.BatchCode;
                            }
                        }
                        else
                        {
                            rCV.m_lotNo = "";
                        }
                        #endregion

                        rCVList.Add(rCV);
                        strlog.AppendLine("来源委外发料单号:" + line.InvCode);
                        strlog.AppendLine("料品编码:" + line.InvCode);
                        strlog.AppendLine("料品数量:" + line.Quantity);
                        strlog.AppendLine("退料仓库:" + WHCode);
                        strlog.AppendLine("批号ID:" + LotID);

                    }
                }
                pOList = rCVList.ToArray();

                (client.Endpoint.Binding as BasicHttpBinding).MaxReceivedMessageSize = int.MaxValue;
                (client.Endpoint.Binding as BasicHttpBinding).MaxBufferSize = int.MaxValue;
                List<string> shDocList = new List<string>();
                StringBuilder finalstr = new StringBuilder();
                //给上下文信息赋值
                context = CreateContextObj(OrgID);
                returnItems = client.Do(out returnMsg, context, pOList, false, 2);
                if (returnItems != null || returnItems.Count() > 0)
                {
                    List<string> DocNoList = new List<string>();
                    string SqlDocNo = "";
                    for (int i = 0; i < returnItems.Count(); i++)
                    {
                        if (SqlDocNo == "")
                        {
                            SqlDocNo += "'" + returnItems[i].ToString() + "'";
                        }
                        else
                        {
                            SqlDocNo += ",'" + returnItems[i].ToString() + "'";
                        }
                        DocNoList.Add(returnItems[i].ToString());
                    }
                    #region 审核之前先写入确认时间
                    string updatesql = @"update PM_IssueDoc set BusinessCreatedOn=GETDATE()
                                         where DocNo IN ({0}) AND IssueOrg='{1}'";
                    updatesql = string.Format(updatesql, SqlDocNo, OrgID);
                    DBhlper.EXecute(updatesql, Appconfig.GetU9ConnStr());
                    #endregion
                    strlog.AppendLine("开始调用审核委外退料单接口------------");
                    BFPMRecedeApprove.CustApproveBFPMRecede.OperationResult shresult = new BFPMRecedeApprove.CustApproveBFPMRecede.OperationResult();
                    BFPMRecedeApprove.CustApproveBFPMRecede PMRecedeApprove = new BFPMRecedeApprove.CustApproveBFPMRecede();
                    shresult = PMRecedeApprove.CustBFPMRecedeApprove(DocNoList, OrgID, "审核");
                    if (shresult.IsSuccess == true)
                    {
                        rtnRcvInfo rtnpo = new rtnRcvInfo();
                        rtnpo.Success = true;
                        rtnpo.Message = "委外退料单审核成功";
                        rtnpo.DocNo = SqlDocNo;
                        rtnpos.Add(rtnpo);
                    }
                    else
                    {
                        strlog.AppendLine("开始调用删除委外退料单接口------------");
                        BFPMRecedeDelete.CustDeleteBFPMRecede.CustBFPMRecedeDelete(DocNoList, OrgID);
                        rtnRcvInfo rtnpo = new rtnRcvInfo();
                        rtnpo.Success = false;
                        rtnpo.Message = "委外退料单审核失败";
                        rtnpo.DocNo = shresult.MESSAGE;
                        rtnpos.Add(rtnpo);
                        return rtnpos;
                    }
                }
                strlog.AppendLine("返回数据:");
                foreach (var info in rtnpos)
                {
                    strlog.AppendLine("单号:" + info.DocNo);
                    strlog.AppendLine("结果:" + info.Success);
                    strlog.AppendLine("返回消息:" + info.Message);
                    //foreach (var _line in info.rtnLines)
                    //{
                    //    strlog.AppendLine("行号:" + _line.LineNo);
                    //}
                }
                strlog.AppendLine("*****************************************************");
                Appconfig.WriteLogFile(strlog.ToString(), "创建委外退料单");

                return rtnpos;
            }
            catch (Exception ex)
            {
                //异常信息捕获
                List<rtnRcvInfo> rtnpos = new List<rtnRcvInfo>();
                rtnRcvInfo rtnpo = new rtnRcvInfo();
                rtnpo.Success = false;
                rtnpo.Message = GetExceptionMessage(ex);
                rtnpos.Add(rtnpo);

                StringBuilder strlog = new StringBuilder();
                strlog.AppendLine("创建委外退料单");
                strlog.AppendLine("*****************************************************");
                foreach (var item in rCVInfoList)
                {
                    strlog.AppendLine("来源委外采购订单号:" + item.SourceCode);
                    foreach (var line in item.details)
                    {
                        strlog.AppendLine("来源委外采购订单行:" + line.Sequence);
                        strlog.AppendLine("料品编码:" + line.InvCode);
                        strlog.AppendLine("料品数量:" + line.Quantity);
                        strlog.AppendLine("仓库:" + line.WHCode);
                    }
                }
                strlog.AppendLine("返回消息：" + rtnpo.Message);
                strlog.AppendLine("*****************************************************");
                Appconfig.WriteLogFile(strlog.ToString(), "创建委外退料单");

                return rtnpos;
            }
            #endregion
        }

        public rtnRcvInfo CustCreatePMRecede(List<rCVhead> rCVInfoList)
        {
            #region 接口传入参数日志
            StringBuilder firststrlog = new StringBuilder();
            firststrlog.AppendLine("传入数据开始");
            firststrlog.AppendLine("*****************************************************");
            foreach (var item in rCVInfoList)
            {
                firststrlog.AppendLine("来源委外采购订单号:" + item.SourceCode);
                firststrlog.AppendLine("组织编码:" + item.WorkPoint);
                foreach (var line in item.details)
                {
                    firststrlog.AppendLine("来源委外发料单行ID:" + line.SourceDetailID);
                    firststrlog.AppendLine("来源委外发料单行:" + line.Sequence);
                    firststrlog.AppendLine("料品编码:" + line.InvCode);
                    firststrlog.AppendLine("料品数量:" + line.Quantity);
                    firststrlog.AppendLine("批号:" + line.BatchCode);
                    firststrlog.AppendLine("仓库:" + line.WHCode);
                    firststrlog.AppendLine("LogId:" + line.LogId);
                }
            }
            firststrlog.AppendLine("*****************************************************");
            firststrlog.AppendLine("传入数据结束");
            Appconfig.WriteLogFile(firststrlog.ToString(), "创建委外退料单");
            #endregion
            #region 服务调用框架结构
            UFIDAU9ISVPMIssueICreatPMRecedeIssueDocSVClient client = new UFIDAU9ISVPMIssueICreatPMRecedeIssueDocSVClient();
            //服务返回结果
            string[] returnItems;
            //返回异常信息，目前还没有使用此属性
            UFSoft.UBF.Exceptions1.MessageBase[] returnMsg;
            //上下文信息
            object context;
            //传入 参数
            UFIDAU9ISVPMIssuePMRecedeItemAndSnDTOData[] pOList;
            //空
            string[] splitBy = new string[] { };

            try
            {
                string OrgID = "";
                rtnRcvInfo rtnpo = new rtnRcvInfo();
                long PickID = 0;
                long ItemID = 0;
                if (rCVInfoList == null || rCVInfoList.Count == 0)
                {
                    StringBuilder errormsg = new StringBuilder();
                    errormsg.AppendLine("*********************报错记录开始*********************");
                    errormsg.AppendLine("传入参数不能为空！");
                    errormsg.AppendLine("*********************报错记录结束*********************");
                    Appconfig.WriteLogFile(errormsg.ToString(), "创建委外退料单");
                    rtnpo.Success = false;
                    rtnpo.Message = "传入参数不能为空";
                    return rtnpo;
                }

                foreach (var item in rCVInfoList)
                {
                    if (item.details == null || item.details.Count() == 0)
                    {
                        StringBuilder errormsg = new StringBuilder();
                        errormsg.AppendLine("*********************报错记录开始*********************");
                        errormsg.AppendLine("传入行信息不能为空！");
                        errormsg.AppendLine("*********************报错记录结束*********************");
                        Appconfig.WriteLogFile(errormsg.ToString(), "创建委外退料单");
                        rtnpo.Success = false;
                        rtnpo.Message = "传入行信息不能为空";
                        return rtnpo;
                    }
                    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
                    {
                        StringBuilder errormsg = new StringBuilder();
                        errormsg.AppendLine("*********************报错记录开始*********************");
                        errormsg.AppendLine("传入组织编码:" + item.WorkPoint + "不存在！");
                        errormsg.AppendLine("*********************报错记录结束*********************");
                        Appconfig.WriteLogFile(errormsg.ToString(), "创建委外退料单");
                        rtnpo.Success = false;
                        rtnpo.Message = "传入组织编码:" + item.WorkPoint + "不存在！";
                        return rtnpo;
                    }
                    foreach (var _item in item.details)
                    {
                        if (_item.Sequence == 0)
                        {
                            StringBuilder errormsg = new StringBuilder();
                            errormsg.AppendLine("*********************报错记录开始*********************");
                            errormsg.AppendLine("请传入来源单据行号！");
                            errormsg.AppendLine("*********************报错记录结束*********************");
                            Appconfig.WriteLogFile(errormsg.ToString(), "创建委外退料单");
                            rtnpo.Success = false;
                            rtnpo.Message = "请传入来源单据行号";
                            return rtnpo;
                        }
                        if (_item.Quantity == 0)
                        {
                            StringBuilder errormsg = new StringBuilder();
                            errormsg.AppendLine("*********************报错记录开始*********************");
                            errormsg.AppendLine("传入数量不能为空！");
                            errormsg.AppendLine("*********************报错记录结束*********************");
                            Appconfig.WriteLogFile(errormsg.ToString(), "创建委外退料单");
                            rtnpo.Success = false;
                            rtnpo.Message = "传入数量不能为空";
                            return rtnpo;
                        }
                    }
                }
                //给传入参数赋值

                //pOList = SetrCVDtos(rCVInfoList);
                StringBuilder strlog = new StringBuilder();
                strlog.AppendLine("创建委外退料单");
                strlog.AppendLine("*****************************************************");

                List<UFIDAU9ISVPMIssuePMRecedeItemAndSnDTOData> rCVList = new List<UFIDAU9ISVPMIssuePMRecedeItemAndSnDTOData>();
                foreach (var rCVhead in rCVInfoList)
                {
                    strlog.AppendLine("来源委外发料单号:" + rCVhead.SourceCode);
                    foreach (rCVLine line in rCVhead.details)
                    {
                        UFIDAU9ISVPMIssuePMRecedeItemAndSnDTOData rCV = new UFIDAU9ISVPMIssuePMRecedeItemAndSnDTOData();

                        #region 获取委外发料单ID
                        string sqlPick = @"select B.ID,B.POPick,B.IsIssued from PM_IssueDoc A
                                           LEFT JOIN PM_IssueDocLine B
                                           ON B.PMIssueDoc=A.ID
                                           where B.POPick='" + line.SourceDetailID + "'";
                        sqlPick = string.Format(sqlPick);
                        DataTable dtPick = DBhlper.Query(sqlPick, Appconfig.GetU9ConnStr());
                        if (dtPick.Rows.Count > 0)
                        {
                            rCV.m_pickID = long.Parse(dtPick.Rows[0]["POPick"].ToString());
                        }
                        else
                        {
                            rtnpo.Success = false;
                            rtnpo.Message = "传入备料ID：" + line.SourceDetailID + "尚未发料!";
                            return rtnpo;
                        }
                        #endregion
                        #region 获取退料料品ID
                        string sqlitem = @"select ID from CBO_ItemMaster 
                                           where Code='" + line.InvCode + "' AND Org='" + OrgID + "'";
                        sqlitem = string.Format(sqlitem);
                        DataTable dtitem = DBhlper.Query(sqlitem, Appconfig.GetU9ConnStr());
                        if (dtitem.Rows.Count > 0)
                        {
                            ItemID = long.Parse(dtitem.Rows[0]["ID"].ToString());
                        }
                        else
                        {
                            rtnpo.Success = false;
                            rtnpo.Message = "料品不存在!";
                            return rtnpo;
                        }
                        #endregion
                        rCV.m_itemCode = line.InvCode;
                        rCV.m_recedeQty = line.Quantity;
                        rCV.m_recedeReason = 1;
                        string sqlWH = @"select ID,Code,IsLot from CBO_Wh
                                         WHERE Code='" + line.WHCode + "' AND Org='" + OrgID + "' ";
                        sqlWH = string.Format(sqlWH);
                        DataTable _dtWH = DBhlper.Query(sqlWH, Appconfig.GetU9ConnStr());
                        string WHCode = string.Empty;
                        long WHID = 0;
                        bool IsLot = false;
                        if (_dtWH != null && _dtWH.Rows.Count > 0)
                        {
                            WHCode = _dtWH.Rows[0]["Code"].ToString();
                            WHID = long.Parse(_dtWH.Rows[0]["ID"].ToString());
                            IsLot = Convert.ToBoolean(_dtWH.Rows[0]["IsLot"].ToString());
                        }
                        if (string.IsNullOrWhiteSpace(WHCode))
                        {
                            rtnpo.Success = false;
                            rtnpo.Message = "未获取到仓库";
                            return rtnpo;

                        }
                        //仓库
                        rCV.m_whCode = WHCode;
                        rCV.m_wh = WHID;
                        #region 创建批号接口调用
                        string LotID = "";
                        if (line.BatchCode != "" && IsLot == true)
                        {
                            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 (LotID != "")
                            {
                                rCV.m_lotMaster = long.Parse(LotID);
                                rCV.m_lotNo = line.BatchCode;
                            }
                        }
                        else
                        {
                            rCV.m_lotNo = "";
                        }
                        #endregion

                        rCVList.Add(rCV);
                        strlog.AppendLine("来源委外发料单号:" + line.InvCode);
                        strlog.AppendLine("料品编码:" + line.InvCode);
                        strlog.AppendLine("料品数量:" + line.Quantity);
                        strlog.AppendLine("退料仓库:" + WHCode);
                        strlog.AppendLine("批号ID:" + LotID);

                    }
                }
                pOList = rCVList.ToArray();

                (client.Endpoint.Binding as BasicHttpBinding).MaxReceivedMessageSize = int.MaxValue;
                (client.Endpoint.Binding as BasicHttpBinding).MaxBufferSize = int.MaxValue;
                List<string> shDocList = new List<string>();
                StringBuilder finalstr = new StringBuilder();
                //给上下文信息赋值
                context = CreateContextObj(OrgID);
                returnItems = client.Do(out returnMsg, context, pOList, false, 2);
                if (returnItems != null || returnItems.Count() > 0)
                {
                    List<string> DocNoList = new List<string>();
                    string SqlDocNo = "";
                    for (int i = 0; i < returnItems.Count(); i++)
                    {
                        if (SqlDocNo == "")
                        {
                            SqlDocNo += "'" + returnItems[i].ToString() + "'";
                        }
                        else
                        {
                            SqlDocNo += ",'" + returnItems[i].ToString() + "'";
                        }
                        DocNoList.Add(returnItems[i].ToString());
                    }
                    #region 审核之前先写入确认时间
                    string updatesql = @"update PM_IssueDoc set BusinessCreatedOn=GETDATE()
                                         where DocNo IN ({0}) AND IssueOrg='{1}'";
                    updatesql = string.Format(updatesql, SqlDocNo, OrgID);
                    DBhlper.EXecute(updatesql, Appconfig.GetU9ConnStr());
                    #endregion
                    strlog.AppendLine("开始调用审核委外退料单接口------------");
                    BFPMRecedeApprove.CustApproveBFPMRecede.OperationResult shresult = new BFPMRecedeApprove.CustApproveBFPMRecede.OperationResult();
                    BFPMRecedeApprove.CustApproveBFPMRecede PMRecedeApprove = new BFPMRecedeApprove.CustApproveBFPMRecede();
                    shresult = PMRecedeApprove.CustBFPMRecedeApprove(DocNoList, OrgID, "审核");
                    if (shresult.IsSuccess == true)
                    {
                        rtnpo.Success = true;
                        rtnpo.Message = "委外退料单审核成功";
                        rtnpo.DocNo = SqlDocNo;
                        #region 回写查询
                        List<Data> _datalist = new List<Data>();
                        foreach (string DocNO in DocNoList)
                        {
                            string DocTypeName = string.Empty;
                            Data _data = new Data();
                            if (returnItems != null)
                            {
                                List<DataLine> list = new List<DataLine>();
                                string Selsql = @" SELECT a.ID,a.DocNo as IssueNEGCode,a.CreatedBy as cMaker,a.CreatedOn as dnmaketime,a.ModifiedBy as cHandler
		                                            ,a.ModifiedOn as dnverifytime,b.ID as DetailID,b.LineNum as Sequence,c.Code as InvCode,b.IssuedQty as Quantity
		                                            ,D.Code AS cDepCode,DD.Name AS cDepName,E.Code AS WHCode,EE.Name AS WHName,B.RecedeIssueSourceLine AS SourceDetailID
		                                            ,F.Code AS ProjectCode,0 AS Amount,G.LotCode AS cBatch,'' AS brand,
                                                    '' cFree1,'' cFree2,'' cFree3,
                                                    '' cFree4,'' cFree5,'' cFree6,
                                                    '' cFree7,'' cFree8,'' cFree9,
                                                    '' cFree10,'' LogId
                                                    FROM PM_IssueDoc a
                                                    LEFT JOIN PM_IssueDocLine b ON b.PMIssueDoc=a.ID
                                                    LEFT JOIN CBO_ItemMaster c ON c.ID=b.Item
                                                    LEFT JOIN CBO_Department d ON D.ID=B.IssueDept
		                                            LEFT JOIN CBO_Degree_Trl DD ON DD.ID=D.ID
		                                            LEFT JOIN CBO_Wh E ON E.ID=B.Wh
		                                            LEFT JOIN CBO_Wh_Trl EE ON EE.ID=E.ID
		                                            LEFT JOIN CBO_Project F ON F.ID=B.Project
		                                            LEFT JOIN Lot_LotMaster G ON G.ID=B.LotMaster
		                                            WHERE A.DocNo='" + DocNO + "' AND A.Org='" + OrgID + "'";
                                DataTable Seldt = DBhlper.Query(Selsql, Appconfig.GetU9ConnStr());
                                if (Seldt != null && Seldt.Rows.Count > 0)
                                {
                                    foreach (DataRow item in Seldt.Rows)
                                    {
                                        DataLine _DataLine = new DataLine();
                                        _data.ID = item["ID"].ToString();
                                        _data.IssueNEGCode = item["IssueNEGCode"].ToString();
                                        _data.cMaker = item["cMaker"].ToString();
                                        _data.dnmaketime = Convert.ToDateTime(item["dnmaketime"].ToString());
                                        _data.cHandler = item["cHandler"].ToString();
                                        _data.dnverifytime = Convert.ToDateTime(item["dnverifytime"].ToString());

                                        _DataLine.DetailID = item["DetailID"].ToString();
                                        _DataLine.Sequence = Int32.Parse(item["Sequence"].ToString());
                                        _DataLine.InvCode = item["InvCode"].ToString();
                                        _DataLine.Quantity = Decimal.Parse(item["Quantity"].ToString());
                                        _DataLine.cDepCode = item["cDepCode"].ToString();
                                        _DataLine.cDepName = item["cDepName"].ToString();
                                        _DataLine.WHCode = item["WHCode"].ToString();
                                        _DataLine.WHName = item["WHName"].ToString();
                                        _DataLine.SourceDetailID = item["SourceDetailID"].ToString();
                                        _DataLine.Amount = Convert.ToDecimal(item["Amount"].ToString());
                                        _DataLine.ProjectCode = item["ProjectCode"].ToString();
                                        _DataLine.cBatch = item["cBatch"].ToString();
                                        _DataLine.brand = item["brand"].ToString();
                                        _DataLine.cFree1 = item["cFree1"].ToString();
                                        _DataLine.cFree2 = item["cFree2"].ToString();
                                        _DataLine.cFree3 = item["cFree3"].ToString();
                                        _DataLine.cFree4 = item["cFree4"].ToString();
                                        _DataLine.cFree5 = item["cFree5"].ToString();
                                        _DataLine.cFree6 = item["cFree6"].ToString();
                                        _DataLine.cFree7 = item["cFree7"].ToString();
                                        _DataLine.cFree8 = item["cFree8"].ToString();
                                        _DataLine.cFree9 = item["cFree9"].ToString();
                                        _DataLine.cFree10 = item["cFree10"].ToString();
                                        _DataLine.LogId = item["LogId"].ToString();

                                        list.Add(_DataLine);
                                    }
                                    _data.details = list;
                                    _datalist.Add(_data);
                                }
                            }
                        }
                        #endregion
                        rtnpo.Data = _datalist;
                    }
                    else
                    {
                        strlog.AppendLine("开始调用删除委外退料单接口------------");
                        BFPMRecedeDelete.CustDeleteBFPMRecede.CustBFPMRecedeDelete(DocNoList, OrgID);
                        rtnpo.Success = false;
                        rtnpo.Message = "委外退料单审核失败";
                        rtnpo.DocNo = shresult.MESSAGE;
                        return rtnpo;
                    }
                }
                strlog.AppendLine("返回数据:");
                strlog.AppendLine("单号:" + rtnpo.DocNo);
                strlog.AppendLine("结果:" + rtnpo.Success);
                strlog.AppendLine("返回消息:" + rtnpo.Message);
                strlog.AppendLine("*****************************************************");
                Appconfig.WriteLogFile(strlog.ToString(), "创建委外退料单");

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

                StringBuilder strlog = new StringBuilder();
                strlog.AppendLine("创建委外退料单");
                strlog.AppendLine("*****************************************************");
                foreach (var item in rCVInfoList)
                {
                    strlog.AppendLine("来源委外采购订单号:" + item.SourceCode);
                    foreach (var line in item.details)
                    {
                        strlog.AppendLine("来源委外采购订单行:" + line.Sequence);
                        strlog.AppendLine("料品编码:" + line.InvCode);
                        strlog.AppendLine("料品数量:" + line.Quantity);
                        strlog.AppendLine("仓库:" + line.WHCode);
                    }
                }
                strlog.AppendLine("返回消息：" + ex.Message);
                strlog.AppendLine("*****************************************************");
                Appconfig.WriteLogFile(strlog.ToString(), "创建委外退料单");

                return rtnpo;
            }
            #endregion
        }

        #region 给传入参数赋值
        private UFIDAU9ISVPMIssuePMRecedeItemAndSnDTOData[] SetrCVDtos(List<rCVhead> headList)
        {

            List<UFIDAU9ISVPMIssuePMRecedeItemAndSnDTOData> rCVList = new List<UFIDAU9ISVPMIssuePMRecedeItemAndSnDTOData>();
            foreach (var rCVhead in headList)
            {
                foreach (rCVLine line in rCVhead.details)
                {
                    UFIDAU9ISVPMIssuePMRecedeItemAndSnDTOData rCV = new UFIDAU9ISVPMIssuePMRecedeItemAndSnDTOData();
                    rCV.m_snCode = rCVhead.SourceCode;

                    rCV.m_itemCode = line.InvCode;


                    rCV.m_recedeQty = line.Quantity;

                    rCV.m_whCode = line.WHCode;

                    rCVList.Add(rCV);
                }
            }

            return rCVList.ToArray();
        }
        #endregion

        #region 表头类
        public class rCVhead
        {
            private rCVLine[] _lines;
            private string _srcDocPONo;
            private string _OrgCode;

            //private string _DocType;


            public rCVLine[] details
            {
                get { return _lines; }
                set { _lines = value; }
            }

            /// <summary>
            /// 来源委外采购订单
            /// </summary>
            public string SourceCode
            {
                get { return _srcDocPONo; }
                set { _srcDocPONo = value; }
            }

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

            //public string DocType
            //{
            //    get { return _DocType; }
            //    set { _DocType = value; }
            // }
        }
        #endregion

        #region 表体类
        public class rCVLine
        {
            /// <summary>
            /// 数量
            /// </summary>
            public string SourceDetailID { get; set; }
            public decimal Quantity { get; set; }

            public string WHCode { get; set; }


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


            /// <summary>
            /// 来源委外采购订单料号
            /// </summary>
            public string InvCode { get; set; }


            /// <summary>
            /// 来源委外采购订单行
            /// </summary>
            public int Sequence { get; set; }


            /// <summary>
            /// 库存批号
            /// </summary>
            public string BatchCode { get; set; }


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

            System.Collections.Generic.Dictionary<object, object> ns = new Dictionary<object, object>();
            ns.Add("OrgID", OrgID);
            ns.Add("UserID", ConfigurationManager.AppSettings["userID"].ToString());
            ns.Add("User", ConfigurationManager.AppSettings["userCode"].ToString());
            ns.Add("MTime", 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 User
        {
            get { return _UserCode; }
            set { _UserCode = value; }
        }

        /// <summary>
        /// 时间
        /// </summary>
        public DateTime MTime
        {
            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";
            MTime = DateTime.Now;
        }
    }
    #endregion



    #region 返回信息类
    public class rtnRcvInfo
    {
        public string DocNo { get; set; }
        public bool Success { get; set; }
        public string Message { get; set; }
        public List<Data> Data { get; set; }
    }

    public class Data
    {
        public string ID { get; set; }
        public string IssueNEGCode { get; set; }
        public string cDepCode { get; set; }
        public string cDepName { get; set; }
        public string WHCode { get; set; }
        public string WHName { get; set; }
        public string cMaker { get; set; }
        public DateTime dnmaketime { get; set; }
        public string cHandler { get; set; }
        public DateTime dnverifytime { get; set; }
        public List<DataLine> details { get; set; }
    }

    public class DataLine
    {
        public string DetailID { get; set; }
        public int Sequence { get; set; }
        public string InvCode { get; set; }
        public Decimal Quantity { get; set; }
        public string cDepCode { get; set; }
        public string cDepName { get; set; }
        public string WHCode { get; set; }
        public string WHName { get; set; }
        public string SourceDetailID { get; set; }
        public string ProjectCode { get; set; }
        public Decimal Amount { get; set; }
        public string cBatch { get; set; }
        public string brand { get; set; }
        public string cFree1 { get; set; }
        public string cFree2 { get; set; }
        public string cFree3 { get; set; }
        public string cFree4 { get; set; }
        public string cFree5 { get; set; }
        public string cFree6 { get; set; }
        public string cFree7 { get; set; }
        public string cFree8 { get; set; }
        public string cFree9 { get; set; }
        public string cFree10 { get; set; }

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


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

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

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

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

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


}
