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 OtherOutDoc
    {
        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 ConfirmRd09(List<ICSOtherOutDoc> Bills)
        {
            bool ResultFlag = false;
            DataTable dtNew = null;
            string connS = "";
            SqlConnection conn = new SqlConnection();

            SqlCommand cmd = new SqlCommand();

            
                if (Bills.Count <= 0)
                {
                    throw new Exception("传送数据为空!");
                }
                LogInfo(Bills);
                foreach (ICSOtherOutDoc head in Bills)
                {
                    try
                    {
                    connS = string.Format(connString, head.WorkPoint);
                    conn = new System.Data.SqlClient.SqlConnection(connS);
                    conn.Open();
                    SqlTransaction sqlTran = conn.BeginTransaction();
                    cmd = new SqlCommand();
                    cmd.Transaction = sqlTran;
                    cmd.Connection = conn;

                    string[] ss = head.WorkPoint.Split('_');
                    ERPDB = ss[1];

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

                    #region 检验单号是否存在
                    sql = "select * from RdRecord09 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.RdRecord09 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.RdRecords09 a inner join RdRecord09 b on a.ID=b.ID where b.ID='" + head.ID + "';";
                    DataTable dtChecks = DBHelper.SQlReturnData(sql, cmd);
                    #region 更新现存量
                    for (int i = 0; i < dtChecks.Rows.Count; i++)
                    {
                        //判断物料批号与现存量表批号是否一致、数量不能超过现存量物料数量
                        sql = @"SELECT cBatch,iQuantity from CurrentStock WHERE cInvCode='" + dtChecks.Rows[i]["cInvCode"].ToString() + "'AND cBatch=''and cWhCode='" + dtChecks.Rows[i]["cWhCode"].ToString() + "'";
                        DataTable dtItem = DBHelper.SQlReturnData(sql, cmd);
                        if (dtItem != null && dtItem.Rows.Count > 0)
                        {
                            //if (!dtItem.Rows[0]["cBatch"].ToString().Equals(body.cBatch))
                            //{
                            //    throw new Exception("物料条码的批号与U8现存量物料批号不一致,物料:" + body.cInvCode);
                            //}
                            if (Convert.ToDecimal(dtItem.Rows[0]["iQuantity"].ToString()) < Convert.ToDecimal(dtChecks.Rows[i]["iQuantity"].ToString()))
                            {
                                throw new Exception("物料条码的数量大于U8现存量物料数量,物料:" + dtChecks.Rows[i]["cInvCode"].ToString());
                            }

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


                        VouchKey key = new VouchKey();
                        key.cBustypeUN = "其他出库";
                        key.cVouchTypeUN = "09";
                        key.TableName = "IA_ST_UnAccountVouch09";
                        DBHelper.UpdateCurrentStock(cmd, dtChecks.Rows[i]["cInvCode"].ToString(), dtChecks.Rows[i]["cWhCode"].ToString(),"", -Convert.ToDecimal(dtChecks.Rows[i]["iQuantity"].ToString()), key);

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

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

                    cmd.Transaction.Commit();
                    }
            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<ICSOtherOutDoc> Bills)
       {
           string HeadList = string.Empty;
           string BodyList = string.Empty;
           foreach (ICSOtherOutDoc head in Bills)
           {
               HeadList += "\r\n 表头主键ID:" + head.ID + ",用户:" + head.User + ",站点:" + head.WorkPoint +"";
              
           }
           log.Info(HeadList);
           log.Info(BodyList);
       }

    }
}