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.ApproveMiscShip;
using UFIDA.ISV.CommitMiscShip;
//using UFIDA.ISV.ApproveMiscShip;
//using UFIDA.ISV.CommitMiscShip;
//using UFIDA.ISV.CreateLotMaster;
using UFSoft.UBF.Service;
using UFSoft.UBF.Util.Context;
using www.ufida.org.EntityData;

namespace UFIDA.ISV.CreateBFMisShip
{

    public class CustCreateBFMisShipSrvSub
    {
        //public List<rtnRcvInfo> CustCreateBFMisShip(List<rCVhead> rCVInfoList)
        public rtnRcvInfo CustCreateBFMisShip(List<rCVhead> rCVInfoList)
        {
            #region 接口传入参数日志
            StringBuilder firststrlog = new StringBuilder();
            firststrlog.AppendLine("传入数据开始");
            firststrlog.AppendLine("*****************************************************");
            foreach (var item in rCVInfoList)
            {
                firststrlog.AppendLine("表头信息 ：");
                firststrlog.AppendLine("单据编号:" + item.DocNO);
                firststrlog.AppendLine("单据类型:" + item.DocType);
                firststrlog.AppendLine("组织编码:" + item.WorkPoint);
                firststrlog.AppendLine("客户编码:" + item.ClientCode);
                int i = 0;
                foreach (var line in item.details)
                {
                    i++;
                    firststrlog.AppendLine("表体信息" + i + " ：");
                    firststrlog.AppendLine("料品编码:" + line.InvCode);
                    firststrlog.AppendLine("料品数量:" + line.Quantity);
                    firststrlog.AppendLine("批号:" + line.BatchCode);
                    firststrlog.AppendLine("仓库:" + line.WHCode);
                    firststrlog.AppendLine("受益项目:" + line.Project);
                    firststrlog.AppendLine("受益部门:" + line.Dep);

                    firststrlog.AppendLine("cFree1:" + line.cFree1);
                    firststrlog.AppendLine("cFree2:" + line.cFree2);
                    firststrlog.AppendLine("cFree3:" + line.cFree3);
                    firststrlog.AppendLine("cFree4:" + line.cFree4);
                    firststrlog.AppendLine("cFree5:" + line.cFree5);
                    firststrlog.AppendLine("cFree6:" + line.cFree6);
                    firststrlog.AppendLine("cFree7:" + line.cFree7);
                    firststrlog.AppendLine("cFree8:" + line.cFree8);
                    firststrlog.AppendLine("cFree9:" + line.cFree9);
                    firststrlog.AppendLine("cFree10:" + line.cFree10);
                    firststrlog.AppendLine("LogId:" + line.LogId);
                }
            }
            firststrlog.AppendLine("*****************************************************");
            firststrlog.AppendLine("传入数据结束");
            Appconfig.WriteLogFile(firststrlog.ToString(), "创建杂发单");
            #endregion
            #region 服务调用框架结构
            UFIDAU9ISVMiscShipISVICommonCreateMiscShipClient client = new UFIDAU9ISVMiscShipISVICommonCreateMiscShipClient();
            //服务返回结果
            UFIDAU9CBOPubControllerCommonArchiveDataDTOData[] returnItems;
            //返回异常信息，目前还没有使用此属性
            UFSoft.UBF.Exceptions1.MessageBase[] returnMsg;
            //上下文信息
            object context;
            //传入 参数
            UFIDAU9ISVMiscShipISVIC_MiscShipmentDTOData[] pOList;
            //空
            string[] splitBy = new string[] { };
            rtnRcvInfo rtnpos = new rtnRcvInfo();
            List<string> StrList = new List<string>();
            string orgID = "";

            string updatesql = "";
            try
            {
                //List<rtnRcvInfo> rtnpos = new List<rtnRcvInfo>();

                long PickID = 0;
                long ItemID = 0;
                if (rCVInfoList == null || rCVInfoList.Count == 0)
                {
                    rtnRcvInfo rtnpo = new rtnRcvInfo();
                    rtnpo.Success = false;
                    rtnpo.Message = "传入参数不能为空";
                    rtnpo.Data = null;
                    //rtnpos.Add(rtnpo);
                    return rtnpo;
                }

                foreach (var item in rCVInfoList)
                {
                    if (item.DocType == null || item.DocType == "")
                    {
                        rtnRcvInfo rtnpo = new rtnRcvInfo();
                        rtnpo.Success = false;
                        rtnpo.Message = "传入单据类型不能为空";
                        //rtnpos.Add(rtnpo);
                        rtnpo.Data = null;
                        return rtnpo;
                    }
                    //if (item.ClientCode == null || item.ClientCode == "")
                    //{
                    //    rtnRcvInfo rtnpo = new rtnRcvInfo();
                    //    rtnpo.Success = false;
                    //    rtnpo.Message = "传入客户信息不能为空";
                    //    rtnpos.Add(rtnpo);
                    //    return rtnpos;
                    //}
                    if (item.details == null || item.details.Count() == 0)
                    {
                        rtnRcvInfo rtnpo = new rtnRcvInfo();
                        rtnpo.Success = false;
                        rtnpo.Message = "传入行信息不能为空";
                        //rtnpos.Add(rtnpo);
                        rtnpo.Data = null;
                        return rtnpo;
                    }
                    foreach (var _item in item.details)
                    {
                        if (_item.InvCode == null || _item.InvCode == "")
                        {
                            rtnRcvInfo rtnpo = new rtnRcvInfo();
                            rtnpo.Success = false;
                            rtnpo.Message = "传入行信息中料号不能为空!";
                            //rtnpos.Add(rtnpo);
                            rtnpo.Data = null;
                            return rtnpo;
                        }
                        if (_item.Quantity == 0)
                        {
                            rtnRcvInfo rtnpo = new rtnRcvInfo();
                            rtnpo.Success = false;
                            rtnpo.Message = "传入行信息中数量不能为空";
                            //rtnpos.Add(rtnpo);
                            rtnpo.Data = null;
                            return rtnpo;
                        }
                        if (_item.WHCode == null || _item.WHCode == "")
                        {
                            rtnRcvInfo rtnpo = new rtnRcvInfo();
                            rtnpo.Success = false;
                            rtnpo.Message = "传入行信息中仓库不能为空";
                            //rtnpos.Add(rtnpo);
                            rtnpo.Data = null;
                            return rtnpo;
                        }

                        if (string.IsNullOrEmpty(_item.Dep))
                        {
                            rtnRcvInfo rtnpo = new rtnRcvInfo();
                            rtnpo.Success = false;
                            rtnpo.Message = "传入行信息中部门不能为空";
                            //rtnpos.Add(rtnpo);
                            rtnpo.Data = null;
                            return rtnpo;
                        }
                        //if (string.IsNullOrEmpty(_item.Project))
                        //{
                        //    rtnRcvInfo rtnpo = new rtnRcvInfo();
                        //    rtnpo.Success = false;
                        //    rtnpo.Message = "传入行信息中项目不能为空";
                        //    rtnpos.Add(rtnpo);
                        //    return rtnpos;
                        //}

                    }
                }


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

                //pOList = SetrCVDtos(rCVInfoList);
                StringBuilder strlog = new StringBuilder();
                strlog.AppendLine("创建杂发单");
                strlog.AppendLine("*****************************************************");
                List<UFIDAU9ISVMiscShipISVIC_MiscShipmentDTOData> shipList = new List<UFIDAU9ISVMiscShipISVIC_MiscShipmentDTOData>();
                foreach (var rCVhead in rCVInfoList)
                {
                    strlog.AppendLine("组织编码:" + rCVhead.WorkPoint);
                    //获取组织ID
                    string orgsql = @"select ID from Base_Organization
                                      where Code='{0}' ";
                    orgsql = string.Format(orgsql, rCVhead.WorkPoint);
                    DataTable orgdt = DBhlper.Query(orgsql, Appconfig.GetU9ConnStr());
                    if (orgdt.Rows.Count == 0)
                    {
                        rtnRcvInfo rtnpo = new rtnRcvInfo();
                        rtnpo.Success = false;
                        rtnpo.Message = "组织编码不存在";
                        //rtnpos.Add(rtnpo);
                        strlog.AppendLine("返回数据:");
                        strlog.AppendLine("组织编码不存在!");
                        Appconfig.WriteLogFile(strlog.ToString(), "创建杂发单");
                        return rtnpo;
                    }
                    else
                    {
                        orgID = orgdt.Rows[0]["ID"].ToString();
                    }
                    //获取单据类型ID
                    string docsql = @"select ID from InvDoc_MiscShipDocType
                                          where Code='{0}' AND Org='{1}'";
                    docsql = string.Format(docsql, rCVhead.DocType, orgID);
                    DataTable docdt = DBhlper.Query(docsql, Appconfig.GetU9ConnStr());
                    long docTypeID = 0;
                    if (docdt != null && docdt.Rows.Count > 0)
                    {
                        docTypeID = long.Parse(docdt.Rows[0]["ID"].ToString());
                    }
                    if (docTypeID == 0)
                    {
                        rtnRcvInfo rtnpo = new rtnRcvInfo();
                        rtnpo.Success = false;
                        rtnpo.Message = "未获取到单据类型ID";
                        //rtnpos.Add(rtnpo);
                        strlog.AppendLine("返回数据:");
                        strlog.AppendLine("未获取到单据类型ID!");
                        Appconfig.WriteLogFile(strlog.ToString(), "创建杂发单");
                        return rtnpo;
                    }
                    UFIDAU9ISVMiscShipISVIC_MiscShipmentDTOData ship = new UFIDAU9ISVMiscShipISVIC_MiscShipmentDTOData();
                    ship.m_docNo = rCVhead.DocNO;
                    ship.m_miscShipDocType = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                    ship.m_miscShipDocType.m_code = rCVhead.DocType;
                    ship.m_miscShipDocType.m_iD = docTypeID;
                   

                    ship.m_businessDate = Convert.ToDateTime(rCVhead.DocDate);

                    ship.m_benefitOrg = long.Parse(orgID);
                    ship.m_descFlexField = new UFIDAU9BaseFlexFieldDescFlexFieldDescFlexSegmentsData();
                    ship.m_descFlexField.m_privateDescSeg3 = rCVhead.HcFree1;
                    ship.m_descFlexField.m_privateDescSeg5 = rCVhead.HcFree2;
                    ship.m_descFlexField.m_privateDescSeg4 = rCVhead.HcFree4;

                    ship.m_descFlexField.m_privateDescSeg6 = rCVhead.HcFree3;


                    List<UFIDAU9ISVMiscShipISVIC_MiscShipmentLDTOData> shipLineList = new List<UFIDAU9ISVMiscShipISVIC_MiscShipmentLDTOData>();
                    foreach (rCVLine line in rCVhead.details)
                    {
                        //获取料品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);
                            strlog.AppendLine("返回数据:");
                            strlog.AppendLine("料品不存在!");
                            Appconfig.WriteLogFile(strlog.ToString(), "创建杂发单");
                            return rtnpo;
                        }
                        //获取仓库ID
                        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);
                            strlog.AppendLine("返回数据:");
                            strlog.AppendLine("未获取到仓库!");
                            Appconfig.WriteLogFile(strlog.ToString(), "创建杂发单");
                            return rtnpo;
                        }
                        //获取部门ID
                        string deptsql = @"select ID,Case When IsMFG=1 then 'True' Else 'False' End AS IsMFG from CBO_Department
                                           where Code='{0}' AND Org='{1}'";
                        deptsql = string.Format(deptsql, line.Dep, orgID);
                        DataTable deptdt = DBhlper.Query(deptsql, Appconfig.GetU9ConnStr());
                        long DeptID = 0;
                        string IsMFG = "";
                        if (deptdt != null && deptdt.Rows.Count > 0)
                        {
                            DeptID = long.Parse(deptdt.Rows[0]["ID"].ToString());
                            IsMFG = deptdt.Rows[0]["IsMFG"].ToString();
                        }

                        if (DeptID == 0)
                        {
                            rtnRcvInfo rtnpo = new rtnRcvInfo();
                            rtnpo.Success = false;
                            rtnpo.Message = "未获取到部门";
                            //rtnpos.Add(rtnpo);
                            strlog.AppendLine("返回数据:");
                            strlog.AppendLine("未获取到部门!");
                            Appconfig.WriteLogFile(strlog.ToString(), "创建杂发单");
                            return rtnpo;
                        }
                        UFIDAU9ISVMiscShipISVIC_MiscShipmentLDTOData shipLine = new UFIDAU9ISVMiscShipISVIC_MiscShipmentLDTOData();
                        shipLine.m_docLineNo = line.Sequence;

                        shipLine.m_benefitDept = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                        shipLine.m_benefitDept.m_code = line.Dep;
                        shipLine.m_benefitDept.m_iD = DeptID;
                        if (IsMFG == "True")
                        {
                            shipLine.m_isMFG = true;
                        }
                        else
                        {
                            shipLine.m_isMFG = false;
                        }
                        shipLine.m_itemInfo = new UFIDAU9CBOSCMItemItemInfoData();
                        shipLine.m_itemInfo.m_itemCode = line.InvCode;
                        shipLine.m_itemInfo.ItemID = ItemID;
                        shipLine.m_itemInfo.ItemID_SKey = new UFSoft.UBF.Business.BusinessEntity.EntityKey();
                        shipLine.m_itemInfo.ItemID_SKey.ID = ItemID;
                        shipLine.m_storeType = 4;
                        shipLine.m_costUOMQty = line.Quantity;
                        shipLine.m_wh = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                        shipLine.m_wh.m_iD = WHID;
                        shipLine.m_benefitOrg = long.Parse(orgID);
                        shipLine.m_customerInfo = new UFIDAU9CBOSCMCustomerCustomerMISCInfoData();
                        shipLine.m_customerInfo.m_code = rCVhead.ClientCode;
                        shipLine.m_memo = line.Memo;


                        if (!string.IsNullOrEmpty(line.Project))
                        {
                            string projectsql = @"select ID from CBO_Project
                                           where Code='{0}' AND Org='{1}'";
                            projectsql = string.Format(projectsql, line.Project, orgID);
                            DataTable projectdt = DBhlper.Query(projectsql, Appconfig.GetU9ConnStr());
                            long projectID = 0;
                            if (projectdt != null && projectdt.Rows.Count > 0)
                            {
                                projectID = long.Parse(projectdt.Rows[0]["ID"].ToString());
                                //shipLine.m_project = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                                //shipLine.m_project.m_code = line.Project;
                                //shipLine.m_project.m_iD = projectID;

                                shipLine.m_benefitProject = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                                shipLine.m_benefitProject.m_code = line.Project;
                                shipLine.m_benefitProject.m_iD = projectID;
                            }
                            if (projectID == 0)
                            {
                                rtnRcvInfo rtnpo = new rtnRcvInfo();
                                rtnpo.Success = false;
                                rtnpo.Message = "项目有误，请核对！";
                                //rtnpos.Add(rtnpo);
                                return rtnpo;
                            }
                        }
                        //else
                        //{
                        //    rtnRcvInfo rtnpo = new rtnRcvInfo();
                        //    rtnpo.Success = false;
                        //    rtnpo.Message = "受益项目为空，请核对！";
                        //    rtnpos.Add(rtnpo);
                        //    return rtnpos;
                        //}


                        shipLine.m_descFlexSegments = new UFIDAU9BaseFlexFieldDescFlexFieldDescFlexSegmentsData();
                        shipLine.m_descFlexSegments.m_privateDescSeg1 = line.cFree1;
                        shipLine.m_descFlexSegments.m_privateDescSeg2 = line.cFree2;
                        shipLine.m_descFlexSegments.m_privateDescSeg3 = line.cFree3;
                        shipLine.m_descFlexSegments.m_privateDescSeg4 = line.cFree4;
                        shipLine.m_descFlexSegments.m_privateDescSeg5 = line.cFree5;
                        shipLine.m_descFlexSegments.m_privateDescSeg6 = line.cFree6;
                        shipLine.m_descFlexSegments.m_privateDescSeg7 = line.cFree7;
                        shipLine.m_descFlexSegments.m_privateDescSeg8 = line.cFree8;
                        shipLine.m_descFlexSegments.m_privateDescSeg9 = line.cFree9;
                        shipLine.m_descFlexSegments.m_privateDescSeg10 = line.cFree10;

                        #region 批号处理(根据料品，仓库，数量查询符合条件的批号)
                        string lotsql = @"select StoreQty from InvTrans_WhQoh 
                                           where ItemInfo_ItemID='{0}' AND Wh='{1}'  AND LotInfo_LotCode='{3}'
                                           --AND StoreQty>={2} 
                                           AND LotInfo_LotCode!='' AND LotInfo_LotCode IS NOT NULL";
                        lotsql = string.Format(lotsql, ItemID, WHID, line.Quantity, line.BatchCode);
                        DataTable lotdt = DBhlper.Query(lotsql, Appconfig.GetU9ConnStr());
                        if (lotdt == null || lotdt.Rows.Count == 0)
                        {
                            rtnRcvInfo rtnpo = new rtnRcvInfo();
                            rtnpo.Success = false;
                            rtnpo.Message = "出库物料对应批号没有足够的库存，库存杂发单生成失败!";
                            strlog.AppendLine("返回数据:");
                            strlog.AppendLine("出库物料对应批号没有足够的库存，库存杂发单生成失败!");
                            Appconfig.WriteLogFile(strlog.ToString(), "创建杂发单");
                            return rtnpo;
                        }
                        else
                        {
                            //if (line.Quantity > Decimal.Parse(lotdt.Rows[0]["StoreQty"].ToString()))
                            //{
                            //    rtnRcvInfo rtnpo = new rtnRcvInfo();
                            //    rtnpo.Success = false;
                            //    rtnpo.Message = "出库物料对应批号没有足够的库存，库存杂发单生成失败!";
                            //    strlog.AppendLine("返回数据:");
                            //    strlog.AppendLine("出库物料对应批号没有足够的库存，库存杂发单生成失败!");
                            //    Appconfig.WriteLogFile(strlog.ToString(), "创建杂发单");
                            //    return rtnpo;
                            //}
                        }
                        shipLine.m_lotInfo = new UFIDAU9CBOSCMPropertyTypesLotInfoData();
                        shipLine.m_lotInfo.m_lotCode = line.BatchCode;
                        shipLine.m_lotInfo.m_lotMaster = new UFIDAU9BasePropertyTypesBizEntityKeyData();

                        #endregion

                        shipLineList.Add(shipLine);
                        strlog.AppendLine("料品编码:" + line.InvCode);
                        strlog.AppendLine("料品数量:" + line.Quantity);
                        strlog.AppendLine("仓库:" + WHCode);

                    }
                    ship.m_miscShipLs = shipLineList.ToArray();
                    shipList.Add(ship);
                }
                pOList = shipList.ToArray();

                (client.Endpoint.Binding as BasicHttpBinding).MaxReceivedMessageSize = int.MaxValue;
                (client.Endpoint.Binding as BasicHttpBinding).MaxBufferSize = int.MaxValue;
                List<string> shDocList = new List<string>();
                UFIDAU9CBOPubControllerContextDTOData info = new UFIDAU9CBOPubControllerContextDTOData();
                info.m_orgID = long.Parse(orgID);
                info.m_orgCode = rCVInfoList[0].WorkPoint;
                info.m_userID = long.Parse(ConfigurationManager.AppSettings["userID"].ToString());
                info.m_userCode = ConfigurationManager.AppSettings["userCode"].ToString();
                info.m_cultureName = ConfigurationManager.AppSettings["cultureName"].ToString();
                info.m_entCode = ConfigurationManager.AppSettings["enterpriseID"].ToString();
                returnItems = client.Do(out returnMsg, context, pOList, info);
                strlog.AppendLine("返回数据:");

                bool isDel = false;
                List<Data> _datalist = new List<Data>();
                rtnRcvInfo rtnpo_ = new rtnRcvInfo();
                foreach (var itemm in returnItems)
                {
                    StrList.Add(itemm.m_code);
                    strlog.AppendLine("单号:" + itemm.m_code);
                    strlog.AppendLine("返回消息:杂发单生成成功!");
                    Data _data = new Data();
                    #region 20231222
                    List<DataLine> list = new List<DataLine>();
                    string Selsql = @"SELECT a.ID,b.BenefitDept,a.DocNo SourceCode,c.Code cWHCode,cc.Name cWHName,b.id DetailID,b.DocLineNo Sequence,b.ItemInfo_ItemCode InvCode,b.StoreUOMQty Quantity,b.LotInfo_LotCode cBatch,
                        b.DescFlexSegments_PrivateDescSeg1 cFree1,b.DescFlexSegments_PrivateDescSeg2 cFree2,b.DescFlexSegments_PrivateDescSeg3 cFree3,
                        b.DescFlexSegments_PrivateDescSeg4 cFree4,b.DescFlexSegments_PrivateDescSeg5 cFree5,b.DescFlexSegments_PrivateDescSeg6 cFree6,
                        b.DescFlexSegments_PrivateDescSeg7 cFree7,b.DescFlexSegments_PrivateDescSeg8 cFree8,b.DescFlexSegments_PrivateDescSeg9 cFree9,
                        b.DescFlexSegments_PrivateDescSeg10 cFree10,'' LogId
                          FROM InvDoc_MiscShip a
                        LEFT JOIN InvDoc_MiscShipL b ON b.MiscShip=a.ID
                        LEFT JOIN CBO_Wh c ON b.Wh=c.ID
                        LEFT JOIN CBO_Wh_Trl cc ON c.ID=cc.ID
                        WHERE a.DocNo='" + itemm.m_code + "'";
                    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.DocNo = itemm.m_code;
                            _data.ID = item["ID"].ToString();
                            _data.SourceCode = itemm.m_code;
                            _data.cDepCode = item["BenefitDept"].ToString();
                            _data.cWHCode = item["cWHCode"].ToString();
                            _data.cWHName = item["cWHName"].ToString();
                            _DataLine.DetailID = item["DetailID"].ToString();
                            _DataLine.Sequence = Int32.Parse(item["Sequence"].ToString());
                            _DataLine.Quantity = Decimal.Parse(item["Quantity"].ToString());
                            _DataLine.InvCode = item["InvCode"].ToString();
                            _DataLine.cBatch = item["cBatch"].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);
                       
                        //rtnpos.Add(rtnpo_);
                    }
                    //rtnpos.Add(rtnpo_);
                    #endregion

                    strlog.AppendLine("*****************************************************");
                    Appconfig.WriteLogFile(strlog.ToString(), "创建杂发单");
                }
                rtnpo_.Data = _datalist;

                if (returnItems.Count() > 0)
                {
                    #region 提交杂发单
                    //提交杂发单
                    CustCommonitMisShip CommitCust = new CustCommonitMisShip();
                    CustCommonitMisShip.OperationResult_CommitMisShip commitResult = new CustCommonitMisShip.OperationResult_CommitMisShip();
                    //commitResult = CommitCust.CustCommitMisShip(itemm.m_code, rCVInfoList[0].WorkPoint);
                    commitResult = CommitCust.CustCommitMisShip(StrList[0], rCVInfoList[0].WorkPoint,"","");

                    if (commitResult.IsSuccess == true)
                    {
                        #region 审核杂发单
                        CustApproveMiscShip ApproveCust = new CustApproveMiscShip();
                        CustApproveMiscShip.OperationResult_ApproveMisShip approveResult = new CustApproveMiscShip.OperationResult_ApproveMisShip();
                        //approveResult = ApproveCust.CustApproveMis(itemm.m_code, rCVInfoList[0].WorkPoint);
                        approveResult = ApproveCust.CustApproveMis(StrList[0], rCVInfoList[0].WorkPoint,"","");

                        if (approveResult.IsSuccess == true)
                        {
                            //StrList.Add(itemm.m_code);
                            //rtnpos = new List<rtnRcvInfo>();
                            //rtnRcvInfo rtnpo = new rtnRcvInfo();
                            rtnpos.Success = true;
                            rtnpos.DocNo ="";
                            rtnpos.Message = "杂发单审核成功!";
                            rtnpos.Data = _datalist;
                            //rtnpos.Add(rtnpo);
                            //return rtnpos;
                        }
                        else
                        {
                            //rtnpos = new List<rtnRcvInfo>();
                            //rtnRcvInfo rtnpo = new rtnRcvInfo();
                            rtnpos.Success = false;
                            rtnpos.DocNo = "";
                            rtnpos.Message = "杂发单审核失败，失败原因:" + approveResult.Message;
                            rtnpos.Data = _datalist;

                            isDel = true;
                            List<string> listt = new List<string>();
                            //listt.Add(itemm.m_code);
                            ICS.DeleteMiscShip.DeleteMiscShipCode custtt = new ICS.DeleteMiscShip.DeleteMiscShipCode();
                            custtt.CustDeleteMiscShip(StrList, orgID);

                            //rtnpos.Add(rtnpo);
                            //return rtnpos;
                        }
                        #endregion
                    }
                    else
                    {
                        //rtnpos = new List<rtnRcvInfo>();
                        //rtnRcvInfo rtnpos = new rtnRcvInfo();
                        ICS.DeleteMiscShip.DeleteMiscShipCode custtt = new ICS.DeleteMiscShip.DeleteMiscShipCode();
                        custtt.CustDeleteMiscShip(StrList, orgID);
                        rtnpos.Success = false;
                        rtnpos.DocNo = "";
                        rtnpos.Data = _datalist;
                        rtnpos.Message = "杂发单提交失败，失败原因:" + commitResult.Message;
                        StringBuilder errorstrlog = new StringBuilder();
                        errorstrlog.AppendLine("创建杂发单(提交失败)");
                        errorstrlog.AppendLine("*****************************************************");
                        foreach (var item in rCVInfoList)
                        {
                            errorstrlog.AppendLine("组织编码:" + item.WorkPoint);
                            foreach (var line in item.details)
                            {
                                errorstrlog.AppendLine("料品编码:" + line.InvCode);
                                errorstrlog.AppendLine("料品数量:" + line.Quantity);
                                errorstrlog.AppendLine("仓库:" + line.WHCode);
                                errorstrlog.AppendLine("批号:" + line.BatchCode);
                            }
                        }
                        errorstrlog.AppendLine("返回消息：" + rtnpos.Message);
                        errorstrlog.AppendLine("*****************************************************");
                        Appconfig.WriteLogFile(errorstrlog.ToString(), "创建杂发单");
                        return rtnpos;
                        

                        //rtnpos.Add(rtnpo);
                        //return rtnpos;
                    }
                    #endregion

                    rtnRcvInfo rtnpotrue = new rtnRcvInfo();
                    rtnpotrue.Success = true;
                    rtnpotrue.DocNo ="";
                    rtnpotrue.Data = _datalist;
                    rtnpotrue.Message = "杂发单创建成功！";
                    //rtnpos.Add(rtnpotrue);
                }
                if (isDel)
                {
                    if (StrList != null && StrList.Count > 0)
                    {
                        ICS.UnApporveMiscShipSV.CustUnApporveMiscShip custUnApprove = new ICS.UnApporveMiscShipSV.CustUnApporveMiscShip(); ;

                        custUnApprove.UnApporveMiscShip(StrList, orgID);

                        ICS.DeleteMiscShip.DeleteMiscShipCode custtt = new ICS.DeleteMiscShip.DeleteMiscShipCode();
                        custtt.CustDeleteMiscShip(StrList, orgID);

                    }
                }

                return rtnpos;
            }
            catch (Exception ex)
            {
                //异常信息捕获
                //List<rtnRcvInfo> rtnpos = new List<rtnRcvInfo>();
                //rtnRcvInfo rtnpo = new rtnRcvInfo();
                rtnpos.Success = false;
                rtnpos.Message = GetExceptionMessage(ex).Split('<')[0];
                //rtnpos.Add(rtnpo);
                if (StrList != null)
                {
                    ICS.DeleteMiscShip.DeleteMiscShipCode custtt = new ICS.DeleteMiscShip.DeleteMiscShipCode();
                    custtt.CustDeleteMiscShip(StrList, orgID);
                }
                StringBuilder strlog = new StringBuilder();
                strlog.AppendLine("创建杂发单");
                strlog.AppendLine("*****************************************************");
                strlog.AppendLine("修改创建人SQL:" + updatesql);
                foreach (var item in rCVInfoList)
                {
                    strlog.AppendLine("组织编码:" + item.WorkPoint);
                    foreach (var line in item.details)
                    {
                        strlog.AppendLine("料品编码:" + line.InvCode);
                        strlog.AppendLine("料品数量:" + line.Quantity);
                        strlog.AppendLine("仓库:" + line.WHCode);
                        strlog.AppendLine("批号:" + line.BatchCode);
                    }
                }
                strlog.AppendLine("返回消息：" + rtnpos.Message);
                strlog.AppendLine("*****************************************************");
                Appconfig.WriteLogFile(strlog.ToString(), "创建杂发单");

                return rtnpos;
            }
            #endregion
        }

        #region 表头类
        public class rCVhead
        {
            private rCVLine[] _lines;
            private string _DocType;
            private string _OrgCode;
            private string _ClientCode;
            private string _DocNO;
            public string DocDate { get; set; }
            //private string _DocType;


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

            public string DocNO
            {
                get { return _DocNO; }
                set { _DocNO = value; }
            }

            /// <summary>
            /// 单据类型
            /// </summary>
            public string DocType
            {
                get { return _DocType; }
                set { _DocType = value; }
            }
            /// <summary>
            /// 组织编码
            /// </summary>
            public string WorkPoint
            {
                get { return _OrgCode; }
                set { _OrgCode = value; }
            }
            /// <summary>
            /// 客户
            /// </summary>
            public string ClientCode
            {
                get { return _ClientCode; }
                set { _ClientCode = value; }
            }
            public string HcFree1 { get; set; }
            public string HcFree2 { get; set; }
            public string HcFree3 { get; set; }
            public string HcFree4 { get; set; }
            public string HcFree5 { get; set; }
            public string HcFree6 { get; set; }


        }
        #endregion

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

            public string WHCode { get; set; }

            public int Sequence { get; set; }

            /// <summary>
            /// 料号
            /// </summary>
            public string InvCode { get; set; }
            /// <summary>
            /// 受益部门
            /// </summary>
            public string Dep { get; set; }

            public string BatchCode { get; set; }

            /// <summary>
            /// 库存批号
            /// </summary>
            public string Project { get; set; }
            /// <summary>
            /// 备注
            /// </summary>
            public string Memo { get; set; }

            /// 私有段1
            //public string PrivateDescSeg1 { get; set; }
            ///// 私有段2
            //public string PrivateDescSeg2 { get; set; }
            public string cFree1 { get; set; }
            /// 私有段2
            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 提取异常信息
        /// <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()
        {
            // 实例化应用上下文对象
            ThreadContext thContext = new ThreadContext();

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

            return thContext;
        }
        #endregion

        #region 时间戳方法
        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 Success { get; set; }
        public string Message { get; set; }
        //public rtnRcvLine[] rtnLines { get; set; }

        //public Data Data { get; set; }
        public List<Data> Data { get; set; }

    }
    public class Data
    {
        public string DocNo { get; set; }
        public string ID { get; set; }
        public string SourceCode { get; set; }
        public string OtherInCode { get; set; }
        public string cDepCode { get; set; }
        public string proCode { get; set; }
        public string cDepName { get; set; }
        public string cWHCode { get; set; }
        public string cWHName { get; set; }
        public string SourceType { get; set; }
        public string CreateUser { get; set; }
        public DateTime CreateDateTime { get; set; }
        public string Checker { get; set; }
        public DateTime CheckDateTime { 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 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; }
    }


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

        //public string srcDocNo { get; set; }

        //public int srcLineNo { get; set; }

        //public decimal reqQty { get; set; }

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

 

}
