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 PurchaseReceiveDoctNegative
    {
        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"];
        /// <summary>
        /// 获取采购入库单(红字)
        /// </summary>
        /// <param name="infos">传入参数</param>
        /// <returns></returns>
        public string Get(List<ICSPurchaseReceiveDoc> infos)
        {
            List<ICSPurchaseReceiveDoc> szJson = new List<ICSPurchaseReceiveDoc>();
            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 (ICSPurchaseReceiveDoc info in infos)
                {
                    if (info.MTime < new DateTime(2000, 01, 01))
                        throw new Exception("请输入正确的操作时间:" + info.MTime);
                    sql = @"select  a.ID,a.cCode,a.cVenCode,''as cVenName,cWhCode,''as cWhName,cARVCode,cMaker,dnmaketime,cHandler,dVeriDate,
                            AutoID,irowno,cInvCode,iQuantity,iNum,iUnitCost,iArrsId
                            FROM  RdRecord01 a 
                            LEFT JOIN rdrecords01 b on a.ID=b.ID
                            INNER JOIN DEPARTMENT C ON A.CDEPCODE=C.CDEPCODE
                            INNER JOIN VENDOR D ON A.CVENCODE=D.CVENCODE WHERE 1=1 and iQuantity<0";
                    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 string CreatePurchaseReceiveDoctNegative(List<ICSPurchaseReceiveDoc> Bills)
        {
           string szJson = "";
           string sql = "";
           int iFatherId=0;
           int iChildId=0;
           string iFatherIdTwo = "";
           DateTime time = DateTime.Now;
           int num = 0;
            DataTable dt = null;
            decimal iTaxRate = 0;
            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 (ICSPurchaseReceiveDoc 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 dates = DateTime.Now;
                string iBaseCodeLen = DBHelper.GetAllRDCode("24", "" + time + "", "admin");
                string cRDcode = DBHelper.GetRDCode("采购入库", cmd);
                string DEF_ID08 = DBHelper.GetDefaultTemplate("24", cmd);
                if (head.MTime < new DateTime(2000, 01, 01))
                    throw new Exception("请输入正确的操作时间:" + head.MTime);
              
                #region 验证入库数量不能大于采购订单数量
//                foreach (ICSPurchaseReceiveDocs body in head.details)
//                {
//                    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 b.POID,b.cPOID,a.cVenCode,a.cDepCode,a.cexch_name,a.iTaxRate,a.cMaker,a.cpocode,
                                b.nflat,a.cPersonCode,a.cptcode ,a.ID,a.cCode,a.cBusType
                                FROM  PU_ArrivalVouch a
                                LEFT JOIN PO_Pomain b ON b.cPOID=a.cpocode
                                WHERE a.cCode ='" + head.DNRTCode + "'";
                cmd.CommandText = sql;
                DataTable dtPOMain = DBHelper.SQlReturnData(sql, cmd);
                if (dtPOMain != null && dtPOMain.Rows.Count > 0)
                {
                    string cSource = "";
                    string cCode = "";
                    int bredvouch = 0;
                    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 = 1;

                    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',b.cBusType,@cSource,
                                @cWhCode,@dDate,@cCode,@cRdCode,@cDepCode,
                                @cPersonCode,b.cVenCode,b.cPOID,@cARVCode,
                                @cHandler,0,@cMaker,b.cDefine1,b.cDefine2,
                                @cVeriDate,0,0,@dARVDate,@VT_ID,
                                0,@ipurorderid,b.iTaxRate,b.nflat,b.cexch_name,
                                0,0,0,0,0,
                                0,0,'',@dnmakertime,@dnverifytime,
                                @bredvouch,0,0,@ipurarriveid,b.cPTCode,b.cPayCode
                                FROM  PU_ArrivalVouch a
                                LEFT JOIN PO_Pomain b ON b.cPOID=a.cpocode
                                WHERE a.cCode ='" + head.DNRTCode + "'";
                    cmd.Parameters.Clear();
                    cmd.Parameters.Add(new SqlParameter("@ID", iFatherId));
                    cmd.Parameters.Add(new SqlParameter("@cSource", cSource));
                    cmd.Parameters.Add(new SqlParameter("@cWhCode", head.WHCode));
                    cmd.Parameters.Add(new SqlParameter("@dDate", Convert.ToDateTime(DateTime.Now).ToString("yyyy -MM-dd")));
                    cmd.Parameters.Add(new SqlParameter("@cCode", iBaseCodeLen));
                    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", DEF_ID08));
                    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", cRDcode));
                    ;

                    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 采购入库单表体
                foreach (ICSPurchaseReceiveDocs body in head.details)
                {
                    sql = @"SELECT c.id,c.cInvCode,c.iUnitPrice ,c.iMoney AS 原币无税金额 ,c.ivouchrowno,
                                    c.iTax AS 原币税额 ,c.iSum AS 原币价税合计 ,c.iNatUnitPrice ,
                                    c.iNatMoney AS 本币无税金额 ,c.iNatTax AS 本币税额 ,c.iNatSum AS 本币价税合计 ,
                                    c.iTaxPrice ,c.freceivedqty AS 合格品入库数量  ,c.iPerTaxRate,b.Autoid,a.cCode,a.dDate
									 FROM  dbo.PU_ArrivalVouch a 
									LEFT JOIN dbo.PU_ArrivalVouchs b ON a.ID=b.ID
                                    LEFT JOIN  dbo.PO_Podetails  c ON  b.iPOsID=c.ID 
                                    left JOIN dbo.PO_Pomain d ON c.POID=d.POID 
                                    where  b.AutoID='" + body.DNRTDetailID + "'";
                    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());//原币含税单价
                        if (!string.IsNullOrEmpty(dtPODetails.Rows[0]["iPerTaxRate"].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,b.ID,
                                                        @fACost,@iNQuantity,c.cVenCode,@iOriTaxCost,@iOriCost,
                                                        @iOriMoney,@iOriTaxPrice,@ioriSum,@iTaxRate,@iTaxPrice,
                                                        @iSum,1,c.cPOID,0,0,
                                                        0,0,null,null,d.bInCost,
                                                        null,0,0,0,@irowno,
                                                        @iArrsId,@cbarvcode,@dbarvdate
                                             FROM dbo.PU_ArrivalVouchs a
											left JOIN dbo.PO_Podetails b ON a.iPOsID = b.ID
                                            left JOIN dbo.PO_Pomain c ON b.POID = c.POID
                                            left JOIN dbo.Warehouse d ON d.cWhCode ='{0}'
                                            WHERE a.Autoid = '{1}'";
                        sql = string.Format(sql, head.WHCode, body.DNRTDetailID);
                        cmd.Parameters.Clear();
                        cmd.Parameters.Add(new SqlParameter("@AutoID", iChildId));
                        cmd.Parameters.Add(new SqlParameter("@ID", iFatherId));
                        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", iUnitPrice));
                        cmd.Parameters.Add(new SqlParameter("@iOriCost", iTaxPrice));
                        cmd.Parameters.Add(new SqlParameter("@iOriMoney", Math.Round(body.Quantity * iUnitPrice, 2)));
                        cmd.Parameters.Add(new SqlParameter("@iOriTaxPrice", Math.Round(Math.Round(iTaxPrice * body.Quantity, 2) - Math.Round(body.Quantity * iUnitPrice, 2), 2)));
                        cmd.Parameters.Add(new SqlParameter("@ioriSum", Math.Round(iTaxPrice * body.Quantity, 2)));
                        cmd.Parameters.Add(new SqlParameter("@iTaxRate", iTaxRate));
                        cmd.Parameters.Add(new SqlParameter("@iTaxPrice", Math.Round(Math.Round(iTaxPrice * body.Quantity, 2) - Math.Round(body.Quantity * iUnitPrice, 2), 2)));
                        cmd.Parameters.Add(new SqlParameter("@iSum", Math.Round(iTaxPrice * body.Quantity, 2)));
                        cmd.Parameters.Add(new SqlParameter("@irowno", body.Sequence));
                        //cmd.Parameters.Add(new SqlParameter("@cPOID", head.POCode));
                        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.DNRTDetailID));
                        try
                        {
                            log.Info("PU_Autoid:" + body.DNRTDetailID);
                            cmd.ExecuteNonQuery();
                        }
                        catch (Exception ex)
                        {
                            log.Error("回写采购到货单子表合格品入库数量失败:Autoid:" + body.DNRTDetailID + ";异常:" + 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.DNRTDetailID));
                        try
                        {
                            log.Info("iPOsID:" + body.DNRTDetailID);
                            cmd.ExecuteNonQuery();
                        }
                        catch (Exception ex)
                        {
                            log.Error("回写采购订单累计到货数量和累计到货金额失败:采购订单表体行号:" + body.DNDetailID + ";异常:" + ex.Message);
                            throw new Exception("程序异常,请联系开发人员!");
                        }
                        #endregion

                        #region 判断现存量是否超入库
                        sql = @"IF EXISTS(SELECT ID FROM dbo.PO_Podetails WHERE isnull(freceivedqty,0)>iQuantity AND ID={0})
                            BEGIN
	                            DECLARE @MSG NVARCHAR(100)
	                            SELECT @MSG='ERP入库数量不能大于订单数量!ID:'+CAST(ID AS NVARCHAR(100)) FROM dbo.PO_Podetails WHERE isnull(freceivedqty,0)>iQuantity AND ID={0}
 	                            RAISERROR(@MSG,16,1)
                            END";
                        sql = string.Format(sql, body.DNRTDetailID);
                        cmd.CommandText = sql;
                        cmd.ExecuteNonQuery();
                       
                        #endregion
                        //更新现存量
                        key.cBustypeUN = "普通采购";
                        key.cVouchTypeUN = "01";
                        key.TableName = "IA_ST_UnAccountVouch01";

                        DBHelper.UpdateCurrentStock(cmd, body.InvCode, head.WHCode, body.InvCode, -body.Quantity, key);
                    }
                    iChildId--;
                    ////更新主键ID,DID
                    //DBHelper.UpdateIDandDID("rd", head.list.Count(), cmd);
                }
                iFatherIdTwo += "'" + iFatherId + "',";
                #endregion
            }
            #region 查询
            sql = @"    select a.ID as ID,a.ID as IDs,a.cCode as RCVNEGCode,a.cVenCode,D.cVenName,
                                a.cWhCode,c.cWhName,cARVCode as DNRTCode,cMaker as CreateUser,
                                dnmaketime as CreateDateTime,cHandler as Checker,dVeriDate as CheckDateTime
                            FROM  RdRecord01 a 
                            LEFT JOIN Warehouse  C ON A.cWhCode=C.cWhCode
                            LEFT JOIN VENDOR D ON A.CVENCODE=D.CVENCODE WHERE 1=1  and a.ID in ({0})  

                      select   a.ID as IDs, AutoID as DetailID,irowno as Sequence,
                            cInvCode as InvCode,iQuantity as Quantity,iNum as Amount,iArrsId as DNRTDetailID
                            FROM  RdRecord01 a 
                            LEFT JOIN rdrecords01 b on a.ID=b.ID
                            LEFT JOIN DEPARTMENT C ON A.CDEPCODE=C.CDEPCODE
                            LEFT JOIN VENDOR D ON A.CVENCODE=D.CVENCODE WHERE 1=1 and 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);
            szJson = DBHelper.DataSetToJson(ds, RelationName); 
            #endregion
            cmd.Transaction.Commit();
            return szJson;
        }
        /// <summary>
        /// 审核采购入库单(红字)
        /// </summary>
        /// <param name="infos"></param>
        /// <returns></returns>
        public bool  Approve(List<ICSPurchaseReceiveDoc> infos)
        {
            bool ResultFlag = false;
            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
            {
                if (infos.Count <= 0)
                {
                    throw new Exception("传送数据为空!");
                }
                LogInfo(infos);
                foreach (ICSPurchaseReceiveDoc head in infos)
                {
                    string sql = "";
                    ICSUserInfo userInfo = new ICSUserInfo();
                    userInfo = DBHelper.GetPersonInfo(head.User, cmd);

                    #region 检验单号是否存在
                    sql = "select * from RdRecord01 where ID='" + head.ID + "'";
                    DataTable dt = DBHelper.SQlReturnData(sql, cmd);
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        string cHandler = dt.Rows[0]["cHandler"].ToString();
                        if (!string.IsNullOrEmpty(cHandler))
                        {
                            throw new Exception("单据ID:" + head.ID + "不是开立状态!");
                        }
                    }
                    else
                    {
                        throw new Exception("单据ID:" + head.ID + "在U8中不存在!");
                    }
                    #endregion

                    #region 审核其他出库单
                    sql = @"UPDATE dbo.RdRecord01 SET cHandler='" + userInfo.UserName + @"' ,
                            dVeriDate=CONVERT(VARCHAR(50),GETDATE(),112),dnverifytime=GETDATE() WHERE ID='" + head.ID + "'";
                    DBHelper.CmdExecuteNonQuery(sql, cmd, "审核其他出库单失败!");
                    #endregion
                    sql = "select * from dbo.RdRecords01 a inner join RdRecord01 b on a.ID=b.ID where b.ID='" + head.ID + "';";
                    DataTable dtChecks = DBHelper.SQlReturnData(sql, cmd);
                    #region 更新现存量
                    for (int i = 0; i < dtChecks.Rows.Count; i++)
                    {
                        //判断物料批号与现存量表批号是否一致、数量不能超过现存量物料数量
                        sql = @"SELECT cBatch,iQuantity from CurrentStock WHERE cInvCode='" + dtChecks.Rows[i]["cInvCode"].ToString() + "'AND cBatch=''and cWhCode='" + dtChecks.Rows[i]["cWhCode"].ToString() + "'";
                        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.cInvCode);
                            //}
                            if (Convert.ToDecimal(dtItem.Rows[0]["iQuantity"].ToString()) < Convert.ToDecimal(dtChecks.Rows[i]["iQuantity"].ToString()))
                            {
                                throw new Exception("物料条码的数量大于U8现存量物料数量,物料:" + dtChecks.Rows[i]["cInvCode"].ToString());
                            }

                        }
                        else
                        {
                            throw new Exception("物料:" + dtChecks.Rows[i]["cInvCode"].ToString() + "在现存量表中不存在!");
                        }


                        VouchKey key = new VouchKey();
                        key.cBustypeUN = "普通采购";
                        key.cVouchTypeUN = "01";
                        key.TableName = "IA_ST_UnAccountVouch01";
                        DBHelper.UpdateCurrentStock(cmd, dtChecks.Rows[i]["cInvCode"].ToString(), dtChecks.Rows[i]["cWhCode"].ToString(), "", Convert.ToDecimal(dtChecks.Rows[i]["iQuantity"].ToString()), key);

                        //回写fOutQuantityy
                        //                        sql = @"Update CurrentStock set fOutQuantity=isnull(fOutQuantity,0)-" + Convert.ToDecimal(dtChecks.Rows[i]["iQuantity"].ToString()) + @" 
                        //                                where cInvCode='" + dtChecks.Rows[i]["cInvCode"].ToString() + "' and cWhCode='" + dtChecks.Rows[i]["cWhCode"].ToString() + "' ";
                        //if (body.cBatch != null)
                        //{
                        //    sql += "and cBatch='" + body.cBatch + "'";
                        //}
                        //else
                        //{
                        //    sql += "and cBatch=''";
                        //}
                        //DBHelper.CmdExecuteNonQuery(sql, cmd, "回写fOutQuantity失败!");
                        //if (head.UpdateTodoQuantity == true)
                        //{
                        #region 判断现存量是否足够
                        sql = @"IF EXISTS(SELECT AutoID FROM dbo.CurrentStock WHERE iQuantity<0 OR iNum<0 OR fOutQuantity<0)
                            BEGIN
	                            DECLARE @MSG NVARCHAR(100)
	                            SELECT @MSG='ERP待出库数量不足!AutoID:'+CAST(AutoID AS NVARCHAR(100)) FROM dbo.CurrentStock WHERE iQuantity<0 OR iNum<0 OR fOutQuantity<0
 	                            RAISERROR(@MSG,16,1)
                            END";

                        cmd.CommandText = sql;
                        cmd.ExecuteNonQuery();
                        #endregion


                    }
                    #endregion

                }


                cmd.Transaction.Commit();
                ResultFlag = true;
                return ResultFlag;
            }
            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();
            }

//            List<ICSPurchaseReceiveDoc> szJson = new List<ICSPurchaseReceiveDoc>();
//            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 (ICSPurchaseReceiveDoc 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<ICSPurchaseReceiveDoc> infos)
        {
            List<ICSPurchaseReceiveDoc> szJson = new List<ICSPurchaseReceiveDoc>();
            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 (ICSPurchaseReceiveDoc 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 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();
            }
        }
        public string GetSerialCode(string ID)
        {
            string sql = "EXEC Addins_GetSerialCode '{0}'";
            sql = string.Format(sql, new object[] { ID });
            return DBHelper.ExecuteScalar(CommandType.Text, sql, connString).ToString();
        }
        /// <summary>
        /// 记录日志
        /// </summary>
        /// <param name="Bills"></param>
        private void LogInfo(List<ICSPurchaseReceiveDoc> Bills)
        {
            string HeadList = string.Empty;
            string BodyList = string.Empty;
            foreach (ICSPurchaseReceiveDoc head in Bills)
            {
                HeadList += "\r\n 表头主键ID:" + head.ID + ",用户:" + head.User + "";

            }
            log.Info(HeadList);
            log.Info(BodyList);
        }
    }

}