using Kingdee.BOS;
using Kingdee.BOS.BusinessEntity.BillTrack;
using Kingdee.BOS.Core.Bill;
using Kingdee.BOS.Core.Bill.PlugIn;
using Kingdee.BOS.Core.Bill.PlugIn.Args;
using Kingdee.BOS.Core.CommonFilter;
using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Core.DynamicForm.Operation;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Core.List;
using Kingdee.BOS.Core.List.PlugIn.Args;
using Kingdee.BOS.Core.Metadata;
using Kingdee.BOS.Core.Metadata.ConvertElement;
using Kingdee.BOS.Core.Metadata.ConvertElement.ServiceArgs;
using Kingdee.BOS.Core.Metadata.EntityElement;
using Kingdee.BOS.Core.Metadata.FormElement;
using Kingdee.BOS.Core.Validation;
using Kingdee.BOS.Orm;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.Resource;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.Util;
using Kingdee.K3.BD.Common.Business.PlugIn;
using Kingdee.K3.BD.ServiceHelper;
using Kingdee.K3.Core.SCM.Args;
using Kingdee.K3.Core.SCM.STK.SP;
using Kingdee.K3.SCM.Business;
using Kingdee.K3.SCM.ServiceHelper;
using Kingdee.K3.SCM.ServiceHelper.SP;
using static Kingdee.K3.SCM.Business.BillUtils;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;

namespace Kingdee.K3.SCM.Stock.Business.PlugIn.SP
{
	[Description("简单生产领料单-表单插件")]
	public class SpPickMtrlEdit : AbstractBillPlugIn
	{
		private const string SPPickMtrlUserParameter = "SP_PickMtrlUserParameter";

		private List<long> _entityIdsInStockBeforeSave;

		private long lastAuxpropId;

		//private string PushEnityKey = "FEntity";

		public override void PreOpenForm(PreOpenFormEventArgs e)
		{
			if (!e.Context.IsMultiOrg && Kingdee.K3.SCM.ServiceHelper.StockServiceHelper.GetUpdateStockDate(e.Context, e.Context.CurrentOrganizationInfo.ID) == null)
			{
				e.CancelMessage = ResManager.LoadKDString("请先在【启用库存管理】中设置库存启用日期,再进行库存业务处理.", "004023030002269", SubSystemType.SCM, new object[0]);
				e.Cancel = true;
			}
		}

		public override void BeforeDoOperation(BeforeDoOperationEventArgs e)
		{
			base.BeforeDoOperation(e);
			if (e.Operation.FormOperation.OperationId == FormOperation.Operation_Draw)
			{
				SelInStockBillParam selInStockBillParam = new SelInStockBillParam();
				selInStockBillParam.StockOrgId = this.Model.GetValue("FStockOrgId", -1, 0L, null);
				selInStockBillParam.PrdOrgId = this.Model.GetValue("FPrdOrgId", -1, 0L, null);
				selInStockBillParam.OwnerType = this.Model.GetValue("FOwnerTypeId0", -1, "", null);
				selInStockBillParam.OwnerId = this.Model.GetValue("FOwnerId0", -1, 0L, null);
				selInStockBillParam.WorkShopId = this.Model.GetValue("FWorkShopId", -1, 0L, null);
				if (this.ValidatePush(selInStockBillParam))
				{
					selInStockBillParam.FilterString = string.Format(" FPrdOrgId = {0} AND FIsPick = 'N' AND  FDocumentStatus = 'C' AND FCancelStatus = 'A' ", selInStockBillParam.PrdOrgId);
					if (selInStockBillParam.WorkShopId > 0L)
					{
						SelInStockBillParam expr_DE = selInStockBillParam;
						expr_DE.FilterString += string.Format(" AND FWorkShopId1 = {0} ", selInStockBillParam.WorkShopId);
					}
					e.Option.SetVariableValue("FilterString", selInStockBillParam.FilterString);
					e.Option.SetVariableValue("SelInStockBillParam", selInStockBillParam);
					base.View.Session["SelInStockBillParam"] = selInStockBillParam;
					return;
				}
				e.Cancel = true;
			}
		}

		public override void AfterDoOperation(AfterDoOperationEventArgs e)
		{
			base.AfterDoOperation(e);
			if (e.Operation.OperationId == FormOperation.Operation_Draw)
			{
				for (int i = base.View.Model.GetEntryRowCount("FEntity") - 1; i >= 0; i--)
				{
					DynamicObject dynamicObject = base.View.Model.GetValue("FMaterialId", i) as DynamicObject;
					long num = (dynamicObject == null) ? 0L : Convert.ToInt64(dynamicObject["Id"]);
					if (num == 0L)
					{
						base.View.Model.DeleteEntryRow("FEntity", i);
					}
				}
			}
		}

		public override void OnShowConvertOpForm(ShowConvertOpFormEventArgs e)
		{
			base.OnShowConvertOpForm(e);
			if (e.ConvertOperation == FormOperationEnum.Draw && e.Bills is List<ConvertBillElement>)
			{
				List<ConvertBillElement> list = e.Bills as List<ConvertBillElement>;
				list.Add(new ConvertBillElement
				{
					FormID = "SP_InStock",
					ConvertBillType = ConvertBillType.Bill,
					Name = new LocaleValue(ResManager.LoadKDString("简单生产入库单", "004023030004288", SubSystemType.SCM, new object[0]), base.Context.UserLocale.LCID)
				});
				list.Add(new ConvertBillElement
				{
					FormID = "ENG_PRODUCTSTRUCTURE",
					ConvertBillType = ConvertBillType.Bill,
					Name = new LocaleValue(ResManager.LoadKDString("物料清单", "004023030004291", SubSystemType.SCM, new object[0]), base.Context.UserLocale.LCID)
				});
				e.Bills = list;
				return;
			}
			FormOperationEnum arg_E1_0 = e.ConvertOperation;
		}

		public override void OnShowTrackResult(ShowTrackResultEventArgs e)
		{
			base.OnShowTrackResult(e);
			FormOperationEnum arg_0D_0 = e.TrackOperation;
		}

		private BillNode GetSPInstockTrackResult(BillNode trackResult)
		{
			if (this.Model.DataObject == null)
			{
				return trackResult;
			}
			DynamicObjectCollection source = this.Model.DataObject["Entity"] as DynamicObjectCollection;
			List<long> ids = (from p in source
							  select Convert.ToInt64(p["Id"])).ToList<long>();
			List<string> pickRelateInstockEntryIds = SpPickMtrlServiceHelper.GetPickRelateInstockEntryIds(base.View.Context, ids, true, true);
			trackResult = BillNode.Create("SP_InStock", "", null);
			trackResult.LinkEntry = "FEntity";
			trackResult.TrackUpDownLinkEntry = "FEntity";
			trackResult.AddLinkCopyData(pickRelateInstockEntryIds);
			return trackResult;
		}

		public override void OnGetConvertRule(GetConvertRuleEventArgs e)
		{
			base.OnGetConvertRule(e);
			if (e.ConvertOperation == FormOperationEnum.Draw && (e.SourceFormId == "ENG_PRODUCTSTRUCTURE" || e.SourceFormId == "SP_InStock"))
			{
				ConvertRuleElement convertRuleElement = ConvertServiceHelper.GetConvertRules(base.Context, "ENG_BomExpandBill", e.TargetFormId).FirstOrDefault<ConvertRuleElement>();
				if (convertRuleElement != null && e.SourceFormId == "ENG_PRODUCTSTRUCTURE")
				{
					DynamicFormShowParameter dynamicFormShowParameter = new DynamicFormShowParameter();
					dynamicFormShowParameter.FormId = e.SourceFormId;
					dynamicFormShowParameter.OpenStyle.ShowType = ShowType.NonModal;
					dynamicFormShowParameter.CustomParams["ShowMode"] = 3.ToString();
					dynamicFormShowParameter.ParentPageId = base.View.PageId;
					e.DynamicFormShowParameter = dynamicFormShowParameter;
				}
				this.SetParentOwnerFieldMap(convertRuleElement, e.SourceFormId);
				e.Rule = convertRuleElement;
			}
		}

		public override void BeforeSave(BeforeSaveEventArgs e)
		{
			base.BeforeSave(e);
			this._entityIdsInStockBeforeSave = SpPickMtrlServiceHelper.GetSpPickMtrlEntryIds(base.View.Context, this.Model.DataObject.GetDynamicObjectItemValue("Id", 0L));
			if (!this.ClearZeroRow())
			{
				e.Cancel = true;
			}
		}

		public override void AfterSave(AfterSaveEventArgs e)
		{
			if (this._entityIdsInStockBeforeSave != null && this._entityIdsInStockBeforeSave.Count<long>() > 0)
			{
				List<long> entityIdsInStockAfterSave = (from w in base.View.Model.DataObject.GetDynamicObjectItemValue<DynamicObjectCollection>("Entity")
														where w.GetDynamicObjectItemValue<string>("SrcBillType") == "SP_InStock" && w.GetDynamicObjectItemValue("SrcEnteryId", 0L) > 0L
														select w.GetDynamicObjectItemValue("SrcEnteryId", 0L)).Distinct<long>().ToList<long>();
				List<long> list = (from w in this._entityIdsInStockBeforeSave
								   where !entityIdsInStockAfterSave.Contains(w)
								   select w).ToList<long>();
				if (list.Count<long>() > 0)
				{
					SpInStockServiceHelper.ResetIsPickInInStcokEntry(base.View.Context, list);
				}
			}
			base.AfterSave(e);
		}

		public override void AfterCreateNewEntryRow(CreateNewEntryEventArgs e)
		{
			if (e.Entity.Key.EqualsIgnoreCase("FEntity"))
			{
				this.SetDefKeeperTypeAndKeeperValue(e.Row);
			}
		}

		public override void DataChanged(DataChangedEventArgs e)
		{
			base.DataChanged(e);
			string key;
			if ((key = e.Field.Key) != null)
			{
				if (key == "FOwnerId0")
				{
					if (Convert.ToString(base.View.Model.GetValue("FOwnerTypeId0", 0)).EqualsIgnoreCase("BD_OwnerOrg"))
					{
						SCMCommon.SetDefLocalCurrency(this, "FOwnerId0", "FCurrId");
					}
					string keeperTypeAndKeeper = Convert.ToString(e.NewValue);
					this.SetKeeperTypeAndKeeper(keeperTypeAndKeeper);
					return;
				}
				if (key == "FMaterialId")
				{
					long userOrgId = 0L;
					DynamicObject dynamicObject = base.View.Model.GetValue("FStockOrgId") as DynamicObject;
					if (dynamicObject != null)
					{
						userOrgId = Convert.ToInt64(dynamicObject["Id"]);
					}
					DynamicObject materialObj = base.View.Model.GetValue("FMaterialId", e.Row) as DynamicObject;
					base.View.Model.SetValue("FBomId", SCMCommon.GetBomDefaultValueByMaterial(base.Context, materialObj, 0L, false, userOrgId, false), e.Row);
					this.SetDefOwnerAndKeeperValue(e.Row);
					return;
				}
				if (key == "FKeeperTypeId")
				{
					string newKeeperTypeId = Convert.ToString(e.NewValue);
					this.SetKeeperValue(newKeeperTypeId, e.Row);
					return;
				}
				if (!(key == "FAuxPropId"))
				{
					return;
				}
				DynamicObject newAuxpropData = e.OldValue as DynamicObject;
				this.AuxpropDataChanged(newAuxpropData, e.Row);
			}
		}

		public override void CustomEvents(CustomEventsArgs e)
		{
			base.CustomEvents(e);
			IDynamicFormView view = base.View.GetView(e.Key);
			if (view != null && view.BusinessInfo.GetForm().Id == "ENG_PRODUCTSTRUCTURE" && e.EventName == "CustomSelBill")
			{
				//SelBill0ption formSession = Common.GetFormSession<SelBill0ption>(base.View, "returnData", true);
				//this.DoSelBills(formSession);
			}
		}

		public override void BeforeBindData(EventArgs e)
		{
			base.BeforeBindData(e);
			this.LockOrgAndOwner();
			this.LockKPTypeAndKPAfterSave();
		}

		public override void AfterCreateModelData(EventArgs e)
		{
			if (base.View.OpenParameter.Status == OperationStatus.ADDNEW && base.View.OpenParameter.CreateFrom != CreateFrom.Push)
			{
				this.SetBusinessTypeByBillType();
			}
		}

		public override void AfterBindData(EventArgs e)
		{
			if (Convert.ToString(base.View.Model.GetValue("FOwnerTypeId0", 0)).EqualsIgnoreCase("BD_OwnerOrg"))
			{
				SCMCommon.SetDefLocalCurrency(this, "FOwnerId0", "FCurrId");
			}
			FormMetadata formMetadata = MetaDataServiceHelper.Load(base.Context, "SP_PickMtrl", true) as FormMetadata;
			if (formMetadata == null)
			{
				return;
			}
			string id = "SP_PickMtrlUserParameter";
			if (!string.IsNullOrWhiteSpace(formMetadata.BusinessInfo.GetForm().ParameterObjectId))
			{
				id = formMetadata.BusinessInfo.GetForm().ParameterObjectId;
			}
			FormMetadata formMetadata2 = MetaDataServiceHelper.Load(base.Context, id, true) as FormMetadata;
			DynamicObject dynamicObject = UserParamterServiceHelper.Load(base.Context, formMetadata2.BusinessInfo, base.Context.UserId, "SP_PickMtrl", "UserParameter");
			bool dynamicObjectItemValue = dynamicObject.GetDynamicObjectItemValue("IsSetPicker", false);
			if (dynamicObjectItemValue)
			{
				this.SetPickerId();
				return;
			}
			this.SetStockerId();
		}

		public override void BeforeF7Select(BeforeF7SelectEventArgs e)
		{
			base.BeforeF7Select(e);
			string text = e.ListFilterParameter.Filter;
			bool f7AndSetNumberEvent = this.GetF7AndSetNumberEvent(e.FieldKey, e.Row, out text);
			if (f7AndSetNumberEvent)
			{
				e.Cancel = true;
			}
			else if (!string.IsNullOrWhiteSpace(text))
			{
				//e.ListFilterParameter.Filter = Common.SqlAppendAnd(e.ListFilterParameter.Filter, text);
			}
			if (e.FieldKey.EqualsIgnoreCase("FLot"))
			{
				text = Common.GetLotF8InvFilter(this, new LotF8InvFilterArgBD
				{
					MaterialFieldKey = "FMaterialId",
					StockOrgFieldKey = "FStockOrgId",
					OwnerTypeFieldKey = "FOwnerTypeId",
					OwnerFieldKey = "FOwnerId",
					KeeperTypeFieldKey = "FKeeperTypeId",
					KeeperFieldKey = "FKeeperId",
					AuxpropFieldKey = "FAuxPropId",
					BomFieldKey = "FBomId",
					StockFieldKey = "FStockId",
					StockLocFieldKey = "FStockLocId",
					StockStatusFieldKey = "FStockStatusId",
					MtoFieldKey = "FMtoNo"
				}, e.Row);
				if (!string.IsNullOrWhiteSpace(text))
				{
					if (string.IsNullOrEmpty(e.ListFilterParameter.Filter))
					{
						e.ListFilterParameter.Filter = text;
						return;
					}
					IRegularFilterParameter expr_132 = e.ListFilterParameter;
					expr_132.Filter = expr_132.Filter + " AND " + text;
				}
			}
		}

		public override void AuthPermissionBeforeF7Select(AuthPermissionBeforeF7SelectEventArgs e)
		{
			base.AuthPermissionBeforeF7Select(e);
			string fieldKey;
			if ((fieldKey = e.FieldKey) != null)
			{
				if (!(fieldKey == "FBomId"))
				{
					return;
				}
				e.IsIsolationOrg = false;
			}
		}

		public override void BeforeSetItemValueByNumber(BeforeSetItemValueByNumberArgs e)
		{
			base.BeforeSetItemValueByNumber(e);
			string filter = e.Filter;
			this.GetF7AndSetNumberEvent(e.BaseDataFieldKey, e.Row, out filter);
			if (!string.IsNullOrWhiteSpace(filter))
			{
				//e.Filter = Common.SqlAppendAnd(e.Filter, filter);
			}
		}

		private void SetStockerId()
		{
			if (base.View.OpenParameter.Status == OperationStatus.ADDNEW)
			{
				long num = base.View.Model.DataObject.GetDynamicObjectItemValue("StockerId_Id", 0L);
				if (num <= 0L)
				{
					long dynamicObjectItemValue = base.View.Model.DataObject.GetDynamicObjectItemValue("StockOrgId_Id", 0L);
					num = StaffServiceHelper.GetUserOperatorId(base.Context, base.Context.UserId, dynamicObjectItemValue, "WHY");
					base.View.Model.SetValue("FStockerId", num);
				}
			}
		}

		private void SetPickerId()
		{
			if (base.View.OpenParameter.Status == OperationStatus.ADDNEW)
			{
				List<DynamicObject> userLinkInfo = SpPickMtrlServiceHelper.GetUserLinkInfo(base.Context, base.Context.UserId);
				if (!userLinkInfo.IsEmpty<DynamicObject>())
				{
					long dynamicObjectItemValue = userLinkInfo.FirstOrDefault<DynamicObject>().GetDynamicObjectItemValue("Fid", 0L);
					this.Model.SetValue("FPickerId", dynamicObjectItemValue);
				}
			}
		}

		private bool GetF7AndSetNumberEvent(string fieldKey, int eRow, out string filter)
		{
			bool flag = false;
			filter = "";
			switch (fieldKey)
			{
				case "FPrdOrgId":
					{
						long value = this.Model.GetValue("FStockOrgId", -1, 0L, null);
						if (value <= 0L)
						{
							flag = true;
							base.View.ShowErrMessage(ResManager.LoadKDString("请先录入发料组织的内容！", "004023030004294", SubSystemType.SCM, new object[0]), "", MessageBoxType.Notice);
						}
						break;
					}
				case "FStockStatusId":
					//flag = Common.GetStockStatusFilterStr(this, eRow, "FStockId", out filter);
					break;
				case "FStockerId":
					{
						DynamicObject dynamicObject = base.View.Model.GetValue("FStockerGroupId") as DynamicObject;
						filter += " FIsUse='1' ";
						long num2 = (dynamicObject == null) ? 0L : Convert.ToInt64(dynamicObject["Id"]);
						if (num2 != 0L)
						{
							filter = filter + "And FOPERATORGROUPID = " + num2.ToString();
						}
						break;
					}
				case "FStockerGroupId":
					{
						DynamicObject dynamicObject2 = base.View.Model.GetValue("FStockerId") as DynamicObject;
						filter += " FIsUse='1' ";
						if (dynamicObject2 != null && Convert.ToInt64(dynamicObject2["Id"]) > 0L)
						{
							filter += string.Format("And FENTRYID IN (SELECT tod.FOPERATORGROUPID FROM T_BD_OPERATORENTRY toe\r\n                                                INNER JOIN T_BD_OPERATORDETAILS tod ON tod.FENTRYID = toe.FENTRYID\r\n                                                WHERE toe.FENTRYID = {0})", Convert.ToInt64(dynamicObject2["Id"]));
						}
						break;
					}
				case "FExtAuxUnitId":
					filter = SCMCommon.GetAuxUnitFilter(this, "FMaterialId", "FBaseUnitId", "FSecUnitId", eRow);
					break;
				case "FStockOrgId":
					filter = " EXISTS (SELECT 1 FROM T_BAS_SYSTEMPROFILE T2 WHERE T2.FORGID = FORGID AND T2.FCATEGORY='STK' AND T2.FKEY='STARTSTOCKDATE' )";
					break;
				case "FOwnerId0":
					{
						string str = base.View.Model.GetValue("FBizType") as string;
						if (str.EqualsIgnoreCase("VMI"))
						{
							filter = " FVmiBusiness = '1' ";
						}
						else
						{
							filter = SCMCommon.GetOwnerFilterByRelation(this, new GetOwnerFilterArgs("FOwnerTypeId0", eRow, "FPrdOrgId", eRow, "102", "1"));
						}
						break;
					}
				case "FOwnerId":
					{
						string str2 = base.View.Model.GetValue("FBizType") as string;
						if (str2.EqualsIgnoreCase("VMI"))
						{
							filter = " FVmiBusiness = '1' ";
						}
						else
						{
							filter = SCMCommon.GetOwnerFilterByRelation(this, new GetOwnerFilterArgs("FOwnerTypeId", eRow, "FPrdOrgId", eRow, "102", "1"));
						}
						break;
					}
				case "FPRODUCTGROUPID":
					{
						DynamicObject dynamicObject3 = base.View.Model.GetValue("FPrdOrgId") as DynamicObject;
						int orgId = (dynamicObject3 == null) ? 0 : Convert.ToInt32(dynamicObject3["Id"]);
						//Common.GetProductGroupFieldFilter(orgId, out filter);
						break;
					}
				case "FMaterialId":
					{
						string str3 = base.View.Model.GetValue("FBizType") as string;
						if (str3.EqualsIgnoreCase("VMI"))
						{
							filter = " FIsVmiBusiness = '1' ";
						}
						break;
					}
			}
			if (flag)
			{
				filter = " 1 = 0 ";
			}
			return flag;
		}

		public override void BeforeFlexSelect(BeforeFlexSelectEventArgs e)
		{
			base.BeforeFlexSelect(e);
			if (e.FieldKey.EqualsIgnoreCase("FAuxPropId"))
			{
				DynamicObject dynamicObject = base.View.Model.GetValue("FAuxPropId", e.Row) as DynamicObject;
				this.lastAuxpropId = ((dynamicObject == null) ? 0L : Convert.ToInt64(dynamicObject["Id"]));
			}
		}

		public override void AfterShowFlexForm(AfterShowFlexFormEventArgs e)
		{
			base.AfterShowFlexForm(e);
			if (e.Result == AfterShowFlexFormEventArgs.FormResult.OK && e.FlexField.Key.EqualsIgnoreCase("FAuxPropId"))
			{
				this.AuxpropDataChanged(e.Row);
			}
		}

		public override void BarItemClick(BarItemClickEventArgs e)
		{
			base.BarItemClick(e);
			string barItemKey;
			if ((barItemKey = e.BarItemKey) != null)
			{
				if (!(barItemKey == "tbStockSplit"))
				{
					return;
				}
				this.SplitPickMtrl("StockId_Id");
			}
		}

		private void SplitPickMtrl(string splitKey)
		{
			if (base.View.Model.DataChanged)
			{
				base.View.ShowMessage(ResManager.LoadKDString("界面有变动,请先保存单据", "004023000023424", SubSystemType.SCM, new object[0]), MessageBoxType.Notice);
				return;
			}
			DynamicObject dataObject = base.View.Model.DataObject;
			string[] splitKeys = splitKey.Split(new string[]
			{
				"|"
			}, StringSplitOptions.RemoveEmptyEntries);
			DynamicObjectCollection dynamicObjectItemValue = base.View.Model.DataObject.GetDynamicObjectItemValue<DynamicObjectCollection>("Entity", null);
			Dictionary<long, IGrouping<long, DynamicObject>> dictionary = new Dictionary<long, IGrouping<long, DynamicObject>>();
			List<DynamicObject> list = new List<DynamicObject>();
			List<DynamicObject> list2 = new List<DynamicObject>();
			if (splitKeys.Length <= 1)
			{
				dictionary = (from w in dynamicObjectItemValue
							  where w.GetDynamicObjectItemValue(splitKeys[0], 0L) != 0L
							  select w into g
							  group g by g.GetDynamicObjectItemValue(splitKeys[0], 0L)).ToDictionary((IGrouping<long, DynamicObject> d) => d.Key);
			}
			if (dynamicObjectItemValue.IsEmpty<DynamicObject>())
			{
				base.View.ShowMessage(ResManager.LoadKDString("简单生产领料单明细表体为空或仓库全为空，无需分仓领料", "004023000019677", SubSystemType.SCM, new object[0]), MessageBoxType.Notice);
				return;
			}
			if (dictionary.Keys.Count<long>() == 1)
			{
				base.View.ShowMessage(ResManager.LoadKDString("简单生产领料单明细表体不存在仓库不一致的分录，无需分仓领料", "004023000019678", SubSystemType.SCM, new object[0]), MessageBoxType.Notice);
				return;
			}
			int num = 0;
			foreach (KeyValuePair<long, IGrouping<long, DynamicObject>> current in dictionary)
			{
				num++;
				if (num == 1)
				{
					int num2 = 1;
					using (IEnumerator<DynamicObject> enumerator2 = current.Value.GetEnumerator())
					{
						while (enumerator2.MoveNext())
						{
							DynamicObject current2 = enumerator2.Current;
							current2.SetDynamicObjectItemValue("Seq", num2++);
						}
						continue;
					}
				}
				DynamicObject dynamicObject = dataObject.Clone(false, true) as DynamicObject;
				DynamicObjectCollection dynamicObjectItemValue2 = dynamicObject.GetDynamicObjectItemValue<DynamicObjectCollection>("Entity", null);
				dynamicObjectItemValue2.Clear();
				int num3 = 1;
				foreach (DynamicObject current3 in current.Value)
				{
					DynamicObject dynamicObject2 = current3.Clone(false, true) as DynamicObject;
					long dynamicObjectItemValue3 = current3.GetDynamicObjectItemValue("Id", 0L);
					dynamicObject2.SetDynamicObjectItemValue("Seq", num3);
					dynamicObject2.SetDynamicObjectItemValue("SrcEnteryId", dynamicObjectItemValue3);
					dynamicObjectItemValue2.Add(dynamicObject2);
					list2.Add(current3);
					num3++;
				}
				dynamicObject.SetDynamicObjectItemValue("BillNo", string.Empty);
				dynamicObject.SetDynamicObjectItemValue("DocumentStatus", "Z");
				list.Add(dynamicObject);
			}
			OperateOption operateOption = OperateOption.Create();
			operateOption.SetVariableValue("IsOverPickValidator", false);
			IOperationResult operationResult = BusinessDataServiceHelper.Save(base.Context, base.View.BusinessInfo, list.ToArray(), operateOption, "");
			if (!operationResult.SuccessDataEnity.IsEmpty<DynamicObject>())
			{
				this.ShowResult(operationResult.SuccessDataEnity.ToList<DynamicObject>(), "SP_PickMtrl", dynamicObjectItemValue, list2);
			}
		}

		private void ShowResult(List<DynamicObject> objs, string targetFormId, DynamicObjectCollection pickEntryDatas, List<DynamicObject> removeEntryDatas)
		{
			BillShowParameter billShowParameter = new BillShowParameter();
			billShowParameter.ParentPageId = base.View.PageId;
			if (objs.Count == 1)
			{
				billShowParameter.Status = OperationStatus.EDIT;
				string key = "_ConvertSessionKey";
				string text = "ConverOneResult";
				billShowParameter.CustomParams.Add(key, text);
				base.View.Session[text] = objs[0];
				billShowParameter.FormId = targetFormId;
				billShowParameter.PKey = Convert.ToString(objs[0].GetDynamicObjectItemValue("Id", 0L));
			}
			else
			{
				if (objs.Count <= 1)
				{
					return;
				}
				billShowParameter.FormId = "BOS_ConvertResultForm";
				string key2 = "ConvertResults";
				base.View.Session[key2] = objs.ToArray();
				billShowParameter.CustomParams.Add("_ConvertResultFormId", targetFormId);
			}
			if (base.View.Context.UserToken.ToLowerInvariant().Equals("bosidetest"))
			{
				billShowParameter.OpenStyle.ShowType = ShowType.Default;
			}
			else
			{
				billShowParameter.OpenStyle.ShowType = ShowType.MainNewTabPage;
			}
			base.View.ShowForm(billShowParameter);
			IEnumerable<DynamicObject> source = from data in objs
												from entrydata in data.GetDynamicObjectItemValue<DynamicObjectCollection>("Entity", null)
												select entrydata;
			List<long> list = (from s in source
							   select s.GetDynamicObjectItemValue("SrcEnteryId", 0L)).ToList<long>();
			if (list.IsEmpty<long>())
			{
				return;
			}
			new List<long>();
			foreach (DynamicObject current in removeEntryDatas)
			{
				long dynamicObjectItemValue = current.GetDynamicObjectItemValue("Id", 0L);
				if (list.Contains(dynamicObjectItemValue))
				{
					pickEntryDatas.Remove(current);
				}
			}
			OperateOption operateOption = OperateOption.Create();
			operateOption.SetVariableValue("IsOverPickValidator", false);
			BusinessDataServiceHelper.Save(base.Context, base.View.Model.BusinessInfo, base.View.Model.DataObject, operateOption, "");
			base.View.UpdateView();
		}

		private bool GetBOMFilter(int row, out string filter)
		{
			filter = "";
			DynamicObject dynamicObject = base.View.Model.GetValue("FMaterialId", row) as DynamicObject;
			if (dynamicObject == null)
			{
				return false;
			}
			long lMaterialMasterId = Convert.ToInt64(dynamicObject["msterID"]);
			long value = base.View.Model.GetValue("FStockOrgId", -1, 0L, null);
			DynamicObject dynamicObject2 = base.View.Model.GetValue("FAuxPropId", row) as DynamicObject;
			long auxpropid = (dynamicObject2 == null) ? 0L : Convert.ToInt64(dynamicObject2["Id"]);
			List<long> approvedBomIdByOrgId = MFGServiceHelperForSCM.GetApprovedBomIdByOrgId(base.View.Context, lMaterialMasterId, value, auxpropid);
			if (!approvedBomIdByOrgId.IsEmpty<long>())
			{
				filter = string.Format(" FID IN ({0}) ", string.Join<long>(",", approvedBomIdByOrgId));
			}
			else
			{
				filter = string.Format(" FID={0}", 0);
			}
			return !string.IsNullOrWhiteSpace(filter);
		}

		private void AuxpropDataChanged(int row)
		{
			DynamicObject dynamicObject = base.View.Model.GetValue("FAuxPropId", row) as DynamicObject;
			long num = (dynamicObject == null) ? 0L : Convert.ToInt64(dynamicObject["Id"]);
			if (num == this.lastAuxpropId)
			{
				return;
			}
			DynamicObject materialObj = base.View.Model.GetValue("FMaterialId", row) as DynamicObject;
			long value = base.View.Model.GetValue("FBOMId", row, 0L, null);
			long value2 = base.View.Model.GetValue("FStockOrgId", -1, 0L, null);
			long bomDefaultValueByMaterial = SCMCommon.GetBomDefaultValueByMaterial(base.Context, materialObj, num, false, value2, false);
			if (bomDefaultValueByMaterial != value)
			{
				base.View.Model.SetValue("FBOMId", bomDefaultValueByMaterial, row);
			}
			this.lastAuxpropId = num;
			base.View.UpdateView("FEntity", row);
		}

		private void AuxpropDataChanged(DynamicObject newAuxpropData, int row)
		{
			DynamicObject materialObj = base.View.Model.GetValue("FMaterialId", row) as DynamicObject;
			long value = base.View.Model.GetValue("FBOMId", row, 0L, null);
			long value2 = base.View.Model.GetValue("FStockOrgId", -1, 0L, null);
			long bomDefaultValueByMaterialExceptApi = SCMCommon.GetBomDefaultValueByMaterialExceptApi(base.View, materialObj, newAuxpropData, false, value2, value, false);
			if (bomDefaultValueByMaterialExceptApi != value)
			{
				base.View.Model.SetValue("FBOMId", bomDefaultValueByMaterialExceptApi, row);
			}
		}

		private bool ClearZeroRow()
		{
			DynamicObject parameterData = this.Model.ParameterData;
			if (parameterData != null && Convert.ToBoolean(parameterData["IsClearZeroRow"]))
			{
				Entity entity = this.Model.BillBusinessInfo.GetEntity("FEntity");
				List<DynamicObject> list = (from x in this.Model.GetEntityDataObject(entity)
											where Convert.ToDecimal(x["ActualQty"]) == 0m
											select x).ToList<DynamicObject>();
				foreach (DynamicObject current in list)
				{
					this.Model.DeleteEntryRow("FEntity", Convert.ToInt32(current["Seq"]) - 1);
				}
				if (this.Model.GetEntryRowCount("FEntity") == 0)
				{
					base.View.ShowErrMessage("", ResManager.LoadKDString("分录“明细”是必填项。", "004023000021872", SubSystemType.SCM, new object[0]), MessageBoxType.Notice);
					return false;
				}
				base.View.UpdateView("FEntity");
			}
			return true;
		}

		private void DoSelBills(SelBill0ption selBillOPtion)
		{
			IEnumerable<DynamicObject> listSelRows = selBillOPtion.ListSelRows;
			if (listSelRows == null || listSelRows.Count<DynamicObject>() <= 0)
			{
				return;
			}
			int i = 0;
			ListSelectedRow[] source = (from p in listSelRows
										select new ListSelectedRow("0", p.GetDynamicObjectItemValue("Id", 0L).ToString(), i++, "ENG_BomExpandBill")
										{
											EntryEntityKey = "FBomResult"
										}).ToArray<ListSelectedRow>();
			ConvertRuleElement convertRuleElement = null;
			if (selBillOPtion.FormId == "SP_InStock")
			{
				this.SetParentOwnerFieldMap(convertRuleElement, selBillOPtion.FormId);
			}
			Dictionary<string, object> dictionary = new Dictionary<string, object>();
			dictionary.Add("SelInStockBillParam", new SelInStockBillParam
			{
				StockOrgId = this.Model.GetValue("FStockOrgId", -1, 0L, null)
			});
			ConvertOperationResult convertOperationResult = ConvertServiceHelper.Draw(base.View.Context, new DrawArgs(convertRuleElement, base.View.Model.DataObject, source.ToArray<ListSelectedRow>())
			{
				CustomParams = dictionary
			}, null);
			if (!convertOperationResult.ValidationErrors.IsEmpty<ValidationErrorInfo>())
			{
				StringBuilder stringBuilder = new StringBuilder();
				foreach (ValidationErrorInfo current in convertOperationResult.ValidationErrors)
				{
					if (!string.IsNullOrWhiteSpace(current.Message))
					{
						stringBuilder.AppendLine(current.Message);
					}
				}
				if (!stringBuilder.IsNullOrEmptyOrWhiteSpace())
				{
					base.View.ShowNotificationMessage(stringBuilder.ToString(), string.Empty, MessageBoxType.Advise);
				}
			}
			base.View.UpdateView("FEntity");
			this.Model.DataChanged = true;
		}

		private void SetParentOwnerFieldMap(ConvertRuleElement bom2PickRule, string sFormid)
		{
			if (bom2PickRule != null)
			{
				string sourceFieldKey = this.GetConLossRate() ? "FBaseQty" : "FBaseActualQty";
				ConvertFilterPolicyElement convertFilterPolicyElement = (from p in bom2PickRule.Policies
																		 where p is ConvertFilterPolicyElement
																		 select p as ConvertFilterPolicyElement).FirstOrDefault<ConvertFilterPolicyElement>();
				convertFilterPolicyElement.AlertMessage = new LocaleValue(ResManager.LoadKDString("1.用户需有入库物料BOM上发料组织下简单生产领料单的新增权限。\r\n2.简单生产入库单领料标识应该为“否”。", "004023030006275", SubSystemType.SCM, new object[0]), base.Context.LogLocale.LCID);
				List<DefaultConvertPolicyElement> source = (from w in bom2PickRule.Policies
															where w is DefaultConvertPolicyElement
															select w as DefaultConvertPolicyElement).ToList<DefaultConvertPolicyElement>();
				if (source.Count<DefaultConvertPolicyElement>() >= 1)
				{
					DefaultConvertPolicyElement defaultConvertPolicyElement = source.First<DefaultConvertPolicyElement>();
					bool flag = false;
					bool flag2 = false;
					bool flag3 = false;
					foreach (FieldMapElement current in defaultConvertPolicyElement.FieldMaps)
					{
						if (current.TargetFieldKey == "FBaseActualQty")
						{
							flag = true;
							current.SourceFieldKey = sourceFieldKey;
						}
						else if (current.TargetFieldKey == "FBaseAppQty")
						{
							flag2 = true;
							current.SourceFieldKey = sourceFieldKey;
						}
						else if (current.TargetFieldKey == "FWorkShopId" && sFormid == "SP_InStock")
						{
							flag3 = true;
							current.SourceFieldKey = "fworkshopid_reg";
						}
						if ((flag & flag2 & !sFormid.Equals("SP_InStock")) || (sFormid.Equals("SP_InStock") & flag & flag2 & flag3))
						{
							break;
						}
					}
				}
			}
		}

		private bool GetConLossRate()
		{
			bool result = false;
			string id = "SP_PickMtrlUserParameter";
			if (!string.IsNullOrWhiteSpace(base.View.BusinessInfo.GetForm().ParameterObjectId))
			{
				id = base.View.BusinessInfo.GetForm().ParameterObjectId;
			}
			FormMetadata formMetadata = MetaDataServiceHelper.Load(base.Context, id, true) as FormMetadata;
			if (formMetadata == null)
			{
				return result;
			}
			DynamicObject dynamicObject = UserParamterServiceHelper.Load(base.Context, formMetadata.BusinessInfo, base.Context.UserId, base.View.BusinessInfo.GetForm().Id, "UserParameter");
			if (dynamicObject != null || dynamicObject.DynamicObjectType.Properties.ContainsKey("ConLossRate"))
			{
				result = Convert.ToBoolean(dynamicObject["ConLossRate"]);
			}
			return result;
		}

		private bool ValidatePush(SelBomBillParam billParam)
		{
			List<string> list = new List<string>();
			if (billParam.StockOrgId <= 0L)
			{
				list.Add(ResManager.LoadKDString("发料组织", "004023030004297", SubSystemType.SCM, new object[0]));
			}
			if (billParam.PrdOrgId <= 0L)
			{
				list.Add(ResManager.LoadKDString("生产组织", "004023030004300", SubSystemType.SCM, new object[0]));
			}
			if (string.IsNullOrWhiteSpace(billParam.OwnerType))
			{
				list.Add(ResManager.LoadKDString("货主类型", "004023030004306", SubSystemType.SCM, new object[0]));
			}
			if (!string.IsNullOrWhiteSpace(billParam.OwnerType) && billParam.OwnerType.EqualsIgnoreCase("BD_OwnerOrg") && billParam.OwnerId <= 0L)
			{
				list.Add(ResManager.LoadKDString("货主", "004023030004309", SubSystemType.SCM, new object[0]));
			}
			if (list.Count > 0)
			{
				base.View.ShowMessage(string.Format(ResManager.LoadKDString("【{0}】 字段为选单必录项！", "004023030004312", SubSystemType.SCM, new object[0]), string.Join(ResManager.LoadKDString("】,【", "004023030004315", SubSystemType.SCM, new object[0]), list)), MessageBoxType.Notice);
				return false;
			}
			return true;
		}

		private void LockOrgAndOwner()
		{
			bool flag = true;
			DynamicObjectCollection dynamicObjectCollection = (DynamicObjectCollection)this.Model.DataObject["Entity"];
			if (dynamicObjectCollection != null && dynamicObjectCollection.Count<DynamicObject>() > 0)
			{
				if ((from w in dynamicObjectCollection
					 where w.GetDynamicObjectItemValue("SrcEnteryId", 0) > 0
					 select w).Count<DynamicObject>() > 0)
				{
					flag = false;
				}
			}
			base.View.LockField("FOwnerTypeId0", flag, -1);
			if (Convert.ToString(this.Model.GetValue("FOwnerTypeId0")).EqualsIgnoreCase("BD_OwnerOrg"))
			{
				base.View.LockField("FOwnerId0", flag, -1);
			}
			base.View.LockField("FStockOrgId", flag, -1);
			base.View.LockField("FPrdOrgId", flag, -1);
			if (!flag)
			{
				if ((from w in dynamicObjectCollection
					 where w.GetDynamicObjectItemValue<string>("SrcBillType", null) == "SP_InStock"
					 select w).Count<DynamicObject>() <= 0)
				{
					flag = true;
				}
			}
			base.View.LockField("FWorkShopId", flag, -1);
		}

		private void LockKPTypeAndKPAfterSave()
		{
			object value = base.View.Model.GetValue("FOwnerTypeId0");
			string a = "";
			if (value != null)
			{
				a = Convert.ToString(value);
			}
			DynamicObject dynamicObject = base.View.Model.GetValue("FStockOrgId") as DynamicObject;
			long num = (dynamicObject == null) ? 0L : Convert.ToInt64(dynamicObject["Id"]);
			int entryRowCount = base.View.Model.GetEntryRowCount("FEntity");
			for (int i = 0; i < entryRowCount; i++)
			{
				DynamicObject dynamicObject2 = base.View.Model.GetValue("FOwnerId", i) as DynamicObject;
				long num2 = (dynamicObject2 == null) ? 0L : Convert.ToInt64(dynamicObject2["Id"]);
				if (num2 == num && a == "BD_OwnerOrg")
				{
					base.View.GetFieldEditor("FKeeperTypeId", i).Enabled = true;
					base.View.GetFieldEditor("FKeeperId", i).Enabled = true;
				}
				else
				{
					base.View.GetFieldEditor("FKeeperTypeId", i).Enabled = false;
					base.View.GetFieldEditor("FKeeperId", i).Enabled = false;
				}
			}
		}

		private void SetDefOwnerAndKeeperValue(int row = -1)
		{
			DynamicObject dynamicObject = base.View.Model.GetValue("FStockOrgId") as DynamicObject;
			long num = (dynamicObject == null) ? 0L : Convert.ToInt64(dynamicObject["Id"]);
			DynamicObject dynamicObject2 = base.View.Model.GetValue("FPrdOrgId") as DynamicObject;
			long num2 = (dynamicObject2 == null) ? 0L : Convert.ToInt64(dynamicObject2["Id"]);
			int num3 = row;
			int num4 = row;
			if (row == -1)
			{
				num3 = 0;
				num4 = base.View.Model.GetEntryRowCount("FEntity") - 1;
			}
			for (int i = num3; i <= num4; i++)
			{
				object value = this.Model.GetValue("FOwnerTypeId", i);
				DynamicObject dynamicObject3 = this.Model.GetValue("FMaterialId", i) as DynamicObject;
				if (value != null)
				{
					string text = value.ToString();
					this.Model.SetItemValueByNumber("FOwnerId", "", i);
					if (!string.IsNullOrWhiteSpace(text) && text.EqualsIgnoreCase("BD_OwnerOrg") && num2 > 0L)
					{
						if (dynamicObject3 != null && Convert.ToInt64(dynamicObject3["Id"]) != 0L)
						{
							this.Model.SetValue("FOwnerId", num2.ToString(), i);
						}
						base.View.GetFieldEditor("FOwnerId", row).Enabled = true;
					}
				}
				value = this.Model.GetValue("FKeeperTypeId", i);
				if (value != null)
				{
					string text = value.ToString();
					this.Model.SetItemValueByNumber("FKeeperId", "", i);
					if (!string.IsNullOrWhiteSpace(text) && text.EqualsIgnoreCase("BD_KeeperOrg") && num > 0L)
					{
						this.Model.SetValue("FKeeperId", num.ToString(), i);
						base.View.GetFieldEditor("FKeeperId", row).Enabled = true;
					}
				}
			}
		}

		private void SetDefKeeperTypeAndKeeperValue(int row)
		{
			object value = base.View.Model.GetValue("FOwnerTypeId0");
			string a = "";
			if (value != null)
			{
				a = Convert.ToString(value);
			}
			DynamicObject dynamicObject = base.View.Model.GetValue("FOwnerId0") as DynamicObject;
			long num = (dynamicObject == null) ? 0L : Convert.ToInt64(dynamicObject["Id"]);
			DynamicObject dynamicObject2 = base.View.Model.GetValue("FStockOrgId") as DynamicObject;
			long num2 = (dynamicObject2 == null) ? 0L : Convert.ToInt64(dynamicObject2["Id"]);
			base.View.Model.SetValue("FOwnerTypeId", value, row);
			if (num == num2 && a == "BD_OwnerOrg")
			{
				base.View.Model.SetValue("FKeeperTypeId", "BD_KeeperOrg", row);
				base.View.Model.SetValue("FKeeperId", num2, row);
				base.View.GetFieldEditor("FKeeperTypeId", row).Enabled = true;
				base.View.GetFieldEditor("FKeeperId", row).Enabled = true;
				return;
			}
			base.View.GetFieldEditor("FKeeperTypeId", row).Enabled = false;
			base.View.GetFieldEditor("FKeeperId", row).Enabled = false;
		}

		private void SetKeeperTypeAndKeeper(string newOwerValue)
		{
			object value = base.View.Model.GetValue("FOwnerTypeId0");
			string a = "";
			if (value != null)
			{
				a = Convert.ToString(value);
			}
			DynamicObject dynamicObject = base.View.Model.GetValue("FStockOrgId") as DynamicObject;
			long value2 = (dynamicObject == null) ? 0L : Convert.ToInt64(dynamicObject["Id"]);
			string text = Convert.ToString(value2);
			int entryRowCount = base.View.Model.GetEntryRowCount("FEntity");
			if (newOwerValue == text && a == "BD_OwnerOrg")
			{
				for (int i = 0; i < entryRowCount; i++)
				{
					DynamicObject dynamicObject2 = base.View.Model.GetValue("FMaterialId", i) as DynamicObject;
					base.View.Model.SetValue("FOwnerTypeId", value, i);
					if (dynamicObject2 != null && Convert.ToInt64(dynamicObject2["Id"]) != 0L)
					{
						base.View.Model.SetValue("FOwnerId", newOwerValue, i);
					}
					base.View.GetFieldEditor("FKeeperTypeId", i).Enabled = true;
					base.View.GetFieldEditor("FKeeperId", i).Enabled = true;
				}
				return;
			}
			for (int j = 0; j < entryRowCount; j++)
			{
				base.View.Model.SetValue("FOwnerTypeId", value, j);
				DynamicObject dynamicObject2 = base.View.Model.GetValue("FMaterialId", j) as DynamicObject;
				if (a == "BD_OwnerOrg")
				{
					if (dynamicObject2 != null && Convert.ToInt64(dynamicObject2["Id"]) != 0L)
					{
						base.View.Model.SetValue("FOwnerId", newOwerValue, j);
					}
				}
				else if (!string.IsNullOrEmpty(newOwerValue) && !newOwerValue.Equals("0"))
				{
					DynamicObject dynamicObject3 = base.View.Model.GetValue("FOwnerId", j) as DynamicObject;
					long num = (dynamicObject3 == null) ? 0L : Convert.ToInt64(dynamicObject3["Id"]);
					if (num == 0L && base.View.GetControl("FOwnerId").Enabled && dynamicObject2 != null && Convert.ToInt64(dynamicObject2["Id"]) != 0L)
					{
						base.View.Model.SetValue("FOwnerId", newOwerValue, j);
					}
				}
				base.View.Model.SetValue("FKeeperTypeId", "BD_KeeperOrg", j);
				base.View.Model.SetValue("FKeeperId", text, j);
				base.View.GetFieldEditor("FKeeperTypeId", j).Enabled = false;
				base.View.GetFieldEditor("FKeeperId", j).Enabled = false;
			}
		}

		private void SetKeeperValue(string newKeeperTypeId, int row)
		{
			object value = base.View.Model.GetValue("FOwnerTypeId0");
			string a = "";
			if (value != null)
			{
				a = Convert.ToString(value);
			}
			DynamicObject dynamicObject = base.View.Model.GetValue("FOwnerId0") as DynamicObject;
			long num = (dynamicObject == null) ? 0L : Convert.ToInt64(dynamicObject["Id"]);
			DynamicObject dynamicObject2 = base.View.Model.GetValue("FStockOrgId") as DynamicObject;
			long num2 = (dynamicObject2 == null) ? 0L : Convert.ToInt64(dynamicObject2["Id"]);
			if (num == num2 && a == "BD_OwnerOrg")
			{
				base.View.GetFieldEditor("FKEEPERID", row).Enabled = true;
				return;
			}
			base.View.GetFieldEditor("FKEEPERID", row).Enabled = false;
		}

		private void SetBusinessTypeByBillType()
		{
			string baseDataStringValue = SCMCommon.GetBaseDataStringValue(this, "FBillType");
			DynamicObject dynamicObject = BusinessDataServiceHelper.LoadBillTypePara(base.Context, "SP_PickMtrlBillTypeParmSetting", baseDataStringValue, true);
			if (dynamicObject != null)
			{
				base.View.Model.SetValue("FBizType", dynamicObject["BusinessType"]);
			}
		}
	}
}
