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 MOIssueDocNegatives
    {
        private static log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        private static string connString = System.Configuration.ConfigurationManager.AppSettings["ERPConnStr"];
        private static string ERPDB = System.Configuration.ConfigurationManager.AppSettings["ERPDB"];
        private static string Type = System.Configuration.ConfigurationManager.AppSettings["Type"];
       public string Get(List<ICSMOIssueDocNegative> infos)
       {
           List<ICSMOIssueDocNegative> szJson = new List<ICSMOIssueDocNegative>();
           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 (ICSMOIssueDocNegative info in infos)
               {
                   if (info.MTime < new DateTime(2000, 01, 01))
                       throw new Exception("请输入正确的操作时间：" + info.MTime);
                   sql = @"  select a.ID,iMPoIds,iordercode,cCode,a.cDepCode,c.cDepName,a.cWhCode,d.cWhName,cSource,cMaker,dnmaketime,cHandler,dnverifytime,cSourceCodeLs,b.AutoID ,irowno,b.cInvCode,iQuantity,f.MoDId,iNum,g.MoCode from rdrecord11 a
                            left join rdrecords11 b on a.ID=b.ID
                            left join Department c on a.cDepCode=c.cDepCode
                            left join Warehouse d on a.cWhCode=d.cWhCode
                            left join mom_moallocate e on b.iMPoIds=e.AllocateId
                            INNER JOIN dbo.mom_orderdetail f ON e.MoDId=f.MoDId
                            INNER JOIN dbo.mom_order g ON f.MoId=g.MoId where b.iQuantity<0";
                   if (!string.IsNullOrWhiteSpace(info.IssueNEGCode))
                   {
                       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.IssueNEGCode, info.MTime, info.User);
                   dt = DBHelper.SQlReturnData(sql, cmd);
                   json = JsonConvert.SerializeObject(dt);
                   if (dt.Rows.Count<=0||dt==null)
                       throw new Exception("材料出库单：" + info.IssueNEGCode + "，无信息！");
                  
               }
               cmd.Transaction.Commit();
               return json;
           }
           catch (Exception ex)
           {
               cmd.Transaction.Rollback();
               log.Error(ex.Message);
               throw new Exception(ex.Message);
           }
           finally
           {
               if (conn.State == ConnectionState.Open)
               {
                   conn.Close();
               }
               conn.Dispose();
           }
       }
       public string  CreateRd11(List<ICSMOIssueDocNegative> Bills)
       {
           string msg = "";
           string sql = string.Empty;
           string iFatherIdTwo = string.Empty;
           SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString);
           conn.Open();
           VouchKey key = new VouchKey();
           int num = 0;
           SqlTransaction sqlTran = conn.BeginTransaction();
           SqlCommand cmd = new SqlCommand();
           cmd.Transaction = sqlTran;
           cmd.Connection = conn;
           cmd.CommandTimeout = 300;
           try
           {
               if (Bills.Count <= 0)
               {
                   throw new Exception("传送数据为空！");
               }
               LogInfo(Bills);
               //MergeObject(Bills, cmd);
               LogInfo(Bills);
               foreach (ICSMOIssueDocNegative head in Bills)
               {
                   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");
                   string DEF_ID = DBHelper.GetDefaultTemplate(Type, cmd);
         
                   //                   #region 判断工单是否已关闭
                   //                   sql = @"SELECT isnull(CloseUser,'') as CloseUser from mom_orderdetail a 
                   //                                           inner join mom_order b on a.MoId=b.MoId where b.MoId='" + head.DetailID + "' ";
                   //                   DataTable dtClose = DBHelper.SQlReturnData(sql, cmd);
                   //                   if (dtClose != null && dtClose.Rows.Count > 0)
                   //                   {
                   //                       if (!string.IsNullOrEmpty(dtClose.Rows[0][0].ToString()))
                   //                       {
                   //                           throw new Exception("该工单行已关闭，无法领料！");
                   //                       }
                   //                   }
                   //                   #endregion
                   #region 材料出库单表头
                   sql = @"INSERT INTO dbo.rdrecord11
                            ( ID ,bRdFlag ,cVouchType ,cBusType ,cSource ,cWhCode ,dDate ,
                            cCode ,cRdCode ,cDepCode,cHandler ,bTransFlag ,cMaker ,
                            dVeriDate ,bpufirst ,biafirst ,VT_ID ,bIsSTQc 
                            ,cPsPcode ,cMPoCode ,iproorderid ,bFromPreYear ,
                            bIsLsQuery ,bIsComplement ,iDiscountTaxType ,ireturncount ,iverifystate ,
                            iswfcontrolled ,dnmaketime ,dnverifytime ,bredvouch ,iPrintCount,
                            iMQuantity)

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

                   #region 材料出库单表体
                   foreach (ICSMOIssueDocNegatives body in head.details)
                   {
                       sql = @"INSERT INTO dbo.rdrecords11
                                    ( AutoID ,ID ,cInvCode ,iQuantity ,cBatch ,iFlag ,
                                        cItemCode ,cName ,iNQuantity ,iMPoIds ,bLPUseFree ,
                                        iOriTrackID ,bCosting ,bVMIUsed ,cmocode ,invcode ,imoseq ,
                                        iopseq ,iExpiratDateCalcu ,iorderdid ,iordertype ,isotype ,
                                        ipesodid ,ipesotype ,cpesocode ,ipesoseq ,irowno ,
                                        bcanreplace ,iposflag)
                            SELECT @AutoID,@ID,a.InvCode,@iQuantity,@cBatch,0,
                                	null,null,a.Qty,a.AllocateId,0,
                                	0,1,0,c.MoCode,b.InvCode,b.SortSeq,
                                	'0000',0,0,0,0,
                                	a.AllocateId,'7',c.MoCode,b.SortSeq,@irowno,
                                    0,null
                            FROM dbo.mom_moallocate a
                            INNER JOIN dbo.mom_orderdetail b ON a.MoDId=b.MoDId
                            INNER JOIN dbo.mom_order c ON b.MoId=c.MoId
                            WHERE a.AllocateId='" + body.SourceDetailID + "'";
                       cmd.Parameters.Clear();

                       cmd.Parameters.Add(new SqlParameter("@AutoID", iChildId));
                       cmd.Parameters.Add(new SqlParameter("@ID", iFatherId));
                       cmd.Parameters.Add(new SqlParameter("@iQuantity", -body.Quantity));
                       cmd.Parameters.Add(new SqlParameter("@cCode", iBaseCodeLen));
                       cmd.Parameters.Add(new SqlParameter("@cBatch", ""));
                       cmd.Parameters.Add(new SqlParameter("@irowno", body.Sequence));

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

                       #region 回写工单子件已领数量
                       sql = "update mom_moallocate set IssQty=isnull(IssQty,0)+" + body.Quantity + " where AllocateId='" + body.SourceDetailID + "' ";
                       DBHelper.CmdExecuteNonQuery(sql, cmd, "回写工单子件已领数量失败！");
                       #endregion
                       iChildId--;

                   }
                   #endregion
                   iFatherIdTwo += "'" + iFatherId + "',";

               }
               #region 查询
               sql = @"  
                            select a.ID as ID,a.ID as IDs,cMPoCode as SourceCode ,
                           cCode as IssueNEGCode,a.cDepCode,c.cDepName,a.cWhCode,d.cWhName,
                            cSource as SourceType,cMaker as CreateUser,dnmaketime as CreateDateTime,
                            cHandler as Checker,dnverifytime as CheckDateTime
                            from rdrecord11 a
                            left join Department c on a.cDepCode=c.cDepCode
                            left join Warehouse d on a.cWhCode=d.cWhCode
                            WHERE a.ID in ({0})

                           select a.ID as IDs,b.AutoID as DetailID,irowno as Sequence,b.cInvCode as InvCode 
                           ,iQuantity as Quantity,e.AllocateId as SourceDetailID,iNum as Amount
                            from rdrecord11 a
                            left join rdrecords11 b on a.ID=b.ID
                            left join Department c on a.cDepCode=c.cDepCode
                            left join Warehouse d on a.cWhCode=d.cWhCode
                            left join mom_moallocate e on b.iMPoIds=e.AllocateId
                            INNER JOIN dbo.mom_orderdetail f ON e.MoDId=f.MoDId
                            INNER JOIN dbo.mom_order g ON f.MoId=g.MoId WHERE a.ID in ({0})";
               sql = string.Format(sql, iFatherIdTwo.TrimEnd(','));
               DataSet ds = DBHelper.SQlReturnDataSet(sql, cmd);
               string RelationName = "details";
               DataRelation dr = new DataRelation(RelationName, ds.Tables[0].Columns["IDs"], ds.Tables[1].Columns["IDs"]);
               ds.Relations.Add(dr);
               msg = DBHelper.DataSetToJson(ds, RelationName);
               cmd.Transaction.Commit();
               return msg;
               #endregion
           }

           catch (Exception ex)
           {
               cmd.Transaction.Rollback();
               log.Error(ex.Message);
               throw new Exception(ex.Message);
           }
           finally
           {
               if (conn.State == ConnectionState.Open)
               {
                   conn.Close();
               }
               conn.Dispose();
           }
       }
       public string Approve(List<ICSMOIssueDocNegative> infos)
       {
           List<ICSMOIssueDocNegative> szJson = new List<ICSMOIssueDocNegative>();
           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 (ICSMOIssueDocNegative info in infos)
               {
                   if (info.MTime < new DateTime(2000, 01, 01))
                       throw new Exception("请输入正确的操作时间：" + info.MTime);
                   sql = @"UPDATE  dbo.rdrecord11 SET cHandler ='" + info.User + @"' ,
                            dnmodifytime  =CONVERT(VARCHAR(50),GETDATE(),112),dModifyDate  =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<ICSMOIssueDocNegative> infos)
       {
           List<ICSMOIssueDocNegative> szJson = new List<ICSMOIssueDocNegative>();
           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 (ICSMOIssueDocNegative 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();
           }
       }
       private void LogInfo(List<ICSMOIssueDocNegative> Bills)
       {
           string HeadList = string.Empty;
           string BodyList = string.Empty;
           foreach (ICSMOIssueDocNegative head in Bills)
           {
               HeadList += "\r\n 表头主键ID：" + head.ID + "，仓库：" + head.WHCode + "，用户：" + head.User;
               foreach (ICSMOIssueDocNegatives body in head.details)
               {
                   BodyList += "\r\n 表体主键ID： " + body.SourceDetailID + "，数量：" + body.Quantity;
               }
           }
           log.Info(HeadList);
           log.Info(BodyList);
       }

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