public void DataBind(GeneralBusinessAnalysis model)
 {
     ViewModel = (GeneralBusinessAnalysis)model;
     this.DataContext = (GeneralBusinessAnalysis)model;
     CurrentAssetsTb.Text = string.Format(FormatUtils.Percentage, ViewModel.StructureCompanyDiagram["Оборотные активы"].ToString());
     LongTermAssetsTb.Text = string.Format(FormatUtils.Percentage, ViewModel.StructureCompanyDiagram["Долгосрочные активы"].ToString());
     CurrentDebtTb.Text = string.Format(FormatUtils.Percentage, ViewModel.StructureCompanyDiagram["Текущая задолженность"].ToString());
     LongTermDebtTb.Text = string.Format(FormatUtils.Percentage, ViewModel.StructureCompanyDiagram["Долгосрочная задолженность"].ToString());
     EquityTb.Text = string.Format(FormatUtils.Percentage, ViewModel.StructureCompanyDiagram["Собственный капитал"].ToString());
     UpdateColors();
     UpdateTableSize();
 }
        public static GeneralBusinessAnalysis GetGeneralBusinessAnalysis(DateTime startDate, DateTime endDate, MainModel MainModel)
        {
            var tmSpan = MainAccessor.GetTimeSpan();
            var stTodayDate = MainModel.StartDate;
            var endTodayDate = MainModel.EndDate;

            var model = new GeneralBusinessAnalysis();

            model.Sales = MainModel.Sales.Select(i => i.Sales.Sum(j => j.SalesWithoutNDS)).Sum();

            model.CostPrice = MainModel.Sales.Select(i => i.Sales.Sum(j => j.CostPrise)).Sum();
            //TODO вроде верная дрянь но считается она не верно
            model.GrossProfit = MainModel.Sales.Select(i => i.Sales.Sum(j => j.SalesWithoutNDS - j.CostPrise)).Sum();
            model.AveGrossProfit = MainModel.Sales.Select(i => i.Sales.Sum(j => j.SalesWithoutNDS - j.AveCostPrise)).Sum();

            model.Cost = MainModel.ReportProfitAndLoss.Costs.Sum();

            #region Прошлые периоды
            MainModel.newStTodayDate = new DateTime();
            MainModel.newEndTodayDate = new DateTime();
            dif = (endTodayDate.Year - stTodayDate.Year) * 12 + (endTodayDate.Month - stTodayDate.Month);
            //if (dif <= 12)
            //{
                decimal tmp = decimal.Zero;
                MainModel.newStTodayDate = stTodayDate.AddMonths(-dif);
                MainModel.newEndTodayDate = stTodayDate.AddMonths(1);
                model.salesFirst = Accessors.GetSales(MainModel.newStTodayDate, MainModel.newEndTodayDate, true);

                MainModel tmMain = new MainModel();
                decimal RPALF = decimal.Zero;
                if (model.Cost > 0)
                {
                    tmMain.StartDate = MainModel.newStTodayDate;
                    tmMain.EndDate = MainModel.newEndTodayDate;
                    tmMain.StartTranz = MainAccessor.GetAllTrans(MainModel.StartDate, null);
                    tmMain.EndTranz = MainAccessor.GetAllTrans(MainModel.StartDate, MainModel.EndDate);
                    //tmMain.StartTranzOriginal = MainAccessor.GetAllTransOriginal(MainModel.StartDate, null);
                    //tmMain.EndTranzOriginal = MainAccessor.GetAllTransOriginal(MainModel.StartDate, MainModel.EndDate);
                    tmMain.ReportProfitAndLoss = Accessors.GetReportProfitAndLoss(MainModel);
                    RPALF = tmMain.ReportProfitAndLoss.Costs.Sum();
                    tmp = RPALF / model.Cost * 100;
                    model.CostAnFirst = tmp; //(tmp > 1 ? (tmp - 1).ToString() : (1 - tmp).ToString()) + "%";
                }

                MainModel.newStTodayDate = stTodayDate.AddYears(-1);
                MainModel.newEndTodayDate = endTodayDate.AddYears(-1);
                var salesSecond = Accessors.GetSales(MainModel.newStTodayDate, MainModel.newEndTodayDate, true);

                decimal RPALS = decimal.Zero;
                if (model.Cost > 0)
                {
                    tmMain.StartDate = MainModel.newStTodayDate;
                    tmMain.EndDate = MainModel.newEndTodayDate;
                    tmMain.StartTranz = MainAccessor.GetAllTrans(MainModel.StartDate, null);
                    tmMain.EndTranz = MainAccessor.GetAllTrans(MainModel.StartDate, MainModel.EndDate);
                    //tmMain.StartTranzOriginal = MainAccessor.GetAllTransOriginal(MainModel.StartDate, null);
                    //tmMain.EndTranzOriginal = MainAccessor.GetAllTransOriginal(MainModel.StartDate, MainModel.EndDate);
                    tmMain.ReportProfitAndLoss = Accessors.GetReportProfitAndLoss(MainModel);
                    RPALS = tmMain.ReportProfitAndLoss.Costs.Sum();
                    tmp = RPALS / model.Cost * 100;
                    model.CostAnSecond = tmp; // (tmp > 1 ? (tmp - 1).ToString() : (1 - tmp).ToString()) + "%";
                }

            if (model.Sales != 0)
            {
                tmp = model.salesFirst.Select(i => i.Sales.Sum(j => j.SalesWithoutNDS)).Sum() / model.Sales * 100;
                model.SalesAnFirst = tmp; //(tmp > 1 ? (tmp - 1).ToString() : (1 - tmp).ToString()) + "%";

                tmp = salesSecond.Select(i => i.Sales.Sum(j => j.SalesWithoutNDS)).Sum() / model.Sales * 100;
                model.SalesAnSecond = tmp; //(tmp > 1 ? (tmp - 1).ToString() : (1 - tmp).ToString()) + "%";
            }

            if (model.CostPrice != 0)
            {
                tmp = model.salesFirst.Select(i => i.Sales.Sum(j => j.CostPrise)).Sum() / model.CostPrice * 100;
                model.CostPriceAnFirst = tmp; //(tmp > 1 ? (tmp - 1).ToString() : (1 - tmp).ToString()) + "%";

                tmp = salesSecond.Select(i => i.Sales.Sum(j => j.CostPrise)).Sum() / model.CostPrice * 100;
                model.CostPriceAnSecond = tmp; //(tmp > 1 ? (tmp - 1).ToString() : (1 - tmp).ToString()) + "%";
            }

                var GPFtmp = model.salesFirst.Select(i => i.Sales.Sum(j => j.SalesWithoutNDS - j.CostPrise)).Sum();
            if (model.CostPrice != 0)
            {
                tmp = GPFtmp / model.CostPrice * 100;
                model.GrossProfitAnFirst = tmp; //(GPFtmp > 1 ? (GPFtmp - 1).ToString() : (1 - GPFtmp).ToString()) + "%";
            }

                var GPStmp = salesSecond.Select(i => i.Sales.Sum(j => j.SalesWithoutNDS - j.CostPrise)).Sum();
            if (model.CostPrice != 0)
            {
                tmp = GPStmp / model.CostPrice * 100;
                model.GrossProfitAnSecond = tmp; // (GPStmp > 1 ? (GPStmp - 1).ToString() : (1 - GPStmp).ToString()) + "%";
            }

                model.NetProfit = model.GrossProfit - model.Cost;
            if (model.NetProfit != 0)
            {
                tmp = (GPFtmp - RPALF) / model.NetProfit * 100;
                model.NetProfitAnFirst = tmp; //(tmp > 1 ? (tmp - 1).ToString() : (1 - tmp).ToString()) + "%";
                tmp = (GPStmp - RPALS) / model.NetProfit * 100;
                model.NetProfitAnSecond = tmp; //(tmp > 1 ? (tmp - 1).ToString() : (1 - tmp).ToString()) + "%";
            }
            //}
            //else
            //{
            //    model.SalesAnFirst =
            //    model.SalesAnSecond =
            //    model.CostPriceAnSecond =
            //    model.GrossProfitAnFirst =
            //    model.GrossProfitAnSecond =
            //    model.NetProfitAnFirst =
            //    model.NetProfitAnSecond =
            //    model.CostAnFirst =
            //    model.CostAnSecond =
            //    model.CostPriceAnFirst = 0;//"-";
            //}
            #endregion

            model.StructureCompanyDiagram = new Dictionary<string, decimal>();
            model.StructureCompanyDiagram.Add("Оборотные активы", (MainModel.BusinessResults.CirculatingAssetsEnd + MainModel.BusinessResults.LongTermAssetsEnd) != 0 ? 
                MainModel.BusinessResults.CirculatingAssetsEnd / (MainModel.BusinessResults.CirculatingAssetsEnd + MainModel.BusinessResults.LongTermAssetsEnd) * 100 : 0);
            model.StructureCompanyDiagram.Add("Долгосрочные активы", (MainModel.BusinessResults.CirculatingAssetsEnd + MainModel.BusinessResults.LongTermAssetsEnd) != 0 ? 
                100 - MainModel.BusinessResults.CirculatingAssetsEnd / (MainModel.BusinessResults.CirculatingAssetsEnd + MainModel.BusinessResults.LongTermAssetsEnd) * 100 : 0);
            model.StructureCompanyDiagram.Add("Текущая задолженность", (MainModel.BusinessResults.CurrentDebtEnd + MainModel.BusinessResults.LongTermDebtEnd + MainModel.BusinessResults.OwnCapitalEnd) != 0 ? 
                MainModel.BusinessResults.CurrentDebtEnd / (MainModel.BusinessResults.CurrentDebtEnd + MainModel.BusinessResults.LongTermDebtEnd + MainModel.BusinessResults.OwnCapitalEnd) * 100 : 0);
            model.StructureCompanyDiagram.Add("Долгосрочная задолженность", (MainModel.BusinessResults.CurrentDebtEnd + MainModel.BusinessResults.LongTermDebtEnd + MainModel.BusinessResults.OwnCapitalEnd) != 0 ? 
                MainModel.BusinessResults.LongTermDebtEnd / (MainModel.BusinessResults.CurrentDebtEnd + MainModel.BusinessResults.LongTermDebtEnd + MainModel.BusinessResults.OwnCapitalEnd) * 100 : 0);
            model.StructureCompanyDiagram.Add("Собственный капитал", (MainModel.BusinessResults.CurrentDebtEnd + MainModel.BusinessResults.LongTermDebtEnd + MainModel.BusinessResults.OwnCapitalEnd) != 0 ? 100 -
                MainModel.BusinessResults.CurrentDebtEnd / (MainModel.BusinessResults.CurrentDebtEnd + MainModel.BusinessResults.LongTermDebtEnd + MainModel.BusinessResults.OwnCapitalEnd) * 100
                - MainModel.BusinessResults.LongTermDebtEnd / (MainModel.BusinessResults.CurrentDebtEnd + MainModel.BusinessResults.LongTermDebtEnd + MainModel.BusinessResults.OwnCapitalEnd) * 100 : 0);

            #region рентабельность
            //Для рентабельности вложенных денег нам необходимо знать сколько какого товара на начало периода
            //var beginingDate = new DateTime(2010, 01, 01);
            //var beginingSalesModel = Accessors.GetSalesOneQuery(stTodayDate, endTodayDate);
            //var beginingSales = beginingSalesModel.SelectMany(_ => _.Sales);// вытащим все месяца в одну ентити
            //var GroupsBSales = (from bs in beginingSales
            //                    group bs by bs.GroupCode into g
            //                    select new SalesEnt
            //                    {
            //                        GroupCode = g.FirstOrDefault().GroupCode,
            //                        GroupName = g.FirstOrDefault().GroupName,
            //                        CostPrise = g.Sum(_ => _.CostPrise),
            //                        SalesWithoutNDS = g.Sum(_ => _.SalesWithoutNDS),
            //                        CountPur = g.Sum(_ => _.CountPur),
            //                        CountSal = g.Sum(_ => _.CountSal),
            //                        CountGoodsSt = g.Sum(_ => _.CountGoodsSt),
            //                        CountGoodsEnd = g.Sum(_ => _.CountGoodsEnd)
            //                    }
            //                    ).ToList();

            //тоже самое уже для нашего периода
            //Вроде не нужно
            //var thisSales = Accessors.GetSalesOneQuery(stTodayDate, endTodayDate);
            var sEnt = MainModel.Sales.SelectMany(_ => _.Sales);
            model.gSales = (from s in sEnt
                            group s by s.GroupCode into g
                            select new SalesEnt
                            {
                                GroupCode = g.FirstOrDefault().GroupCode,
                                GroupName = g.FirstOrDefault().GroupName,
                                CostPrise = g.Sum(_ => _.CostPrise),
                                SalesWithoutNDS = g.Sum(_ => _.SalesWithoutNDS),
                                CountPur = g.Sum(_ => _.CountPur),
                                CountSal = g.Sum(_ => _.CountSal),
                                CountGoodsSt = g.Sum(_ => _.CountGoodsSt),
                                CountGoodsEnd = g.Sum(_ => _.CountGoodsEnd),
                                AveCostPrise = g.Sum(_ => _.AveCostPrise)
                            }
                          ).ToList();

            model.gSalesByClient = (from s in sEnt
                                    group s by s.BuyerCode into g
                                    select new SalesEnt
                                    {
                                        BuyerCode = g.FirstOrDefault().BuyerCode,
                                        BuyerName = g.FirstOrDefault().BuyerName,
                                        CostPrise = g.Sum(_ => _.CostPrise),
                                        SalesWithoutNDS = g.Sum(_ => _.SalesWithoutNDS),
                                        CountPur = g.Sum(_ => _.CountPur),
                                        CountSal = g.Sum(_ => _.CountSal),
                                        CountGoodsSt = g.Sum(_ => _.CountGoodsSt),
                                        CountGoodsEnd = g.Sum(_ => _.CountGoodsEnd),
                                        AveCostPrise = g.Sum(_ => _.AveCostPrise)
                                    }
                                  ).ToList();

            //TODO  спросить что с группами которые купили и продали внутри периода
            //с процентами беда
            var averageRentSales = (from s in model.gSales 
                                    where s.CountGoodsSt != 0 || s.CountGoodsEnd != 0
                                    select new FillModel
                                    {
                                        Name = s.GroupName,
                                        Share = MainModel.Sales.SelectMany(_ => _.Sales).Where(_ => _.GroupCode == s.GroupCode).Sum(i => i.SalesWithoutNDS - i.CostPrise) / ((s.CountGoodsSt + s.CountGoodsEnd) / 2) * 100
                                    }
                                    ).OrderByDescending(_ => _.Share).ToList();
            model.ProfitabilityDiagram = averageRentSales;
            #endregion

            #region объем оборотного капитала и все к нему
            model.SalesDiagram = new Dictionary<string, decimal>();
            foreach (var mon in MainModel.Sales)
            {
                model.SalesDiagram.Add(MainModel.IsItQuarter || (MainModel.EndDate - MainModel.StartDate).Days > 365 ? string.Format("{0}, {1}", (Month)mon.Date.Month, mon.Date.Year - MainModel.TimeSpan) : ((Month)mon.Date.Month).ToString(), mon.Sales.Sum(_ => _.SalesWithoutNDS));
            }

            model.NetProfitDiagram = new Dictionary<string, decimal>();
            var tmpMon = 0;
            for (int i = 0; i < dif; i++)
            {
                var _year = startDate;
                if (startDate.Month + i > 12) tmpMon = i - 12;
                else tmpMon = startDate.Month + i;
                model.NetProfitDiagram.Add(MainModel.IsItQuarter || (MainModel.EndDate - MainModel.StartDate).Days > 365 ? string.Format("{0}, {1}", (Month)tmpMon, _year.AddMonths(i).Year - MainModel.TimeSpan) : ((Month)tmpMon).ToString(), MainModel.ReportProfitAndLoss.Costs.ToArray()[i]);
            }

            var mm = new MainModel();
            model.AverageWorkingCapitalDiagram = new Dictionary<string, decimal>();
            int[] endMonthYear = new int[] { MainModel.EndDate.Month, MainModel.EndDate.Year };

            int monthCount = 0;
            int[] startMonthYear = new int[] { MainModel.StartDate.Month, MainModel.StartDate.Year };//будем бежать от начала до конца периода
            do
            {
                mm.StartDate = new DateTime(startMonthYear[1], startMonthYear[0], 01);
                mm.EndDate = new DateTime(startMonthYear[1], startMonthYear[0], DateTime.DaysInMonth(startMonthYear[1], startMonthYear[0]))
                    .AddHours(23).AddMinutes(59).AddSeconds(59);

                mm.StartTranz = MainModel.StartTranz.Where(_ => _.period < mm.StartDate).ToList();
                mm.EndTranz = MainModel.EndTranz.Where(_ => _.period < mm.EndDate).ToList();
                
                //mm.StartTranzOriginal = MainModel.StartTranzOriginal.Where(_ => _.period < mm.StartDate).ToList();
                //mm.EndTranzOriginal = MainModel.EndTranzOriginal.Where(_ => _.period < mm.EndDate).ToList();
                if (mm.EndTranz.Where(_ => _.period < mm.StartDate).Count() > 0)
                    mm.StartTranz.AddRange(mm.EndTranz.Where(_ => _.period < mm.StartDate).ToList());//чтобы из бд не тащить мы переложим из модельки за текущий период транзикции в прошедщий период

                model.PastBisRes = Accessors.GetBusinessResults(mm);
                // TODO: XYUTA
                model.AverageWorkingCapitalDiagram.Add(
                MainModel.IsItQuarter || (MainModel.EndDate - MainModel.StartDate).Days >= 365 ? string.Format("{0}, {1}", (Month)startMonthYear[0], startMonthYear[1]) : ((Month)startMonthYear[0]).ToString(), (model.PastBisRes.CirculatingAssetsStart + model.PastBisRes.CirculatingAssetsEnd) / 2);

                #region Cчитаем кол-во месяцев
                if (startMonthYear[0] == 12)
                {
                    startMonthYear[1]++;
                    startMonthYear[0] = 1;
                    monthCount++;
                }
                else
                {
                    startMonthYear[0]++;
                    monthCount++;
                }
                #endregion

            }
            while ((startMonthYear[1] < endMonthYear[1] && startMonthYear[1] != endMonthYear[1]) || (startMonthYear[0] < endMonthYear[0] && startMonthYear[1] == endMonthYear[1]));
            #endregion 

            return model;
        }
        private static void FillPercentForAllProperty(ref string First, ref string Second, DateTime stTodayDate, DateTime endTodayDate, GeneralBusinessAnalysis model
            , List<SalesModel> salesFirst, List<SalesModel> salesSecond, int dif)
        {

        }