private decimal?GetSummOfValues(IEnumerable <DataRow> rows, ListPointWithResult point)
        {
            decimal?result = null;

            if (rows != null)
            {
                var aminusvalues = rows
                                   .Where(i => i.Field <decimal>("POINT_ID") == point.Id)
                                   .Select(i => i.Field <decimal?>("PL_V"))
                                   .Where(i => i.HasValue)
                                   .Select(i => i / 1000)
                                   .ToArray();
                if (aminusvalues.Length > 0)
                {
                    result = aminusvalues.Sum();
                }
                else
                {
                    result = null;
                }
            }
            return(result);
        }
        public GetDataControl()
        {
            InitializeComponent();

            _window = TMPApplication.ServiceInjector.Instance.GetService <TMPApplication.WpfDialogs.Contracts.IWindowWithDialogs>();
            if (_window == null)
            {
                throw new ArgumentNullException("Not found Window that implementing IWindowWithDialogs");
            }

            CancelCommand = new DelegateCommand(
                o =>
            {
                var q = _window.DialogQuestion(Strings.InterruptQuestion);
                q.Yes = () =>
                {
                    _cts.Cancel();
                    App.Current.MainWindow.TaskbarItemInfo.ProgressState = System.Windows.Shell.TaskbarItemProgressState.Error;
                };
                q.Show();
            },
                o => _cts != null && (_cts.IsCancellationRequested == false));
            CloseControlCommand = new DelegateCommand(o =>
            {
                if (_onClosed != null)
                {
                    _onClosed();
                }
            });
            SaveAllCommand = new DelegateCommand(o =>
            {
                CommonOpenFileDialog cfd = new CommonOpenFileDialog();
                cfd.Title                     = Strings.SelectFolderToSave;
                cfd.IsFolderPicker            = true;
                cfd.AddToMostRecentlyUsedList = false;
                cfd.EnsurePathExists          = true;
                cfd.Multiselect               = false;
                cfd.ShowPlacesList            = true;
                cfd.AllowNonFileSystemItems   = true;
                if (cfd.ShowDialog() == CommonFileDialogResult.Ok)
                {
                    App.Log("Сохранение всех отчётов в папку");
                    try
                    {
                        var folder = cfd.FileName;
                        foreach (var item in _list)
                        {
                            if (item.Status == ListPointStatus.Готово)
                            {
                                if (item.ResultType == "txt")
                                {
                                    System.IO.File.WriteAllText(
                                        System.IO.Path.Combine(folder, item.ResultName + ".csv"), TrimStringValue((string)item.ResultValue), Encoding.UTF8);
                                }
                                else
                                if (item.ResultType == "xls")
                                {
                                    byte[] bytes = (byte[])item.ResultValue;
                                    if (bytes != null)
                                    {
                                        System.IO.File.WriteAllBytes(
                                            System.IO.Path.Combine(folder, item.ResultName + ".xls"), bytes);
                                    }
                                }
                                else
                                {
                                    System.IO.File.WriteAllText(
                                        System.IO.Path.Combine(folder, item.ResultName + ".txt"), TrimStringValue((string)item.ResultValue), Encoding.UTF8);
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        _window.ShowDialogError(ex, Strings.ErrorOnSave);
                    }
                }
            },
                                                 o => _list != null && _list.All(i => i.ResultValue != null));
            SaveAllInSigleFileCommand = new DelegateCommand(o =>
            {
                bool isStringContent = _list.Where(i => i.Status == ListPointStatus.Готово).All(i => i.ResultType != "xls");
                if (isStringContent)
                {
                    try
                    {
                        StringBuilder sb = new StringBuilder();
                        foreach (var item in _list)
                        {
                            if (item.Status == ListPointStatus.Готово)
                            {
                                sb.AppendLine(TrimStringValue((string)item.ResultValue));
                            }
                        }

                        Microsoft.Win32.SaveFileDialog sfd = new Microsoft.Win32.SaveFileDialog();

                        sfd.Filter             = Strings.DialogCsvFilter;
                        sfd.DefaultExt         = ".csv";
                        sfd.AddExtension       = true;
                        sfd.FileName           = DateTime.Now.AddMonths(-1).ToString(Strings.MultipleFileNameTemplate);
                        Nullable <bool> result = sfd.ShowDialog(App.Current.MainWindow);
                        if (result == true)
                        {
                            App.Log("Сохранение всех отчётов в один файл");
                            System.IO.File.WriteAllText(sfd.FileName, sb.ToString(), Encoding.UTF8);
                        }
                    }
                    catch (Exception ex)
                    {
                        _window.ShowDialogError(ex, Strings.ErrorOnSave);
                    }
                }
            },
                                                            o => _list != null && _list.All(i => i.ResultValue != null) && _list.All(i => i.ResultType != "xls"));
            SaveCommand = new DelegateCommand(o =>
            {
                try
                {
                    ListPointWithResult point = o as ListPointWithResult;
                    if (point != null)
                    {
                        Microsoft.Win32.SaveFileDialog sfd = new Microsoft.Win32.SaveFileDialog();
                        sfd.FileName     = String.Format(Strings.SingleFileNameTemplate, point.ResultName, DateTime.Now.AddMonths(-1));
                        sfd.AddExtension = true;
                        if (point.ResultType == "xls")
                        {
                            sfd.Filter     = Strings.DialogXlsFilter;
                            sfd.DefaultExt = ".xls";
                        }
                        else
                        if (point.ResultType == "txt")
                        {
                            sfd.Filter     = Strings.DialogCsvFilter;
                            sfd.DefaultExt = ".csv";
                        }
                        else
                        {
                            sfd.Filter     = Strings.DialogTxtFilter;
                            sfd.DefaultExt = ".txt";
                        }
                        Nullable <bool> result = sfd.ShowDialog(App.Current.MainWindow);
                        if (result == true)
                        {
                            App.Log("Сохранение отчёта");
                            if (point.ResultType == "xls")
                            {
                                byte[] bytes = (byte[])point.ResultValue;
                                if (bytes != null)
                                {
                                    System.IO.File.WriteAllBytes(sfd.FileName, bytes);
                                }
                            }
                            else
                            {
                                System.IO.File.WriteAllText(sfd.FileName, TrimStringValue((string)point.ResultValue), Encoding.UTF8);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    _window.ShowDialogError(ex, Strings.ErrorOnSave);
                }
            });
            DataContext = this;
        }
        private void PrepareReport(ListPointWithResult point)
        {
            int    groupId = point.Id;
            string param   = String.Format("__invoker=undefined&RP_ID={0}&RP_NAME={1}&errorDispatch=false&dataBlock=PARAMETERS&action=GET",
                                           _selectedReport.RP_ID, _selectedReport.RP_NAME);
            string url    = @"{0}scripts/reports.asp";
            string answer = ServiceHelper.ExecuteFunctionAsync(ServiceHelper.MakeRequestAsync, url, param, true, (p) => ServiceHelper.DecodeAnswer(p)).Result;

            if (String.IsNullOrEmpty(answer) == false && answer.Contains("result=0"))
            {
                var records = Utils.ParseRecords(answer);
                if (records == null)
                {
                    System.Diagnostics.Debugger.Break();
                }

                List <RPQ> rpqs = new List <RPQ>(records.Count);
                foreach (var nvc in records)
                {
                    if (nvc.Get("COLUMN_NAME") != "GR_ID")
                    {
                        _window.ShowDialogError(Strings.InvalidReport);
                        return;
                    }
                    RPQ rpq = new RPQ();
                    for (int i = 0; i < nvc.Count; i++)
                    {
                        #region  азбор полей

                        switch (nvc.GetKey(i))
                        {
                        case "RPQ_ID":
                            rpq.RPQ_ID = nvc[i];
                            break;

                        case "RPQ_NAME":
                            rpq.RPQ_NAME = nvc[i];
                            break;

                        case "TABLE_NAME":
                            rpq.TABLE_NAME = nvc[i];
                            break;

                        case "RPQF_ID":
                            rpq.RPQF_ID = nvc[i];
                            break;

                        case "RPQO_ID":
                            rpq.RPQO_ID = nvc[i];
                            break;

                        case "RPQO_CODE":
                            rpq.RPQO_CODE = nvc[i];
                            break;

                        case "RPQF_VALUE":
                            rpq.RPQF_VALUE = nvc[i];
                            break;

                        case "FIELD_DESC":
                            rpq.FIELD_DESC = nvc[i];
                            break;

                        case "RPQF_ALLOW_EMPTY_VALUES":
                            rpq.RPQF_ALLOW_EMPTY_VALUES = nvc[i];
                            break;

                        case "DATA_TYPE":
                            rpq.DATA_TYPE = nvc[i];
                            break;
                        }

                        #endregion  азбор полей
                    }
                    rpqs.Add(rpq);
                }
                param = String.Format("__invoker=undefined&RP_ID={0}&RP_NAME={1}&errorDispatch=false&dataBlock=PREPARED_RP&action=GET",
                                      _selectedReport.RP_ID, _selectedReport.RP_NAME);
                url    = @"{0}scripts/reports.asp";
                answer = ServiceHelper.ExecuteFunctionAsync(ServiceHelper.MakeRequestAsync, url, param, true, (p) => ServiceHelper.DecodeAnswer(p)).Result;

                if (String.IsNullOrEmpty(answer) == false && answer.Contains("result=0"))
                {
                    StringBuilder sb = new StringBuilder();
                    for (int i = 0; i < rpqs.Count; i++)
                    {
                        RPQ rpq = rpqs[i];
                        sb.AppendFormat("RPQF_{0}={1}&DATA_TYPE_0_{2}={3}&RPQF_VALUE_0_{2}={1}&COLUMN_NAME_0_{2}={4}&RPQO_ID_0_{2}={5}&RPQF_ID_0_{2}={0}&",
                                        rpq.RPQF_ID,     //0
                                        groupId,         //1
                                        i,               //2
                                        rpq.DATA_TYPE,   //3
                                        rpq.COLUMN_NAME, //4
                                        rpq.RPQO_ID      //5
                                        );
                    }
                    sb.AppendFormat("RPQ_NAME_0={0}&RPQ_ID_0={1}&RPQF_COUNT_0={2}&RPQ_COUNT=1&export_to_html=0&RP_ID={3}&action=SHOW_REPORT",
                                    rpqs[0].RPQ_NAME,
                                    rpqs[0].RPQ_ID,
                                    rpqs.Count,
                                    _selectedReport.RP_ID);

                    url    = @"{0}scripts/ReportGenerator.asp";
                    answer = ServiceHelper.MakeRequestAsync(url, sb.ToString()).Result;

                    if (ServiceHelper.StatusCode == System.Net.HttpStatusCode.OK)
                    {
                        // получение имени файла

                        /*
                         * <HTML>
                         * <HEAD>
                         * <META HTTP-EQUIV=Refresh CONTENT="0;URL=../\\reports\2016\12\30\Для расчета балансов ПС до 35кВ_2016_12_30_113404_1.txt">
                         * </HEAD>
                         * </HTML>
                         */
                        Match  KeywordMatch = Regex.Match(answer, "<meta HTTP-EQUIV=Refresh content=\"([^<]*)\">", RegexOptions.IgnoreCase | RegexOptions.Multiline);
                        string metaKeywords = KeywordMatch.Groups[1].Value;
                        string file         = metaKeywords.Substring(8).Replace("../", "").Replace("\\", "/");

                        var client = new WebClient();

                        if (file.EndsWith(".txt"))
                        {
                            point.ResultValue = client.DownloadString(ServiceHelper.SiteAddress + file);
                            point.ResultType  = "txt";
                        }
                        else
                        if (file.EndsWith(".xls"))
                        {
                            point.ResultValue = client.DownloadData(ServiceHelper.SiteAddress + file);
                            point.ResultType  = "xls";
                        }
                        else
                        {
                            point.ResultValue = client.DownloadString(ServiceHelper.SiteAddress + file);
                            point.ResultType  = "unknown";
                        }
                    }
                }
            }
        }
        public GetEnergyControl(IList <ListPoint> source, Action closeed, Action canceled = null, Action <Exception> faulted = null) : this()
        {
            if (source == null || closeed == null)
            {
                throw new ArgumentNullException();
            }

            _onClosed   = closeed;
            _onCanceled = canceled;
            _onFaulted  = faulted;

            List <ListPointWithResult> list = null;

            Dialogs.IDialog dialog = _window.DialogWaitingScreen("Подготовка ...");
            dialog.Show();
            System.Threading.ThreadPool.QueueUserWorkItem(o =>
            {
                var _s = source
                         .Flatten(i => i.Items)
                         .Where(i => i.TypeCode == "SUBSTATION")
                         .OrderBy(i => i.ParentName)
                         .ThenBy(i => i.Name)
                         .ToList <ListPoint>();

                list = new List <ListPointWithResult>();
                foreach (var point in _s)
                {
                    ListPointWithResult pwr = new ListPointWithResult(point)
                    {
                        Items = null
                    };
                    var items = point.Items
                                .Flatten(i => i.Items)
                                .Where(i =>
                                       (i.ParentTypeCode == "AUXILIARY" && i.TypeCode == "ELECTRICITY" && i.EсpName == "Свои нужды") ||
                                       (i.ParentTypeCode == "SECTIONBUS" && (i.ParentName.Contains("10кВ") || i.ParentName.Contains("6кВ")) &&
                                        i.TypeCode == "ELECTRICITY" && i.EсpName == "Трансформаторы"))
                                .Select(i => new ListPointWithResult(i)
                    {
                        ParentName = pwr.ParentName, ParentTypeCode = pwr.Name
                    })
                                .ToList();

                    pwr.Items = items;

                    list.Add(pwr);
                    foreach (var item in items)
                    {
                        list.Add(item);
                    }
                }

                if (list == null || list.Count == 0)
                {
                    _window.ShowDialogWarning(Strings.EmptyList);
                    dialog.Close();
                    _onClosed();
                }
                List = new ObservableCollection <ListPointWithResult>(list);
                dialog.Close();
            });
        }