using APT.BaseData.Domain.IServices;
using APT.Infrastructure.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using APT.Infrastructure.Api;
namespace APT.BaseData.Services.Sys
{
	public class FMOrganizationService: CommonService, IFMOrganizationService
	{
		public FMOrganizationService(IRepository repository)
		   : base(repository)
		{
		} 

		/// <summary>
		/// 重置组织缓存
		/// </summary>
		public void SetOrgCache()
		{
			var orgs = this.GetEntities<T_FM_ORGANIZATION>(t => t.ENABLE_STATUS==0, new BaseFilter()).ToList();
			SysPermission sysPermission = APT.Infrastructure.Api.AppContext.SysPermission;
			if (sysPermission == null)
			{
				sysPermission = new SysPermission();
				APT.Infrastructure.Api.AppContext.SysPermission = sysPermission;
			}
			this.DoGetChildrenOrgCache(orgs, null, null, sysPermission);
            foreach (var o in orgs)
                sysPermission.OrgCodeCaches[o.CODE] = o.ID;
		}

		private void DoGetChildrenOrgCache(List<T_FM_ORGANIZATION> orgList,
				Guid? parentId, OrgCache parentCache, SysPermission sysPermission)
		{
			if (orgList == null || !orgList.Any()) return;
			var tempOrgs = orgList.Where(t => t.PARENT_ID == parentId).ToList();
			if (tempOrgs != null && tempOrgs.Any())
			{
				foreach (var item in tempOrgs)
				{
					OrgCache orgCache = new OrgCache();
					orgCache.OrgId = item.ID;
					orgCache.Code = item.CODE;
					sysPermission.OrgCaches[item.ID] = orgCache;
					if (parentCache != null)
					{
						parentCache.AllChildrenIds.Add(item.ID);
						if (parentCache.AllParentIds != null && parentCache.AllParentIds.Any())
						{
							orgCache.AllParentIds.AddRange(parentCache.AllParentIds);
							foreach(var pId in parentCache.AllParentIds)
							{
								OrgCache pOrgCache = null;
								if (sysPermission.OrgCaches.TryGetValue(pId, out pOrgCache))
								{
									if (!pOrgCache.AllChildrenIds.Contains(item.ID))
										pOrgCache.AllChildrenIds.Add(item.ID);
								}
							}
						}
						orgCache.AllParentIds.Add(parentCache.OrgId);
					}
					this.DoGetChildrenOrgCache(orgList, item.ID, orgCache, sysPermission);
				}
			}
		}
	}
}
