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
{
    /// <summary>
    /// 采购订单
    /// </summary>
    public class PurchaseOrder
    {
        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<ICSPurchaseOrder> infos)
        {
            
            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 (ICSPurchaseOrder info in infos)
                {
                    if (info.MTime < new DateTime(2000, 01, 01))
                        throw new Exception("请输入正确的操作时间：" + info.MTime);
                    sql = @" SELECT A.CPOID,A.CVENCODE,A.CDEPCODE,A.CAPPCODE,C.CDEPNAME,D.CVENNAME,A.CMAKER,A.CMAKETIME,A.CVERIFIER,A.CAUDITTIME,
                             B.IROWNO,B.CINVCODE ,B.IQUANTITY ,B.INUM,B.IRECEIVEDQTY,B.DARRIVEDATE,A.CEXCH_NAME,B.ITAXPRICE,B.INATUNITPRICE,B.IUNITPRICE
                             FROM PO_POMAIN A
                             INNER JOIN PO_PODETAILS B ON A.POID=B.POID
                             INNER JOIN DEPARTMENT C ON A.CDEPCODE=C.CDEPCODE
                             INNER JOIN VENDOR D ON A.CVENCODE=D.CVENCODE WHERE 1=1";
                    if (!string.IsNullOrWhiteSpace(info.POCode))
                    {
                        sql += " and a.CPOID='{0}'";
                    }
                    if (!string.IsNullOrWhiteSpace(info.MTime.ToString()))
                    {
                        sql += " and ISNULL(b.cbCloseTime,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.POCode,info.MTime,info.User);
                    dt = DBHelper.SQlReturnData(sql, cmd);
                    json = JsonConvert.SerializeObject(dt);
                    if (dt.Rows.Count <= 0 || dt == null)
                        throw new Exception("采购订单：" + info.PRCode + "，无信息！");
                }
                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  CreateICSPurchaseOrder(List<ICSPurchaseOrder> infos)
        {
            int num = 0;
            foreach (ICSPurchaseOrder head in infos)
            {
                num = head.details.Count();
            }
            Dictionary<string, int> dic = DBHelper.GetAllCode("" + ERPDB + "", "PoMain", "" + num + "");
            int iFatherId = Convert.ToInt32(dic["iFatherId"].ToString());
            int iChildId = Convert.ToInt32(dic["iChildId"].ToString());
            DateTime date = DateTime.Now;
            string iBaseCodeLen = DBHelper.GetAllRDCode("88", "" + date + "", "admin");
            string szJson = "";
            DataTable dt = null;
            string sql = "";
            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
            {
                #region 采购订单表头
                foreach (ICSPurchaseOrder info in infos)
                {
                    if (string.IsNullOrWhiteSpace(info.PRCode))
                    {
                        sql = @"Insert Into dbo.PO_Pomain
                                     (cPOID ,dPODate ,cVenCode ,cexch_name ,
                              nflat ,iTaxRate ,iCost ,iBargain ,
                              cMemo ,cState ,cMaker ,cVerifier ,
                              POID ,iVTid ,cBusType ,iDiscountTaxType ,
                              iverifystateex ,ireturncount ,IsWfControlled ,cmaketime ,
                              cAuditTime ,cAuditDate ,iPrintCount,cDefine14,
                              cPersonCode,cDepCode)
                              Values 
                              ( @cPOID,CONVERT(NVARCHAR(15),GETDATE(),23),@cVenCode,'人民币',
                                 '','',0,0,
                                 '',1,'','',
                                @POID,'','普通采购',0,
                                2,0,0,GETDATE(),
                                GETDATE()  ,CONVERT(NVARCHAR(15),GETDATE(),23)  ,0 ,'',
                                '',@cDepCode)" + Environment.NewLine;
                        cmd.Parameters.Clear();
                        cmd.Parameters.Add("@cPOID", iBaseCodeLen);
                         cmd.Parameters.Add("@cVenCode", info.VenCode);
                        cmd.Parameters.Add("@POID", iFatherId);
                        cmd.Parameters.Add("@cDepCode", "''");
                    }
                    else {
                        sql += @"INSERT INTO  dbo.PO_Pomain
                             (cPOID ,dPODate ,cVenCode ,cexch_name ,
                              nflat ,iTaxRate ,iCost ,iBargain ,
                              cMemo ,cState ,cMaker ,cVerifier ,
                              POID ,iVTid ,cBusType ,iDiscountTaxType ,
                              iverifystateex ,ireturncount ,IsWfControlled ,cmaketime ,
                              cAuditTime ,cAuditDate ,iPrintCount,cDefine14,
                              cPersonCode,cDepCode)
                              SELECT 
                              @cPOID,CONVERT(NVARCHAR(15),GETDATE(),23),@cVenCode ,'人民币' ,
                              '' AS nflat ,'' ,0 AS iCost ,0 AS iBargain,
                              cMemo , '1' AS cState ,cMaker ,cVerifier ,
                              @POID ,'' AS iVTid ,'普通采购' AS cBusType ,0 AS iDiscountTaxType ,
                              2 AS iverifystateex ,0 AS ireturncount ,0 AS IsWfControlled ,GETDATE() AS cmaketime ,
                             GETDATE() AS cAuditTime ,CONVERT(NVARCHAR(15),GETDATE(),23) AS cAuditDate ,0 AS iPrintCount ,ID,
                            cPersonCode,@cDepCode FROM dbo.PU_AppVouch where  ccode='" + info.PRCode + "'";
                        cmd.Parameters.Clear();
                        cmd.Parameters.Add("@cPOID", iBaseCodeLen);
                        cmd.Parameters.Add("@cVenCode", info.VenCode);
                        cmd.Parameters.Add("@POID", iFatherId);
                        cmd.Parameters.Add("@cDepCode", info.DepCode);
                    }
                    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 (var detail in info.details)
                    {
                        if (string.IsNullOrWhiteSpace(info.PRCode))
                        {
                            sql = @"
                                 Insert Into PO_Podetails
                                 (ID,cInvCode ,iQuantity ,iNum ,iUnitPrice ,iMoney ,iTax ,iSum ,
                                 iNatUnitPrice ,iNatMoney ,iNatTax ,iNatSum ,dArriveDate ,
                                 iReceivedQTY ,iReceivedNum ,iReceivedMoney ,iPerTaxRate ,
                                 bGsp ,POID ,iTaxPrice ,bTaxCost ,cSource ,SoType ,cupsocode ,
                                 iordertype ,ivouchrowno ,bgift)
                                 VALUES 
                                 ('',@cInvCode,@iQuantity,@iNum,@iUnitPrice,'','','',
                                 0,0,'','',@dArriveDate,
                                 '','',0,'',
                                 0,@ID,'',0,'','','' NULL,@ivouchrowno,'')" + Environment.NewLine;
                            cmd.Parameters.Clear();
                            cmd.Parameters.Add("@ID", iFatherId);
                            cmd.Parameters.Add("@cInvCode", detail.InvCode);
                            cmd.Parameters.Add("@Code", info.PRCode);
                            cmd.Parameters.Add("@ivouchrowno", detail.Sequence);
                            cmd.Parameters.Add("@iQuantity", detail.Quantity);
                            cmd.Parameters.Add("@iNum", detail.Amount);
                            cmd.Parameters.Add("@iUnitPrice", detail.UnitPrice);
                            cmd.Parameters.Add("@dArriveDate", detail.ArriveDate);
                        }
                        sql = @"INSERT INTO PO_Podetails
                                 (ID,cInvCode ,iQuantity ,iNum ,iUnitPrice ,iMoney ,iTax ,iSum ,
                                 iNatUnitPrice ,iNatMoney ,iNatTax ,iNatSum ,dArriveDate ,
                                 iReceivedQTY ,iReceivedNum ,iReceivedMoney ,iPerTaxRate ,
                                 bGsp ,POID ,iTaxPrice ,bTaxCost ,cSource ,SoType ,cupsocode ,
                                 iordertype ,ivouchrowno ,bgift)

                                 SELECT AutoID ,@cInvCode ,@iQuantity ,@iNum ,@iUnitPrice ,iMoney ,iOriTaxPrice,iOriSum ,
                                 0  ,0 ,iTaxPrice  ,'' ,@dArriveDate ,
                                 iReceivedQTY ,iReceivedNum ,0 ,iPerTaxRate ,
                                 0 ,@ID ,iOriTaxCost ,0 ,cSource ,SoType ,@Code ,
                                 iordertype ,@ivouchrowno ,''
		                         FROM PU_AppVouchs  WHERE AutoID='" + detail.PRDetailID + "'";
                        cmd.Parameters.Clear();
                        cmd.Parameters.Add("@ID", iFatherId);
                        cmd.Parameters.Add("@cInvCode", detail.InvCode);
                        cmd.Parameters.Add("@Code", info.PRCode);
                        cmd.Parameters.Add("@ivouchrowno", detail.Sequence);
                        cmd.Parameters.Add("@iQuantity", detail.Quantity);
                        cmd.Parameters.Add("@iNum", detail.Amount);
                        cmd.Parameters.Add("@iUnitPrice", detail.UnitPrice);
                        cmd.Parameters.Add("@dArriveDate", detail.ArriveDate);
                        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 查询
                    cmd.Transaction.Commit();
                    sql = @"select a.POID,a.cPOID,a.cVenCode,c.cVenName,
                            a.cDepCode,d.cDepName,a.cappcode,a.cMaker, 
                            a.cmaketime ,a.cVerifier,a.cAuditDate,b.ID,
                            b.ivouchrowno ,b.cInvCode , b.iQuantity, b.iNum, 
                            b.fPoArrQuantity, b.dArriveDate ,'人民币' ,b.iTaxPrice ,
                            b.iAppIds   from po_pomain a
							left join  PO_Podetails b on a.POID=b.POID
							left join Vendor c on a.cVenCode=c.cVenCode
							left join  Department d on a.cDepCode=d.cDepCode where a.poid='{0}' ";
                    sql = string.Format(sql, iFatherId);
                    dt = DBHelper.SQlReturnData(sql, cmd); 
                    #endregion
                }
                szJson = JsonConvert.SerializeObject(dt);
                return szJson;
            }
            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 Approve(List<ICSPurchaseOrder> infos)
        {
            List<ICSPurchaseOrder> szJson = new List<ICSPurchaseOrder>();
            DataTable dt = null;
            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 (ICSPurchaseOrder info in infos)
                {
                    if (info.MTime < new DateTime(2000, 01, 01))
                        throw new Exception("请输入正确的操作时间：" + info.MTime);
                    sql = @"UPDATE  PO_POMAIN SET cVerifier ='" + info.User + @"' ,
                            cAuditTime=CONVERT(VARCHAR(50),GETDATE(),112),cAuditDate=GETDATE() WHERE POID='" + info.ID + "'";
                    sql = string.Format(sql, ERPDB);
                    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();
            }
        }
        /// <summary>
        /// 删除采购订单
        /// </summary>
        /// <param name="infos"></param>
        /// <returns></returns>
        public string Delete(List<ICSPurchaseOrder> infos)
        {
            List<ICSPurchaseOrder> szJson = new List<ICSPurchaseOrder>();
            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 (ICSPurchaseOrder info in infos)
                {
                    if (info.MTime < new DateTime(2000, 01, 01))
                        throw new Exception("请输入正确的操作时间：" + info.MTime);
                    sql = @" DELETE  PO_POMAIN WHERE POID='{0}'";
                    sql = string.Format(sql, 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();
            }
        }
    }
}
