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 SalesDeliveryNotice
    {
        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<ICSSalesDeliveryNotice> infos)
        {

            List<ICSSalesDeliveryNotice> szJson = new List<ICSSalesDeliveryNotice>();
            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 (ICSSalesDeliveryNotice info in infos)
                {
                    if (info.MTime < new DateTime(2000, 01, 01))
                        throw new Exception("请输入正确的操作时间：" + info.MTime);
                    sql = @" select a.DLID  ,a.cDLCode ,a.cCusCode,c.cCusName,a.cDepCode ,
                             d.cDepName,b.cordercode ,a.cMaker ,a.dcreatesystime ,
                             b.AutoID ,b.irowno,b.cInvCode ,b.iQuantity ,b.iNum ,b.iSOsID 
                             FROM dbo.DispatchList a 
                             INNER JOIN dbo.DispatchLists b ON a.DLID = b.DLID
                             LEFT JOIN dbo.Customer c ON a.cCusCode = c.cCusCode
							 left join Department d on a.cDepCode=d.cDepCode ";
                    if (!string.IsNullOrWhiteSpace(info.SDNCode))
                    {
                        sql += " and a.cDLCode='{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 + "，无信息！");
                    json = JsonConvert.SerializeObject(dt);
                }
                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="Bills"></param>
        /// <returns></returns>
        public string CerateSalesDeliveryNotice(List<ICSSalesDeliveryNotice> Bills)
        {
            string msg = "";
            DataTable dt = null;
            //bool ResultFlag = false;
            SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString);
            conn.Open();
            SqlTransaction sqlTran = conn.BeginTransaction();
            SqlCommand cmd = new SqlCommand();
            cmd.Transaction = sqlTran;
            cmd.Connection = conn;
            VouchKey key = new VouchKey();
            try
            {
                if (Bills.Count <= 0)
                {
                    throw new Exception("传送数据为空！");
                }
                LogInfo(Bills);
                foreach (ICSSalesDeliveryNotice head in Bills)
                {
                    string sql = "";

                    #region 销售发货单表头
                    int num = 0;
                    foreach (ICSSalesDeliveryNotice heads in Bills)
                    {
                        num = heads.details.Count();
                    }
                    string SO_SOMain_VT_ID = DBHelper.GetDefaultTemplate("05", cmd);//目标账套销售订单VT_ID模板
                    DateTime time = DateTime.Now;
                    Dictionary<string, int> dic = DBHelper.GetAllCode("" + ERPDB + "", "DelNote", "" + num + "");
                    int iFatherId = Convert.ToInt32(dic ["iFatherId"].ToString());
                    int iChildId = Convert.ToInt32(dic ["iChildId"] .ToString());
                    DateTime date = DateTime.Now;
                    string iBaseCodeLen = DBHelper.GetAllRDCode("05", "" + time + "", "admin");
                    sql = string.Format(@"INSERT INTO  dbo.DispatchList
                                (@DLID , @cDLCode , @cVouchType  , cSTCode ,CONVERT(NVARCHAR(50),GETDATE(),23) 
                                 , @cDepCode  ,SBVID  , @cSOCode , @cCusCode , cPayCode 
                                 , cSCCode, cCusOAddress , cexch_name , iExchRate , iTaxRate , 0 , bReturnFlag 
                                 , bFirst , cMemo  , cVerifier , cMaker  , iSale, (select cCusName from {0}.dbo.Customer where cCusCode='@cCusCode') 
                                 , iVTid , ufts , cBusType , cCloser , cAccounter , cCreChpName 
                                  , bIAFirst , ioutgolden , cgatheringplan , dCreditStart , dGatheringDate , icreditdays , bCredit 
                                  , caddcode , iverifystate , ireturncount  , iswfcontrolled , icreditstate , bARFirst 
                                  , cmodifier  , dmoddate  , dverifydate  , ccusperson  , dcreatesystime  , dverifysystime  , dmodifysystime 
                                  , csvouchtype  , iflowid , bsigncreate , bcashsale , cgathingcode , cChanger , cChangeMemo 
                                  , outid  , bmustbook , cBookDepcode , cBookType , bSaUsed , bneedbill , baccswitchflag 
                                  , iPrintCount , ccuspersoncode , cSourceCode , bsaleoutcreatebill , cSysBarCode , cCurrentAuditor 
                                  , csscode , cinvoicecompany , fEBweight , cEBweightUnit , cEBExpressCode  , iEBExpressCoID 
                                  , SeparateID , bNotToGoldTax , cEBTrnumber , cEBBuyer , cEBBuyerNote , ccontactname , cEBprovince 
                                  , cEBcity , cEBdistrict , cmobilephone , cInvoiceCusName , cweighter , dweighttime , cPickVouchCode 
                                  , cGCRouteCode)
                                    SELECT 
                                    @DLID , @cDLCode , @cVouchType  , cSTCode ,CONVERT(NVARCHAR(50),GETDATE(),23) 
                                    , @cDepCode  , 0  , @cSOCode , @cCusCode , cPayCode 
                                    , cSCCode, cCusOAddress , cexch_name , iExchRate , iTaxRate , 0 , bReturnFlag 
                                    , 0 , cMemo  , cVerifier , cMaker  , 0 , (select cCusName from dbo.Customer where cCusCode='@cCusCode') 
                                    , @iVTid , ufts , cBusType , cCloser , NULL , NULL 
                                  , 0 , null , cgatheringplan , CONVERT(NVARCHAR(50),GETDATE(),23) ,NULL , NULL , 0 
                                  , caddcode , iverifystate , ireturncount  , iswfcontrolled , icreditstate , 0 
                                  , NULL  , NULL  , NULL  , ccusperson  , CONVERT(NVARCHAR(50),GETDATE(),23)  , dverifysystime  , dmodifysystime 
                                  , csvouchtype  , iflowid , 0 , 0 , cgathingcode , NULL , NULL 
                                  , outid  , bmustbook , NULL , NULL , NULL , 0 , 0 
                                  , 0 , ccuspersoncode , NULL , 0 , cSysBarCode , cCurrentAuditor 
                                  , csscode , cinvoicecompany , NULL , NULL , NULL  , NULL 
                                  , NULL , 0 , NULL , NULL , NULL , NULL , NULL 
                                  , NULL , NULL , NULL , NULL , NULL , NULL , NULL 
                                  , NULL  FROM SO_SOMain a
                                    where a.cSOCode ='" + head.SOCode + "'");
                    cmd.Parameters.Clear();
                    cmd.Parameters.Add(new SqlParameter("@DLID", iFatherId));
                    cmd.Parameters.Add(new SqlParameter("@cDLCode", iBaseCodeLen));
                    cmd.Parameters.Add(new SqlParameter("@cVouchType","05"));
                    cmd.Parameters.Add(new SqlParameter("@cDepCode", head.DepCode));
                    cmd.Parameters.Add(new SqlParameter("@cSOCode", head.SOCode));
                    cmd.Parameters.Add(new SqlParameter("@cCusCode", head.CusCode));
                    cmd.Parameters.Add(new SqlParameter("@iVTid", SO_SOMain_VT_ID));
                    //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.SDNCode + "；异常：" + ex.Message + "；SQL：\r\n" + sql, ex);
                        throw new Exception("生成销售出库单表头失败！销售订单号：" + head.SDNCode + "；异常：" + ex.Message + "；SQL：\r\n" + sql, ex);
                    }
                    #endregion

                    #region 销售出库单表体
                    foreach (ICSSalesDeliveryNotices body in head.details)
                    {
                        #region 销售顶订单表体
                        sql = string.Format(@"INSERT INTO  dbo.DispatchLists
                                (AutoID , DLID , iCorID , cWhCode , cInvCode , iQuantity , iNum 
      , iQuotedPrice , iUnitPrice , iTaxUnitPrice , iMoney , iTax , iSum , iDisCount  , iNatUnitPrice 
      , iNatMoney , iNatTax  , iNatSum , iNatDisCount , iSettleNum , iSettleQuantity , iBatch , cBatch 
      , bSettleAll , cMemo  , iTB , dvDate , TBQuantity , TBNum , iSOsID , iDLsID 
      , KL , KL2 , cInvName , iTaxRate
      , fOutQuantity , fOutNum , cItemCode , cItem_class , fSaleCost , fSalePrice , cVenAbbName 
      , cItemName , cItem_CName
      , bIsSTQc  , iInvExchRate  , cUnitID   , cCode   , iRetQuantity     , fEnSettleQuan    , fEnSettleSum   , iSettlePrice   , dMDate  , bGsp 
      , cGspState , cSoCode  , cCorCode , iPPartSeqID , iPPartID  , iPPartQty  , cContractID  , cContractTagCode  , cContractRowGuid 
      , iMassDate , cMassUnit , bQANeedCheck  , bQAUrgency , bQAChecking  , bQAChecked , iQAQuantity , iQANum 
      , cCusInvCode , cCusInvName  , fsumsignquantity , fsumsignnum  , cbaccounter , bcosting , cordercode 
      , iorderrowno , fcusminprice , icostquantity , icostsum , ispecialtype , cvmivencode , iexchsum 
      , imoneysum , irowno , frettbquantity  , fretsum , iExpiratDateCalcu , dblPreExchMomey , dblPreMomey , idemandtype 
      , cdemandcode , cdemandmemo , cdemandid , idemandseq , cvencode , cReasonCode , cInvSN , iInvSNCount , bneedsign 
      , bsignover , bneedloss , flossrate , frlossqty , fulossqty , isettletype , crelacuscode , cLossMaker 
      , dLossDate , dLossTime , icoridlsid , fretoutqty  , body_outid , fVeriBillQty 
      , fVeriBillSum  , fVeriRetQty  , fVeriRetSum , fLastSettleQty 
      , fLastSettleSum , cBookWhcode    , cInVouchType     , cPosition   , fretqtywkp  , fretqtyykp , frettbqtyykp 
      , fretsumykp    , dkeepdate     , cSCloser    , isaleoutid  , bsaleprice  , bgift  , bmpforderclosed 
      , cbSysBarCode  , fxjquantity , fxjnum 
      , bIAcreatebill   , cParentCode  , cChildCode   , fchildqty  , fchildrate  , iCalcType , fappretwkpqty  , fappretwkpsum 
      , fappretykpqty  , fappretykpsum  , fappretwkptbqty  , fappretykptbqty  , irtnappid  , crtnappcode , fretailrealamount 
      , fretailsettleamount  , cFactoryCode , GCSourceId , GCSourceIds , cConfirmer  , dConfirmDate )
       SELECT 
       @AutoID , @DLID  , @cWhCode , @cInvCode , @iQuantity , @iNum 
      , iQuotedPrice , iUnitPrice , iTaxUnitPrice , iMoney , iTax , iSum , iDisCount  , iNatUnitPrice 
      , iNatMoney , iNatTax  , iNatSum , iNatDisCount   , NULL , NULL 
      , 0 , cMemo   , 0 , NULL , 0 , NULL , iSOsID , NULL 
      , KL , KL2 , cInvName , iTaxRate
      , fOutQuantity , fOutNum , cItemCode , cItem_class , fSaleCost , fSalePrice ,NUll 
      , cItemName , cItem_CName
      , 0  , iInvExchRate  , cUnitID   , NULL   , 0     , 0    , 0   , 0   , NULL  , 0 
      , NULL , @cSoCode  , NULL , iPPartSeqID , iPPartID  , iPPartQty  , cContractID  , cContractTagCode  , cContractRowGuid 
      , NULL , NULL , 0  , 0 , 0  , 0 , 0 , 0 
      , cCusInvCode , cCusInvName  , 0 , 0  , NULL , 0 , @cordercode 
      , NULL , fcusminprice , icostquantity , icostsum , NULL , NULL , iexchsum 
      , imoneysum , @irowno , 0  , 0 , NULL , 0 , 0 , NULL 
      , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL 
      , NULL , NULL , NULL , 0 , 0 , NULL , NULL , NULL 
      , NULL , NULL , NULL , NULL  , NULL , NULL 
      , NULL  , NULL  , NULL , NULL 
      , NULL , NULL    , NULL     , NULL   , NULL  , NULL , NULL 
      , NULL    , NULL     , NULL    , isaleoutid  , 1  , 0  , 0 
      , cbSysBarCode  , NULL , NULL 
      , 1   , NULL  , NULL   , NULL  , NULL  , NULL , NULL  , NULL 
      , NULL  , NULL  , NULL  , NULL  , NULL  , NULL , NULL 
      , NULL  , NULL , NULL , NULL , NULL  , NULL  FROM SO_SODetails a
                                    where a.AutoID ='" + body.SODetailID + "'");
                        cmd.Parameters.Clear();
                        cmd.Parameters.Add(new SqlParameter("@AutoID", iChildId));
                        cmd.Parameters.Add(new SqlParameter("@DLID", iFatherId));
                        cmd.Parameters.Add(new SqlParameter("@cInvCode", body.InvCode));

                        cmd.Parameters.Add(new SqlParameter("@iQuantity", body.Quantity));
                        cmd.Parameters.Add(new SqlParameter("@iNum",body.Amount));
                        cmd.Parameters.Add(new SqlParameter("@cSoCode", head.SOCode));
                        cmd.Parameters.Add(new SqlParameter("@cordercode", head.SOCode));
                        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--;
                    }
                    #endregion
                    sql = @"
                           select a.DLID  ,a.cDLCode ,a.cCusCode,c.cCusName,a.cDepCode ,
                             d.cDepName,b.cordercode ,a.cMaker ,a.dcreatesystime ,
                             b.AutoID ,b.irowno,b.cInvCode ,b.iQuantity ,b.iNum ,b.iSOsID 
                             FROM dbo.DispatchList a 
                             INNER JOIN dbo.DispatchLists b ON a.DLID = b.DLID
                             LEFT JOIN dbo.Customer c ON a.cCusCode = c.cCusCode
							 left join Department d on a.cDepCode=d.cDepCode  WHERE a.DLID = '{0}' ";
                    sql = string.Format(sql, iFatherId);
                    dt = DBHelper.SQlReturnData(sql, cmd);

                }
                msg = JsonConvert.SerializeObject(dt);
                cmd.Transaction.Commit();

            }
            catch (Exception ex)
            {
                cmd.Transaction.Rollback();
                log.Error(ex.Message);
                throw new Exception(ex.Message);
            }
            return msg;
        }
        /// <summary>
        /// 审核销售发货
        /// </summary>
        /// <param name="infos"></param>
        /// <returns></returns>
        public string Approve(List<ICSSalesDeliveryNotice> infos)
        {
            List<ICSSalesDeliveryNotice> szJson = new List<ICSSalesDeliveryNotice>();
            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 (ICSSalesDeliveryNotice info in infos)
                {
                    if (info.MTime < new DateTime(2000, 01, 01))
                        throw new Exception("请输入正确的操作时间：" + info.MTime);
                    sql = @"UPDATE  DispatchList SET cMaker ='" + info.User + @"' ,
                            dverifysystime =CONVERT(VARCHAR(50),GETDATE(),112),dverifydate =GETDATE() WHERE DLID='{0}'";
                    sql = string.Format(sql, info.ID);
                    DBHelper.CmdExecuteNonQuery(sql, cmd, "未查询到对应数据！");
                }
                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 Delete(List<ICSSalesDeliveryNotice> infos)
        {
            List<ICSSalesDeliveryNotice> szJson = new List<ICSSalesDeliveryNotice>();
            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 (ICSSalesDeliveryNotice info in infos)
                {
                    if (info.MTime < new DateTime(2000, 01, 01))
                        throw new Exception("请输入正确的操作时间：" + info.MTime);
                    sql = @" DELETE  DispatchList WHERE DLID={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();
            }
        }
        /// <summary>
        /// 
        /// 记录日志
        /// </summary>
        /// <param name="Bills"></param>
        private void LogInfo(List<ICSSalesDeliveryNotice> Bills)
        {
            string HeadList = string.Empty;
            string BodyList = string.Empty;
            foreach (ICSSalesDeliveryNotice head in Bills)
            {
                HeadList += "\r\n 表头主键ID：" + head.ID + "，用户：" + head.User;
                foreach (ICSSalesDeliveryNotices body in head.details)
                {
                    BodyList += "\r\n 表体主键ID：数量：" + body.Quantity;
                }
            }
            log.Info(HeadList);
            log.Info(BodyList);
        }

    }
}
