using Kingdee.BOS;
using Kingdee.BOS.Core;
using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Core.Metadata;
using Kingdee.BOS.Core.Metadata.EntityElement;
using Kingdee.BOS.Core.Metadata.FieldElement;
using Kingdee.BOS.Core.SqlBuilder;
using Kingdee.BOS.JSON;
using Kingdee.BOS.Log;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.Orm.Metadata.DataEntity;
using Kingdee.BOS.Resource;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LQKJ.WebApi.Stub
{
    public class FlexService
    {
        private JSONObject _sourceData;

        private FormMetadata _metaData;
        private Context _ctx;
        private string _flexFormId;
		private List<DynamicObject> _lstItemInfo;
		long _orgId;

		public FlexService(Context ctx, String flexFormId, long orgId)
		{
			this._ctx = ctx;
			this._flexFormId = flexFormId;
			this._orgId = orgId;
		}

		public IOperationResult FlexSave(string data)
        {
            IOperationResult opeResult = new OperationResult();
            DateTime dtBegin = DateTime.Now;
            DateTime dtEnd = DateTime.Now;

            try
            {
                this._sourceData = JSONObject.Parse(Convert.ToString(data));
                this._metaData = FormMetaDataCache.GetCachedFormMetaData(this._ctx, this._flexFormId);


                List<DynamicObject> list = this.Save();
                foreach (DynamicObject dynamicObject in list)
                {
                    opeResult.IsSuccess = true;
                    OperateResult item = this.GenerateOprResult("", true, dynamicObject["Id"]);
                    opeResult.OperateResult.Add(item);
                }
                DateTime now3 = DateTime.Now;
            }
            catch (Exception ex)
            {
				Logger.Error("FlexService", "FlexSave", ex);
            }
			return opeResult;
        }

		/**
		 * 获取名称
		 */
		private string GetFormName()
		{
			var formName = "";
			if (this._flexFormId.ToUpper() == FormIdConst.BD_FLEXITEMDETAILV)
			{
				formName = "核算维度";
			}
			else if (this._flexFormId.ToUpper() == FormIdConst.BD_FLEXSITEMDETAILV)
			{
				formName = "辅助属性";
			}
			else if (this._flexFormId.ToUpper() == FormIdConst.BD_FLEXVALUESDETAIL)
			{
				formName = "辅助属性";
			}
			else if (this._flexFormId.ToUpper() == FormIdConst.HR_JS_FlexGradeItemDetail)
			{
				formName = "职等维度";
			}
			return formName;
		}

			private List<DynamicObject> Save()
		{
			this._lstItemInfo = FlexServiceHelper.GetFlexItemInfo(this._ctx, this._flexFormId);
			HeadEntity entity = this._metaData.BusinessInfo.GetEntity(0) as HeadEntity;
			DynamicObjectType dynamicObjectType = BusinessInfo.BuilderHeaderDataType(this._metaData.BusinessInfo.GetForm(), entity);
			
			JSONArray paramValue = this._sourceData.Get("Model") as JSONArray;
			List<DynamicObject> list = new List<DynamicObject>();
			int num = 0;
			StringBuilder stringBuilder = new StringBuilder();
			foreach (object obj in paramValue)
			{
				num++;
				DynamicObject dynamicObject = dynamicObjectType.CreateInstance() as DynamicObject;
				Dictionary<string, object> dictionary = obj as Dictionary<string, object>;
				using (Dictionary<string, object>.Enumerator enumerator2 = dictionary.GetEnumerator())
				{
					while (enumerator2.MoveNext())
					{
						KeyValuePair<string, object> item = enumerator2.Current;
						BusinessInfo businessInfo = this._metaData.BusinessInfo;
						KeyValuePair<string, object> item12 = item;
						Field field = businessInfo.GetField(item12.Key);
						if (field == null)
						{
							string format = "第(2)行，{@)中不存在Key为 : [(1] 的字段";
							object formName = this.GetFormName();
							KeyValuePair<string, object> item2 = item;
							string value = string.Format(format, formName, item2.Key, num);
							stringBuilder.AppendLine(value);
						}
						else
						{
							string propertyName = field.PropertyName;
							if (field.DynamicProperty is ISimpleProperty)
							{
								KeyValuePair<string, object> item3 = item;
								if (item3.Value.IsNullOrEmpty())
								{
									dynamicObject[propertyName] = null;
								}
								else if (field is DateTimeField)
								{
									DynamicObject dynamicObject2 = dynamicObject;
									string propertyName2 = propertyName;
									KeyValuePair<string, object> item4 = item;
									dynamicObject2[propertyName2] = Convert.ToDateTime(item4.Value);
								}
								else
								{
									DynamicObject dynamicObject3 = dynamicObject;
									string propertyName3 = propertyName;
									KeyValuePair<string, object> item5 = item;
									dynamicObject3[propertyName3] = item5.Value;
								}
							}
							else
							{
								BaseDataField baseDataField = field as BaseDataField;
								KeyValuePair<string, object> item6 = item;
								if (item6.Value.IsNullOrEmpty() || baseDataField == null || !baseDataField.SupportSetValueByNumber)
								{
									dynamicObject[propertyName] = null;
									dynamicObject[propertyName + "_Id"] = null;
								}
								else
								{
									KeyValuePair<string, object> item7 = item;
									Dictionary<string, object> dictionary2 = item7.Value as Dictionary<string, object>;
									if (dictionary2 == null)
									{
										string format2 = "第{1}行，Key为: 【{0}】字段的值的格式不正确";
										KeyValuePair<string, object> item8 = item;
										string value2 = string.Format(format2, item8.Key, num);
										stringBuilder.AppendLine(value2);
									}
									else
									{
										object arg;
										dictionary2.TryGetValue("FNumber", out arg);
										DynamicObject dynamicObject4 = this._lstItemInfo.FirstOrDefault(delegate (DynamicObject e)
										{
											string str = e["FFlexNumber"].ToString();
											KeyValuePair<string, object> item11 = item;
											KeyValuePair<string, object> keyValuePair;
											if (!false)
											{
												keyValuePair = item11;
											}
											return str.EqualsIgnoreCase(keyValuePair.Key);
										});
										QueryBuilderParemeter queryBuilderParemeter = new QueryBuilderParemeter();
										queryBuilderParemeter.FormId = baseDataField.LookUpObject.FormId;
										queryBuilderParemeter.SelectItems.Add(new SelectorItemInfo(baseDataField.LookUpObject.PkFieldName));
										string text = string.Format("{0} = '{1}'", baseDataField.LookUpObject.NumberFieldName, arg);

										
										if (this._orgId > 0 && (baseDataField.LookUpObject.StrategyType == Enu_BaseDataStrategyType.Distribute || baseDataField.LookUpObject.StrategyType == Enu_BaseDataStrategyType.Private))
										{
											text += string.Format(" AND {0} = {1}", baseDataField.LookUpObject.OrgFieldName, this._orgId);
										}

										if (this._flexFormId.ToUpper() != FormIdConst.BD_FLEXVALUESDETAIL)
										{
											text += string.Format(" AND FForbidStatus <> '{0}' AND FDOCUMENTSTATUS='{1}'", 'B'.ToString(), 'C'.ToString());
										}
										if (dynamicObject4 != null && int.Parse(dynamicObject4["FValueType"].ToString()) == 1)
										{
											text += string.Format(" AND FID='[0)’ ", (dynamicObject4["FValueSource"].ToString()));
										}
										queryBuilderParemeter.FilterClauseWihtKey = text;
										DynamicObject[] array = BusinessDataServiceHelper.LoadFromCache(this._ctx, baseDataField.RefFormDynamicObjectType, queryBuilderParemeter);
										if (array != null && array.Count<DynamicObject>() > 0)
										{
											dynamicObject[propertyName] = array[0];
											dynamicObject[propertyName + "_Id"] = array[0]["Id"];
										}
										else
										{
											string format3 = "第{1}行 ，key为 : 【{0}】 字段的值不存在或未审核或被禁用。";
											KeyValuePair<string, object> item9 = item;
											string value3 = string.Format(format3, item9.Key, num);
											stringBuilder.AppendLine(value3);
										}
									}
								}
							}
						}
					}
				}
				list.Add(dynamicObject);
			}
			if (list.Count<DynamicObject>() == 0)
			{
				throw new Exception("数据包不能为空");
			}
			string text2 = stringBuilder.ToString();
			if (!string.IsNullOrWhiteSpace(text2))
			{
				throw new Exception(text2);
			}
			List<DynamicObject> list2 = new List<DynamicObject>();
			foreach (DynamicObject dynamicObject5 in list)
			{
				long flexDataId = FlexServiceHelper.GetFlexDataId(this._ctx, dynamicObject5, this._flexFormId);
				if (flexDataId > 0L)
				{
					dynamicObject5["Id"] = flexDataId;
					list2.Add(dynamicObject5);
				}
				else
				{
					DynamicObject item10 = BusinessDataServiceHelper.Save(this._ctx, dynamicObject5);
					list2.Add(item10);
				}
			}
			return list2;
		}

		private OperateResult GenerateOprResult(string infoMsg, bool isSucc, object pkValue)
		{
			var operateResult = new OperateResult();
			operateResult.SuccessStatus = isSucc;
			operateResult.Message = infoMsg;
			if (isSucc)
			{
				operateResult.PKValue = pkValue;
			}
			return operateResult;
		}
	}
}
