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

namespace ICSSoft.DataProject
{
    public class MOIssueDocApprove
    {
        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="Bills"></param>
        /// <returns></returns>
        public bool ConfirmRd11(List<ICSMOIssueDocApprove> Bills)
        {
            bool ResultFlag = false;
            string connS = "";
            SqlConnection conn = new SqlConnection();

            SqlCommand cmd = new SqlCommand();

            if (Bills.Count <= 0)
            {
                throw new Exception("传送数据为空!");
            }
            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 (ICSMOIssueDocApprove head in Bills)
                      {
                          if (WorkPoint != head.WorkPoint)
                              continue;
                          if (!DBHelper.IsInventoryConsolidation(cmd, head.WorkPoint))
                              throw new Exception("U8正在整理现存量,请稍后再试");

                          string sql = "";
                          ICSUserInfo userInfo = new ICSUserInfo();
                          userInfo = DBHelper.GetPersonInfo(head.User, cmd);

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

                          #region 审核其他入库单
                          sql = @"UPDATE dbo.rdrecord11 SET cHandler='" + userInfo.UserName + @"' ,
                            dVeriDate=CONVERT(VARCHAR(50),GETDATE(),112),dnverifytime=GETDATE() WHERE ID='" + head.ID + "'";
                          DBHelper.CmdExecuteNonQuery(sql, cmd, "审核核材料出库单失败!");
                          #endregion
                          sql = "select * from dbo.rdrecords11 a inner join rdrecord11 b on a.ID=b.ID  where a.ID='" + head.ID + "';";
                          DataTable dtChecks = DBHelper.SQlReturnData(sql, cmd);
                          if (head.UpdateStock)
                          {
                              #region 更新现存量
                              for (int i = 0; i < dtChecks.Rows.Count; i++)
                              {
                                  VouchKey key = new VouchKey();
                                  key.cBustypeUN = "领料";
                                  key.cVouchTypeUN = "11";
                                  key.TableName = "IA_ST_UnAccountVouch11";
                                  //DBHelper.UpdateCurrentStock(cmd, dtChecks.Rows[i]["cInvCode"].ToString(), dtChecks.Rows[i]["cWhCode"].ToString(), "", Convert.ToDecimal(dtChecks.Rows[i]["iQuantity"].ToString()), key);
                                  //DBHelper.UpdateCurrentStockNEW(cmd, dtChecks.Rows[i]["cInvCode"].ToString(), dtChecks.Rows[i]["cWhCode"].ToString(), dtChecks.Rows[i]["cBatch"].ToString(), Convert.ToDecimal(dtChecks.Rows[i]["iQuantity"].ToString()), dtChecks.Rows[i]["cFree1"].ToString(), dtChecks.Rows[i]["cFree2"].ToString(), dtChecks.Rows[i]["cFree3"].ToString(), dtChecks.Rows[i]["cFree4"].ToString(), dtChecks.Rows[i]["cFree5"].ToString(), dtChecks.Rows[i]["cFree6"].ToString(), dtChecks.Rows[i]["cFree7"].ToString(), dtChecks.Rows[i]["cFree8"].ToString(), dtChecks.Rows[i]["cFree9"].ToString(), dtChecks.Rows[i]["cFree10"].ToString(), key);
                                  DBHelper.UpdateCurrentStockCCGC(cmd, dtChecks.Rows[i]["cInvCode"].ToString(), dtChecks.Rows[i]["cWhCode"].ToString(), dtChecks.Rows[i]["cBatch"].ToString(), Convert.ToDecimal(dtChecks.Rows[i]["iAVQuantity"].ToString()), Convert.ToDecimal(dtChecks.Rows[i]["iAVNum"].ToString()), dtChecks.Rows[i]["cFree1"].ToString(),
                                        dtChecks.Rows[i]["cFree2"].ToString(), dtChecks.Rows[i]["cFree3"].ToString(), dtChecks.Rows[i]["cFree4"].ToString(), dtChecks.Rows[i]["cFree5"].ToString(), dtChecks.Rows[i]["cFree6"].ToString(), dtChecks.Rows[i]["cFree7"].ToString(), dtChecks.Rows[i]["cFree8"].ToString(), dtChecks.Rows[i]["cFree9"].ToString(), dtChecks.Rows[i]["cFree10"].ToString(),
                                        "", key, "", "", "", "", 0, 0, 0, 0, 0, 0, 0, 0, Convert.ToInt32(dtChecks.Rows[i]["ID"].ToString()), Convert.ToInt32(dtChecks.Rows[i]["AutoID"].ToString()));
                                  
                                  //                        //回写fInQuantity
                                  //                        sql = @"Update CurrentStock set fInQuantity=isnull(fInQuantity,0)-" + Convert.ToDecimal(dtChecks.Rows[i]["iQuantity"].ToString()) + @" 
                                  //                                where cInvCode='" + dtChecks.Rows[i]["cInvCode"].ToString() + "' and cWhCode='" + dtChecks.Rows[i]["cWhCode"].ToString() + "' ";
                                  //if (body.cBatch != null)
                                  //{
                                  //    sql += "and cBatch='" + body.cBatch + "'";
                                  //}
                                  //else
                                  //{
                                  //    sql += "and cBatch=''";
                                  //}
                                  //DBHelper.CmdExecuteNonQuery(sql, cmd, "回写fInQuantity失败!");
                                  if (head.UpdateTodoQuantity == true)
                                  {
                                      #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
                          }

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

        /// <summary>
        /// 记录日志
        /// </summary>
        /// <param name="Bills"></param>
        private void LogInfo(List<ICSMOIssueDocApprove> Bills)
        {
            string HeadList = string.Empty;
            string BodyList = string.Empty;
            foreach (ICSMOIssueDocApprove head in Bills)
            {
                HeadList += "\r\n 表头调拨单号:" + head.ID + ",用户:" + head.User + ",站点:" + head.WorkPoint;
                foreach (ICSMOIssueDocApprove body in Bills)
                {
                    BodyList += "\r\n 表体主键ID: " + body.ID + "";
                }
            }
            log.Info(HeadList);
            log.Info(BodyList);
        }
    }
}