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
{
   public  class DisassemblyDoc
    {

        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 Dismrecord01(List<ICSDisassemblyDoc> Bills)
        {
            bool ResultFlag = false;
            DataTable dtNew = null;
            string connS = "";
            SqlConnection conn = new SqlConnection();
           
            SqlCommand cmd = new SqlCommand();
         
            
                if (Bills.Count <= 0)
                {
                    throw new Exception("传送数据为空！");
                }
                LogInfo(Bills);
                foreach (ICSDisassemblyDoc head in Bills)
                {
                    try
                    {
                    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];

                    string sql = "";
                    ICSUserInfo userInfo = new ICSUserInfo();
                    userInfo = DBHelper.GetPersonInfo(head.User, cmd);
                    string cHandler = string.Empty;
                    string cIWhCode = string.Empty;

                    #region 检验单号是否存在
                    sql = "select * from AssemVouch where ID='" + head.ID + "'";
                    DataTable dt = DBHelper.SQlReturnData(sql, cmd);
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        cHandler = dt.Rows[0]["cVerifyPerson"].ToString();
                        //cIWhCode = head.cWhCode;
                        if (!string.IsNullOrEmpty(cHandler))
                        {
                            throw new Exception("单据ID：" + head.ID + "不是开立状态！");
                        }
                    }
                    else
                    {
                        throw new Exception("单据ID：" + head.ID + "在U8中不存在！");
                    }
                    #endregion

                    #region 审核拆卸单
                    sql = @"UPDATE dbo.AssemVouch SET cVerifyPerson='" + userInfo.UserName + @"' ,
                            dVerifyDate=CONVERT(VARCHAR(50),GETDATE(),112),dnverifytime=GETDATE() WHERE ID='" + head.ID + "'";
                    DBHelper.CmdExecuteNonQuery(sql, cmd, "审核拆卸单失败！");
                    #endregion

                    #region  其他出库单表头
                    //取得out库单的默认显示模版
                    string DEF_ID09 = DBHelper.GetDefaultTemplate("0301", cmd);
                    //取得采购入库单单据 表头ID，表体DID
                    VouchKey key09 = new VouchKey();
                    var nums = Bills.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", "" + dates + "", "admin");
                    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.cAVCode,b.cWhCode,CONVERT(NVARCHAR(15),GETDATE(),23),@cCode,null,
                            @cHandler,@cMemo,'0',@cMaker,CONVERT(NVARCHAR(15),GETDATE(),23),'0','0',
                            '85','0','0','0','0','0','0','0','0',GETDATE(),GETDATE(),'0',null,cDepCode 
                            from dbo.AssemVouch a
                            inner join AssemVouchs  b on a.id=b.id
                            WHERE a.ID='" + head.ID + "' and bAVType='套件' ";

                    cmd.Parameters.Clear();
                    cmd.Parameters.Add(new SqlParameter("@ID", iFatherIds));
                    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 其他出库单表体

                    #region 检验单号是否存在
                    sql = "select iAVQuantity,* from AssemVouchs where ID='" + head.ID + "' and bAVType='套件'";
                    DataTable dsh = DBHelper.SQlReturnData(sql, cmd);
                    if (dsh != null && dsh.Rows.Count > 0)
                    {
                        cIWhCode = dsh.Rows[0]["cWhCode"].ToString();
                    }
                    else
                    {
                        throw new Exception("单据ID：" + head.ID + "在U8中不存在！");
                    }
                    //判断物料批号与现存量表批号是否一致、数量不能超过现存量物料数量
                    sql = @"SELECT cBatch,iQuantity from CurrentStock WHERE cInvCode='"+dsh.Rows[0]["cInvCode"].ToString() + "'AND cBatch=''and cWhCode='" + dsh.Rows[0]["cWhCode"].ToString()+ "'";
                    DataTable dtItem = DBHelper.SQlReturnData(sql, cmd);
                    if (dtItem != null && dtItem.Rows.Count > 0)
                    {

                        if (Convert.ToDecimal(dtItem.Rows[0]["iQuantity"].ToString()) < Convert.ToInt32(dsh.Rows[0]["iAVQuantity"].ToString()))
                        {
                            throw new Exception("物料条码的数量大于U8现存量物料数量,物料:" + dsh.Rows[0]["cInvCode"].ToString());
                        }

                    }
                    else
                    {
                        throw new Exception("物料:" + dsh.Rows[0]["cInvCode"].ToString() + "在现存量表中不存在!");
                    }
                    #endregion
                    #region 3.5.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,@iItemcode,@iQuantity,'0','0','0',a.autoID,iAVQuantity,
                         '0','0','0','0','1','0','0','0',a.irowno,null,cAVBatch,iAVPCost,iAVPPrice
                        from AssemVouchs a
                        where ID=" + head.ID + @" and bAVType='套件' ;";

                    cmd.Parameters.Clear();
                    cmd.Parameters.Add(new SqlParameter("@AutoID", iChildIds));
                    cmd.Parameters.Add(new SqlParameter("@ID", iFatherIds));
                    cmd.Parameters.Add(new SqlParameter("@iItemcode", dsh.Rows[0]["cInvCode"].ToString()));
                    cmd.Parameters.Add(new SqlParameter("@iQuantity", dsh.Rows[0]["iAVQuantity"].ToString()));
                    //cmd.Parameters.Add(new SqlParameter("@iTrIds", head.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, dsh.Rows[0]["cInvCode"].ToString(), cIWhCode, "", -Convert.ToDecimal(dsh.Rows[0]["iAVQuantity"].ToString()), key09);

                    //DBHelper.UpdateIDandDID("rd", ErpName, head.list.Count(), cmd);
                    #endregion

                    sql = "select cWhCode from dbo.AssemVouchs  where ID='" + head.ID + "' and bAVType='散件' group by cWhCode;";
                    DataTable dtChecks = DBHelper.SQlReturnData(sql, cmd);
                    int iChildId = 0;
                    int iFatherId = 0;
                    VouchKey key08 = new VouchKey();
                    for (int i = 0; i < dtChecks.Rows.Count; i++)
                    {
                        #region 其他入库单表头
                        //取得out库单的默认显示模版
                        string DEF_ID08 = DBHelper.GetDefaultTemplate("0301", cmd);
                        //取得采购入库单单据 表头ID，表体DID
                        var num = Bills.Count;
                        Dictionary<string, int> dic = DBHelper.GetAllCode("" + ERPDB + "", "rd", "" + num + "");
                        iFatherId = Convert.ToInt32(dic["iFatherId"].ToString());
                        iChildId = Convert.ToInt32(dic["iChildId"].ToString());
                        DateTime date = DateTime.Now;
                        string iBaseCodeLen = DBHelper.GetAllRDCode("0301", "" + date + "", "admin");

                        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.cAVCode,@cWhCode,CONVERT(NVARCHAR(15),GETDATE(),23),@cCode,null,
                        @cHandler,@cMemo,'0',@cMaker,CONVERT(NVARCHAR(15),GETDATE(),23),'0','0',
                        @VT_ID,'0','0','0','0','0','0','0','0',GETDATE(),GETDATE(),'0',null,cDepCode 
                        from dbo.AssemVouch a  
                        WHERE id='" + head.ID + "' ";

                        cmd.Parameters.Clear();
                        cmd.Parameters.Add(new SqlParameter("@ID", iFatherId));
                        //cmd.Parameters.Add(new SqlParameter("@cBusCode", head.cCode));
                        cmd.Parameters.Add(new SqlParameter("@cWhCode", dtChecks.Rows[0]["cWhCode"].ToString()));
                        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
                        sql = "select * from AssemVouchs where ID='" + head.ID + "' and bAVType='散件' and cWhCode='" + dtChecks.Rows[i]["cWhCode"].ToString() + "' ";
                        DataTable ds = DBHelper.SQlReturnData(sql, cmd);
                        for (int j = 0; j < ds.Rows.Count; j++)
                        {
                            #region 其他入库单表体
                            if (ds != null && ds.Rows.Count > 0)
                            {
                                cIWhCode = ds.Rows[j]["cWhCode"].ToString();
                            }
                            else
                            {
                                throw new Exception("单据号：" + head.ID + "在U8中不存在！");
                            }
                            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,a.iAVQuantity,'0','0','0',a.AutoID,iAVQuantity,
                         '0','0','0','0','1','0','0','0',a.irowno,null,cAVBatch,iAVPCost,iAVPPrice from AssemVouchs a  
                        where a.autoID=" + ds.Rows[j]["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", body.iQuantity));
                            //cmd.Parameters.Add(new SqlParameter("@iTrIds", body.AutoID));
                            //cmd.Parameters.Add(new SqlParameter("@irowno", Rd08irowno));
                            cmd.CommandText = sql;
                            try
                            {
                                cmd.ExecuteNonQuery();
                            }
                            catch (Exception ex)
                            {
                                log.Error("生成其他出库单表体失败！拆卸单单号：" + head.ID + "；异常：" + ex.Message + "；SQL：\r\n" + sql);
                                throw new Exception("程序异常，请联系开发人员！");
                            }


                            //更新现存量
                            key08.cBustypeUN = "拆卸入库";
                            key08.cVouchTypeUN = "08";
                            key08.TableName = "IA_ST_UnAccountVouch08";

                            DBHelper.UpdateCurrentStock(cmd, ds.Rows[j]["cInvCode"].ToString(), cIWhCode, "", Convert.ToDecimal(ds.Rows[j]["iAVQuantity"].ToString()), key08);
                            #endregion
                            iChildId--;
                        }
                    }
                    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();
            }
                }
               
                ResultFlag = true;
                return ResultFlag;
            
        }
        /// <summary>
        /// 记录日志
        /// </summary>
        /// <param name="Bills"></param>
        private void LogInfo(List<ICSDisassemblyDoc> Bills)
        {
            string HeadList = string.Empty;
            string BodyList = string.Empty;
            foreach (ICSDisassemblyDoc head in Bills)
            {
                HeadList += "\r\n 表头主键ID：" + head.ID + "，用户：" + head.User + "，站点：" + head.WorkPoint +"";
               
            }
            log.Info(HeadList);
            log.Info(BodyList);
        }
    }
}
