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 OutsourcingReceiveDoc
    {
        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<ICSOutsourcingReceiveDoc> infos)
        {
  
            List<ICSOutsourcingReceiveDoc> szJson = new List<ICSOutsourcingReceiveDoc>();
            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 (ICSOutsourcingReceiveDoc info in infos)
                {
                    if (info.MTime < new DateTime(2000, 01, 01))
                        throw new Exception("请输入正确的操作时间:" + info.MTime);
                    sql = @" select a.ID,iMPoIds,iordercode,a.cCode,a.cDepCode,c.cDepName,a.cWhCode,
                            d.cWhName,a.cSource,a.cMaker,dnmaketime,cHandler,dnverifytime,cSourceCodeLs,
                            b.AutoID ,b.irowno,b.cInvCode,b.iQuantity,e.MoDetailsID,b.iNum,e.csocode
                            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 OM_MODetails e on b.iOMoDID=e.MoDetailsID
                           where a.cBusType='委外加工'";
                    if (!string.IsNullOrWhiteSpace(info.ORCVTCode))
                    {
                        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.ORCVTCode, info.MTime, info.User);
                    dt = DBHelper.SQlReturnData(sql, cmd);
                    json = JsonConvert.SerializeObject(dt);
                    if (dt.Rows.Count <= 0 || dt == null)
                        throw new Exception("委外发料单:" + info.ORCVTCode + ",无信息!");

                }
                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 CreateOutsourcingReceiveDocByPOArrive(List<ICSOutsourcingReceiveDoc> Bills)
        {
            string msg = "";
            int num = 0;
            string sql = "";
            string iFatherIdTwo = "";
            //取得采购入库单单据 表头ID,表体DID
            VouchKey key = new VouchKey();
            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 (Bills.Count <= 0)
                {
                    throw new Exception("传送数据为空!");
                }
                LogInfo(Bills);
                foreach (ICSOutsourcingReceiveDoc head in Bills)
                {
                    num = head.details.Count();
                    //取得out库单的默认显示模版
                    Dictionary<string, int> dic = DBHelper.GetAllCode("" + ERPDB + "", "PuArrival", "" + 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");
          

                    #region 验证数量不能大于到货单数量

                    //foreach (ICSOutsourcingReceiveDocs body in head.details)
                    //    {
                    //        sql = "SELECT isnull(-iQuantity,0) FROM dbo.PU_ArrivalVouchs WHERE Autoid='" + body.ODNDetailID + "'";
                    //        DataTable dtQty = DBHelper.SQlReturnData(sql, cmd);
                    //        if (dtQty != null && dtQty.Rows.Count > 0)
                    //        {
                    //            //到货单可入数量
                    //            decimal PUQty = Convert.ToDecimal(dtQty.Rows[0][0]);
                    //            sql = "SELECT ISNULL(SUM(-iQuantity),0) FROM dbo.RdRecords01 WHERE iArrsId='" + body.ODNDetailID + "'";
                    //            DataTable dtReceQty = DBHelper.SQlReturnData(sql, cmd);
                    //            decimal ReceQty = Convert.ToDecimal(dtReceQty.Rows[0][0]);
                    //            if (ReceQty + body.Quantity > PUQty)
                    //            {
                    //                throw new Exception("入库数量大于当前到货单行可入库数量!");
                    //            }
                    //        }
                    //        else
                    //        {
                    //            throw new Exception("U8不存在该到货单行!");
                    //        }
                    //    }
                   
                    #endregion

                    #region 委外采购入库单 表头
                   
                    sql = @"INSERT INTO dbo.RdRecord01
                        ( ID ,bRdFlag ,cVouchType ,cBusType ,cSource ,cWhCode ,
                          dDate ,cCode ,cRdCode ,cDepCode ,cPersonCode ,cPTCode ,
                          cVenCode ,cOrderCode ,cARVCode ,cHandler ,cMemo ,
                          bTransFlag ,cMaker ,cDefine1 ,cDefine2 ,cDefine3 ,
                          cDefine4 ,cDefine5 ,cDefine6 ,cDefine7 ,cDefine8 ,
                          cDefine9 ,cDefine10 ,dVeriDate ,bpufirst ,biafirst ,
                		  dARVDate ,VT_ID ,bIsSTQc ,cDefine11 ,cDefine12 ,
                          cDefine13 ,cDefine14 ,cDefine15 ,cDefine16 ,
                          ipurarriveid ,iTaxRate ,iExchRate ,cExch_Name ,bOMFirst,
                          bFromPreYear ,bIsComplement ,iDiscountTaxType ,
                          ireturncount ,iverifystate ,iswfcontrolled ,
                          cModifyPerson ,dnmaketime ,dnverifytime ,
                          bredvouch  ,bCredit ,iPrintCount)
                SELECT @ID,1,'01','委外加工','委外到货单',@cWhCode,
                		CONVERT(NVARCHAR(15),GETDATE(),23),@cCode,'101',@cDepCode,a.cPersonCode,'01',
                		a.cVenCode,b.cCode,a.cCode,@cHandler,a.cMemo,
                		0,@cMaker,a.cDefine1,a.cDefine2,a.cDefine3,
                		a.cDefine4,a.cDefine5,a.cDefine6,a.cDefine7,a.cDefine8,
                		a.cDefine9,a.cDefine10,CONVERT(NVARCHAR(15),GETDATE(),23),0,0,
                		a.dDate,@VT_ID,0,a.cDefine11,a.cDefine12,
                		a.cDefine13,a.cDefine14,a.cDefine15,a.cDefine16,
                		a.ID,a.iTaxRate,a.iExchRate,a.cexch_name,0,
                		0,0,0,
                		0,0,0,
                		'',GETDATE(),GETDATE(),
                		0,0,0
                 FROM dbo.PU_ArrivalVouch a LEFT JOIN dbo.OM_MOMain b ON a.cpocode=b.cCode WHERE a.cCode='" + head.ODNCode + "'";
                    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("@cDepCode", ""));
                        cmd.Parameters.Add(new SqlParameter("@cHandler", head.User));
                        cmd.Parameters.Add(new SqlParameter("@cMaker", head.User));
                        cmd.Parameters.Add(new SqlParameter("@VT_ID", iChildId));
                        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 采购入库单 表体
                    foreach (ICSOutsourcingReceiveDocs body in head.details)
                    {
                       
                      
                        sql = @"INSERT INTO dbo.rdrecords01
          ( AutoID ,ID ,cInvCode ,iQuantity ,iUnitCost ,iPrice ,iAPrice ,
            iFlag ,iSQuantity ,iSNum ,iMoney ,
            cDefine22 ,cDefine23 ,cDefine24 ,cDefine25 ,cDefine26 ,cDefine27 ,
            cItem_class ,cItemCode ,iPOsID ,fACost ,cName  ,iNQuantity ,
            chVencode ,iArrsId ,iOriTaxCost ,iOriCost ,iOriMoney ,iOriTaxPrice ,
            ioriSum ,iTaxRate ,iTaxPrice ,iSum ,bTaxCost ,cPOID ,iMatSettleState ,
            iBillSettleCount ,bLPUseFree ,iOriTrackID ,bCosting ,cbarvcode ,
            dbarvdate ,iExpiratDateCalcu ,iordertype ,isotype ,irowno ,bgift,cBatch,iProcessFee, iProcessCost )
  SELECT @AutoID,@ID,@cInvCode,@iQuantity,0,0,0,
  		0,0,0,0,
  		a.cDefine22,a.cDefine23,a.cDefine24,a.cDefine25,a.cDefine26,a.cDefine27,
  		a.cItem_class,a.cItemCode,a.iPOsID,0,a.cItemName,a.iQuantity,
  		c.cVenCode,a.Autoid,0,0,0,0,
  		0,a.iTaxRate,0,0,1,d.cCode,0,
  		0,0,0,1,c.cCode,
  		c.dDate,0,0,0,@irowno,0,@cBatch,a.iCost*convert(decimal, @iQuantity),a.iCost
  FROM dbo.PU_ArrivalVouchs a LEFT JOIN dbo.OM_MODetails b ON a.iPOsID=b.MODetailsID
  INNER JOIN dbo.OM_MOMain d ON b.MOID=d.MOID
  INNER JOIN dbo.PU_ArrivalVouch c ON a.ID=c.ID where a.Autoid='" + body.ODNDetailID + "'";
                        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("@irowno", body.Sequence));
                        cmd.Parameters.Add(new SqlParameter("@cBatch", ""));
                        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);
                        }

            
                        //更新现存量
                        key.cBustypeUN = "委外加工";
                        key.cVouchTypeUN = "01";
                        key.TableName = "IA_ST_UnAccountVouch01";
                        DBHelper.UpdateCurrentStock(cmd, body.InvCode, head.WHCode,"", body.Quantity, key);

                        //OM_MODetails
                        sql = @"UPDATE b SET freceivedqty=ISNULL(freceivedqty,0)+" + body.Quantity + @" 
                                FROM dbo.PU_ArrivalVouchs a LEFT JOIN dbo.OM_MODetails b ON a.iPOsID=b.MODetailsID
                                WHERE a.Autoid='" + body.ODNDetailID + "'";
                        DBHelper.CmdExecuteNonQuery(sql, cmd, "回写OM_MODetails失败!");
                        //回写PU_ArrivalVouchs失败
                        sql = "UPDATE dbo.PU_ArrivalVouchs SET fValidInQuan=ISNULL(fValidInQuan,0)+" + body.Quantity + " WHERE Autoid='" + body.ODNDetailID + "'";
                        DBHelper.CmdExecuteNonQuery(sql, cmd, "回写PU_ArrivalVouchs失败!");
                        iChildId--;
                    }

                    #endregion
                    iFatherIdTwo += "'" + iFatherId + "',";
                }
                sql = @"  select a.ID as ID,a.ID as IDs,a.cCode  as ORCVTCode ,a.cVenCode,d.cVenName,a.cOrderCode as OOCode, 
                       a.cMaker as CreateUser,dnmaketime as CreateDateTime,cHandler as Checker,dnverifytime as CheckDateTime
                           from rdrecord01 a
                       left join Department c on a.cDepCode=c.cDepCode
                       left join Vendor d on a.cVenCode=d.cVenCode
                          where a.cBusType='委外加工' AND A.ID in ({0}) 

                          select a.ID as IDs,b.AutoID as DetailID,b.irowno as Sequence,b.cInvCode as InvCode,b.iQuantity as Quantity,iNum as Amount,iArrsId as ODNDetailID
                           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 a.cBusType='委外加工' 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);
                msg = DBHelper.DataSetToJson(ds, RelationName);
                cmd.Transaction.Commit();
                return msg;
            }
            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 CreateOutsourcingReceiveDocByPU(List<ICSOutsourcingReceiveDoc> Bills)
        {
            string msg = "";
            int num = 0;
            //取得out库单的默认显示模版
         
            //取得采购入库单单据 表头ID,表体DID
            VouchKey key = new VouchKey();
            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 (Bills.Count <= 0)
                {
                    throw new Exception("传送数据为空!");
                }
                LogInfo(Bills);
                foreach (ICSOutsourcingReceiveDoc head in Bills)
                {
                    num = head.details.Count();
                    Dictionary<string, int> dic = DBHelper.GetAllCode("" + ERPDB + "", "PuArrival", "" + 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 sql = "";

                    #region 验证数量不能大于到货单数量

                    foreach (ICSOutsourcingReceiveDocs body in head.details)
                    {
                        sql = "SELECT isnull(-iQuantity,0) FROM dbo.PU_ArrivalVouchs WHERE Autoid='" + body.ODNDetailID + "'";
                        DataTable dtQty = DBHelper.SQlReturnData(sql, cmd);
                        if (dtQty != null && dtQty.Rows.Count > 0)
                        {
                            //到货单可入数量
                            decimal PUQty = Convert.ToDecimal(dtQty.Rows[0][0]);
                            sql = "SELECT ISNULL(SUM(-iQuantity),0) FROM dbo.RdRecords01 WHERE iArrsId='" + body.ODNDetailID + "'";
                            DataTable dtReceQty = DBHelper.SQlReturnData(sql, cmd);
                            decimal ReceQty = Convert.ToDecimal(dtReceQty.Rows[0][0]);
                            if (ReceQty + body.Quantity > PUQty)
                            {
                                throw new Exception("入库数量大于当前到货单行可入库数量!");
                            }
                        }
                        else
                        {
                            throw new Exception("U8不存在该到货单行!");
                        }
                    }

                    #endregion

                    #region 委外采购入库单 表头

                    sql = @"INSERT INTO dbo.RdRecord01
                        ( ID ,bRdFlag ,cVouchType ,cBusType ,cSource ,cWhCode ,
                          dDate ,cCode ,cRdCode ,cDepCode ,cPersonCode ,cPTCode ,
                          cVenCode ,cOrderCode ,cARVCode ,cHandler ,cMemo ,
                          bTransFlag ,cMaker ,cDefine1 ,cDefine2 ,cDefine3 ,
                          cDefine4 ,cDefine5 ,cDefine6 ,cDefine7 ,cDefine8 ,
                          cDefine9 ,cDefine10 ,dVeriDate ,bpufirst ,biafirst ,
                		  dARVDate ,VT_ID ,bIsSTQc ,cDefine11 ,cDefine12 ,
                          cDefine13 ,cDefine14 ,cDefine15 ,cDefine16 ,
                          ipurarriveid ,iTaxRate ,iExchRate ,cExch_Name ,bOMFirst,
                          bFromPreYear ,bIsComplement ,iDiscountTaxType ,
                          ireturncount ,iverifystate ,iswfcontrolled ,
                          cModifyPerson ,dnmaketime ,dnverifytime ,
                          bredvouch  ,bCredit ,iPrintCount)
                SELECT @ID,1,'01','委外加工','委外到货单',@cWhCode,
                		CONVERT(NVARCHAR(15),GETDATE(),23),@cCode,'101',@cDepCode,a.cPersonCode,'01',
                		a.cVenCode,b.cCode,a.cCode,@cHandler,a.cMemo,
                		0,@cMaker,a.cDefine1,a.cDefine2,a.cDefine3,
                		a.cDefine4,a.cDefine5,a.cDefine6,a.cDefine7,a.cDefine8,
                		a.cDefine9,a.cDefine10,CONVERT(NVARCHAR(15),GETDATE(),23),0,0,
                		a.dDate,@VT_ID,0,a.cDefine11,a.cDefine12,
                		a.cDefine13,a.cDefine14,a.cDefine15,a.cDefine16,
                		a.ID,a.iTaxRate,a.iExchRate,a.cexch_name,0,
                		0,0,0,
                		0,0,0,
                		'',GETDATE(),GETDATE(),
                		0,0,0
                 FROM dbo.PU_ArrivalVouch a LEFT JOIN dbo.OM_MOMain b ON a.cpocode=b.cCode WHERE a.cCode ='" + head.ODNCode + "'";
                    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("@cDepCode", ""));
                    cmd.Parameters.Add(new SqlParameter("@cHandler", head.User));
                    cmd.Parameters.Add(new SqlParameter("@cMaker", head.User));
                    cmd.Parameters.Add(new SqlParameter("@VT_ID", iChildId));
                    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 (ICSOutsourcingReceiveDocs body in head.details)
                    { 
                        sql = @"INSERT INTO dbo.rdrecords01
          ( AutoID ,ID ,cInvCode ,iQuantity ,iUnitCost ,iPrice ,iAPrice ,
            iFlag ,iSQuantity ,iSNum ,iMoney ,
            cDefine22 ,cDefine23 ,cDefine24 ,cDefine25 ,cDefine26 ,cDefine27 ,
            cItem_class ,cItemCode ,iPOsID ,fACost ,cName  ,iNQuantity ,
            chVencode ,iArrsId ,iOriTaxCost ,iOriCost ,iOriMoney ,iOriTaxPrice ,
            ioriSum ,iTaxRate ,iTaxPrice ,iSum ,bTaxCost ,cPOID ,iMatSettleState ,
            iBillSettleCount ,bLPUseFree ,iOriTrackID ,bCosting ,cbarvcode ,
            dbarvdate ,iExpiratDateCalcu ,iordertype ,isotype ,irowno ,bgift,cBatch,iProcessFee, iProcessCost )
  SELECT @AutoID,@ID,@cInvCode,@iQuantity,0,0,0,
  		0,0,0,0,
  		a.cDefine22,a.cDefine23,a.cDefine24,a.cDefine25,a.cDefine26,a.cDefine27,
  		a.cItem_class,a.cItemCode,a.iPOsID,0,a.cItemName,a.iQuantity,
  		c.cVenCode,a.Autoid,0,0,0,0,
  		0,a.iTaxRate,0,0,1,d.cCode,0,
  		0,0,0,1,c.cCode,
  		c.dDate,0,0,0,@irowno,0,@cBatch,a.iCost*convert(decimal, @iQuantity),a.iCost
  FROM dbo.PU_ArrivalVouchs a LEFT JOIN dbo.OM_MODetails b ON a.iPOsID=b.MODetailsID
  INNER JOIN dbo.OM_MOMain d ON b.MOID=d.MOID
  INNER JOIN dbo.PU_ArrivalVouch c ON a.ID=c.ID where a.Autoid='" + body.ODNDetailID + "'";
                        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("@irowno", irowno));
                        cmd.Parameters.Add(new SqlParameter("@cBatch", ""));
                        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);
                        }


                        //更新现存量
                        key.cBustypeUN = "委外加工";
                        key.cVouchTypeUN = "01";
                        key.TableName = "IA_ST_UnAccountVouch01";
                        DBHelper.UpdateCurrentStock(cmd, body.InvCode, head.WHCode, "", body.Quantity, key);

                        //OM_MODetails
                        sql = @"UPDATE b SET freceivedqty=ISNULL(freceivedqty,0)+" + body.Quantity + @" 
                                FROM dbo.PU_ArrivalVouchs a LEFT JOIN dbo.OM_MODetails b ON a.iPOsID=b.MODetailsID
                                WHERE a.Autoid='" + body.ODNDetailID + "'";
                        DBHelper.CmdExecuteNonQuery(sql, cmd, "回写OM_MODetails失败!");
                        //回写PU_ArrivalVouchs失败
                        sql = "UPDATE dbo.PU_ArrivalVouchs SET fValidInQuan=ISNULL(fValidInQuan,0)+" + body.Quantity + " WHERE Autoid='" + body.ODNDetailID + "'";
                        DBHelper.CmdExecuteNonQuery(sql, cmd, "回写PU_ArrivalVouchs失败!");

                        //更新待入库数量
                        sql = "UPDATE dbo.CurrentStock SET fInQuantity=ISNULL(fInQuantity,0)-" + body.Quantity + " WHERE cInvCode='" + body.InvCode + "' AND cWhCode ='" + head.WHCode + "'";
                        if (DBHelper.bInvBatch(body.InvCode, cmd) == true)
                        {
                            //if (!string.IsNullOrWhiteSpace(body.cBatch))
                            //{
                            //    sql += " and cBatch='" + body.cBatch + "'";
                            //}
                        }
                        DBHelper.CmdExecuteNonQuery(sql, cmd, "更新待入库数量失败!");
//                        #region 判断现存量是否足够
//                        sql = @"IF EXISTS(SELECT AutoID FROM dbo.CurrentStock WHERE iQuantity<0 OR iNum<0 OR fInQuantity<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 fInQuantity<0
// 	                        RAISERROR(@MSG,16,1)
//                        END";

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

                    #endregion

                }
                //GetSerialCode(iFatherId.ToString());
                cmd.Transaction.Commit();
                return msg;
            }
            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 CreateOutsourcingReceiveDocByPO(List<ICSOutsourcingReceiveDoc> Bills)
        {
            string msg = "";
            int num = 0;
            string iFatherIdTwo = "";
            string sql = "";
            DataTable dt = null;
            VouchKey key = new VouchKey();
            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 (Bills.Count <= 0)
                {
                    throw new Exception("传送数据为空!");
                }
                LogInfo(Bills);
                foreach (ICSOutsourcingReceiveDoc head in Bills)
                {
                    string RdCode= DBHelper.GetRDCode("采购入库", cmd);
                    num = head.details.Count();
                    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");
            

                    #region 验证数量不能大于到货单数量

                    //foreach (ICSOutsourcingReceiveDocs body in head.details)
                    //{
                    //    sql = "SELECT isnull(-iQuantity,0) FROM dbo.PU_ArrivalVouchs WHERE Autoid='" + body.ODNDetailID + "'";
                    //    DataTable dtQty = DBHelper.SQlReturnData(sql, cmd);
                    //    if (dtQty != null && dtQty.Rows.Count > 0)
                    //    {
                    //        //到货单可入数量
                    //        decimal PUQty = Convert.ToDecimal(dtQty.Rows[0][0]);
                    //        sql = "SELECT ISNULL(SUM(-iQuantity),0) FROM dbo.RdRecords01 WHERE iArrsId='" + body.ODNDetailID + "'";
                    //        DataTable dtReceQty = DBHelper.SQlReturnData(sql, cmd);
                    //        decimal ReceQty = Convert.ToDecimal(dtReceQty.Rows[0][0]);
                    //        if (ReceQty + body.Quantity > PUQty)
                    //        {
                    //            throw new Exception("入库数量大于当前到货单行可入库数量!");
                    //        }
                    //    }
                    //    else
                    //    {
                    //        throw new Exception("U8不存在该到货单行!");
                    //    }
                    //}

                    #endregion

                    #region 委外采购入库单 表头

                    sql = @"INSERT INTO dbo.RdRecord01
                        ( ID ,bRdFlag ,cVouchType ,cBusType ,cSource ,cWhCode ,
                          dDate ,cCode ,cRdCode ,cDepCode ,cPersonCode ,cPTCode ,
                          cVenCode ,cOrderCode ,cARVCode ,cHandler ,cMemo ,
                          bTransFlag ,cMaker ,cDefine1 ,cDefine2 ,cDefine3 ,
                          cDefine4 ,cDefine5 ,cDefine6 ,cDefine7 ,cDefine8 ,
                          cDefine9 ,cDefine10 ,dVeriDate ,bpufirst ,biafirst ,
                		  dARVDate ,VT_ID ,bIsSTQc ,cDefine11 ,cDefine12 ,
                          cDefine13 ,cDefine14 ,cDefine15 ,cDefine16 ,
                          ipurarriveid ,iTaxRate ,iExchRate ,cExch_Name ,bOMFirst,
                          bFromPreYear ,bIsComplement ,iDiscountTaxType ,
                          ireturncount ,iverifystate ,iswfcontrolled ,
                          cModifyPerson ,dnmaketime ,dnverifytime ,
                          bredvouch  ,bCredit ,iPrintCount)
                SELECT @ID,1,'01','委外加工','委外订单',@cWhCode,
                		CONVERT(NVARCHAR(15),GETDATE(),23),@cCode,@RdCode,@cDepCode,a.cPersonCode,'01',
                		a.cVenCode,'',a.cCode,@cHandler,a.cMemo,
                		0,@cMaker,a.cDefine1,a.cDefine2,a.cDefine3,
                		a.cDefine4,a.cDefine5,a.cDefine6,a.cDefine7,a.cDefine8,
                		a.cDefine9,a.cDefine10,CONVERT(NVARCHAR(15),GETDATE(),23),0,0,
                		a.dDate,@VT_ID,0,a.cDefine11,a.cDefine12,
                		a.cDefine13,a.cDefine14,a.cDefine15,a.cDefine16,
                		'',a.iTaxRate,a.nflat,a.cexch_name,0,
                		0,0,0,
                		0,0,0,
                		'',GETDATE(),GETDATE(),
                		0,0,0
                 FROM dbo.OM_MOMain a   WHERE a.cCode='" + head.OOCode + "'";
                    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("@cDepCode", ""));
                    cmd.Parameters.Add(new SqlParameter("@cHandler", head.User));
                    cmd.Parameters.Add(new SqlParameter("@cMaker", head.User));
                    cmd.Parameters.Add(new SqlParameter("@VT_ID", iChildId));
                    cmd.Parameters.Add(new SqlParameter("@RdCode", RdCode));
                    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 采购入库单 表体
                    foreach (ICSOutsourcingReceiveDocs body in head.details)
                    {
                        sql = @"INSERT INTO dbo.rdrecords01
          ( AutoID ,ID ,cInvCode ,iQuantity ,iUnitCost ,iPrice ,iAPrice ,
            iFlag ,iSQuantity ,iSNum ,iMoney ,
            cDefine22 ,cDefine23 ,cDefine24 ,cDefine25 ,cDefine26 ,cDefine27 ,
            cItem_class ,cItemCode ,iOMoDID ,fACost ,cName  ,iNQuantity ,
            chVencode ,iArrsId ,iOriTaxCost ,iOriCost ,iOriMoney ,iOriTaxPrice ,
            ioriSum ,iTaxRate ,iTaxPrice ,iSum ,bTaxCost ,cPOID ,iMatSettleState ,
            iBillSettleCount ,bLPUseFree ,iOriTrackID ,bCosting ,cbarvcode 
            ,iExpiratDateCalcu ,iordertype ,isotype ,irowno ,bgift,cBatch,iProcessFee, iProcessCost )
  SELECT @AutoID,@ID,@cInvCode,@iQuantity,0,0,0,
  		0,0,0,0,
  		a.cDefine22,a.cDefine23,a.cDefine24,a.cDefine25,a.cDefine26,a.cDefine27,
  		a.cItem_class,a.cItemCode,a.MODetailsID,0,a.cItemName,a.iQuantity,
  		@VenCode,'',0,0,0,0,
  		0,d.nflat,0,0,1,'',0,
  		0,0,0,1,'',
  		0,0,0,@irowno,0,@cBatch,a.iNatUnitPrice *convert(decimal, @iQuantity),a.iNatUnitPrice 
  FROM dbo.OM_MODetails a
  INNER JOIN dbo.OM_MOMain d ON a.MOID=d.MOID
   where a.MODetailsID='" + body.OODetailID + "'";
                        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("@irowno",body.Sequence));
                        cmd.Parameters.Add(new SqlParameter("@cBatch", ""));
                        cmd.Parameters.Add(new SqlParameter("@VenCode", head.VenCode));
                        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);
                        }

                      
                        //更新现存量
                        key.cBustypeUN = "委外加工";
                        key.cVouchTypeUN = "01";
                        key.TableName = "IA_ST_UnAccountVouch01";
                        DBHelper.UpdateCurrentStock(cmd, body.InvCode, head.WHCode, "", body.Quantity, key);

                        //OM_MODetails
                        sql = @"UPDATE a SET freceivedqty=ISNULL(freceivedqty,0)+" + body.Quantity + @" 
                                FROM  dbo.OM_MODetails a 
                                WHERE a.MODetailsID='" + body.OODetailID + "'";
                        DBHelper.CmdExecuteNonQuery(sql, cmd, "回写OM_MODetails失败!");

                        //更新待入库数量
                        sql = "UPDATE dbo.CurrentStock SET fInQuantity=ISNULL(fInQuantity,0)-" + body.Quantity + " WHERE cInvCode='" + body.InvCode + "' AND cWhCode ='" + head.WHCode + "'";
                        if (DBHelper.bInvBatch(body.InvCode, cmd) == true)
                        {
                            //if (!string.IsNullOrWhiteSpace(body.cBatch))
                            //{
                            //    sql += " and cBatch='" + body.cBatch + "'";
                            //}
                        }
                        DBHelper.CmdExecuteNonQuery(sql, cmd, "更新待入库数量失败!");
                        iChildId--;
                    }
                    iFatherIdTwo += "'" + iFatherId + "',";
                    #endregion
      
                }
                sql = @"  select a.ID as ID,a.ID as IDs,a.cCode  as ORCVTCode ,a.cVenCode,d.cVenName,a.cOrderCode as OOCode, 
                       a.cMaker as CreateUser,dnmaketime as CreateDateTime,cHandler as Checker,dnverifytime as CheckDateTime
                           from rdrecord01 a
                       left join Department c on a.cDepCode=c.cDepCode
                       left join Vendor d on a.cVenCode=d.cVenCode
                          where a.cBusType='委外加工' AND A.ID in ({0}) 

                          select a.ID as IDs,b.AutoID as DetailID,b.irowno as Sequence,b.cInvCode as InvCode,b.iQuantity as Quantity,iNum as Amount,b.iOMoDID as OODetailID
                           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 a.cBusType='委外加工' 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);
                cmd.Transaction.Commit();
                msg = DBHelper.DataSetToJson(ds, RelationName);
                return msg;
            }
            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 Approve(List<ICSOutsourcingReceiveDoc> infos)
        {
            List<ICSSalesShipmentDoc> szJson = new List<ICSSalesShipmentDoc>();
            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 (ICSOutsourcingReceiveDoc info in infos)
                {
                    if (info.MTime < new DateTime(2000, 01, 01))
                        throw new Exception("请输入正确的操作时间:" + info.MTime);
                    sql = @"UPDATE  RdRecord01 SET cHandler ='" + info.User + @"' ,
                            dnverifytime=CONVERT(VARCHAR(50),GETDATE(),112),dVeriDate=GETDATE() WHERE ID='{0}'";
                    sql = string.Format(sql, 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<ICSOutsourcingReceiveDoc> infos)
        {
            List<ICSSalesShipmentDoc> szJson = new List<ICSSalesShipmentDoc>();
            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 (ICSOutsourcingReceiveDoc info in infos)
                {
                    if (info.MTime < new DateTime(2000, 01, 01))
                        throw new Exception("请输入正确的操作时间:" + info.MTime);
                    sql = @"delete  RdRecord01  where  RdRecord01.ID='" + info.ID + "'";
                    sql += @"delete  RdRecords01  where  RdRecords01.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();
            }
        }
        /// <summary>
        /// 
        /// 记录日志
        /// </summary>
        /// <param name="Bills"></param>
        private void LogInfo(List<ICSOutsourcingReceiveDoc> Bills)
        {
            string HeadList = string.Empty;
            string BodyList = string.Empty;
            foreach (ICSOutsourcingReceiveDoc head in Bills)
            {
                HeadList += "\r\n 表头主键ID:" + head.ID + ",仓库:" + head.WHCode + ",用户:" + head.User;
                foreach (ICSOutsourcingReceiveDocs body in head.details)
                {
                    BodyList += "\r\n 表体主键ID: " + body.ODNDetailID + ",数量:" + body.Quantity;
                }
            }
            log.Info(HeadList);
            log.Info(BodyList);
        }
        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();
        }
    }
}