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
{
    public class SalesOrder
    {
        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"];
        string bustype = string.Empty;
        /// <summary>
        /// 获取销售出库单
        /// </summary>
        /// <param name="infos"></param>
        /// <returns></returns>
        public string Get(List<ICSSalesOrder> infos)
        {

            List<ICSSalesOrder> szJson = new List<ICSSalesOrder>();
            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;
            foreach (ICSSalesOrder info in infos)
            {
                try
                {
                    connS = string.Format(connString, info.WorkPoint);
                    conn = new System.Data.SqlClient.SqlConnection(connS);
                    conn.Open();
                    SqlTransaction sqlTran = conn.BeginTransaction();
                    cmd = new SqlCommand();
                    cmd.Transaction = sqlTran;
                    cmd.Connection = conn;
                    if (info.MTime < new DateTime(2000, 01, 01))
                        throw new Exception("请输入正确的操作时间:" + info.MTime);
                    sql = @"select a.ID ,a.cSOCode ,a.cCusCode,c.cCusName,a.cDepCode ,
                            d.cDepName,a.cMaker ,a.dcreatesystime ,a.cVerifier ,a.dverifydate ,
                            b.AutoID,b.iRowNo ,b.cInvCode ,b.iQuantity ,b.iNum ,b.iFHQuantity ,
                            b.dPreDate  from SO_SOMain a 
                            inner join SO_SODetails b on a.ID =b.ID 
                            Left join Customer c on a.cCusCode=c.cCusCode
                            left join Department d on a.cDepCode=d.cDepCode ";
                    if (!string.IsNullOrWhiteSpace(info.SOCode))
                    {
                        sql += " and a.cSOCode='{0}'";
                    }
                    if (!string.IsNullOrWhiteSpace(info.MTime.ToString()))
                    {
                        sql += " and ISNULL(a.dnmodifytime ,ISNULL(a.dverifydate , ISNULL(a.dnmodifytime , a.dcreatesystime )))>='{1}'";
                    }
                    if (!string.IsNullOrWhiteSpace(info.User))
                    {
                        sql += "and a.CMAKER='{2}'";
                    }
                    sql = string.Format(sql, info.SOCode, info.MTime, info.User);
                    dt = DBHelper.SQlReturnData(sql, cmd);
                    if (dt.Rows.Count <= 0 || dt == null)
                        throw new Exception("销售出库单号:" + info.SOCode + ",无信息!");
                    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 CerateSalesOrder(List<ICSSalesOrder> Bills)
        {
            string msg = "";
            DataTable dt = null;
            DataTable dtNew = null;
            string connS = "";
            //bool ResultFlag = false;
            SqlConnection conn = new SqlConnection();

            SqlCommand cmd = new SqlCommand();

            VouchKey key = new VouchKey();

            if (Bills.Count <= 0)
            {
                throw new Exception("传送数据为空!");
            }
            LogInfo(Bills);
            foreach (ICSSalesOrder head in Bills)
            {
                try
                {
                    string sql = "";
                    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];
                    #region 销售订单表头
                    int num = 0;
                    foreach (ICSSalesOrder heads in Bills)
                    {
                        num = heads.details.Count();
                    }
                    string SO_SOMain_VT_ID = DBHelper.GetDefaultTemplate("17", cmd);//目标账套销售订单VT_ID模板
                    DateTime time = DateTime.Now;
                    Dictionary<string, int> dic = DBHelper.GetAllCode("" + ERPDB + "", "SalesOrder", "" + 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("17", "" + time + "", "admin", head.WorkPoint);
                    sql = string.Format(@"INSERT INTO  dbo.SO_SOMain
                                ( cSTCode ,dDate ,cSOCode ,cCusCode ,cDepCode ,
                                  cCusOAddress ,cexch_name ,iExchRate ,iTaxRate ,
                                  cMemo ,iStatus ,cMaker ,cVerifier ,bDisFlag ,
                                  cDefine1 ,cDefine2 ,cDefine3 ,cDefine4 ,cDefine5 ,
                                  cDefine6 ,cDefine7 ,cDefine8 ,cDefine9 ,cDefine10 ,
                                  bReturnFlag ,cCusName ,bOrder ,ID ,iVTid ,cBusType ,
                                  cDefine11 ,cDefine12 ,cDefine13 ,cDefine14 ,
                                  cDefine15 ,cDefine16 ,dPreMoDateBT ,dPreDateBT ,
                                  cgatheringplan ,caddcode ,iverifystate ,
                                  iswfcontrolled ,dverifydate ,ccusperson ,
                                  dcreatesystime ,dverifysystime ,bcashsale ,
                                  bmustbook ,cinvoicecompany ,cbcode)
                        SELECT '10',CONVERT(NVARCHAR(50),GETDATE(),23),a.cPOID,@cCusCode,'999',
                        		(select cCusOAddress from {0}.dbo.Customer where cCusCode='@cCusCode'),a.cexch_name,a.nflat,a.iTaxRate,
                        		a.cMemo,1,a.cMaker,a.cVerifier,0,
                        		a.cDefine1,a.cDefine2,a.cDefine3,a.cDefine4,a.cDefine5,
                        		a.cDefine6,a.cDefine7,a.cDefine8,a.cDefine9,a.cDefine10,
                        		0,(select cCusName from {0}.dbo.Customer where cCusCode='@cCusCode'),0,@ID,@iVTid,'普通销售',
                        		a.cDefine11,'{1}',a.cDefine13,a.cDefine14,
                        		a.cDefine15,a.cDefine16,CONVERT(NVARCHAR(50),GETDATE(),23),CONVERT(NVARCHAR(50),GETDATE(),23),
                        		NULL,NULL,0,
                        		0,a.cAuditDate,(select cCusPerson from {0}.dbo.Customer where cCusCode='@cCusCode'),
                        		GETDATE(),a.cAuditTime,0,
                        		0,'@cCusCode','10'
                        FROM  dbo.PO_Pomain a        
                             
                        where a.POID='" + head.POID + "'");
                    cmd.Parameters.Clear();
                    cmd.Parameters.Add(new SqlParameter("@ID", iFatherId));
                    cmd.Parameters.Add(new SqlParameter("@iVTid", SO_SOMain_VT_ID));
                    cmd.Parameters.Add(new SqlParameter("@cCusCode", head.CusCode));
                    //cmd.Parameters.Add(new SqlParameter("@dDate", data.dMate));
                    cmd.CommandText = sql;
                    try
                    {
                        int count = cmd.ExecuteNonQuery();
                        if (count <= 0)
                        {
                            log.Error("生成销售订单表头失败,受影响行数<=0;");
                            throw new Exception("生成销售订单表头失败,受影响行数<=0;");
                        }
                    }
                    catch (Exception ex)
                    {
                        log.Error("生成销售订单表头失败!销售订单号:" + head.SOCode + ";异常:" + ex.Message + ";SQL:\r\n" + sql, ex);
                        throw new Exception("生成销售订单表头失败!销售订单号:" + head.SOCode + ";异常:" + ex.Message + ";SQL:\r\n" + sql, ex);
                    }



                    #endregion

                    #region 销售出库单表体
                    foreach (ICSSalesOrders body in head.details)
                    {

                        #region 销售顶订单表体
                        sql = string.Format(@"INSERT INTO {0}.dbo.SO_SODetails
                                    ( cSOCode ,cInvCode ,dPreDate ,iQuantity ,iNum,
                                      iQuotedPrice ,iUnitPrice ,
                            		  iTaxUnitPrice ,iMoney ,
                                      iTax ,iSum ,
                                      iDisCount ,iNatUnitPrice ,
                                      iNatMoney ,iNatTax ,
                                      iNatSum ,iNatDisCount ,
                                      iFHNum ,iFHQuantity ,iFHMoney ,
                                      iSOsID ,KL ,KL2 ,
                                      cInvName ,iTaxRate ,cDefine22 ,cDefine23 ,
                                      cDefine24 ,cDefine25 ,cDefine26 ,cDefine27 ,
                                      ID ,cDefine28 ,cDefine29 ,cDefine30 ,cDefine31 ,
                                      cDefine32 ,cDefine33 ,cDefine34 ,cDefine35 ,
                                      cDefine36 ,cDefine37  ,fSalePrice ,
                                      dPreMoDate ,iRowNo ,fcusminprice ,foutquantity ,
                                      foutnum ,bOrderBOM ,bOrderBOMOver ,idemandtype ,
                                      busecusbom ,fVeriDispQty ,fVeriDispSum ,bsaleprice ,bgift )
                            SELECT c.cPOID,a.cInvCode,CONVERT(NVARCHAR(50),GETDATE(),23),a.iQuantity,a.iNum,
                            		a.iTaxPrice,a.iUnitPrice,
                            		a.iTaxPrice,a.iMoney,
                            		a.iTax,a.iSum,
                            		0,a.iNatUnitPrice,
                            		a.iNatMoney,a.iNatTax,
                            		a.iNatSum,0,
                            		0,0,a.iMoney,
                            		@iSOsID,100,100,
                            		b.cInvName,a.iPerTaxRate,a.cDefine22,a.cDefine23,
                            		a.cDefine24,a.cDefine25,a.cDefine26,a.cDefine27,
                            		@ID,a.ID,a.cDefine29,a.cDefine30,a.cDefine31,
                            		a.cDefine32,a.cDefine33,a.cDefine34,a.cDefine35,
                            		a.cDefine36,a.cDefine37,0,
                            		CONVERT(NVARCHAR(50),GETDATE(),23),@iRowNo,0,NULL,
                            		NULL,0,0,1,
                            		0,0,a.iSum,1,0
                            FROM dbo.PO_Podetails a 
                            LEFT JOIN dbo.Inventory b ON a.cInvCode=b.cInvCode
                            LEFT JOIN  dbo.PO_Pomain c ON a.POID=c.POID
                            WHERE a.ID='" + body.PODetailID + "'");
                        cmd.Parameters.Clear();
                        cmd.Parameters.Add(new SqlParameter("@iSOsID", iChildId));
                        cmd.Parameters.Add(new SqlParameter("@ID", iFatherId));
                        cmd.Parameters.Add(new SqlParameter("@iRowNo", body.Sequence));
                        //cmd.Parameters.Add(new SqlParameter("@dDate", data.dMate));
                        cmd.CommandText = sql;
                        try
                        {
                            int count = cmd.ExecuteNonQuery();
                            if (count <= 0)
                            {
                                log.Error("生成销售订单表体失败,受影响行数<=0;");
                                throw new Exception("生成销售订单表体失败,受影响行数<=0;");
                            }
                        }
                        catch (Exception ex)
                        {
                            log.Error("生成销售订单表体失败!销售订单号:" + head.SOCode + ";异常:" + ex.Message + ";SQL:\r\n" + sql, ex);
                            throw new Exception("生成销售订单表体失败!销售订单号:" + head.SOCode + ";异常:" + ex.Message + ";SQL:\r\n" + sql, ex);
                        }
                        #endregion
                        iChildId -= 1;
                    }
                    #endregion
                    sql = @"
                            select a.ID ,a.cSOCode ,a.cCusCode,c.cCusName,a.cDepCode ,
                            d.cDepName,a.cMaker ,a.dcreatesystime ,a.cVerifier ,a.dverifydate ,
                            b.AutoID,b.iRowNo ,b.cInvCode ,b.iQuantity ,b.iNum ,b.iFHQuantity ,
                            b.dPreDate  from SO_SOMain a 
                            inner join SO_SODetails b on a.ID =b.ID 
                            Left join Customer c on a.cCusCode=c.cCusCode
                            left join Department d on a.cDepCode=d.cDepCode WHERE a.ID = '{0}' ";
                    sql = string.Format(sql, iFatherId);
                    dt = DBHelper.SQlReturnData(sql, cmd);
                    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<ICSSalesOrder> infos)
        {
            List<ICSSalesOrder> szJson = new List<ICSSalesOrder>();
            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;
            foreach (ICSSalesOrder info in infos)
            {
                try
                {
                    connS = string.Format(connString, info.WorkPoint);
                    conn = new System.Data.SqlClient.SqlConnection(connS);
                    conn.Open();
                    SqlTransaction sqlTran = conn.BeginTransaction();
                    cmd = new SqlCommand();
                    cmd.Transaction = sqlTran;
                    cmd.Connection = conn;
                    if (info.MTime < new DateTime(2000, 01, 01))
                        throw new Exception("请输入正确的操作时间:" + info.MTime);
                    sql = @"UPDATE  SO_SOMain SET cMaker ='" + info.User + @"' ,
                            dverifysystime =CONVERT(VARCHAR(50),GETDATE(),112),dverifydate =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<ICSSalesOrder> infos)
        {
            List<ICSSalesOrder> szJson = new List<ICSSalesOrder>();
            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;
            foreach (ICSSalesOrder info in infos)
            {
                try
                {
                    connS = string.Format(connString, info.WorkPoint);
                    conn = new System.Data.SqlClient.SqlConnection(connS);
                    conn.Open();
                    SqlTransaction sqlTran = conn.BeginTransaction();
                    cmd = new SqlCommand();
                    cmd.Transaction = sqlTran;
                    cmd.Connection = conn;
                    if (info.MTime < new DateTime(2000, 01, 01))
                        throw new Exception("请输入正确的操作时间:" + info.MTime);
                    sql = @" DELETE  SO_SOMain 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 res;
        }
        /// <summary>
        /// 
        /// 记录日志
        /// </summary>
        /// <param name="Bills"></param>
        private void LogInfo(List<ICSSalesOrder> Bills)
        {
            string HeadList = string.Empty;
            string BodyList = string.Empty;
            foreach (ICSSalesOrder head in Bills)
            {
                HeadList += "\r\n 表头主键ID:" + head.ID + ",用户:" + head.User + ",站点:" + head.WorkPoint;
                foreach (ICSSalesOrders body in head.details)
                {
                    BodyList += "\r\n 表体主键ID:数量:" + body.Quantity;
                }
            }
            log.Info(HeadList);
            log.Info(BodyList);
        }

    }
}