using Kingdee.BOS;
using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Core.Metadata;
using Kingdee.BOS.Core.Metadata.ConvertElement;
using Kingdee.BOS.Log;
using Kingdee.BOS.Orm;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.Resource;
using Kingdee.BOS.Util;
using Kingdee.K3.Core.MFG.Common;
using Kingdee.K3.Core.MFG.EntityHelper;
using Kingdee.K3.Core.MFG.PRD.ParamOption;
using Kingdee.K3.Core.MFG.PRD.SchedulingMatch;
using Kingdee.K3.MFG.App;
using Kingdee.K3.MFG.Common.BusinessEntity.PRD;
using Kingdee.K3.MFG.Contracts;
using Kingdee.K3.MFG.Contracts.PRD;
using Kingdee.K3.MFG.PRD.App.Core.Preparation;
using Kingdee.K3.MFG.PRD.App.Core.Preparation.Match;
using Kingdee.K3.MFG.PRD.App.Core.Preparation.Match.PushPick;
using Kingdee.K3.MFG.PRD.App.Core.Preparation.Match.PushTranferDirect;
using Kingdee.K3.MFG.PRD.App.Core.PrepareMtrl;
using Kingdee.K3.MFG.PRD.App.Core.PrepareMtrl.LackAnalyse;
using Kingdee.K3.MFG.PRD.App.Core.PrepareMtrl.MatchAnalyse;
using Kingdee.K3.MFG.PRD.App.Core.PrepareMtrl.ShortageAnalyse;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;

namespace LQKJ.K3.MFG.PRD.App.ServicePlugIn
{
	[Description("缺料分析调用方法")]
	public class PrepareMtrlService
	{
		public IOperationResult PrepareMtrlAnalyse(Context ctx, List<DynamicObject> lstPrepareMtrlDatas)
		{
			IOperationResult result = new OperationResult();
			if (lstPrepareMtrlDatas == null || lstPrepareMtrlDatas.IsEmpty<DynamicObject>())
			{
				return result;
			}
			lstPrepareMtrlDatas.ForEach(delegate(DynamicObject o)
			{
				result.MergeResult(this.PrepareMtrlAnalyse(ctx, o));
			});
			return result;
		}

		public void AsyncPrepareMtrlAnalyse(Context ctx, DynamicObject prepareMtrlData, IOperationResult result)
		{
			string empty = string.Empty;
			result.CustomMessageFormParameter.CustomParams.TryGetValue("taskId", out empty);
			try
			{
				PrepareMtrlOption prepareMtrlOption = new PrepareMtrlOption
				{
					IsAsync = true
				};
				prepareMtrlOption.ExtendedOption.SetVariableValue("taskId", empty);
				prepareMtrlOption.PreparemtrlData = prepareMtrlData;
				prepareMtrlOption.OperationResult = result;
				Kingdee.K3.MFG.Common.BusinessEntity.PRD.PrepareMtrlBillView prepareMtrlBillView = prepareMtrlData;
				if (prepareMtrlBillView.BusinessType == 1.ToString())
				{
					this.PrepareMtrlMatchAnalyse(ctx, prepareMtrlOption);
				}
				if (prepareMtrlBillView.BusinessType == 2.ToString())
				{
					this.PrepareMtrlShortageAnalyse(ctx, prepareMtrlOption);
				}
				if (prepareMtrlBillView.BusinessType == 3.ToString())
				{
					this.PrepareMtrlLackAnalyse(ctx, prepareMtrlOption);
				}
				if (prepareMtrlOption.IsAsync)
				{
					prepareMtrlOption.PreparemtrlData["Analysised"] = true;
					MFGFlexHelperUtil.SaveFlexFixedColumn(ctx, prepareMtrlOption.PrepareMtrlMetaData.BusinessInfo, new DynamicObject[]
					{
						prepareMtrlOption.PreparemtrlData
					}, "Save");
					AppServiceContext.SaveService.Save(ctx, prepareMtrlOption.PrepareMtrlMetaData.BusinessInfo, new DynamicObject[]
					{
						prepareMtrlOption.PreparemtrlData
					}, null, "");
				}
			}
			catch (Exception ex)
			{
				result.IsSuccess = false;
				result.OperateResult.Add(new OperateResult
				{
					Message = ResManager.LoadKDString("备料分析操作出现异常，请查看本站点的系统日志", "015075000018956", SubSystemType.MFG, new object[0]),
					SuccessStatus = false,
					MessageType = MessageType.FatalError
				});
				result.OperateResult.Add(new OperateResult
				{
					Message = ex.Message,
					SuccessStatus = false,
					MessageType = MessageType.FatalError
				});
				result.OperateResult.Add(new OperateResult
				{
					Message = ex.StackTrace,
					SuccessStatus = false,
					MessageType = MessageType.FatalError
				});
				Logger.Error("PRD", ResManager.LoadKDString("备料分析操作异常", "015075000018957", SubSystemType.MFG, new object[0]), ex);
			}
		}

		private void SavePMResult(Context ctx, DynamicObject prepareMtrlData, DynamicObject lackBillData, string taskId = "")
		{
			ConvertRuleMetaData convertRule = AppServiceContext.ConvertService.GetConvertRule(ctx, "PRD_Lack2LackDetail");
			List<FieldMapHandle> handles = new List<FieldMapHandle>();
			if (convertRule != null)
			{
				handles = MFGBillFieldLinkUtil.GetConvertRuleFieldMapHandle(ctx, convertRule.Rule);
			}
			FormMetadata formMetadata = AppServiceContext.MetadataService.Load(ctx, "PRD_PMPPBOMENTRY", true) as FormMetadata;
			List<DynamicObject> list = new List<DynamicObject>();
			Dictionary<string, IGrouping<string, DynamicObject>> dictionary = (from x in lackBillData["Entity"] as DynamicObjectCollection
			group x by string.Format("{0}_{1}", x["SelOrderType"], x["MoEntryId"])).ToDictionary((IGrouping<string, DynamicObject> k) => k.Key);
			foreach (DynamicObject current in (prepareMtrlData["PrepareMatrlPPbomlEntity"] as DynamicObjectCollection))
			{
				DynamicObject dynamicObject = new DynamicObject(formMetadata.BusinessInfo.GetDynamicObjectType());
				dynamicObject.CopyAllPropertyValues(current, null, null);
				dynamicObject["Id"] = 0;
				dynamicObject["FID"] = prepareMtrlData["Id"];
				IGrouping<string, DynamicObject> source = null;
				string key = string.Format("{0}_{1}", current["SelOrderType"], current["MoEntryId"]);
				if (dictionary.TryGetValue(key, out source))
				{
					MFGBillFieldLinkUtil.DoFieldMapping(handles, dynamicObject, source.FirstOrDefault<DynamicObject>());
				}
				list.Add(dynamicObject);
			}
			if (list.Count > 400)
			{
				int num = 400;
				int num2 = num;
				List<DynamicObject> list2 = new List<DynamicObject>();
				for (int i = 0; i < list.Count; i += num)
				{
					list2 = list.Take(num2).Skip(i).ToList<DynamicObject>();
					num2 += num;
					AppServiceContext.SaveService.Save(ctx, list2.ToArray());
					if (taskId != "")
					{
						string progressMessage = string.Format(ResManager.LoadKDString("正在保存{0}/{1}行分析结果...", "015075000036344", SubSystemType.MFG, new object[0]), num2, list.Count);
						AppServiceContext.GetService<ITaskProgressService>().SetTaskProgressMessage(ctx, taskId, progressMessage);
					}
				}
				return;
			}
			if (!list.IsEmpty<DynamicObject>())
			{
				if (taskId != "")
				{
					string progressMessage2 = string.Format(ResManager.LoadKDString("保存{0}行分析结果...", "015075000036345", SubSystemType.MFG, new object[0]), list.Count);
					AppServiceContext.GetService<ITaskProgressService>().SetTaskProgressMessage(ctx, taskId, progressMessage2);
				}
				AppServiceContext.SaveService.Save(ctx, list.ToArray());
			}
		}

		private void ClearPMResult(Context ctx, DynamicObject prepareMtrlData)
		{
			long num = prepareMtrlData["Id"].ConvertTo(0L);
			if (num > 0L)
			{
				string strSQL = "SELECT FENTRYID FROM T_PRD_PMPPBOMENTRY WHERE FID = @id";
				SqlParam[] paramList = new SqlParam[]
				{
					new SqlParam("@id", KDDbType.Int64, num)
				};
				DynamicObjectCollection col = AppServiceContext.DBService.ExecuteDynamicObject(ctx, strSQL, null, null, CommandType.Text, paramList);
				if (col.IsEmpty<DynamicObject>())
				{
					return;
				}
				List<SqlParam> paramList2 = new List<SqlParam>
				{
					new SqlParam("@fid", KDDbType.Int64, num)
				};
				string strSQL2 = string.Format("MERGE INTO T_PRD_PMPPBOMENTRY_A U1 USING(\r\nSELECT FENTRYID,FID FROM T_PRD_PMPPBOMENTRY WHERE FID = @fid\r\n) U2 ON U1.FENTRYID = U2.FENTRYID WHEN MATCHED THEN UPDATE SET U1.FID = U2.FID;", new object[0]);
				AppServiceContext.DBService.Execute(ctx, strSQL2, paramList2);
				string strSQL3 = "DELETE T_PRD_PMPPBOMENTRY WHERE FID = @fid";
				string strSQL4 = "DELETE T_PRD_PMPPBOMENTRY_A WHERE FID = @fid";
				AppServiceContext.DBService.Execute(ctx, strSQL3, paramList2);
				AppServiceContext.DBService.Execute(ctx, strSQL4, paramList2);
			}
		}

		public IOperationResult RunPMAnalysis(Context ctx, DynamicObject prepareMtrlData, PrepareMtrlOption option)
		{
			IOperationResult operationResult = new OperationResult();
			option.WriteTaskMessage = new Action<Context, PrepareMtrlOption, string, string, string>(this.WriteTaskMessage);
			option.WriteTaskException = new Action<Context, PrepareMtrlOption, string, Exception>(this.WriteTaskException);
			option.SetTaskProgressValue = new Action<Context, PrepareMtrlOption>(this.SetTaskProgressValue);
			try
			{
				option.PreparemtrlData = prepareMtrlData;
				option.OperationResult = operationResult;
				PrepareMtrlBillView prepareMtrlBillView = prepareMtrlData;
				if (prepareMtrlBillView.BusinessType == 1.ToString())
				{
					this.PrepareMtrlMatchAnalyse(ctx, option);
				}
				if (prepareMtrlBillView.BusinessType == 2.ToString())
				{
					this.PrepareMtrlShortageAnalyse(ctx, option);
				}
				if (prepareMtrlBillView.BusinessType == 3.ToString())
				{
					this.PrepareMtrlLackAnalyse(ctx, option);
				}
				option.PreparemtrlData["Analysised"] = true;
				operationResult.SuccessDataEnity = new DynamicObject[]
				{
					option.PreparemtrlData
				};
			}
			catch (Exception ex)
			{
				option.WriteTaskException(ctx, option, ResManager.LoadKDString("备料分析中断", "015075000039192", SubSystemType.MFG, new object[0]), ex);
				operationResult.OperateResult.Add(new OperateResult
				{
					Message = ResManager.LoadKDString("备料分析操作出现异常，请查看本站点的系统日志", "015075000018956", SubSystemType.MFG, new object[0])
				});
				Logger.Error("PRD", ResManager.LoadKDString("备料分析操作异常", "015075000018957", SubSystemType.MFG, new object[0]), ex);
			}
			return operationResult;
		}

		protected void WriteTaskMessage(Context ctx, PrepareMtrlOption option, string period, string msg, string msgType)
		{
			DynamicObject dynamicObject = new DynamicObject(option.TaskProgressDetailMeta.BusinessInfo.GetDynamicObjectType());
			dynamicObject["ComputeNo"] = option.ComputeNo;
			dynamicObject["ProgressMsgId"] = option.TaskId;
			dynamicObject["period"] = period;
			dynamicObject["message"] = msg;
			dynamicObject["DetailTime"] = DateTime.Now;
			dynamicObject["MessageType"] = msgType;
			AppServiceContext.GetService<IBGProgressService>().SetProgressDetail(ctx, dynamicObject);
		}

		protected void WriteTaskException(Context ctx, PrepareMtrlOption option, string period, Exception ex)
		{
			DynamicObject dynamicObject = new DynamicObject(option.TaskProgressDetailMeta.BusinessInfo.GetDynamicObjectType());
			dynamicObject["ComputeNo"] = option.ComputeNo;
			dynamicObject["ProgressMsgId"] = option.TaskId;
			dynamicObject["period"] = period;
			dynamicObject["DetailTime"] = DateTime.Now;
			dynamicObject["message"] = ex.Message;
			dynamicObject["MessageType"] = "2";
			dynamicObject["Exceptions"] = ex.StackTrace;
			AppServiceContext.GetService<IBGProgressService>().SetProgressDetail(ctx, dynamicObject);
		}

		protected void SetTaskProgressValue(Context ctx, PrepareMtrlOption option)
		{
			AppServiceContext.GetService<IBGProgressService>().SetProgressStatus(ctx, option.ComputeNo, "0", option.TaskProgressValue);
		}

		public IOperationResult PushBills(Context ctx, DynamicObject prepareMtrlData, PrepareMtrlOption option)
		{
			return null;
		}

		public List<string> GetBillNoList(Context ctx, List<long> lstPMFIds)
		{
			if (lstPMFIds == null || lstPMFIds.Count < 1)
			{
				return new List<string>();
			}
			string strSQL = "SELECT T1.FBILLNO AS BILLNO FROM T_PRD_PREPAREMTRL T1 INNER JOIN table(fn_StrSplit(@FID,',',1)) T2 ON T1.FID =T2.FID ";
			DynamicObjectCollection dynamicObjectCollection = AppServiceContext.DBService.ExecuteDynamicObject(ctx, strSQL, null, null, CommandType.Text, new SqlParam[]
			{
				new SqlParam("@FID", KDDbType.udt_inttable, lstPMFIds.Distinct<long>().ToArray<long>())
			});
			if (dynamicObjectCollection == null || dynamicObjectCollection.Count <= 0)
			{
				return new List<string>();
			}
			return (from o in dynamicObjectCollection
			select o["BILLNO"].ToString()).ToList<string>();
		}

		public List<long> GetPPBOMEntryIdesByPMFID(Context ctx, List<long> lstPMFIds)
		{
			if (lstPMFIds == null || lstPMFIds.Count < 1)
			{
				return new List<long>();
			}
			string strSQL = "SELECT T1.FPPBOMENTRYID AS PPBOMENTRYID FROM T_PRD_PREPAREMTRLPPBOMENTRY T1 INNER JOIN table(fn_StrSplit(@FID,',',1)) T2 ON T1.FID =T2.FID ";
			DynamicObjectCollection dynamicObjectCollection = AppServiceContext.DBService.ExecuteDynamicObject(ctx, strSQL, null, null, CommandType.Text, new SqlParam[]
			{
				new SqlParam("@FID", KDDbType.udt_inttable, lstPMFIds.Distinct<long>().ToArray<long>())
			});
			if (dynamicObjectCollection == null || dynamicObjectCollection.Count <= 0)
			{
				return new List<long>();
			}
			return (from o in dynamicObjectCollection
			select Convert.ToInt64(o["PPBOMENTRYID"].ToString())).ToList<long>();
		}

		private IOperationResult PrepareMtrlAnalyse(Context ctx, DynamicObject prepareMtrlData)
		{
			IOperationResult operationResult = new OperationResult();
			PrepareMtrlOption prepareMtrlOption = new PrepareMtrlOption();
			prepareMtrlOption.PreparemtrlData = prepareMtrlData;
			prepareMtrlOption.OperationResult = operationResult;
			PrepareMtrlBillView prepareMtrlBillView = prepareMtrlData;
			if (prepareMtrlBillView.BusinessType == 1.ToString())
			{
				this.PrepareMtrlMatchAnalyse(ctx, prepareMtrlOption);
			}
			if (prepareMtrlBillView.BusinessType == 2.ToString())
			{
				this.PrepareMtrlShortageAnalyse(ctx, prepareMtrlOption);
			}
			if (prepareMtrlBillView.BusinessType == 3.ToString())
			{
				this.PrepareMtrlLackAnalyse(ctx, prepareMtrlOption);
			}
			return prepareMtrlOption.OperationResult;
		}

		private void PrepareMtrlMatchAnalyse(Context ctx, PrepareMtrlOption option)
		{
			List<AbstractPrepareMtrlBaseAction> list = new List<AbstractPrepareMtrlBaseAction>();
			AbstractPrepareMtrlBaseAction item = new Kingdee.K3.MFG.PRD.App.Core.PrepareMtrl.MatchAnalyse.PrepareMtrlInitAction(ctx, option);
			AbstractPrepareMtrlBaseAction item2 = new Kingdee.K3.MFG.PRD.App.Core.PrepareMtrl.MatchAnalyse.PrepareMtrlScopeAction(ctx, option);
			AbstractPrepareMtrlBaseAction item3 = new Kingdee.K3.MFG.PRD.App.Core.PrepareMtrl.MatchAnalyse.PrepareMtrlDemendAction(ctx, option);
			AbstractPrepareMtrlBaseAction item4 = new Kingdee.K3.MFG.PRD.App.Core.PrepareMtrl.MatchAnalyse.PrepareMtrlSupplyAction(ctx, option);
			AbstractPrepareMtrlBaseAction item5 = new Kingdee.K3.MFG.PRD.App.Core.PrepareMtrl.MatchAnalyse.PrepareMtrlDSAnalyseAction(ctx, option);
			AbstractPrepareMtrlBaseAction item6 = new Kingdee.K3.MFG.PRD.App.Core.PrepareMtrl.MatchAnalyse.PrepareMtrlUnitConvertAction(ctx, option);
			AbstractPrepareMtrlBaseAction item7 = new Kingdee.K3.MFG.PRD.App.Core.PrepareMtrl.MatchAnalyse.PrepareMtrlEndAction(ctx, option);
			list.Add(item);
			list.Add(item2);
			list.Add(item3);
			list.Add(item4);
			list.Add(item5);
			list.Add(item6);
			list.Add(item7);
			this.ExecuteActions(list);
		}

		private void PrepareMtrlShortageAnalyse(Context ctx, PrepareMtrlOption option)
		{
			List<AbstractPrepareMtrlBaseAction> list = new List<AbstractPrepareMtrlBaseAction>();
			AbstractPrepareMtrlBaseAction item = new Kingdee.K3.MFG.PRD.App.Core.PrepareMtrl.ShortageAnalyse.PrepareMtrlInitAction(ctx, option);
			AbstractPrepareMtrlBaseAction item2 = new Kingdee.K3.MFG.PRD.App.Core.PrepareMtrl.ShortageAnalyse.PrepareMtrlScopeAction(ctx, option);
			AbstractPrepareMtrlBaseAction item3 = new Kingdee.K3.MFG.PRD.App.Core.PrepareMtrl.ShortageAnalyse.PrepareMtrlDemendAction(ctx, option);
			AbstractPrepareMtrlBaseAction item4 = new Kingdee.K3.MFG.PRD.App.Core.PrepareMtrl.ShortageAnalyse.PrepareMtrlSupplyAction(ctx, option);
			AbstractPrepareMtrlBaseAction item5 = new Kingdee.K3.MFG.PRD.App.Core.PrepareMtrl.ShortageAnalyse.PrepareMtrlDSAnalyseAction(ctx, option);
			AbstractPrepareMtrlBaseAction item6 = new Kingdee.K3.MFG.PRD.App.Core.PrepareMtrl.ShortageAnalyse.PrepareMtrlUnitConvertAction(ctx, option);
			AbstractPrepareMtrlBaseAction item7 = new Kingdee.K3.MFG.PRD.App.Core.PrepareMtrl.ShortageAnalyse.PrepareMtrlEndAction(ctx, option);
			list.Add(item);
			list.Add(item2);
			list.Add(item3);
			list.Add(item4);
			list.Add(item5);
			list.Add(item6);
			list.Add(item7);
			this.ExecuteActions(list);
		}

		private void PrepareMtrlLackAnalyse(Context ctx, PrepareMtrlOption option)
		{
			List<AbstractPrepareMtrlBaseAction> list = new List<AbstractPrepareMtrlBaseAction>();
			AbstractPrepareMtrlBaseAction item = new Kingdee.K3.MFG.PRD.App.Core.PrepareMtrl.LackAnalyse.PrepareMtrlInitAction(ctx, option);
			AbstractPrepareMtrlBaseAction item2 = new Kingdee.K3.MFG.PRD.App.Core.PrepareMtrl.LackAnalyse.PrepareMtrlScopeAction(ctx, option);
			AbstractPrepareMtrlBaseAction item3 = new Kingdee.K3.MFG.PRD.App.Core.PrepareMtrl.LackAnalyse.PrepareMtrlDemendAction(ctx, option);
			AbstractPrepareMtrlBaseAction item4 = new Kingdee.K3.MFG.PRD.App.Core.PrepareMtrl.LackAnalyse.PrepareMtrlSupplyAction(ctx, option);
			AbstractPrepareMtrlBaseAction item5 = new Kingdee.K3.MFG.PRD.App.Core.PrepareMtrl.LackAnalyse.PrepareMtrlDSAnalyseAction(ctx, option);
			AbstractPrepareMtrlBaseAction item6 = new Kingdee.K3.MFG.PRD.App.Core.PrepareMtrl.LackAnalyse.PrepareMtrlUnitConvertAction(ctx, option);
			AbstractPrepareMtrlBaseAction item7 = new Kingdee.K3.MFG.PRD.App.Core.PrepareMtrl.LackAnalyse.PrepareMtrlEndAction(ctx, option);
			list.Add(item);
			list.Add(item2);
			list.Add(item3);
			list.Add(item4);
			list.Add(item5);
			list.Add(item6);
			list.Add(item7);
			this.ExecuteActions(list);
		}

		private void ExecuteActions(List<AbstractPrepareMtrlBaseAction> prepareMtrlActionList)
		{
			foreach (AbstractPrepareMtrlBaseAction current in prepareMtrlActionList)
			{
				current.Execute();
				if (!current.OperationResult.IsSuccess)
				{
					break;
				}
			}
		}

		public void MatchAnalyseForBoard(Context ctx, DynamicObject matchBillData, IOperationResult result, OperateOption extendOption)
		{
			string empty = string.Empty;
			extendOption.TryGetVariableValue<string>("taskId", out empty);
			try
			{
				FormMetadata pmMeta = AppServiceContext.MetadataService.Load(ctx, "PRD_PREPAREMTRL", true) as FormMetadata;
				DynamicObject item = this.DoMatchAnalyse(ctx, matchBillData, result, empty, pmMeta);
				result.SuccessDataEnity = new List<DynamicObject>
				{
					item
				};
				result.IsSuccess = true;
			}
			catch (Exception ex)
			{
				result.IsSuccess = false;
				result.OperateResult.Add(new OperateResult
				{
					Message = ResManager.LoadKDString("齐套分析操作出现异常，请查看本站点的系统日志", "015075000039193", SubSystemType.MFG, new object[0]),
					SuccessStatus = false,
					MessageType = MessageType.FatalError
				});
				result.OperateResult.Add(new OperateResult
				{
					Message = ex.Message,
					SuccessStatus = false,
					MessageType = MessageType.FatalError
				});
				result.OperateResult.Add(new OperateResult
				{
					Message = ex.StackTrace,
					SuccessStatus = false,
					MessageType = MessageType.FatalError
				});
				Logger.Error("PRD", ResManager.LoadKDString("齐套分析操作异常", "015075000039194", SubSystemType.MFG, new object[0]), ex);
			}
		}

		public void AsyncMatchAnalyse(Context ctx, DynamicObject matchBillData, IOperationResult result, OperateOption extendOption)
		{
			string empty = string.Empty;
			extendOption.TryGetVariableValue<string>("taskId", out empty);
			try
			{
				this.ClearMatchResult(ctx, matchBillData);
				FormMetadata pmMeta = AppServiceContext.MetadataService.Load(ctx, "PRD_PREPAREMTRL", true) as FormMetadata;
				DynamicObject prepareMtrlData = this.DoMatchAnalyse(ctx, matchBillData, result, empty, pmMeta);
				FormMetadata formMetadata = AppServiceContext.MetadataService.Load(ctx, "PRD_MatchAnalyseBill", true) as FormMetadata;
				MFGFlexHelperUtil.SaveFlexFixedColumn(ctx, formMetadata.BusinessInfo, new DynamicObject[]
				{
					matchBillData
				}, "Save");
				this.SaveMatchResult(ctx, prepareMtrlData, empty);
				IOperationResult operationResult = AppServiceContext.SaveService.Save(ctx, formMetadata.BusinessInfo, new DynamicObject[]
				{
					matchBillData
				}, null, "");
				if (!operationResult.IsSuccess)
				{
					result.IsSuccess = false;
					operationResult.MergeValidateErrors();
					result.MergeResult(operationResult);
					matchBillData["Analysised"] = false;
					AppServiceContext.SaveService.Save(ctx, new DynamicObject[]
					{
						matchBillData
					});
				}
			}
			catch (Exception ex)
			{
				result.IsSuccess = false;
				result.OperateResult.Add(new OperateResult
				{
					Message = ResManager.LoadKDString("齐套分析操作出现异常，请查看本站点的系统日志", "015075000039193", SubSystemType.MFG, new object[0]),
					SuccessStatus = false,
					MessageType = MessageType.FatalError
				});
				result.OperateResult.Add(new OperateResult
				{
					Message = ex.Message,
					SuccessStatus = false,
					MessageType = MessageType.FatalError
				});
				result.OperateResult.Add(new OperateResult
				{
					Message = ex.StackTrace,
					SuccessStatus = false,
					MessageType = MessageType.FatalError
				});
				Logger.Error("PRD", ResManager.LoadKDString("齐套分析操作异常", "015075000039194", SubSystemType.MFG, new object[0]), ex);
			}
		}

		private DynamicObject DoMatchAnalyse(Context ctx, DynamicObject matchBillData, IOperationResult result, string taskId, FormMetadata pmMeta)
		{
			DynamicObject dynamicObject = new DynamicObject(pmMeta.BusinessInfo.GetDynamicObjectType());
			dynamicObject.CopyAllPropertyValues(matchBillData, null, null);
			dynamicObject.SetDynamicObjectItemValue("Id", matchBillData.GetDynamicValue("Id", 0L));
			DynamicObjectCollection sourceDataEntities = matchBillData["MASTKScope"] as DynamicObjectCollection;
			DynamicObjectCollection dataEntities = dynamicObject["PreparemtrlStockEntity"] as DynamicObjectCollection;
			dataEntities.FromDataSource(sourceDataEntities, true, null, null, null);
			DynamicObjectCollection moEntrys = matchBillData["Entity"] as DynamicObjectCollection;
			DynamicObjectCollection dynamicObjectCollection = dynamicObject["Entity"] as DynamicObjectCollection;
			foreach (DynamicObject current in moEntrys)
			{
				DynamicObject dynamicObject2 = new DynamicObject(dynamicObjectCollection.DynamicCollectionItemPropertyType);
				dynamicObject2.CopyAllPropertyValues(current, null, null);
				dynamicObject2.SetDynamicObjectItemValue("Id", current.GetDynamicValue("Id", 0L));
				dynamicObjectCollection.Add(dynamicObject2);
			}
			PrepareMtrlOption prepareMtrlOption = new PrepareMtrlOption();
			prepareMtrlOption.ExtendedOption.SetVariableValue("taskId", taskId);
			prepareMtrlOption.ExtendedOption.SetVariableValue("ExceptRO", matchBillData.GetDynamicValue("ExceptRO", false));
			prepareMtrlOption.PreparemtrlData = dynamicObject;
			prepareMtrlOption.OperationResult = result;
			//dynamicObject;
			new MatchAnalyseStrategy(ctx, prepareMtrlOption).Execute();
			Dictionary<long, DynamicObject> dictionary = (from x in dynamicObjectCollection
			group x by x.GetDynamicValue("Id", 0L)).ToDictionary((IGrouping<long, DynamicObject> x) => x.Key, (IGrouping<long, DynamicObject> v) => v.First<DynamicObject>());
			List<DynamicObject> list = new List<DynamicObject>();
			foreach (DynamicObject current2 in moEntrys)
			{
				DynamicObject dynamicObject3;
				if (dictionary.TryGetValue(current2.GetDynamicValue("Id", 0L), out dynamicObject3))
				{
					current2.SetDynamicObjectItemValue("MatchQty", dynamicObject3.GetDynamicValue("MatchQty", 0m));
					current2.SetDynamicObjectItemValue("BaseMatchQty", dynamicObject3.GetDynamicValue("BaseMatchQty", 0m));
				}
				else
				{
					list.Add(current2);
				}
			}
			if (!list.IsEmpty<DynamicObject>())
			{
				list.ForEach(delegate(DynamicObject x)
				{
					moEntrys.Remove(x);
				});
			}
			matchBillData["Analysised"] = true;
			return dynamicObject;
		}

		private void SaveMatchResult(Context ctx, DynamicObject prepareMtrlData, string taskId = "")
		{
			FormMetadata formMetadata = AppServiceContext.MetadataService.Load(ctx, "PRD_MATCHDETAIL", true) as FormMetadata;
			List<DynamicObject> list = new List<DynamicObject>();
			foreach (DynamicObject current in (prepareMtrlData["PrepareMatrlPPbomlEntity"] as DynamicObjectCollection))
			{
				DynamicObject dynamicObject = new DynamicObject(formMetadata.BusinessInfo.GetDynamicObjectType());
				dynamicObject.CopyAllPropertyValues(current, null, null);
				dynamicObject["Id"] = 0;
				dynamicObject["FID"] = prepareMtrlData["Id"];
				list.Add(dynamicObject);
			}
			if (list.Count > 400)
			{
				int num = 400;
				int num2 = num;
				List<DynamicObject> list2 = new List<DynamicObject>();
				for (int i = 0; i < list.Count; i += num)
				{
					list2 = list.Take(num2).Skip(i).ToList<DynamicObject>();
					num2 += num;
					AppServiceContext.SaveService.Save(ctx, list2.ToArray());
					if (taskId != "")
					{
						string progressMessage = string.Format(ResManager.LoadKDString("正在保存{0}/{1}行分析结果...", "015075000036344", SubSystemType.MFG, new object[0]), num2, list.Count);
						AppServiceContext.GetService<ITaskProgressService>().SetTaskProgressMessage(ctx, taskId, progressMessage);
					}
				}
				return;
			}
			if (!list.IsEmpty<DynamicObject>())
			{
				if (taskId != "")
				{
					string progressMessage2 = string.Format(ResManager.LoadKDString("保存{0}行分析结果...", "015075000036345", SubSystemType.MFG, new object[0]), list.Count);
					AppServiceContext.GetService<ITaskProgressService>().SetTaskProgressMessage(ctx, taskId, progressMessage2);
				}
				AppServiceContext.SaveService.Save(ctx, list.ToArray());
			}
		}

		private void ClearMatchResult(Context ctx, DynamicObject prepareMtrlData)
		{
			long num = prepareMtrlData["Id"].ConvertTo(0L);
			if (num > 0L)
			{
				string strSQL = "SELECT FENTRYID FROM T_PRD_MAPPBOMENTRY WHERE FID = @id";
				SqlParam[] paramList = new SqlParam[]
				{
					new SqlParam("@id", KDDbType.Int64, num)
				};
				DynamicObjectCollection col = AppServiceContext.DBService.ExecuteDynamicObject(ctx, strSQL, null, null, CommandType.Text, paramList);
				if (col.IsEmpty<DynamicObject>())
				{
					return;
				}
				List<SqlParam> paramList2 = new List<SqlParam>
				{
					new SqlParam("@fid", KDDbType.Int64, num)
				};
				string strSQL2 = string.Format("MERGE INTO T_PRD_MAPPBOMENTRY_A U1 USING(\r\nSELECT FID,FENTRYID FROM T_PRD_MAPPBOMENTRY WHERE FID=@fid\r\n) U2 ON U1.FENTRYID = U2.FENTRYID WHEN MATCHED THEN UPDATE SET U1.FID = U2.FID;", new object[0]);
				AppServiceContext.DbUtils.Execute(ctx, strSQL2, paramList2);
				string strSQL3 = "DELETE FROM T_PRD_MAPPBOMENTRY_A WHERE FID=@fid";
				AppServiceContext.DBService.Execute(ctx, strSQL3, paramList2);
				string strSQL4 = "DELETE T_PRD_MAPPBOMENTRY WHERE FID = @fid";
				AppServiceContext.DBService.Execute(ctx, strSQL4, paramList2);
			}
		}

		public void PushPickMtrl(Context ctx, DynamicObject matchBillData, IOperationResult result, OperateOption extendOption)
		{
			string empty = string.Empty;
			extendOption.TryGetVariableValue<string>("taskId", out empty);
			try
			{
				AppServiceContext.GetService<ITaskProgressService>().SetTaskProgressMessage(ctx, empty, ResManager.LoadKDString("正在下推生产领料单...", "015075000039195", SubSystemType.MFG, new object[0]));
				PickMtrlBuilder.BuildPickMtrl(ctx, matchBillData, result, extendOption);
			}
			catch (Exception ex)
			{
				result.OperateResult.Add(new OperateResult
				{
					Message = string.Format(ResManager.LoadKDString("齐套分析单下推领料单出现异常，请查看本站点的系统日志", "015075000039196", SubSystemType.MFG, new object[0]), new object[0]),
					SuccessStatus = false,
					MessageType = MessageType.FatalError
				});
				result.OperateResult.Add(new OperateResult
				{
					Message = ex.Message,
					SuccessStatus = false,
					MessageType = MessageType.FatalError
				});
				result.OperateResult.Add(new OperateResult
				{
					Message = ex.StackTrace,
					SuccessStatus = false,
					MessageType = MessageType.FatalError
				});
				result.IsSuccess = false;
				Logger.Error("PRD_MatchAnalyse", ex.Message, ex);
			}
		}

		public void PushTransferDirect(Context ctx, DynamicObject matchBillData, IOperationResult result, OperateOption extendOption)
		{
			string empty = string.Empty;
			extendOption.TryGetVariableValue<string>("taskId", out empty);
			try
			{
				AppServiceContext.GetService<ITaskProgressService>().SetTaskProgressMessage(ctx, empty, ResManager.LoadKDString("正在下推直接调拨单...", "015075000039197", SubSystemType.MFG, new object[0]));
				TransferDirectBuilder.PushTransferDirect(ctx, matchBillData, result, extendOption);
			}
			catch (Exception ex)
			{
				result.OperateResult.Add(new OperateResult
				{
					Message = string.Format(ResManager.LoadKDString("齐套分析单下推直接调拨单出现异常，请查看本站点的系统日志", "015075000039198", SubSystemType.MFG, new object[0]), new object[0]),
					SuccessStatus = false,
					MessageType = MessageType.FatalError
				});
				result.OperateResult.Add(new OperateResult
				{
					Message = ex.Message,
					SuccessStatus = false,
					MessageType = MessageType.FatalError
				});
				result.OperateResult.Add(new OperateResult
				{
					Message = ex.StackTrace,
					SuccessStatus = false,
					MessageType = MessageType.FatalError
				});
				result.IsSuccess = false;
				Logger.Error("PRD_MatchAnalyse", ex.Message, ex);
			}
		}

		public IOperationResult CallSUBMatchAnalyse(Context ctx, DynamicObject subPrepareMtrlData, OperateOption extendOption)
		{
			IOperationResult operationResult = new OperationResult();
			FormMetadata formMetadata = AppServiceContext.MetadataService.Load(ctx, "PRD_PREPAREMTRL", true) as FormMetadata;
			DynamicObject dynamicObject = new DynamicObject(formMetadata.BusinessInfo.GetDynamicObjectType());
			ConvertRuleMetaData convertRule = AppServiceContext.ConvertService.GetConvertRule(ctx, "SUB_PrepareMtrl2PMHead");
			List<FieldMapHandle> handles = new List<FieldMapHandle>();
			if (convertRule != null)
			{
				handles = MFGBillFieldLinkUtil.GetConvertRuleFieldMapHandle(ctx, convertRule.Rule);
			}
			MFGBillFieldLinkUtil.DoFieldMapping(handles, dynamicObject, subPrepareMtrlData);
			dynamicObject.SetDynamicObjectItemValue("Id", subPrepareMtrlData.GetDynamicValue("Id", 0L));
			DynamicObjectCollection sourceDataEntities = subPrepareMtrlData["PreparemtrlStockEntity"] as DynamicObjectCollection;
			DynamicObjectCollection dataEntities = dynamicObject["PreparemtrlStockEntity"] as DynamicObjectCollection;
			dataEntities.FromDataSource(sourceDataEntities, true, null, null, null);
			DynamicObjectCollection moEntrys = subPrepareMtrlData["Entity"] as DynamicObjectCollection;
			DynamicObjectCollection dynamicObjectCollection = dynamicObject["Entity"] as DynamicObjectCollection;
			ConvertRuleMetaData convertRule2 = AppServiceContext.ConvertService.GetConvertRule(ctx, "SUB_PrepareMtrl2PMMoList");
			List<FieldMapHandle> handles2 = new List<FieldMapHandle>();
			if (convertRule != null)
			{
				handles2 = MFGBillFieldLinkUtil.GetConvertRuleFieldMapHandle(ctx, convertRule2.Rule);
			}
			foreach (DynamicObject current in moEntrys)
			{
				DynamicObject dynamicObject2 = new DynamicObject(dynamicObjectCollection.DynamicCollectionItemPropertyType);
				MFGBillFieldLinkUtil.DoFieldMapping(handles2, dynamicObject2, current);
				dynamicObject2.SetDynamicObjectItemValue("Id", current.GetDynamicValue("Id", 0L));
				dynamicObjectCollection.Add(dynamicObject2);
			}
			AppServiceContext.DBService.LoadReferenceObject(ctx, new DynamicObject[]
			{
				dynamicObject
			}, formMetadata.BusinessInfo.GetDynamicObjectType(), true);
			PrepareMtrlOption prepareMtrlOption = new PrepareMtrlOption();
			string value = SequentialGuid.NewGuid().ToString();
			prepareMtrlOption.ExtendedOption.SetVariableValue("taskId", value);
			prepareMtrlOption.ExtendedOption.SetVariableValue("ExceptRO", false);
			prepareMtrlOption.PreparemtrlData = dynamicObject;
			prepareMtrlOption.OperationResult = operationResult;
			//dynamicObject;
			new MatchAnalyseStrategy(ctx, prepareMtrlOption).Execute();
			ConvertRuleMetaData convertRule3 = AppServiceContext.ConvertService.GetConvertRule(ctx, "PRD_PrepareMtrl2SUBPM");
			List<FieldMapHandle> handles3 = new List<FieldMapHandle>();
			if (convertRule3 != null)
			{
				handles3 = MFGBillFieldLinkUtil.GetConvertRuleFieldMapHandle(ctx, convertRule3.Rule);
			}
			DynamicObjectCollection dynamicObjectCollection2 = subPrepareMtrlData["PrepareMatrlPPbomlEntity"] as DynamicObjectCollection;
			dynamicObjectCollection2.Clear();
			DynamicObjectCollection dynamicObjectCollection3 = dynamicObject["PrepareMatrlPPbomlEntity"] as DynamicObjectCollection;
			int num = 1;
			foreach (DynamicObject current2 in dynamicObjectCollection3)
			{
				DynamicObject dynamicObject3 = new DynamicObject(dynamicObjectCollection2.DynamicCollectionItemPropertyType);
				MFGBillFieldLinkUtil.DoFieldMapping(handles3, dynamicObject3, current2);
				dynamicObject3.SetDynamicObjectItemValue("Seq", num++);
				dynamicObjectCollection2.Add(dynamicObject3);
			}
			Dictionary<long, DynamicObject> dictionary = (from x in dynamicObjectCollection
			group x by x.GetDynamicValue("Id", 0L)).ToDictionary((IGrouping<long, DynamicObject> x) => x.Key, (IGrouping<long, DynamicObject> v) => v.First<DynamicObject>());
			List<DynamicObject> list = new List<DynamicObject>();
			foreach (DynamicObject current3 in moEntrys)
			{
				DynamicObject dynamicObject4;
				if (dictionary.TryGetValue(current3.GetDynamicValue("Id", 0L), out dynamicObject4))
				{
					current3.SetDynamicObjectItemValue("MatchQty", dynamicObject4.GetDynamicValue("MatchQty", 0m));
					current3.SetDynamicObjectItemValue("BaseMatchQty", dynamicObject4.GetDynamicValue("BaseMatchQty", 0m));
				}
				else
				{
					list.Add(current3);
				}
			}
			if (!list.IsEmpty<DynamicObject>())
			{
				list.ForEach(delegate(DynamicObject x)
				{
					moEntrys.Remove(x);
				});
			}
			subPrepareMtrlData["Analysised"] = true;
			AppServiceContext.DBService.LoadReferenceObject(ctx, new DynamicObject[]
			{
				subPrepareMtrlData
			}, subPrepareMtrlData.DynamicObjectType, true);
			return operationResult;
		}

		public void AsyncLackAnalyse(Context ctx, DynamicObject lackBillData, IOperationResult result, OperateOption extendOption)
		{
			string empty = string.Empty;
			extendOption.TryGetVariableValue<string>("taskId", out empty);
			try
			{
				FormMetadata formMetadata = AppServiceContext.MetadataService.Load(ctx, "PRD_PREPAREMTRL", true) as FormMetadata;
				DynamicObject dynamicObject = new DynamicObject(formMetadata.BusinessInfo.GetDynamicObjectType());
				dynamicObject.CopyAllPropertyValues(lackBillData, null, null);
				dynamicObject.SetDynamicObjectItemValue("Id", lackBillData.GetDynamicValue("Id", 0L));
				DynamicObjectCollection sourceDataEntities = lackBillData["LKScopeEntity"] as DynamicObjectCollection;
				DynamicObjectCollection dataEntities = dynamicObject["PreparemtrlStockEntity"] as DynamicObjectCollection;
				dataEntities.FromDataSource(sourceDataEntities, true, null, null, null);
				DynamicObjectCollection moEntrys = lackBillData["Entity"] as DynamicObjectCollection;
				DynamicObjectCollection dynamicObjectCollection = dynamicObject["Entity"] as DynamicObjectCollection;
				foreach (DynamicObject current in moEntrys)
				{
					DynamicObject dynamicObject2 = new DynamicObject(dynamicObjectCollection.DynamicCollectionItemPropertyType);
					dynamicObject2.CopyAllPropertyValues(current, null, null);
					dynamicObject2.SetDynamicObjectItemValue("Id", current.GetDynamicValue("Id", 0L));
					dynamicObjectCollection.Add(dynamicObject2);
				}
				PrepareMtrlOption prepareMtrlOption = new PrepareMtrlOption();
				prepareMtrlOption.ExtendedOption.SetVariableValue("taskId", empty);
				prepareMtrlOption.ExtendedOption.SetVariableValue("matchOwner", lackBillData.GetDynamicValue("MatchOwner", false));
				prepareMtrlOption.ExtendedOption.SetVariableValue("billTypeSetting", lackBillData.GetDynamicValue("BillTypeEntity", default(DynamicObjectCollection)));
				prepareMtrlOption.ExtendedOption.SetVariableValue("Requisition", lackBillData.GetDynamicValue("Requisition", false));
				prepareMtrlOption.ExtendedOption.SetVariableValue("POExpireDate", lackBillData.GetDynamicValue("POExpireDate", default(DateTime)));
				prepareMtrlOption.PreparemtrlData = dynamicObject;
				prepareMtrlOption.OperationResult = result;
				PrepareMtrlBillView prepareMtrlBillView = dynamicObject;
				this.ClearPMResult(ctx, lackBillData);
				new LackPMStrategy(ctx, prepareMtrlOption).Execute();
				Dictionary<long, DynamicObject> dictionary = (from x in dynamicObjectCollection
				group x by x.GetDynamicValue("Id", 0L)).ToDictionary((IGrouping<long, DynamicObject> x) => x.Key, (IGrouping<long, DynamicObject> v) => v.First<DynamicObject>());
				List<DynamicObject> list = new List<DynamicObject>();
				foreach (DynamicObject current2 in moEntrys)
				{
					DynamicObject dynamicObject3;
					if (dictionary.TryGetValue(current2.GetDynamicValue("Id", 0L), out dynamicObject3))
					{
						current2.SetDynamicObjectItemValue("IsLack", dynamicObject3.GetDynamicValue("IsLack", 0m));
					}
					else
					{
						list.Add(current2);
					}
				}
				if (!list.IsEmpty<DynamicObject>())
				{
					list.ForEach(delegate(DynamicObject x)
					{
						moEntrys.Remove(x);
					});
				}
				DynamicObjectCollection dataEntities2 = lackBillData["LackEntity"] as DynamicObjectCollection;
				DynamicObjectCollection sourceDataEntities2 = prepareMtrlBillView.DataEntity["PrepareMatrlLackEntity"] as DynamicObjectCollection;
				MFGFlexHelperUtil.SaveFlexFixedColumn(ctx, formMetadata.BusinessInfo, new DynamicObject[]
				{
					prepareMtrlBillView.DataEntity
				}, "Save");
				dataEntities2.FromDataSource(sourceDataEntities2, true, null, null, null);
				FormMetadata formMetadata2 = AppServiceContext.MetadataService.Load(ctx, "PRD_LackAnalyeBill", true) as FormMetadata;
				lackBillData["Analysised"] = true;
				this.SavePMResult(ctx, dynamicObject, lackBillData, empty);
				AppServiceContext.SaveService.Save(ctx, formMetadata2.BusinessInfo, new DynamicObject[]
				{
					lackBillData
				}, null, "");
			}
			catch (Exception ex)
			{
				result.IsSuccess = false;
				result.OperateResult.Add(new OperateResult
				{
					Message = ResManager.LoadKDString("缺料分析操作出现异常，请查看本站点的系统日志", "015075000036342", SubSystemType.MFG, new object[0]),
					SuccessStatus = false,
					MessageType = MessageType.FatalError
				});
				result.OperateResult.Add(new OperateResult
				{
					Message = ex.Message,
					SuccessStatus = false,
					MessageType = MessageType.FatalError
				});
				result.OperateResult.Add(new OperateResult
				{
					Message = ex.StackTrace,
					SuccessStatus = false,
					MessageType = MessageType.FatalError
				});
				Logger.Error("PRD", ResManager.LoadKDString("缺料分析操作异常", "015075000036343", SubSystemType.MFG, new object[0]), ex);
			}
		}

    }
}
