/// <summary>
        /// Loads the budget monthly report.
        /// </summary>
        /// <param name="seachingCondition">The seaching condition.</param>
        /// <returns></returns>
        public IEnumerable<SummaryDetails> LoadBudgetMonthlyReport(DetailsCondition searchingCondition)
        {

            var data = AccountBookDataContext.BudgetMonthlyReports
                .Where(p => p.ItemType == searchingCondition.IncomeOrExpenses
                && p.Year == searchingCondition.StartDate.Value.Year && p.Month >= searchingCondition.StartDate.Value.Month)
                .ToList();

            var query = data.GroupBy(p => new
                {
                    Date = new DateTime(p.Year, p.Month == 0 ? 1 : p.Month, 1),
                    ItemType = p.ItemType
                });

            foreach (var item in query)
            {
                yield return new SummaryDetails()
                {
                    AccountItemType = item.Key.ItemType,
                    TotalAmout = item.Sum(p => p.GetMoney()),
                    Date = item.Key.Date,
                    Count = item.Count(),
                    Name = "{0}".FormatWith(item.Key.Date.ToString(LocalizedStrings.CultureName.DateTimeFormat.YearMonthPattern, LocalizedStrings.CultureName)),
                };
            }
        }
 public override void LoadData()
 {
     DetailsCondition ds = new DetailsCondition {
         SearchingScope = this.yearlyMonthsIncomeExpenseAvgInfo.ScopeForSummary
     };
     System.Collections.Generic.List<AccountItem> list = (from p in this.AccountBookDataContext.AccountItems
         where (p.CreateTime.Date > ds.StartDate.GetValueOrDefault().Date) && (p.CreateTime.Date < ds.EndDate.GetValueOrDefault().Date)
         select p).ToList<AccountItem>();
     decimal val = ((System.Collections.Generic.IEnumerable<Decimal>) (from p in list
         where p.Type == ItemType.Expense
         select p.GetMoney().Value)).Sum() / 12.0M;
     decimal num2 = ((System.Collections.Generic.IEnumerable<Decimal>) (from p in list
         where p.Type == ItemType.Income
         select p.GetMoney().Value)).Sum() / 12M;
     string symOfCurrency = AppSetting.Instance.DefaultCurrency.GetCurrentString();
     this.YearlyMonthsIncomeExpenseAvgInfo.AmountInfo = "{0}/{1}".FormatWith(new object[] { AppSetting.Instance.DefaultCurrency.GetAmountInfoWithCurrencySymbol(symOfCurrency, num2.ToMoneyF2()), AppSetting.Instance.DefaultCurrency.GetAmountInfoWithCurrencySymbol(symOfCurrency, val.ToMoneyF2()) });
     ds.SearchingScope = this.monthlyWeeksExpenseAvgInfo.ScopeForSummary;
     decimal? nullable = ViewModelLocator.BorrowLeanViewModel.QueryBorrowLoan(p => ((int?) p.BorrowOrLean) == ((int?) LeanType.BorrowIn)).ToList<Repayment>().Sum<Repayment>(p => p.GetMoney());
     decimal? nullable2 = ViewModelLocator.BorrowLeanViewModel.QueryBorrowLoan(p => ((int?) p.BorrowOrLean) == ((int?) LeanType.LoanOut)).ToList<Repayment>().Sum<Repayment>(p => p.GetMoney());
     this.TotalInDebt.AmountInfo = this.GetAmountInfo(symOfCurrency, nullable.GetValueOrDefault().ToMoneyF2());
     this.TotalLoanOut.AmountInfo = this.GetAmountInfo(symOfCurrency, nullable2.GetValueOrDefault().ToMoneyF2());
     this.TotalTransaction.AmountInfo = (from p in this.AccountBookDataContext.TransferingItems
         where (p.TransferingDate.Date > ds.StartDate.Value.Date) && (p.TransferingDate.Date <= ds.EndDate.Value.Date)
         select p).Count<TransferingItem>().ToString();
     Deployment.Current.Dispatcher.BeginInvoke(delegate {
         this.CurrentMontlyDailyExpenseAmount = "{0}{1}".FormatWith(new object[] { symOfCurrency, (this.MainPageViewModel.ThisMonthSummary.TotalExpenseAmount / DayCountOfThisMonth).ToMoneyF2() });
     });
 }
        public void LoadData(DetailsCondition dc, IEnumerable<SummaryDetails> dataForBinding)
        {
            if (dc == null || dataForBinding == null) return;
            if (!NeedRefreshData) return;

            if (dc.IncomeOrExpenses == ItemType.Expense)
                dataForBinding = dataForBinding.Where(p => p.AccountItemType == ItemType.Expense);
            else if (dc.IncomeOrExpenses == ItemType.Income)
                dataForBinding = dataForBinding.Where(p => p.AccountItemType == ItemType.Income);

            this.PieChart.Series[0].DataSource = dataForBinding.ToList();
            NeedRefreshData = false;

        }
 private IEnumerable<SummaryDetails> loopData(DetailsCondition dc, ItemType itemType)
 {
     var temp = loadDailyData(dc, itemType).ToList();
     return temp;
 }
        /// <summary>
        /// Loads the settle monthly report.
        /// </summary>
        /// <param name="searchingCondition">The seaching condtion.</param>
        /// <returns></returns>
        public IEnumerable<SummaryDetails> LoadSettleMonthlyReport(DetailsCondition searchingCondition)
        {

            var settleAmount = AccountBookDataContext
                .AccountItems.Where(p => p.Type == searchingCondition.IncomeOrExpenses
                    && p.CreateTime.Year == searchingCondition.StartDate.Value.Year && p.CreateTime.Month >= searchingCondition.StartDate.Value.Month)

                    .GroupBy(p => new
                    {
                        Date = new DateTime(p.CreateTime.Year, p.CreateTime.Month, 1),
                        ItemType = p.Type
                    })
                    .ToList();

            Func<ItemType, string> incomeOrExpense = (i) => i == ItemType.Expense ? AppResources.Expense : AppResources.Income;

            foreach (var item in settleAmount)
            {
                yield return new SummaryDetails
                {
                    Count = item.Count(),
                    Date = item.Key.Date,
                    TotalAmout = item.Sum(p => p.GetMoney()),
                    AccountItemType = item.Key.ItemType,
                    Name = "{0}".FormatWith(item.Key.Date.ToString(LocalizedStrings.CultureName.DateTimeFormat.YearMonthPattern, LocalizedStrings.CultureName)),
                };
            }


        }
        /// <summary>
        /// Loads the test data.
        /// </summary>
        /// <param name="dc">The dc.</param>
        /// <param name="start">The start.</param>
        /// <param name="end">The end.</param>
        /// <returns></returns>
        public IEnumerable<SummaryDetails> LoadTestData(DetailsCondition dc, int start, int end)
        {
            var query = Enumerable.Range(1, 5)
                .Select(p => new DateTime(DateTime.Now.Year, p, 1))
                .GroupBy(p => new
                {
                    ItemType = ItemType.Expense,
                    Date = p,
                });

            Random rd = new Random(DateTime.Now.Millisecond * new Random().Next());

            foreach (var item in query)
            {
                yield return new SummaryDetails()
                {
                    AccountItemType = item.Key.ItemType,
                    TotalAmout = (decimal)rd.Next(start, end),
                    Date = item.Key.Date,
                    Count = item.Count(),
                    Name = "{0}".FormatWith(item.Key.Date.ToString(LocalizedStrings.CultureName.DateTimeFormat.YearMonthPattern, LocalizedStrings.CultureName)),
                };
            }

        }
        private void StatisticsInfoButton_Click(object sender, RoutedEventArgs e)
        {
            SearchingScope scope = (SearchingScope)System.Enum.Parse(typeof(SearchingScope), (sender as HyperlinkButton).Tag.ToString(), true);
            SummaryDetails details2 = new SummaryDetails();
            AccountItem item = new AccountItem
            {
                Category = this.current
            };
            details2.Tag = item;

            SummaryDetails details = details2;

            DetailsCondition condition2 = new DetailsCondition
            {
                ChartGroupMode = ChartGroupMode.ByCategoryName,
                SearchingScope = scope,
                GroupCategoryMode = this.current.IsParent ? CategorySortType.ByParentCategory : CategorySortType.ByChildCategory
            };

            DetailsCondition searchingCondition = condition2;
            StatsticSummaryItemsViewer.Show(details, searchingCondition, this);
        }
        /// <summary>
        /// Counts for settle amount for budget project.
        /// </summary>
        /// <param name="project">The project.</param>
        /// <param name="scope">The scope.</param>
        /// <returns></returns>
        public decimal CountForSettleAmountForBudgetProject(BudgetProject project, SearchingScope scope = SearchingScope.CurrentMonth)
        {
            if (project.BudgetItems == null || project.BudgetItems.Count == 0)
            {
                return 0.0m;
            }

            DetailsCondition dc = new DetailsCondition();
            dc.SearchingScope = scope;

            var result = 0.0m;
            foreach (var category in project.BudgetItems)
            {
                result += CountSumOfBudgetItems(category, dc);
            }

            return result;
        }
 /// <summary>
 /// Counts for last settle amount for category. The value is represent in global currency rate by the default currency type.
 /// </summary>
 /// <param name="budgetItem">The budget item.</param>
 /// <returns></returns>
 public decimal CountForLastSettleAmountForCategory(BudgetItem budgetItem, SearchingScope scope = SearchingScope.LastMonth)
 {
     DetailsCondition dc = new DetailsCondition();
     dc.SearchingScope = scope;
     return CountSumOfBudgetItems(budgetItem, dc);
 }
        /// <summary>
        /// Res the calculate.
        /// </summary>
        /// <param name="searchingContext">The searching context.</param>
        /// <param name="movingMonthDateOffset">The moving month date offset.</param>
        /// <returns></returns>
        public static DetailsCondition ReCalculate(DetailsCondition searchingContext, SearchingScope scope, DateTime movingMonthStartDateOffset, DateTime movingMonthEndDateOffset)
        {
            initializeStartDateAndEndDateBySearchScope(searchingContext, scope, movingMonthStartDateOffset, movingMonthEndDateOffset);

            return searchingContext;
        }
        public void LoadChart()
        {

            if (budgetSettleMonthlyReportChart == null || budgetSettleMonthlyReportChart.NeedRefreshData)
            {
                this.BusyForWork(AppResources.Loading);
                Thread th = new Thread(() =>
                {
                    this.InvokeInThread(() =>
                    {
                        if (budgetSettleMonthlyReportChart == null)
                        {
                            seachingCondtion = new DetailsCondition();
                            seachingCondtion.IncomeOrExpenses = Component.ItemType.Expense;
                            seachingCondtion.SearchingScope = SearchingScope.CurrentYear;

                            budgetSettleMonthlyReportChart = new Controls.BudgetSettleMonthlyReportChart();

                            this.ImagePivot.Content = budgetSettleMonthlyReportChart;
                        }

                        budgetSettleMonthlyReportChart.LoadData(seachingCondtion, null);

                        this.WorkDone();
                    });
                });

                th.Start();
            }
        }
        /// <summary>
        /// Queries the data by searching condition.
        /// </summary>
        /// <param name="e">The e.</param>
        /// <returns></returns>
        public static IEnumerable<AccountItem> QueryDataBySearchingCondition(DetailsCondition e)
        {
            IEnumerable<AccountItem> data;
            data = ViewModelLocator.AccountItemViewModel.AccountBookDataContext.AccountItems;
            if (e.SearchingScope != SearchingScope.All)
            {
                data = data.Where(p => p.CreateTime.Date >= e.StartDate.GetValueOrDefault().Date
                              && p.CreateTime.Date <= e.EndDate.GetValueOrDefault().Date);
            }

            if (e.IncomeOrExpenses != ItemType.All)
                data = data.Where(p => p.Type == e.IncomeOrExpenses);

            if (e.AccountIds.Count != 0)
            {
                data = data.Where(p => e.AccountIds.Contains(p.AccountId));
            }

            if (e.CategoryIds.Count != 0)
            {
                if (e.GroupCategoryMode == CategorySortType.ByChildCategory)
                    data = data.Where(p => e.CategoryIds.Contains(p.CategoryId));
                else
                {
                    data = data.Where(p => e.CategoryIds.Contains(p.Category.ParentCategoryId));
                }
            }

            if (!string.IsNullOrEmpty(e.NotesKey))
            {
                var keys = e.NotesKey.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);

                if (keys.Length > 0)
                {
                    data = data.Where(p => keys.Contains(p.Description));
                }
            }
            return data;
        }
        /// <summary>
        /// Shows the specified item.
        /// </summary>
        /// <param name="item">The item.</param>
        /// <param name="SearchingCondition">The searching condition.</param>
        /// <param name="pageFrom">The page from.</param>
        public static void Show(SummaryDetails item, DetailsCondition SearchingCondition, PhoneApplicationPage pageFrom)
        {
            var queryForSeeMore = QueryDataBySearchingCondition(SearchingCondition);

            var summaryItem = item.Tag as AccountItem;

            Guid categoryID = summaryItem.CategoryId;

            Account account = summaryItem.Account;

            if (SearchingCondition.ChartGroupMode == ChartGroupMode.ByCategoryName)
            {
                if (SearchingCondition.GroupCategoryMode == CategorySortType.ByParentCategory)
                {
                    IEnumerable<Guid> ids = null;

                    if (summaryItem.Category.IsParent)
                    {
                        categoryID = summaryItem.Category.Id;
                        ids = ViewModelLocator.CategoryViewModel.AccountBookDataContext.Categories.Where(p => p.ParentCategoryId == categoryID)
                        .Select(p => p.Id).ToList();
                    }
                    else
                    {
                        categoryID = summaryItem.Category.ParentCategoryId;
                        ids = ViewModelLocator.CategoryViewModel.AccountBookDataContext.Categories.Where(p => p.ParentCategoryId == summaryItem.Category.ParentCategory.Id)
                        .Select(p => p.Id).ToList();
                    }

                    queryForSeeMore = queryForSeeMore.Where(p => ids.Contains(p.CategoryId));
                }
                else
                {
                    queryForSeeMore = queryForSeeMore.Where(i => i.CategoryId == categoryID);
                }
            }
            else
            {
                if (account != null)
                {
                    queryForSeeMore = queryForSeeMore.Where(p => p.AccountId == account.Id);
                }
            }

            StatsticSummaryItemsViewer.NeedReloadData = true;

            Pages.DialogBox.StatsticSummaryItemsViewer.DataSourceGetter = () => queryForSeeMore;

            pageFrom.NavigateTo("/Pages/DialogBox/StatsticSummaryItemsViewer.xaml");
        }
 public ViewModeConfig()
 {
     this.ViewDateTime = System.DateTime.Now;
     this.Mode = ViewMode.Day;
     this.searchingCondition = new DetailsCondition();
 }
        public IEnumerable<SummaryDetails> loadDailyData(DetailsCondition e, ItemType it)
        {
            var data = ViewModelLocator.AccountItemViewModel.AccountBookDataContext.AccountItems.Where(p => p.Type == it);
            if (e.SearchingScope != SearchingScope.All)
            {
                data = data.Where(p => p.CreateTime.Date >= e.StartDate && p.CreateTime.Date <= e.EndDate);
            }
            var currentYear = DateTime.Now.Year;
            var dataL = data.ToList();

            var duringMode = e.DuringMode;

            IEnumerable<SummaryDetails> dataForBinding = null;

            if (duringMode == DuringMode.ByDay)
            {
                dataForBinding = (from d in dataL
                                  orderby d.CreateTime.Date ascending
                                  group d by d.CreateTime.Date into g
                                  select new SummaryDetails()
                                          {
                                              Name = g.Key.ToString(g.Key.Year == currentYear ? ConstString.formatWithoutYearNoDDD : ConstString.formatWithYearNoDDD),
                                              AccountItemType = e.IncomeOrExpenses,
                                              Count = g.Count(),
                                              TotalAmout = g.Sum(p => p.GetMoney()),
                                          });
            }
            else
            {
                var groups = (from d in dataL
                              orderby d.CreateTime.Date ascending
                              group d by BuildGroupByMode(d, duringMode));

                dataForBinding = from g in groups
                                 select new SummaryDetails()
                                          {
                                              Name = g.Key,
                                              AccountItemType = e.IncomeOrExpenses,
                                              Count = g.Count(),
                                              TotalAmout = g.Sum(p => p.GetMoney()),
                                          };
            }

            return dataForBinding;
        }
        /// <summary>
        /// Res the calculate.
        /// </summary>
        /// <param name="searchingScope">The searching scope.</param>
        /// <param name="movingMonthDateOffset">The moving month date offset.</param>
        /// <returns></returns>
        public static DetailsCondition ReCalculate(SearchingScope searchingScope, DateTime movingMonthDateOffset)
        {
            var searchingContext = new DetailsCondition();
            searchingContext.searchingScope = searchingScope;

            initializeStartDateAndEndDateBySearchScope(searchingContext, searchingScope, movingMonthDateOffset);

            return searchingContext;
        }
        public void LoadData(DetailsCondition dc, IEnumerable<SummaryDetails> source)
        {
            if (dc.IncomeOrExpenses == ItemType.All)
            {
                IncomeSeries.DataSource = loopData(dc, ItemType.Income);
                ExpenseSeries.DataSource = loopData(dc, ItemType.Expense);
            }
            else
            {
                if (dc.IncomeOrExpenses == ItemType.Expense)
                { ExpenseSeries.DataSource = loopData(dc, ItemType.Expense); }
                if (dc.IncomeOrExpenses == ItemType.Income)
                { IncomeSeries.DataSource = loopData(dc, ItemType.Income); }
            }

            NeedRefreshData = false;
            this.SummaryTitle = dc.SummaryTitle;
        }
        /// <summary>
        /// Initializes the start date and end date by search scope.
        /// </summary>
        /// <param name="calculatingContext">The calculating context.</param>
        /// <param name="scope">The scope.</param>
        /// <param name="startDateOffset">The start date offset.</param>
        /// <param name="endDateOffset">The end date offset.</param>
        private static void initializeStartDateAndEndDateBySearchScope(DetailsCondition calculatingContext, SearchingScope? scope = null, DateTime? startDateOffset = null, DateTime? endDateOffset = null)
        {
            if (startDateOffset == null)
            {
                startDateOffset = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1, 0, 0, 0);
            }
            if (endDateOffset == null)
            {
                endDateOffset = startDateOffset.Value.GetLastDayOfMonth();
            }

            var offsetStartDate = startDateOffset.Value;
            var offsetEndDate = endDateOffset.Value;

            int startDay, startMonth, startYear;
            int endDay, endMonth, endYear;

            var isCustomized = AppSetting.Instance.BudgetStatsicSettings.BudgetStatsicMode == BudgetStatsicMode.BudgetStaticModeOfCustomized;

            var needToCalculateAgagin = true;

            if (startDateOffset == null && endDateOffset == null &&
                (AppSetting.Instance.BudgetStatsicSettings.BudgetStatsicMode == BudgetStatsicMode.BudgetStaticModeOfCustomized))
            {
                needToCalculateAgagin = false;
                offsetStartDate = AppSetting.Instance.BudgetStatsicSettings.StartDate;
                offsetEndDate = AppSetting.Instance.BudgetStatsicSettings.EndDate;
            }

            startDay = offsetStartDate.Day;
            startMonth = offsetStartDate.Month;
            startYear = offsetStartDate.Year;

            endDay = offsetEndDate.Day;
            endMonth = offsetEndDate.Month;
            endYear = offsetEndDate.Year;

            if (AppSetting.Instance.BudgetStatsicSettings.BudgetStatsicMode == BudgetStatsicMode.BudgetStaticModeOfCustomized)
            {
                needToCalculateAgagin = false;
                startDay = AppSetting.Instance.BudgetStatsicSettings.StartDate.Day;
                endDay = AppSetting.Instance.BudgetStatsicSettings.EndDate.Day;
            }


            if (scope == null && calculatingContext != null)
            {
                scope = calculatingContext.searchingScope;
            }
            else if (scope == null)
            {
                scope = SearchingScope.CurrentMonth;
            }

            var l_searchingScopr = scope;


            if (l_searchingScopr == TinyMoneyManager.Component.SearchingScope.LastMonth)
            {
                // ---> 2012.11.14.00.00 ---2012.12.14, 
                // ---> 2012.12.13.59.59 ---2013.1.15.  

                //  2012.11.15-2012.12.14
                //  2012.12.15-2013.1.14
                //  2013.1.15 - 2013.2.14.

                // --> 
                if (startMonth == 1)
                {
                    startMonth = 12;
                    startYear = startYear - 1;
                }
                else
                {
                    startMonth--;
                }

                if (endMonth == 1)
                {
                    endMonth = 12;
                    endYear = endYear - 1;
                }
                else
                {
                    endMonth--;
                }

                var maxDayOfStartDate = new DateTime(startYear, startMonth, 1).GetLastDayOfMonth().Day;
                var maxDayOfEndDate = new DateTime(endYear, endMonth, 1).GetLastDayOfMonth().Day;

                if (maxDayOfEndDate < endDay || !isCustomized)
                {
                    endDay = maxDayOfEndDate;
                }

                if (maxDayOfStartDate < startDay)
                {
                    startDay = maxDayOfStartDate;
                }

                offsetStartDate = new System.DateTime(startYear, startMonth, startDay, 0, 0, 0);
                offsetEndDate = new System.DateTime(endYear, endMonth, endDay, 23, 59, 59);
            }
            else if (l_searchingScopr == Component.SearchingScope.NextMonth)
            {
                if (startMonth == 12)
                {
                    startMonth = 1;
                    startYear = startYear + 1;
                }
                else
                {
                    startMonth++;
                }

                if (endMonth == 12)
                {
                    endMonth = 1;
                    endYear = endYear + 1;
                }
                else
                {
                    endMonth++;
                }

                var maxDayOfStartDate = new DateTime(startYear, startMonth, 1).GetLastDayOfMonth().Day;
                var maxDayOfEndDate = new DateTime(endYear, endMonth, 1).GetLastDayOfMonth().Day;

                if (maxDayOfEndDate < endDay || !isCustomized)
                {
                    endDay = maxDayOfEndDate;
                }
                if (maxDayOfStartDate < startDay)
                {
                    startDay = maxDayOfStartDate;
                }

                offsetStartDate = new System.DateTime(startYear, startMonth, startDay, 0, 0, 0);
                offsetEndDate = new System.DateTime(endYear, endMonth, endDay, 23, 59, 59);
            }
            else if (l_searchingScopr == TinyMoneyManager.Component.SearchingScope.CurrentWeek)
            {
                offsetStartDate = DateTime.Now;

                offsetStartDate = offsetStartDate.GetDateTimeOfFisrtDayOfWeek();
                offsetEndDate = offsetStartDate.AddDays(7.0).Date;
            }
            else if (l_searchingScopr == TinyMoneyManager.Component.SearchingScope.CurrentMonth)
            {
                if (needToCalculateAgagin)
                {
                    offsetStartDate = System.DateTime.Now.Date.GetFirstDayOfMonth();
                    offsetEndDate = System.DateTime.Now.Date.GetLastDayOfMonth();
                }
                else
                {
                    var maxDayOfStartDate = new DateTime(startYear, startMonth, 1).GetLastDayOfMonth().Day;
                    var maxDayOfEndDate = new DateTime(endYear, endMonth, 1).GetLastDayOfMonth().Day;

                    if (maxDayOfEndDate < endDay || !isCustomized)
                    {
                        endDay = maxDayOfEndDate;
                    }
                    if (maxDayOfStartDate < startDay)
                    {
                        startDay = maxDayOfStartDate;
                    }

                    if (DateTime.Now.Day >= startDay)
                    {
                        // 2013.1.15
                        // 2013.2.14
                        offsetStartDate = new DateTime(startYear, startMonth, startDay);

                        if (endMonth == 12)
                        {
                            endMonth = 1;
                            endYear = endYear + 1;
                        }

                        offsetEndDate = new DateTime(endYear, endMonth, endDay);
                    }
                    else
                    {
                        // 2012.12.15,
                        // 2013.1.14.
                        if (endMonth == 1)
                        {
                            startMonth = 12;
                            startYear = endYear - 1;
                        }

                        offsetStartDate = new DateTime(startYear, startMonth, startDay);

                        offsetEndDate = new DateTime(endYear, endMonth, endDay);
                    }
                }
            }
            else if (l_searchingScopr == TinyMoneyManager.Component.SearchingScope.CurrentYear)
            {
                offsetStartDate = new System.DateTime(System.DateTime.Now.Year, 1, 1, 0, 0, 0);
                offsetEndDate = new System.DateTime(System.DateTime.Now.Year, 12, 31, 23, 59, 59);
            }

            calculatingContext.StartDate = offsetStartDate;
            calculatingContext.EndDate = offsetEndDate;

        }
        /// <summary>
        /// Counts the sum of budget items.
        /// </summary>
        /// <param name="budgetItem">The budget item.</param>
        /// <param name="dc">The dc.</param>
        /// <returns></returns>
        public decimal CountSumOfBudgetItems(BudgetItem budgetItem, DetailsCondition dc)
        {
            var query = AccountBookDataContext.AccountItems.AsQueryable();

            query = query.Where(p => p.CreateTime.Date >= dc.StartDate.Value.Date
                && p.CreateTime.Date <= dc.EndDate.Value.Date);

            if (budgetItem.BudgetItemType == BudgetType.ParentCategory)
            {
                var childIds = AccountBookDataContext.Categories
                    .Where(p => p.ParentCategoryId == budgetItem.AssociatedCategory.Id)
                    .Select(p => p.Id)
                        .ToList();

                query = query.Where(p => childIds.Contains(p.CategoryId));
            }
            else
            {
                query = query.Where(p => p.CategoryId == budgetItem.AssociatedCategory.Id);
            }

            var result = query.AsEnumerable().Sum(p => p.GetMoney());

            return result.GetValueOrDefault();
        }
        private void LoadStasticsInfo(Category category)
        {
            int count = 0;
            DetailsCondition dc = new DetailsCondition
            {
                SearchingScope = SearchingScope.CurrentMonth
            };


            decimal val = ViewModelLocator.CategoryViewModel.CountStatistic(category, dc, delegate(int p)
            {
                count = p;
            });


            AccountItem ai = new AccountItem
            {
                SecondInfo = this.currentMonthName,
                ThirdInfo = AppResources.StatisticsInfoFormatterForCategory.FormatWith(new object[] { count, string.Empty, "{0}{1}".FormatWith(new object[] { this.symbol, val.ToMoneyF2() }) })
            };
            count = 0;

            DetailsCondition condition2 = new DetailsCondition
            {
                SearchingScope = SearchingScope.LastMonth
            };

            val = ViewModelLocator.CategoryViewModel.CountStatistic(category, condition2, delegate(int p)
            {
                count = p;
            });
            AccountItem lastMonthai = new AccountItem
            {
                SecondInfo = this.lastMonthName,
                ThirdInfo = AppResources.StatisticsInfoFormatterForCategory.FormatWith(new object[] { count, string.Empty, "{0}{1}".FormatWith(new object[] { this.symbol, val.ToMoneyF2() }) })
            };
            base.Dispatcher.BeginInvoke(delegate
            {
                this.CurrentMonthStaticsInfoPanel.DataContext = ai;
                this.LastMonthStaticsInfoPanel.DataContext = lastMonthai;
                this.hasLoadStatisticsInfo = true;
                this.WorkDone();
            });

            BudgetItem budgetItem = new BudgetItem
            {
                AssociatedCategory = category,
                BudgetType = category.CategoryType
            };
            DetailsCondition detailsCondition = new DetailsCondition
            {
                SearchingScope = SearchingScope.CurrentMonth
            };
            decimal monthlyBudgetAmount = ViewModelLocator.BudgetProjectViewModel.GetBudgetAmountForCategory(budgetItem, detailsCondition);
            base.Dispatcher.BeginInvoke(delegate
            {
                this.BudgetBlock.Text = "{0}{1}".FormatWith(new object[] { this.symbol, monthlyBudgetAmount.ToMoneyF2() });
            });
        }
        /// <summary>
        /// Gets the budget amount for category.
        /// </summary>
        /// <param name="budgetItem">The budget item.</param>
        /// <param name="detailsCondition">The details condition.</param>
        /// <returns></returns>
        public decimal GetBudgetAmountForCategory(BudgetItem budgetItem, DetailsCondition detailsCondition)
        {
            var query = AccountBookDataContext.BudgetItems.Where(p => p.BudgetTargetId == budgetItem.AssociatedCategory.Id)
                .ToList().Sum(p => p.GetMoney());

            return query.GetValueOrDefault();
        }
        /// <summary>
        /// Loads the settle monthly report by customized.
        /// </summary>
        /// <param name="searchingCondition">The searching condition.</param>
        /// <returns></returns>
        public IEnumerable<SummaryDetails> LoadSettleMonthlyReportByCustomized(DetailsCondition searchingCondition)
        {
            // ensure the start year,
            var startYear = DateTime.Now.Year;
            var startYearToSearch = startYear;
            var endYear = startYear;
            var currentMonth = DateTime.Now.Month;

            int startDay = AppSetting.Instance.BudgetStatsicSettings.StartDay, endDay = AppSetting.Instance.BudgetStatsicSettings.EndDay;
            int startMonth = 1, endMonth = 1;

            var itemType = searchingCondition.IncomeOrExpenses;

            for (int i = 1; i < 13; i++)
            {
                if (i > currentMonth) { break; }

                startMonth = i;

                if (i == 12)
                {
                    endYear = startYear + 1;
                    endMonth = 1;
                }
                else
                {
                    endMonth = i + 1;
                }

                if (startDay > 3)
                {
                    if (i == 1)
                    {
                        startMonth = 12;
                        endMonth = 1;

                        startYearToSearch = startYear - 1;
                    }
                }


                // create group.
                var startDate = new DateTime(startYearToSearch, startMonth, startDay);

                var endDate = new DateTime(endYear, endMonth, endDay);

                var data =
                    AccountBookDataContext
                .AccountItems.Where(p => p.Type == searchingCondition.IncomeOrExpenses
                    && p.CreateTime.Date >= startDate && p.CreateTime.Date <= endDate)
                    .ToList();

                //groupDateList.Add(i.ToString(), new DateTime[] { startDate, endDate });

                var keyDate = new DateTime(startYear, i, 1);

                yield return new SummaryDetails
                  {
                      Count = data.Count(),
                      Date = keyDate,
                      TotalAmout = data.Sum(p => p.GetMoney()),
                      AccountItemType = itemType,
                      Name = keyDate.ToString(LocalizedStrings.CultureName.DateTimeFormat.YearMonthPattern, LocalizedStrings.CultureName)
                  };
            }

        }