narsil/Tanshu.Accounts.Repository/ModifierBI.cs
2014-10-16 16:45:03 +05:30

81 lines
3.1 KiB
C#

using System.Collections.Generic;
using System.Linq;
using Tanshu.Accounts.Entities;
namespace Tanshu.Accounts.Repository
{
public class ModifierBI : UnitOfWork<Modifier>
{
public IList<ProductGroup> ProductGroupList()
{
return _session.QueryOver<ProductGroup>()
.OrderBy(x => x.SortOrder).Asc
.List();
}
public void Insert(Modifier modifier, bool showForAll, IEnumerable<ProductGroup> selectedGroups)
{
if (showForAll)
selectedGroups = null;
SetGroups(modifier, selectedGroups);
_session.Save(modifier);
}
public void Update(Modifier modifier, bool showForAll, IEnumerable<ProductGroup> selectedGroups)
{
if (showForAll)
selectedGroups = null;
SetGroups(modifier, selectedGroups);
_session.Update(modifier);
}
private void SetGroups(Modifier modifier, IEnumerable<ProductGroup> selectedGroups)
{
if (selectedGroups == null)
{
var ug = modifier.ProductGroupModifiers.SingleOrDefault(x => x.ProductGroup == null);
var others = modifier.ProductGroupModifiers.Where(x => x.ProductGroup != null).ToList();
for (var i = others.Count() -1; i >= 0; i--)
{
var item = others[i];
modifier.ProductGroupModifiers.Remove(item);
_session.Delete(item);
}
if (ug == null)
{
var pgm = new ProductGroupModifier() { Modifier = modifier, ProductGroup = null, ShowAutomatically = false };
_session.Save(pgm);
}
}
else
{
var groups = new Dictionary<ProductGroup, bool>();
foreach (var item in ProductGroupList())
{
groups.Add(item, selectedGroups.Any(x => x.ProductGroupID == item.ProductGroupID));
}
foreach (var item in groups)
{
var id = item.Key.ProductGroupID;
var ug = modifier.ProductGroupModifiers.SingleOrDefault(x =>x.ProductGroup != null && x.ProductGroup.ProductGroupID == id);
if (item.Value && ug == null)
{
var pgm = new ProductGroupModifier() { Modifier = modifier, ProductGroup = item.Key, ShowAutomatically = false };
_session.Save(pgm);
}
else if (!item.Value && ug != null)
{
modifier.ProductGroupModifiers.Remove(ug);
_session.Delete(ug);
}
}
var blank = modifier.ProductGroupModifiers.SingleOrDefault(x => x.ProductGroup == null);
if (blank != null)
{
modifier.ProductGroupModifiers.Remove(blank);
_session.Delete(blank);
}
}
}
}
}