using Kingdee.BOS;
using Kingdee.BOS.App.Data;
using Kingdee.BOS.Contracts;
using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Core.DynamicForm.Operation;
using Kingdee.BOS.Core.List;
using Kingdee.BOS.Core.Metadata;
using Kingdee.BOS.Core.Metadata.ConvertElement;
using Kingdee.BOS.Core.Metadata.ConvertElement.ServiceArgs;
using Kingdee.BOS.Log;
using Kingdee.BOS.Orm;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.ServiceHelper;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;

namespace LQKJ.K3.MFG.PRD.App.ServicePlugIn
{
    [Description("缺料分析")]
    public class AnalysisResults
    {
        DataTable dt = new DataTable();//存放采购订单数据
        int qldatarows = 0;//缺料条数
        Dictionary<string, string> list = new Dictionary<string, string>();//记录异常数据
        /// <summary>
        /// 加载生产订单到缺料分析中
        /// </summary>
        /// <param name="analyeBills"></param>
        public void DrawFormMO(List<DynamicObject> analyeBills, Context Context)
        {
            string sqlMO = $@"/*dialect*/select FENTRYID from T_PRD_MO t1 left join T_PRD_MOENTRY_A t2 on t1.FID=t2.FID 
                                         where FDOCUMENTSTATUS='C' and FCANCELSTATUS='A' and FSTATUS!=6 and FSTATUS!=5 and  FSTATUS!=7";
            List<ListSelectedRow> listSelectedRows = new List<ListSelectedRow>();
            using (IDataReader reader = DBUtils.ExecuteReader(Context, sqlMO))
            {
                while (reader.Read())
                {
                    listSelectedRows.Add(new ListSelectedRow("", reader["FENTRYID"].ToString(), 0, "PRD_MO") { EntryEntityKey = "FTreeEntity" });
                }
            }
            if (listSelectedRows.Count > 0)
            {
                List<ConvertRuleElement> convertRules = ConvertServiceHelper.GetConvertRules(Context, "PRD_MO", "PRD_LackAnalyeBill");
                var rule = convertRules.FirstOrDefault((ConvertRuleElement t) => t.Id.Equals("PRD_MO2LACK", StringComparison.OrdinalIgnoreCase));
                foreach (var item in analyeBills)
                {
                    var entity = item["Entity"] as DynamicObjectCollection;
                    entity.Clear();
                    DrawArgs drawArgs = new DrawArgs(rule, item, listSelectedRows.ToArray())
                    {
                        CustomParams = new Dictionary<string, object>()
                    };

                    var option = OperateOption.Create();
                    option.SetVariableValue("SelectByBillId", false);
                    ConvertOperationResult convertOperationResult = ConvertServiceHelper.Draw(Context, drawArgs, option);
                    item["Date"] = DateTime.Now;
                }
            }
        }
        /// <summary>
        /// 加载委外订单到缺料分析中
        /// </summary>
        /// <param name="analyeBills"></param>
        /// <param name="Context"></param>
        public void DrawFormSUB(List<DynamicObject> analyeBills, Context Context)
        {
            string sqlMO = $@"/*dialect*/select FENTRYID from T_SUB_REQORDER t1 left join T_SUB_REQORDERENTRY t2 on t1.fid=t2.fid 
                                    where FDOCUMENTSTATUS='C' and FCANCELSTATUS='A' and  FSTATUS!=6 and FSTATUS!=5 and  FSTATUS!=7";
            List<ListSelectedRow> listSelectedRows = new List<ListSelectedRow>();
            using (IDataReader reader = DBUtils.ExecuteReader(Context, sqlMO))
            {
                while (reader.Read())
                {
                    listSelectedRows.Add(new ListSelectedRow("", reader["FENTRYID"].ToString(), 0, "SUB_SUBREQORDER") { EntryEntityKey = "FTreeEntity" });
                }
            }
            if (listSelectedRows.Count > 0)
            {
                List<ConvertRuleElement> convertRules = ConvertServiceHelper.GetConvertRules(Context, "SUB_SUBREQORDER", "PRD_LackAnalyeBill");
                var rule = convertRules.FirstOrDefault((ConvertRuleElement t) => t.Id.Equals("SUB_ReqOrder2Lack", StringComparison.OrdinalIgnoreCase));
                foreach (var item in analyeBills)
                {
                    var entity = item["Entity"] as DynamicObjectCollection;
                    //entity.Clear();
                    DrawArgs drawArgs = new DrawArgs(rule, item, listSelectedRows.ToArray())
                    {
                        CustomParams = new Dictionary<string, object>()
                    };

                    var option = OperateOption.Create();
                    option.SetVariableValue("SelectByBillId", false);
                    ConvertOperationResult convertOperationResult = ConvertServiceHelper.Draw(Context, drawArgs, option);
                    item["Date"] = DateTime.Now;
                }
            }
        }
        /// <summary>
        /// 分析
        /// </summary>
        /// <param name="ctx"></param>
        /// <param name="view"></param>
        /// <param name="Push"></param>
        /// Automatic自动
        /// Manual手动
        public void LackAnalyse(Context ctx, string Push, IDynamicFormView view = null)
        {
            //Logger.Info记录日志
            Logger.Info("缺料分析", "开始" + ctx.DBId+","+ Push);
            //获取缺料分析  勾选是否模板
            string sql = "select FID,FBILLNO from T_PRD_LACKANALYSEBILL where F_LQKJ_ISTEMPLATE = '1'";
            DataTable qldata = DBServiceHelper.ExecuteDataSet(ctx, sql).Tables[0];
            List<object> ids = new List<object>();
            for (int i = 0; i < qldata.Rows.Count; i++)
            {
                ids.Add(qldata.Rows[i]["FID"].ToString());
            }
            IMetaDataService metaDataService = ServiceFactory.GetMetaDataService(ctx);
            var lackAnalyeBill = metaDataService.Load(ctx, "PRD_LackAnalyeBill") as FormMetadata;
            IViewService viewService = ServiceFactory.GetService<IViewService>(ctx);
            var objects = viewService.Load(ctx, ids.ToArray(), lackAnalyeBill.BusinessInfo.GetDynamicObjectType());

            //对缺料分析进行克隆并保存
            List<DynamicObject> analyeBills = new List<DynamicObject>();
            foreach (DynamicObject curObj in objects)
            {
                var analyeObj = curObj.Clone() as DynamicObject;
                analyeObj["F_LQKJ_IsTemplate"] = false;

                analyeObj["BillNo"] = "";
                analyeBills.Add(analyeObj);
            }
            if (analyeBills.Count <= 0) { return; }
            DrawFormMO(analyeBills, ctx);
            DrawFormSUB(analyeBills, ctx);
            ISaveService saveService = ServiceFactory.GetSaveService(ctx);
            var result = saveService.Save(ctx, lackAnalyeBill.BusinessInfo, analyeBills.ToArray());
            if (result.SuccessDataEnity == null) return;

            //调用分析方法
            OperateOption operateOption = OperateOption.Create();
            operateOption.SetVariableValue("taskId", "");
            PrepareMtrlService prepareMtrlService = new PrepareMtrlService();
            qldatarows = 0;//当前分析的单
            var jdt = qldata.Rows.Count;
            string sqlmax = "select ISNULL(max(F_LQKJ_PUSHNUMBER), 0) as maxnumber from t_LackAnalysisResult";
            string max = "0";
            var curRows = DBUtils.ExecuteDataSet(ctx, sqlmax).Tables[0].Rows;
            if (curRows.Count > 0)
            {
                max = curRows[0]["maxnumber"].ToString();
            }
            var max2 = "-1";
            foreach (var dataEntity in result.SuccessDataEnity)
            {

                prepareMtrlService.AsyncLackAnalyse(ctx, dataEntity, new OperationResult(), operateOption);
                //把分析结果对比采购订单
                var id = dataEntity["Id"].ToString();//新克隆的分析单
                var FBILLNO = dataEntity["BillNo"].ToString();

                //根据分析单的数据查找出相关的采购订单
                string sql1 = $@"/*dialect*/ select t1.FBILLNO,t2.FMATERIALID,t4.FNUMBER,(case when FSTOCKJOINBASEQTY> FSTOCKBASEQTY then 0 else FSTOCKBASEQTY -FSTOCKJOINBASEQTY end) * FCONVERTDENOMINATOR / FCONVERTNUMERATOR as FREMAINSTOCKINQTY,
                                            t5.FNUMBER FSUPPLIERID,t10.FNAME cgdw,FQTY,t7.FNAME kcdw,FSTOCKQTY,t1.FDATE FDELIVERYDATE,FSEQ from t_PUR_POOrder t1 
                                            left join t_PUR_POOrderEntry t2 on t1.FID=t2.FID
                                            LEFT JOIN T_PUR_POORDERENTRY_D T2D ON T2.FENTRYID=T2D.FENTRYID
                                            left join T_PUR_POORDERENTRY_R t3 on t2.FENTRYID=t3.FENTRYID
                                            left join T_BD_MATERIAL t4 on t4.FMATERIALID=t2.FMATERIALID
                                            left join t_BD_Supplier t5 on t5.FSUPPLIERID=t1.FSUPPLIERID
                                            left join T_BD_UNIT_L t6 on t6.FUNITID=t2.FUNITID
                                            left join T_BD_UNIT_L t7 on t7.FUNITID=t2.FSTOCKUNITID
                                            left join t_BD_MaterialStock t9 on t9.FMATERIALID=t4.FMATERIALID
                                            Inner join T_BD_UNITCONVERTRATE t8 on T9.FSTOREUNITID = t8.FUNITID
                                            left join T_BD_UNIT_L t10 on t10.FUNITID=t8.FUNITID
                                            where t2.FMATERIALID in(select FMATERIALIDSUB  from T_PRD_PMPPBOMENTRY  where FID={id})
                                            and t1.FDOCUMENTSTATUS='C' and FCLOSESTATUS='A'  and FCANCELSTATUS='A' and t2.FMRPCLOSESTATUS='A'
                                            ORDER BY FDELIVERYDATE ASC";

                //根据分析单查找出缺料物料、数量
                string sql2 = $@"/*dialect*/ select t1.FROWID zFROWID,t2.FROWID fFROWID,t1.FMATERIALIDSUB z,t4.FNUMBER znumber,
                                                     		t6.FINCREASEQTY zmin,t1.FLACKQTY zLACKQTY,t1.FLACKQTY zsumLACKQTY,t2.FMATERIALIDSUB f,t5.FNUMBER fnumber,
                                                     	    t7.FINCREASEQTY fmin,t2.FLACKQTY,t3_z.*,t3_f.*,t1.FNEEDDATE fFNEEDDATE,
                                                     	    t1.FMOBILLNO fFSALEORDERNO,t1.FMOENTRYSEQ,t10.FNUMBER fxqwl,t11.FMATERIALID lackmaterial,t11.FLACKQTY sumlackqty
                                                        from T_PRD_PMPPBOMENTRY t1
                                                     left join T_PRD_PMPPBOMENTRY t2 on t1.FID = T2.FID and  t1.FPARENTROWID=t2.FROWID
                                                     left join (
                                                        select FORDERBOMID zFORDERBOMID,T2.FMATERIALID,T2.FMATERIALTYPE z物料类型,T3.FREPLACEPOLICY z替代策略,
                                                        FMOBILLNO zFMOBILLNO,FMOENTRYSEQ  zFMOENTRYSEQbom from T_PRD_LACKMOENTRY t1 left join T_ENG_BOMCHILD t2 on t1.FORDERBOMID=t2.FID
                                                        left join T_ENG_BOMCHILD_A  T3 ON T3.FENTRYID=T2.FENTRYID where T1.FID={id}
                                                        )  t3_z on t3_z.zFMOBILLNO=t1.FMOBILLNO and t3_z.zFMOENTRYSEQbom=t1.FMOENTRYSEQ and t3_z.FMATERIALID=t1.FMATERIALIDSUB--子项
                                                     left join(
                                                        select FORDERBOMID fFORDERBOMID,T2.FMATERIALID,T2.FMATERIALTYPE f物料类型,T3.FREPLACEPOLICY f替代策略,
                                                        FMOBILLNO fFMOBILLNO,FMOENTRYSEQ  fFMOENTRYSEQbom from T_PRD_LACKMOENTRY t1 left join T_ENG_BOMCHILD t2 on t1.FORDERBOMID=t2.FID
                                                        left join T_ENG_BOMCHILD_A  T3 ON T3.FENTRYID=T2.FENTRYID where T1.FID={id}
                                                        )  t3_f on t3_f.fFMOBILLNO=t1.FMOBILLNO and t3_f.fFMOENTRYSEQbom=t1.FMOENTRYSEQ and t3_f.FMATERIALID=t1.FMATERIALIDSUB--父项
                                                        left join (select FISSUETYPE,t2.FENTRYID from T_PRD_LACKMOENTRY t1 left join T_PRD_PMPPBOMENTRY t2 on t1.FMOBILLNO=t2.FMOBILLNO
                                                        and t1.FMOENTRYSEQ=t2.FMOENTRYSEQ   and t1.FID=t2.FID 
                                                        left join T_PRD_PPBOMENTRY t3 on t3.fid=t2.FPPBOMID and t3.FENTRYID=t2.FPPBOMENTRYID
                                                        where t2.FID={id} and FSELORDERTYPE='A') t1type on t1type.FENTRYID=t1.FENTRYID
                                                        left join T_BD_MATERIAL t4 on t4.FMATERIALID=t1.FMATERIALIDSUB--子项
                                                        left join T_BD_MATERIAL t5 on t5.FMATERIALID=t2.FMATERIALIDSUB--父项
                                                        left join t_BD_MaterialPlan t6 on t6.FMATERIALID=t1.FMATERIALIDSUB--子项（最小包装）
                                                        left join t_BD_MaterialPlan t7 on t7.FMATERIALID=t2.FMATERIALIDSUB--父项（最小包装）
                                                        left join t_BD_MaterialBase t8 on t8.FMATERIALID=t1.FMATERIALIDSUB--子项（物料属性）
                                                        left join t_BD_MaterialBase t9 on t9.FMATERIALID=t2.FMATERIALIDSUB--父项（物料属性）
                                                        left join T_BD_MATERIAL t10 on t10.FMATERIALID=t1.FMATERIALID--产品物料（需求）
                                                        left join T_PRD_LACKENTRY t11 on t11.FMATERIALID=t1.FMATERIALIDSUB and t11.FID=t1.FID
                                                        where T1.FID={id}  and (t2.FLACKQTY>1 or  (t2.FLACKQTY is null and t1.FLACKQTY>1)) and (t1type .FISSUETYPE!=7 or(t1type .FISSUETYPE is null ) )
                                                     and t8.FERPCLSID!=5 and (t9.FERPCLSID!=5 or t9.FERPCLSID is null) ";

                Logger.Info("sql2:", ctx.DBId + "," + sql2.ToString());
                Logger.Info("sql1:", ctx.DBId + "," + sql1.ToString());
                dt = DBServiceHelper.ExecuteDataSet(ctx, sql1).Tables[0];
                DataTable dt2 = DBServiceHelper.ExecuteDataSet(ctx, sql2).Tables[0];
                //查询本次推送的记录

                //采购订单  
                string cgjlbsql = $@"/*dialect*/select F_LQKJ_PURCHASE,F_LQKJ_FMATERIAL,SUM(F_LQKJ_PURCHASEQTY) as num from t_LackAnalysisResult
                                                where F_LQKJ_PUSHNUMBER='{max2}'
                                                group by F_LQKJ_PURCHASE ,F_LQKJ_FMATERIAL order by F_LQKJ_PURCHASE ";
                Logger.Info("cgjlbsql:", ctx.DBId + "," + cgjlbsql);
                //缺料分析
                string qlsql = $@"/*dialect*/ select F_LQKJ_LACK,F_LQKJ_FMATERIAL,sum(F_LQKJ_PURCHASEQTY) as num from t_LackAnalysisResult 
                                                where F_LQKJ_PUSHNUMBER='{max2}'
                                                group by F_LQKJ_LACK,F_LQKJ_FMATERIAL order by F_LQKJ_LACK";
                Logger.Info("qlsql:", ctx.DBId + "," + qlsql);
                DataTable cgtab = DBServiceHelper.ExecuteDataSet(ctx, cgjlbsql).Tables[0];
                DataTable qltab = DBServiceHelper.ExecuteDataSet(ctx, qlsql).Tables[0];

                //排除推送数量
                for (int i = 0; i < cgtab.Rows.Count; i++)
                {
                    var currow = cgtab.Rows[i];
                    for (int j = 0; j < dt.Rows.Count; j++)
                    {
                        var ddcurRow = dt.Rows[j];
                        //数量大于0，采购订单编号相同，物料相同
                        if (Convert.ToInt64(ddcurRow["FREMAINSTOCKINQTY"]) > 0 && ddcurRow["FBILLNO"].ToString() == currow["F_LQKJ_PURCHASE"].ToString() && ddcurRow["FMATERIALID"].ToString() == currow["F_LQKJ_FMATERIAL"].ToString())
                        {
                            //采购订单中的数量减去已经推送过的数量
                            ddcurRow["FREMAINSTOCKINQTY"] = Convert.ToInt64(ddcurRow["FREMAINSTOCKINQTY"]) - Convert.ToInt64(currow["num"]);
                            if (Convert.ToInt64(ddcurRow["FREMAINSTOCKINQTY"]) <= 0)
                            {
                                ddcurRow["FREMAINSTOCKINQTY"] = 0;
                            }
                        }
                    }
                }

                Dictionary<string, List<DataRow>> childsDic = new Dictionary<string, List<DataRow>>();
                List<DataRow> parents = new List<DataRow>();
                for (int i = 0; i < dt2.Rows.Count; i++)
                {
                    var curRow = dt2.Rows[i];
                    if (curRow["fFROWID"] == DBNull.Value)
                    {
                        parents.Add(curRow);
                    }
                    else
                    {
                        var parentId = curRow["fFROWID"] as string;
                        List<DataRow> rows;
                        if (!childsDic.TryGetValue(parentId, out rows))
                        {
                            rows = new List<DataRow>();
                            childsDic.Add(parentId, rows);
                        }
                        rows.Add(curRow);
                    }

                }

                Logger.Info("childsDic:", childsDic.Count.ToString());
                Logger.Info("parents:", parents.Count.ToString());
                //需要发送的数据
                List<DataRow> toSendlist = new List<DataRow>();
                if (dt.Rows.Count > 0) //采购订单中有相关数据
                {
                    for (int i = 0; i < parents.Count; i++)
                    {
                        var curRow = parents[i];
                        long nowwl = Convert.ToInt64(curRow["z"]);//当前物料
                                                                  //如果当前物料的缺料数量为0,则不用执行后面的操作(看主料，不看替代料)
                        Logger.Info("nowwl_1:", nowwl.ToString());
                        Logger.Info("curRow[\"FLACKQTY\"]:", curRow["zLACKQTY"].ToString());
                        if (Convert.ToDecimal(curRow["zLACKQTY"]) <= 0) continue;
                        Logger.Info("nowwl_2:", nowwl.ToString());

                        var parentId = curRow["zFROWID"] as string;
                        List<DataRow> childs = new List<DataRow>();
                        if (childsDic.ContainsKey(parentId))
                        {
                            childs = childsDic[parentId];
                        }
                        //调用匹配方式
                        switch (curRow["z替代策略"].ToString())
                        {
                            case "1"://混合替代  1
                                var ruslut = HhReplace(curRow, childs);
                                Logger.Info("HhReplace.Count:", ruslut.Count.ToString());
                                foreach (var item in ruslut)
                                {
                                    toSendlist.Add(item);
                                }

                                break;
                            case "2"://整批替代  2
                                var ruslut2 = ZpReplace(curRow, childs);
                                Logger.Info("ZpReplace.Count:", ruslut2.Count.ToString());
                                foreach (var item in ruslut2)
                                {
                                    toSendlist.Add(item);
                                }
                                break;
                            case "3": //手工      3
                                var ruslut3 = SgReplace(curRow);

                                Logger.Info("SgReplace.Count:", ruslut3.Count.ToString());
                                foreach (var item in ruslut3)
                                {
                                    toSendlist.Add(item);
                                }
                                break;
                            case "4"://混合+整批 4
                                childs.Add(curRow);
                                var num = Convert.ToInt32(curRow["zLACKQTY"]);//取到物料的缺料数量
                                var materialId = GetFullUsedMaterialId(childs, num, new Dictionary<long, int>());
                                if (materialId > 0)
                                {
                                    var hh = ZpReplace(curRow, childs);//整批替代
                                    toSendlist.AddRange(hh);
                                }
                                else
                                {
                                    var hh = HhReplace(curRow, childs);
                                    toSendlist.AddRange(hh);
                                }

                                break;
                            case " "://无替代策略
                                var ruslut4 = SgReplace(curRow);

                                Logger.Info("SgReplace.Count:", ruslut4.Count.ToString());
                                foreach (var item in ruslut4)
                                {
                                    toSendlist.Add(item);
                                }
                                break;
                        }
                    }
                    //判断缺料数据中是否还有剩余的数量
                    DataTable table = new DataTable();
                    table.Columns.Add("FBILLNO");
                    table.Columns.Add("FMATERIALID");
                    table.Columns.Add("FNUMBER");
                    table.Columns.Add("FREMAINSTOCKINQTY");
                    table.Columns.Add("FSUPPLIERID");
                    table.Columns.Add("cgdw");
                    table.Columns.Add("FQTY");
                    table.Columns.Add("kcdw");
                    table.Columns.Add("FSTOCKQTY");
                    table.Columns.Add("FSEQ");//行号
                    table.Columns.Add("FNEEDDATE");//需求日期
                    table.Columns.Add("YDTYPE");//源单类型
                    table.Columns.Add("FSALEORDERNO");//源单单号
                    table.Columns.Add("FMOENTRYSEQ");//源单单号
                    table.Columns.Add("ydwl");//源单物料
                    table.Columns.Add("minnum");//最小包装数
                    table.Columns.Add("TDType");//物料类型
                    table.Columns.Add("LackMaterial");//缺料物料
                    table.Columns.Add("LackSum");//缺料总数
                    table.Columns.Add("DetailedNum");//缺料明细
                    for (int i = 0; i < dt2.Rows.Count; i++)
                    {
                        Logger.Info("znumber1:", dt2.Rows[i]["znumber"].ToString() + "/" + dt2.Rows[i]["zLACKQTY"].ToString());
                        if (dt2.Rows[i]["fFROWID"] != DBNull.Value) continue;
                        Logger.Info("znumber2:", dt2.Rows[i]["znumber"].ToString());
                        if (Convert.ToInt64(dt2.Rows[i]["zLACKQTY"]) > 0)
                        {
                            Logger.Info("znumber3:", dt2.Rows[i]["znumber"].ToString());
                            table.Rows.Add(" ", dt2.Rows[i]["z"].ToString(), dt2.Rows[i]["znumber"].ToString(), dt2.Rows[i]["zLACKQTY"].ToString(), " ", " ", " ", " ", " ", " ", dt2.Rows[i]["fFNEEDDATE"], " ", dt2.Rows[i]["fFSALEORDERNO"], dt2.Rows[i]["FMOENTRYSEQ"], dt2.Rows[i]["fxqwl"], dt2.Rows[i]["zmin"], "1", dt2.Rows[i]["lackmaterial"].ToString(), Convert.ToInt64(dt2.Rows[i]["sumlackqty"]), Convert.ToInt64(dt2.Rows[i]["zsumLACKQTY"]));
                        }
                    }


                    Logger.Info("table.Rows.Count:", table.Rows.Count.ToString());
                    if (table.Rows.Count > 0)
                    {
                        for (int i = 0; i < table.Rows.Count; i++)
                        {
                            var curRow = table.Rows[i];
                            toSendlist.Add(curRow);
                        }
                    }
                }
                //采购订单中无相关数据
                else if (dt.Rows.Count == 0)
                {
                    toSendlist.AddRange(NotData(dt2));
                }
                ///把匹配结果记录到推送记录表中

                Logger.Info("toSendlist.Count", ctx.DBId + "," + toSendlist.Count.ToString());
                if (toSendlist.Count > 0)
                {
                    //记录推送
                    //创建临时表存放推送数据
                    string tab = DBServiceHelper.CreateTemporaryTableName(ctx);
                    DBUtils.Execute(ctx, $"if exists(select 1 from sys.sysobjects where name='{tab}') drop table {tab}");
                    //判断是否存在此表，如果存在则删除
                    string sqltab = $@"/*dialect*/ IF Object_id('{tab}') IS NOT NULL DROP TABLE LStable";
                    //创建表
                    string crearesql = $@"/*dialect*/ create table {tab}
                             (PURCHASE nvarchar(1000),PURCHASENum nvarchar(1000),wl nvarchar(1000),gys nvarchar(1000),
                             fxd nvarchar(1000),dw nvarchar(1000),cgseq nvarchar(1000),xqdate nvarchar(1000),yddh nvarchar(1000),
                             ydwl nvarchar(1000),mbfxd nvarchar(1000),Column1 int,wltype nvarchar(1000),
                             Lack nvarchar(1000),LackSum nvarchar(1000),LackNum nvarchar(1000))";
                    DBServiceHelper.Execute(ctx, crearesql);
                    //数据存入临时表
                    List<SqlObject> insertsqlList = new List<SqlObject>();
                    var columnl = 0;
                    foreach (var item in toSendlist)//新增语句
                    {
                        if (item["FBILLNO"].ToString() == " ")
                        {
                            var cgnum = 0.00;
                            var num = Convert.ToDouble(item["FREMAINSTOCKINQTY"]);
                            var minnum = Convert.ToDouble(item["minnum"]);
                            if (minnum == 0) { minnum = 1; }
                            if (num % minnum == 0)
                            {
                                cgnum = num;
                            }
                            else
                            {
                                cgnum = num + (minnum - num % minnum);
                            }
                            item["FREMAINSTOCKINQTY"] = cgnum;
                        }
                        Logger.Info(ctx.DBId + "," + "toSendlistMATERUALID:", item["FMATERIALID"].ToString() + "/" + item["FBILLNO"].ToString() + "/" + item["FREMAINSTOCKINQTY"].ToString()+"/"+ item["FQTY"].ToString());
                        columnl++;
                        var yddh = item["FSALEORDERNO"] + "_" + item["FMOENTRYSEQ"];
                        string insertsql1 = $@"/*dialect*/insert into {tab} values('{item["FBILLNO"]}','{item["FREMAINSTOCKINQTY"]}',
                                '{item["FMATERIALID"]}','{item["FSUPPLIERID"]}','{FBILLNO}','{item["cgdw"]}','{item["FSEQ"]}','{item["FNEEDDATE"]}','{yddh}',
                                '{item["ydwl"]}','{qldata.Rows[qldatarows]["FBILLNO"].ToString()}','{columnl}','{item["TDType"]}','{item["LackMaterial"]}','{item["LackSum"]}','{item["DetailedNum"]}')";
                        insertsqlList.Add(new SqlObject(insertsql1, new List<SqlParam>()));
                    }
                    var count = qldata.Rows.Count;
                    var nowcount = 0;
                    if (count == qldatarows + 1)
                    {
                        nowcount = 1;
                    }
                    //批量执行sql
                    var success = DBUtils.ExecuteBatch(ctx, insertsqlList);
                    if (success > 0)
                    {
                        //启用事务
                        using (SessionScope scope = new SessionScope())
                        {
                            using (KDTransactionScope ts = new KDTransactionScope(TransactionScopeOption.Required))
                            {
                                //生成FID
                                string sqlfid = $@"/*dialect*/insert into Z_LackAnalysisResult (Column1) select Column1 from {tab}";
                                DBUtils.Execute(ctx, sqlfid);
                                //生成推送编码
                                var billno = "TS" + DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + (Convert.ToInt16(max) + 1).ToString();

                                //采购订单、采购数量、缺料分析单、缺料数量
                                if (max == null || max == " " || max == "") { max = "0"; }
                                string insertsql = $@"/*dialect*/insert into t_LackAnalysisResult(FID,FFormId,F_LQKJ_PURCHASE,F_LQKJ_PURCHASEQTY,
                                        F_LQKJ_FMATERIAL,F_LQKJ_NOWLACK,F_LQKJ_FSTOCKUNITID,F_LQKJ_COMBO,F_LQKJ_PURCHASEFSQ,F_LQKJ_FNEEDDATE,F_LQKJ_XQBILLNO,
                                        F_LQKJ_XQMATERIAL,F_LQKJ_PUSHNUMBER,F_LQKJ_SUPPLIER,F_LQKJ_LACK,FCREATEDATE1,F_LQKJ_CHECKEND,F_LQKJ_PUSHCOUNT,
                                        F_LQKJ_PUSHBILNO,F_LQKJ_FMATERIALTYPE,F_LQKJ_LACKMATERIAL1,F_LQKJ_FLACKSUM,F_LQKJ_INTEGER) 
                                        select t2.Id,'LQKJ_ContrastRecord',t1.PURCHASE,t1.PURCHASENum,wl,
                                        fxd,dw,case PURCHASE when null then '1' when ' ' then '1' else '0' end states,cgseq,xqdate,yddh,ydwl,
                                        {Convert.ToInt16(max) + 1},gys,mbfxd,CONVERT(varchar(100), GETDATE(),120),{nowcount},{toSendlist.Count},'{billno}',wltype,
                                        Lack,LackSum,LackNum
                                        from {tab} T1 left join Z_LackAnalysisResult T2 on t1.Column1=t2.Column1  ";
                                Logger.Info(ctx.DBId + "," + "insertsql", insertsql);
                                var successsum = DBUtils.Execute(ctx, insertsql);

                                if (successsum > 0)
                                {
                                    //记录到同步记录表中后  推送
                                    string text = ctx.UserId.ToString();
                                    string sqltb = $@"/*dialect*/insert into LQKJ_t_IMSSync(FID,F_LQKJ_SYNCDATAID,F_LQKJ_SYNCBILL,
                                            F_LQKJ_SYNDDATETIME,FCREATORID,FMODIFIERID,FCREATEDATE,FMODIFYDATE,
                                            F_LQKJ_SYNCCHECK,F_LQKJ_OPERATIONNAME,F_LQKJ_operationinnercode) select  NEWID(),Id,'LQKJ_ContrastRecord',
                                            null,{text},'0',GETDATE(),GETDATE(),'0','保存','Save' from Z_LackAnalysisResult";
                                    var ccc = DBUtils.Execute(ctx, sqltb);
                                }
                                DBUtils.Execute(ctx, "delete from Z_LackAnalysisResult");//清空自动生成FID表
                                ts.Complete();
                            }
                        }


                        DBUtils.Execute(ctx, "drop table " + tab);
                    }

                }
                //如果推送方式为手动推送
                if (Push == "Manual")
                {
                    //Logger.Info();
                    view.Session["ProcessTips"] = string.Format("正在处理第{0}条缺料分析单数据，共{1}条数据", qldatarows + 1, jdt);
                    var rate = Convert.ToInt32((qldatarows + 1) * 100 / jdt);
                    view.Session["ProcessRateValue"] = rate;
                    if (max2 == max || max2 == null || max2 == "" || max2 == " ") { max2 = (Convert.ToInt16(max) + 1).ToString(); }

                    qldatarows++;
                }


                Logger.Info("缺料分析", "结束同步" + ctx.DBId + "," + Push);
            }
        }
        /// <summary>
        /// 混合替代
        /// 混合替代
        /// </summary>
        /// <param name="dr"></param>
        public List<DataRow> HhReplace(DataRow parentRow, List<DataRow> childs)
        {
            List<DataRow> toSendlist = new List<DataRow>();
            DataTable table = new DataTable();
            table.Columns.Add("FBILLNO");
            table.Columns.Add("FMATERIALID");
            table.Columns.Add("FNUMBER");
            table.Columns.Add("FREMAINSTOCKINQTY");
            table.Columns.Add("FSUPPLIERID");
            table.Columns.Add("cgdw");
            table.Columns.Add("FQTY");
            table.Columns.Add("kcdw");
            table.Columns.Add("FSTOCKQTY");
            table.Columns.Add("FSEQ");//行号
            table.Columns.Add("FNEEDDATE");//需求日期
            table.Columns.Add("YDTYPE");//源单类型
            table.Columns.Add("FSALEORDERNO");//源单单号
            table.Columns.Add("FMOENTRYSEQ");//源单单号
            table.Columns.Add("ydwl");//源单物料
            table.Columns.Add("minnum");//最新包装数
            table.Columns.Add("TDType");//物料类型
            table.Columns.Add("LackMaterial");//缺料物料
            table.Columns.Add("LackSum");//缺料总数
            table.Columns.Add("DetailedNum");//缺料明细
            var materialId = Convert.ToInt64(parentRow["z"]);
            var curQTY = Convert.ToInt64(parentRow["zLACKQTY"]); //数量
            childs.Add(parentRow);

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                foreach (var dr in childs)
                {
                    var curRow = dt.Rows[i];
                    if (Convert.ToInt64(dr["z"]) == Convert.ToInt64(curRow["FMATERIALID"]))//主料替代料都查
                    {
                        if (Convert.ToInt64(curRow["FREMAINSTOCKINQTY"]) > 0)
                        {
                            //剩余数量为0时，则为满足了缺料数量，就不需要再找订单了
                            if (curQTY == 0)
                            {
                                for (int j = 0; j < table.Rows.Count; j++)
                                {
                                    var nowrow = table.Rows[j];
                                    toSendlist.Add(nowrow);
                                }
                                parentRow["zLACKQTY"] = 0;
                                return toSendlist;
                            }

                            var qty = Convert.ToInt64(curRow["FREMAINSTOCKINQTY"]);//获取订单数量
                            if (curQTY >= qty)//缺料数量大于订单数量时，则是缺料数量还不满足
                            {
                                curQTY = curQTY - qty;
                                // Logger.Info("beforelackqty,cgqty:", curRow["FBILLNO"] + "/" + curRow["FMATERIALID"] + "/" + curQTY.ToString() + "/" + qty.ToString());
                                if (Convert.ToInt64(curRow["FMATERIALID"]) == materialId)
                                {
                                    table.Rows.Add(curRow["FBILLNO"], curRow["FMATERIALID"], curRow["FNUMBER"], qty, curRow["FSUPPLIERID"], curRow["cgdw"], curRow["FQTY"], curRow["kcdw"], curRow["FSTOCKQTY"], curRow["FSEQ"], dr["fFNEEDDATE"], " ", dr["fFSALEORDERNO"], dr["FMOENTRYSEQ"], dr["fxqwl"], dr["zmin"], "1", parentRow["lackmaterial"], Convert.ToInt64(parentRow["sumlackqty"]), Convert.ToInt64(parentRow["zsumLACKQTY"]));
                                    Logger.Info("混，匹配数据记录", curRow["FBILLNO"] + "/" + curRow["FMATERIALID"] + "/" + dr["FLACKQTY"].ToString() + "/" + dt.Rows[i]["FREMAINSTOCKINQTY"].ToString());


                                }
                                else
                                {
                                    table.Rows.Add(curRow["FBILLNO"], curRow["FMATERIALID"], curRow["FNUMBER"], qty, curRow["FSUPPLIERID"], curRow["cgdw"], curRow["FQTY"], curRow["kcdw"], curRow["FSTOCKQTY"], curRow["FSEQ"], dr["fFNEEDDATE"], " ", dr["fFSALEORDERNO"], dr["FMOENTRYSEQ"], dr["fxqwl"], dr["zmin"], "3", parentRow["lackmaterial"], Convert.ToInt64(parentRow["sumlackqty"]), Convert.ToInt64(parentRow["zsumLACKQTY"]));
                                    Logger.Info("混，匹配数据记录", curRow["FBILLNO"] + "/" + curRow["FMATERIALID"] + "/" + dr["FLACKQTY"].ToString() + "/" + dt.Rows[i]["FREMAINSTOCKINQTY"].ToString());
                                }
                                parentRow["zLACKQTY"] = curQTY;
                                dt.Rows[i]["FREMAINSTOCKINQTY"] = 0;
                            }
                            else//缺料数量小于订单数量时，则是缺料数量满足了
                            {
                                var mateialType = 1;
                                if (Convert.ToInt64(curRow["FMATERIALID"]) != materialId) { mateialType = 3; }
                                var cgnum = 0.00;
                                var minnum = Convert.ToDouble(dr["zmin"]);
                                if (minnum == 0) { minnum = 1; }
                                if (curQTY % minnum == 0)//无余数，满足最小包装
                                {
                                    table.Rows.Add(curRow["FBILLNO"], curRow["FMATERIALID"], curRow["FNUMBER"], curQTY, curRow["FSUPPLIERID"], curRow["cgdw"], curRow["FQTY"], curRow["kcdw"], curRow["FSTOCKQTY"], curRow["FSEQ"], dr["fFNEEDDATE"], " ", dr["fFSALEORDERNO"], dr["FMOENTRYSEQ"], dr["fxqwl"], dr["zmin"], mateialType, parentRow["lackmaterial"], Convert.ToInt64(parentRow["sumlackqty"]), Convert.ToInt64(parentRow["zsumLACKQTY"]));

                                    dt.Rows[i]["FREMAINSTOCKINQTY"] = qty - curQTY;//将采购订单数量减去缺料使用的数量
                                    Logger.Info("混，匹配数据记录", curRow["FBILLNO"] + "/" + curRow["FMATERIALID"] + "/" + dr["FLACKQTY"].ToString() + "/" + curQTY);

                                }
                                else//有余数
                                {
                                    cgnum = curQTY + (minnum - curQTY % minnum);
                                    if (qty > cgnum)//订单数量比最小包装数值大
                                    {
                                        table.Rows.Add(curRow["FBILLNO"], curRow["FMATERIALID"], curRow["FNUMBER"], cgnum, curRow["FSUPPLIERID"], curRow["cgdw"], curRow["FQTY"], curRow["kcdw"], curRow["FSTOCKQTY"], curRow["FSEQ"], dr["fFNEEDDATE"], " ", dr["fFSALEORDERNO"], dr["FMOENTRYSEQ"], dr["fxqwl"], dr["zmin"], mateialType, parentRow["lackmaterial"], Convert.ToInt64(parentRow["sumlackqty"]), Convert.ToInt64(parentRow["zsumLACKQTY"]));

                                        dt.Rows[i]["FREMAINSTOCKINQTY"] = qty - cgnum;//将采购订单数量减去缺料使用的数量
                                        Logger.Info("混，匹配数据记录", curRow["FBILLNO"] + "/" + curRow["FMATERIALID"] + "/" + dr["FLACKQTY"].ToString() + "/" + cgnum);
                                    }
                                    else//订单数量比最小包装数值小
                                    {
                                        table.Rows.Add(curRow["FBILLNO"], curRow["FMATERIALID"], curRow["FNUMBER"], qty, curRow["FSUPPLIERID"], curRow["cgdw"], curRow["FQTY"], curRow["kcdw"], curRow["FSTOCKQTY"], curRow["FSEQ"], dr["fFNEEDDATE"], " ", dr["fFSALEORDERNO"], dr["FMOENTRYSEQ"], dr["fxqwl"], dr["zmin"], mateialType, parentRow["lackmaterial"], Convert.ToInt64(parentRow["sumlackqty"]), Convert.ToInt64(parentRow["zsumLACKQTY"]));

                                        dt.Rows[i]["FREMAINSTOCKINQTY"] = 0;//将采购订单数量减去缺料使用的数量
                                        Logger.Info("混，匹配数据记录", curRow["FBILLNO"] + "/" + curRow["FMATERIALID"] + "/" + dr["FLACKQTY"].ToString() + "/" + qty);

                                    }
                                }
                                curQTY = 0;
                                parentRow["zLACKQTY"] = curQTY;
                                //Logger.Info("1Afterlackqty,cgqty:", curRow["FBILLNO"] + "/" + curRow["FMATERIALID"] + "/" + dr["FLACKQTY"].ToString() + "/" + dt.Rows[i]["FREMAINSTOCKINQTY"].ToString());

                            }
                        }
                    }
                }
            }
            //执行完了都还没有返回数据，说明缺货数量还未满足
            if (curQTY > 0)
            {
                parentRow["zLACKQTY"] = curQTY;
            }
            for (int j = 0; j < table.Rows.Count; j++)
            {
                var nowrow = table.Rows[j];
                toSendlist.Add(nowrow);

            }
            return toSendlist;
        }

        /// <summary>
        /// 获取完全符合缺料数量的物料
        /// </summary>
        /// <returns></returns>
        public long GetFullUsedMaterialId(List<DataRow> childs, int neededNumber, Dictionary<long, int> materialUsedNumber)
        {
            foreach (var item in childs)
            {
                materialUsedNumber.Add(Convert.ToInt64(item["z"]), neededNumber);
            }
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                var CurRow = dt.Rows[i];
                var curmaterial = Convert.ToInt64(CurRow["FMATERIALID"]);//当前订单物料
                var qty = Convert.ToInt32(CurRow["FREMAINSTOCKINQTY"]);//当前订单数量
                if (qty > 0)//订单数量大于0
                {
                    if (materialUsedNumber.ContainsKey(curmaterial))//当前订单物料=主料或者替代料
                    {
                        var materialQty = materialUsedNumber[curmaterial];
                        //if (materialQty == 0)//如果当前物料为0，就是匹配够了
                        //{
                        //    return curmaterial;
                        //}
                        if (materialQty > qty)//当前订单数量比缺料数量少，还未满足缺料数量
                        {
                            //缺料数量扣除次订单数量
                            materialUsedNumber[curmaterial] = materialQty - qty;
                        }
                        else//当前订单数量比缺料数量多，已满足缺料数量，可返回
                        {
                            return curmaterial;
                        }

                    }
                }
            }
            return 0;
        }
        /// <summary>
        /// 整批替代时，获取使用的物料ID
        /// </summary>
        /// <returns></returns>
        public long GetUsedMaterialId(List<DataRow> childs, int neededNumber, long mainMaterialId)
        {
            Dictionary<long, int> materialUsedNumber = new Dictionary<long, int>();
            var materialId = GetFullUsedMaterialId(childs, neededNumber, materialUsedNumber);
            if (materialId > 0)
            {
                return materialId;
            }

            //订单走完了还未有数据返回（都未匹配够，需要对比哪个物料剩余少，就返回哪个物料）
            long matetialId = mainMaterialId;
            int usedNumber = materialUsedNumber[mainMaterialId];
            foreach (var item in materialUsedNumber)
            {
                if (item.Value < usedNumber)
                {
                    matetialId = item.Key;
                    usedNumber = item.Value;
                }
            }

            return matetialId;

        }

        /// <summary>
        /// 整批替代
        /// </summary>
        /// <param name="dr"></param>
        /// <returns></returns>
        public List<DataRow> ZpReplace(DataRow parentRow, List<DataRow> childs)
        {
            var materialId = Convert.ToInt64(parentRow["z"]);
            var curQTY = Convert.ToInt32(parentRow["zLACKQTY"]); //数量
            childs.Add(parentRow);
            var usedMaterialId = GetUsedMaterialId(childs, curQTY, materialId);
            if (usedMaterialId == 0)
            {
                usedMaterialId = materialId;
            }
            foreach (var dr in childs)
            {
                if (Convert.ToInt64(dr["z"]) == usedMaterialId)
                {
                    return SgReplace(dr, materialId == usedMaterialId ? "1" : "3", curQTY, parentRow);
                }
            }

            return new List<DataRow>();

        }
        /// <summary>
        /// 手工  只考虑主料，替代料不查找
        /// </summary>
        /// <param name="dr"></param>
        /// <returns></returns>
        public List<DataRow> SgReplace(DataRow dr, string replaceType = "1", long curQTY = 0, DataRow parentRow = null)
        {
            List<DataRow> toSendlist = new List<DataRow>();
            DataTable table = new DataTable();
            table.Columns.Add("FBILLNO");
            table.Columns.Add("FMATERIALID");
            table.Columns.Add("FNUMBER");
            table.Columns.Add("FREMAINSTOCKINQTY");
            table.Columns.Add("FSUPPLIERID");
            table.Columns.Add("cgdw");
            table.Columns.Add("FQTY");
            table.Columns.Add("kcdw");
            table.Columns.Add("FSTOCKQTY");
            table.Columns.Add("FSEQ");//行号
            table.Columns.Add("FNEEDDATE");//需求日期
            table.Columns.Add("YDTYPE");//源单类型
            table.Columns.Add("FSALEORDERNO");//源单单号
            table.Columns.Add("FMOENTRYSEQ");//源单单号
            table.Columns.Add("ydwl");//源单物料
            table.Columns.Add("minnum");//最新包装数
            table.Columns.Add("TDType");//物料类型
            table.Columns.Add("LackMaterial");//缺料物料
            table.Columns.Add("LackSum");//缺料总数
            table.Columns.Add("DetailedNum");//缺料明细
            if (curQTY == 0)
            {
                curQTY = Convert.ToInt64(dr["zLACKQTY"]);
            }
            if (parentRow == null)
            {
                parentRow = dr;
            }
            var materialId = Convert.ToInt64(dr["z"]);
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                var curRow = dt.Rows[i];
                if (Convert.ToInt64(curRow["FMATERIALID"]) == materialId)
                {
                    if (Convert.ToInt64(curRow["FREMAINSTOCKINQTY"]) > 0)
                    {
                        if (curQTY == 0)
                        {
                            for (int j = 0; j < table.Rows.Count; j++)
                            {
                                var nowrow = table.Rows[j];
                                toSendlist.Add(nowrow);

                            }
                            return toSendlist;
                        }
                        var qty = Convert.ToInt64(curRow["FREMAINSTOCKINQTY"]);
                        if (curQTY >= qty)
                        {
                            table.Rows.Add(curRow["FBILLNO"], curRow["FMATERIALID"], curRow["FNUMBER"], qty, curRow["FSUPPLIERID"], curRow["cgdw"], curRow["FQTY"], curRow["kcdw"], curRow["FSTOCKQTY"], curRow["FSEQ"], dr["fFNEEDDATE"], " ", dr["fFSALEORDERNO"], dr["FMOENTRYSEQ"], dr["fxqwl"], dr["zmin"], replaceType, parentRow["lackmaterial"], Convert.ToInt64(parentRow["sumlackqty"]), Convert.ToInt64(parentRow["zsumLACKQTY"]));

                            dt.Rows[i]["FREMAINSTOCKINQTY"] = 0;
                            curQTY = curQTY - qty;
                            dr["zLACKQTY"] = curQTY - qty;
                        }
                        else
                        {
                            var cgnum = 0.00;
                            var minnum = Convert.ToDouble(dr["zmin"]);
                            if (minnum == 0) { minnum = 1; }
                            if (curQTY % minnum == 0)//无余数，满足最小包装
                            {
                                table.Rows.Add(curRow["FBILLNO"], curRow["FMATERIALID"], curRow["FNUMBER"], curQTY, curRow["FSUPPLIERID"], curRow["cgdw"], curRow["FQTY"], curRow["kcdw"], curRow["FSTOCKQTY"], curRow["FSEQ"], dr["fFNEEDDATE"], " ", dr["fFSALEORDERNO"], dr["FMOENTRYSEQ"], dr["fxqwl"], dr["zmin"], replaceType, parentRow["lackmaterial"], Convert.ToInt64(parentRow["sumlackqty"]), Convert.ToInt64(parentRow["zsumLACKQTY"]));

                                dt.Rows[i]["FREMAINSTOCKINQTY"] = qty - curQTY;//将采购订单数量减去缺料使用的数量
                                Logger.Info("整，匹配数据记录", curRow["FBILLNO"] + "/" + curRow["FMATERIALID"] + "/" + dr["FLACKQTY"].ToString() + "/" + curQTY);

                            }
                            else
                            {
                                cgnum = curQTY + (minnum - curQTY % minnum);
                                if (qty > cgnum)//订单数量比最小包装数值大
                                {
                                    table.Rows.Add(curRow["FBILLNO"], curRow["FMATERIALID"], curRow["FNUMBER"], cgnum, curRow["FSUPPLIERID"], curRow["cgdw"], curRow["FQTY"], curRow["kcdw"], curRow["FSTOCKQTY"], curRow["FSEQ"], dr["fFNEEDDATE"], " ", dr["fFSALEORDERNO"], dr["FMOENTRYSEQ"], dr["fxqwl"], dr["zmin"], replaceType, parentRow["lackmaterial"], Convert.ToInt64(parentRow["sumlackqty"]), Convert.ToInt64(parentRow["zsumLACKQTY"]));

                                    dt.Rows[i]["FREMAINSTOCKINQTY"] = qty - cgnum;//将采购订单数量减去缺料使用的数量
                                    Logger.Info("整，匹配数据记录", curRow["FBILLNO"] + "/" + curRow["FMATERIALID"] + "/" + dr["FLACKQTY"].ToString() + "/" + cgnum);

                                }
                                else//订单数量比最小包装数值小
                                {
                                    table.Rows.Add(curRow["FBILLNO"], curRow["FMATERIALID"], curRow["FNUMBER"], qty, curRow["FSUPPLIERID"], curRow["cgdw"], curRow["FQTY"], curRow["kcdw"], curRow["FSTOCKQTY"], curRow["FSEQ"], dr["fFNEEDDATE"], " ", dr["fFSALEORDERNO"], dr["FMOENTRYSEQ"], dr["fxqwl"], dr["zmin"], replaceType, parentRow["lackmaterial"], Convert.ToInt64(parentRow["sumlackqty"]), Convert.ToInt64(parentRow["zsumLACKQTY"]));

                                    dt.Rows[i]["FREMAINSTOCKINQTY"] = 0;//将采购订单数量减去缺料使用的数量
                                    Logger.Info("整，匹配数据记录", curRow["FBILLNO"] + "/" + curRow["FMATERIALID"] + "/" + dr["FLACKQTY"].ToString() + "/" + qty);

                                }
                            }
                            curQTY = 0;
                            dr["zLACKQTY"] = curQTY;
                        }
                        Logger.Info("afterelackqty,cgqty:", curRow["FBILLNO"] + "/" + curRow["FMATERIALID"] + "/" + dr["FLACKQTY"].ToString() + "/" + dt.Rows[i]["FREMAINSTOCKINQTY"].ToString());

                    }
                }
                else continue;
            }
            if (curQTY > 0)
            {
                dr["zLACKQTY"] = curQTY;
            }
            for (int j = 0; j < table.Rows.Count; j++)
            {
                var nowrow = table.Rows[j];
                toSendlist.Add(nowrow);
            }
            return toSendlist;
        }
        /// <summary>
        /// 采购订单中无相关数据
        /// </summary>
        /// <param name="dt2"></param>
        /// <returns></returns>
        public List<DataRow> NotData(DataTable dt2)
        {
            List<DataRow> toSendlist = new List<DataRow>();
            DataTable table = new DataTable();
            table.Columns.Add("FBILLNO");
            table.Columns.Add("FMATERIALID");
            table.Columns.Add("FNUMBER");
            table.Columns.Add("FREMAINSTOCKINQTY");
            table.Columns.Add("FSUPPLIERID");
            table.Columns.Add("cgdw");
            table.Columns.Add("FQTY");
            table.Columns.Add("kcdw");
            table.Columns.Add("FSTOCKQTY");
            table.Columns.Add("FSEQ");//行号
            table.Columns.Add("FNEEDDATE");//需求日期
            table.Columns.Add("YDTYPE");//源单类型
            table.Columns.Add("FSALEORDERNO");//源单单号
            table.Columns.Add("FMOENTRYSEQ");//源单行号
            table.Columns.Add("ydwl");//源单物料
            table.Columns.Add("minnum");//最新包装数
            table.Columns.Add("TDType");//物料类型
            table.Columns.Add("LackMaterial");//缺料物料
            table.Columns.Add("LackSum");//缺料总数
            table.Columns.Add("DetailedNum");//缺料明细
            for (int i = 0; i < dt2.Rows.Count; i++)
            {
                //排除替代料
                if (dt2.Rows[i]["z物料类型"].ToString() == "3")
                {
                    continue;
                }
                else
                {
                    if (Convert.ToDecimal(dt2.Rows[i]["zLACKQTY"]) != 0)//数量为0，不记录
                    {
                        table.Rows.Add(" ", dt2.Rows[i]["z"].ToString(), dt2.Rows[i]["znumber"].ToString(), dt2.Rows[i]["zLACKQTY"].ToString(), " ", " ", " ", " ", " ", " ", dt2.Rows[i]["fFNEEDDATE"], " ", dt2.Rows[i]["fFSALEORDERNO"], dt2.Rows[i]["FMOENTRYSEQ"], dt2.Rows[i]["fxqwl"], dt2.Rows[i]["zmin"], "1", dt2.Rows[i]["lackmaterial"].ToString(), Convert.ToInt64(dt2.Rows[i]["sumlackqty"]), dt2.Rows[i]["zsumLACKQTY"].ToString());
                        Logger.Info("未匹配数据记录", dt2.Rows[i]["z"].ToString() + "/" + dt2.Rows[i]["znumber"].ToString() + "/" + dt2.Rows[i]["zLACKQTY"].ToString() );

                    }
                }
            }
            if (table.Rows.Count > 0)
            {
                for (int i = 0; i < table.Rows.Count; i++)
                {
                    var curRow = table.Rows[i];
                    toSendlist.Add(curRow);
                }
            }
            return toSendlist;
        }
    }
}
