using ICS.BFIssueDelete;
using ICS.WCF.Base;
using ICSSoft.DataProject;
using ICSSoft.Entity;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks;
using UFIDA.ISV.BFIssueApprove;
using UFSoft.UBF.Exceptions1;
using UFSoft.UBF.Service;
using UFSoft.UBF.Util.Context;
using www.ufida.org.EntityData;

namespace UFIDA.ISV.CreateAboveIssue
{
    public class CustCreateAboveIssue
    {
        private static string connString = System.Configuration.ConfigurationManager.AppSettings["ERPConnStr"];
        private static log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        /// <summary>
        /// 创建领料单
        /// </summary>
        /// <returns></returns>
        /// 
        public Result CreateAboveIssue(List<IssueAboveData> modellist)
        {
            Result result = new Result();
            var datalist = new List<CreateAboveRtnModel>();
            foreach (IssueAboveData model in modellist)
            {
                try
                {
                    string OrgID = "";
                    List<string> LLCodeList = new List<string>();
                    MessageBase[] message = null;

                    string _MOCode = string.Empty;
                    UFIDAU9ISVMOICreateIssue4ExternalClient client = new UFIDAU9ISVMOICreateIssue4ExternalClient();
                    List<UFIDAU9ISVMOIssueDTOData> molist = new List<UFIDAU9ISVMOIssueDTOData>();
                    UFIDAU9ISVMOIssueDTOData mo = new UFIDAU9ISVMOIssueDTOData();
                    List<UFIDAU9ISVMOPickListDTOData> PL = new List<UFIDAU9ISVMOPickListDTOData>();


                    string orgsql = @"select ID from Base_Organization
                                  where Code='{0}'";
                    orgsql = string.Format(orgsql, model.WorkPoint);
                    DataTable orgdt = DBhlper.Query(orgsql, Appconfig.GetU9ConnStr());
                    if (orgdt.Rows.Count != 0)
                    {
                        OrgID = orgdt.Rows[0]["ID"].ToString();
                    }
                    else
                    {
                        throw new Exception("未获取到组织!");
                    }


                    string sql = "select ID,Name,Code from Base_User where Code ='" + model.User + "'";
                    DataTable dt = DBhlper.Query(sql, Appconfig.GetU9ConnStr());
                    if (dt.Rows.Count == 0)
                    {
                        sql = "select ID,Name,Code from Base_User where Code ='" + Appconfig.GetDefaultUser() + "'";
                        dt = DBhlper.Query(sql, Appconfig.GetU9ConnStr());
                        if (dt.Rows.Count == 0)
                        {
                            throw new Exception("用户不存在");
                        }
                    }

                    var UserID = dt.Rows[0]["ID"].ToString();
                    var UserName = dt.Rows[0]["Name"].ToString();
                    var UserCode = dt.Rows[0]["Code"].ToString();

                    ThreadContext context = CreateContextObj(OrgID, UserID, UserCode);

                    //验证该工单的备料表中是否存在数据
                    int p = Appconfig.IsExistcPickList(model.SourceCode);

                    if (p > 0)
                    {
                        #region 遍历入参LL单行

                        foreach (var item in model.details)
                        {
                            bool IsVMI = false;
                            string strCcode = item.InvCode; //子料
                            decimal _useQty = item.Quantity; //子件使用量

                            string _strWhID = string.Empty;//仓库ID
                            string WHID = "";
                            string ItemID = "";
                            if (!string.IsNullOrWhiteSpace(strCcode))
                            {
                                string _SqlDbType = @"  select Distinct ID,Code from CBO_WH
                                                        where Code='" + item.WHCode + "' AND Org='" + OrgID + "'";
                                _SqlDbType = string.Format(_SqlDbType);
                                DataTable _SqlDbTypedt = DBhlper.Query(_SqlDbType, Appconfig.GetU9ConnStr());
                                if (_SqlDbTypedt != null && _SqlDbTypedt.Rows.Count > 0)
                                {
                                    WHID = _SqlDbTypedt.Rows[0]["ID"].ToString();
                                }
                                else
                                {
                                    throw new Exception("传入仓库不存在!");
                                }

                                _SqlDbType = @"  select Distinct ID,Code from CBO_ItemMaster
                                                     where Code='" + item.InvCode + "' AND Org='" + OrgID + "'";
                                _SqlDbType = string.Format(_SqlDbType);
                                _SqlDbTypedt = DBhlper.Query(_SqlDbType, Appconfig.GetU9ConnStr());
                                if (_SqlDbTypedt != null && _SqlDbTypedt.Rows.Count > 0)
                                {
                                    ItemID = _SqlDbTypedt.Rows[0]["ID"].ToString();
                                }
                                else
                                {
                                    throw new Exception("传入物料不存在!");
                                }
                            }

                            UFIDAU9ISVMOPickListDTOData PLS = new UFIDAU9ISVMOPickListDTOData();

                            PLS.m_descFlexField = new UFIDAU9BaseFlexFieldDescFlexFieldDescFlexSegmentsData();

                            PLS.m_descFlexField.m_privateDescSeg30 = item.LogIds;



                            Decimal MOQty = 0;
                            long MOID = 0;
                            _MOCode = model.SourceCode;
                            DataTable _dt = Appconfig.GetMOQtyAndID(model.SourceCode, OrgID);
                            if (_dt.Rows.Count > 0)
                            {
                                string _strMOQty = string.Empty;
                                string _strMOID = string.Empty;

                                _strMOQty = _dt.Rows[0]["ProductQty"].ToString();
                                if (!string.IsNullOrWhiteSpace(_strMOQty))
                                {
                                    MOQty = Decimal.Parse(_strMOQty);//生产订单数量
                                }
                                _strMOID = _dt.Rows[0]["ID"].ToString();
                                if (!string.IsNullOrWhiteSpace(_strMOID))
                                {
                                    MOID = long.Parse(_strMOID);
                                }

                            }

                            string mOPickList = string.Empty;
                            mOPickList = Appconfig.GetMoPickListIDWithLine(model.SourceCode, strCcode, item.SubLineNO, OrgID);// 1001903220007058;// iPickid;
                            Decimal IssuedQty = 0;   //已发放数量
                            Decimal ActualReqQty = 0; //实际需求数量
                            if (!string.IsNullOrWhiteSpace(mOPickList))
                            {
                                //已发放数量-领料未发数量
                                DataTable dtQty = Appconfig.GetQtyBymOPickList(model.SourceCode, strCcode);
                                if (dtQty != null && dtQty.Rows.Count > 0)
                                {
                                    ActualReqQty = Decimal.Parse(dtQty.Rows[0]["ActualReqQty"].ToString());
                                }
                                PLS.m_mOPickList = long.Parse(mOPickList);
                            }
                            else
                            {
                                throw new Exception("备料表单ID不存在!工单：'" + model.SourceCode + "',料号：'" + strCcode + "' ");
                            }

                            //PLS.m_issueQty = useQty * MOQty - SendQty;// item.issueQty* useQty;//1;   //应发数量

                            //if (ActualReqQty < _useQty)
                            //{
                            //    result.Message += "该料品" + strCcode + "需要领用的数量大于未领数量不能创建改料品的领用;";
                            //}
                            //else
                            //{

                            //if (useQty * MOQty - SendQty - IssueNotDeliverQty > 0)
                            //{
                            //20190920修改ZM
                            //PLS.m_issuedQty = useQty * MOQty - SendQty - IssueNotDeliverQty;// item.issuedQty* useQty;// 1;  //实发数量

                            PLS.m_issueQty = _useQty;
                            PLS.m_issuedQty = _useQty;

                            //仓库
                            if (!string.IsNullOrWhiteSpace(WHID))
                            {
                                PLS.m_issueWh = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                                PLS.m_issueWh.m_iD = long.Parse(WHID);
                            }
                            if (!string.IsNullOrEmpty(item.Vender))
                            {
                                #region 获取供应商ID
                                long VenderID = 0;
                                string vendersql = @"select ID from CBO_Supplier
                                                         where Code='{0}' and Org='{1}'";
                                vendersql = string.Format(vendersql, item.Vender, OrgID);
                                DataTable venderdt = DBhlper.Query(vendersql, Appconfig.GetU9ConnStr());
                                if (venderdt.Rows.Count == 0)
                                {
                                    throw new Exception("传入供应商无法在U9查到对应ID，请确认供应商:" + item.Vender + "在U9是否存在！");
                                }
                                else
                                {
                                    VenderID = long.Parse(venderdt.Rows[0]["ID"].ToString());
                                }
                                #endregion
                                PLS.m_supplier = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                                PLS.m_supplier.m_iD = VenderID;
                                PLS.m_supplier.m_code = item.Vender;
                            }
                            //发货单位
                            PLS.m_issueUOM = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                            string uom = Appconfig.GetMaterialUOM(strCcode);
                            if (!string.IsNullOrWhiteSpace(uom))
                            {
                                PLS.m_issueUOM.m_iD = long.Parse(uom);
                            }

                            PLS.m_aCDType = 0;

                            PLS.m_storageType = 4;//存储类型

                            PLS.SourceIssueDocLine = MOID;
                            #region 获取批号ID(锐腾特殊逻辑，先查询数据中新组织00的批号及库存，有库存则优先使用00组织，其他项目可以忽略该逻辑)
                            long LotID = 0;
                            if (item.BatchCode != "")
                            {
                                string lotsql = @"SELECT ID FROM Lot_LotMaster
                                                      WHERE LotCode='{0}' AND Item='{1}'";
                                lotsql = string.Format(lotsql, item.BatchCode, ItemID);
                                DataTable lotdt = DBhlper.Query(lotsql, Appconfig.GetU9ConnStr());
                                if (lotdt.Rows.Count == 0)
                                {
                                    throw new Exception("传入批号对应料号无关联，获取批号ID失败！");
                                }
                                else
                                {
                                    LotID = long.Parse(lotdt.Rows[0]["ID"].ToString());
                                    #region 先验证U9是否有足够的库存进行发料
                                    string chksql = @"select ISNULL(StoreQtyCU,0) AS StoreQtyCU from InvTrans_WhQoh
                                                                      where ItemInfo_ItemID='{0}' and LotInfo_LotMaster_EntityID='{1}' and Wh='{2}'";
                                    chksql = string.Format(chksql, ItemID, LotID, WHID);
                                    DataTable chkdt = DBhlper.Query(chksql, Appconfig.GetU9ConnStr());
                                    if (chkdt.Rows.Count == 0)
                                    {
                                        throw new Exception("传入料号:" + item.InvCode + "对应批号:" + item.BatchCode + "在仓库:" + item.WHCode + "无库存，无法领料！");
                                    }
                                    else
                                    {
                                        if (Convert.ToDecimal(chkdt.Rows[0]["StoreQtyCU"]) < item.Quantity)
                                        {
                                            throw new Exception("传入料号:" + item.InvCode + "对应批号:" + item.BatchCode + "在仓库:" + item.WHCode + "库存剩余:" + chkdt.Rows[0]["StoreQtyCU"].ToString() + ",传入本次领料数量为:" + item.Quantity + ",库存不足，无法领料！");

                                        }
                                    }
                                    #endregion
                                }
                            }
                            #endregion
                            if (LotID != 0)
                            {
                                PLS.m_lot = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                                PLS.m_lot.m_code = item.BatchCode;
                                PLS.m_lot.m_iD = LotID;
                            }
                            if (IsVMI == true)
                            {
                                PLS.m_supplier = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                                PLS.m_supplier.m_code = item.Vender;
                            }

                            PL.Add(PLS);
                        }

                        #endregion
                    }
                    else
                    {
                        throw new Exception("该工单没有备料表信息");
                    }



                    if (PL != null && PL.Count() > 0)
                    {
                        mo.m_issueType = 0;
                        //部门
                        mo.m_dept = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                        mo.m_dept.m_code = model.DepCode;
                        mo.m_docType = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                        #region 获取生产订单单据类型（作为生产领料单的业务类型）
                        string IssueDocType = "";
                        int IssueBusinessType = 0;
                        string IssueDocTypeCode = "";
                        string DocTypeID = "";

                        string doctypesql = @"SELECT c.Code AS DocTypeCode,aa.BusinessType,aa.Code,aa.ID
                                                    FROM MO_MO A
                                                    LEFT JOIN MO_MODocType c ON c.ID = A.MODocType AND c.Org = A.Org
                                                    LEFT JOIN   MO_IssueDocType aa ON c.BusinessType=aa.BusinessType
                                                    LEFT JOIN MO_IssueDocType_Trl b ON aa.ID=b.ID AND b.SysMLFlag='zh-CN'
                                                   WHERE a.DocNo='{0}' AND a.Org={1} AND b.Name='生产领料单'";
                        doctypesql = string.Format(doctypesql, model.SourceCode, OrgID);
                        DataTable doctypedt = DBhlper.Query(doctypesql, Appconfig.GetU9ConnStr());
                        if (doctypedt.Rows.Count != 0)
                        {
                            IssueDocType = doctypedt.Rows[0]["DocTypeCode"].ToString();
                            IssueBusinessType = int.Parse(doctypedt.Rows[0]["BusinessType"].ToString());
                            IssueDocTypeCode = doctypedt.Rows[0]["Code"].ToString();
                            DocTypeID = doctypedt.Rows[0]["ID"].ToString();
                        }
                        else
                        {
                            throw new Exception("未查询到生产订单对应生产领料单单据类型");
                        }
                        #endregion

                        mo.m_docType.m_code = IssueDocTypeCode;

                        mo.m_docType.m_iD = long.Parse(DocTypeID);
                        mo.m_businessType = IssueBusinessType;
                        mo.m_businessDate = DateTime.Now;


                        string BusinessType = Appconfig.GetBusinessType(model.DocTypeCode);
                        mo.m_srcDoc = new UFIDAU9MOPropertyTypesMOSourceDocData();// _MOCode;
                        mo.m_srcDoc.m_srcDocNo = _MOCode;

                        mo.m_memo = model.Memo; //备注
                        mo.m_pickListDTOs = PL.ToArray();

                        molist.Add(mo);


                        UFIDAU9ISVMOIssueKeyDTOData[] _result = null;
                        _result = client.Do(out message, context, molist.ToArray());
                        if (_result != null && _result.Count() > 0)
                        {
                            foreach (var item in _result)
                            {
                                if (!string.IsNullOrWhiteSpace(item.m_docNo))
                                {
                                    LLCodeList.Add(item.m_docNo);
                                }
                            }
                        }

                        try
                        {
                            //审核
                            CustApproveIssue approveIssue = new CustApproveIssue();
                            CustApproveIssue.OperationResult approveresult = new CustApproveIssue.OperationResult();
                            approveresult = approveIssue.CustBFApproveIssue(LLCodeList, modellist[0].WorkPoint);

                            if (approveresult.IsSuccess == true)
                            {
                                string sqlqry = @"select a.ID HeadID,a.DocNo,b.LineNum,b.ID,b.DescFlexField_PrivateDescSeg30,
                                            b.ItemInfo_ItemCode,b.IssuedQty,b.SourceDoc_SrcDocLine_EntityID
											from MO_IssueDoc a
                                            left join MO_IssueDocLine b on a.id = b.IssueDoc
                                            where a.DocNo ='" + LLCodeList[0] + "' and a.Org ='" + OrgID + "'";
                                DataTable dtqry = DBhlper.Query(sqlqry, Appconfig.GetU9ConnStr());
                                if (dtqry.Rows.Count > 0)
                                {
                                    var linelist = new List<CreateAboveLineRtnModel>();

                                    foreach (DataRow item in dtqry.Rows)
                                    {
                                        linelist.Add(new CreateAboveLineRtnModel
                                        {
                                            DetailID = item["ID"].ToString(),
                                            LogIds = item["DescFlexField_PrivateDescSeg30"].ToString(),
                                            Sequence = item["LineNum"].ToString(),
                                            InvCode = item["ItemInfo_ItemCode"].ToString(),
                                            Quantity = decimal.Parse(item["IssuedQty"].ToString()),
                                            SourceDetailID = item["SourceDoc_SrcDocLine_EntityID"].ToString()
                                        });
                                    }

                                    datalist.Add(new CreateAboveRtnModel
                                    {
                                        IsSuccess = true,
                                        Message = "成功",
                                        IssueCode = LLCodeList[0],
                                        ID = dtqry.Rows[0]["HeadID"].ToString(),
                                        details = linelist
                                    });
                                }
                            }
                            else
                            {
                                throw new Exception(approveresult.MESSAGE);
                            }
                        }
                        catch (Exception ex)
                        {
                            try
                            {
                                //删除
                                CustBFIssueDelete issueDelete = new CustBFIssueDelete();
                                bool success = issueDelete.CustDeleteIssue(LLCodeList, OrgID);
                                if (success)
                                {
                                    var linelist = new List<CreateAboveLineRtnModel>();

                                    foreach (var item in model.details)
                                    {
                                        linelist.Add(new CreateAboveLineRtnModel
                                        {
                                            SourceDetailID = item.SourceDetailID,
                                            LogIds = item.LogIds,
                                            Sequence = item.Sequence
                                        });
                                    }

                                    datalist.Add(new CreateAboveRtnModel
                                    {
                                        IsSuccess = false,
                                        Message = "审核失败，删除成功，审核异常：" + ex.Message,
                                        details = linelist
                                    });
                                }
                                else
                                {
                                    throw new Exception("审核失败，删除失败，审核异常：" + ex.Message);
                                }
                            }
                            catch (Exception exdelete)
                            {
                                var linelist = new List<CreateAboveLineRtnModel>();

                                foreach (var item in model.details)
                                {
                                    linelist.Add(new CreateAboveLineRtnModel
                                    {
                                        SourceDetailID = item.SourceDetailID,
                                        LogIds = item.LogIds,
                                        Sequence = item.Sequence
                                    });
                                }

                                datalist.Add(new CreateAboveRtnModel
                                {
                                    IsSuccess = false,
                                    Message = "审核失败，删除失败，异常：" + exdelete.Message,
                                    details = linelist
                                });
                            }

                        }
                    }
                    else
                    {
                        throw new Exception("传入的数据未获取到创建领料的信息 ");
                    }

                }
                catch (Exception ex)
                {
                    var linelist = new List<CreateAboveLineRtnModel>();

                    foreach (var item in model.details)
                    {
                        linelist.Add(new CreateAboveLineRtnModel
                        {
                            SourceDetailID = item.SourceDetailID,
                            LogIds = item.LogIds,
                            Sequence = item.Sequence
                        });
                    }

                    datalist.Add(new CreateAboveRtnModel
                    {
                        IsSuccess = false,
                        Message = "创建失败：" + ex.Message,
                        details = linelist
                    });
                }
            }
            result.Success = true;
            result.Message = "成功";
            result.Data = datalist;
            return result;
        }

        /// <summary>
        /// 创建生产领料单（无备料领料，领料同时创建备料单）
        /// </summary>
        /// <param name="modellist"></param>
        /// <returns></returns>
        public OperationResultForNoSrc CreateIssueWithOutPickList(List<IssueWithOutPickListData> modellist)
        {
            OperationResultForNoSrc result = new OperationResultForNoSrc();
            object context = new object();
            List<string> LLCodeList = new List<string>();
            string OrgID = "";
            bool IsDelete = false;
            try
            {
                StringBuilder beginstrlog = new StringBuilder();
                beginstrlog.AppendLine("创建生产备料单(传入数据开始)");
                beginstrlog.AppendLine("*****************************************************");
                foreach (var model in modellist)
                {
                    beginstrlog.AppendLine("生产订单:" + model.MOCODE);
                    beginstrlog.AppendLine("组织:" + model.OrgCode);

                    foreach (var item in model.linelist)
                    {

                        beginstrlog.AppendLine("行号:" + item.DOCLINENO);
                        beginstrlog.AppendLine("料号:" + item.ITEM);
                        beginstrlog.AppendLine("实际需求数量:" + item.ActualReqQty);
                        beginstrlog.AppendLine("标准用量:" + item.STDReqQty);

                    }
                    beginstrlog.AppendLine("--------------------------------------------------");

                }
                beginstrlog.AppendLine("*****************************************************");
                beginstrlog.AppendLine("创建生产备料单(传入数据结束)");
                Appconfig.WriteLogFile(beginstrlog.ToString(), "创建生产备料单");
                string _MOCode = string.Empty;
                UFIDAU9ISVMOICreateIssue4ExternalClient client = new UFIDAU9ISVMOICreateIssue4ExternalClient();
                MessageBase[] message = null;


                StringBuilder str = new StringBuilder();
                string ORGCode = modellist[0].OrgCode;

                OrgID = Appconfig.IsExistsCode(ORGCode, "Base_Organization");

                if (string.IsNullOrEmpty(OrgID))
                {
                    throw new Exception("组织编码：" + ORGCode + "在U9中不存在。");
                }

                UFIDAU9ISVMOIssueDTOData[] molist = createiss(modellist, OrgID, ORGCode);



                context = CreateContextObj(OrgID,"","");
                UFIDAU9ISVMOIssueKeyDTOData[] _result = null;
                _result = client.Do(out message, context, molist);

                string LLCode = "";
                string ResultLLCode = "";

                StringBuilder endstr = new StringBuilder();
                endstr.AppendLine("**************创建生产备料单返回日志******************");
                if (_result != null && _result.Count() > 0)
                {
                    for (int i = 0; i < _result.Count(); i++)
                    {
                        endstr.AppendLine("领料单" + _result[i].m_docNo.ToString());
                        LLCode += _result[i].m_docNo.ToString() + ",";
                        ResultLLCode += "'" + _result[i].m_docNo.ToString() + "',";
                        LLCodeList.Add(_result[i].m_docNo.ToString());
                    }
                    result.LLCode = LLCode.TrimEnd(',');
                    result.Success = true;
                    DataSet ds = new DataSet();
                    #region 查询
                    string rtnsql = @"  
                            select DISTINCT a.ID as ID,a.ID as IDs,SourceDoc_SrcDocNo as SourceCode ,
                           a.DocNo as IssueCode,'' AS cDepCode,'' as cDepName,'' WHCode,'' WHName,
                            a.SourceDoc_SrcDocType as SourceType,a.CreatedBy as CreateUser,a.CreatedOn as CreateDateTime,
                            a.ApproveBy as Checker,a.ApproveOn as CheckDateTime
                            from MO_IssueDoc a
                            WHERE a.DocNo IN ({0}) and a.Org='{1}'";
                    rtnsql = string.Format(rtnsql, ResultLLCode.TrimEnd(','), OrgID);
                    DataTable mdt = DBhlper.Query(rtnsql, connString);
                    ds.Tables.Add(mdt);
                    rtnsql = @" select DISTINCT a.ID as IDs,b.ID as DetailID,b.LineNum as Sequence,c.Code as InvCode 
							,b.IssuedQty as Quantity,b.SourceDoc_SrcDocLineID as SourceDetailID,0 as Amount
							,d.Code as cDepCode,dd.Name as cDepName,e.Code as WHCode,ee.Name as WHName
							,isnull(f.Code,'') ProjectCode,isnull(g.LotCode,'') cBatch,'' version ,'' brand,
							'' as cFree1,
							'' as cFree2,
							'' as cFree3,
							'' as cFree4,
							'' as cFree5,
							'' as cFree6,
							'' as cFree7,
							'' as cFree8,
							'' as cFree9,
							'' as cFree10
							from MO_IssueDoc a
							left join MO_IssueDocLine b on b.IssueDoc=a.ID
							left join CBO_ItemMaster c on c.ID=b.ItemInfo_ItemID
							left join CBO_Department d on d.ID=b.IssueDept
							left join CBO_Department_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 IN ({0}) and a.Org='{1}'";
                    rtnsql = string.Format(rtnsql, ResultLLCode.TrimEnd(','), OrgID);
                    DataTable sdt = DBhlper.Query(rtnsql, connString);
                    ds.Tables.Add(sdt);
                    #endregion
                    result.Data = JSON.DataSetToJson(ds, "details", "IDs");
                }
                else
                {
                    result.Success = false;
                }
                if (result.Success)
                {
                    result.Message = "创建成功";
                }
                else
                {
                    result.Message = "创建失败";
                }
                endstr.AppendLine("**************创建生产备料单返回日志结束******************");
                Appconfig.WriteLogFile(endstr.ToString(), "创建生产备料单");

                CustApproveIssue cusappiss = new CustApproveIssue();
                CustApproveIssue.OperationResult ISSAPP = cusappiss.CustBFApproveIssue(LLCodeList, ORGCode);
                if (!ISSAPP.IsSuccess)
                {
                    #region 审核失败日志
                    StringBuilder strlog = new StringBuilder();
                    strlog.AppendLine("审核失败日志记录开始");
                    strlog.AppendLine("*****************************************************");
                    foreach (string code in LLCodeList)
                    {
                        strlog.AppendLine("领料单号:" + code);
                    }
                    strlog.AppendLine("失败原因:" + ISSAPP.MESSAGE);
                    strlog.AppendLine("*****************************************************");
                    Appconfig.WriteLogFile(strlog.ToString(), "创建U9领料单");
                    #endregion
                    #region 审核失败时删除所有生成的领料单
                    CustBFIssueDelete issueDelete = new CustBFIssueDelete();
                    issueDelete.CustDeleteIssue(LLCodeList, OrgID);
                    IsDelete = true;
                    #endregion
                    throw new Exception("单据：" + ISSAPP.LLCode + "提交错误，错误提示：" + ISSAPP.MESSAGE + "！");
                }
            }
            catch (Exception ex)
            {
                string Message = GetExceptionMessage(ex);
                result.Success = false;
                result.Message += Message;
                StringBuilder str = new StringBuilder();
                str.AppendLine("创建生产备料单：");
                str.AppendLine("返回错误信息：" + result.Message);
                Appconfig.WriteLogFile(str.ToString(), "创建生产备料单");
                #region 失败时删除所有生成的领料单
                if (IsDelete == false)
                {
                    CustBFIssueDelete issueDelete = new CustBFIssueDelete();
                    issueDelete.CustDeleteIssue(LLCodeList, OrgID);
                }
                #endregion
            }
            return result;
        }

        private UFIDAU9ISVMOIssueDTOData[] createiss(List<IssueWithOutPickListData> modellist, string OrgID, string ORGCode)
        {
            string moid = "";
            string docType = "";
            string docTypeCode = "";
            List<UFIDAU9ISVMOIssueDTOData> lsslist = new List<UFIDAU9ISVMOIssueDTOData>();
            UFIDAU9ISVMOIssueDTOData lss = new UFIDAU9ISVMOIssueDTOData();
            List<UFIDAU9CBOPubControllerCommonArchiveDataDTOData> molst = new List<UFIDAU9CBOPubControllerCommonArchiveDataDTOData>();
            List<UFIDAU9ISVMOPickListDTOData> picklst = new List<UFIDAU9ISVMOPickListDTOData>();


            foreach (IssueWithOutPickListData model in modellist)
            {
                if (!string.IsNullOrWhiteSpace(model.MOCODE))
                {
                    string orgsql = @"select A.ID,A.DocState,ISNULL(B.TargetDocType,'') AS TargetDocType
                                      ,ISNULL(B.TargetDocTypeCode,'') AS TargetDocTypeCode from MO_MO A 
                                      LEFT JOIN Base_PushToDocTypeRuleLine B ON B.EntityFieldValue1=Convert(nvarchar,A.BusinessType)
                                      AND B.SourceOrg=A.Org AND B.EntityFieldValue3=A.MODocType
                                      where A.DocNo='{0}' AND A.Org='{1}'";
                    orgsql = string.Format(orgsql, model.MOCODE, OrgID);
                    DataTable orgdt = DBhlper.Query(orgsql, Appconfig.GetU9ConnStr());
                    if (orgdt.Rows.Count != 0)
                    {
                        moid = orgdt.Rows[0]["ID"].ToString();
                        docType = orgdt.Rows[0]["TargetDocType"].ToString();
                        docTypeCode = orgdt.Rows[0]["TargetDocTypeCode"].ToString();
                    }
                    else
                    {
                        throw new Exception("工单：" + model.MOCODE + "不存在!");
                    }


                    UFIDAU9CBOPubControllerCommonArchiveDataDTOData mo1 = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                    mo1.m_iD = Convert.ToInt64(moid);
                    mo1.m_code = model.MOCODE;
                    molst.Add(mo1);


                    foreach (IssueWithOutPickListDatas line in model.linelist)
                    {
                        UFIDAU9ISVMOPickListDTOData pick = new UFIDAU9ISVMOPickListDTOData();

                        pick.m_aCDType = 0;

                        //无备料领料
                        pick.m_isNoPickLine = true;
                        //生产订单
                        UFIDAU9CBOPubControllerCommonArchiveDataDTOData mo = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                        mo.m_iD = Convert.ToInt64(moid);
                        mo.m_code = model.MOCODE;
                        pick.m_mO = mo;

                        // 料品
                        string itemid = "";
                        orgsql = @"select id from CBO_ItemMaster where code='{0}'";
                        orgsql = string.Format(orgsql, line.ITEM);
                        orgdt = DBhlper.Query(orgsql, Appconfig.GetU9ConnStr());
                        if (orgdt.Rows.Count != 0)
                            itemid = orgdt.Rows[0]["ID"].ToString();
                        else
                            throw new Exception("料品：" + line.ITEM + "不存在!");


                        UFIDAU9CBOPubControllerCommonArchiveDataDTOData item = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                        item.m_iD = Convert.ToInt64(itemid);
                        item.m_code = line.ITEM;
                        pick.m_item = item;

                        //领料单位
                        if (!string.IsNullOrWhiteSpace(Appconfig.GetMaterialUOM(line.ITEM)))
                        {
                            UFIDAU9CBOPubControllerCommonArchiveDataDTOData uom = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                            uom.m_iD = Convert.ToInt64(Appconfig.GetMaterialUOM(line.ITEM));
                            pick.m_issueUOM = uom;
                        }
                        else
                        {
                            throw new Exception("单位：" + line.UOM + "不存在!");
                        }
                        pick.m_storageType = 4;

                        //发料数量 
                        pick.m_issuedQty = Convert.ToDecimal(line.ActualReqQty);
                        // 应发数量
                        pick.m_issueQty = Convert.ToDecimal(line.ActualReqQty);
                        //存储地点
                        if (!string.IsNullOrWhiteSpace(line.WH))
                        {
                            UFIDAU9CBOPubControllerCommonArchiveDataDTOData ww = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                            if (!string.IsNullOrWhiteSpace(Appconfig.GetWhCodeByBinid(line.WH, OrgID)))
                            {
                                ww.m_iD = Convert.ToInt64(Appconfig.GetWhCodeByBinid(line.WH, OrgID));
                                ww.m_code = line.WH;
                                pick.m_issueWh = ww;
                            }
                            else
                            {
                                throw new Exception("仓库：" + line.WH + "不存在!");
                            }
                        }
                        // 批号
                        if (!string.IsNullOrWhiteSpace(line.LotNO))
                        {
                            UFIDAU9CBOPubControllerCommonArchiveDataDTOData lotno = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                            if (!string.IsNullOrWhiteSpace(Appconfig.GetLotNOByBinid(line.LotNO, OrgID, itemid)))
                            {
                                lotno.m_iD = Convert.ToInt64(Appconfig.GetLotNOByBinid(line.LotNO, OrgID, itemid));
                                lotno.m_code = line.LotNO;
                                pick.m_lot = lotno;
                            }

                        }
                        // 货主组织
                        UFIDAU9CBOPubControllerCommonArchiveDataDTOData org = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                        org.m_iD = long.Parse(OrgID);
                        org.m_code = ORGCode;// line.ORGCODE;
                        pick.m_ownerOrg = org;
                        picklst.Add(pick);
                    }
                }
                else
                {
                    throw new Exception("存在生产订单号为空!");
                }

            }
            lss.m_mOs = molst.ToArray();

            lss.m_issueType = 0;
            lss.sysState = 0;
            lss.m_businessDate = Convert.ToDateTime(DateTime.Now);
            UFIDAU9CBOPubControllerCommonArchiveDataDTOData d = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
            d.m_iD = Convert.ToInt64(OrgID);
            d.m_code = ORGCode;
            lss.m_issueOrg = d;
            lss.m_docType = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
            lss.m_docType.m_iD = long.Parse(docType);
            lss.m_docType.m_code = docTypeCode;

            lss.m_businessType = 47;
            lss.m_pickListDTOs = picklst.ToArray();
            lsslist.Add(lss);

            return lsslist.ToArray();
        }

        #region 辅助方法


        private ThreadContext CreateContextObj(string OrgID,string UserID,string UserCode)
        {
            // 实例化应用上下文对象
            ThreadContext thContext = new ThreadContext();

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

            return thContext;
        }
        # endregion


        #region 提取异常信息
        /// <summary>
        /// 提取异常信息
        /// </summary>
        /// <param name="ex"></param>
        private static 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

        public class OperationResult
        {
            /// <summary>
            /// 结果状态,默认值false
            /// </summary>
            public bool Success { get; set; }

            /// <summary>
            ///处理消息
            /// </summary>
            public string Message { get; set; }

            /// <summary>
            /// 输出领料订单
            /// </summary>
            public string LLCode { get; set; }
        }

        public class OperationResultForNoSrc
        {
            /// <summary>
            /// 结果状态,默认值false
            /// </summary>
            public bool Success { get; set; }

            /// <summary>
            ///处理消息
            /// </summary>
            public string Message { get; set; }

            /// <summary>
            /// 输出领料订单
            /// </summary>
            public string LLCode { get; set; }
            public object Data { get; set; }
        }


        public class CreateAboveRtnModel
        {
            public string IssueCode { get; set; }

            public string ID { get; set; }

            public bool IsSuccess { get; set; }

            public string Message { get; set; }

            public List<CreateAboveLineRtnModel> details { get; set; }
        }

        public class CreateAboveLineRtnModel
        {
            public string DetailID { get; set; }

            public string Sequence { get; set; }

            public string LogIds { get; set; }

            public string SourceDetailID { get; set; }

            public string InvCode { get; set; }

            public decimal Quantity { get; set; }
        }

        #region 20190705

        //public OperationResult CreateIssue_20190701bak(IssueData model)
        //{
        //    OperationResult result = new OperationResult();
        //    ThreadContext context = CreateContextObj();
        //    //MO-19050007   11020007
        //    try
        //    {
        //        string _MOCode = string.Empty;
        //        UFIDAU9ISVMOICreateIssue4ExternalClient client = new UFIDAU9ISVMOICreateIssue4ExternalClient();
        //        MessageBase[] message = null;
        //        List<UFIDAU9ISVMOIssueDTOData> molist = new List<UFIDAU9ISVMOIssueDTOData>();
        //        UFIDAU9ISVMOIssueDTOData mo = new UFIDAU9ISVMOIssueDTOData();

        //        List<UFIDAU9ISVMOPickListDTOData> PL = new List<UFIDAU9ISVMOPickListDTOData>();

        //        if (model != null && model.lines.Count > 0)
        //        {
        //            foreach (var item in model.lines)
        //            {
        //                if (!string.IsNullOrWhiteSpace(item.InvCode))
        //                {
        //                    DataTable dt = Appconfig.GetCcodeListByMcode(item.InvCode);
        //                    if (dt != null && dt.Rows.Count > 0)
        //                    {
        //                        foreach (DataRow row in dt.Rows)
        //                        {
        //                            string strCcode = row["ccode"].ToString(); //子料
        //                            decimal useQty = Decimal.Parse(row["useQty"].ToString()); //子件使用量
        //                            string strUnitCode = row["UnitCode"].ToString(); //单位

        //                            //string strWhCode = row["WhCode"].ToString(); //仓库
        //                            //string strBinCode = row["BinCode"].ToString(); //库位

        //                            string strWhCode = item.WhCode; //row["WhCode"].ToString(); //仓库
        //                            string strBinCode = item.BinCode;//row["BinCode"].ToString(); //库位

        //                            UFIDAU9ISVMOPickListDTOData PLS = new UFIDAU9ISVMOPickListDTOData();

        //                            int i = Appconfig.IsExistItem(strCcode);
        //                            if (i < 1)
        //                            {
        //                                result.Message = "料品编码不存在!";
        //                                result.IsSuccess = false;
        //                                return result;
        //                            }

        //                            #region 注释
        //                            //if (!string.IsNullOrWhiteSpace(item.BinCode))
        //                            //{
        //                            //    int j = Appconfig.IsExistcPos(item.BinCode);
        //                            //    if (i < 1)
        //                            //    {
        //                            //        result.Message = "库位编码不存在!";
        //                            //        result.IsSuccess = false;
        //                            //        return result;
        //                            //    }
        //                            //    else
        //                            //    {
        //                            //        PLS.m_issueBin = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
        //                            //        PLS.m_issueBin.m_code = item.BinCode;
        //                            //    }
        //                            //}
        //                            //string WhCode = string.Empty;
        //                            //if (!string.IsNullOrWhiteSpace(item.BinCode))
        //                            //{
        //                            //    WhCode = Appconfig.GetWhCodeByBin(item.BinCode);
        //                            //}
        //                            #endregion

        //                            Decimal MOQty = 0;
        //                            long MOID = 0;
        //                            _MOCode = item.SourceCode;
        //                            DataTable _dt = Appconfig.GetMOQtyAndID(item.SourceCode);
        //                            if (_dt != null && _dt.Rows.Count > 0)
        //                            {
        //                                foreach (DataRow _item in _dt.Rows)
        //                                {
        //                                    string _strMOQty = string.Empty;
        //                                    string _strMOID = string.Empty;

        //                                    _strMOQty = _item["ProductQty"].ToString();
        //                                    if (!string.IsNullOrWhiteSpace(_strMOQty))
        //                                    {
        //                                        MOQty = Decimal.Parse(_strMOQty);
        //                                    }
        //                                    _strMOID = _item["ID"].ToString();
        //                                    if (!string.IsNullOrWhiteSpace(_strMOID))
        //                                    {
        //                                        MOID = long.Parse(_strMOID);
        //                                    }
        //                                }
        //                            }


        //                            string mOPickList = string.Empty;
        //                            mOPickList = Appconfig.GetMoPickListID(item.SourceCode, strCcode);// 1001903220007058;// iPickid;
        //                            Decimal IssuedQty = 0;   //已发放数量
        //                            Decimal IssueNotDeliverQty = 0; //领料未发数量
        //                            Decimal SendQty = 0; //已发放数量
        //                            if (!string.IsNullOrWhiteSpace(mOPickList))
        //                            {
        //                                //已发放数量-领料未发数量
        //                                DataTable dtQty = Appconfig.GetQtyBymOPickList(item.SourceCode);
        //                                if (dtQty != null && dtQty.Rows.Count > 0)
        //                                {
        //                                    //IssuedQty = Decimal.Parse(dtQty.Rows[0]["IssuedQty"].ToString());
        //                                    IssueNotDeliverQty = Decimal.Parse(dtQty.Rows[0]["TotalIssueNotDeliverQty"].ToString());
        //                                    SendQty = Decimal.Parse(dtQty.Rows[0]["IssuedQty"].ToString());

        //                                }
        //                                PLS.m_mOPickList = long.Parse(mOPickList);
        //                            }
        //                            else
        //                            {
        //                                result.Message = "备料表单ID不存在!工单：'" + item.SourceCode + "',料号：'" + strCcode + "' ";
        //                                result.IsSuccess = false;
        //                                return result;
        //                            }

        //                            //根据工单获取已发掉的料数量
        //                            //Decimal SendQty = Appconfig.GetMOSendQty(item.SourceCode);

        //                            //PLS.m_issueQty = useQty * MOQty - SendQty;// item.issueQty* useQty;//1;   //应发数量
        //                            PLS.m_issueQty = useQty * MOQty;// item.issueQty* useQty;//1;   //应发数量
        //                            //产生领料单的数量为:实际需求数量-已发放数量-领料未发数量
        //                            //PLS.m_issuedQty = useQty * MOQty - SendQty;// item.issuedQty* useQty;// 1;  //实发数量

        //                            if (useQty * MOQty - SendQty - IssueNotDeliverQty > 0)
        //                            {
        //                                PLS.m_issuedQty = useQty * MOQty - SendQty - IssueNotDeliverQty;// item.issuedQty* useQty;// 1;  //实发数量

        //                                if (!string.IsNullOrWhiteSpace(strBinCode))
        //                                {
        //                                    PLS.m_issueBin = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
        //                                    PLS.m_issueBin.m_code = strBinCode;
        //                                }
        //                                //仓库
        //                                if (!string.IsNullOrWhiteSpace(strWhCode))
        //                                {
        //                                    PLS.m_issueWh = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
        //                                    PLS.m_issueWh.m_code = strWhCode;// "004";//cWh;
        //                                }
        //                                //发货单位
        //                                PLS.m_issueUOM = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
        //                                string uom = Appconfig.GetMaterialUOM(strCcode);
        //                                if (!string.IsNullOrWhiteSpace(uom))
        //                                {
        //                                    PLS.m_issueUOM.m_iD = long.Parse(uom);// Appconfig.GetMaterialUOM(item.InvCode);// 1001607080022602;// iMaterialOutUOM;
        //                                }
        //                                PLS.m_aCDType = 0;

        //                                //Decimal MOQty = Decimal.Parse(Appconfig.GetMOQty(item.SourceCode));

        //                                PLS.m_storageType = 4;//存储类型
        //                                //SourceDoc_SrcDocNo
        //                                PLS.SourceIssueDocLine = MOID;


        //                                PL.Add(PLS);
        //                            }
        //                            else
        //                            {
        //                                result.Message = "该工单料品数量已经领料完成，不能继续领料" + item.SourceCode + "',料号：'" + strCcode + "' ";
        //                                result.IsSuccess = false;

        //                                return result;
        //                            }
        //                        }
        //                    }

        //                }

        //            }
        //        }

        //        //部门
        //        mo.m_dept = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
        //        mo.m_dept.m_code = model.DepCode;// "MY0601";
        //        mo.m_docType = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
        //        mo.m_docType.m_code = model.DocTypeCode;//"1"; 单据类型
        //        //mo.m_businessType = model.BusinessType;// 47;//标准生产
        //        string BusinessType = Appconfig.GetBusinessType(model.DocTypeCode);
        //        if (!string.IsNullOrWhiteSpace(BusinessType))
        //        {
        //            mo.m_businessType = Int32.Parse(BusinessType);// 47;//标准生产
        //        }
        //        mo.m_srcDoc = new UFIDAU9MOPropertyTypesMOSourceDocData();// _MOCode;
        //        mo.m_srcDoc.m_srcDocNo = _MOCode;



        //        mo.m_memo = model.Memo; //备注
        //        mo.m_pickListDTOs = PL.ToArray();

        //        molist.Add(mo);

        //        UFIDAU9ISVMOIssueKeyDTOData[] _result = null;
        //        _result = client.Do(out message, context, molist.ToArray());
        //        if (_result != null && _result.Count() > 0)
        //        {
        //            foreach (var item in _result)
        //            {
        //                result.LLCode = item.m_docNo;
        //                if (!string.IsNullOrWhiteSpace(item.m_docNo))
        //                {
        //                    result.IsSuccess = true;
        //                    result.Message = "成功创建领料单！";
        //                }
        //            }
        //        }
        //        #region 错误
        //        //        //class UFIDA.U9.MO.MO.MO has no such field: Code in AttributeMap when Compiling OQL:  Code=@Code and Org=@Org
        //        //        //领料单1001906120110350不存在单行信息
        //        //        //未将对象引用设置到对象的实例。
        //        //        //领料单1001906140000062不存在单行信息
        //        //        //领料单1001906140000083不存在单行信息
        //        //        //领料单1001906140000105不存在单行信息
        //        //        //领料单1001906140000106不存在单行信息
        //        //        //必需设置单据类型
        //        //        //领料单1001906170000093不存在单行信息
        //        //        //领料单1001906170000104不存在单行信息
        //        #endregion
        //    }
        //    catch (Exception ex)
        //    {
        //        string Message = GetExceptionMessage(ex);
        //        result.IsSuccess = false;
        //        result.Message = Message;
        //    }
        //    return result;
        //}



        //public OperationResult CreateIssue(IssueData model)
        //{
        //    OperationResult result = new OperationResult();
        //    ThreadContext context = CreateContextObj();
        //    //MO-19050007   11020007
        //    try
        //    {
        //        string _MOCode = string.Empty;
        //        UFIDAU9ISVMOICreateIssue4ExternalClient client = new UFIDAU9ISVMOICreateIssue4ExternalClient();
        //        MessageBase[] message = null;
        //        List<UFIDAU9ISVMOIssueDTOData> molist = new List<UFIDAU9ISVMOIssueDTOData>();
        //        UFIDAU9ISVMOIssueDTOData mo = new UFIDAU9ISVMOIssueDTOData();

        //        List<UFIDAU9ISVMOPickListDTOData> PL = new List<UFIDAU9ISVMOPickListDTOData>();


        //        if (model != null && model.lines.Count > 0)
        //        {
        //            foreach (var item in model.lines)
        //            {
        //                //if (!string.IsNullOrWhiteSpace(item.InvCode))
        //                //{
        //                //验证该工单的备料表中是否存在数据
        //                int p = Appconfig.IsExistcPickList(item.SourceCode);

        //                if (p > 0)
        //                {
        //                    #region 根据备料表获取数据
        //                    DataTable dt = Appconfig.GetPickList(item.SourceCode);
        //                    if (dt != null && dt.Rows.Count > 0)
        //                    {
        //                        foreach (DataRow row in dt.Rows)
        //                        {
        //                            string strCcode = row["ccode"].ToString(); //子料
        //                            decimal useQty = Decimal.Parse(row["useQty"].ToString()); //子件使用量
        //                            string strUnitCode = row["UnitCode"].ToString(); //单位

        //                            //string strWhCode = row["WhCode"].ToString(); //仓库
        //                            //string strBinCode = row["BinCode"].ToString(); //库位

        //                            string strWhCode = item.WhCode; //row["WhCode"].ToString(); //仓库
        //                            string strBinCode = item.BinCode;//row["BinCode"].ToString(); //库位

        //                            UFIDAU9ISVMOPickListDTOData PLS = new UFIDAU9ISVMOPickListDTOData();

        //                            int i = Appconfig.IsExistItem(strCcode);
        //                            if (i < 1)
        //                            {
        //                                result.Message = "料品编码不存在!";
        //                                result.IsSuccess = false;
        //                                return result;
        //                            }

        //                            Decimal MOQty = 0;
        //                            long MOID = 0;
        //                            _MOCode = item.SourceCode;
        //                            DataTable _dt = Appconfig.GetMOQtyAndID(item.SourceCode);
        //                            if (_dt != null && _dt.Rows.Count > 0)
        //                            {
        //                                foreach (DataRow _item in _dt.Rows)
        //                                {
        //                                    string _strMOQty = string.Empty;
        //                                    string _strMOID = string.Empty;

        //                                    _strMOQty = _item["ProductQty"].ToString();
        //                                    if (!string.IsNullOrWhiteSpace(_strMOQty))
        //                                    {
        //                                        MOQty = Decimal.Parse(_strMOQty);//生产订单数量
        //                                    }
        //                                    _strMOID = _item["ID"].ToString();
        //                                    if (!string.IsNullOrWhiteSpace(_strMOID))
        //                                    {
        //                                        MOID = long.Parse(_strMOID);
        //                                    }
        //                                }
        //                            }

        //                            string mOPickList = string.Empty;
        //                            mOPickList = Appconfig.GetMoPickListID(item.SourceCode, strCcode);// 1001903220007058;// iPickid;
        //                            Decimal IssuedQty = 0;   //已发放数量
        //                            Decimal IssueNotDeliverQty = 0; //领料未发数量
        //                            Decimal SendQty = 0; //已发放数量
        //                            if (!string.IsNullOrWhiteSpace(mOPickList))
        //                            {
        //                                //已发放数量-领料未发数量
        //                                DataTable dtQty = Appconfig.GetQtyBymOPickList(item.SourceCode);
        //                                if (dtQty != null && dtQty.Rows.Count > 0)
        //                                {
        //                                    //IssuedQty = Decimal.Parse(dtQty.Rows[0]["IssuedQty"].ToString());
        //                                    IssueNotDeliverQty = Decimal.Parse(dtQty.Rows[0]["TotalIssueNotDeliverQty"].ToString());
        //                                    SendQty = Decimal.Parse(dtQty.Rows[0]["IssuedQty"].ToString());

        //                                }
        //                                PLS.m_mOPickList = long.Parse(mOPickList);
        //                            }
        //                            else
        //                            {
        //                                result.Message = "备料表单ID不存在!工单：'" + item.SourceCode + "',料号：'" + strCcode + "' ";
        //                                result.IsSuccess = false;
        //                                return result;
        //                            }

        //                            //根据工单获取已发掉的料数量
        //                            //Decimal SendQty = Appconfig.GetMOSendQty(item.SourceCode);

        //                            //PLS.m_issueQty = useQty * MOQty - SendQty;// item.issueQty* useQty;//1;   //应发数量
        //                            PLS.m_issueQty = useQty * MOQty;// item.issueQty* useQty;//1;   //应发数量
        //                            //产生领料单的数量为:实际需求数量-已发放数量-领料未发数量
        //                            //PLS.m_issuedQty = useQty * MOQty - SendQty;// item.issuedQty* useQty;// 1;  //实发数量

        //                            if (useQty * MOQty - SendQty - IssueNotDeliverQty > 0)
        //                            {
        //                                PLS.m_issuedQty = useQty * MOQty - SendQty - IssueNotDeliverQty;// item.issuedQty* useQty;// 1;  //实发数量

        //                                if (!string.IsNullOrWhiteSpace(strBinCode))
        //                                {
        //                                    PLS.m_issueBin = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
        //                                    PLS.m_issueBin.m_code = strBinCode;
        //                                }
        //                                //仓库
        //                                if (!string.IsNullOrWhiteSpace(strWhCode))
        //                                {
        //                                    PLS.m_issueWh = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
        //                                    PLS.m_issueWh.m_code = strWhCode;// "004";//cWh;
        //                                }
        //                                //发货单位
        //                                PLS.m_issueUOM = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
        //                                string uom = Appconfig.GetMaterialUOM(strCcode);
        //                                if (!string.IsNullOrWhiteSpace(uom))
        //                                {
        //                                    PLS.m_issueUOM.m_iD = long.Parse(uom);// Appconfig.GetMaterialUOM(item.InvCode);// 1001607080022602;// iMaterialOutUOM;
        //                                }
        //                                PLS.m_aCDType = 0;

        //                                //Decimal MOQty = Decimal.Parse(Appconfig.GetMOQty(item.SourceCode));

        //                                PLS.m_storageType = 4;//存储类型
        //                                //SourceDoc_SrcDocNo
        //                                PLS.SourceIssueDocLine = MOID;


        //                                PL.Add(PLS);
        //                            }
        //                            else
        //                            {
        //                                result.Message = "该工单料品数量已经领料完成，不能继续领料" + item.SourceCode + "',料号：'" + strCcode + "' ";
        //                                result.IsSuccess = false;

        //                                return result;
        //                            }
        //                        }
        //                    }
        //                    #endregion
        //                }
        //                else
        //                {
        //                    result.Message = "该工单没有备料表信息 ";
        //                    result.IsSuccess = false;

        //                    return result;
        //                }
        //                #region 20190705注释ZM
        //                //else
        //                //{
        //                //    #region 根据BOM展开获取数据
        //                //    DataTable dt = Appconfig.GetCcodeListByMcode(item.InvCode);
        //                //    if (dt != null && dt.Rows.Count > 0)
        //                //    {
        //                //        foreach (DataRow row in dt.Rows)
        //                //        {
        //                //            string strCcode = row["ccode"].ToString(); //子料
        //                //            decimal useQty = Decimal.Parse(row["useQty"].ToString()); //子件使用量
        //                //            string strUnitCode = row["UnitCode"].ToString(); //单位

        //                //            //string strWhCode = row["WhCode"].ToString(); //仓库
        //                //            //string strBinCode = row["BinCode"].ToString(); //库位

        //                //            string strWhCode = item.WhCode; //row["WhCode"].ToString(); //仓库
        //                //            string strBinCode = item.BinCode;//row["BinCode"].ToString(); //库位

        //                //            UFIDAU9ISVMOPickListDTOData PLS = new UFIDAU9ISVMOPickListDTOData();

        //                //            int i = Appconfig.IsExistItem(strCcode);
        //                //            if (i < 1)
        //                //            {
        //                //                result.Message = "料品编码不存在!";
        //                //                result.IsSuccess = false;
        //                //                return result;
        //                //            }

        //                //            #region 注释
        //                //            //if (!string.IsNullOrWhiteSpace(item.BinCode))
        //                //            //{
        //                //            //    int j = Appconfig.IsExistcPos(item.BinCode);
        //                //            //    if (i < 1)
        //                //            //    {
        //                //            //        result.Message = "库位编码不存在!";
        //                //            //        result.IsSuccess = false;
        //                //            //        return result;
        //                //            //    }
        //                //            //    else
        //                //            //    {
        //                //            //        PLS.m_issueBin = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
        //                //            //        PLS.m_issueBin.m_code = item.BinCode;
        //                //            //    }
        //                //            //}
        //                //            //string WhCode = string.Empty;
        //                //            //if (!string.IsNullOrWhiteSpace(item.BinCode))
        //                //            //{
        //                //            //    WhCode = Appconfig.GetWhCodeByBin(item.BinCode);
        //                //            //}
        //                //            #endregion

        //                //            Decimal MOQty = 0;
        //                //            long MOID = 0;
        //                //            _MOCode = item.SourceCode;
        //                //            DataTable _dt = Appconfig.GetMOQtyAndID(item.SourceCode);
        //                //            if (_dt != null && _dt.Rows.Count > 0)
        //                //            {
        //                //                foreach (DataRow _item in _dt.Rows)
        //                //                {
        //                //                    string _strMOQty = string.Empty;
        //                //                    string _strMOID = string.Empty;

        //                //                    _strMOQty = _item["ProductQty"].ToString();
        //                //                    if (!string.IsNullOrWhiteSpace(_strMOQty))
        //                //                    {
        //                //                        MOQty = Decimal.Parse(_strMOQty);
        //                //                    }
        //                //                    _strMOID = _item["ID"].ToString();
        //                //                    if (!string.IsNullOrWhiteSpace(_strMOID))
        //                //                    {
        //                //                        MOID = long.Parse(_strMOID);
        //                //                    }
        //                //                }
        //                //            }


        //                //            string mOPickList = string.Empty;
        //                //            mOPickList = Appconfig.GetMoPickListID(item.SourceCode, strCcode);// 1001903220007058;// iPickid;
        //                //            Decimal IssuedQty = 0;   //已发放数量
        //                //            Decimal IssueNotDeliverQty = 0; //领料未发数量
        //                //            Decimal SendQty = 0; //已发放数量
        //                //            if (!string.IsNullOrWhiteSpace(mOPickList))
        //                //            {
        //                //                //已发放数量-领料未发数量
        //                //                DataTable dtQty = Appconfig.GetQtyBymOPickList(item.SourceCode);
        //                //                if (dtQty != null && dtQty.Rows.Count > 0)
        //                //                {
        //                //                    //IssuedQty = Decimal.Parse(dtQty.Rows[0]["IssuedQty"].ToString());
        //                //                    IssueNotDeliverQty = Decimal.Parse(dtQty.Rows[0]["TotalIssueNotDeliverQty"].ToString());
        //                //                    SendQty = Decimal.Parse(dtQty.Rows[0]["IssuedQty"].ToString());

        //                //                }
        //                //                PLS.m_mOPickList = long.Parse(mOPickList);
        //                //            }
        //                //            else
        //                //            {
        //                //                result.Message = "备料表单ID不存在!工单：'" + item.SourceCode + "',料号：'" + strCcode + "' ";
        //                //                result.IsSuccess = false;
        //                //                return result;
        //                //            }

        //                //            //根据工单获取已发掉的料数量
        //                //            //Decimal SendQty = Appconfig.GetMOSendQty(item.SourceCode);

        //                //            //PLS.m_issueQty = useQty * MOQty - SendQty;// item.issueQty* useQty;//1;   //应发数量
        //                //            PLS.m_issueQty = useQty * MOQty;// item.issueQty* useQty;//1;   //应发数量
        //                //            //产生领料单的数量为:实际需求数量-已发放数量-领料未发数量
        //                //            //PLS.m_issuedQty = useQty * MOQty - SendQty;// item.issuedQty* useQty;// 1;  //实发数量

        //                //            if (useQty * MOQty - SendQty - IssueNotDeliverQty > 0)
        //                //            {
        //                //                PLS.m_issuedQty = useQty * MOQty - SendQty - IssueNotDeliverQty;// item.issuedQty* useQty;// 1;  //实发数量

        //                //                if (!string.IsNullOrWhiteSpace(strBinCode))
        //                //                {
        //                //                    PLS.m_issueBin = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
        //                //                    PLS.m_issueBin.m_code = strBinCode;
        //                //                }
        //                //                //仓库
        //                //                if (!string.IsNullOrWhiteSpace(strWhCode))
        //                //                {
        //                //                    PLS.m_issueWh = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
        //                //                    PLS.m_issueWh.m_code = strWhCode;// "004";//cWh;
        //                //                }
        //                //                //发货单位
        //                //                PLS.m_issueUOM = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
        //                //                string uom = Appconfig.GetMaterialUOM(strCcode);
        //                //                if (!string.IsNullOrWhiteSpace(uom))
        //                //                {
        //                //                    PLS.m_issueUOM.m_iD = long.Parse(uom);// Appconfig.GetMaterialUOM(item.InvCode);// 1001607080022602;// iMaterialOutUOM;
        //                //                }
        //                //                PLS.m_aCDType = 0;

        //                //                //Decimal MOQty = Decimal.Parse(Appconfig.GetMOQty(item.SourceCode));

        //                //                PLS.m_storageType = 4;//存储类型
        //                //                //SourceDoc_SrcDocNo
        //                //                PLS.SourceIssueDocLine = MOID;


        //                //                PL.Add(PLS);
        //                //            }
        //                //            else
        //                //            {
        //                //                result.Message = "该工单料品数量已经领料完成，不能继续领料" + item.SourceCode + "',料号：'" + strCcode + "' ";
        //                //                result.IsSuccess = false;

        //                //                return result;
        //                //            }
        //                //        }
        //                //    }
        //                //    #endregion
        //                //}
        //                #endregion

        //                //}

        //            }
        //        }

        //        //部门
        //        mo.m_dept = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
        //        mo.m_dept.m_code = model.DepCode;// "MY0601";
        //        mo.m_docType = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
        //        mo.m_docType.m_code = model.DocTypeCode;//"1"; 单据类型
        //        //mo.m_businessType = model.BusinessType;// 47;//标准生产
        //        string BusinessType = Appconfig.GetBusinessType(model.DocTypeCode);
        //        if (!string.IsNullOrWhiteSpace(BusinessType))
        //        {
        //            mo.m_businessType = Int32.Parse(BusinessType);// 47;//标准生产
        //        }
        //        mo.m_srcDoc = new UFIDAU9MOPropertyTypesMOSourceDocData();// _MOCode;
        //        mo.m_srcDoc.m_srcDocNo = _MOCode;

        //        mo.m_memo = model.Memo; //备注
        //        mo.m_pickListDTOs = PL.ToArray();

        //        molist.Add(mo);

        //        UFIDAU9ISVMOIssueKeyDTOData[] _result = null;
        //        _result = client.Do(out message, context, molist.ToArray());
        //        if (_result != null && _result.Count() > 0)
        //        {
        //            foreach (var item in _result)
        //            {
        //                result.LLCode = item.m_docNo;
        //                if (!string.IsNullOrWhiteSpace(item.m_docNo))
        //                {
        //                    result.IsSuccess = true;
        //                    result.Message = "成功创建领料单！";
        //                }
        //            }
        //        }
        //        #region 错误
        //        //        //class UFIDA.U9.MO.MO.MO has no such field: Code in AttributeMap when Compiling OQL:  Code=@Code and Org=@Org
        //        //        //领料单1001906120110350不存在单行信息
        //        //        //未将对象引用设置到对象的实例。
        //        //        //领料单1001906140000062不存在单行信息
        //        //        //领料单1001906140000083不存在单行信息
        //        //        //领料单1001906140000105不存在单行信息
        //        //        //领料单1001906140000106不存在单行信息
        //        //        //必需设置单据类型
        //        //        //领料单1001906170000093不存在单行信息
        //        //        //领料单1001906170000104不存在单行信息
        //        #endregion
        //    }
        //    catch (Exception ex)
        //    {
        //        string Message = GetExceptionMessage(ex);
        //        result.IsSuccess = false;
        //        result.Message = Message;
        //    }
        //    return result;
        //}
        #endregion


        public class IssueAboveData
        {
            /// <summary>
            /// 申请部门
            /// </summary>
            public string DepCode { get; set; }

            /// <summary>
            /// 领料单据类型    1--生产领料单
            /// </summary>
            public string DocTypeCode { get; set; }

            /// <summary>
            /// 生产工单 
            /// </summary>
            public string SourceCode { get; set; }

            public string Memo { get; set; }//备注
            /// <summary>
            /// 组织编码
            /// </summary>
            public string WorkPoint { get; set; }

            public string User { get; set; }

            //public string WhCode { get; set; }//仓库
            //public string BinCode { get; set; }//库位 20190917换到表体上
            public List<IssueLineData> details { get; set; }

        }

        public class IssueData_bak20190709
        {
            /// <summary>
            /// 申请部门
            /// </summary>
            public string DepCode { get; set; }

            /// <summary>
            /// 领料单据类型    1--生产领料单
            /// </summary>
            public string DocTypeCode { get; set; }

            /// <summary>
            /// 生产工单 
            /// </summary>
            public string SourceCode { get; set; }

            public string Memo { get; set; }//备注

            public string WhCode { get; set; }//仓库
            public string BinCode { get; set; }//库位 
            public List<IssueLineData> details { get; set; }

        }

        public class IssueLineData
        {
            public string SubLineNO { get; set; }//工单子件行号
            public string InvCode { get; set; }//子料号
            public Decimal Quantity { get; set; }//子料数量
            public string WHCode { get; set; }//存储地点 
            public string BatchCode { get; set; }//领料批号
            public string Vender { get; set; }//供应商

            public string SourceDetailID { get; set; }

            public string Sequence { 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 LogIds { get; set; }
        }


        public class RtnIssueData
        {
            public string DocNo { get; set; }//单号
            public List<IssueLineData> lines { get; set; }//行
        }


        public class IssueWithOutPickListData
        {
            public string MOCODE { get; set; }
            public string OrgCode { get; set; }
            public string memo { get; set; }
            public string DocDate { get; set; }
            public string DocTypeCode { get; set; }
            public List<IssueWithOutPickListDatas> linelist { get; set; }
        }
        public class IssueWithOutPickListDatas
        {
            public string ORGCODE { get; set; }
            public string DOCLINENO { get; set; }
            public string ITEM { get; set; }
            public string UOM { get; set; }
            public string Project { get; set; }
            public string WH { get; set; }
            public string LotNO { get; set; }
            public decimal ActualReqQty { get; set; }
            public decimal STDReqQty { get; set; }

        }
        public class LLMO
        {

            public string LLCODE { get; set; }

            public string MOCODE { get; set; }
        }
    }


}
