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.BFIssueApprove;
//using UFIDA.ISV.CreateLotMaster;
using UFSoft.UBF.Exceptions;
using UFSoft.UBF.Service;
using UFSoft.UBF.Util.Context;
using www.ufida.org.EntityData;
using UFIDA.ISV.BFPMRecedeApprove;
using ICS.CreateLotMaster;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using ICSSoft.DataProject;
using ICSSoft.Entity;
using ICS.BFIssueDelete;

namespace ICS.CreateIssue
{
    public class CustCreateIssue
    {
        private static log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        private static string connString = System.Configuration.ConfigurationManager.AppSettings["ERPConnStr"];
        private static string LogName = "创建材料入库单";
        /// <summary>
        /// 创建退料单
        /// </summary>
        /// <returns></returns>
        /// 
        public Result CreateIssue(List<IssueData> modellist)
        {
            Result res = new Result();
            var datalist = new List<IssueData>();

            foreach (var info in modellist)
            {
                try
                {
                    ThreadContext context = new ThreadContext();
                    string _MOCode = string.Empty;
                    UFIDAU9ISVMOICreatRecedeIssueDocSVClient client = new UFIDAU9ISVMOICreatRecedeIssueDocSVClient();
                    MessageBase[] message = null;
                    List<UFIDAU9ISVMORecedeItemAndSnDTOData> molist = new List<UFIDAU9ISVMORecedeItemAndSnDTOData>();


                    UFIDAU9CBOPubControllerCommonArchiveDataDTOData docType = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();

                    string OrgID = "";
                    string orgsql = @"select ID from Base_Organization
                                          where Code='{0}'";
                    orgsql = string.Format(orgsql, info.WorkPoint);
                    DataTable orgdt = DBhlper.Query(orgsql, Appconfig.GetU9ConnStr());
                    if (orgdt.Rows.Count != 0)
                    {
                        OrgID = orgdt.Rows[0]["ID"].ToString();
                    }
                    else
                    {
                        throw new Exception("组织编码不存在");
                    }
                    #region 获取业务员名称
                    string CreateBy = string.Empty;
                    string usersql = "select ID,Name,Code from Base_User where Code ='" + info.User + "'";
                    DataTable userdt = DBhlper.Query(usersql, Appconfig.GetU9ConnStr());
                    #endregion
                    if (userdt.Rows.Count != 0)
                    {
                        CreateBy = userdt.Rows[0]["Name"].ToString();
                    }
                    else
                    {
                        usersql = "select ID,Name,Code from Base_User where Code ='" + Appconfig.GetDefaultUser() + "'";
                        userdt = DBhlper.Query(usersql, Appconfig.GetU9ConnStr());
                        if (userdt.Rows.Count != 0)
                        {
                            CreateBy = userdt.Rows[0]["Name"].ToString();
                        }
                        else
                        {
                            throw new Exception("用户编码不存在");
                        }


                    }

                    string UserID = userdt.Rows[0]["ID"].ToString();
                    string UserCode = userdt.Rows[0]["Code"].ToString();


                    #region 遍历入参LL单行
                    foreach (var item in info.details)
                    {
                        UFIDAU9ISVMORecedeItemAndSnDTOData mo = new UFIDAU9ISVMORecedeItemAndSnDTOData();
                        long lllineID = 0;
                        string llsql = @"select ID,IsIssued from MO_IssueDocLine
                                      where ID='{0}'";
                        llsql = string.Format(llsql, item.SourceDetailID);
                        DataTable lldt = DBhlper.Query(llsql, Appconfig.GetU9ConnStr());
                        if (lldt.Rows.Count > 0)
                        {
                            if (lldt.Rows[0]["IsIssued"].ToString().ToUpper() != "TRUE")
                            {
                                throw new Exception("领料单行未进行发料确认，不能退料，行：" + item.SourceDetailID);
                            }
                            else
                            {
                                lllineID = long.Parse(lldt.Rows[0]["ID"].ToString());
                            }
                        }
                        else
                        {
                            throw new Exception("领料单行不存在");
                        }

                        mo.m_issueDocLine = lllineID;

                        if (string.IsNullOrEmpty(item.InvCode))
                        {
                            throw new Exception("料品编码为空，行：" + item.SourceDetailID);
                        }


                        string sqlWH = @"select ID,Code from CBO_Wh
                                         WHERE Code='" + item.WHCode + "' AND Org='" + OrgID + "'";
                        sqlWH = string.Format(sqlWH);
                        DataTable _dtWH = DBhlper.Query(sqlWH, Appconfig.GetU9ConnStr());
                        if (_dtWH.Rows.Count == 0)
                        {
                            throw new Exception("仓库不存在，行：" + item.SourceDetailID);
                        }

                        string strWhCode = _dtWH.Rows[0]["Code"].ToString();
                        string _strWhID = _dtWH.Rows[0]["ID"].ToString();


                        mo.m_whCode = strWhCode;
                        mo.m_wh = long.Parse(_strWhID);


                        int i = Appconfig.IsExistItem(item.InvCode);
                        if (i < 1)
                        {
                            throw new Exception("料品编码不存在，行：" + item.SourceDetailID);
                        }

                        mo.m_recedeQty = item.Quantity;
                        mo.m_itemCode = item.InvCode;
                        mo.m_recedeReason = item.RecedeReason;


                        #region 创建批号接口调用
                        string LotID = "";
                        if (item.BatchCode != "")
                        {
                            CustCreateLotMaster LotMasterCreate = new CustCreateLotMaster();
                            string lotWHCode = item.WHCode;
                            string lotItemCode = item.InvCode;
                            string LotCode = item.BatchCode;
                            LotMasterCreate.CustCreateRCVLotMaster(lotWHCode, lotItemCode, LotCode, OrgID, ref LotID);
                            if (LotID != "")
                            {
                                mo.m_lotMaster = long.Parse(LotID);
                                mo.m_lotNo = item.BatchCode;
                            }
                        }
                        #endregion

                        molist.Add(mo);
                    }

                    #endregion


                    if (!ConfigurationManager.AppSettings.AllKeys.Contains("RtnMoIssueDocType"))
                    {
                        throw new Exception("生产退料单单据类型在配置文件未配置");
                    }

                    string sqlDocType = @"SELECT a.Code,b.Name,a.ID FROM MO_IssueDocType a
                                LEFT JOIN MO_IssueDocType_Trl b ON a.ID=b.ID
                                 WHERE a.Code ='" + Appconfig.GetRtnMoIssueDocType() + "'   AND a.Org ='" + OrgID + "'";


                    DataTable _dtDocType = DBhlper.Query(sqlDocType, Appconfig.GetU9ConnStr());

                    if (_dtDocType.Rows.Count == 0)
                    {
                        throw new Exception("生产退料单单据类型不存在");
                    }


                    docType.m_code = Appconfig.GetRtnMoIssueDocType();

                    docType.m_iD = long.Parse(_dtDocType.Rows[0]["ID"].ToString());
                    docType.m_name = _dtDocType.Rows[0]["Name"].ToString();



                    context = CreateContextObj(OrgID, UserID, UserCode);

                    string[] _result = client.Do(out message, context, molist.ToArray(), false, docType);
                    List<string> LLCodeList = new List<string>();

                    if (_result != null && _result.Count() > 0)
                    {
                        for (int i = 0; i < _result.Count(); i++)
                        {
                            LLCodeList.Add(_result[i].ToString());
                        }
                    }



                    if (LLCodeList != null && LLCodeList.Count > 0)
                    {
                        try
                        {
                            foreach (var item in info.details)
                            {
                                string sqlLog = @"update b set b.DescFlexField_PrivateDescSeg30 ='{0}'
                                        from MO_IssueDoc a
                                        left join MO_IssueDocLine b on a.ID = b.IssueDoc
                                        where a.DocNo ='" + LLCodeList[0] + "' and b.SourceIssueDocLine ='" + item.SourceDetailID + "'";
                                sqlLog = string.Format(sqlLog, item.LogIds);
                                DBhlper.EXecute(sqlLog, Appconfig.GetU9ConnStr());
                            }


                            CustApproveIssue.OperationResult shResult = new CustApproveIssue.OperationResult();
                            CustApproveIssue sh = new CustApproveIssue();
                            shResult = sh.CustBFApproveIssue(LLCodeList, info.WorkPoint);
                            if (shResult.IsSuccess == true)
                            {
                                #region 审核后修改单据审核人
                                string DocNoList = "";
                                foreach (string LLDocNO in LLCodeList)
                                {
                                    DocNoList += "'" + LLDocNO + "',";
                                }
                                DocNoList = DocNoList.TrimEnd(',');

                                usersql = @"update MO_IssueDoc set ApproveBy='{0}',ModifiedBy='{0}'
                                where DocNo in ({1}) AND Org='{2}'
                                update MO_IssueDocLine set ModifiedBy='{0}'
                                where IssueDoc in (select ID from MO_IssueDoc
								where DocNo in ({1}) AND Org='{2}')";
                                usersql = string.Format(usersql, CreateBy, DocNoList, OrgID);
                                DBhlper.EXecute(usersql, Appconfig.GetU9ConnStr());

                                #endregion

                                var linelist = new List<IssueLineData>();
                                foreach (var item in info.details)
                                {
                                    linelist.Add(new IssueLineData
                                    {
                                        SourceDetailID = item.SourceDetailID,
                                        LogIds = item.LogIds
                                    });
                                }

                                datalist.Add(new IssueData
                                {
                                    SourceCode = info.SourceCode,
                                    IsSuccess = true,
                                    Message = "创建已审核的单据成功",
                                    details = linelist
                                });
                            }
                            else
                            {
                                throw new Exception(shResult.MESSAGE);
                            }
                        }
                        catch (Exception ex)
                        {
                            //审核异常  删除单据
                            try
                            {
                                CustBFIssueDelete issueDelete = new CustBFIssueDelete();
                                bool IsTrue = issueDelete.CustDeleteIssue(LLCodeList, OrgID);
                                if (!IsTrue)
                                {
                                    throw new Exception("删除失败");
                                }


                                var linelist = new List<IssueLineData>();
                                foreach (var item in info.details)
                                {
                                    linelist.Add(new IssueLineData
                                    {
                                        SourceDetailID = item.SourceDetailID,
                                        LogIds = item.LogIds
                                    });
                                }

                                datalist.Add(new IssueData
                                {
                                    SourceCode = info.SourceCode,
                                    IsSuccess = false,
                                    Message = "创建成功，审核失败，删除成功，审核异常：" + GetExceptionMessage(ex),
                                    details = linelist
                                });
                            }
                            catch (Exception exdelete)
                            {
                                var linelist = new List<IssueLineData>();
                                foreach (var item in info.details)
                                {
                                    linelist.Add(new IssueLineData
                                    {
                                        SourceDetailID = item.SourceDetailID,
                                        LogIds = item.LogIds
                                    });
                                }

                                datalist.Add(new IssueData
                                {
                                    SourceCode = info.SourceCode,
                                    IsSuccess = false,
                                    Message = "创建成功，审核失败，删除失败，审核异常：" + ex.Message + "，删除异常：" + GetExceptionMessage(exdelete),
                                    details = linelist
                                });
                            }
                        }

                    }
                    else
                    {
                        throw new Exception("创建失败，返回单号为空");
                    }
                }
                catch (Exception ex)
                {
                    var linelist = new List<IssueLineData>();
                    foreach (var item in info.details)
                    {
                        linelist.Add(new IssueLineData
                        {
                            SourceDetailID = item.SourceDetailID,
                            LogIds = item.LogIds
                        });
                    }

                    datalist.Add(new IssueData
                    {
                        SourceCode = info.SourceCode,
                        IsSuccess = false,
                        Message = "创建失败：" + GetExceptionMessage(ex),
                        details = linelist
                    });
                }
            }

            res.Success = true;
            res.Message = "成功";
            res.Data = datalist;
            return res;
        }




        public Result CreateIssueWithPickID(List<IssueData> modellist)
        {
            Result res = new Result();
            var datalist = new List<IssueData>();

            foreach (var info in modellist)
            {
                try
                {
                    ThreadContext context = new ThreadContext();

                    string _MOCode = string.Empty;
                    UFIDAU9ISVMOICreatRecedeIssueDocSVClient client = new UFIDAU9ISVMOICreatRecedeIssueDocSVClient();
                    MessageBase[] message = null;
                    List<UFIDAU9ISVMORecedeItemAndSnDTOData> molist = new List<UFIDAU9ISVMORecedeItemAndSnDTOData>();
                    UFIDAU9ISVMORecedeItemAndSnDTOData mo = new UFIDAU9ISVMORecedeItemAndSnDTOData();

                    UFIDAU9CBOPubControllerCommonArchiveDataDTOData docType = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();


                    string OrgID = "";
                    string orgsql = @"select ID from Base_Organization
                                          where Code='{0}'";
                    orgsql = string.Format(orgsql, info.WorkPoint);
                    DataTable orgdt = DBhlper.Query(orgsql, Appconfig.GetU9ConnStr());
                    if (orgdt.Rows.Count != 0)
                    {
                        OrgID = orgdt.Rows[0]["ID"].ToString();
                    }
                    else
                    {
                        throw new Exception("组织编码:" + info.WorkPoint + "不存在!");
                    }


                    string CreateBy = string.Empty;
                    string usersql = "select ID,Name from Base_User where Code ='" + info.User + "'";
                    DataTable userdt = DBhlper.Query(usersql, Appconfig.GetU9ConnStr());

                    if (userdt.Rows.Count != 0)
                    {
                        CreateBy = userdt.Rows[0]["Name"].ToString();
                    }
                    else
                    {
                        throw new Exception("用户编码不存在");
                    }

                    string UserID = userdt.Rows[0]["ID"].ToString();

                    if (string.IsNullOrEmpty(info.SourceCode))
                    {
                        throw new Exception("领料单号为空");
                    }


                    #region 遍历入参LL单行
                    foreach (var item in info.details)
                    {
                        string sql = "select ID from MO_MOPickList where id ='" + item.SourceDetailID + "'";
                        DataTable dt = DBhlper.Query(sql, Appconfig.GetU9ConnStr());
                        if (dt.Rows.Count == 0)
                        {
                            throw new Exception("备料单行不存在");
                        }


                        mo = new UFIDAU9ISVMORecedeItemAndSnDTOData();
                        mo.m_pickID = long.Parse(item.SourceDetailID);



                        if (string.IsNullOrEmpty(item.InvCode))
                        {
                            throw new Exception("料品编码为空，行：" + item.SourceDetailID);
                        }


                        string sqlWH = @"select ID,Code from CBO_Wh
                                         WHERE Code='" + item.WHCode + "' AND Org='" + OrgID + "'";
                        sqlWH = string.Format(sqlWH);
                        DataTable _dtWH = DBhlper.Query(sqlWH, Appconfig.GetU9ConnStr());
                        if (_dtWH.Rows.Count == 0)
                        {
                            throw new Exception("仓库不存在，行：" + item.SourceDetailID);
                        }

                        string strWhCode = _dtWH.Rows[0]["Code"].ToString();
                        string _strWhID = _dtWH.Rows[0]["ID"].ToString();

                        int i = Appconfig.IsExistItem(item.InvCode);
                        if (i < 1)
                        {
                            throw new Exception("料品不存在，行：" + item.SourceDetailID);
                        }



                        mo.m_recedeQty = item.Quantity;
                        mo.m_itemCode = item.InvCode;
                        mo.m_recedeReason = item.RecedeReason;

                        #region 创建批号接口调用
                        string LotID = "";
                        if (item.BatchCode != "")
                        {
                            CustCreateLotMaster LotMasterCreate = new CustCreateLotMaster();
                            string lotWHCode = item.WHCode;
                            string lotItemCode = item.InvCode;
                            string LotCode = item.BatchCode;
                            LotMasterCreate.CustCreateRCVLotMaster(lotWHCode, lotItemCode, LotCode, OrgID, ref LotID);
                            if (LotID != "")
                            {
                                mo.m_lotMaster = long.Parse(LotID);
                                mo.m_lotNo = item.BatchCode;
                            }
                        }
                        #endregion
                        molist.Add(mo);
                    }

                    #endregion





                    if (!ConfigurationManager.AppSettings.AllKeys.Contains("RtnMoIssueDocType"))
                    {
                        throw new Exception("生产退料单单据类型在配置文件未配置");
                    }

                    string sqlDocType = @"SELECT a.Code,b.Name,a.ID FROM MO_IssueDocType a
                                LEFT JOIN MO_IssueDocType_Trl b ON a.ID=b.ID
                                 WHERE a.Code ='" + Appconfig.GetRtnMoIssueDocType() + "'   AND a.Org ='" + OrgID + "'";


                    DataTable _dtDocType = DBhlper.Query(sqlDocType, Appconfig.GetU9ConnStr());

                    if (_dtDocType.Rows.Count == 0)
                    {
                        throw new Exception("生产退料单单据类型不存在");
                    }


                    docType.m_code = Appconfig.GetRtnMoIssueDocType();

                    docType.m_iD = long.Parse(_dtDocType.Rows[0]["ID"].ToString());
                    docType.m_name = _dtDocType.Rows[0]["Name"].ToString();


                    context = CreateContextObj(OrgID, UserID, info.User);

                    string[] _result = client.Do(out message, context, molist.ToArray(), false, docType);


                    if (_result.Length == 0)
                    {
                        throw new Exception("U9标准创建服务返回的单据为空");
                    }


                    List<string> LLCodeList = new List<string>();
                    for (int i = 0; i < _result.Count(); i++)
                    {
                        LLCodeList.Add(_result[i].ToString());
                    }


                    try
                    {
                        //更新Logids
                        foreach (var item in info.details)
                        {
                            string sqlLog = @"update b set b.DescFlexField_PrivateDescSeg30 ='{0}'
                                        from MO_IssueDoc a
                                        left join MO_IssueDocLine b on a.ID = b.IssueDoc
                                        where a.DocNo ='" + LLCodeList[0] + "' and b.SourceIssueDocLine ='" + item.SourceDetailID + "'";
                            sqlLog = string.Format(sqlLog, item.LogIds);
                            DBhlper.Query(sqlLog, Appconfig.GetU9ConnStr());
                        }


                        CustApproveIssue.OperationResult shResult = new CustApproveIssue.OperationResult();
                        CustApproveIssue sh = new CustApproveIssue();
                        shResult = sh.CustBFApproveIssue(LLCodeList, info.WorkPoint);
                        if (shResult.IsSuccess == true)
                        {
                            #region 审核后修改单据审核人
                            usersql = @"update MO_IssueDoc set ApproveBy='{0}',ModifiedBy='{0}'
                                where DocNo = '{1}' AND Org='{2}';
                                update MO_IssueDocLine set ModifiedBy='{0}'
                                where IssueDoc in (select ID from MO_IssueDoc
								where DocNo ='{1}' AND Org='{2}')";
                            usersql = string.Format(usersql, CreateBy, LLCodeList[0], OrgID);
                            DBhlper.Query(usersql, Appconfig.GetU9ConnStr());

                            #endregion

                            string sql = @"select distinct a.ID,a.DocNo,b.ID LineID,b.LineNum,c.Code,b.IssuedQty,
                                b.DescFlexField_PrivateDescSeg30,b.SourceDoc_SrcDocLine_EntityID
                                from MO_IssueDoc a
                                left join MO_IssueDocLine b on a.ID = b.IssueDoc
                                left join CBO_ItemMaster c on b.Item = c.ID
                                where a.DocNo ='' and a.Org =''";
                            DataTable dt = DBhlper.Query(sql, Appconfig.GetU9ConnStr());
                            if (dt.Rows.Count == 0)
                            {
                                throw new Exception("服务返回的单号未查到相关单据信息");
                            }

                            var linelist = new List<IssueLineData>();
                            foreach (DataRow dr in dt.Rows)
                            {
                                linelist.Add(new IssueLineData
                                {
                                    DetailID = dr["LineID"].ToString(),
                                    Sequence = dr["LineNum"].ToString(),
                                    InvCode = dr["Code"].ToString(),
                                    Quantity = decimal.Parse(dr["IssuedQty"].ToString()),
                                    LogIds = dr["DescFlexField_PrivateDescSeg30"].ToString(),
                                    SourceDetailID = dr["SourceDoc_SrcDocLine_EntityID"].ToString()
                                });
                            }
                            datalist.Add(new IssueData
                            {
                                ID = dt.Rows[0]["ID"].ToString(),
                                IssueNEGCode = dt.Rows[0]["DocNo"].ToString(),
                                IsSuccess = true,
                                Message = "创建已审核的单据成功",
                                details = linelist
                            });
                        }
                        else
                        {
                            throw new Exception(shResult.MESSAGE);
                        }
                    }
                    catch (Exception ex)
                    {
                        //审核异常  删除单据
                        try
                        {
                            CustBFIssueDelete issueDelete = new CustBFIssueDelete();
                            bool IsTrue = issueDelete.CustDeleteIssue(LLCodeList, OrgID);
                            if (!IsTrue)
                            {
                                throw new Exception("删除失败");
                            }


                            var linelist = new List<IssueLineData>();
                            foreach (var item in info.details)
                            {
                                linelist.Add(new IssueLineData
                                {
                                    SourceDetailID = item.SourceDetailID,
                                    LogIds = item.LogIds
                                });
                            }

                            datalist.Add(new IssueData
                            {
                                SourceCode = info.SourceCode,
                                IsSuccess = false,
                                Message = "创建成功，审核失败，删除成功，审核异常：" + ex.Message,
                                details = linelist
                            });
                        }
                        catch (Exception exdelete)
                        {
                            throw new Exception("创建成功，审核失败，删除失败，审核异常：" + ex.Message + "，删除异常：" + exdelete.Message);
                        }
                    }


                }
                catch (Exception ex)
                {
                    var linelist = new List<IssueLineData>();
                    foreach (var item in info.details)
                    {
                        linelist.Add(new IssueLineData
                        {
                            SourceDetailID = item.SourceDetailID,
                            LogIds = item.LogIds
                        });
                    }

                    datalist.Add(new IssueData
                    {
                        IsSuccess = false,
                        Message = ex.Message,
                        details = linelist
                    });
                }
            }

            res.Success = true;
            res.Message = "成功";
            res.Data = datalist;
            return res;
        }







        public rtnMaterialInInfo ActionCreateMaterialIN(List<IssueData> infos)
        {
            rtnMaterialInInfo rtninfo = new rtnMaterialInInfo();
            try
            {
                string OrgID = "";
                string orgsql = @"select ID from Base_Organization
                                  where Code='{0}'";
                orgsql = string.Format(orgsql, infos[0].WorkPoint);
                DataTable orgdt = DBhlper.Query(orgsql, connString);
                if (orgdt.Rows.Count != 0)
                {
                    OrgID = orgdt.Rows[0]["ID"].ToString();
                }
                else
                {
                    throw new Exception("传入组织编码错误!");
                }
                List<CreateMaterialINDocAPIModel> HeadList = new List<CreateMaterialINDocAPIModel>();
                CreateMaterialINDocAPIModel HeadInfo = new CreateMaterialINDocAPIModel();
                List<LineData> BodyList = new List<LineData>();
                LineData BodyInfo = new LineData();
                foreach (IssueData Info in infos)
                {
                    HeadInfo = new CreateMaterialINDocAPIModel();
                    HeadInfo.IssueType = 1;
                    HeadInfo.BusinessDate = DateTime.Now;
                    foreach (IssueLineData line in Info.details)
                    {
                        //根据传入行ID查询申请单行信息
                        string linesql = @"select ID,MOPick,SupplyWh,Project,LotMaster,ItemInfo from Issue_IssueApplyDocLine
                                           where ID='{0}'";
                        linesql = string.Format(linesql, line.SourceDetailID);
                        DataTable linedt = DBhlper.Query(linesql, connString);
                        if (linedt.Rows.Count == 0)
                        {
                            throw new Exception("传入领料申请单行的ID:" + line.SourceDetailID + "无法在U9查询到相关信息!");
                        }
                        else
                        {
                            //验证仓库是否启用批号管理
                            string whsql = @"select IsLot,Code from CBO_Wh
                                             where ID='{0}'";
                            whsql = string.Format(whsql, linedt.Rows[0]["SupplyWh"].ToString());
                            DataTable whdt = DBhlper.Query(whsql, connString);
                            long LotID = 0;
                            DataTable infodt = new DataTable();
                            if (whdt.Rows[0]["IsLot"].ToString().ToUpper() == "TRUE")
                            {
                                if (line.BatchCode != "")
                                {
                                    //批号ID获取
                                    string infosql = @"select ID from Lot_LotMaster
                                                   where LotCode='{0}' and Item='{1}'";
                                    infosql = string.Format(infosql, line.BatchCode, long.Parse(linedt.Rows[0]["ItemInfo"].ToString()));
                                    infodt = DBhlper.Query(infosql, connString);
                                    if (infodt.Rows.Count == 0)
                                    {
                                        //入库时如传入批号在U9不存在，需要先创建批号
                                        #region 创建批号接口调用
                                        string NewLotID = "";
                                        CustCreateLotMaster LotMasterCreate = new CustCreateLotMaster();
                                        string lotWHCode = whdt.Rows[0]["Code"].ToString();
                                        string lotItemCode = line.InvCode;
                                        string LotCode = line.BatchCode;
                                        LotMasterCreate.CustCreateRCVLotMaster(lotWHCode, lotItemCode, LotCode, OrgID, ref NewLotID);
                                        if (NewLotID != "")
                                        {
                                            LotID = long.Parse(NewLotID);
                                        }
                                        #endregion
                                    }
                                    else
                                    {
                                        LotID = long.Parse(infodt.Rows[0]["ID"].ToString());
                                    }
                                }
                                else
                                {
                                    throw new Exception("单据行维护仓库:" + whdt.Rows[0]["Code"].ToString() + "启用批号管控，传入批号不能为空!");
                                }
                            }
                            BodyInfo = new LineData();
                            BodyInfo.SourceDocType = 3;
                            BodyInfo.IssueApplyDocLine = new IssueApplyDocLine();
                            BodyInfo.IssueApplyDocLine.ID = long.Parse(line.SourceDetailID);
                            BodyInfo.Wh = new Wh();
                            BodyInfo.Wh.ID = long.Parse(linedt.Rows[0]["SupplyWh"].ToString());
                            BodyInfo.IssuedQty = line.Quantity;
                            if (LotID != 0)
                            {
                                BodyInfo.Lot = new Lot();
                                BodyInfo.Lot.ID = long.Parse(infodt.Rows[0]["ID"].ToString());
                                BodyInfo.Lot.Code = line.BatchCode;
                            }
                            BodyInfo.Item = new Item();
                            BodyInfo.Item.ID = long.Parse(linedt.Rows[0]["ItemInfo"].ToString());
                            BodyInfo.Item.Code = line.InvCode;
                            BodyList.Add(BodyInfo);
                        }
                    }
                    HeadInfo.MaterialDeliveryDocLines = BodyList;
                    HeadList.Add(HeadInfo);
                }
                string postJson = JsonConvert.SerializeObject(HeadList);
                APIreturnInfo value = new APIreturnInfo();
                value = PostJsonToMaterialIn(postJson, "admin", infos[0].WorkPoint);
                if (value.IsSuccess == true)
                {
                    DataSet ds = new DataSet();
                    rtninfo.DocNo = value.DocNo;
                    rtninfo.IsSuccess = true;
                    #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 Issue_MaterialDeliveryDoc a
                            WHERE a.DocNo='{0}' and a.Org='{1}'";
                    rtnsql = string.Format(rtnsql, value.DocNo, OrgID);
                    DataTable mdt = DBhlper.Query(rtnsql, connString);
                    ds.Tables.Add(mdt);
                    rtnsql = @" select DISTINCT a.ID as IDs,b.ID as DetailID,b.DocLineNo as Sequence,c.Code as InvCode 
							,b.IssuedQtyUOM 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,
                            '' as LogId
							from Issue_MaterialDeliveryDoc a
							left join Issue_MaterialDeliveryDocLine b on b.MaterialDeliveryDoc=a.ID
							left join CBO_ItemMaster c on c.ID=b.ItemInfo
							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.SupplyWh
							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='{0}' and a.Org='{1}'";
                    rtnsql = string.Format(rtnsql, value.DocNo, OrgID);
                    DataTable sdt = DBhlper.Query(rtnsql, connString);
                    ds.Tables.Add(sdt);
                    #endregion
                    rtninfo.Data = JSON.DataSetToJson(ds, "details", "IDs");
                }
                else
                {
                    throw new Exception(value.Message);
                }
                return rtninfo;
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
                throw new Exception(ex.Message);
            }
        }

        public static APIreturnInfo PostJsonToMaterialIn(string DataJson, string CreateByCode, string ORGCode)
        {
            APIreturnInfo valueRet = new APIreturnInfo();
            try
            {

                Appconfig.WriteLogFile("调用接口Json：" + DataJson, LogName);
                string TokenCode = GetToken(CreateByCode, ORGCode);
                if (!string.IsNullOrWhiteSpace(TokenCode))
                {
                    string U9IP = ConfigurationManager.AppSettings["U9IP"].ToString();
                    string CreateUrl = "http://{0}/u9c/webapi/MaterialDeliveryDoc/Create";
                    CreateUrl = string.Format(CreateUrl, U9IP);

                    string resultCreateSoFile = PostData.APT(CreateUrl, DataJson, TokenCode);

                    Appconfig.WriteLogFile("创建材料入库单返回Json：" + resultCreateSoFile, LogName);

                    JObject objuu = JObject.Parse(resultCreateSoFile);
                    bool IsSucess = false;
                    string DocNo = "";
                    long ID = -1;
                    string Message = "";
                    if (objuu["Success"] != null && objuu["Data"] != null && objuu["Success"].ToString().ToUpper() == "TRUE")
                    {
                        CreateMaterialINWebApiReturnModel RetModel = JsonConvert.DeserializeObject<CreateMaterialINWebApiReturnModel>(resultCreateSoFile);
                        if (RetModel.Success == true &&
                            RetModel.Data != null && RetModel.Data.Count > 0)
                        {
                            var IsTrues = RetModel.Data.Where(a => a.m_isSucess == false);
                            if (IsTrues != null && IsTrues.Count() > 0)
                            {

                                Message += RetModel.Data[0].m_errorMsg;
                            }
                            else
                            {

                                DocNo = RetModel.Data[0].m_code;
                                if (!string.IsNullOrEmpty(RetModel.Data[0].m_iD))
                                {
                                    ID = long.Parse(RetModel.Data[0].m_iD);
                                }
                                else
                                {
                                    ID = GetDocID(DocNo, ORGCode);
                                }
                                Message += "材料入库单：" + DocNo + "创建成功。";
                                #region 提交/审核材料出库单
                                List<OperateMaterialINModel> ListDoc = new List<OperateMaterialINModel>();
                                OperateMaterialINModel subm = new OperateMaterialINModel();
                                int Version = GetDocSysVersion(ID);
                                subm.ID = ID;
                                subm.DocNo = RetModel.Data[0].m_code;
                                subm.CurrentSysVersion = Version;
                                subm.isAutoApp = true;
                                ListDoc.Add(subm);
                                string postSubmitJson = JsonConvert.SerializeObject(ListDoc);

                                TokenCode = GetToken(CreateByCode, ORGCode);

                                string SubmitUrl = "http://{0}/u9c/webapi/MaterialDeliveryDoc/Approve";
                                SubmitUrl = string.Format(SubmitUrl, U9IP);
                                Appconfig.WriteLogFile("提交调用接口Json：" + postSubmitJson, LogName);
                                string resultSubmFile = PostData.APT(SubmitUrl, postSubmitJson, TokenCode);

                                Appconfig.WriteLogFile("提交材料入库单返回Json：" + resultSubmFile, LogName);

                                JObject objuu2 = JObject.Parse(resultSubmFile);


                                if (objuu2["Success"] != null && objuu2["Data"] != null && objuu2["Success"].ToString().ToUpper() == "TRUE")
                                {
                                    CreateMaterialINWebApiReturnModel RetModel2 = JsonConvert.DeserializeObject<CreateMaterialINWebApiReturnModel>(resultSubmFile);
                                    if (RetModel2.Success == true &&
                                        RetModel2.Data != null && RetModel2.Data.Count > 0)
                                    {
                                        var IsTrues2 = RetModel2.Data.Where(a => a.m_isSucess == false);
                                        if (IsTrues2 != null && IsTrues2.Count() > 0)
                                        {
                                            Message += RetModel2.Data[0].m_errorMsg;
                                        }
                                        else
                                        {

                                            #region 审核材料出库单
                                            List<OperateMaterialINModel> ListDoc3 = new List<OperateMaterialINModel>();
                                            OperateMaterialINModel Apprm = new OperateMaterialINModel();
                                            Version = GetDocSysVersion(ID);
                                            string Status = GetDocStatus(ID);
                                            if (Status == "1")
                                            {
                                                Apprm.ID = ID;
                                                Apprm.DocNo = RetModel.Data[0].m_code;
                                                Apprm.CurrentSysVersion = Version;
                                                Apprm.isAutoApp = true;
                                                ListDoc3.Add(Apprm);
                                                string postApproveJson = JsonConvert.SerializeObject(ListDoc3);

                                                TokenCode = GetToken(CreateByCode, ORGCode);

                                                string ApproveUrl = "http://{0}/u9c/webapi/MaterialDeliveryDoc/Approve";
                                                ApproveUrl = string.Format(ApproveUrl, U9IP);
                                                Appconfig.WriteLogFile("审核调用接口Json：" + postApproveJson, LogName);
                                                string resultappmFile = PostData.APT(ApproveUrl, postApproveJson, TokenCode);

                                                Appconfig.WriteLogFile("审核材料入库单返回Json：" + resultappmFile, LogName);

                                                JObject objuu3 = JObject.Parse(resultappmFile);


                                                if (objuu3["Success"] != null && objuu3["Data"] != null && objuu3["Success"].ToString().ToUpper() == "TRUE")
                                                {
                                                    CreateMaterialINWebApiReturnModel RetModel3 = JsonConvert.DeserializeObject<CreateMaterialINWebApiReturnModel>(resultappmFile);
                                                    if (RetModel3.Success == true &&
                                                        RetModel3.Data != null && RetModel3.Data.Count > 0)
                                                    {
                                                        var IsTrues3 = RetModel3.Data.Where(a => a.m_isSucess == false);
                                                        if (IsTrues3 != null && IsTrues3.Count() > 0)
                                                        {
                                                            Message += RetModel3.Data[0].m_errorMsg;
                                                        }
                                                        else
                                                        {

                                                            IsSucess = true;
                                                            Message += "审核材料入库单：" + DocNo + "成功。";
                                                        }
                                                    }
                                                }
                                                else
                                                {
                                                    Message += "审核材料入库单：" + DocNo + "失败：";
                                                    if (objuu3["Message"] != null && !string.IsNullOrEmpty(objuu3["Message"].ToString()))
                                                    {
                                                        Message += objuu3["Message"].ToString();
                                                    }
                                                    if (objuu3["ResMsg"] != null && !string.IsNullOrEmpty(objuu3["ResMsg"].ToString()))
                                                    {
                                                        Message += objuu3["ResMsg"].ToString();
                                                    }
                                                }
                                            }
                                            else
                                            {
                                                IsSucess = true;
                                                Message += "审核材料入库单：" + DocNo + "成功。";
                                            }
                                            #endregion
                                        }
                                    }
                                }
                                else
                                {
                                    Message += "提交材料入库单：" + DocNo + "失败：";
                                    if (objuu2["Message"] != null && !string.IsNullOrEmpty(objuu2["Message"].ToString()))
                                    {
                                        Message += objuu2["Message"].ToString();
                                    }
                                    if (objuu2["ResMsg"] != null && !string.IsNullOrEmpty(objuu2["ResMsg"].ToString()))
                                    {
                                        Message += objuu2["ResMsg"].ToString();
                                    }
                                }
                                #endregion

                                #region 没有成功 就删除
                                if (!IsSucess)
                                {
                                    List<OperateMaterialINModel> ListDoc4 = new List<OperateMaterialINModel>();
                                    OperateMaterialINModel delm = new OperateMaterialINModel();
                                    Version = GetDocSysVersion(ID);
                                    delm.ID = ID;
                                    delm.DocNo = RetModel.Data[0].m_code;
                                    delm.CurrentSysVersion = Version;
                                    delm.isAutoApp = true;
                                    ListDoc4.Add(delm);
                                    string postDelJson = JsonConvert.SerializeObject(ListDoc4);

                                    TokenCode = GetToken(CreateByCode, ORGCode);

                                    string DelUrl = "http://{0}/u9c/webapi/MaterialDeliveryDoc/Delete";
                                    DelUrl = string.Format(DelUrl, U9IP);
                                    Appconfig.WriteLogFile("删除调用接口Json：" + postDelJson, LogName);
                                    string resultDelFile = PostData.APT(DelUrl, postDelJson, TokenCode);

                                    Appconfig.WriteLogFile("删除材料入库单返回Json：" + resultDelFile, LogName);

                                    JObject objuu4 = JObject.Parse(resultDelFile);


                                    if (objuu4["Success"] != null && objuu4["Data"] != null && objuu4["Success"].ToString().ToUpper() == "TRUE")
                                    {
                                        CreateMaterialINWebApiReturnModel RetModel4 = JsonConvert.DeserializeObject<CreateMaterialINWebApiReturnModel>(resultDelFile);
                                        if (RetModel4.Success == true &&
                                            RetModel4.Data != null && RetModel4.Data.Count > 0)
                                        {
                                            var IsTrues4 = RetModel4.Data.Where(a => a.m_isSucess == false);
                                            if (IsTrues4 != null && IsTrues4.Count() > 0)
                                            {
                                                Message += RetModel4.Data[0].m_errorMsg;
                                            }
                                            else
                                            {
                                                Message += "删除材料入库单：" + DocNo + "成功";
                                            }
                                        }
                                    }
                                    else
                                    {
                                        Message += "删除材料入库单：" + DocNo + "失败：";
                                        if (objuu4["Message"] != null && !string.IsNullOrEmpty(objuu4["Message"].ToString()))
                                        {
                                            Message += objuu4["Message"].ToString();
                                        }
                                        if (objuu4["ResMsg"] != null && !string.IsNullOrEmpty(objuu4["ResMsg"].ToString()))
                                        {
                                            Message += objuu4["ResMsg"].ToString();
                                        }
                                    }
                                }

                                #endregion

                            }
                        }
                        else
                        {
                            Message += RetModel.ResMsg; ;
                        }


                    }
                    else
                    {
                        IsSucess = false;
                        string ErrorMessage = "";
                        if (objuu["Message"] != null && !string.IsNullOrEmpty(objuu["Message"].ToString()))
                        {
                            ErrorMessage += objuu["Message"].ToString();
                        }
                        if (objuu["ResMsg"] != null && !string.IsNullOrEmpty(objuu["ResMsg"].ToString()))
                        {
                            ErrorMessage += objuu["ResMsg"].ToString();
                        }
                        throw new Exception("调用OpenAPI创建材料入库单失败." + ErrorMessage);

                    }

                    valueRet.IsSuccess = IsSucess;
                    valueRet.DocNo = DocNo;
                    valueRet.Message = Message;
                }
                else
                {
                    throw new Exception("获取token值失败。");
                }

            }
            catch (Exception ex)
            {
                Appconfig.WriteLogFile("Error：" + ex.ToString(), LogName);
                valueRet.IsSuccess = false;
                valueRet.DocNo = "";
                valueRet.Message = ex.Message;

            }
            return valueRet;
        }

        public static string GetToken(string CreateByCode, string ORGCode)
        {
            Appconfig.WriteLogFile("调用接口CreateByCode：" + CreateByCode + ORGCode + ",ORGCode:" + ORGCode, LogName);

            if (ConfigurationManager.AppSettings["clientid"] == null || string.IsNullOrEmpty(ConfigurationManager.AppSettings["clientid"].ToString()))
            {
                throw new Exception("请联系管理员，未配置clientid。");
            }
            if (ConfigurationManager.AppSettings["clientsecret"] == null || string.IsNullOrEmpty(ConfigurationManager.AppSettings["clientsecret"].ToString()))
            {
                throw new Exception("请联系管理员，未配置clientsecret。");
            }
            if (ConfigurationManager.AppSettings["U9IP"] == null || string.IsNullOrEmpty(ConfigurationManager.AppSettings["U9IP"].ToString()))
            {
                throw new Exception("请联系管理员，未配置U9IP。");
            }
            if (ConfigurationManager.AppSettings["enterpriseID"] == null || string.IsNullOrEmpty(ConfigurationManager.AppSettings["enterpriseID"].ToString()))
            {
                throw new Exception("请联系管理员，未配置enterpriseID。");
            }

            string clientid = ConfigurationManager.AppSettings["clientid"].ToString();
            string clientsecret = ConfigurationManager.AppSettings["clientsecret"].ToString();
            string U9IP = ConfigurationManager.AppSettings["U9IP"].ToString();
            string enterpriseID = ConfigurationManager.AppSettings["enterpriseID"].ToString();
            DateTime dateTime = DateTime.Now;
            string url = "http://{2}/u9c/webapi/OAuth2/GetAuthorizeCode?clientid={0}&clientsecret={1}";
            url = string.Format(url, clientid, clientsecret, U9IP);
            string resultuu = PostData.GetInfo("", url);

            Appconfig.WriteLogFile("授权返回Json：" + resultuu, LogName);

            JObject objuu = new JObject();
            objuu = JObject.Parse(resultuu);

            string keyCode = objuu["Data"].ToString();
            if (!string.IsNullOrWhiteSpace(keyCode))
            {
                string ToeknUrl = "http://{4}/u9c/webapi/OAuth2/Login?userCode={0}&entcode={1}&orgcode={2}&code={3}";
                ToeknUrl = string.Format(ToeknUrl, CreateByCode, enterpriseID, ORGCode, keyCode, U9IP);
                string resultToken = PostData.GetInfo("", ToeknUrl);

                Appconfig.WriteLogFile("Token返回Json：" + resultToken, LogName);
                JObject objToken = new JObject();
                objuu = JObject.Parse(resultToken);
                string TokenCode = objuu["Data"].ToString();
                return TokenCode;
            }
            else
            {
                throw new Exception("获取token失败");
            }
        }

        # region 辅助方法


        /// <summary>
        /// 创建上下文
        /// </summary>
        /// <returns></returns>
        private static ThreadContext CreateContextObj(string OrgID, string UerID, string UserCode)
        {
            // 实例化应用上下文对象
            ThreadContext thContext = new ThreadContext();

            System.Collections.Generic.Dictionary<object, object> ns = new Dictionary<object, object>();
            ns.Add("OrgID", OrgID);
            ns.Add("UserID", UerID);
            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 string CheckERPDocKind(string DocID)
        {
            try
            {
                string str = "";
                //string OrgID = "";
                //string orgsql = @"select ID from Base_Organization
                //                  where Code='{0}'";
                //orgsql = string.Format(orgsql, OrgCode);
                //DataTable orgdt = DBhlper.Query(orgsql, Appconfig.GetU9ConnStr());
                //if (orgdt.Rows.Count != 0)
                //{
                //    OrgID = orgdt.Rows[0]["ID"].ToString();
                //}
                //else
                //{
                //    throw new Exception("传入组织编码错误!");
                //}
                string sqsql = @"select '领料申请单' AS Type from Issue_IssueApplyDocLine
                                 where id = '{0}'
                                 UNION ALL
                                 SELECT '生产订单备料' AS Type FROM MO_MOPickList
                                 WHERE id = '{0}'
                                ";
                sqsql = string.Format(sqsql, DocID);
                DataTable sqdt = DBhlper.Query(sqsql, Appconfig.GetU9ConnStr());
                if (sqdt.Rows.Count != 0)
                {
                    str = sqdt.Rows[0]["Type"].ToString();
                }
                else
                {
                    str = "生产领料单";
                }
                return str;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        public static long GetDocID(string DocNO, string OrgCode)
        {
            try
            {
                long ID = 0;
                string sqsql = @"select A.ID from Issue_IssueApplyDoc A
                                 LEFT JOIN Base_Organization B ON B.ID=A.Org
                                 where A.DocNo='{0}' AND B.Code='{1}'";
                sqsql = string.Format(sqsql, DocNO, OrgCode);
                DataTable sqdt = DBhlper.Query(sqsql, connString);
                if (sqdt.Rows.Count != 0)
                {
                    ID = long.Parse(sqdt.Rows[0]["ID"].ToString());
                }
                return ID;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        public static string GetDocStatus(long ID)
        {
            try
            {
                string Status = "";
                string sqsql = @"select DocState from Issue_IssueApplyDoc
                                  where ID='{0}'";
                sqsql = string.Format(sqsql, ID);
                DataTable sqdt = DBhlper.Query(sqsql, connString);
                if (sqdt.Rows.Count != 0)
                {
                    Status = sqdt.Rows[0]["DocState"].ToString();
                }
                return Status;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        public static int GetDocSysVersion(long ID)
        {
            try
            {
                int version = 0;
                string sqsql = @"select SysVersion from Issue_MaterialDeliveryDoc
                                  where ID='{0}'";
                sqsql = string.Format(sqsql, ID);
                DataTable sqdt = DBhlper.Query(sqsql, connString);
                if (sqdt.Rows.Count != 0)
                {
                    version = int.Parse(sqdt.Rows[0]["SysVersion"].ToString());
                }
                return version;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        public class IssueData
        {
            /// <summary>
            /// 领料单据类型    1--生产领料单 2--生产退料单
            /// </summary>
            public string DocTypeCode { get; set; }
            /// <summary>
            /// 领料单号
            /// </summary>
            public string SourceCode { get; set; }

            public string SourceType { get; set; }

            public string DocCode { get; set; }

            public string ID { get; set; }

            public string IssueNEGCode { get; set; }

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

            public string WorkPoint { get; set; }//组织编码

            public string User { get; set; }//业务员编码

            public bool IsSuccess { get; set; }

            public string Message { get; set; }

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


        public class IssueLineData
        {
            /// <summary>
            /// 领料单行ID
            /// </summary>
            public string SourceDetailID { get; set; }

            public string Sequence { get; set; }

            public string DetailID { get; set; }

            public string DocLineNo { get; set; }
            public string InvCode { get; set; }//子料号
            public Decimal Quantity { get; set; }//子料数量
            public int RecedeReason { get; set; }//退料理由
            public string WHCode { get; set; }//仓库
            public string BatchCode { get; set; }//批号

            public string LogIds { get; set; }
        }


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

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

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

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

        public class rtnMaterialInInfo
        {
            public string DocNo { get; set; }
            public bool IsSuccess { get; set; }
            public string Message { get; set; }
            public object Data { get; set; }
        }
        public class APIreturnInfo
        {
            public string DocNo { get; set; }
            public bool IsSuccess { get; set; }
            public string Message { get; set; }
        }
    }


}
