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 PurchaseRequisition
    {
        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<ICSPurchaseRequisition> infos)
        {
            List<ICSPurchaseRequisition> szJson = new List<ICSPurchaseRequisition>();
            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 (ICSPurchaseRequisition 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 = @" select a.ID,a.cCode,a.cDepCode ,c.cDepName,a.cMaker ,a.cMakeTime ,a.cVerifier ,a.cAuditTime,
                             b.AutoID ,b.irowno ,b.cInvCode ,b.fQuantity ,b.dRequirDate ,b.dArriveDate ,b.cexch_name ,b.fUnitPrice   
                             from PU_AppVouch a
                             inner join PU_AppVouchs b on a.ID =b.ID
                             left join Department c on a.cDepCode=c.cDepCode WHERE 1=1";
                          if (!string.IsNullOrWhiteSpace(info.PRCode))
                          {
                              sql += " and a.cCode='{0}'";
                          }
                          if (!string.IsNullOrWhiteSpace(info.MTime.ToString()))
                          {
                              sql += " and ISNULL(a.dCloseTime ,ISNULL(a.cChangAuditTime,ISNULL(a.cAuditTime, ISNULL(a.cModifyTime, a.cmaketime))))>='{1}'";
                          }
                          if (!string.IsNullOrWhiteSpace(info.User))
                          {
                              sql += "and a.CMAKER='{2}'";
                          }
                          sql = string.Format(sql, info.PRCode, info.MTime, userInfo.UserName);
                          dt = DBHelper.SQlReturnData(sql, cmd);

                          if (dt.Rows.Count <= 0 || dt == null)
                              throw new Exception("请购单：" + info.PRCode + "，无信息！");
                          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>
        /// 创建请购单
        /// </summary>
        /// <param name="Bills"></param>
        /// <returns></returns>
        public string CreatePurchaseRequisition(List<ICSPurchaseRequisition> Bills)
        {
            string msg = "";
            DataTable dt = null;
            DataTable dtNew = null;
            string connS = "";
            SqlConnection conn = new SqlConnection();

            VouchKey key = new VouchKey();
            int num = 0;
        


            SqlCommand cmd = new SqlCommand();



            if (Bills.Count <= 0)
            {
                throw new Exception("传送数据为空！");
            }
            LogInfo(Bills);
            //MergeObject(Bills, cmd);

            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 (ICSPurchaseRequisition head in Bills)
                    {
                        num = head.details.Count();
                        if (WorkPoint != head.WorkPoint)
                            continue;
                        cmd.CommandTimeout = 300;
                        string[] ss = head.WorkPoint.Split('_');
                        ERPDB = ss[1];
                        Dictionary<string, int> dic = DBHelper.GetAllCode("" + ERPDB + "", "PuApp", "" + 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("27", "" + date + "", "admin", "", head.WorkPoint);
                        string sql = string.Empty;
                        #region 请购单表头
                        sql = @"Insert Into PU_AppVouch
                                    (ivtid,id,ccode,ddate,cdepcode,
                                    cpersoncode,cbustype,cmaker,cverifier,
                                    iverifystateex,ireturncount,iswfcontrolled,cAuditDate,iPrintCount,
                                    cMakeTime,cAuditTime
                                    ) 
                                    Values 
                                    ('8171',@ID,@ccode,CONVERT(VARCHAR(10),GETDATE(),23),@cdepcode,
                                    null,'普通采购',@cmaker,@cverifier,
                                    '2','0','0','','0',
                                    GETDATE(),GETDATE()
                                    )" + Environment.NewLine;
                        cmd.Parameters.Clear();
                        cmd.Parameters.Add(new SqlParameter("@ID", iFatherId));
                        cmd.Parameters.Add(new SqlParameter("@ccode", iBaseCodeLen));
                        cmd.Parameters.Add(new SqlParameter("@cdepcode", head.DepCode));
                        cmd.Parameters.Add(new SqlParameter("@cverifier", head.User));
                        cmd.Parameters.Add(new SqlParameter("@cmaker", head.User));
                        //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 请购单表体
                        int irowno = 0;
                        foreach (ICSPurchaseRequisitions body in head.details)
                        {
                            iChildId -= 1;
                            sql += @"IF NOT EXISTS(
	                                SELECT cInvCode 
	                                FROM Inventory
	                                WHERE cInvCode='@cInvCode'
                                )
                                BEGIN
	                                RAISERROR('存货编码：@cInvCode 不存在！',16,0)
                                END" + Environment.NewLine;
                            sql = @"Insert Into PU_AppVouchs
                                        (id,autoid,cvencode,cinvcode,fquantity,
                                        funitprice,ipertaxrate,ftaxprice,fmoney,drequirdate,
                                        darrivedate,iReceivedQTY,cdefine22,cdefine23,btaxcost,
                                        iReceivedNum,cpersoncodeexec,cdepcodeexec,cexch_name,iexchrate,
                                        ioricost,ioritaxcost,iorimoney,ioritaxprice,iorisum,
                                        imoney,itaxprice,ivouchrowno) 
                                        VALUES 
                                        (@ID,@AutoID,NULL,@cInvCode,@fQuantity,
                                        NULL,17,NULL,NULL,@drequirdate,
                                        @darrivedate,'0',NULL,NULL,1,
                                        0,NULL,NULL,N'人民币',1,
                                        NULL,NULL,NULL,NULL,NULL,
                                        NULL,NULL,@ivouchrowno)" + Environment.NewLine;
                            cmd.Parameters.Clear();

                            cmd.Parameters.Add(new SqlParameter("@AutoID", iChildId));
                            cmd.Parameters.Add(new SqlParameter("@cInvCode", body.InvCode));
                            cmd.Parameters.Add(new SqlParameter("@ID", iFatherId));
                            cmd.Parameters.Add(new SqlParameter("@fQuantity", body.Quantity));
                            cmd.Parameters.Add(new SqlParameter("@drequirdate", body.RequirDate));
                            cmd.Parameters.Add(new SqlParameter("@darrivedate", body.ArriveDate));
                            cmd.Parameters.Add(new SqlParameter("@ivouchrowno", 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);
                            }

                        }
                        sql = @"
select a.ID,a.cCode,a.cDepCode ,c.cDepName,a.cMaker ,a.cMakeTime ,a.cVerifier ,a.cAuditTime,
                             b.AutoID ,b.irowno ,b.cInvCode ,b.fQuantity ,b.dRequirDate ,b.dArriveDate ,b.cexch_name ,b.fUnitPrice   
                             from PU_AppVouch a
                             inner join PU_AppVouchs b on a.ID =b.ID
                             left join Department c on a.cDepCode=c.cDepCode where a.id='{0}' ";
                        sql = string.Format(sql, iFatherId);
                        dt = DBHelper.SQlReturnData(sql, cmd);
                        #endregion
                        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();
                }
            }
            msg = JsonConvert.SerializeObject(dtNew);
            return msg;

        }
        /// <summary>
        /// 审核请购单
        /// </summary>
        /// <param name="infos"></param>
        /// <returns></returns>
        public string Approve(List<ICSPurchaseRequisition> infos)
        {
            List<ICSPurchaseRequisition> szJson = new List<ICSPurchaseRequisition>();
            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 (ICSPurchaseRequisition info in infos)
                       {
                           if (WorkPoint != info.WorkPoint)
                               continue;
                           if (info.MTime < new DateTime(2000, 01, 01))
                               throw new Exception("请输入正确的操作时间：" + info.MTime);
                           sql = @"UPDATE  dbo.PU_AppVouch SET cVerifier  ='" + info.User + @"' ,
                            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<ICSPurchaseRequisition> infos)
        {
            List<ICSPurchaseRequisition> szJson = new List<ICSPurchaseRequisition>();
            if (infos.Count <= 0)
            {
                throw new Exception("传送数据为空！");
            }
            string res = string.Empty;
            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 (ICSPurchaseRequisition 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  PU_AppVouch.ID='" + info.ID + "'";
                         sql += @"delete  PU_AppVouchs  where  PU_AppVouchs.ID='" + 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;
        }
        private void LogInfo(List<ICSPurchaseRequisition> Bills)
        {
            string HeadList = string.Empty;
            string BodyList = string.Empty;
            foreach (ICSPurchaseRequisition head in Bills)
            {
                HeadList += "\r\n 表头主键ID：" + head.ID + "，部门：" + head.DepCode + "，用户：" + head.User + "，站点：" + head.WorkPoint;
                foreach (ICSPurchaseRequisitions body in head.details)
                {
                    //  BodyList += "\r\n 表体主键ID： " + body. + "，数量：" + body.Quantity;
                }
            }
            log.Info(HeadList);
            log.Info(BodyList);
        }
    }
}
