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
{
    /// <summary>
    /// 归还(生成其他入库单)
    /// </summary>
     public  class ReturnDoc
    {
          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 string ConfirmRd08(List<ICSReturnDoc> Bills)
        {
            string msg = string.Empty;
            string sql = string.Empty;
            SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString);
            string iFatherIdTwo = "";
            conn.Open();
            int num = 0;
            SqlTransaction sqlTran = conn.BeginTransaction();
            SqlCommand cmd = new SqlCommand();
            cmd.Transaction = sqlTran;
            cmd.Connection = conn;
            try
            {
                //List<RdRecord09> Vouchers = new List<RdRecord09>();
                foreach (ICSReturnDoc head in Bills)
                {
                    num = head.details.Count();
                    Dictionary<string, int> dic = DBHelper.GetAllCode("" + ERPDB + "", "rd", "" + num + "");
                    int iFatherId = Convert.ToInt32(dic["iFatherId"].ToString());
                    int iChildId = Convert.ToInt32(dic["iChildId"].ToString());
                    DateTime date = DateTime.Now;
                    string iBaseCodeLen = DBHelper.GetAllRDCode("0302", "" + date + "", "admin");
                    string cRDcode = DBHelper.GetRDCode("样品出库", cmd);

                    //取得out库单的默认显示模版
                    string DEF_ID08 = DBHelper.GetDefaultTemplate("0302", cmd);
                    //取得其他出库单单据 表头ID,表体DID
                    VouchKey key08 = new VouchKey();
                    #region  其他出库单表头
                    sql = @"INSERT INTO dbo.RdRecord08
                        (ID,bRdFlag,cVouchType,cBusType,cSource,cBusCode,cWhCode,dDate,cCode,cRdCode,
                        cHandler,cMemo,bTransFlag,cMaker,dVeriDate,bpufirst,biafirst,VT_ID,bIsSTQc,bOMFirst,
                        bFromPreYear,bIsComplement,iDiscountTaxType,ireturncount,
                        iverifystate,iswfcontrolled,dnmaketime,dnverifytime,bredvouch,cSourceLs,cDepCode)
                    VALUES(@ID,1,'08','其他出库','借出借用单',@cBusCode,@cWhCode,CONVERT(NVARCHAR(15),GETDATE(),23),@cCode,@cRdCode,
                    		@cHandler,@cMemo,'0',@cMaker,CONVERT(NVARCHAR(15),GETDATE(),23),'0','0',
                    		@VT_ID,'0','0','0','0','0','0','0','0',GETDATE(),GETDATE(),'0','1',@cDepCode) ";

                    cmd.Parameters.Clear();
                    cmd.Parameters.Add(new SqlParameter("@ID", iFatherId));
                    cmd.Parameters.Add(new SqlParameter("@cWhCode", head.WHCode));
                    cmd.Parameters.Add(new SqlParameter("@cCode", iBaseCodeLen));
                    cmd.Parameters.Add(new SqlParameter("@cRdCode", cRDcode));
                    cmd.Parameters.Add(new SqlParameter("@cDepCode", head.DepCode));
                    cmd.Parameters.Add(new SqlParameter("@cHandler", head.User));
                    cmd.Parameters.Add(new SqlParameter("@cMemo", head.User));
                    cmd.Parameters.Add(new SqlParameter("@cMaker", head.User));
                    cmd.Parameters.Add(new SqlParameter("@VT_ID", DEF_ID08));
                    cmd.Parameters.Add(new SqlParameter("@cBusCode", head.SourceCode));
                    cmd.CommandText = sql;
                    try
                    {
                        cmd.ExecuteNonQuery();
                    }
                    catch (Exception ex)
                    {
                        log.Error("生成其他出库单失败!SQL:\r\n" + sql);
                        throw new Exception("程序异常,请联系开发人员!");
                    }
                    #endregion
                    foreach (ICSBrrowDocs body in head.details)
                    {
                        #region 3.5.1 表体
                        sql = @"INSERT INTO dbo.rdrecords08
                        (AutoID,ID,cInvCode,iQuantity,iSOutQuantity,iSOutNum,iFlag,iDebitIDs,iNQuantity,
                        cMassUnit,bLPUseFree,iRSRowNO,iOriTrackID,bCosting,bVMIUsed,iExpiratDateCalcu,iordertype,irowno,cbaccounter,cBatch,iPUnitCost,iPPrice)
                                VALUES(@AutoID,@ID,@cInvCode,@iQuantity,'0','0','0',@iDebitIDs,'0',
                                		 '0','0','0','0','1','0','0','0',@irowno,null,null,null,null )";
                        cmd.Parameters.Clear();
                        cmd.Parameters.Add(new SqlParameter("@AutoID", iChildId));
                        cmd.Parameters.Add(new SqlParameter("@ID", iFatherId));
                        cmd.Parameters.Add(new SqlParameter("@cInvCode", body.InvCode));
                        cmd.Parameters.Add(new SqlParameter("@iQuantity", body.Quantity));
                        cmd.Parameters.Add(new SqlParameter("@irowno", body.Sequence));
                        cmd.Parameters.Add(new SqlParameter("@iDebitIDs", body.SourceDetailID));
                        cmd.CommandText = sql;
                        try
                        {
                            cmd.ExecuteNonQuery();
                        }
                        catch (Exception ex)
                        {
                            log.Error("生成其他出库单表体失败!SQL:\r\n" + sql);
                            throw new Exception("程序异常,请联系开发人员!");
                        }
                        #endregion
                        //更新现存量
                        key08.cBustypeUN = "调拨入库";
                        key08.cVouchTypeUN = "08";
                        key08.TableName = "IA_ST_UnAccountVouch08";

                        DBHelper.UpdateCurrentStock(cmd, body.InvCode, head.WHCode, "", body.Quantity, key08);
                        iChildId--;
                        sql = @"UPDATE a SET iQtyRK =ISNULL(iQtyRK,0)+" + body.Quantity + @" 
                                FROM dbo.HY_DZ_BorrowOutBacks a
                                WHERE a.Autoid='" + body.SourceDetailID + "'";
                        DBHelper.CmdExecuteNonQuery(sql, cmd, "回写借入单数量失败!");
                    }
                    iFatherIdTwo += "'" + iFatherId + "',";
                }
                #region 查询
                sql = @"  
                            select a.ID as ID,a.ID as IDs,cBusCode as SourceCode ,
                           cCode as OtherInCode,a.cDepCode,c.cDepName,a.cWhCode,d.cWhName,
                            cSource as SourceType,cMaker as CreateUser,dnmaketime as CreateDateTime,
                            cHandler as Checker,dnverifytime as CheckDateTime
                            from rdrecord08 a
                            left join Department c on a.cDepCode=c.cDepCode
                            left join Warehouse d on a.cWhCode=d.cWhCode
                            WHERE a.ID in ({0})

                           select a.ID as IDs,b.AutoID as DetailID,irowno as Sequence,b.cInvCode as InvCode 
                           ,iQuantity as Quantity,b.iDebitIDs as SourceDetailID,iNum as Amount
                            from rdrecord08 a
                            left join rdrecords08 b on a.ID=b.ID
                            left join Department c on a.cDepCode=c.cDepCode
                            left join Warehouse d on a.cWhCode=d.cWhCode
                             WHERE a.ID in ({0})";
                sql = string.Format(sql, iFatherIdTwo.TrimEnd(','));
                DataSet ds = DBHelper.SQlReturnDataSet(sql, cmd);
                string RelationName = "details";
                DataRelation dr = new DataRelation(RelationName, ds.Tables[0].Columns["IDs"], ds.Tables[1].Columns["IDs"]);
                ds.Relations.Add(dr);
                msg = DBHelper.DataSetToJson(ds, RelationName);
                #endregion
                cmd.Transaction.Commit();
                return msg;

            }
            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<ICSReturnDoc> Bills)
        {
            string HeadList = string.Empty;
            string BodyList = string.Empty;
            foreach (ICSReturnDoc head in Bills)
            {
                HeadList += "\r\n 借用单号:" + head.SourceCode + ",用户:" + head.User + "";

            }
            log.Info(HeadList);
            log.Info(BodyList);
        }
    
    }
}