using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ICSSoft.ASKCommon;
using ICSSoft.ASKEntity;
using Newtonsoft.Json;



namespace ICSSoft.ASKDataProject
{
    public class ManufactureReceiveDocASK
    {
        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"];
        private static string CRNALL = System.Configuration.ConfigurationManager.AppSettings["ManuFaCRDNAME"];
        private static string CRNA = System.Configuration.ConfigurationManager.AppSettings["MoICRDNAME"];

        public string CreateManufactureReceiveDoc(List<ICSManufactureReceiveDocASK> Bills)
        {
            string msg = "";
            DataSet ds = null;
            string iFatherIdTwo = "";
            string iFatherIdTree = "";
            List<WH> LWH = new List<WH>();
            int isif = 0;
            string connS = "";
            string MoClass = "";
            int num = 0;
            int news = 0;
            int iseq = 0;
            int out11 = 0;
            int irownnew = 0;
            string sql = string.Empty;
            string mocode = "";
            string seq = "";
            //取得out库单的默认显示模版

            //取得采购入库单单据 表头ID,表体DID
            VouchKey key = new VouchKey();
            SqlConnection conn = new SqlConnection();
            SqlCommand cmd = new SqlCommand();
            if (Bills.Count <= 0)
            {
                throw new Exception("传送数据为空!");
            }
            LogInfo(Bills);
            foreach (ICSManufactureReceiveDocASK head in Bills)
            {
                foreach (ICSManufactureReceiveDocs load in head.details)
                {
                    foreach (ICSManufactureReceiveDocss loads in load.detailss)
                    {
                        news++;
                    }
                }
            }

            if (news != 0)
            {
                foreach (ICSManufactureReceiveDocASK head in Bills)
                {
                    foreach (ICSManufactureReceiveDocs load in head.details)
                    {
                        foreach (ICSManufactureReceiveDocss loads in load.detailss)
                        {
                            WH wh = new WH();
                            wh.WHCODE = loads.WHCode;
                            wh.seq = 0;
                            if (LWH.Count != 0)
                            {
                                int whnumber = 0;
                                foreach (WH item in LWH)
                                {
                                    if (item.WHCODE == wh.WHCODE)
                                        whnumber++;
                                }
                                if (whnumber == 0)
                                    LWH.Add(wh);
                            }
                            else
                                LWH.Add(wh);

                        }
                    }
                }
            }

            List<string> result = Bills.Select(t => t.WorkPoint).Distinct().ToList();


            foreach (string WorkPoint in result)
            {
                try
                {
                    connS = string.Format(connString, WorkPoint);
                    conn = new System.Data.SqlClient.SqlConnection(connS);
                    conn.Open();
                    SqlTransaction sqlTran = conn.BeginTransaction();
                    cmd = new SqlCommand();
                    cmd.Transaction = sqlTran;
                    cmd.Connection = conn;



                    #region 连副产品
                    foreach (ICSManufactureReceiveDocASK head in Bills)
                    {
                        iFatherIdTwo = "";
                        if (WorkPoint != head.WorkPoint)
                            continue;

                        if (head.TYPE != "连副产品")
                            continue;

                        if (!DBHelper.IsInventoryConsolidation(cmd, head.WorkPoint))
                            throw new Exception("U8正在整理现存量,请稍后再试");

                        string[] ss = head.WorkPoint.Split('_');
                        ERPDB = ss[1];
                        ICSUserInfo userInfo = new ICSUserInfo();
                        userInfo = DBHelper.GetPersonInfo(head.User, cmd);
                        string[] dd = CRNALL.Split('~');
                        string crdname = dd[0];
                        string carname = dd[1];
                        string surface = dd[2];

                        string cardnewcode = DBHelper.GetCardNumber(carname, cmd);

                        num = head.details.Count();
                        Dictionary<string, int> dic = DBHelper.GetAllCode("" + ERPDB + "", surface, "" + num + "", head.WorkPoint);
                        int iFatherId = Convert.ToInt32(dic["iFatherId"].ToString());
                        int iChildId = Convert.ToInt32(dic["iChildId"].ToString());
                        DateTime date = DateTime.Now;
                        string DEF_ID = DBHelper.GetDefaultTemplate(cardnewcode, cmd);
                        string cRDcode = DBHelper.GetRDCode(crdname, cmd);
                        string iBaseCodeLen = DBHelper.GetAllRDCode(cardnewcode, "" + date + "", "admin", cRDcode, head.WorkPoint,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", userInfo.UserName));
                        cmd.Parameters.Add(new SqlParameter("@cMaker", userInfo.UserName));
                        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 产成品入库单表体
                        int irowno = 0;
                        foreach (ICSManufactureReceiveDocs body in head.details)
                        {
                            //if (DBHelper.bInvBatch(body.InvCode, cmd) == true)
                            //{
                            //    if (body.BatchCode == "")
                            //    {
                            //        log.Error("该物料:" + body.InvCode + "已启用批次,请重新填写!");
                            //        throw new Exception("该物料:" + body.InvCode + "已启用批次,请重新填写!");
                            //    }
                            //}
                            //else
                            //{
                            //    if (body.BatchCode != "")
                            //    {
                            //        log.Error("该物料:" + body.InvCode + "未启用批次,请重新填写!");
                            //        throw new Exception("该物料:" + body.InvCode + "未启用批次,请重新填写!");
                            //    }
                            //}
                            irowno++;
                            #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 =(select MoDId from dbo.mom_moallocate where AllocateId='" + body.MODetailID + "')";
                            DataTable dtCheck = DBHelper.SQlReturnData(sql, cmd);
                            if (dtCheck != null && dtCheck.Rows.Count > 0)
                            {
                                mocode = dtCheck.Rows[0]["MoCode"].ToString();
                                seq = dtCheck.Rows[0]["SortSeq"].ToString();
                                if (dtCheck.Rows[0]["CloseUser"].ToString()!="")
                                    throw new Exception("工单号:" + dtCheck.Rows[0]["MoCode"].ToString() + ",行号:" + dtCheck.Rows[0]["SortSeq"].ToString() + ",已关闭,无法入库!");
                                sql = @"  select
                            count(c.AllocateID) num,d.number
                            from DBO.mom_order a 
                            left join DBO.mom_orderdetail b on a.moid = b.moid
                            left join DBO.mom_moallocate c on b.modid = c.modid
                            left join(select modid,COUNT(AllocateID) number from  DBO.mom_moallocate where WIPType=1 GROUP BY modid
                            ) d on b.modid = d.modid
                            where a.MoCode='{0}' and b.SortSeq='{1}'
                            GROUP BY d.number ";
                                sql = string.Format(sql, mocode, seq);
                                dtCheck = DBHelper.SQlReturnData(sql, cmd);
                                if (dtCheck != null && dtCheck.Rows.Count > 0)
                                {
                                    if (dtCheck.Rows[0]["num"].ToString() != dtCheck.Rows[0]["number"].ToString())
                                        isif = 1;
                                    else
                                        isif = 0;
                                }
                            }
                            #endregion

                            #region 判断是否都是联.副产品
                            sql = @"select ProductType from dbo.mom_moallocate where AllocateId='" + body.MODetailID + "'";
                            dtCheck = DBHelper.SQlReturnData(sql, cmd);
                            if (dtCheck != null && dtCheck.Rows.Count > 0)
                            {
                                string ProductType = dtCheck.Rows[0]["ProductType"].ToString();
                                if (Convert.ToInt32(ProductType) == 1)
                                    throw new Exception("该返工工单存在非联、副产品子件,无法入库!");
                            }
                            #endregion
                            #region 生成产成品入库单表体
                            sql = @"INSERT INTO dbo.rdrecords10
                                    ( AutoID ,ID ,cInvCode ,iQuantity ,cBatch ,iFlag ,iNum,
                                      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 ,cFree1,cFree2,cFree3,cFree4,cFree5,cFree6,cFree7,cFree8,cFree9,cFree10)
                            SELECT @AutoID,@ID,@cInvCode,@iQuantity,@cBatch,0,@iNum,
                            		a.Define22,a.Define23,a.Define24,a.Define25,a.Define26,a.Define27,
                            		@cItemCode,null,c.Qty-isnull(c.QualifiedInQty,0),c.Define28,
                            		c.Define29,c.Define30,c.Define31,c.Define32,c.Define33,c.Define34,
                            		c.Define35,c.Define36,c.Define37,c.MoDId,0,0,
                            		0,0,1,b.MoCode,a.SortSeq,0,
                            		a.AllocateId,c.OrderType,c.OrderCode,c.OrderSeq,c.SoDId,c.SoType,c.SoCode,c.SoSeq,@irowno,0,@cFree1,@cFree2,@cFree3,@cFree4,@cFree5,@cFree6,@cFree7,@cFree8,@cFree9,@cFree10
                              FROM dbo.mom_moallocate a
							INNER join dbo.mom_orderdetail c on a.MoDId=c.MoDId
							 INNER JOIN dbo.mom_order b ON c.MoId=b.MoId
							WHERE a.AllocateId='" + 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("@iNum", body.Amount.ToString("0.00")));
                            cmd.Parameters.Add(new SqlParameter("@cBatch", ""));
                            cmd.Parameters.Add(new SqlParameter("@cItemCode", body.ProjectCode));
                            cmd.Parameters.Add(new SqlParameter("@irowno", irowno));
                            cmd.Parameters.Add(new SqlParameter("@cFree1", body.cFree1));
                            cmd.Parameters.Add(new SqlParameter("@cFree2", body.cFree2));
                            cmd.Parameters.Add(new SqlParameter("@cFree3", body.cFree3));
                            cmd.Parameters.Add(new SqlParameter("@cFree4", body.cFree4));
                            cmd.Parameters.Add(new SqlParameter("@cFree5", body.cFree5));
                            cmd.Parameters.Add(new SqlParameter("@cFree6", body.cFree6));
                            cmd.Parameters.Add(new SqlParameter("@cFree7", body.cFree7));
                            cmd.Parameters.Add(new SqlParameter("@cFree8", body.cFree8));
                            cmd.Parameters.Add(new SqlParameter("@cFree9", body.cFree9));
                            cmd.Parameters.Add(new SqlParameter("@cFree10", body.cFree10));
                            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
                            if (isif == 1)
                            {
                                if (head.CompleteVerification)
                                {
                                    #region 齐套检验
                                    sql = @" select cValue from AccInformation where cName=N'iMOProInCtrlBySet' ";
                                    DataTable qt = DBHelper.SQlReturnData(sql, cmd);
                                    if (qt != null && qt.Rows.Count > 0)
                                    {
                                        if (qt.Rows[0]["cValue"].ToString() == "1")
                                        {

                                            sql = @"select MoCode,SortSeq,MIN(lotqty) min_lotqty from 
                                    (
                                    select
                                    a.MoCode,b.SortSeq,
                                    case when aa.AllocateId IS null then c.AllocateId else aa.AllocateId
                                    end as AllocateId,sum(c.Qty) as Qty,SUM(c.IssQty) IssQty,SUM(c.IssQty)/(SUM(c.Qty)/b.Qty) lotqty
                                    from DBO.mom_order a 
                                    left join DBO.mom_orderdetail b on a.moid = b.moid
                                    left join DBO.mom_moallocate c on b.modid = c.modid
                                    left join 
                                    (select d.AllocateId,e.InvCode,d.MoallocateSubId from 
                                    DBO.mom_moallocatesub d 
                                    left join DBO.bas_part e ON d.partid = e.PartId ) aa on   c.MoallocateSubId=aa.MoallocateSubId
                                    left join DBO.Inventory_Sub f on c.InvCode=f.cInvSubCode
                                    where a.MoCode='{0}' and b.SortSeq='{1}'
                                    and c.WIPType<>1 and c.Qty<>0 and c.ByproductFlag<>1
                                    group by a.MoCode,b.SortSeq,case when aa.AllocateId IS null then c.AllocateId else aa.AllocateId end ,b.Qty 
                                    ) tt
                                    group by MoCode,SortSeq";
                                            sql = string.Format(sql, mocode, seq);
                                            qt = DBHelper.SQlReturnData(sql, cmd);
                                            if (qt == null || qt.Rows.Count == 0)
                                                throw new Exception("该物料:" + body.InvCode + @"在订单内未领料!");
                                            else
                                            {
                                                if (Convert.ToDecimal(qt.Rows[0]["min_lotqty"]) <= 0)
                                                    throw new Exception("该物料:" + body.InvCode + @"在订单内未领料<=0!");
                                            }
                                        }
                                        else if (qt.Rows[0]["cValue"].ToString() == "2")
                                        {
                                            sql = @"select cValue from AccInformation where cName=N'bControlKeyMaterial'";
                                            qt = DBHelper.SQlReturnData(sql, cmd);
                                            if (qt != null && qt.Rows.Count > 0)
                                            {
                                                if (qt.Rows[0]["cValue"].ToString() == "true")
                                                {
                                                    sql = @"select MoCode,SortSeq,MIN(lotqty) min_lotqty from 
                                    (
                                    select
                                    a.MoCode,b.SortSeq,
                                    case when aa.AllocateId IS null then c.AllocateId else aa.AllocateId
                                    end as AllocateId,sum(c.Qty) as Qty,SUM(c.IssQty) IssQty,SUM(c.IssQty)/(SUM(c.Qty)/b.Qty) lotqty
                                    from DBO.mom_order a 
                                    left join DBO.mom_orderdetail b on a.moid = b.moid
                                    left join DBO.mom_moallocate c on b.modid = c.modid
                                    left join 
                                    (select d.AllocateId,e.InvCode,d.MoallocateSubId from 
                                    DBO.mom_moallocatesub d 
                                    left join DBO.bas_part e ON d.partid = e.PartId ) aa on   c.MoallocateSubId=aa.MoallocateSubId
                                    left join DBO.Inventory_Sub f on c.InvCode=f.cInvSubCode
                                    where a.MoCode='{0}' and b.SortSeq='{1}'
                                    and c.WIPType<>1 and c.Qty<>0 and c.ByproductFlag<>1 and f.bInvKeyPart=1
                                    group by a.MoCode,b.SortSeq,case when aa.AllocateId IS null then c.AllocateId else aa.AllocateId end ,b.Qty 
                                    ) tt
                                    group by MoCode,SortSeq";
                                                    sql = string.Format(sql, mocode, seq);
                                                    qt = DBHelper.SQlReturnData(sql, cmd);

                                                    if (qt == null || qt.Rows.Count == 0)
                                                    {
                                                        throw new Exception("该物料:" + body.InvCode + @"在订单内未有可用领料!");
                                                    }
                                                    else
                                                    {
                                                        if (Convert.ToDecimal(qt.Rows[0]["min_lotqty"]) <= 0)
                                                        {
                                                            throw new Exception("该物料:" + body.InvCode + @"在订单内未领料!");
                                                        }
                                                        else if (Convert.ToDecimal(qt.Rows[0]["min_lotqty"]) - body.Quantity <= 0)
                                                        {
                                                            throw new Exception("该物料:" + body.InvCode + @"入库数量大于关键物料领料套数!");
                                                        }
                                                    }
                                                }
                                                else
                                                {
                                                    sql = @"select MoCode,SortSeq,MIN(lotqty) min_lotqty from 
                                    (
                                    select
                                    a.MoCode,b.SortSeq,
                                    case when aa.AllocateId IS null then c.AllocateId else aa.AllocateId
                                    end as AllocateId,sum(c.Qty) as Qty,SUM(c.IssQty) IssQty,SUM(c.IssQty)/(SUM(c.Qty)/b.Qty) lotqty
                                    from DBO.mom_order a 
                                    left join DBO.mom_orderdetail b on a.moid = b.moid
                                    left join DBO.mom_moallocate c on b.modid = c.modid
                                    left join 
                                    (select d.AllocateId,e.InvCode,d.MoallocateSubId from 
                                    DBO.mom_moallocatesub d 
                                    left join DBO.bas_part e ON d.partid = e.PartId ) aa on   c.MoallocateSubId=aa.MoallocateSubId
                                    left join DBO.Inventory_Sub f on c.InvCode=f.cInvSubCode
                                    where a.MoCode='{0}' and b.SortSeq='{1}'
                                    and c.WIPType<>1 and c.Qty<>0 and c.ByproductFlag<>1
                                    group by a.MoCode,b.SortSeq,case when aa.AllocateId IS null then c.AllocateId else aa.AllocateId end ,b.Qty 
                                    ) tt
                                    group by MoCode,SortSeq";
                                                    sql = string.Format(sql, mocode, seq);
                                                    qt = DBHelper.SQlReturnData(sql, cmd);

                                                    if (qt == null || qt.Rows.Count == 0)
                                                    {
                                                        throw new Exception("该物料:" + body.InvCode + @"在订单内未有可用领料!");
                                                    }
                                                    else
                                                    {
                                                        if (Convert.ToDecimal(qt.Rows[0]["min_lotqty"]) <= 0)
                                                        {
                                                            throw new Exception("该物料:" + body.InvCode + @"在订单内未领料!");
                                                        }
                                                        else if (Convert.ToDecimal(qt.Rows[0]["min_lotqty"]) - body.Quantity <= 0)
                                                        {
                                                            throw new Exception("该物料:" + body.InvCode + @"入库数量大于领料套数!");
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    #endregion
                                }
                            }

                            #region 回写生产子件已领数量
                            sql = @"
                        UPDATE a SET a.IssQty=ISNULL(a.IssQty,0)+" + body.Quantity + @" from dbo.mom_moallocate a 
                        inner join dbo.mom_orderdetail b on  a.MoDId=b.MoDId
                        where a.AllocateId='" + body.MODetailID + "' and a.SortSeq='" + body.Sequence + @"'
                        ";
                            DBHelper.CmdExecuteNonQuery(sql, cmd, "回写生产订单入库数量失败!");
                            #endregion

                            sql = @"select isnull(IssQty,0)fOutQuantity,isnull(Qty,0)iQuantity,ISNULL(AuxQty, 0)iNum,ISNULL(NiNum, 0)NiNum,ISNULL(AuxQty, 0)-ISNULL(NiNum, 0) SiNum from mom_moallocate a
                        LEFT JOIN (select sum(iNum) NiNum,iorderdid from rdrecords10 GROUP BY iorderdid) b on a.AllocateId=b.iorderdid
                        where  a.AllocateId='" + body.MODetailID + "'";
                            DataTable dtDisCheck = DBHelper.SQlReturnData(sql, cmd);
                            if (dtDisCheck != null && dtDisCheck.Rows.Count > 0)
                            {
                                foreach (DataRow item in dtDisCheck.Rows)
                                {
                                    if (Convert.ToDecimal(item["fOutQuantity"].ToString()) == Convert.ToDecimal(item["iQuantity"].ToString()))
                                    {
                                        if (Convert.ToDecimal(item["iNum"].ToString()) != 0)
                                        {
                                            if (Convert.ToDecimal(item["SiNum"].ToString()) != 0)
                                            {
                                                sql = @"Update rdrecords10 set iNum=isnull(iNum,0)+(" + item["SiNum"].ToString() + ") where autoid='" + iChildId + "' ";
                                                body.Amount = (Convert.ToDecimal(body.Amount.ToString("0.00"))) + (Convert.ToDecimal(item["SiNum"].ToString()));
                                                DBHelper.CmdExecuteNonQuery(sql, cmd, "辅计量余数处理失败!");
                                            }
                                        }
                                    }
                                }

                            }

                            #region 更新现存量
                            key.cBustypeUN = "成品入库";
                            key.cVouchTypeUN = "10";
                            key.TableName = "IA_ST_UnAccountVouch10";
                            //DBHelper.UpdateCurrentStockNEW(cmd, body.InvCode, head.WHCode, body.BatchCode, body.Quantity, body.cFree1, body.cFree2, body.cFree3, body.cFree4, body.cFree5, body.cFree6, body.cFree7, body.cFree8, body.cFree9, body.cFree10, key);
                            DBHelper.UpdateCurrentStockCCGC(cmd, body.InvCode, head.WHCode, "", body.Quantity, body.Amount, body.cFree1,
                                  body.cFree2, body.cFree3, body.cFree4, body.cFree5, body.cFree6, body.cFree7, body.cFree8, body.cFree9, body.cFree10,
                                  "", key, "", "", "", "", 0, 0, 0, 0, 0, 0, 0, 0, iFatherId, iChildId);
                            #endregion

                            #region 判断工单行是否全部入库
                            sql = "select Qty from mom_moallocate WHERE MoDId=(select MoDId from dbo.mom_moallocate where AllocateId='" + body.MODetailID + @"') and IssQty-qty<0 
                                union all
                                select Qty from mom_orderdetail where MoDId=(select MoDId from dbo.mom_moallocate where AllocateId='" + body.MODetailID + @"') and QualifiedInQty-Qty<0";
                            DataTable dtClose = DBHelper.SQlReturnData(sql, cmd);
                            if (dtClose.Rows.Count == 0)
                            {
                                sql = @"  
                            update mom_orderdetail set CloseTime = GETDATE(),CloseDate= CONVERT(NVARCHAR(15),GETDATE(),23), CloseUser ='" + head.User + "',Status=4 where MODId=(select MoDId from dbo.mom_moallocate where AllocateId='" + body.MODetailID + @"')";
                                DBHelper.CmdExecuteNonQuery(sql, cmd, "生产订单行关闭失败!");
                            }
                            #endregion

                            iChildId--;
                        }
                        #endregion
                    }
                    #endregion


                    #region 入库倒冲
                    foreach (ICSManufactureReceiveDocASK head in Bills)
                    {
                        if (WorkPoint != head.WorkPoint)
                            continue;

                        if (head.TYPE != "入库")
                            continue;

                        if (!DBHelper.IsInventoryConsolidation(cmd, head.WorkPoint))
                            throw new Exception("U8正在整理现存量,请稍后再试");

                        string[] ss = head.WorkPoint.Split('_');
                        ERPDB = ss[1];
                        ICSUserInfo userInfo = new ICSUserInfo();
                        userInfo = DBHelper.GetPersonInfo(head.User, cmd);
                        string[] dd = CRNALL.Split('~');
                        string crdname = dd[0];
                        string carname = dd[1];
                        string surface = dd[2];

                        string[] d = CRNA.Split('~');
                        string crdname1 = d[0];
                        string carname1 = d[1];
                        string surface1 = d[2];

                        string cardnewcode = DBHelper.GetCardNumber(carname, cmd);
                        string cardnewcode1 = DBHelper.GetCardNumber(carname1, cmd);
                        num = head.details.Count();
                        Dictionary<string, int> dic = DBHelper.GetAllCode("" + ERPDB + "", surface, "" + num + "", head.WorkPoint);
                        int iFatherId = Convert.ToInt32(dic["iFatherId"].ToString());
                        int iChildId = Convert.ToInt32(dic["iChildId"].ToString());
                        DateTime date = DateTime.Now;
                        string DEF_ID = DBHelper.GetDefaultTemplate(cardnewcode, cmd);

                        string cRDcode = DBHelper.GetRDCode(crdname, cmd);
                        string iBaseCodeLen = DBHelper.GetAllRDCode(cardnewcode, "" + date + "", "admin", cRDcode, head.WorkPoint, cmd);
                        string cRDcode1 = DBHelper.GetRDCode(crdname1, cmd);
                        string DEF_ID1 = DBHelper.GetDefaultTemplate(cardnewcode1, 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", userInfo.UserName));
                        cmd.Parameters.Add(new SqlParameter("@cMaker", userInfo.UserName));
                        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
                        if (news != 0)
                        {

                            foreach (WH item in LWH)
                            {
                                Dictionary<string, int> dic1 = DBHelper.GetAllCode("" + ERPDB + "", surface1, "1", head.WorkPoint);
                                int iFatherId1 = Convert.ToInt32(dic1["iFatherId"].ToString());

                                int iChildId1 = Convert.ToInt32(dic1["iChildId"].ToString());
                                DateTime date1 = DateTime.Now;
                                string iBaseCodeLen1 = DBHelper.GetAllRDCode(cardnewcode1, "" + date1 + "", "admin", cRDcode1, head.WorkPoint, cmd);
                                #region 材料出库单表头
                                sql = @"INSERT INTO dbo.rdrecord11
                            ( ID ,bRdFlag ,cVouchType ,cBusType ,cSource ,cWhCode ,dDate ,cBusCode,
                            cCode ,cRdCode ,cDepCode,cHandler ,bTransFlag ,cMaker ,
                            dVeriDate ,bpufirst ,biafirst ,VT_ID ,bIsSTQc 
                            ,cPsPcode ,cMPoCode ,iproorderid ,bFromPreYear ,
                            bIsLsQuery ,bIsComplement ,iDiscountTaxType ,ireturncount ,iverifystate ,
                            iswfcontrolled ,dnmaketime ,dnverifytime ,bredvouch ,iPrintCount,
                            iMQuantity)

                            SELECT TOP 1 @ID,0,'11','生产倒冲','产成品入库单',@cWhCode,CONVERT(NVARCHAR(15),GETDATE(),23),@cBusCode,
                            @cCode,@cRdCode,a.MDeptCode,@cHandler,0,@cMaker,
                            CONVERT(NVARCHAR(15),GETDATE(),23),0,0,@VT_ID,0,
                            null,b.MoCode,a.MoId,0,
                            0,0,0,0,0,
                            0,GETDATE(),GETDATE(),1,1,
                            null
                            FROM dbo.mom_orderdetail a
                            left JOIN dbo.mom_order b ON a.MoId=b.MoId 
                            left join mom_morder c on a.modid=c.modid
                            WHERE b.MoCode='" + head.MOCode + "'";
                                cmd.Parameters.Clear();
                                cmd.Parameters.Add(new SqlParameter("@ID", iFatherId1));
                                cmd.Parameters.Add(new SqlParameter("@cBusCode", iBaseCodeLen));
                                cmd.Parameters.Add(new SqlParameter("@cWhCode", item.WHCODE));
                                cmd.Parameters.Add(new SqlParameter("@cCode", iBaseCodeLen1));
                                cmd.Parameters.Add(new SqlParameter("@cHandler", userInfo.UserName));
                                cmd.Parameters.Add(new SqlParameter("@cMaker", userInfo.UserName));
                                cmd.Parameters.Add(new SqlParameter("@VT_ID", DEF_ID1));
                                cmd.Parameters.Add(new SqlParameter("@cRdCode", cRDcode1));
                                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);
                                }

                                item.ID = iFatherId1;

                                #endregion
                            }

                        }

                        #region 产成品入库单表体
                        int irow = 0;
                        foreach (ICSManufactureReceiveDocs body in head.details)
                        {
                            if (DBHelper.bInvBatch(body.InvCode, cmd) == true)
                            {
                                if (body.BatchCode == "")
                                {
                                    log.Error("该物料:" + body.InvCode + "已启用批次,请重新填写!");
                                    throw new Exception("该物料:" + body.InvCode + "已启用批次,请重新填写!");
                                }
                            }
                            else
                            {
                                if (body.BatchCode != "")
                                {
                                    log.Error("该物料:" + body.InvCode + "未启用批次,请重新填写!");
                                    throw new Exception("该物料:" + body.InvCode + "未启用批次,请重新填写!");
                                }
                            }
                            irow++;
                            #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)
                            {
                                mocode = dtCheck.Rows[0]["MoCode"].ToString();
                                seq = dtCheck.Rows[0]["SortSeq"].ToString();
                                if (dtCheck.Rows[0]["CloseUser"].ToString()!="")
                                {
                                    throw new Exception("工单号:" + dtCheck.Rows[0]["MoCode"].ToString() + ",行号:" + dtCheck.Rows[0]["SortSeq"].ToString() + ",已关闭,无法入库!");
                                }

                                sql = @"  select
                            count(c.AllocateID) num,d.number
                            from DBO.mom_order a 
                            left join DBO.mom_orderdetail b on a.moid = b.moid
                            left join DBO.mom_moallocate c on b.modid = c.modid
                            left join(select modid,COUNT(AllocateID) number from  DBO.mom_moallocate where WIPType=1 GROUP BY modid
                            ) d on b.modid = d.modid
                            where a.MoCode='{0}' and b.SortSeq='{1}'
                            GROUP BY d.number ";
                                sql = string.Format(sql, mocode, seq);
                                dtCheck = DBHelper.SQlReturnData(sql, cmd);
                                if (dtCheck != null && dtCheck.Rows.Count > 0)
                                {
                                    if (dtCheck.Rows[0]["num"].ToString() != dtCheck.Rows[0]["number"].ToString())
                                    {
                                        isif = 1;
                                    }
                                    else
                                    {
                                        isif = 0;
                                    }
                                }
                            }
                            #endregion
                            #region 判断是否为非标
                            sql = @"select MoClass from dbo.mom_orderdetail where MoDId='" + body.MODetailID + "'";
                            dtCheck = DBHelper.SQlReturnData(sql, cmd);
                            if (dtCheck != null && dtCheck.Rows.Count > 0)
                            {
                                MoClass = dtCheck.Rows[0]["MoClass"].ToString();
                            }
                            #endregion
                            #region 生成产成品入库单表体
                            sql = @"INSERT INTO dbo.rdrecords10
                                    ( AutoID ,ID ,cInvCode ,iQuantity ,cBatch ,iFlag ,iNum,
                                      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 ,cFree1,cFree2,cFree3,cFree4,cFree5,cFree6,cFree7,cFree8,cFree9,cFree10)
                            SELECT @AutoID,@ID,@cInvCode,@iQuantity,@cBatch,0,@iNum,
                            		a.Define22,a.Define23,a.Define24,a.Define25,a.Define26,a.Define27,
                            		@cItemCode,null,a.Qty-isnull(a.QualifiedInQty,0),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,@cFree1,@cFree2,@cFree3,@cFree4,@cFree5,@cFree6,@cFree7,@cFree8,@cFree9,@cFree10
                            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("@iNum", body.Amount.ToString("0.00")));
                            cmd.Parameters.Add(new SqlParameter("@iQuantity", body.Quantity));
                            cmd.Parameters.Add(new SqlParameter("@cBatch", body.BatchCode));
                            cmd.Parameters.Add(new SqlParameter("@cItemCode", body.ProjectCode));
                            cmd.Parameters.Add(new SqlParameter("@irowno", irow));
                            cmd.Parameters.Add(new SqlParameter("@cFree1", body.cFree1));
                            cmd.Parameters.Add(new SqlParameter("@cFree2", body.cFree2));
                            cmd.Parameters.Add(new SqlParameter("@cFree3", body.cFree3));
                            cmd.Parameters.Add(new SqlParameter("@cFree4", body.cFree4));
                            cmd.Parameters.Add(new SqlParameter("@cFree5", body.cFree5));
                            cmd.Parameters.Add(new SqlParameter("@cFree6", body.cFree6));
                            cmd.Parameters.Add(new SqlParameter("@cFree7", body.cFree7));
                            cmd.Parameters.Add(new SqlParameter("@cFree8", body.cFree8));
                            cmd.Parameters.Add(new SqlParameter("@cFree9", body.cFree9));
                            cmd.Parameters.Add(new SqlParameter("@cFree10", body.cFree10));

                            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
                            if (isif == 1)
                            {
                                if (head.CompleteVerification)
                                {
                                    #region 齐套检验
                                    sql = @" select cValue from AccInformation where cName=N'iMOProInCtrlBySet' ";
                                    DataTable qt = DBHelper.SQlReturnData(sql, cmd);
                                    if (qt != null && qt.Rows.Count > 0)
                                    {
                                        if (qt.Rows[0]["cValue"].ToString() == "1")
                                        {

                                            sql = @"select MoCode,SortSeq,MIN(lotqty) min_lotqty from 
                                    (
                                    select
                                    a.MoCode,b.SortSeq,
                                    case when aa.AllocateId IS null then c.AllocateId else aa.AllocateId
                                    end as AllocateId,sum(c.Qty) as Qty,SUM(c.IssQty) IssQty,SUM(c.IssQty)/(SUM(c.Qty)/b.Qty) lotqty
                                    from DBO.mom_order a 
                                    left join DBO.mom_orderdetail b on a.moid = b.moid
                                    left join DBO.mom_moallocate c on b.modid = c.modid
                                    left join 
                                    (select d.AllocateId,e.InvCode,d.MoallocateSubId from 
                                    DBO.mom_moallocatesub d 
                                    left join DBO.bas_part e ON d.partid = e.PartId ) aa on   c.MoallocateSubId=aa.MoallocateSubId
                                    left join DBO.Inventory_Sub f on c.InvCode=f.cInvSubCode
                                    where a.MoCode='{0}' and b.SortSeq='{1}'
                                    and c.WIPType<>1 and c.Qty<>0 and c.ByproductFlag<>1
                                    group by a.MoCode,b.SortSeq,case when aa.AllocateId IS null then c.AllocateId else aa.AllocateId end ,b.Qty 
                                    ) tt
                                    group by MoCode,SortSeq";
                                            sql = string.Format(sql, mocode, seq);
                                            qt = DBHelper.SQlReturnData(sql, cmd);
                                            if (qt == null || qt.Rows.Count == 0)
                                            {
                                                throw new Exception("该物料:" + body.InvCode + @"在订单内未领料!");
                                            }
                                            else
                                            {
                                                if (Convert.ToDecimal(qt.Rows[0]["min_lotqty"]) <= 0)
                                                {
                                                    throw new Exception("该物料:" + body.InvCode + @"在订单内未领料<=0!");
                                                }
                                            }
                                        }
                                        else if (qt.Rows[0]["cValue"].ToString() == "2")
                                        {
                                            sql = @"select cValue from AccInformation where cName=N'bControlKeyMaterial'";
                                            qt = DBHelper.SQlReturnData(sql, cmd);
                                            if (qt != null && qt.Rows.Count > 0)
                                            {
                                                if (qt.Rows[0]["cValue"].ToString() == "true")
                                                {
                                                    sql = @"select MoCode,SortSeq,MIN(lotqty) min_lotqty from 
                                    (
                                    select
                                    a.MoCode,b.SortSeq,
                                    case when aa.AllocateId IS null then c.AllocateId else aa.AllocateId
                                    end as AllocateId,sum(c.Qty) as Qty,SUM(c.IssQty) IssQty,SUM(c.IssQty)/(SUM(c.Qty)/b.Qty) lotqty
                                    from DBO.mom_order a 
                                    left join DBO.mom_orderdetail b on a.moid = b.moid
                                    left join DBO.mom_moallocate c on b.modid = c.modid
                                    left join 
                                    (select d.AllocateId,e.InvCode,d.MoallocateSubId from 
                                    DBO.mom_moallocatesub d 
                                    left join DBO.bas_part e ON d.partid = e.PartId ) aa on   c.MoallocateSubId=aa.MoallocateSubId
                                    left join DBO.Inventory_Sub f on c.InvCode=f.cInvSubCode
                                    where a.MoCode='{0}' and b.SortSeq='{1}'
                                    and c.WIPType<>1 and c.Qty<>0 and c.ByproductFlag<>1 and f.bInvKeyPart=1
                                    group by a.MoCode,b.SortSeq,case when aa.AllocateId IS null then c.AllocateId else aa.AllocateId end ,b.Qty 
                                    ) tt
                                    group by MoCode,SortSeq";
                                                    sql = string.Format(sql, mocode, seq);
                                                    qt = DBHelper.SQlReturnData(sql, cmd);

                                                    if (qt == null || qt.Rows.Count == 0)
                                                    {
                                                        throw new Exception("该物料:" + body.InvCode + @"在订单内未有可用领料!");
                                                    }
                                                    else
                                                    {
                                                        if (Convert.ToDecimal(qt.Rows[0]["min_lotqty"]) <= 0)
                                                        {
                                                            throw new Exception("该物料:" + body.InvCode + @"在订单内未领料!");
                                                        }
                                                        else if (Convert.ToDecimal(qt.Rows[0]["min_lotqty"]) - body.Quantity <= 0)
                                                        {
                                                            throw new Exception("该物料:" + body.InvCode + @"入库数量大于关键物料领料套数!");
                                                        }
                                                    }
                                                }
                                                else
                                                {

                                                    sql = @"select MoCode,SortSeq,MIN(lotqty) min_lotqty from 
                                    (
                                    select
                                    a.MoCode,b.SortSeq,
                                    case when aa.AllocateId IS null then c.AllocateId else aa.AllocateId
                                    end as AllocateId,sum(c.Qty) as Qty,SUM(c.IssQty) IssQty,SUM(c.IssQty)/(SUM(c.Qty)/b.Qty) lotqty
                                    from DBO.mom_order a 
                                    left join DBO.mom_orderdetail b on a.moid = b.moid
                                    left join DBO.mom_moallocate c on b.modid = c.modid
                                    left join 
                                    (select d.AllocateId,e.InvCode,d.MoallocateSubId from 
                                    DBO.mom_moallocatesub d 
                                    left join DBO.bas_part e ON d.partid = e.PartId ) aa on   c.MoallocateSubId=aa.MoallocateSubId
                                    left join DBO.Inventory_Sub f on c.InvCode=f.cInvSubCode
                                    where a.MoCode='{0}' and b.SortSeq='{1}'
                                    and c.WIPType<>1 and c.Qty<>0 and c.ByproductFlag<>1
                                    group by a.MoCode,b.SortSeq,case when aa.AllocateId IS null then c.AllocateId else aa.AllocateId end ,b.Qty 
                                    ) tt
                                    group by MoCode,SortSeq";
                                                    sql = string.Format(sql, mocode, seq);
                                                    qt = DBHelper.SQlReturnData(sql, cmd);

                                                    if (qt == null || qt.Rows.Count == 0)
                                                    {
                                                        throw new Exception("该物料:" + body.InvCode + @"在订单内未有可用领料!");
                                                    }
                                                    else
                                                    {
                                                        if (Convert.ToDecimal(qt.Rows[0]["min_lotqty"]) <= 0)
                                                        {
                                                            throw new Exception("该物料:" + body.InvCode + @"在订单内未领料!");
                                                        }
                                                        else if (Convert.ToDecimal(qt.Rows[0]["min_lotqty"]) - body.Quantity <= 0)
                                                        {
                                                            throw new Exception("该物料:" + body.InvCode + @"入库数量大于领料套数!");
                                                        }
                                                    }

                                                }
                                            }

                                        }
                                    }

                                    #endregion
                                }
                            }

                            #region 回写生产订单入库数量
                            sql = @"UPDATE dbo.mom_orderdetail SET QualifiedInQty=ISNULL(QualifiedInQty,0)+" + body.Quantity + " where MoDId='" + body.MODetailID + "'";
                            DBHelper.CmdExecuteNonQuery(sql, cmd, "回写生产订单入库数量失败!");
                            #endregion
                            if (Convert.ToInt32(MoClass) == 1)
                            {
                                #region 判断工单行是否全部入库
                                sql = "select Qty from mom_moallocate WHERE MoDId='" + body.MODetailID + @"' and IssQty-qty<0 and ProductType=1
                                union all
                            select Qty from mom_orderdetail where MoDId='" + body.MODetailID + @"' and QualifiedInQty-Qty<0";

                                DataTable dtClose = DBHelper.SQlReturnData(sql, cmd);
                                if (dtClose.Rows.Count == 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
                            }
                            else
                            {
                                #region 判断工单行是否全部入库
                                sql = "select Qty from mom_moallocate WHERE MoDId='" + body.MODetailID + @"' and IssQty-qty<0 
                                union all
                                select Qty from mom_orderdetail where MoDId='" + body.MODetailID + @"' and QualifiedInQty-Qty<0
                        ";

                                DataTable dtClose = DBHelper.SQlReturnData(sql, cmd);
                                if (dtClose.Rows.Count == 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
                            }

                            sql = @"select isnull(QualifiedInQty,0)fOutQuantity,isnull(Qty,0)iQuantity,ISNULL(AuxQty, 0)iNum,ISNULL(NiNum, 0)NiNum,ISNULL(AuxQty, 0)-ISNULL(NiNum, 0) SiNum from mom_orderdetail a
                        LEFT JOIN (select sum(iNum) NiNum,iMPoIds from rdrecords10 GROUP BY iMPoIds) b on a.MoDId=b.iMPoIds
                        where  a.MoDId='" + body.MODetailID + "'";
                            DataTable dtDisCheck = DBHelper.SQlReturnData(sql, cmd);
                            if (dtDisCheck != null && dtDisCheck.Rows.Count > 0)
                            {
                                foreach (DataRow item in dtDisCheck.Rows)
                                {
                                    if (Convert.ToDecimal(item["fOutQuantity"].ToString()) == Convert.ToDecimal(item["iQuantity"].ToString()))
                                    {
                                        if (Convert.ToDecimal(item["iNum"].ToString()) != 0)
                                        {
                                            if (Convert.ToDecimal(item["SiNum"].ToString()) != 0)
                                            {
                                                sql = @"Update rdrecords10 set iNum=isnull(iNum,0)+(" + item["SiNum"].ToString() + ") where autoid='" + iChildId + "' ";
                                                body.Amount = (Convert.ToDecimal(body.Amount.ToString("0.00"))) + (Convert.ToDecimal(item["SiNum"].ToString()));

                                                DBHelper.CmdExecuteNonQuery(sql, cmd, "辅计量余数处理失败!");
                                            }
                                        }
                                    }
                                }

                            }
                            #region 更新现存量
                            key.cBustypeUN = "成品入库";
                            key.cVouchTypeUN = "10";
                            key.TableName = "IA_ST_UnAccountVouch10";
                            //DBHelper.UpdateCurrentStockNEW(cmd, body.InvCode, head.WHCode, body.BatchCode, body.Quantity, body.cFree1, body.cFree2, body.cFree3, body.cFree4, body.cFree5, body.cFree6, body.cFree7, body.cFree8, body.cFree9, body.cFree10, key);
                            DBHelper.UpdateCurrentStockCCGC(cmd, body.InvCode, head.WHCode, body.BatchCode, body.Quantity, body.Amount, body.cFree1,
                                      body.cFree2, body.cFree3, body.cFree4, body.cFree5, body.cFree6, body.cFree7, body.cFree8, body.cFree9, body.cFree10,
                                      "", key, "", "", "", "", 0, 0, 0, 0, 0, 0, 0, 0,iFatherId, iChildId);
                            #endregion
                            num = body.detailss.Count();
                            Dictionary<string, int> dic2 = DBHelper.GetAllCode("" + ERPDB + "", surface1, "" + num + "", head.WorkPoint);
                            int iFatherId2 = Convert.ToInt32(dic2["iFatherId"].ToString());
                            int iChildId2 = Convert.ToInt32(dic2["iChildId"].ToString());
                            iFatherIdTree = "";
                            irownnew = 0;
                            foreach (ICSManufactureReceiveDocss item in body.detailss)
                            {
                                if (item.PickID != null && item.PickID != "")
                                {
                                    foreach (WH wh in LWH)
                                    {
                                        if (wh.WHCODE == item.WHCode)
                                        {
                                            out11 = wh.ID;
                                            iseq = wh.seq + 1;
                                            wh.seq += 1;
                                        }
                                    }
                                

                                    irownnew++;
                                    sql = @"INSERT INTO dbo.rdrecords11
                                    ( AutoID ,ID ,cInvCode ,iQuantity ,cBatch ,iFlag ,iNum,
                                        cItemCode ,cName ,iNQuantity ,iMPoIds ,bLPUseFree ,
                                        iOriTrackID ,bCosting ,bVMIUsed ,cmocode ,invcode ,imoseq ,
                                        iopseq ,iExpiratDateCalcu ,iorderdid ,iordertype ,isotype ,
                                        ipesodid ,ipesotype ,cpesocode ,ipesoseq ,irowno ,
                                        bcanreplace ,iposflag,cFree1,cFree2,cFree3,cFree4,cFree5,cFree6,cFree7,cFree8,cFree9,cFree10)
                            SELECT @AutoID,@ID,a.InvCode,@iQuantity,@cBatch,0,@iNum,
                                	@cItemCode,null,a.Qty,a.AllocateId,0,
                                	0,1,0,c.MoCode,b.InvCode,b.SortSeq,
                                	'0000',0,0,0,0,
                                	a.AllocateId,'7',c.MoCode,b.SortSeq,@irowno,
                                    0,null,@cFree1,@cFree2,@cFree3,@cFree4,@cFree5,@cFree6,@cFree7,@cFree8,@cFree9,@cFree10
                            FROM dbo.mom_moallocate a
                            INNER JOIN dbo.mom_orderdetail b ON a.MoDId=b.MoDId
                            INNER JOIN dbo.mom_order c ON b.MoId=c.MoId
                            WHERE a.AllocateId='" + item.PickID + "'";
                                    cmd.Parameters.Clear();

                                    cmd.Parameters.Add(new SqlParameter("@AutoID", iChildId2));
                                    cmd.Parameters.Add(new SqlParameter("@ID", out11));
                                    cmd.Parameters.Add(new SqlParameter("@iQuantity", item.Quantity));
                                    cmd.Parameters.Add(new SqlParameter("@iNum", item.Amount.ToString("0.00")));
                                    cmd.Parameters.Add(new SqlParameter("@cBatch", item.BatchCode));
                                    cmd.Parameters.Add(new SqlParameter("@cItemCode", item.ProjectCode));
                                    cmd.Parameters.Add(new SqlParameter("@irowno", iseq));
                                    cmd.Parameters.Add(new SqlParameter("@cFree1", item.cFree1));
                                    cmd.Parameters.Add(new SqlParameter("@cFree2", item.cFree2));
                                    cmd.Parameters.Add(new SqlParameter("@cFree3", item.cFree3));
                                    cmd.Parameters.Add(new SqlParameter("@cFree4", item.cFree4));
                                    cmd.Parameters.Add(new SqlParameter("@cFree5", item.cFree5));
                                    cmd.Parameters.Add(new SqlParameter("@cFree6", item.cFree6));
                                    cmd.Parameters.Add(new SqlParameter("@cFree7", item.cFree7));
                                    cmd.Parameters.Add(new SqlParameter("@cFree8", item.cFree8));
                                    cmd.Parameters.Add(new SqlParameter("@cFree9", item.cFree9));
                                    cmd.Parameters.Add(new SqlParameter("@cFree10", item.cFree10));

                                    cmd.CommandText = sql;
                                    try
                                    {
                                        int count = cmd.ExecuteNonQuery();
                                        if (count <= 0)
                                        {
                                            log.Error("生成材料出库单表体失败,受影响行数<=0;");
                                            throw new Exception("生成材料出库单表体失败,受影响行数<=0;");
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        log.Error("生成材料出库单表体失败" + sql, ex);
                                        throw new Exception("生成材料出库单表体失败 " + sql, ex);
                                    }
                                    #region 回写工单子件已领数量
                                    sql = "update mom_moallocate set IssQty=isnull(IssQty,0)+" + item.Quantity + ",RequisitionIssQty=isnull(RequisitionIssQty,0)+(" + item.Quantity + ") where AllocateId='" + item.PickID + "' ";
                                    DBHelper.CmdExecuteNonQuery(sql, cmd, "回写工单子件已领数量失败!");
                                    #endregion

                                    sql = @"select isnull(Issqty,0)fOutQuantity,isnull(qty,0)iQuantity,ISNULL(AuxQty, 0)iNum,ISNULL(NiNum, 0)NiNum,ISNULL(AuxQty, 0)-ISNULL(NiNum, 0) SiNum from mom_moallocate a
                        LEFT JOIN (select sum(iNum) NiNum,iMPoIds from rdrecords11 GROUP BY iMPoIds) b on a.AllocateId=b.iMPoIds
                        where  a.AllocateId='" + item.PickID + "'";
                                    dtDisCheck = DBHelper.SQlReturnData(sql, cmd);
                                    if (dtDisCheck != null && dtDisCheck.Rows.Count > 0)
                                    {
                                        foreach (DataRow item1 in dtDisCheck.Rows)
                                        {
                                            if (Convert.ToDecimal(item1["fOutQuantity"].ToString()) == Convert.ToDecimal(item1["iQuantity"].ToString()))
                                            {
                                                if (Convert.ToDecimal(item1["iNum"].ToString()) != 0)
                                                {
                                                    if (Convert.ToDecimal(item1["SiNum"].ToString()) != 0)
                                                    {
                                                        sql = @"Update rdrecords11 set iNum=isnull(iNum,0)+(" + item1["SiNum"].ToString() + ") where autoid='" + iChildId2 + "' ";
                                                        body.Amount = (Convert.ToDecimal(body.Amount.ToString("0.00"))) + (Convert.ToDecimal(item1["SiNum"].ToString()));

                                                        DBHelper.CmdExecuteNonQuery(sql, cmd, "辅计量余数处理失败!");
                                                    }
                                                }
                                            }
                                        }

                                    }
                                    //更新现存量
                                    key.cBustypeUN = "领料";
                                    key.cVouchTypeUN = "11";
                                    key.TableName = "IA_ST_UnAccountVouch11";
                                    //DBHelper.UpdateCurrentStockNEW(cmd, item.InvCode, item.WHCode, item.BatchCode, -item.Quantity, item.cFree1, item.cFree2, item.cFree3, item.cFree4, item.cFree5, item.cFree6, item.cFree7, item.cFree8, item.cFree9, item.cFree10, key);
                                    DBHelper.UpdateCurrentStockCCGC(cmd, item.InvCode, item.WHCode, item.BatchCode, -item.Quantity, -item.Amount, item.cFree1,
                                        item.cFree2, item.cFree3, item.cFree4, item.cFree5, item.cFree6, item.cFree7, item.cFree8, item.cFree9, item.cFree10,
                                        "", key, "", "", "", "", 0, 0, 0, 0, 0, 0, 0, 0, out11, iChildId2);

                                    iFatherIdTree += "'" + out11 + "',";
                                    iChildId2--;
                                }
                            }
                            iFatherIdTwo = "'" + iFatherId + "',";
                            iChildId--;
                        }
                        #endregion
                        #region 查询
                        if (news == 0)
                        {
                            sql = @" select top 1 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 DISTINCT a.ID as IDs, b.AutoID as DetailID,CAST(b.iMPoIds as char) as IDSS ,b.irowno as Sequence  ,b.cInvCode as InvCode ,
                            b.iQuantity as Quantity ,b.iNum as Amount,b.iMPoIds as MODetailID,
                            isnull(b.cItemCode,'') ProjectCode,isnull(b.cbatch,'') cBatch,'' version ,'' brand,
                            isnull(b.cFree1,'') as cFree1,
                            isnull(b.cFree2,'') as cFree2,
                            isnull(b.cFree3,'') as cFree3,
                            isnull(b.cFree4,'') as cFree4,
                            isnull(b.cFree5,'') as cFree5,
                            isnull(b.cFree6,'') as cFree6,
                            isnull(b.cFree7,'') as cFree7,
                            isnull(b.cFree8,'') as cFree8,
                            isnull(b.cFree9,'') as cFree9,
                            isnull(b.cFree10,'') as cFree10

                            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(','));
                        }
                        else
                        {
                            sql = @" select top 1 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 DISTINCT a.ID as IDs, b.AutoID as DetailID,CAST(b.iMPoIds as char) as IDSS ,b.irowno as Sequence  ,b.cInvCode as InvCode ,
                            b.iQuantity as Quantity ,b.iNum as Amount,b.iMPoIds as MODetailID ,
                            isnull(b.cItemCode,'') ProjectCode,isnull(b.cbatch,'') cBatch,'' version ,'' brand,
                            isnull(b.cFree1,'') as cFree1,
                            isnull(b.cFree2,'') as cFree2,
                            isnull(b.cFree3,'') as cFree3,
                            isnull(b.cFree4,'') as cFree4,
                            isnull(b.cFree5,'') as cFree5,
                            isnull(b.cFree6,'') as cFree6,
                            isnull(b.cFree7,'') as cFree7,
                            isnull(b.cFree8,'') as cFree8,
                            isnull(b.cFree9,'') as cFree9,
                            isnull(b.cFree10,'') as cFree10
                            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(','));
                        }
                        if (ds != null)
                            ds.Merge(DBHelper.SQlReturnDataSet(sql, cmd));
                        else
                            ds = DBHelper.SQlReturnDataSet(sql, cmd);
                        #endregion
                    }
                    #endregion

                    cmd.Transaction.Commit();
                }
                catch (Exception ex)
                {
                    if (cmd.Transaction != null)
                    cmd.Transaction.Rollback();
                    log.Error(ex.Message);
                    throw new Exception(ex.Message);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                    }
                    conn.Dispose();
                }
            }

            msg = JSON.DataSetToJson(ds, "details", "IDs");
            return msg;
        }


        /// <summary>
        /// 
        /// 记录日志
        /// </summary>
        /// <param name="Bills"></param>
        private void LogInfo(List<ICSManufactureReceiveDocASK> Bills)
        {
            string HeadList = string.Empty;
            string BodyList = string.Empty;
            foreach (ICSManufactureReceiveDocASK head in Bills)
            {
                HeadList += "\r\n 表头主键ID:" + head.ID + ",仓库:" + head.WHCode + ",用户:" + head.User + ",站点:" + head.WorkPoint;
                foreach (ICSManufactureReceiveDocs body in head.details)
                {
                    BodyList += "\r\n 表体主键ID: " + body.MODetailID + ",数量:" + body.Quantity;
                }
            }
            log.Info(HeadList);
            log.Info(BodyList);
        }
    }
}



//select DISTINCT a.ID as IDs,b.AutoID as DetailID,CAST(f.MoDId as char) as IDSS,a.cCode as MRCVCode,irowno as Sequence,b.cInvCode as InvCode 
//                          ,iQuantity as Quantity,e.AllocateId as SourceDetailID,iNum as Amount,
//                           isnull(b.cItemCode,'') ProjectCode,isnull(b.cbatch,'') cBatch,'' version ,'' brand,
//                           isnull(b.cFree1,'') as cFree1,
//                           isnull(b.cFree2,'') as cFree2,
//                           isnull(b.cFree3,'') as cFree3,
//                           isnull(b.cFree4,'') as cFree4,
//                           isnull(b.cFree5,'') as cFree5,
//                           isnull(b.cFree6,'') as cFree6,
//                           isnull(b.cFree7,'') as cFree7,
//                           isnull(b.cFree8,'') as cFree8,
//                           isnull(b.cFree9,'') as cFree9,
//                           isnull(b.cFree10,'') as cFree10

//                           from rdrecord11 a
//                           left join rdrecords11 b on a.ID=b.ID
//                           left join Department c on a.cDepCode=c.cDepCode
//                           left join Warehouse d on a.cWhCode=d.cWhCode
//                           left join mom_moallocate e on b.iMPoIds=e.AllocateId
//                           INNER JOIN dbo.mom_orderdetail f ON e.MoDId=f.MoDId
//                         INNER JOIN dbo.mom_order g ON f.MoId=g.MoId WHERE a.ID in ({1})