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

namespace ICSSoft.DataProject
{
    public class CreatePuArrivalVouch
    {
        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"];
        private static string CRNALL = System.Configuration.ConfigurationManager.AppSettings["PUARRIVALRCRDNAME"];
        //参数示例
        //[{
        //    "ASNNO": "DN510852000001",
        //    "WHCode": "11",
        //    "User": "CC001",
        //    "MTime": "2021-08-26 17:20:13",
        //    "details": [
        //        {
        //            "LOTNO": "PO200219004100005",
        //            "ReceiveQty": "2"
        //        },{
        //            "LOTNO": "PO200219004100001",
        //            "ReceiveQty": "1"
        //        }
        //    ]
        //}]
        //返回参数
        //{
        //"Success": true,
        //"Message": "接口调用成功！",
        //"Data": null
        //}
        public string Get(List<ICSPUArrivalVouch> infos)
        {
            List<ICSPUArrivalVouch> szJson = new List<ICSPUArrivalVouch>();
            DataTable dt = null;
            DataTable dtNew = null;
            string connS = "";
            string json = "";
            if (infos.Count <= 0)
            {
                throw new Exception("传送数据为空！");
            }
            string res = string.Empty;
            SqlConnection conn = new SqlConnection();

            SqlCommand cmd = new SqlCommand();


            string sql = string.Empty;
            foreach (ICSPUArrivalVouch info in infos)
            {
                try
                {
                    connS = string.Format(connString, info.WorkPoint);
                    conn = new System.Data.SqlClient.SqlConnection(connS);
                    conn.Open();
                    SqlTransaction sqlTran = conn.BeginTransaction();
                    cmd = new SqlCommand();
                    cmd.Transaction = sqlTran;
                    cmd.Connection = conn;
                    ICSUserInfo userInfo = new ICSUserInfo();
                    userInfo = DBHelper.GetPersonInfo(info.User, cmd);
                    if (info.MTime < new DateTime(2000, 01, 01))
                        throw new Exception("请输入正确的操作时间：" + info.MTime);
                    sql = @"SELECT A.ID,A.cCode,A. cVenCode ,D.CVENNAME,A.cDepCode,C.CDEPNAME, A.CMAKER,A.CMAKETIME,A.CVERIFIER,A.CAUDITTIME,
                             B.Autoid ,B.irowno  ,B.IQUANTITY ,B.INUM,B.cInvCode ,B.iCost ,B.irejectautoid 
                             FROM PU_ArrivalVouch A
                             INNER JOIN PU_ArrivalVouchs 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 a.iBillType=2 and b.IQUANTITY<0 ";
                    if (!string.IsNullOrWhiteSpace(info.RJTCode))
                    {
                        sql += " and a.cCode='{0}'";
                    }
                    if (!string.IsNullOrWhiteSpace(info.MTime.ToString()))
                    {
                        sql += " and ISNULL(A.dclosedate,ISNULL(A.caudittime ,ISNULL(A.cAuditTime, ISNULL(A.cModifyTime, A.cMakeTime))))>='{1}'";
                    }
                    if (!string.IsNullOrWhiteSpace(info.User))
                    {
                        sql += "and a.CMAKER='{2}'";
                    }
                    sql = string.Format(sql, info.RJTCode, info.MTime, userInfo.UserName);
                    dt = DBHelper.SQlReturnData(sql, cmd);

                    if (dt.Rows.Count <= 0 || dt == null)
                        throw new Exception("拒收单单：" + info.RJTCode + "，无信息！");
                    if (dtNew == null)
                        dtNew = dt;
                    else
                        dtNew.Merge(dt);

                    cmd.Transaction.Commit();
                }
                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();
                }
            }
            json = JsonConvert.SerializeObject(dtNew);

            return json;

        }

        /// <summary>
        /// 回写U8到货单，
        /// </summary>
        /// <param name="cmd"></param>
        /// <param name="Lotnos"></param>
        /// <param name="info"></param>
        public string CreatePUArrive(List<ICSPUArrivalVouch> Bills)
        {
            string msg = "";
            string szJson = "";
            
            
            DataSet ds = null;
            string iFatherIdTwo = "";
            int num = 0;
          
            string connS = "";
            SqlConnection conn = new SqlConnection();

            SqlCommand cmd = new SqlCommand();


            if (Bills.Count <= 0)
            {
                throw new Exception("传送数据为空！");
            }
            bool isNG = false;
            LogInfo(Bills);
          
            foreach (ICSPUArrivalVouch head in Bills)
            {
                foreach (ICSPUArrivalVouchs body in head.Vouchs)
                {
                    if (body.Quantity > 0)
                    {
                        isNG = true;
                    }
                }
            }
               List<string> result = Bills.Select(t => t.WorkPoint).Distinct().ToList();


               foreach (string WorkPoint in result)
               {
                   try
                   {
                       connS = string.Format(connString, WorkPoint);
                       conn = new System.Data.SqlClient.SqlConnection(connS);
                       conn.Open();
                       SqlTransaction sqlTran = conn.BeginTransaction();
                       cmd = new SqlCommand();
                       cmd.Transaction = sqlTran;
                       cmd.Connection = conn;
                       if (isNG)
                       {
                           int sum = 0;
                           foreach (ICSPUArrivalVouch head in Bills)
                           {
                               iFatherIdTwo = "";
                               num = head.Vouchs.Count();
                               if (WorkPoint != head.WorkPoint)
                               {
                                   continue;
                               }
                               string[] ss = head.WorkPoint.Split('_');
                               ERPDB = ss[1];
                               string sql = "";
                               VouchKey key = new VouchKey();
                               //取得out库单的默认显示模版

                               string[] dd = CRNALL.Split('~');
                               string crdname = dd[0];
                               string carname = dd[1];
                               string surface = dd[2];

                               string cardnewcode = DBHelper.GetCardNumber(carname, cmd);
                               Dictionary<string, int> dic = DBHelper.GetAllCode("" + ERPDB + "", surface, "" + num + "", head.WorkPoint);
                               int iFatherId = Convert.ToInt32(dic["iFatherId"].ToString());
                               int iChildId = Convert.ToInt32(dic["iChildId"].ToString());
                               DateTime date = DateTime.Now;
                               string iBaseCodeLen = DBHelper.GetAllRDCode(cardnewcode, "" + date + "", "admin", "", head.WorkPoint);

                               string DEF_ID = DBHelper.GetDefaultTemplate(cardnewcode, cmd);

                               ICSUserInfo userInfo = new ICSUserInfo();
                               userInfo = DBHelper.GetPersonInfo(head.User, cmd);
                               #region 主表
                               sql = @"INSERT INTO PU_ArrivalVouch
(iVTid, ID, cCode, cPTCode, dDate, cVenCode, cDepCode, cPersonCode, cPayCode, cexch_name, iExchRate, iTaxRate,  cMemo, cBusType, cMaker, bNegative,
iDiscountTaxType, iBillType, cMakeTime, cAuditDate, caudittime, cverifier, iverifystateex, IsWfControlled, iflowid, iPrintCount, cpocode)
SELECT @iVTid, @ID, @cCode, cPTCode, CONVERT(NVARCHAR(10), GETDATE(), 23), cVenCode, cDepCode, cPersonCode, cPayCode, cexch_name, iExchRate, iTaxRate, cMemo, '普通采购', @User, 1,
iDiscountTaxType, 2, GETDATE(), CONVERT(NVARCHAR(10), GETDATE(), 23), GETDATE(), @User, 2, 0, 0, iPrintCount, null
FROM PU_ArrivalVouch WHERE 1=1 AND cCode = @headID ";
                               cmd.Parameters.Clear();
                               cmd.Parameters.Add(new SqlParameter("@iVTid", DEF_ID));
                               cmd.Parameters.Add(new SqlParameter("@ID", iFatherId));
                               cmd.Parameters.Add(new SqlParameter("@cCode", iBaseCodeLen));
                               cmd.Parameters.Add(new SqlParameter("@User", userInfo.UserName));
                               cmd.Parameters.Add(new SqlParameter("@headID", head.DNCode));
                               cmd.CommandText = sql;
                               try
                               {
                                   int count = cmd.ExecuteNonQuery();
                                   if (count <= 0)
                                   {
                                       log.Error("生成采购拒收单表头失败，受影响行数<=0；");
                                       throw new Exception("生成采购拒收单表头失败，受影响行数<=0；");
                                   }
                               }
                               catch (Exception ex)
                               {
                                   log.Error("生成采购拒收单表头失败！到货单ID：" + head.ID + "；异常：" + ex.Message + "；SQL：\r\n" + sql, ex);
                                   throw new Exception("生成采购拒收单表头失败！到货单ID：" + head.ID + "；异常：" + ex.Message + "；SQL：\r\n" + sql, ex);
                               }
                               #endregion
                               iFatherIdTwo = "'" + iFatherId + "',";
                               #region 表体
                               foreach (ICSPUArrivalVouchs body in head.Vouchs)
                               {

                                   sql = @"INSERT INTO PU_ArrivalVouchs
(Autoid, ID, cInvCode, iQuantity, iOriCost, iOriTaxCost, iOriMoney, iOriTaxPrice, iOriSum, iCost, iMoney, iTaxPrice, iSum, iTaxRate,
iPOsID, fValidInQuan, fRealQuantity, fValidQuantity, fRetQuantity, fInValidInQuan, bGsp, fValidNum, fValidInNum, fRealNum, bTaxCost,
SoType, fInvalidInNum, iinvexchrate, cordercode, RejectSource, iExpiratDateCalcu, iordertype, ivouchrowno, bgift,
cFree1, cFree2, cFree3, cFree4, cFree5, cFree6, cFree7, cFree8, cFree9, cFree10,cItemCode,
cBatch, cDefine37, fKPQuantity, finValidQuantity, fRefuseQuantity, iProductType,bexigency,inum,iCorId,carrivalcode )
SELECT @Autoid, @ID1, @cInvCode, @iQuantity,pd.iUnitPrice,pd.iTaxPrice,round((pd.iTaxPrice*@iQuantity)/(1+pd.iPerTaxRate/100),2),
round(pd.iTaxPrice*@iQuantity,2)-round((pd.iTaxPrice*@iQuantity)/(1+pd.iPerTaxRate/100),2),round(pd.iTaxPrice*@iQuantity,2),round((pd.iTaxPrice/(1+pd.iPerTaxRate/100)*b.nflat),2),
round(round((pd.iTaxPrice*@iQuantity)/(1+pd.iPerTaxRate/100),2)*b.nflat,2),
round((round(pd.iTaxPrice*@iQuantity,2)-round((pd.iTaxPrice*@iQuantity)/(1+pd.iPerTaxRate/100),2))*b.nflat,2),round(round(pd.iTaxPrice*3402,2)*b.nflat,2),pd.iPerTaxRate,
pd.ID, 0, @iQuantity, @iQuantity, 0, 0, 0, null, null, null, 1,
0, null, 0, b.cPOID, 0, 0, 0, @ivouchrowno, 0,
@cFree1, @cFree2, @cFree3, @cFree4, @cFree5, @cFree6, @cFree7, @cFree8, @cFree9, @cFree10,@cItemCode,
@Batch, @cDefine37, null, null, null, null, null,0,a.Autoid,c.cCode
FROM dbo.PU_ArrivalVouchs a LEFT JOIN dbo.PO_Podetails pd ON a.iPOsID= pd.ID
  INNER JOIN dbo.PO_Pomain b ON pd.POID=b.POID
  INNER JOIN dbo.PU_ArrivalVouch c ON a.ID=c.ID where a.Autoid='" + body.DNDetailID + @"'  
EXEC PROC_Update_PO_PUArrivalVouchs @ID= @ID1";
                                   cmd.Parameters.Clear();
                                   cmd.Parameters.Add(new SqlParameter("@Autoid", iChildId));
                                   cmd.Parameters.Add(new SqlParameter("@ID1", iFatherId));
                                   cmd.Parameters.Add(new SqlParameter("@cInvCode", body.InvCode));
                                   cmd.Parameters.Add(new SqlParameter("@iQuantity", -body.Quantity));
                                   cmd.Parameters.Add(new SqlParameter("@ivouchrowno", body.Sequence));
                                   cmd.Parameters.Add(new SqlParameter("@Batch", body.BatchCode));
                                   cmd.Parameters.Add(new SqlParameter("@cItemCode", body.ProjectCode));
                                   cmd.Parameters.Add(new SqlParameter("@cDefine37", DateTime.Now.Date.AddDays(1 - DateTime.Now.Day).AddMonths(1).AddSeconds(-1)));
                                   cmd.Parameters.Add(new SqlParameter("@cFree1", body.cFree1));
                                   cmd.Parameters.Add(new SqlParameter("@cFree2", body.cFree2));
                                   cmd.Parameters.Add(new SqlParameter("@cFree3", body.cFree3));
                                   cmd.Parameters.Add(new SqlParameter("@cFree4", body.cFree4));
                                   cmd.Parameters.Add(new SqlParameter("@cFree5", body.cFree5));
                                   cmd.Parameters.Add(new SqlParameter("@cFree6", body.cFree6));
                                   cmd.Parameters.Add(new SqlParameter("@cFree7", body.cFree7));
                                   cmd.Parameters.Add(new SqlParameter("@cFree8", body.cFree8));
                                   cmd.Parameters.Add(new SqlParameter("@cFree9", body.cFree9));
                                   cmd.Parameters.Add(new SqlParameter("@cFree10", body.cFree10));
                                   cmd.CommandText = sql;
                                   try
                                   {
                                       int count = cmd.ExecuteNonQuery();
                                       if (count <= 0)
                                       {
                                           log.Error("生成采购拒收单表体失败，受影响行数<=0；");
                                           throw new Exception("生成采购拒收单表体失败，受影响行数<=0；");
                                       }
                                   }
                                   catch (Exception ex)
                                   {
                                       log.Error("生成采购拒收单表体失败！采购到货单ID：" + head.ID + "；异常：" + ex.Message + "；SQL：\r\n" + sql, ex);
                                       throw new Exception("生成采购拒收单表体失败！采购到货单ID：" + head.ID + "；异常：" + ex.Message + "；SQL：\r\n" + sql, ex);
                                   }

                                   sql = string.Format(@"update pd set pd.fPoRefuseQuantity = isnull(pd.fPoRefuseQuantity,0)+{0}
  from dbo.PU_ArrivalVouchs a LEFT JOIN dbo.PO_Podetails pd ON a.iPOsID= pd.ID
  INNER JOIN dbo.PO_Pomain b ON pd.POID=b.POID
  INNER JOIN dbo.PU_ArrivalVouch c ON a.ID=c.ID where a.Autoid='" + body.DNDetailID + "' ", body.Quantity);
                                   cmd.CommandText = sql;
                                   cmd.ExecuteNonQuery();
                                   iChildId -= 1;
                               }
                               #endregion


                               #region 查询

                               sql = @"select DISTINCT a.ID as ID,a.ID as IDs,a.cCode as RJTCode,a.cVenCode VenCode,d.cVenName VenName,a.cDepCode DepCode,c.cDepName DepName
                            ,b.carrivalcode as DNCode ,a.cMaker as CreateUser ,a.cMakeTime as CreateDateTime
                            ,a.cverifier as Checker ,a.caudittime as CheckDateTime 
                              from PU_ArrivalVouch a 
                            left join PU_ArrivalVouchs 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.cverifier IS NOT NULL AND A.ID in({0})

                          select DISTINCT a.ID as IDs, b.AutoID as DetailID,b.ivouchrowno as Sequence  ,b.cInvCode as InvCode ,
                            b.iQuantity as Quantity ,b.iNum as Amount,a.cexch_name Currency,iOriCost UnitPrice,b.iCorId as DNDetailID 
,isnull(b.cItemCode,'') ProjectCode,
isnull(b.cbatch,'') cBatch,
'' version ,'' brand,
isnull(b.cFree1,'') as cFree1,
isnull(b.cFree2,'') as cFree2,
isnull(b.cFree3,'') as cFree3,
isnull(b.cFree4,'') as cFree4,
isnull(b.cFree5,'') as cFree5,
isnull(b.cFree6,'') as cFree6,
isnull(b.cFree7,'') as cFree7,
isnull(b.cFree8,'') as cFree8,
isnull(b.cFree9,'') as cFree9,
isnull(b.cFree10,'') as cFree10
                            from PU_ArrivalVouch a 
                             left join PU_ArrivalVouchs b on a.ID=b.ID
                             WHERE A.cverifier IS NOT NULL AND A.ID in({0}) ";
                               sql = string.Format(sql, iFatherIdTwo.TrimEnd(','));
                               if (ds != null)
                                   ds.Merge(DBHelper.SQlReturnDataSet(sql, cmd));
                               else
                                   ds = DBHelper.SQlReturnDataSet(sql, cmd);

                               #endregion


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

            szJson = JSON.DataSetToJson(ds, "details", "IDs");
           
            return szJson;
        }
        /// <summary>
        /// 回写委外拒收单
        /// </summary>
        /// <param name="cmd"></param>
        /// <param name="Lotnos"></param>
        /// <param name="info"></param>
        public string CreateWPUArrive(List<ICSOPUArrivalVouch> Bills)
        {
            string msg = "";
            string szJson = "";
            
            
            DataSet ds = null;
            string iFatherIdTwo = "";
            int num = 0;
       
            string connS = "";
            SqlConnection conn = new SqlConnection();

            SqlCommand cmd = new SqlCommand();


            if (Bills.Count <= 0)
            {
                throw new Exception("传送数据为空！");
            }
            bool isNG = false;
            LogInfo(Bills);
         

              List<string> result = Bills.Select(t => t.WorkPoint).Distinct().ToList();


              foreach (string WorkPoint in result)
              {
                  try
                  {
                      connS = string.Format(connString, WorkPoint);
                      conn = new System.Data.SqlClient.SqlConnection(connS);
                      conn.Open();
                      SqlTransaction sqlTran = conn.BeginTransaction();
                      cmd = new SqlCommand();
                      cmd.Transaction = sqlTran;
                      cmd.Connection = conn;
                      foreach (ICSOPUArrivalVouch head in Bills)
                      {
                          foreach (ICSOPUArrivalVouchs body in head.Vouchs)
                          {
                             
                              if (body.Quantity > 0)
                              {
                                  isNG = true;
                              }
                          }
                      }

                      if (isNG)
                      {
                          int sum = 0;
                          foreach (ICSOPUArrivalVouch head in Bills)
                          {
                              iFatherIdTwo = "";
                              if (WorkPoint != head.WorkPoint)
                              {
                                  continue;
                              }
                              ICSUserInfo userInfo = new ICSUserInfo();
                              userInfo = DBHelper.GetPersonInfo(head.User, cmd);
                              string[] ss = head.WorkPoint.Split('_');
                              ERPDB = ss[1];
                              string sql = "";
                              VouchKey key = new VouchKey();
                              //取得out库单的默认显示模版
                              string[] dd = CRNALL.Split('~');
                              string crdname = dd[0];
                              string carname = dd[1];
                              string surface = dd[2];
                              num = head.Vouchs.Count();
                              string cardnewcode = DBHelper.GetCardNumber(carname, cmd);
                              Dictionary<string, int> dic = DBHelper.GetAllCode("" + ERPDB + "", surface, "" + num + "", head.WorkPoint);
                              int iFatherId = Convert.ToInt32(dic["iFatherId"].ToString());
                              int iChildId = Convert.ToInt32(dic["iChildId"].ToString());
                              DateTime date = DateTime.Now;

                              string iBaseCodeLen = DBHelper.GetAllRDCode(cardnewcode, "" + date + "", "admin", "", head.WorkPoint);

                              #region 主表
                              sql = @"INSERT INTO PU_ArrivalVouch
(iVTid, ID, cCode, cPTCode, dDate, cVenCode, cDepCode, cPersonCode, cPayCode, cexch_name, iExchRate, iTaxRate,  cMemo, cBusType, cMaker, bNegative,
iDiscountTaxType, iBillType, cMakeTime, cAuditDate, caudittime, cverifier, iverifystateex, IsWfControlled, iflowid, iPrintCount, cpocode)
SELECT @iVTid, @ID, @cCode, cPTCode, CONVERT(NVARCHAR(10), GETDATE(), 23), cVenCode, cDepCode, cPersonCode, cPayCode, cexch_name, iExchRate, iTaxRate, cMemo, '委外加工', @User, 1,
iDiscountTaxType, 2, GETDATE(), CONVERT(NVARCHAR(10), GETDATE(), 23), GETDATE(), @User, 2, 0, 0, iPrintCount, null
FROM PU_ArrivalVouch WHERE 1=1 AND cCode = @headID ";
                              cmd.Parameters.Clear();
                              cmd.Parameters.Add(new SqlParameter("@iVTid", iChildId));
                              cmd.Parameters.Add(new SqlParameter("@ID", iFatherId));
                              cmd.Parameters.Add(new SqlParameter("@cCode", iBaseCodeLen));
                              cmd.Parameters.Add(new SqlParameter("@User", userInfo.UserName));
                              cmd.Parameters.Add(new SqlParameter("@headID", head.ODNCode));
                              cmd.CommandText = sql;
                              try
                              {
                                  int count = cmd.ExecuteNonQuery();
                                  if (count <= 0)
                                  {
                                      log.Error("生成委外拒收单表头失败，受影响行数<=0；");
                                      throw new Exception("生成委外拒收单表头失败，受影响行数<=0；");
                                  }
                              }
                              catch (Exception ex)
                              {
                                  log.Error("生成委外拒收单表头失败！到货单：" + head.ODNCode + "；异常：" + ex.Message + "；SQL：\r\n" + sql, ex);
                                  throw new Exception("生成委外拒收单表头失败！到货单：" + head.ODNCode + "；异常：" + ex.Message + "；SQL：\r\n" + sql, ex);
                              }
                              #endregion
                              iFatherIdTwo = "'" + iFatherId + "',";
                              #region 表体
                              foreach (ICSOPUArrivalVouchs body in head.Vouchs)
                              {
                                  iChildId -= 1;
                                  sql = @"INSERT INTO PU_ArrivalVouchs
(Autoid, ID, cInvCode, iQuantity, iOriCost, iOriTaxCost, iOriMoney, iOriTaxPrice, iOriSum, iCost, iMoney, iTaxPrice, iSum, iTaxRate,
iPOsID, fValidInQuan, fRealQuantity, fValidQuantity, fRetQuantity, fInValidInQuan, bGsp, fValidNum, fValidInNum, fRealNum, bTaxCost,
SoType, fInvalidInNum, iinvexchrate, cordercode, RejectSource, iExpiratDateCalcu, iordertype, ivouchrowno, bgift,
cFree1, cFree2, cFree3, cFree4, cFree5, cFree6, cFree7, cFree8, cFree9, cFree10,cItemCode,
cBatch, cDefine37, fKPQuantity, finValidQuantity, fRefuseQuantity, iProductType,bexigency,inum,iCorId,carrivalcode )
SELECT top 1 @Autoid, @ID1, @cInvCode, @iQuantity,pd.iUnitPrice,pd.iTaxPrice,round((pd.iTaxPrice*@iQuantity)/(1+pd.iPerTaxRate/100),2),
round(pd.iTaxPrice*@iQuantity,2)-round((pd.iTaxPrice*@iQuantity)/(1+pd.iPerTaxRate/100),2),round(pd.iTaxPrice*@iQuantity,2),round((pd.iTaxPrice/(1+pd.iPerTaxRate/100)*b.nflat),2),
round(round((pd.iTaxPrice*@iQuantity)/(1+pd.iPerTaxRate/100),2)*b.nflat,2),
round((round(pd.iTaxPrice*@iQuantity,2)-round((pd.iTaxPrice*@iQuantity)/(1+pd.iPerTaxRate/100),2))*b.nflat,2),round(round(pd.iTaxPrice*3402,2)*b.nflat,2),pd.iPerTaxRate,
pd.MODetailsID, 0, @iQuantity, @iQuantity, 0, 0, 0, null, null, null, 1,
0, null, 0, b.ccode, 0, 0, 0, @ivouchrowno, 0,
@cFree1, @cFree2, @cFree3, @cFree4, @cFree5, @cFree6, @cFree7, @cFree8, @cFree9, @cFree10,@cItemCode,
@Batch, @cDefine37, null, null, null, null, null,0,a.Autoid,c.cCode
from dbo.PU_ArrivalVouchs a 
LEFT JOIN dbo.OM_MODetails pd ON a.iPOsID = pd.MODetailsID
left JOIN dbo.OM_MOMain b ON pd.MOID = b.MOID
 left  JOIN dbo.PU_ArrivalVouch c ON a.ID=c.ID where a.Autoid='" + body.ODNDetailID + @"'
EXEC PROC_Update_OM_PUArrivalVouchs @ID= @ID1
";
                                  cmd.Parameters.Clear();
                                  cmd.Parameters.Add(new SqlParameter("@Autoid", iChildId));
                                  cmd.Parameters.Add(new SqlParameter("@ID1", iFatherId));
                                  cmd.Parameters.Add(new SqlParameter("@cInvCode", body.InvCode));
                                  cmd.Parameters.Add(new SqlParameter("@iQuantity", -body.Quantity));
                                  cmd.Parameters.Add(new SqlParameter("@ivouchrowno", body.Sequence));
                                  cmd.Parameters.Add(new SqlParameter("@Batch", body.BatchCode));
                                  cmd.Parameters.Add(new SqlParameter("@cItemCode", body.ProjectCode));
                                  cmd.Parameters.Add(new SqlParameter("@cDefine37", DateTime.Now.Date.AddDays(1 - DateTime.Now.Day).AddMonths(1).AddSeconds(-1)));
                                  cmd.Parameters.Add(new SqlParameter("@cFree1", body.cFree1));
                                  cmd.Parameters.Add(new SqlParameter("@cFree2", body.cFree2));
                                  cmd.Parameters.Add(new SqlParameter("@cFree3", body.cFree3));
                                  cmd.Parameters.Add(new SqlParameter("@cFree4", body.cFree4));
                                  cmd.Parameters.Add(new SqlParameter("@cFree5", body.cFree5));
                                  cmd.Parameters.Add(new SqlParameter("@cFree6", body.cFree6));
                                  cmd.Parameters.Add(new SqlParameter("@cFree7", body.cFree7));
                                  cmd.Parameters.Add(new SqlParameter("@cFree8", body.cFree8));
                                  cmd.Parameters.Add(new SqlParameter("@cFree9", body.cFree9));
                                  cmd.Parameters.Add(new SqlParameter("@cFree10", body.cFree10));
                                  cmd.CommandText = sql;
                                  try
                                  {
                                      int count = cmd.ExecuteNonQuery();
                                      if (count <= 0)
                                      {
                                          log.Error("生成委外拒收单表体失败，受影响行数<=0；");
                                          throw new Exception("生成委外拒收单表体失败，受影响行数<=0；");
                                      }
                                  }
                                  catch (Exception ex)
                                  {
                                      log.Error("生成委外拒收单表体失败！委外到货单：" + head.ODNCode + "；异常：" + ex.Message + "；SQL：\r\n" + sql, ex);
                                      throw new Exception("生成委外拒收单表体失败！委外到货单：" + head.ODNCode + "；异常：" + ex.Message + "；SQL：\r\n" + sql, ex);
                                  }

                                  sql = string.Format(@"update pd set pd.fPoRefuseQuantity = isnull(pd.fPoRefuseQuantity,0)+{0}
  from dbo.PU_ArrivalVouchs a LEFT JOIN dbo.PO_Podetails pd ON a.iPOsID= pd.ID
  where a.Autoid='" + body.ODNDetailID + "' ", body.Quantity);
                                  cmd.CommandText = sql;
                                  cmd.ExecuteNonQuery();
                              }
                              #endregion

                              #region 查询

                              sql = @"select DISTINCT a.ID as ID,a.ID as IDs,a.cCode as RJTCode,a.cVenCode VenCode,d.cVenName VenName,a.cDepCode DepCode,c.cDepName DepName
                            ,b.carrivalcode as DNCode ,a.cMaker as CreateUser ,a.cMakeTime as CreateDateTime
                            ,a.cverifier as Checker ,a.caudittime as CheckDateTime 
                              from PU_ArrivalVouch a 
															left join PU_ArrivalVouchs 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.cverifier IS NOT NULL AND A.ID in({0})

                          select DISTINCT a.ID as IDs, b.AutoID as DetailID,b.ivouchrowno as Sequence  ,b.cInvCode as InvCode ,
                            b.iQuantity as Quantity ,b.iNum as Amount,a.cexch_name Currency,iOriCost UnitPrice,b.iCorId as DNDetailID 
,isnull(b.cItemCode,'') ProjectCode,
isnull(b.cbatch,'') cBatch,
'' version ,'' brand,
isnull(b.cFree1,'') as cFree1,
isnull(b.cFree2,'') as cFree2,
isnull(b.cFree3,'') as cFree3,
isnull(b.cFree4,'') as cFree4,
isnull(b.cFree5,'') as cFree5,
isnull(b.cFree6,'') as cFree6,
isnull(b.cFree7,'') as cFree7,
isnull(b.cFree8,'') as cFree8,
isnull(b.cFree9,'') as cFree9,
isnull(b.cFree10,'') as cFree10
                            from PU_ArrivalVouch a 
                             left join PU_ArrivalVouchs b on a.ID=b.ID
                             WHERE A.cverifier IS NOT NULL AND A.ID in({0}) ";
                              sql = string.Format(sql, iFatherIdTwo.TrimEnd(','));
                              if (ds != null)
                                  ds.Merge(DBHelper.SQlReturnDataSet(sql, cmd));
                              else
                                  ds = DBHelper.SQlReturnDataSet(sql, cmd);

                              #endregion



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

            szJson = JSON.DataSetToJson(ds, "details", "IDs");
           
            return szJson;

        }
        public string Approve(List<ICSPUArrivalVouch> infos)
        {
            List<ICSPUArrivalVouch> szJson = new List<ICSPUArrivalVouch>();
            DataTable dt = null;
            DataTable dtNew = null;
            string connS = "";
            string json = "";
            if (infos.Count <= 0)
            {
                throw new Exception("传送数据为空！");
            }
            string res = string.Empty;
            SqlConnection conn = new SqlConnection();

            SqlCommand cmd = new SqlCommand();


            string sql = string.Empty;


             List<string> result = infos.Select(t => t.WorkPoint).Distinct().ToList();


             foreach (string WorkPoint in result)
             {
                 try
                 {
                     connS = string.Format(connString, WorkPoint);
                     conn = new System.Data.SqlClient.SqlConnection(connS);
                     conn.Open();
                     SqlTransaction sqlTran = conn.BeginTransaction();
                     cmd = new SqlCommand();
                     cmd.Transaction = sqlTran;
                     cmd.Connection = conn;
                     foreach (ICSPUArrivalVouch info in infos)
                     {
                         if (WorkPoint != info.WorkPoint)
                         {
                             continue;
                         }

                         ICSUserInfo userInfo = new ICSUserInfo();
                         userInfo = DBHelper.GetPersonInfo(info.User, cmd);

                         if (info.MTime < new DateTime(2000, 01, 01))
                             throw new Exception("请输入正确的操作时间：" + info.MTime);

                         sql = @"UPDATE PU_ArrivalVouch SET cVerifier ='" + userInfo.UserName + @"' ,
                            cAuditTime=CONVERT(VARCHAR(50),GETDATE(),112),cAuditDate=GETDATE() WHERE ID='{0}'";
                         sql = string.Format(sql, info.ID);
                         DBHelper.CmdExecuteNonQuery(sql, cmd, "未查询到对应数据！");

                     }
                     cmd.Transaction.Commit();
                 }
                 catch (Exception ex)
                 {
                     cmd.Transaction.Rollback();
                     log.Error(ex.Message);
                     throw new Exception(ex.Message);
                 }
                 finally
                 {
                     if (conn.State == ConnectionState.Open)
                     {
                         conn.Close();
                     }
                     conn.Dispose();
                 }
             }
            return json;

        }
        /// <summary>
        /// 删除请购单
        /// </summary>
        /// <param name="infos"></param>
        /// <returns></returns>
        public string Delete(List<ICSPUArrivalVouch> infos)
        {
            List<ICSPUArrivalVouch> szJson = new List<ICSPUArrivalVouch>();
            if (infos.Count <= 0)
            {
                throw new Exception("传送数据为空！");
            }
            string res = string.Empty;
            DataTable dtNew = null;
            string connS = "";
            SqlConnection conn = new SqlConnection();
            SqlCommand cmd = new SqlCommand();
            string sql = string.Empty;


              List<string> result = infos.Select(t => t.WorkPoint).Distinct().ToList();


              foreach (string WorkPoint in result)
              {
                  try
                  {
                      connS = string.Format(connString, WorkPoint);
                      conn = new System.Data.SqlClient.SqlConnection(connS);
                      conn.Open();
                      SqlTransaction sqlTran = conn.BeginTransaction();
                      cmd = new SqlCommand();
                      cmd.Transaction = sqlTran;
                      cmd.Connection = conn;
                      foreach (ICSPUArrivalVouch info in infos)
                      {
                          if (WorkPoint != info.WorkPoint)
                          {
                              continue;
                          }
                          if (info.MTime < new DateTime(2000, 01, 01))
                              throw new Exception("请输入正确的操作时间：" + info.MTime);
                          sql = @" DELETE PU_AppVouch WHERE ID={0}";
                          sql = string.Format(sql, info.ID);
                          DBHelper.CmdExecuteNonQuery(sql, cmd, "未查询到对应数据！");

                      }
                      cmd.Transaction.Commit();
                  }
                  catch (Exception ex)
                  {
                      cmd.Transaction.Rollback();
                      log.Error(ex.Message);
                      throw new Exception(ex.Message);
                  }
                  finally
                  {
                      if (conn.State == ConnectionState.Open)
                      {
                          conn.Close();
                      }
                      conn.Dispose();
                  }
              }
            return res;


        }
        /// <summary>
        /// 
        /// 记录日志
        /// </summary>
        /// <param name="Bills"></param>
        private void LogInfo(List<ICSPUArrivalVouch> Bills)
        {
            string HeadList = string.Empty;
            string BodyList = string.Empty;
            foreach (ICSPUArrivalVouch head in Bills)
            {
                HeadList += "\r\n 表头主键ID：" + head.ID + "，用户：" + head.User + "，站点：" + head.WorkPoint;
                foreach (ICSPUArrivalVouchs body in head.Vouchs)
                {
                    BodyList += "\r\n 表体主键ID： " + body.DNDetailID + "，数量：" + body.Quantity;
                }
            }
            log.Info(HeadList);
            log.Info(BodyList);
        }
        /// <summary>
        /// 
        /// 记录日志
        /// </summary>
        /// <param name="Bills"></param>
        private void LogInfo(List<ICSOPUArrivalVouch> Bills)
        {
            string HeadList = string.Empty;
            string BodyList = string.Empty;
            foreach (ICSOPUArrivalVouch head in Bills)
            {
                HeadList += "\r\n 表头主键ID：" + head.ID + "，用户：" + head.User + "，站点：" + head.WorkPoint;
                foreach (ICSOPUArrivalVouchs body in head.Vouchs)
                {
                    BodyList += "\r\n 表体主键ID： " + body.ODNDetailID + "，数量：" + body.Quantity;
                }
            }
            log.Info(HeadList);
            log.Info(BodyList);
        }
    }
}
