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 ManufactureReceiveDoc
    {
        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="infos"></param>
       /// <returns></returns>
        public string Get(List<ICSManufactureReceiveDoc> infos)
        {
            List<ICSManufactureReceiveDoc> szJson = new List<ICSManufactureReceiveDoc>();
            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 (ICSManufactureReceiveDoc info in infos)
                {
                    if (info.MTime < new DateTime(2000, 01, 01))
                        throw new Exception("请输入正确的操作时间:" + info.MTime);
                    sql = @" select a.ID,a.cCode,a.cDepCode,c.cDepName,a.cWhCode,d.cWhName,a.cMPoCode ,a.cMaker ,a.dnmaketime ,a.cHandler ,a.dnverifytime ,
                             b.AutoID,b.iRSRowNO ,b.cInvCode ,b.iQuantity ,b.iNum ,b.iMPoIds  from rdrecord10 a 
                             left join rdrecords10 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 1=1";
                    if (!string.IsNullOrWhiteSpace(info.MRCVCode))
                    {
                        sql += " and a.cCode='{0}'";
                    }
                    if (!string.IsNullOrWhiteSpace(info.MTime.ToString()))
                    {
                        sql += " and ISNULL(a.dnmodifytime,ISNULL(a.dnverifytime, ISNULL(a.dnmodifytime, a.dnmaketime)))>='{1}'";
                    }
                    if (!string.IsNullOrWhiteSpace(info.User))
                    {
                        sql += "and a.CMAKER='{2}'";
                    }
                    sql = string.Format(sql, info.MRCVCode, info.MTime, info.User);
                    dt = DBHelper.SQlReturnData(sql, cmd);
                    json = JsonConvert.SerializeObject(dt);
                    if (dt.Rows.Count <= 0 || dt == null)
                        throw new Exception("成品入库单:" + info.MRCVCode + ",无信息!");

                }
                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  CreateManufactureReceiveDoc(List<ICSManufactureReceiveDoc> Bills)
       {
           string msg = "";
           string sql = string.Empty;
           int num = 0;
           string iFatherIdTwo = string.Empty;
           VouchKey key = new VouchKey();
           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);
               //string ERPName = U8Helper.GetERPName();
               foreach (ICSManufactureReceiveDoc head in Bills)
               {
                   num = head.details.Count();
                   Dictionary<string, int> dic = DBHelper.GetAllCode("" + ERPDB + "", "ReceiveDoc", "" + num + "");
                   int iFatherId = Convert.ToInt32(dic["iFatherId"].ToString());
                   int iChildId = Convert.ToInt32(dic["iChildId"].ToString());
                   DateTime date = DateTime.Now;
                   string iBaseCodeLen = DBHelper.GetAllRDCode("0411", "" + date + "", "admin");
                   string DEF_ID = DBHelper.GetDefaultTemplate("0411", cmd);
                   string cRDcode = DBHelper.GetRDCode("生产完工入库", cmd);
                   //Person personEntity = new Person();
                   //personEntity = U8Helper.GetDepCodeByUserCode(head.UserCode, cmd);
                   DateTime dvDate = DateTime.Now.Date;
                   #region 产成品入库单表头
                   sql = @"INSERT INTO dbo.rdrecord10
                                    ( ID ,bRdFlag ,cVouchType ,cBusType ,cSource ,cWhCode ,dDate ,
                                      cCode ,cRdCode ,cDepCode ,cHandler ,bTransFlag ,cMaker ,
                                      cDefine1 ,cDefine2 ,cDefine3 ,cDefine4 ,cDefine5 ,cDefine6 ,
                                      cDefine7 ,cDefine8 ,cDefine9 ,cDefine10 ,dVeriDate ,bpufirst ,
                                      biafirst ,VT_ID ,bIsSTQc ,cDefine11 ,cDefine12 ,cDefine13 ,
                                      cDefine14 ,cDefine15 ,cDefine16 ,cMPoCode ,iproorderid ,
                                      bFromPreYear ,bIsComplement ,iDiscountTaxType ,ireturncount ,
                                      iverifystate ,iswfcontrolled ,cModifyPerson ,dnmaketime ,
                                      dnverifytime ,bredvouch ,iPrintCount )
                               SELECT @ID,1,'10','成品入库','生产订单',@cWhCode,convert(datetime,convert(varchar(10),getdate(),120)),
                            		@cCode,@RdCode,@DepCode,@cHandler,0,@cMaker,
                            		a.Define1,a.Define2,a.Define3,a.Define4,a.Define5,a.Define6,
                            		a.Define7,a.Define8,a.Define9,a.Define10,@dDate,0,
                            		0,@VT_ID,0,a.Define11,a.Define12,a.Define13,
                            		a.Define14,a.Define15,a.Define16,a.MoCode,a.MoId,
                            		0,0,0,0,
                            		0,0,'',@dDate,
                            		@dDate,0,0
                                FROM dbo.mom_order a 
                                WHERE a.MoCode='" + head.MOCode + "'";
                   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("@cDepCode", head.DepCode));
                   cmd.Parameters.Add(new SqlParameter("@cHandler", head.User));
                   cmd.Parameters.Add(new SqlParameter("@cMaker", head.User));
                   cmd.Parameters.Add(new SqlParameter("@VT_ID", DEF_ID));
                   cmd.Parameters.Add(new SqlParameter("@DepCode", head.DepCode));
                   cmd.Parameters.Add(new SqlParameter("@dDate", dvDate));
                   cmd.Parameters.Add(new SqlParameter("@RdCode", cRDcode));
                   cmd.CommandText = sql;
                        try
                        {
                            int count = cmd.ExecuteNonQuery();
                            if (count <= 0)
                            {
                                log.Error("生成成品入库单表头失败,受影响行数<=0;");
                                throw new Exception("生成成品入库单表头失败,受影响行数<=0;");
                            }
                        }
                        catch (Exception ex)
                        {
                            log.Error("生成成品入库单表头失败!SQL:\r\n" + sql, ex);
                            throw new Exception("生成成品入库单表头失败!SQL:\r\n" + sql, ex);
                        }

                    
               
                   #endregion

                   #region 产成品入库单表体
                   foreach (ICSManufactureReceiveDocs body in head.details)
                   {
                       #region 判断工单行是否关闭,关闭不能入库
                       sql = @"SELECT ISNULL(a.CloseUser,'') as CloseUser,b.MoCode,a.SortSeq  FROM dbo.mom_orderdetail a INNER JOIN
                                dbo.mom_order b ON b.MoId = a.MoId WHERE a.MoDId = '" + body.MODetailID + "'";
                       DataTable dtCheck = DBHelper.SQlReturnData(sql, cmd);
                       if (dtCheck != null && dtCheck.Rows.Count > 0)
                       {
                           if (!string.IsNullOrEmpty(dtCheck.Rows[0]["CloseUser"].ToString()))
                           {
                               throw new Exception("工单号:" + dtCheck.Rows[0]["MoCode"].ToString() + ",行号:" + dtCheck.Rows[0]["SortSeq"].ToString() + ",已关闭,无法入库!");
                           }
                       }
                       #endregion

                       #region 生成产成品入库单表体
                       //if (head.IsReturn == "1")
                       //{
                       //    body.iQuantity = -body.iQuantity;
                       //}
                       sql = @"INSERT INTO dbo.rdrecords10
                                    ( AutoID ,ID ,cInvCode ,iQuantity ,cBatch ,iFlag ,
                                      cDefine22 ,cDefine23 ,cDefine24 ,cDefine25 ,cDefine26 ,cDefine27 ,
                                      cItemCode ,cName ,iNQuantity ,cDefine28 ,
                                      cDefine29 ,cDefine30 ,cDefine31 ,cDefine32 ,cDefine33 ,cDefine34 ,
                                      cDefine35 ,cDefine36 ,cDefine37 ,iMPoIds ,bRelated ,bLPUseFree ,
                                      iRSRowNO ,iOriTrackID ,bCosting ,cmocode ,imoseq ,iExpiratDateCalcu ,
                                      iorderdid ,iordertype,iordercode,iorderseq,isodid,isotype,csocode,isoseq,irowno ,iposflag )
                            SELECT @AutoID,@ID,@cInvCode,@iQuantity,@cBatch,0,
                            		a.Define22,a.Define23,a.Define24,a.Define25,a.Define26,a.Define27,
                            		null,null,a.Qty,a.Define28,
                            		a.Define29,a.Define30,a.Define31,a.Define32,a.Define33,a.Define34,
                            		a.Define35,a.Define36,a.Define37,a.MoDId,0,0,
                            		0,0,1,b.MoCode,a.SortSeq,0,
                            		a.OrderDid,a.OrderType,a.OrderCode,a.OrderSeq,a.SoDId,a.SoType,a.SoCode,a.SoSeq,@irowno,0
                            FROM dbo.mom_orderdetail a
                            INNER JOIN dbo.mom_order b ON a.MoId=b.MoId WHERE a.MoDId='" + body.MODetailID + "'";
                       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("@cBatch", ""));
                       cmd.Parameters.Add(new SqlParameter("@irowno", body.Sequence));
                   
                      cmd.CommandText = sql;
                        try
                        {
                            int count = cmd.ExecuteNonQuery();
                            if (count <= 0)
                            {
                                log.Error("生成材料出库单表头失败,受影响行数<=0;");
                                throw new Exception("生成材料出库单表头失败,受影响行数<=0;");
                            }
                        }
                        catch (Exception ex)
                        {
                            log.Error("生成材料出库单表头失败!SQL:\r\n" + sql, ex);
                            throw new Exception("生成材料出库单表头失败!SQL:\r\n" + sql, ex);
                        }
                   
                    
                   
                       #endregion

                       #region 更新现存量
                       key.cBustypeUN = "成品入库";
                       key.cVouchTypeUN = "10";
                       key.TableName = "IA_ST_UnAccountVouch10";
                       DBHelper.UpdateCurrentStock(cmd, body.InvCode, head.WHCode, "", body.Quantity, key);
                       #endregion


                       #region 回写生产订单入库数量
                       sql = @"UPDATE dbo.mom_orderdetail SET QualifiedInQty=ISNULL(QualifiedInQty,0)+" + body.Quantity + " where MoDId='" + body.MODetailID + "'";
                       DBHelper.CmdExecuteNonQuery(sql, cmd, "回写生产订单入库数量失败!");
                       #endregion

                       #region 判断工单行是否全部入库
                       sql = "SELECT (QualifiedInQty - Qty) as qty,QualifiedInQty FROM dbo.mom_orderdetail WHERE MoDId='" + body.MODetailID + "'";
                       DataTable dtClose = DBHelper.SQlReturnData(sql, cmd);
                       foreach (DataRow dr in dtClose.Rows)
                       {
                           if (Convert.ToDecimal(dr["qty"]) >= 0)
                           {
                               sql = "update mom_orderdetail set CloseTime = GETDATE(),CloseDate= CONVERT(NVARCHAR(15),GETDATE(),23), CloseUser ='" + head.User + "',Status=4 where MODId='" + body.MODetailID + "'";
                               DBHelper.CmdExecuteNonQuery(sql, cmd, "生产订单行关闭失败!");
                           }
                       }
                       #endregion
                       iChildId--;
                   }
                   iFatherIdTwo += "'" + iFatherId + "',";
                   #endregion
               
               }
               #region 查询
               sql = @" select a.ID as ID,a.ID as IDs,a.cCode as MRCVCode,a.cDepCode,c.cDepName,a.cWhCode,d.cWhName
                            ,a.cMPoCode as MOCode ,a.cMaker as CreateUser ,a.dnmaketime as CreateDateTime
                            ,a.cHandler as Checker ,a.dnverifytime as CheckDateTime 
                              from rdrecord10 a 
                             left join Department c on a.cDepCode=c.cDepCode
                             left join Warehouse d on a.cWhCode=d.cWhCode  WHERE A.cHandler IS NOT NULL AND A.ID in({0})

                          select a.ID as IDs, b.AutoID as DetailID,b.irowno as Sequence  ,b.cInvCode as InvCode ,
                            b.iQuantity as Quantity ,b.iNum as Amount,b.iMPoIds as MODetailID 
                            from rdrecord10 a 
                             left join rdrecords10 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.cHandler IS NOT NULL AND A.ID in({0})";
               sql = string.Format(sql, iFatherIdTwo.TrimEnd(','));
               DataSet ds = DBHelper.SQlReturnDataSet(sql, cmd);
               string RelationName = "details";
               DataRelation drs = new DataRelation(RelationName, ds.Tables[0].Columns["IDs"], ds.Tables[1].Columns["IDs"]);
               ds.Relations.Add(drs);
               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="infos"></param>
        /// <returns></returns>
        public bool Approve(List<ICSManufactureReceiveDoc> infos)
        {
            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;
            try
            {
                if (infos.Count <= 0)
                {
                    throw new Exception("传送数据为空!");
                }
                LogInfo(infos);
                foreach (ICSManufactureReceiveDoc head in infos)
                {
                    string sql = "";
                    ICSUserInfo userInfo = new ICSUserInfo();
                    userInfo = DBHelper.GetPersonInfo(head.User, cmd);

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

                    #region 审核其他出库单
                    sql = @"UPDATE dbo.rdrecord10 SET cHandler='" + userInfo.UserName + @"' ,
                            dVeriDate=CONVERT(VARCHAR(50),GETDATE(),112),dnverifytime=GETDATE() WHERE ID='" + head.ID + "'";
                    DBHelper.CmdExecuteNonQuery(sql, cmd, "审核其他出库单失败!");
                    #endregion
                    sql = "select * from dbo.rdrecords10 a inner join rdrecord10 b on a.ID=b.ID where b.ID='" + head.ID + "';";
                    DataTable dtChecks = DBHelper.SQlReturnData(sql, cmd);
                    #region 更新现存量
                    for (int i = 0; i < dtChecks.Rows.Count; i++)
                    {
                        //判断物料批号与现存量表批号是否一致、数量不能超过现存量物料数量
                        sql = @"SELECT cBatch,iQuantity from CurrentStock WHERE cInvCode='" + dtChecks.Rows[i]["cInvCode"].ToString() + "'AND cBatch=''and cWhCode='" + dtChecks.Rows[i]["cWhCode"].ToString() + "'";
                        DataTable dtItem = DBHelper.SQlReturnData(sql, cmd);
                        if (dtItem != null && dtItem.Rows.Count > 0)
                        {
                            //if (!dtItem.Rows[0]["cBatch"].ToString().Equals(body.cBatch))
                            //{
                            //    throw new Exception("物料条码的批号与U8现存量物料批号不一致,物料:" + body.cInvCode);
                            //}
                            if (Convert.ToDecimal(dtItem.Rows[0]["iQuantity"].ToString()) < Convert.ToDecimal(dtChecks.Rows[i]["iQuantity"].ToString()))
                            {
                                throw new Exception("物料条码的数量大于U8现存量物料数量,物料:" + dtChecks.Rows[i]["cInvCode"].ToString());
                            }

                        }
                        else
                        {
                            throw new Exception("物料:" + dtChecks.Rows[i]["cInvCode"].ToString() + "在现存量表中不存在!");
                        }


                        VouchKey key = new VouchKey();
                        key.cBustypeUN = "成品入库";
                        key.cVouchTypeUN = "10";
                        key.TableName = "IA_ST_UnAccountVouch10";
                        DBHelper.UpdateCurrentStock(cmd, dtChecks.Rows[i]["cInvCode"].ToString(), dtChecks.Rows[i]["cWhCode"].ToString(), "", Convert.ToDecimal(dtChecks.Rows[i]["iQuantity"].ToString()), key);

                        //回写fOutQuantityy
                        //                        sql = @"Update CurrentStock set fOutQuantity=isnull(fOutQuantity,0)-" + Convert.ToDecimal(dtChecks.Rows[i]["iQuantity"].ToString()) + @" 
                        //                                where cInvCode='" + dtChecks.Rows[i]["cInvCode"].ToString() + "' and cWhCode='" + dtChecks.Rows[i]["cWhCode"].ToString() + "' ";
                        //if (body.cBatch != null)
                        //{
                        //    sql += "and cBatch='" + body.cBatch + "'";
                        //}
                        //else
                        //{
                        //    sql += "and cBatch=''";
                        //}
                        //DBHelper.CmdExecuteNonQuery(sql, cmd, "回写fOutQuantity失败!");
                        //if (head.UpdateTodoQuantity == true)
                        //{


                    }
                    #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="infos"></param>
        /// <returns></returns>
        public string Delete(List<ICSManufactureReceiveDoc> infos)
        {
            List<ICSManufactureReceiveDoc> szJson = new List<ICSManufactureReceiveDoc>();
            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 (ICSManufactureReceiveDoc info in infos)
                {
                    if (info.MTime < new DateTime(2000, 01, 01))
                        throw new Exception("请输入正确的操作时间:" + info.MTime);
                    sql = @" DELETE  rdrecord10 WHERE ID={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<ICSManufactureReceiveDoc> Bills)
        {
            string HeadList = string.Empty;
            string BodyList = string.Empty;
            foreach (ICSManufactureReceiveDoc head in Bills)
            {
                HeadList += "\r\n 表头主键ID:" + head.ID + ",仓库:" + head.WHCode + ",用户:" + head.User;
                foreach (ICSManufactureReceiveDocs body in head.details)
                {
                    BodyList += "\r\n 表体主键ID: " + body.MODetailID + ",数量:" + body.Quantity;
                }
            }
            log.Info(HeadList);
            log.Info(BodyList);
        }
    }
}