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 TransferDoc
    {
        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 bool ConfirmTrans(List<ICSTransferDoc> Bills)
        {
            bool ResultFlag = false;
            //int num = 0;
            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
            {
                if (Bills.Count <= 0)
                {
                    throw new Exception("传送数据为空！");
                }
                LogInfo(Bills);
                //MergeObject(Bills, cmd);
                foreach (ICSTransferDoc head in Bills)
                {
                    string sql = "";
                    ICSUserInfo userInfo = new ICSUserInfo();
                    userInfo = DBHelper.GetPersonInfo(head.User, cmd);
                    string cIWhCode = string.Empty;
                    string cOWhCode = string.Empty;
                    #region 检查
                    sql = "select * from dbo.TransVouch where ID='" + head.ID + "';";
                    DataTable dtCheck = DBHelper.SQlReturnData(sql, cmd);
                    if (dtCheck != null && dtCheck.Rows.Count > 0)
                    {
                        string cHandler = dtCheck.Rows[0]["cVerifyPerson"].ToString();
                        if (!string.IsNullOrEmpty(cHandler))
                        {
                            throw new Exception("调拨单ID：" + head.ID + "不是开立状态！");
                        }
                        cIWhCode = dtCheck.Rows[0]["cIWhCode"].ToString();
                        cOWhCode = dtCheck.Rows[0]["cOWhCode"].ToString();
                        sql = string.Format("select * from Warehouse where cWhCode in ('{0}','{1}')", dtCheck.Rows[0]["cOWhCode"].ToString(), dtCheck.Rows[0]["cIWhCode"].ToString());
                        DataTable dtWh = DBHelper.SQlReturnData(sql, cmd);
                        if (dtWh != null && dtWh.Rows.Count > 1)
                        {
                        }
                        else
                        {
                            throw new Exception("调拨单中转入或者转出仓库不存在！");
                        }
                    }
                    else
                    {
                        throw new Exception("调拨单ID：" + head.ID + "在U8中不存在！");
                    }
                    #endregion

                    #region 审核
                    sql = "UPDATE dbo.TransVouch SET cVerifyPerson='" + userInfo.UserName + "' ,dVerifyDate=CONVERT(VARCHAR(50),GETDATE(),112),dnverifytime=GETDATE() WHERE ID='" + head.ID + "'";
                    cmd.CommandText = sql;
                    try
                    {
                        cmd.ExecuteNonQuery();
                    }
                    catch (Exception ex)
                    {
                        log.Error("审核调拨单失败！异常：" + ex.Message + "；\r\n SQL:" + sql);
                        throw new Exception("程序异常，请联系开发人员！");
                    }
                    int bodyID = 0;
//                    foreach (ICSTransferDoc body in Bills)
//                    {
//                        //回写调出仓库待发数量
//                        string fOutcBatch = string.Empty;
//                        //bodyID = Convert.ToInt32(body);
//                        sql = @"UPDATE a SET fTransOutQuantity=ISNULL(a.fTransOutQuantity,0)-ISNULL(a.iQuantity,0)
//                                FROM dbo.CurrentStock a
//                                LEFT JOIN (SELECT a.cOWhCode,a.cIWhCode,b.cInvCode,b.autoID,
//                            ISNULL(b.cTVBatch,'') AS cTVBatch FROM dbo.TransVouch a 
//                            INNER JOIN dbo.TransVouchs b ON a.cTVCode = b.cTVCode)b 
//                              ON a.cInvCode=b.cInvCode AND a.cBatch=b.cTVBatch and a.cWhCode=b.cOWhCode WHERE b.autoID=@bodyID";
//                        cmd.Parameters.Clear();
//                        //cmd.Parameters.Add(new SqlParameter("@Qty", dtCheck.Rows[0]["iQuantity"].ToString()));
//                        cmd.Parameters.Add(new SqlParameter("@bodyID",body.ID));
//                        cmd.CommandText = sql;
//                        try
//                        {
//                            cmd.ExecuteNonQuery();
//                        }
//                        catch (Exception ex)
//                        {
//                            log.Error("回写现存量表 待调拨数量！异常：" + ex.Message + "；\r\n SQL:" + sql);
//                            throw new Exception("程序异常，请联系开发人员！");
//                        }

////                        #region 判断现存量是否足够
////                        sql = @"IF EXISTS(SELECT AutoID FROM dbo.CurrentStock WHERE iQuantity<0 OR iNum<0 OR fTransOutQuantity<0)
////                            BEGIN
////	                            DECLARE @MSG NVARCHAR(100)
////	                            SELECT @MSG='ERP待调拨出库数量不足！AutoID：'+CAST(AutoID AS NVARCHAR(100)) FROM dbo.CurrentStock WHERE iQuantity<0 OR iNum<0 OR fTransOutQuantity<0
//// 	                            RAISERROR(@MSG,16,1)
////                            END";

////                        cmd.CommandText = sql;
////                        cmd.ExecuteNonQuery();
////                        #endregion
//                        //回写调入仓库在途数量
//                        fOutcBatch = string.Empty;
//                        sql = @"UPDATE a SET fTransInQuantity=ISNULL(fTransInQuantity,0)-ISNULL(a.iQuantity,0)
//                                FROM dbo.CurrentStock a
//                                LEFT JOIN (SELECT a.cOWhCode,a.cIWhCode,b.cInvCode,b.autoID,
//                            ISNULL(b.cTVBatch,'') AS cTVBatch FROM dbo.TransVouch a 
//                            INNER JOIN dbo.TransVouchs b ON a.cTVCode = b.cTVCode)b 
//                              ON a.cInvCode=b.cInvCode AND a.cBatch=b.cTVBatch and a.cWhCode=b.cIWhCode WHERE b.autoID=@bodyID";
//                        cmd.Parameters.Clear();
//                        //cmd.Parameters.Add(new SqlParameter("@Qty", dtCheck.Rows[0]["iQuantity"].ToString()));
//                        cmd.Parameters.Add(new SqlParameter("@bodyID", body.ID));
//                        cmd.CommandText = sql;
//                        try
//                        {
//                            cmd.ExecuteNonQuery();
//                        }
//                        catch (Exception ex)
//                        {
//                            log.Error("回写现存量表在途数量！异常：" + ex.Message + "；\r\n SQL:" + sql);
//                            throw new Exception("程序异常，请联系开发人员！");
//                        }

////                        #region 判断现存量是否足够
////                        sql = @"IF EXISTS(SELECT AutoID FROM dbo.CurrentStock WHERE iQuantity<0 OR iNum<0 OR fTransInQuantity<0)
////                            BEGIN
////	                            DECLARE @MSG NVARCHAR(100)
////	                            SELECT @MSG='ERP待调拨入库数量不足！AutoID：'+CAST(AutoID AS NVARCHAR(100)) FROM dbo.CurrentStock WHERE iQuantity<0 OR iNum<0 OR fTransInQuantity<0
//// 	                            RAISERROR(@MSG,16,1)
////                            END";

////                        cmd.CommandText = sql;
////                        cmd.ExecuteNonQuery();
////                        #endregion
//                    }
                    #endregion
                    //0305 形态转换单CartonNum
                    sql = "select * from dbo.TransVouchs where ID='" + head.ID + "';";
                    DataTable dtChecks = DBHelper.SQlReturnData(sql, cmd);
                    #region 其他入库单
                    //取得out库单的默认显示模版
                    string DEF_ID08 = DBHelper.GetDefaultTemplate("0301", cmd);
                    VouchKey key08 = new VouchKey();
                    //key08 = U8Helper.GetPrimaryKey("rd", ErpName, 1, cmd);
                    //// 取得表头单据号
                    //string Code08 = U8Helper.GetRdrecord08Code(ErpName, "QR", cmd);
                    var num = Bills.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("0301", "" + date + "", "admin");
                    #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)

                         SELECT @ID,'1','08','调拨入库','调拨',a.cTVCode,cIWhCode,CONVERT(NVARCHAR(15),GETDATE(),23),a.cTVCode,'14',
                        @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',cIDepCode from dbo.TransVouch a WHERE ID='" + head.ID + "' ";

                    cmd.Parameters.Clear();
                    cmd.Parameters.Add(new SqlParameter("@ID", iFatherId));
                    //cmd.Parameters.Add(new SqlParameter("@cBusCode", head.ID));

                    cmd.Parameters.Add(new SqlParameter("@cCode", iBaseCodeLen));
                    cmd.Parameters.Add(new SqlParameter("@cHandler", userInfo.UserName));
                    cmd.Parameters.Add(new SqlParameter("@cMemo", ""));
                    cmd.Parameters.Add(new SqlParameter("@cMaker", userInfo.UserName));
                    cmd.Parameters.Add(new SqlParameter("@VT_ID", DEF_ID08));
                    cmd.CommandText = sql;
                    try
                    {
                        cmd.ExecuteNonQuery();
                    }
                    catch (Exception ex)
                    {
                        log.Error("生成其他入库单表头失败！调拨单ID：" + head.ID + ";异常：" + ex.Message + "；SQL：\r\n" + sql);
                        throw new Exception("程序异常，请联系开发人员！");
                    }
                    #endregion

                    #region 3.5 其他入库单表体
                    for (int i = 0; i < dtChecks.Rows.Count;i++ )
                    {
                        #region 3.5.1 表体
                        sql = @"INSERT INTO dbo.rdrecords08
                        (AutoID,ID,cInvCode,iQuantity,iSOutQuantity,iSOutNum,iFlag,iTrIds,iNQuantity,
                        cMassUnit,bLPUseFree,iRSRowNO,iOriTrackID,bCosting,bVMIUsed,iExpiratDateCalcu,iordertype,irowno,cbaccounter,cBatch,iPUnitCost,iPPrice)
                        SELECT @AutoID,@ID,cInvCode,b.iQuantity,'0','0','0',a.AutoID,iTVQuantity,
                         '0','0','0','0','1','0','0','0',@irowno,null,cTVBatch,iTVPCost,iTVPPrice 
                        from TransVouchs a
                        inner join  TransVouch b on a.ID=b.ID
                       where a.ID='" + dtChecks.Rows[i]["AutoID"].ToString() + @"';";

                        cmd.Parameters.Clear();
                        cmd.Parameters.Add(new SqlParameter("@AutoID", iChildId));
                        cmd.Parameters.Add(new SqlParameter("@ID", iFatherId));
                        //cmd.Parameters.Add(new SqlParameter("@iQuantity", dtCheck.Rows[0]["iQuantity"].ToString()));
                        //cmd.Parameters.Add(new SqlParameter("@iTrIds", body.AutoID));
                        cmd.Parameters.Add(new SqlParameter("@irowno", dtChecks.Rows[i]["irowno"].ToString()));
                        cmd.CommandText = sql;
                        try
                        {
                            cmd.ExecuteNonQuery();
                        }
                        catch (Exception ex)
                        {
                            log.Error("生成其他出库单表体失败！调拨单ID：" + head.ID + "；异常：" + ex.Message + "；SQL：\r\n" + sql);
                            throw new Exception("程序异常，请联系开发人员！");
                        }
                        #endregion

                        //更新现存量
                        key08.cBustypeUN = "调拨入库";
                        key08.cVouchTypeUN = "08";
                        key08.TableName = "IA_ST_UnAccountVouch08";
                        key08.UpdateTodoQuantity = head.UpdateTodoQuantity;
                        DBHelper.UpdateCurrentStock(cmd, dtChecks.Rows[i]["cInvCode"].ToString(), cIWhCode, "", Convert.ToDecimal(dtChecks.Rows[i]["iTVQuantity"].ToString()), key08);
                    }

                    #endregion

                    #endregion

                    #region 其他出库单

                    //取得out库单的默认显示模版
                    string DEF_ID09 = DBHelper.GetDefaultTemplate( "0301", cmd);
                    //取得采购入库单单据 表头ID，表体DID
                    VouchKey key09 = new VouchKey();
                    //key09 = U8Helper.GetPrimaryKey("rd", ErpName, 1, cmd);
                    //// 取得表头单据号
                    //string Code09 = U8Helper.GetRdrecord09Code(ErpName, "QC", cmd);
                    var nums = dtChecks.Rows.Count;
                    Dictionary<string, int> dics = DBHelper.GetAllCode("" + ERPDB + "", "rd", "" + nums + "");
                    int iFatherIds = Convert.ToInt32(dics["iFatherId"].ToString());
                    int iChildIds = Convert.ToInt32(dics["iChildId"].ToString());
                    DateTime dates = DateTime.Now;
                    string iBaseCodeLens = DBHelper.GetAllRDCode("0301", "" + date + "", "admin");
                    #region  其他出库单表头
                    sql = @"INSERT INTO dbo.RdRecord09
        (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)

        SELECT @ID,'0','09','调拨出库','调拨',a.cTVCode,cOWhCode,CONVERT(NVARCHAR(15),GETDATE(),23),@cCode,'24',
        @cHandler,@cMemo,'0',@cMaker,CONVERT(NVARCHAR(15),GETDATE(),23),'0','0',
        '85','0','0','0','0','0','0','0','0',GETDATE(),GETDATE(),'0','1',cODepCode from dbo.TransVouch a WHERE ID='" + head.ID + "' ";

                    cmd.Parameters.Clear();
                    cmd.Parameters.Add(new SqlParameter("@ID", iFatherIds));
                    //cmd.Parameters.Add(new SqlParameter("@cBusCode", dtCheck.Rows[0]["cTVCode"].ToString()));
                    //cmd.Parameters.Add(new SqlParameter("@cWhCode", cOWhCode));
                    cmd.Parameters.Add(new SqlParameter("@cCode", iBaseCodeLens));
                    cmd.Parameters.Add(new SqlParameter("@cHandler", userInfo.UserName));
                    cmd.Parameters.Add(new SqlParameter("@cMemo", ""));
                    cmd.Parameters.Add(new SqlParameter("@cMaker", userInfo.UserName));
                    cmd.Parameters.Add(new SqlParameter("@VT_ID", DEF_ID09));
                    cmd.CommandText = sql;
                    try
                    {
                        cmd.ExecuteNonQuery();
                    }
                    catch (Exception ex)
                    {
                        log.Error("生成其他出库单失败！调拨单ID：" + head.ID + "；异常：" + ex.Message + "；SQL：\r\n" + sql);
                        throw new Exception("程序异常，请联系开发人员！");
                    }
                    #endregion

                    #region 3.5 其他出库单表体
                    for (int i = 0; i < dtChecks.Rows.Count; i++)
                    {
                        #region 3.5.1 表体

                        //判断物料批号与现存量表批号是否一致、数量不能超过现存量物料数量
                        //sql = @"SELECT cBatch,iQuantity from CurrentStock WHERE cInvCode='" + dtCheck.Rows[0]["cInvCode"].ToString() + "'AND cWhCode='" + dtCheck.Rows[0]["cOWhCode"].ToString() + "'";
                        //DataTable dtItem = DBHelper.SQlReturnData(sql, cmd);
                        //if (dtItem != null && dtItem.Rows.Count > 0)
                        //{
                        //    if (!dtItem.Rows[0]["cBatch"].ToString().Equals(body.cTVBatch))
                        //    {
                        //        throw new Exception("物料条码的批号与U8现存量物料批号不一致,物料:" + body.cInvCode);
                        //    }
                        //    if (Convert.ToDecimal(dtItem.Rows[0]["iQuantity"].ToString()) < body.iQuantity)
                        //    {
                        //        throw new Exception("物料条码的数量大于U8现存量物料数量,物料:" + body.cInvCode);
                        //    }

                        //}
                        //else
                        //{
                        //    throw new Exception("物料:" + body.cInvCode + "在现存量表中不存在!");
                        //}
                        //key09.DID += 1;
                        //Rd09irowno += 1;
                        sql = @"INSERT INTO dbo.rdrecords09
                        (AutoID,ID,cInvCode,iQuantity,iSOutQuantity,iSOutNum,iFlag,iTrIds,iNQuantity,
                        cMassUnit,bLPUseFree,iRSRowNO,iOriTrackID,bCosting,bVMIUsed,iExpiratDateCalcu,iordertype,irowno,cbaccounter,cBatch,iPUnitCost,iPPrice)
                        SELECT @AutoID,@ID,cInvCode,a.iTVQuantity,'0','0','0',a.AutoID,iTVQuantity,
                         '0','0','0','0','1','0','0','0',a.irowno,null,cTVBatch,iTVPCost,iTVPPrice 
                         from TransVouchs a
                        inner join TransVouch b on a.ID=b.ID
                        where b.ID='" + dtChecks.Rows[i]["AutoID"].ToString()+ @"' ;";

                        cmd.Parameters.Clear();
                        cmd.Parameters.Add(new SqlParameter("@AutoID", iChildIds));
                        cmd.Parameters.Add(new SqlParameter("@ID", iFatherIds));
                        //cmd.Parameters.Add(new SqlParameter("@iQuantity", dtCheck.Rows[0]["iQuantity"].ToString()));
                        //cmd.Parameters.Add(new SqlParameter("@iTrIds", body.AutoID));
                        //cmd.Parameters.Add(new SqlParameter("@irowno", Rd09irowno));

                        cmd.CommandText = sql;
                        try
                        {
                            cmd.ExecuteNonQuery();
                        }
                        catch (Exception ex)
                        {
                            log.Error("生成其他出库单表体失败！调拨单ID：" + head.ID + "；异常：" + ex.Message + "；SQL：\r\n" + sql);
                            throw new Exception("程序异常，请联系开发人员！");
                        }

                        sql = @"INSERT INTO dbo.rdrecords09sub
                                ( AutoID , ID ,iBG_Ctrl , iBGSTSum )
                                values('" + iChildIds + "','" + iFatherIds + "',0,0)";
                        cmd.CommandText = sql;
                        cmd.ExecuteNonQuery();
                        #endregion

                        //更新现存量
                        key09.cBustypeUN = "调拨出库";
                        key09.cVouchTypeUN = "09";
                        key09.TableName = "IA_ST_UnAccountVouch09";

                        DBHelper.UpdateCurrentStock(cmd, dtChecks.Rows[i]["cInvCode"].ToString(), cOWhCode, "", -Convert.ToDecimal(dtChecks.Rows[i]["iTVQuantity"].ToString()), key09);
                        iChildIds--;
                    }
               
                    #endregion

                    #endregion

                }
                cmd.Transaction.Commit();
                ResultFlag = true;
                return ResultFlag;
            }
            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<ICSTransferDoc> Bills)
        {
            string HeadList = string.Empty;
            string BodyList = string.Empty;
            foreach (ICSTransferDoc head in Bills)
            {
                HeadList += "\r\n 表头调拨单号：" + head.ID + "，用户：" + head.User;
                foreach (ICSTransferDoc body in Bills)
                {
                    BodyList += "\r\n 表体主键ID： " + body.ID + "";
                }
            }
            log.Info(HeadList);
            log.Info(BodyList);
        }

    }

}
