using ICSSoft.Common;
using ICSSoft.Entity;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ICSSoft.DataProject
{
    /// <summary>
    /// 材料出库 备料表，生产订单
    /// </summary>
   public  class MOIssueDoc
    {
        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 ERPDB = System.Configuration.ConfigurationManager.AppSettings["ERPDB"];
        private static string Type = System.Configuration.ConfigurationManager.AppSettings["Type"];
        public string Get(List<ICSRdrecord11> infos)
       {
           List<ICSRdrecord11> szJson = new List<ICSRdrecord11>();
           DataTable dt = null;
           string json = "";
           if (infos.Count <= 0)
           {
               throw new Exception("传送数据为空！");
           }
           string res = string.Empty;
           SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString);
           conn.Open();
           SqlTransaction sqlTran = conn.BeginTransaction();
           SqlCommand cmd = new SqlCommand();
           cmd.Transaction = sqlTran;
           cmd.Connection = conn;
           try
           {
               string sql = string.Empty;
               foreach (ICSRdrecord11 info in infos)
               {
                   if (info.MTime < new DateTime(2000, 01, 01))
                       throw new Exception("请输入正确的操作时间：" + info.MTime);
                   sql = @"  select a.ID,iMPoIds,iordercode,cCode,a.cDepCode,c.cDepName,a.cWhCode,d.cWhName,cSource,cMaker,dnmaketime,cHandler,dnverifytime,cSourceCodeLs,b.AutoID ,irowno,b.cInvCode,iQuantity,f.MoDId,iNum,g.MoCode from rdrecord11 a
                            left join rdrecords11 b on a.ID=b.ID
                            left join Department c on a.cDepCode=c.cDepCode
                            left join Warehouse d on a.cWhCode=d.cWhCode
                            left join mom_moallocate e on b.iMPoIds=e.AllocateId
                            INNER JOIN dbo.mom_orderdetail f ON e.MoDId=f.MoDId
                            INNER JOIN dbo.mom_order g ON f.MoId=g.MoId WHERE 1=1";
                   if (!string.IsNullOrWhiteSpace(info.IssueCode))
                   {
                       sql += " and a.cCode='{0}'";
                   }
                   if (!string.IsNullOrWhiteSpace(info.MTime.ToString()))
                   {
                       sql += " and ISNULL(a.dnmodifytime ,ISNULL(a.dnverifytime , ISNULL(a.dnmodifytime , a.dnmaketime)))>='{1}'";
                   }
                   if (!string.IsNullOrWhiteSpace(info.User))
                   {
                       sql += " and a.CMAKER='{2}'";
                   }
                   sql = string.Format(sql, info.IssueCode, info.MTime, info.User);
                   dt = DBHelper.SQlReturnData(sql, cmd);
                   json = JsonConvert.SerializeObject(dt);
               }
               cmd.Transaction.Commit();
               return json;
           }
           catch (Exception ex)
           {
               cmd.Transaction.Rollback();
               log.Error(ex.Message);
               throw new Exception(ex.Message);
           }
           finally
           {
               if (conn.State == ConnectionState.Open)
               {
                   conn.Close();
               }
               conn.Dispose();
           }
       }
        public string  CreateRd11(List<ICSRdrecord11> Bills)
       {
           string msg = "";
           DataTable dt = null;
           bool ResultFlag = false;
           SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString);
           conn.Open();
           VouchKey key = new VouchKey();
           int num = 0;
           int iFatherId = 0;
           string iFatherIdTwo = string.Empty;
           int iChildId = 0;
           string sql = string.Empty;
           SqlTransaction sqlTran = conn.BeginTransaction();
           SqlCommand cmd = new SqlCommand();
           cmd.Transaction = sqlTran;
           cmd.Connection = conn;
           cmd.CommandTimeout = 300;
           try
           {
               if (Bills.Count <= 0)
               {
                   throw new Exception("传送数据为空！");
               }
               LogInfo(Bills);
               //MergeObject(Bills, cmd);
               LogInfo(Bills);
               foreach (ICSRdrecord11 head in Bills)
               {
                       num = head.details.Count();
                   Dictionary<string, int> dic = DBHelper.GetAllCode("" + ERPDB + "", "rd", "" + num + "");
                   iFatherId = Convert.ToInt32(dic["iFatherId"].ToString());
                   iChildId = Convert.ToInt32(dic["iChildId"].ToString());
                   DateTime date = DateTime.Now;
                   string iBaseCodeLen = DBHelper.GetAllRDCode("26", "" + date + "", "admin");
                   string DEF_ID = DBHelper.GetDefaultTemplate(Type, cmd);
                   #region 判断工单是否已关闭
                   sql = @"SELECT isnull(CloseUser,'') as CloseUser from mom_orderdetail a 
                        inner join mom_order b on a.MoId=b.MoId where b.MoCode='" + head.SourceCode + "' ";
                   DataTable dtClose = DBHelper.SQlReturnData(sql, cmd);
                   if (dtClose != null && dtClose.Rows.Count > 0)
                   {
                       if (!string.IsNullOrEmpty(dtClose.Rows[0][0].ToString()))
                       {
                           throw new Exception("该工单行已关闭，无法领料！");
                       }
                   }
                   #endregion


                   #region 判断物料是否超额领取
//                   foreach (rdrecords11 body in head.details)
//                   {
//                       sql = @"SELECT isnull(b.fOutExcess,0) as fOutExcess,isnull(a.IssQty,0) as IssQty,a.Qty,a.ReplenishQty  FROM dbo.mom_moallocate a 
//                            LEFT JOIN dbo.Inventory b ON a.InvCode=b.cInvCode
//                            WHERE a.AllocateId='" + body.SourceDetailID + "'";
//                       DataTable dtQty = DBHelper.SQlReturnData(sql, cmd);
//                       if (dtQty != null && dtQty.Rows.Count > 0)
//                       {
//                           //可超领比率
//                           decimal fOutExcess = Convert.ToDecimal(dtQty.Rows[0]["fOutExcess"]);
//                           //已领数量
//                           decimal IssQty = Convert.ToDecimal(dtQty.Rows[0]["IssQty"]);
//                           //应领数量
//                           decimal Qty = Convert.ToDecimal(dtQty.Rows[0]["Qty"]);
//                           //当前可总领数量
//                           decimal TotalQty = Qty;// + fOutExcess * Qty;
//                           //补料数量
//                           decimal ReplenishQty = Convert.ToDecimal(dtQty.Rows[0]["ReplenishQty"]);
                       
//                               string cql = @"SELECT * from Inventory where cInvCode='" + body.InvCode + "'AND bKCCutMantissa =1 AND bCutMantissa=1";
//                               DataTable dtInv = DBHelper.SQlReturnData(cql, cmd);
//                               if (dtInv != null && dtInv.Rows.Count > 0)
//                               {
//                               }
//                               else
//                               {
//                                   if (IssQty - ReplenishQty + body.Quantity > TotalQty)
//                                   {
//                                       throw new Exception("物料领取超过当前可领用最大数，AllocateId：" + body.SourceDetailID);
//                                   }
//                               }
//                               //if (IssQty + body.iQuantity > TotalQty)
//                               //{
//                               //    throw new Exception("物料领取超过当前可领用最大数，AllocateId：" + body.AllocateId);
//                               //}
//                           }
//                       else
//                       {
//                           throw new Exception("工单行子件不存在！AllocateId：" + body.SourceDetailID);
//                       }
//                   }

                   #endregion
                

                   #region 材料出库单表头
                   sql = @"INSERT INTO dbo.rdrecord11
                            ( ID ,bRdFlag ,cVouchType ,cBusType ,cSource ,cWhCode ,dDate ,
                            cCode ,cRdCode ,cDepCode,cHandler ,bTransFlag ,cMaker ,
                            dVeriDate ,bpufirst ,biafirst ,VT_ID ,bIsSTQc 
                            ,cPsPcode ,cMPoCode ,iproorderid ,bFromPreYear ,
                            bIsLsQuery ,bIsComplement ,iDiscountTaxType ,ireturncount ,iverifystate ,
                            iswfcontrolled ,dnmaketime ,dnverifytime ,bredvouch ,iPrintCount,
                            iMQuantity)

                            SELECT @ID,0,'11','领料','生产订单',@cWhCode,CONVERT(NVARCHAR(15),GETDATE(),23),
                            @cCode,'23',a.MDeptCode,@cHandler,0,@cMaker,
                            CONVERT(NVARCHAR(15),GETDATE(),23),0,0,@VT_ID,0,
                            a.InvCode,b.MoCode,a.MoId,0,
                            0,0,0,0,0,
                            0,GETDATE(),GETDATE(),0,0,
                            a.Qty
                            FROM dbo.mom_orderdetail a
                            left JOIN dbo.mom_order b ON a.MoId=b.MoId 
                            left join mom_morder c on a.modid=c.modid
                            WHERE a.MoDId='" + head.MODetailID + "'";
                   cmd.Parameters.Clear();
                   cmd.Parameters.Add(new SqlParameter("@ID", iFatherId));
                   cmd.Parameters.Add(new SqlParameter("@cWhCode", head.WHCode));
                   cmd.Parameters.Add(new SqlParameter("@cCode", iBaseCodeLen));
                   cmd.Parameters.Add(new SqlParameter("@cHandler", head.User));
                   cmd.Parameters.Add(new SqlParameter("@cMaker", head.User));
                   cmd.Parameters.Add(new SqlParameter("@VT_ID", DEF_ID));
                  
                    cmd.CommandText = sql;
                    try
                    {
                        int count = cmd.ExecuteNonQuery();
                        if (count <= 0)
                        {
                            log.Error("生成材料出库单表头失败，受影响行数<=0；");
                            throw new Exception("生成材料出库单表头失败，受影响行数<=0；");
                        }
                    }
                    catch (Exception ex)
                    {
                        log.Error("生成材料出库单表头失败" + sql, ex);
                        throw new Exception("生成材料出库单表头失败" + sql, ex);
                    }
                   #endregion

                   #region 材料出库单表体
                   int irowno = 0;
                   foreach (rdrecords11 body in head.details)
                   {
                       //if (irowno == 0)
                       //{
                       //    iChildId = iChildId;
                       //}
                       //else
                       //{
                       //    iChildId -= 1;
                       //}
                       //irowno += 1;
                       
                       //if (head.IsReturn == "1")
                       //{
                       //    body.iQuantity = -body.iQuantity;
                       //}
                       //if (head.IsReturn == "0")
                       //{
                       //    //判断物料批号与现存量表批号是否一致、数量不能超过现存量物料数量
                       //    sql = @"SELECT cBatch,iQuantity from CurrentStock WHERE cInvCode='" + body.cInvCode + "'AND cBatch='" + body.cBatch + "'and cWhCode='" + head.cWhCode + "'";
                       //    DataTable dtItem = U8Helper.SQlReturnData(sql, cmd);
                       //    if (dtItem != null && dtItem.Rows.Count > 0)
                       //    {
                       //        if (!dtItem.Rows[0]["cBatch"].ToString().Equals(body.cBatch))
                       //        {
                       //            throw new Exception("物料条码的批号与U8现存量物料批号不一致,物料:" + body.cInvCode);
                       //        }
                       //        if (Convert.ToDecimal(dtItem.Rows[0]["iQuantity"].ToString()) < body.iQuantity)
                       //        {
                       //            throw new Exception("物料条码的数量大于U8现存量物料数量,物料:" + body.cInvCode);
                       //        }

                       //    }
                       //    else
                       //    {
                       //        throw new Exception("物料:" + body.cInvCode + "在现存量表中不存在!");
                       //    }
                       //}
                       sql = @"INSERT INTO dbo.rdrecords11
                                    ( AutoID ,ID ,cInvCode ,iQuantity ,cBatch ,iFlag ,
                                        cItemCode ,cName ,iNQuantity ,iMPoIds ,bLPUseFree ,
                                        iOriTrackID ,bCosting ,bVMIUsed ,cmocode ,invcode ,imoseq ,
                                        iopseq ,iExpiratDateCalcu ,iorderdid ,iordertype ,isotype ,
                                        ipesodid ,ipesotype ,cpesocode ,ipesoseq ,irowno ,
                                        bcanreplace ,iposflag)
                            SELECT @AutoID,@ID,a.InvCode,@iQuantity,@cBatch,0,
                                	null,null,a.Qty,a.AllocateId,0,
                                	0,1,0,c.MoCode,b.InvCode,b.SortSeq,
                                	'0000',0,0,0,0,
                                	a.AllocateId,'7',c.MoCode,b.SortSeq,@irowno,
                                    0,null
                            FROM dbo.mom_moallocate a
                            INNER JOIN dbo.mom_orderdetail b ON a.MoDId=b.MoDId
                            INNER JOIN dbo.mom_order c ON b.MoId=c.MoId
                            WHERE a.AllocateId='" + body.SourceDetailID + "'";
                       cmd.Parameters.Clear();

                     cmd.Parameters.Add(new SqlParameter("@AutoID", iChildId));
                     cmd.Parameters.Add(new SqlParameter("@iQuantity",body.Quantity));
                     //cmd.Parameters.Add(new SqlParameter("@cBatch", "''"));
                   cmd.Parameters.Add(new SqlParameter("@ID", iFatherId));
                   cmd.Parameters.Add(new SqlParameter("@cCode", iBaseCodeLen));
                   cmd.Parameters.Add(new SqlParameter("@cBatch",""));
                   cmd.Parameters.Add(new SqlParameter("@irowno", body.Sequence));
                  
                    cmd.CommandText = sql;
                    try
                    {
                        int count = cmd.ExecuteNonQuery();
                        if (count <= 0)
                        {
                            log.Error("生成材料出库单表体失败，受影响行数<=0；");
                            throw new Exception("生成材料出库单表体失败，受影响行数<=0；");
                        }
                    }
                    catch (Exception ex)
                    {
                        log.Error("生成材料出库单表体失败"+ sql, ex);
                        throw new Exception("生成材料出库单表体失败 "+ sql, ex);
                    }
                       //更新现存量
                       key.cBustypeUN = "领料";
                       key.cVouchTypeUN = "11";
                       key.TableName = "IA_ST_UnAccountVouch11";
                       DBHelper.UpdateCurrentStock(cmd, body.InvCode, head.WHCode, "", body.Quantity, key);

                       #region 回写工单子件已领数量
                       sql = "update mom_moallocate set IssQty=isnull(IssQty,0)+" + body.Quantity + " where AllocateId='" + body.SourceDetailID + "' ";
                       DBHelper.CmdExecuteNonQuery(sql, cmd, "回写工单子件已领数量失败！");
                       #endregion
                       
                       iChildId--;
            
                   }
                   #endregion
                   iFatherIdTwo += "'" + iFatherId + "',";
               }
               #region 查询
               sql = @"  
                            select a.ID as ID,a.ID as IDs,cMPoCode as SourceCode ,
                           cCode as IssueCode,a.cDepCode,c.cDepName,a.cWhCode,d.cWhName,
                            cSource as SourceType,cMaker as CreateUser,dnmaketime as CreateDateTime,
                            cHandler as Checker,dnverifytime as CheckDateTime
                            from rdrecord11 a
                            left join Department c on a.cDepCode=c.cDepCode
                            left join Warehouse d on a.cWhCode=d.cWhCode
                            WHERE a.ID in ({0})

                           select a.ID as IDs,b.AutoID as DetailID,irowno as Sequence,b.cInvCode as InvCode 
                           ,iQuantity as Quantity,e.AllocateId as SourceDetailID,iNum as Amount
                            from rdrecord11 a
                            left join rdrecords11 b on a.ID=b.ID
                            left join Department c on a.cDepCode=c.cDepCode
                            left join Warehouse d on a.cWhCode=d.cWhCode
                            left join mom_moallocate e on b.iMPoIds=e.AllocateId
                            INNER JOIN dbo.mom_orderdetail f ON e.MoDId=f.MoDId
                            INNER JOIN dbo.mom_order g ON f.MoId=g.MoId WHERE a.ID in ({0})";
               sql = string.Format(sql, iFatherIdTwo.TrimEnd(','));
               DataSet ds = DBHelper.SQlReturnDataSet(sql, cmd);
               string RelationName = "details";
               DataRelation dr = new DataRelation(RelationName, ds.Tables[0].Columns["IDs"], ds.Tables[1].Columns["IDs"]);
               ds.Relations.Add(dr);
               msg = DBHelper.DataSetToJson(ds, RelationName);
               cmd.Transaction.Commit();
               return msg;
               #endregion
           }
           
           catch (Exception ex)
           {
               cmd.Transaction.Rollback();
               log.Error(ex.Message);
               throw new Exception(ex.Message);
           }
           finally
           {
               if (conn.State == ConnectionState.Open)
               {
                   conn.Close();
               }
               conn.Dispose();
           }
       }
        public string  MaterialAppVouchs(List<ICSRdrecord11> Bills)
        {
            string msg = "";
            string sql = string.Empty;
            string iFatherIdTwo = string.Empty;
            SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString);
            conn.Open();
            SqlTransaction sqlTran = conn.BeginTransaction();
            SqlCommand cmd = new SqlCommand();
            cmd.Transaction = sqlTran;
            cmd.Connection = conn;
            int num = 0;
            foreach (ICSRdrecord11 head in Bills)
            {
                num = head.details.Count();
            }
            try
            {
                if (Bills.Count <= 0)
                {
                    throw new Exception("传送数据为空！");
                }
                LogInfo(Bills);
                //MergeObject(Bills, cmd);
                foreach (ICSRdrecord11 head in Bills)
                {


                    #region 判断物料是否超额领取
                    foreach (rdrecords11 body in head.details)
                    {
                        sql = @"SELECT isnull(fOutQuantity,0) as fOutQuantity,iQuantity FROM dbo.MaterialAppVouchs WHERE AutoID='" + body.SourceDetailID + "'";
                        DataTable dtQty = DBHelper.SQlReturnData(sql, cmd);
                        if (dtQty != null && dtQty.Rows.Count > 0)
                        {
                            //已领数量
                            decimal IssQty = Convert.ToDecimal(dtQty.Rows[0]["fOutQuantity"]);
                            //应领数量
                            decimal Qty = Convert.ToDecimal(dtQty.Rows[0]["iQuantity"]);
                            if (IssQty + body.Quantity > Qty)
                            {
                                throw new Exception("物料领取超过当前可领用最大数，AutoID：" + body.SourceDetailID);
                            }
                        }
                        else
                        {
                            throw new Exception("领料申请单不存在！AutoID：" + body.SourceDetailID);
                        }
                    }
                    #endregion

                    #region 现存量是否够领
//                    //if (head.IsReturn != "1")
//                    //{
//                        foreach (rdrecords11 body in head.rdcords)
//                        {
//                            sql = string.Format(@"SELECT iQuantity FROM dbo.CurrentStock 
//                                                WHERE cInvCode='{0}' AND cWhCode='{1}'", body.cInvCode, head.cWhCode);
//                            if (!string.IsNullOrWhiteSpace(body.cBatch))
//                                sql += " and cBatch='" + body.cBatch + "'";
//                            DataTable dt = DBHelper.SQlReturnData(sql, cmd);
//                            decimal qtyCurrent = 0;
//                            if (dt != null && dt.Rows.Count > 0)
//                            {
//                                qtyCurrent = Convert.ToDecimal(dt.Rows[0][0]);
//                                if (qtyCurrent < body.Quantity)
//                                {
//                                    throw new Exception("物料编号：" + body.cInvCode + "，现存量不足！");
//                                }
//                            }
//                            else
//                            {
//                                throw new Exception("该物料：" + body.cInvCode + "在U8中仓库：" + head.cWhCode + "中不存在！");
//                            }
//                        }
//                    //}

                   #endregion

                    #region 材料出库单表头
                    //取得out库单的默认显示模版
                    Dictionary<string, int> dic = DBHelper.GetAllCode("" + ERPDB + "", "rd", "" + num + "");
                    int iFatherId = Convert.ToInt32(dic["iFatherId"].ToString());
                    int iChildId = Convert.ToInt32(dic["iChildId"].ToString());
                    DateTime date = DateTime.Now;
                    string iBaseCodeLen = DBHelper.GetAllRDCode("26", "" + date + "", "admin");
                    string DEF_ID = DBHelper.GetDefaultTemplate(Type, cmd);
                    //取得采购入库单单据 表头ID，表体DID
                    VouchKey key = new VouchKey();
                 
                    sql = @"INSERT INTO dbo.rdrecord11
                                    ( ID ,bRdFlag ,cVouchType ,cBusType ,cSource ,cBusCode ,cWhCode ,
                                      dDate ,cCode ,cRdCode ,cDepCode ,cPersonCode ,cHandler ,cMemo ,
                                      bTransFlag ,cMaker ,cDefine1 ,cDefine2 ,cDefine3 ,cDefine4 ,
                                      cDefine5 ,cDefine6 ,cDefine7 ,cDefine8 ,cDefine9 ,cDefine10 ,
                                      dVeriDate ,bpufirst ,biafirst ,VT_ID ,bIsSTQc ,cDefine11 ,
                                      cDefine12 ,cDefine13 ,cDefine14 ,cDefine15 ,cDefine16 ,
                                      bOMFirst ,bFromPreYear ,bIsComplement ,iDiscountTaxType ,
                                      ireturncount ,iverifystate ,iswfcontrolled ,cModifyPerson ,
                                      dnmaketime ,dnverifytime ,bredvouch ,bmotran ,bHYVouch ,iPrintCount 
                                    )
                            SELECT @ID,0,'11','领料','领料申请单',a.cCode,@cWhCode,
                            		CONVERT(NVARCHAR(15),GETDATE(),23),@cCode,a.cRdCode,a.cDepCode,a.cPersonCode,@cHandler,a.cMemo,
                            		0,@cMaker,a.cDefine1,cdefine2,a.cDefine3,a.cDefine4,
                            		a.cDefine5,a.cDefine6,a.cDefine7,a.cDefine8,a.cDefine9,a.cDefine10,
                            		CONVERT(NVARCHAR(15),GETDATE(),23),0,0,@VT_ID,0,a.cDefine11,
                            		a.cDefine12,a.cDefine13,a.cDefine14,a.cDefine15,a.cDefine16,
                            		0,0,0,0,
                            		0,0,0,'',
                            		GETDATE(),GETDATE(),0,0,0,0
                            FROM dbo.MaterialAppVouch a WHERE a.cCode='" + head.SourceCode + "'";
                    cmd.Parameters.Clear();
                    cmd.Parameters.Add(new SqlParameter("@ID", iFatherId));
                    cmd.Parameters.Add(new SqlParameter("@cWhCode", head.WHCode));
                    cmd.Parameters.Add(new SqlParameter("@cCode", iBaseCodeLen));
                    cmd.Parameters.Add(new SqlParameter("@cHandler", head.User));
                    cmd.Parameters.Add(new SqlParameter("@cMaker", head.User));
                    cmd.Parameters.Add(new SqlParameter("@VT_ID", DEF_ID));
                    //DBHelper.CmdExecuteNonQuery(sql, cmd, "生成材料出库单表头失败！");
                    cmd.CommandText = sql;
                    try
                    {
                        int count = cmd.ExecuteNonQuery();
                        if (count <= 0)
                        {
                            log.Error("生成材料出库单表头失败，受影响行数<=0；");
                            throw new Exception("生成材料出库单表头失败，受影响行数<=0；");
                        }
                    }
                    catch (Exception ex)
                    {
                        log.Error("生成材料出库单表头失败！SQL：\r\n" + sql, ex);
                        throw new Exception("生成材料出库单表头失败！SQL：\r\n" + sql, ex);
                    }
                    #endregion

                    #region 材料出库单表体
                    int irowno = 0;
                    foreach (rdrecords11 body in head.details)
                    {
                        //if (head.IsReturn == "1")
                        //{
                            body.Quantity = -body.Quantity;
                        //}
                        //判断物料批号与现存量表批号是否一致and数量不能超过现存量物料数量
                       sql = @"SELECT cBatch,iQuantity from CurrentStock WHERE cInvCode='" + body.InvCode + "'AND cBatch=''and cWhCode='" + head.WHCode + "' ";
                        DataTable dtItem = DBHelper.SQlReturnData(sql, cmd);
                        if (dtItem != null && dtItem.Rows.Count > 0)
                        {
                            //if (!dtItem.Rows[0]["cBatch"].ToString().Equals(body.cBatch))
                            //{
                            //    throw new Exception("物料条码的批号与U8现存量物料批号不一致,物料:" + body.InvCode);
                            //}
                            if (Convert.ToDecimal(dtItem.Rows[0]["iQuantity"].ToString()) < body.Quantity)
                            {
                                throw new Exception("物料条码的数量大于U8现存量物料数量,物料:" + body.InvCode);
                            }
                            sql = @"INSERT INTO dbo.rdrecords11
                                        ( AutoID ,ID ,cInvCode ,iQuantity ,iFlag ,cDefine22 ,
                                          cDefine23 ,cDefine24 ,cDefine25 ,cDefine26 ,cDefine27 ,
                                          cItem_class ,cItemCode ,cName ,cItemCName ,iNQuantity ,
                                          cDefine28 ,cDefine29 ,cDefine30 ,cDefine31 ,cDefine32 ,
                                          cDefine33 ,cDefine34 ,cDefine35 ,cDefine36 ,cDefine37 ,
                                          bLPUseFree ,iOriTrackID ,bCosting ,bVMIUsed ,iMaIDs ,
                                          iExpiratDateCalcu ,iordertype ,isotype ,ipesotype ,irowno,
                                          cBatch)
                                SELECT @AutoID,@ID,a.cInvCode,@iQuantity,0,a.cDefine22,
                                		a.cDefine23,a.cDefine24,a.cDefine25,a.cDefine26,a.cDefine27,
                                		a.cItem_class,a.cItemCode,a.cName,a.cItemCName,a.iQuantity,
                                		a.cDefine28,a.cDefine29,a.cDefine30,a.cDefine31,a.cDefine32,
                                		a.cDefine33,a.cDefine34,a.cDefine35,a.cDefine36,a.cDefine37,
                                		0,0,1,0,a.AutoID,
                                		0,0,0,0,@irowno,
                                        @cBatch
                                FROM dbo.MaterialAppVouchs a WHERE a.AutoID='" + body.SourceDetailID + "'";
                            cmd.Parameters.Clear();
                            cmd.Parameters.Add(new SqlParameter("@ID", iFatherId));
                            cmd.Parameters.Add(new SqlParameter("@AutoID", iChildId));
                            cmd.Parameters.Add(new SqlParameter("@iQuantity",body.Quantity));
                            cmd.Parameters.Add(new SqlParameter("@irowno", body.Sequence));
                            cmd.Parameters.Add(new SqlParameter("@cBatch", ""));
                            //DBHelper.CmdExecuteNonQuery(sql, cmd, "生成材料出库单表头失败！");
                            cmd.CommandText = sql;
                        //    SqlParameter[] paramBody = {
                        //    new SqlParameter("@AutoID",DbType.String),
                        //    new SqlParameter("@ID",DbType.String),
                        //    new SqlParameter("@iQuantity",DbType.Decimal),
                        //    new SqlParameter("@irowno",DbType.String),
                        //    new SqlParameter("@cBatch",DbType.String)
                        //};
                            //paramBody[0].Value = key.DID;
                            //paramBody[1].Value = key.ID;
                            //paramBody[2].Value = body.Quantity;
                            //paramBody[3].Value = irowno;
                           // paramBody[4].Value = body.cBatch;
                            try
                            {
                                int count = cmd.ExecuteNonQuery();
                                if (count <= 0)
                                {
                                    log.Error("生成材料出库单表体失败，受影响行数<=0；");
                                    throw new Exception("生成材料出库单表体失败，受影响行数<=0；");
                                }
                            }
                            catch (Exception ex)
                            {
                                log.Error("生成材料出库单表体失败！SQL：\r\n" + sql, ex);
                                throw new Exception("生成材料出库单表体失败！SQL：\r\n" + sql, ex);
                            }
                            //更新现存量
                            key.cBustypeUN = "领料";
                            key.cVouchTypeUN = "11";
                            key.TableName = "IA_ST_UnAccountVouch11";
                            DBHelper.UpdateCurrentStock(cmd, body.InvCode, head.WHCode,"", -body.Quantity, key);

                            #region 回写领料申请单已领数量
                            sql = "UPDATE dbo.MaterialAppVouchs SET fOutQuantity=ISNULL(fOutQuantity,0)+" + body.Quantity + " WHERE AutoID='" + body.SourceDetailID + "'";
                            DBHelper.CmdExecuteNonQuery(sql, cmd, "回写领料申请单已领数量失败！");
                            #endregion
                        }
                        else
                        {
                            throw new Exception("物料:" + body.InvCode + "在现存量表中不存在!");
                        }
                        iChildId--;
                    }
                    #endregion
                    iFatherIdTwo += "'" + iFatherId + "',";
                    //DBHelper.UpdateIDandDID("rd", ErpName, head.list.Count(), cmd);
                }
                #region 查询
                sql = @"  
                            select a.ID as ID,a.ID as IDs,cMPoCode as SourceCode ,
                           cCode as IssueCode,a.cDepCode,c.cDepName,a.cWhCode,d.cWhName,
                            cSource as SourceType,cMaker as CreateUser,dnmaketime as CreateDateTime,
                            cHandler as Checker,dnverifytime as CheckDateTime
                            from rdrecord11 a
                            left join Department c on a.cDepCode=c.cDepCode
                            left join Warehouse d on a.cWhCode=d.cWhCode
                            WHERE a.ID in ({0})

                           select a.ID as IDs,b.AutoID as DetailID,irowno as Sequence,b.cInvCode as InvCode 
                           ,iQuantity as Quantity,b.iMaIDs as SourceDetailID,iNum as Amount
                            from rdrecord11 a
                            left join rdrecords11 b on a.ID=b.ID
                            left join Department c on a.cDepCode=c.cDepCode
                            left join Warehouse d on a.cWhCode=d.cWhCode
                             WHERE a.ID in ({0})";
                sql = string.Format(sql, iFatherIdTwo.TrimEnd(','));
                DataSet ds = DBHelper.SQlReturnDataSet(sql, cmd);
                string RelationName = "details";
                DataRelation dr = new DataRelation(RelationName, ds.Tables[0].Columns["IDs"], ds.Tables[1].Columns["IDs"]);
                ds.Relations.Add(dr);
                msg = DBHelper.DataSetToJson(ds, RelationName);
                cmd.Transaction.Commit();
                //return msg;
                #endregion
              
            }
            catch (Exception ex)
            {
                cmd.Transaction.Rollback();
                log.Error(ex.Message);
                throw new Exception(ex.Message);
            }
            finally
            {
                if (conn.State == ConnectionState.Open)
                {
                    conn.Close();
                }
                conn.Dispose();
            }
            return msg;
        }
       /// <summary>
       /// 审核材料出库单据
       /// </summary>
       /// <param name="infos"></param>
       /// <returns></returns>
        public string Approve(List<ICSRdrecord11> infos)
        {
            List<ICSRdrecord11> szJson = new List<ICSRdrecord11>();
            DataTable dt = null;
            string json = "";
            if (infos.Count <= 0)
            {
                throw new Exception("传送数据为空！");
            }
            string res = string.Empty;
            SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString);
            conn.Open();
            SqlTransaction sqlTran = conn.BeginTransaction();
            SqlCommand cmd = new SqlCommand();
            cmd.Transaction = sqlTran;
            cmd.Connection = conn;
            try
            {
                string sql = string.Empty;
                foreach (ICSRdrecord11 info in infos)
                {
                    if (info.MTime < new DateTime(2000, 01, 01))
                        throw new Exception("请输入正确的操作时间：" + info.MTime);
                    sql = @"UPDATE dbo.rdrecord11  SET cHandler='" + info.User + @"' ,
                            dVeriDate=CONVERT(VARCHAR(50),GETDATE(),112),dnverifytime=GETDATE() 
                            WHERE  ID='" + info.ID + "'";
                     DBHelper.CmdExecuteNonQuery(sql, cmd, "审核材料出库单失败！");
                }
                cmd.Transaction.Commit();
                return json;
            }
            catch (Exception ex)
            {
                cmd.Transaction.Rollback();
                log.Error(ex.Message);
                throw new Exception(ex.Message);
            }
            finally
            {
                if (conn.State == ConnectionState.Open)
                {
                    conn.Close();
                }
                conn.Dispose();
            }
        }
        /// <summary>
        /// 审核材料出库单据
        /// </summary>
        /// <param name="infos"></param>
        /// <returns></returns>
        public string Delete(List<ICSRdrecord11> infos)
        {
            List<ICSRdrecord11> szJson = new List<ICSRdrecord11>();
            DataTable dt = null;
            string json = "";
            if (infos.Count <= 0)
            {
                throw new Exception("传送数据为空！");
            }
            string res = string.Empty;
            SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString);
            conn.Open();
            SqlTransaction sqlTran = conn.BeginTransaction();
            SqlCommand cmd = new SqlCommand();
            cmd.Transaction = sqlTran;
            cmd.Connection = conn;
            try
            {
                string sql = string.Empty;
                foreach (ICSRdrecord11 info in infos)
                {
                    if (info.MTime < new DateTime(2000, 01, 01))
                        throw new Exception("请输入正确的操作时间：" + info.MTime);
                    sql = @"delete  rdrecord11  where  rdrecord11.ID='" + info.ID + "'";
                    sql += @"delete  rdrecords11  where  rdrecords11.ID='" + info.ID + "'";
//UPDATE dbo.rdrecord11 a SET cHandler='" + info.User + @"' ,
//                            dVeriDate=CONVERT(VARCHAR(50),GETDATE(),112),dnverifytime=GETDATE() 
//                            WHERE a.ID='" + info.ID + "'";
                    DBHelper.CmdExecuteNonQuery(sql, cmd, "删除材料出库单失败！");
                }
                cmd.Transaction.Commit();
                return json;
            }
            catch (Exception ex)
            {
                cmd.Transaction.Rollback();
                log.Error(ex.Message);
                throw new Exception(ex.Message);
            }
            finally
            {
                if (conn.State == ConnectionState.Open)
                {
                    conn.Close();
                }
                conn.Dispose();
            }
        }
       /// <summary>
       /// 记录日志
       /// </summary>
       /// <param name="Bills"></param>
       private void LogInfo(List<ICSRdrecord11> Bills)
       {
           string HeadList = string.Empty;
           string BodyList = string.Empty;
           foreach (ICSRdrecord11 head in Bills)
           {
               HeadList += "\r\n 表头主键ID：" + head.ID + "，仓库：" + head.WHCode + "，用户：" + head.User;
               foreach (rdrecords11 body in head.details)
               {
                   BodyList += "\r\n 表体主键ID： " + body.SourceDetailID + "，数量：" + body.Quantity;
               }
           }
           log.Info(HeadList);
           log.Info(BodyList);
       }

       /// <summary>
       /// 表体合并
       /// </summary>
       /// <param name="Bills"></param>
       //private void MergeObject(List<ICSRdrecord11> Bills, SqlCommand cmd)
       //{
       //    foreach (ICSRdrecord11 head in Bills)
       //    {
       //        DataTable dt = DBHelper.ToDataTable(head.details.ToList());
       //        DataTable dtNew = dt.Clone();
       //        dtNew = DBHelper.MergeDataTable(dt, "AllocateId", "cBatch", "iQuantity", "cInvCode", cmd);
       //        List<rdrecords11> list = DBHelper.ConvertTo<rdrecords11>(dtNew).ToList();
       //        head.details = list;
       //    }
       //}
    }
}
