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
{
  public   class CreateRdRecord01
    {
        private static log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        private static string connString = System.Configuration.ConfigurationManager.AppSettings["ConnStr"];
        private static string ERPDB = System.Configuration.ConfigurationManager.AppSettings["ERPDB"];
      /// <summary>
      /// 获取采购入库单
      /// </summary>
      /// <param name="infos">传入参数</param>
      /// <returns></returns>
      public string Get(List<ICSRdRecord01> infos)
      {
          List<ICSRdRecord01> szJson = new List<ICSRdRecord01>();
          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 (ICSRdRecord01 info in infos)
              {
                  if (info.MTime < new DateTime(2000, 01, 01))
                      throw new Exception("请输入正确的操作时间：" + info.MTime);
                  sql = @"select top 10 a.ID,cCode,cVenCode,''as cVenName,cWhCode,''as cWhName,cARVCode,cMaker,dnmaketime,cHandler,dVeriDate,
                            AutoID,irowno,cInvCode,iQuantity,iNum,iUnitCost,iArrsId
                            FROM  [{1}].DBO.RdRecord01 a 
                            LEFT JOIN [{1}].DBO.rdrecords01 b on a.ID=b.ID
                            INNER JOIN [{1}].DBO.DEPARTMENT C ON A.CDEPCODE=C.CDEPCODE
                            INNER JOIN [{1}].DBO.VENDOR D ON A.CVENCODE=D.CVENCODE WHERE 1=1";
                  if (!string.IsNullOrWhiteSpace(info.RCVTCode))
                  {
                      sql += " and a.cCode='{0}'";
                  }
                  if (!string.IsNullOrWhiteSpace(info.MTime.ToString()))
                  {
                      sql += " and ISNULL(b.cbCloseTime,ISNULL(a.cChangAuditTime,ISNULL(a.cAuditTime, ISNULL(a.cModifyTime, a.cmaketime))))>='{2}'";
                  }
                  if (!string.IsNullOrWhiteSpace(info.User))
                  {
                      sql += "and a.CMAKER='{3}'";
                  }
                  sql = string.Format(sql, info.RCVTCode, ERPDB, 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();
          }
      }
       ///<summary>
       //创建采购入库单
       ///</summary>
       ///<param name="Bills"></param>
       ///<returns></returns>
      public List<ICSRdRecord01> CreateRdRecord01s(List<ICSRdRecord01> Bills)
      {
          List<ICSRdRecord01> szJson = new List<ICSRdRecord01>();
          DataTable dt = null;
          decimal iTaxRate = 0;
           Dictionary<string, int> dic = DBHelper.GetAllCode("", "", "");
            int iFatherId = Convert.ToInt32(dic["iFatherId"].ToString());
            int iChildId = Convert.ToInt32(dic["iChildId"].ToString());
            DateTime dates = DateTime.Now;
            string iBaseCodeLen = DBHelper.GetAllRDCode("", "", 1, "");
            VouchKey key = new VouchKey();
          string json = "";
          if (Bills.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;
           foreach (ICSRdRecord01 head in Bills)
                {
                    if (head.MTime < new DateTime(2000, 01, 01))
                      throw new Exception("请输入正确的操作时间：" + head.MTime);
                    string sql = "";
                        #region 验证入库数量不能大于采购订单数量
                      foreach (ICSRdRecord01s body in head.Record01s)
                            {
                                sql = @"SELECT a.iQuantity,a.ID,isnull(a.iReceivedQTY,0) as iReceivedQTY,isnull(a.freceivedqty,0) as freceivedqty,ISNULL(c.fInExcess,0) AS fInExcess  
                                        FROM dbo.PO_Podetails   a 
                                        INNER JOIN dbo.PO_Pomain b ON a.POID=b.POID
                                        LEFT JOIN dbo.Inventory c ON a.cInvCode=c.cInvCode
                                        where a.ID='" + head.ID + "'";
                                cmd.CommandText = sql;
                                DataTable dtQty = DBHelper.SQlReturnData(sql, cmd);
                                if (dtQty != null && dtQty.Rows.Count > 0)
                                {
                                    decimal fInExcess = decimal.Parse(dtQty.Rows[0]["fInExcess"].ToString());//入库超额上限
                                    decimal PoQty = decimal.Parse(dtQty.Rows[0]["iQuantity"].ToString());
                                    decimal iReceicedQty = decimal.Parse(dtQty.Rows[0]["iReceivedQTY"].ToString());//累计到货数量 
                                    decimal freceivedqty = decimal.Parse(dtQty.Rows[0]["freceivedqty"].ToString());//合格品入库数量 
                                    PoQty = PoQty * (1 + fInExcess);
                                    log.Info("PO数量:" + PoQty.ToString()+ "入库超额上限:" + fInExcess.ToString() + ",累计到货数量:" + iReceicedQty.ToString() + ",合格品入库数量:" + freceivedqty.ToString());
                                    //2021-11-05  回写字段变更,见行408
                                    //decimal to = PoQty - iReceicedQty - freceivedqty;
                                    decimal to = PoQty - freceivedqty;
                                    if (body.Quantity > to)
                                    {
                                        throw new Exception("入库数量" + body.Quantity.ToString("f3") + "大于采购订单可入库数量" + to.ToString("f3") 
                                           );
                                    }
                                }
                            }
                        
                        #endregion
                      #region 采购入库单表头
                      string BusType = "";//业务类型
                      sql = @"select a.POID,a.cPOID,a.cVenCode,a.cDepCode,a.cexch_name,a.iTaxRate,a.cMaker,
                                a.nflat,a.cPersonCode,a.cptcode ,b.ID,b.cCode,a.cBusType
                                FROM dbo.PO_Pomain a
                                LEFT JOIN PU_ArrivalVouch b ON a.cPOID=b.cpocode
                                WHERE a.POID ='" + head.ID + "'";
                      cmd.CommandText = sql;
                      DataTable dtPOMain = DBHelper.SQlReturnData(sql, cmd);
                      if (dtPOMain != null && dtPOMain.Rows.Count > 0)
                      {
                          string cSource="";
                          string cCode="";
                          int bredvouch = 0;
                          string cRdCode="";
                          string WHCode="";
                          BusType = dtPOMain.Rows[0]["cBusType"].ToString();
                             //校验采购订单类型是固定资产仓库
                          if (BusType.Equals("固定资产"))
                          {
                              string sqlwh = @"SELECT bWhAsset FROM Warehouse WHERE cWhCode='" + head.WHCode + "'";
                              cmd.CommandText = sqlwh;
                              DataTable dtwhcode = DBHelper.SQlReturnData(sqlwh, cmd);
                              log.Info(dtwhcode.Rows[0]["bWhAsset"].ToString());
                              if (!dtwhcode.Rows[0]["bWhAsset"].ToString().Equals("True"))
                              {
                                  throw new Exception("采购订单:" + dtPOMain.Rows[0]["cPOID"].ToString() + ",业务类型:固定资产,只能入固定资产仓库!");
                              }
                              else
                              {
                                  WHCode = head.WHCode;
                              }
                          }
                          else
                          {
                             WHCode = head.WHCode;
                          }
                        
                              cSource = "采购到货单";
                              cCode = dtPOMain.Rows[0]["cCode"].ToString();
                              bredvouch = 0;
                       
                              cRdCode = "200";
               
                              sql = @"
                                INSERT INTO dbo.RdRecord01
                                (ID ,bRdFlag ,cVouchType ,cBusType ,cSource ,
                                cWhCode ,dDate ,cCode ,cRdCode ,cDepCode ,
                                cPersonCode ,cVenCode ,cOrderCode ,cARVCode,
                                cHandler ,bTransFlag ,cMaker,cDefine1,cDefine2,
                                dVeriDate ,bpufirst ,biafirst , dARVDate ,VT_ID ,
                                bIsSTQc ,ipurorderid ,iTaxRate ,iExchRate ,cExch_Name ,
                                bOMFirst ,bFromPreYear ,bIsComplement ,iDiscountTaxType ,ireturncount ,
                                iverifystate ,iswfcontrolled ,cModifyPerson ,dnmaketime ,dnverifytime ,
                                bredvouch ,bCredit ,iPrintCount,ipurarriveid,cPTCode,cVenPUOMProtocol)

                                SELECT 
                                @ID,1,'01',a.cBusType,@cSource,
                                @cWhCode,@dDate,@cCode,@cRdCode,@cDepCode,
                                @cPersonCode,a.cVenCode,a.cPOID,@cARVCode,
                                @cHandler,0,@cMaker,a.cDefine1,a.cDefine2,
                                @cVeriDate,0,0,@dARVDate,@VT_ID,
                                0,@ipurorderid,a.iTaxRate,a.nflat,a.cexch_name,
                                0,0,0,0,0,
                                0,0,'',@dnmakertime,@dnverifytime,
                                @bredvouch,0,0,@ipurarriveid,a.cPTCode,a.cPayCode
                                FROM dbo.PO_Pomain a 
                                WHERE a.POID='" + head.ID + "'";
                          cmd.Parameters.Clear();
                          cmd.Parameters.Add(new SqlParameter("@ID",iFatherId));
                           cmd.Parameters.Add(new SqlParameter("@cSource",cSource));
                           cmd.Parameters.Add(new SqlParameter("@cWhCode",iFatherId));
                          cmd.Parameters.Add(new SqlParameter("@dDate",Convert.ToDateTime(DateTime.Now).ToString("yyyy -MM-dd")));
                           cmd.Parameters.Add(new SqlParameter("@cCode",head.RCVTCode));
                           cmd.Parameters.Add(new SqlParameter("@cDepCode",dtPOMain.Rows[0]["cDepCode"].ToString()));
                           cmd.Parameters.Add(new SqlParameter("@cPersonCode",dtPOMain.Rows[0]["cPersonCode"].ToString()));
                           cmd.Parameters.Add(new SqlParameter("@cARVCode",cCode));
                           cmd.Parameters.Add(new SqlParameter("@cMaker",head.User));
                           cmd.Parameters.Add(new SqlParameter("@cVeriDate",Convert.ToDateTime(DateTime.Now).ToString("yyyy-MM-dd")));
                           cmd.Parameters.Add(new SqlParameter("@dARVDate",Convert.ToDateTime(head.MTime)));
                           cmd.Parameters.Add(new SqlParameter("@VT_ID",iChildId));
                           cmd.Parameters.Add(new SqlParameter("@ipurorderid",dtPOMain.Rows[0]["POID"].ToString()));
                           cmd.Parameters.Add(new SqlParameter("@dnmakertime",Convert.ToDateTime(DateTime.Now).ToString()));
                           cmd.Parameters.Add(new SqlParameter("@dnverifytime",Convert.ToDateTime(DateTime.Now).ToString()));
                           cmd.Parameters.Add(new SqlParameter("@bredvouch",bredvouch));
                           cmd.Parameters.Add(new SqlParameter("@ipurarriveid",dtPOMain.Rows[0]["ID"].ToString()));
                           cmd.Parameters.Add(new SqlParameter("@cHandler",head.User));
                           cmd.Parameters.Add(new SqlParameter("@cRdCode",iFatherId));
                            ;
                       
                        cmd.CommandText = sql;
                    try
                    {
                        int count = cmd.ExecuteNonQuery();
                        if (count <= 0)
                        {
                            log.Error("生成采购入库单表头失败，受影响行数<=0；");
                            throw new Exception("生成采购入库单表头失败，受影响行数<=0；");
                        }
                    }
                    catch (Exception ex)
                    {
                        log.Error("生成采购入库单表头失败！异常：" + ex.Message + "；SQL：\r\n" + sql, ex);
                        throw new Exception("生成采购入库单表头失败！异常：" + ex.Message + "；SQL：\r\n" + sql, ex);
                    }
                      }
     
                      else
                      {
                          throw new Exception("对应采购订单不存在！采购订单号：" + dtPOMain.Rows[0]["cPOID"].ToString());
                      }
                      #endregion

                      #region 采购入库单表体
                      int irowno = 0;
                      foreach (ICSRdRecord01s body in head.Record01s)
                      {
                          irowno += 1;
                          iChildId -= 1;
                          //if (head.IsReturn == "1")
                          //{
                          //    body.iQuantity = -body.iQuantity;
                          //}
                          sql = @"SELECT a.id,a.cInvCode,a.iUnitPrice ,a.iMoney AS 原币无税金额 ,a.ivouchrowno,
                                    a.iTax AS 原币税额 ,a.iSum AS 原币价税合计 ,a.iNatUnitPrice ,
                                    a.iNatMoney AS 本币无税金额 ,a.iNatTax AS 本币税额 ,a.iNatSum AS 本币价税合计 ,
                                    a.iTaxPrice ,a.freceivedqty AS 合格品入库数量  ,a.iPerTaxRate,c.Autoid,d.cCode,d.dDate
                                    FROM  dbo.PO_Podetails  a 
                                    INNER JOIN dbo.PO_Pomain b ON a.POID=b.POID 
                                    LEFT JOIN dbo.PU_ArrivalVouchs c ON a.ID=c.iPOsID
                                    LEFT JOIN dbo.PU_ArrivalVouch d ON c.ID=d.ID
                                    where  a.ID='" + body.DNDetailID + "'";
                          cmd.CommandText = sql;
                          DataTable dtPODetails = DBHelper.SQlReturnData(sql, cmd);
                          decimal iUnitPrice = 0;
                          decimal iNatUnitPrice = 0;
                          decimal iTaxPrice = 0;
                          string id = "";
                          string code = "";
                          string date = "";

                          if (dtPODetails != null && dtPODetails.Rows.Count > 0)
                          {
                              if (!string.IsNullOrEmpty(dtPODetails.Rows[0]["iUnitPrice"].ToString()))
                                  iUnitPrice = decimal.Parse(dtPODetails.Rows[0]["iUnitPrice"].ToString());//原币无税单价
                              if (!string.IsNullOrEmpty(dtPODetails.Rows[0]["iNatUnitPrice"].ToString()))
                                  iNatUnitPrice = decimal.Parse(dtPODetails.Rows[0]["iNatUnitPrice"].ToString());//本币无税单价
                              if (!string.IsNullOrEmpty(dtPODetails.Rows[0]["iTaxPrice"].ToString()))
                                  iTaxPrice = decimal.Parse(dtPODetails.Rows[0]["iTaxPrice"].ToString());//原币含税单价
                                  iTaxRate = Convert.ToDecimal(dtPODetails.Rows[0]["iPerTaxRate"]);
                              if (!string.IsNullOrEmpty(dtPODetails.Rows[0]["Autoid"].ToString()))//采购退货单字体标识
                                  id = dtPODetails.Rows[0]["Autoid"].ToString();
                              if (!string.IsNullOrEmpty(dtPODetails.Rows[0]["cCode"].ToString()))//采购退货单号
                                  code = dtPODetails.Rows[0]["cCode"].ToString();
                              if (!string.IsNullOrEmpty(dtPODetails.Rows[0]["dDate"].ToString()))//采购退货单日期
                                  date = dtPODetails.Rows[0]["dDate"].ToString();

                              //sql = @"INSERT INTO dbo.rdrecords01
                              //        ( AutoID ,ID ,cInvCode ,iNum ,iQuantity ,
                              //        iUnitCost ,iPrice ,iAPrice ,cBatch ,iFlag ,
                              //        dSDate ,iSQuantity ,iSNum ,iMoney ,iPOsID ,
                              //        fACost ,iNQuantity ,chVencode ,iOriTaxCost ,iOriCost ,
                              //        iOriMoney ,iOriTaxPrice ,ioriSum ,iTaxRate ,iTaxPrice ,
                              //        iSum ,bTaxCost ,cPOID ,iMatSettleState ,iBillSettleCount ,
                              //        bLPUseFree ,iOriTrackID ,cbaccounter ,dbKeepDate ,bCosting ,
                              //        iSumBillQuantity ,bVMIUsed ,iExpiratDateCalcu ,isotype ,irowno,
                              //        iArrsId,cbarvcode,dbarvdate
                              //        )

                              //        select 
                              //        @AutoID,@ID,@cInvCode,0,@iQuantity,
                              //        @iUnitCost,@iPrice,@iAPrice,@cBatch,0,
                              //        null,0,0,0,a.ID,
                              //        @fACost,@iNQuantity,b.cVenCode,@iOriTaxCost,@iOriCost,
                              //        @iOriMoney,@iOriTaxPrice,@ioriSum,@iTaxRate,@iTaxPrice,
                              //        @iSum,1,@cPOID,0,0,
                              //        0,0,null,null,c.bInCost,
                              //        null,0,0,0,@irowno,
                              //        @iArrsId,@cbarvcode,@dbarvdate
                              //        FROM dbo.PO_Podetails  a 
                              //        INNER JOIN dbo.PO_Pomain b ON a.POID=b.POID  
                              //        INNER JOIN dbo.Warehouse c ON c.cWhCode='" + head.cWhCode + "' where a.ID='" + body.iPOsID + "'";
                              sql = @"INSERT INTO dbo.rdrecords01
                                                        ( 
                                                        AutoID ,ID ,cInvCode ,iNum ,iQuantity ,
                                                        iUnitCost ,iPrice ,iAPrice ,cBatch ,iFlag ,
                                                        dSDate ,iSQuantity ,iSNum ,iMoney ,iPOsID ,
                                                        fACost ,iNQuantity ,chVencode ,iOriTaxCost ,iOriCost ,
                                                        iOriMoney ,iOriTaxPrice ,ioriSum ,iTaxRate ,iTaxPrice ,
                                                        iSum ,bTaxCost ,cPOID ,iMatSettleState ,iBillSettleCount ,
                                                        bLPUseFree ,iOriTrackID ,cbaccounter ,dbKeepDate ,bCosting ,
                                                        iSumBillQuantity ,bVMIUsed ,iExpiratDateCalcu ,isotype ,irowno,
                                                        iArrsId,cbarvcode,dbarvdate
                                                        )

                                                        select 
                                                        @AutoID,@ID,@cInvCode,0,@iQuantity,
                                                        @iUnitCost,@iPrice,@iAPrice,@cBatch,0,
                                                        null,0,0,0,a.ID,
                                                        @fACost,@iNQuantity,b.cVenCode,@iOriTaxCost,@iOriCost,
                                                        @iOriMoney,@iOriTaxPrice,@ioriSum,@iTaxRate,@iTaxPrice,
                                                        @iSum,1,@cPOID,0,0,
                                                        0,0,null,null,d.bInCost,
                                                        null,0,0,0,@irowno,
                                                        @iArrsId,@cbarvcode,@dbarvdate
                                            FROM dbo.PO_Podetails a
                                            INNER JOIN dbo.PO_Pomain b ON a.POID = b.POID
                                            INNER JOIN dbo.PU_ArrivalVouchs c ON a.ID = c.iPOsID
                                            INNER JOIN dbo.Warehouse d ON d.cWhCode = '{0}'
                                            WHERE c.Autoid = '{1}'
                                    ";
                              sql = string.Format(sql, head.WHCode, body.DNDetailID);
                              cmd.Parameters.Clear();
                              cmd.Parameters.Add(new SqlParameter("@AutoID", iFatherId));
                              cmd.Parameters.Add(new SqlParameter("@ID", iChildId));
                              cmd.Parameters.Add(new SqlParameter("@cInvCode", body.InvCode));
                              cmd.Parameters.Add(new SqlParameter("@iQuantity", body.Quantity));
                              cmd.Parameters.Add(new SqlParameter("@iUnitCost", iUnitPrice));
                              cmd.Parameters.Add(new SqlParameter("@iPrice", Math.Round(body.Quantity * iUnitPrice, 2)));
                              cmd.Parameters.Add(new SqlParameter("@iAPrice", Math.Round(body.Quantity * iUnitPrice, 2)));
                              cmd.Parameters.Add(new SqlParameter("@cBatch", ""));
                              cmd.Parameters.Add(new SqlParameter("@iSQuantity", 0));
                              cmd.Parameters.Add(new SqlParameter("@iMoney", 0));
                              cmd.Parameters.Add(new SqlParameter("@fACost", iNatUnitPrice));
                              cmd.Parameters.Add(new SqlParameter("@iNQuantity", body.Quantity));
                              cmd.Parameters.Add(new SqlParameter("@iOriTaxCost", iTaxPrice));
                              cmd.Parameters.Add(new SqlParameter("@iOriMoney", iUnitPrice));
                              cmd.Parameters.Add(new SqlParameter("@iOriTaxPrice", Math.Round(body.Quantity * iUnitPrice, 2)));
                              cmd.Parameters.Add(new SqlParameter("@ioriSum", Math.Round(Math.Round(iTaxPrice * body.Quantity, 2) - Math.Round(body.Quantity * iUnitPrice, 2), 2)));
                              cmd.Parameters.Add(new SqlParameter("@iTaxRate", Math.Round(iTaxPrice * body.Quantity, 2)));
                              cmd.Parameters.Add(new SqlParameter("@iTaxPrice", iTaxRate));
                              cmd.Parameters.Add(new SqlParameter("@iSum", Math.Round(Math.Round(iTaxPrice * body.Quantity, 2) - Math.Round(body.Quantity * iUnitPrice, 2), 2)));
                              cmd.Parameters.Add(new SqlParameter("@irowno", Math.Round(iTaxPrice * body.Quantity, 2)));
                              cmd.Parameters.Add(new SqlParameter("@cPOID", int.Parse(dtPODetails.Rows[0]["ivouchrowno"].ToString())));
                              cmd.Parameters.Add(new SqlParameter("@iArrsId", id));
                                cmd.Parameters.Add(new SqlParameter("@cbarvcode", code));
                                cmd.Parameters.Add(new SqlParameter("@dbarvdate", Convert.ToDateTime(date)));


                                cmd.CommandText = sql;
                                try
                                {
                                    int count = cmd.ExecuteNonQuery();
                                    if (count <= 0)
                                    {
                                        log.Error("生成采购入库单表体失败，受影响行数<=0；");
                                        throw new Exception("生成采购入库单表体失败，受影响行数<=0；");
                                    }
                                }
                                catch (Exception ex)
                                {
                                    log.Error("生成采购入库单表体失败！异常：" + ex.Message + "；SQL：\r\n" + sql, ex);
                                    throw new Exception("生成采购入库单表体失败！异常：" + ex.Message + "；SQL：\r\n" + sql, ex);
                                }

                              #region  更新[采购到货单子表]PU_ArrivalVouchs 合格品入库数量20211019
                              sql = @"UPDATE PU_ArrivalVouchs SET fValidInQuan=ISNULL(fValidInQuan,0)+@iQty WHERE Autoid=@Autoid";
                              cmd.CommandText = sql;
                              cmd.Parameters.Clear();
                              cmd.Parameters.Add(new SqlParameter("@iQty", body.Quantity));
                              cmd.Parameters.Add(new SqlParameter("@Autoid", body.DNDetailID));
                              try
                              {
                                  log.Info("PU_Autoid:" + body.DNDetailID);
                                  cmd.ExecuteNonQuery();
                              }
                              catch (Exception ex)
                              {
                                  log.Error("回写采购到货单子表合格品入库数量失败：Autoid：" + body.DNDetailID + ";异常：" + ex.Message);
                                  throw new Exception("程序异常，请联系开发人员！");
                              }
                              #endregion

                              #region 更新[采购订单子表]PO_PODetails累计到货数量和累计到货金额
                              //sql = @"Update a set iReceivedQTY =isnull(iReceivedQTY ,0)+ @iQty,iReceivedMoney=isnull(iReceivedMoney,0)+@iMoney FROM  dbo.PO_Podetails  a   where a.ID='" + body.iPOsID + "'";
                              sql = @"
                                    Update a set 
	                                    iReceivedMoney=isnull(iReceivedMoney,0)+@iMoney 
	                                    ,freceivedqty=isnull(freceivedqty ,0)+ @iQty
                                    FROM  dbo.PO_Podetails  a   where a.ID=@ID"
                                  ;
                              //2021-11-05
                              //1.移除 iReceivedQTY =isnull(iReceivedQTY ,0)+ @iQty  由采购到货,创建到货单CreatePU时写入iReceivedQTY,此处不再回写,累计到货数量 
                              //2.加入 freceivedqty   =isnull(freceivedqty ,0) + @iQty  合格品入库数量 
                              cmd.CommandText = sql;
                              cmd.Parameters.Clear();
                              cmd.Parameters.Add(new SqlParameter("@iQty", body.Quantity));
                              cmd.Parameters.Add(new SqlParameter("@iMoney", body.Quantity * iUnitPrice));
                              cmd.Parameters.Add(new SqlParameter("@ID", body.DNDetailID));
                              try
                              {
                                  log.Info("iPOsID:" + body.DNDetailID);
                                  cmd.ExecuteNonQuery();
                              }
                              catch (Exception ex)
                              {
                                  log.Error("回写采购订单累计到货数量和累计到货金额失败：采购订单表体行号：" + body.DNDetailID + ";异常：" + ex.Message);
                                  throw new Exception("程序异常，请联系开发人员！");
                              }
                              #endregion

                              //更新现存量
                              key.cBustypeUN = "普通采购";
                              key.cVouchTypeUN = "01";
                              key.TableName = "IA_ST_UnAccountVouch01";

                              DBHelper.UpdateCurrentStock(cmd, body.InvCode, head.WHCode, body.InvCode, body.Quantity, key);
                          }
                          ////更新主键ID，DID
                          //DBHelper.UpdateIDandDID("rd", head.list.Count(), cmd);
                      }
                      #endregion

                      #region 判断现存量是否超入库
                        sql = @"IF EXISTS(SELECT ID FROM dbo.PO_Podetails WHERE isnull(ireceivedqty,0)+isnull(freceivedqty,0)>iQuantity AND ID>'1000043932')
                            BEGIN
	                            DECLARE @MSG NVARCHAR(100)
	                            SELECT @MSG='ERP入库数量不能大于订单数量！ID：'+CAST(ID AS NVARCHAR(100)) FROM dbo.PO_Podetails WHERE isnull(ireceivedqty,0)+isnull(freceivedqty,0)>iQuantity AND ID>'1000043932'
 	                            RAISERROR(@MSG,16,1)
                            END";

                        cmd.CommandText = sql;
                        cmd.ExecuteNonQuery();
                        #endregion
                    }
           return szJson;
      }
      /// <summary>
      /// 审核采购入库单
      /// </summary>
      /// <param name="infos"></param>
      /// <returns></returns>
      public string Approve(List<ICSRdRecord01> infos)
      {
          List<ICSRdRecord01> szJson = new List<ICSRdRecord01>();
          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 (ICSRdRecord01 info in infos)
              {
                  if (info.MTime < new DateTime(2000, 01, 01))
                      throw new Exception("请输入正确的操作时间：" + info.MTime);
                  sql = @"UPDATE [{0}].dbo.RdRecord01 SET cVerifier ='" + info.User + @"' ,
                            cAuditTime=CONVERT(VARCHAR(50),GETDATE(),112),cAuditDate=GETDATE() WHERE ID='" + info.ID + "'";
                  sql = string.Format(sql, ERPDB);
                  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<ICSRdRecord01> infos)
      {
          List<ICSRdRecord01> szJson = new List<ICSRdRecord01>();
          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 (ICSRdRecord01 info in infos)
              {
                  if (info.MTime < new DateTime(2000, 01, 01))
                      throw new Exception("请输入正确的操作时间：" + info.MTime);
                  sql = @" DELETE [{1}].dbo.RdRecord01 WHERE ID={0}";
                  sql = string.Format(sql, info.ID, ERPDB);
                  DBHelper.CmdExecuteNonQuery(sql, cmd, "未查询到对应数据！");
              }
              cmd.Transaction.Commit();
              return res;
              ;
          }
          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();
          }
      }
    }
  
}
