public EditEmergencySituationControlVM(Model.IEmergencySituationRepositiry _emergencySituationRepositiry,
                                               Model.IDutyOfficerRepository _dutyOfficerRepository, Model.IVechicleRepository _vechicleRepository)
        {
            vechicleRepository           = _vechicleRepository;
            emergencySituationRepositiry = _emergencySituationRepositiry;
            dutyOfficerRepository        = _dutyOfficerRepository;
            Messenger.Default.Register <Model.DutyOfficer>(this, HandleDutyOfficer);
            Messenger.Default.Register <int>(this, HandleEmergencyID);
            Vechicle2Emergency = new ObservableCollection <Model.Vechicle2Emergency>();
            SuperiorOfficers   = new ObservableCollection <Model.SuperiorOfficer>();

            NeighborhoodList = new ObservableCollection <string>();
            FillOutNeighborhoodList();

            CurrentVechicle2Emergency = new Model.Vechicle2Emergency();
            RegionList = new List <string> {
                "Брестская область", "Витебская область", "Гомельская область", "Гродненская область", "Минская область", "Могилевская область", "г.Минск"
            };
            KindEmergencyList = new List <string> {
                "Загорание частного жилого дома",
                "Загорание частного нежилого дома",
                "Загорание дачного дома",
                "Загорание бытовок,вагончиков",
                "Загорание в гараже",
                "Загорание в квартире",
                "Загорание в административном здании",
                "Загорание на промышленном предприятии",
                "Загорание частного жилого дома",
                "Загорание на железнодорожном транспорте",
                "Загорание в сельскохозяйственной отрасли", "Загорание в учреждении образования",
                "Загорание в гостиницах, общежитиях",
                "Загорание автомобиля",
                "Загорание леса, травы и кустарников",
                "Загорание торфяника",
                "Загорание полигона ТБО",
                "Взрыв", "Обрушение",
                "ДТП",
                "Авария ЖКХ",
                "Происшествие по ЛС",
                "Прочее"
            };



            SelectionRegionCommand = new RelayCommand(() =>
            {
                switch (EmergencySituation.Region)
                {
                case "Брестская область":
                    {
                        NeighborhoodList.Clear();
                        NeighborhoodList.Add("Барановичский район");
                        NeighborhoodList.Add("Берёзовский район");
                        NeighborhoodList.Add("Брестский район");
                        NeighborhoodList.Add("Ганцевичский район");
                        NeighborhoodList.Add("Дрогичинский район");
                        NeighborhoodList.Add("Жабинковский район");
                        NeighborhoodList.Add("Ивановский район");
                        NeighborhoodList.Add("Ивацевичский район");
                        NeighborhoodList.Add("Каменецкий район");
                        NeighborhoodList.Add("Кобринский район");
                        NeighborhoodList.Add("Лунинецкий район");
                        NeighborhoodList.Add("Ляховичский район");
                        NeighborhoodList.Add("Малоритский район");
                        NeighborhoodList.Add("Пинский район");
                        NeighborhoodList.Add("Пружанский район");
                        NeighborhoodList.Add("Столинский район");
                        NeighborhoodList.Add("г.Брест");
                    }
                    break;

                case "Витебская область":
                    {
                        NeighborhoodList.Clear();
                        NeighborhoodList.Add("Бешенковичский район");
                        NeighborhoodList.Add("Браславский район");
                        NeighborhoodList.Add("Верхнедвинский район");
                        NeighborhoodList.Add("Витебский район");
                        NeighborhoodList.Add("Глубокский район");
                        NeighborhoodList.Add("Городокский район");
                        NeighborhoodList.Add("Докшицкий район");
                        NeighborhoodList.Add("Дубровенский район");
                        NeighborhoodList.Add("Лепельский район");
                        NeighborhoodList.Add("Лиозненский район");
                        NeighborhoodList.Add("Миорский район");
                        NeighborhoodList.Add("Оршанский район");
                        NeighborhoodList.Add("Полоцкий район");
                        NeighborhoodList.Add("Поставский район");
                        NeighborhoodList.Add("Россонский район");
                        NeighborhoodList.Add("Сенненский район");
                        NeighborhoodList.Add("Толочинский район");
                        NeighborhoodList.Add("Ушачский район");
                        NeighborhoodList.Add("Чашникский район");
                        NeighborhoodList.Add("Шарковщинский район");
                        NeighborhoodList.Add("Шумилинский район");
                        NeighborhoodList.Add("г.Витебск");
                    }
                    break;

                case "Гомельская область":
                    {
                        NeighborhoodList.Clear();
                        NeighborhoodList.Add("Брагинский район");
                        NeighborhoodList.Add("Буда-Кошелевский район");
                        NeighborhoodList.Add("Ветковский район");
                        NeighborhoodList.Add("Гомельский район");
                        NeighborhoodList.Add("Добрушский район");
                        NeighborhoodList.Add("Ельский район");
                        NeighborhoodList.Add("Житковичский район");
                        NeighborhoodList.Add("Жлобинский район");
                        NeighborhoodList.Add("Калинковичский район");
                        NeighborhoodList.Add("Кормянский район");
                        NeighborhoodList.Add("Лельчицкий район");
                        NeighborhoodList.Add("Лоевский район");
                        NeighborhoodList.Add("Мозырский район");
                        NeighborhoodList.Add("Наровлянский район");
                        NeighborhoodList.Add("Октябрьский район");
                        NeighborhoodList.Add("Петриковский район");
                        NeighborhoodList.Add("Речицкий район");
                        NeighborhoodList.Add("Рогачевский район");
                        NeighborhoodList.Add("Светлогорский район");
                        NeighborhoodList.Add("Хойникский район");
                        NeighborhoodList.Add("Чечерский район");
                        NeighborhoodList.Add("г.Гомель");
                    }
                    break;

                case "Гродненская область":
                    {
                        NeighborhoodList.Clear();
                        NeighborhoodList.Add("Берестовицкий район");
                        NeighborhoodList.Add("Волковысский район");
                        NeighborhoodList.Add("Вороновский район");
                        NeighborhoodList.Add("Гродненский район");
                        NeighborhoodList.Add("Дятловский район");
                        NeighborhoodList.Add("Зельвенский район");
                        NeighborhoodList.Add("Ивьевский район");
                        NeighborhoodList.Add("Кореличский район");
                        NeighborhoodList.Add("Лидский район");
                        NeighborhoodList.Add("Мостовский район");
                        NeighborhoodList.Add("Новогрудский район");
                        NeighborhoodList.Add("Островецкий район");
                        NeighborhoodList.Add("Ошмянский район");
                        NeighborhoodList.Add("Свислочский район");
                        NeighborhoodList.Add("Слонимский район");
                        NeighborhoodList.Add("Сморгонский район");
                        NeighborhoodList.Add("Щучинский район");
                        NeighborhoodList.Add("г.Гродно");
                    }
                    break;

                case "Минская область":
                    {
                        NeighborhoodList.Clear();
                        NeighborhoodList.Add("Березинский район");
                        NeighborhoodList.Add("Борисовский район");
                        NeighborhoodList.Add("Вилейский район");
                        NeighborhoodList.Add("Воложинский район");
                        NeighborhoodList.Add("Дзержинский район");
                        NeighborhoodList.Add("Клецкий район");
                        NeighborhoodList.Add("Копыльский район");
                        NeighborhoodList.Add("Крупский район");
                        NeighborhoodList.Add("Логойский район");
                        NeighborhoodList.Add("Любанский район");
                        NeighborhoodList.Add("Минский район");
                        NeighborhoodList.Add("Молодечненский район");
                        NeighborhoodList.Add("Мядельский район");
                        NeighborhoodList.Add("Несвижский район");
                        NeighborhoodList.Add("Пуховичский район");
                        NeighborhoodList.Add("Слуцкий район");
                        NeighborhoodList.Add("Смолевичский район");
                        NeighborhoodList.Add("Солигорский район");
                        NeighborhoodList.Add("Стародорожский район");
                        NeighborhoodList.Add("Столбцовский район");
                        NeighborhoodList.Add("Узденский район");
                        NeighborhoodList.Add("Червенский район");
                    }
                    break;

                case "Могилевская область":
                    {
                        NeighborhoodList.Clear();
                        NeighborhoodList.Add("Белыничский район");
                        NeighborhoodList.Add("Бобруйский район");
                        NeighborhoodList.Add("Быховский район");
                        NeighborhoodList.Add("Глусский район");
                        NeighborhoodList.Add("Горецкий район");
                        NeighborhoodList.Add("Дрибинский район");
                        NeighborhoodList.Add("Кировский район");
                        NeighborhoodList.Add("Климовичский район");
                        NeighborhoodList.Add("Кличевский район");
                        NeighborhoodList.Add("Костюковичский район");
                        NeighborhoodList.Add("Краснопольский район");
                        NeighborhoodList.Add("Кричевский район");
                        NeighborhoodList.Add("Круглянский район");
                        NeighborhoodList.Add("Могилевский район");
                        NeighborhoodList.Add("Мстиславский район");
                        NeighborhoodList.Add("Осиповичский район");
                        NeighborhoodList.Add("Славгородский район");
                        NeighborhoodList.Add("Хотимский район");
                        NeighborhoodList.Add("Чаусский район");
                        NeighborhoodList.Add("Чериковский район");
                        NeighborhoodList.Add("Шкловский район");
                        NeighborhoodList.Add("г.Могилев");
                    }
                    break;

                case "г.Минск":
                    {
                        NeighborhoodList.Clear();
                        NeighborhoodList.Add("Заводской район");
                        NeighborhoodList.Add("Ленинский район");
                        NeighborhoodList.Add("Московский район");
                        NeighborhoodList.Add("Октябрьский район");
                        NeighborhoodList.Add("Партизанский район");
                        NeighborhoodList.Add("Первомайский район");
                        NeighborhoodList.Add("Советский район");
                        NeighborhoodList.Add("Фрунзенский район");
                        NeighborhoodList.Add("Центральный район");
                    }
                    break;
                }
            });
            SaveCommand = new RelayCommand(() =>
            {
                try
                {
                    MyMessageBox _myMessageBox = new MyMessageBox();

                    if (checkString != FillCheckStringFromDB(EmergencyID))
                    {
                        Messenger.Default.Send("Информация о ЧС была обновлена.\nОткройте заново для редактирования\nактуальных сведений.");
                        _myMessageBox.Show();
                    }

                    else
                    {
                        EmergencySituation.EditLog += $"\n {DateTime.Now.ToShortDateString()} {DateTime.Now.ToString("HH:mm:ss")} редактировал {DutyOfficer.NameDutyOfficer}";
                        emergencySituationRepositiry.EditEmergency(EmergencySituation, SuperiorOfficers, Vechicle2Emergency, ReceivedMessage, Victim);
                        DialogWindowVM.CloseDialogWindow();
                    }
                }
                catch (Exception)
                {
                    MyMessageBox _myMessageBox = new MyMessageBox();
                    Messenger.Default.Send("Проверьте правильность \nвведенных данных");
                    _myMessageBox.Show();
                }
            });
            CancelCommand = new RelayCommand(() =>
            {
                DialogWindowVM.CloseWindow();
            });
            AddRowCommand = new RelayCommand(() =>
            {
                Vechicle2Emergency.Add(new Model.Vechicle2Emergency());
                IsButtonMinusEnable = true;
            });
            AddSpecialReportCommand = new RelayCommand(() =>
            {
                OpenFileDialog saveFileDialog = new OpenFileDialog();
                saveFileDialog.Filter         = "Text files (*.doc,*.docx)|*.doc;*.docx|All files (*.*)|*.*";
                if (saveFileDialog.ShowDialog() == true)
                {
                    PathSpecialReport                = Path.GetFileName(saveFileDialog.FileName);
                    IsButtonDeleteReportEnable       = true;
                    EmergencySituation.SpecialReport = File.ReadAllBytes(saveFileDialog.FileName);
                }
            });

            DeleteRowCommand = new RelayCommand(() =>
            {
                Vechicle2Emergency.Remove(CurrentVechicle2Emergency);
                if (Vechicle2Emergency.Count == 0)
                {
                    IsButtonMinusEnable = false;
                }
            });
            CheckedSuperiorOfficerCommand = new RelayCommand(() =>
            {
                CurrentSuperiorOfficer.StatusOfReport = true;
                string timeReport = DateTime.Now.ToString("HH:mm:ss");
                CurrentSuperiorOfficer.TimeReport = new TimeSpan(int.Parse(timeReport.Split(':')[0]),    // hours
                                                                 int.Parse(timeReport.Split(':')[1]), int.Parse(timeReport.Split(':')[2]));
            });
            UnCheckedSuperiorOfficerCommand = new RelayCommand(() =>
            {
                CurrentSuperiorOfficer.StatusOfReport = false;
                CurrentSuperiorOfficer.TimeReport     = null;
            });
            UnLoadedCommand = new RelayCommand(() =>
            {
                ViewModelLocator.Cleanup();
            });
            OpenSpecialReportCommand = new RelayCommand(() =>
            {
                if (PathSpecialReport != "Ссылка на документ отсутствует")
                {
                    string fileName = PathSpecialReport;
                    var bytes       = EmergencySituation.SpecialReport;
                    try
                    {
                        using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None))
                        {
                            foreach (var b in bytes)
                            {
                                fs.WriteByte(b);
                            }
                        }
                        Process prc            = new Process();
                        prc.StartInfo.FileName = fileName;
                        //prc.EnableRaisingEvents = true;
                        //prc.Exited += Prc_Exited;
                        prc.Start();
                    }
                    catch (Exception)
                    {
                        MyMessageBox _myMessageBox = new MyMessageBox();
                        Messenger.Default.Send("Данный файл уже открыт");
                        _myMessageBox.Show();
                    }
                }
            });
            DeleteSpecialReportCommand = new RelayCommand(() =>
            {
                PathSpecialReport                = "Ссылка на документ отсутствует";
                IsButtonDeleteReportEnable       = false;
                EmergencySituation.SpecialReport = null;
            });
        }
Exemplo n.º 2
0
        public MainViewModel(Model.IDutyOfficerRepository _dutyOfficerRepository, Model.IReportRepository _reportRepository, Model.IEmergencySituationRepositiry _emergencySituationRepositiry)
        {
            int i = 0;

            emergencySituationRepositiry = _emergencySituationRepositiry;
            ValueKey                    = new ObservableCollection <KeyValuePair <string, int> >();
            EmergencySituations         = new ObservableCollection <Model.EmergencySituation>();
            EmergenciesInfoByRegionList = new ObservableCollection <KeyValuePair <string, int> >();
            FillOutEmergencySituationsCollection();
            FillOutEmergenciesInfoByRegionList();
            FillOutStatusBarInfo();

            reportRepository      = _reportRepository;
            IsEditEmergencyEnable = false;
            if ((Report = reportRepository.GetByDate(selectedDate)) != null)
            {
                IsAddReportEnable    = false;
                IsDeleteReportEnable = true;
            }
            else
            {
                IsAddReportEnable    = true;
                IsDeleteReportEnable = false;
            }

            Messenger.Default.Register <Model.DutyOfficer>(this, HandleDutyOfficer);
            dutyOfficerRepository = _dutyOfficerRepository;
            timer          = new DispatcherTimer();
            timer.Interval = TimeSpan.FromSeconds(1.0);
            Task taskShowTime = new Task(
                () =>
            {
                timer.Start();
                timer.Tick += (s, e) =>
                {
                    i++;
                    if (i % 180 == 0) //каждые 3 минуты обновляются данные из бд
                    {
                        EmergencySituations.Clear();
                        FillOutEmergencySituationsCollection();
                    }
                    DateTime datetime = DateTime.Now;
                    Time = datetime.ToString("HH:mm:ss");
                };
            });

            taskShowTime.Start();
            ChangeUserCommand = new RelayCommand(() =>
            {
                AuthenticationControl _authenticationControl = new AuthenticationControl();
                DialogWindow _dialogWindow = new DialogWindow(_authenticationControl);
                foreach (Window window in Application.Current.Windows)
                {
                    if ((window as MainWindow) != null)
                    {
                        window.Close();
                    }
                }
                _dialogWindow.Show();
            });
            UserSettingCommand = new RelayCommand(() =>
            {
                UserSettingControl _userSettingControl = new UserSettingControl();
                DialogWindow _dialogWindow             = new DialogWindow(_userSettingControl);
                Messenger.Default.Send(CurrentDutyOfficer);
                _dialogWindow.ShowDialog();
            });
            AddEmergencyCommand = new RelayCommand(() =>
            {
                EmergencySituationControl _emergencySituationControl = new EmergencySituationControl();
                DialogWindow _dialogWindow = new DialogWindow(_emergencySituationControl);
                Messenger.Default.Send(CurrentDutyOfficer);
                Messenger.Default.Send(SelectedDate);
                if ((_dialogWindow.ShowDialog()) == true)
                {
                    EmergencySituations.Clear();
                    FillOutEmergencySituationsCollection();
                }
            });
            EditEmergencyCommand = new RelayCommand(() =>
            {
                EditEmergencySituationControl _editEmergencySituationControl = new EditEmergencySituationControl();
                DialogWindow _dialogWindow = new DialogWindow(_editEmergencySituationControl);
                Messenger.Default.Send(CurrentDutyOfficer);
                Messenger.Default.Send(CurrentEmergency.EmergencyID);
                if ((_dialogWindow.ShowDialog()) == true)
                {
                    EmergencySituations.Clear();
                    FillOutEmergencySituationsCollection();
                }
            });
            AddReportCommand = new RelayCommand(() =>
            {
                OpenFileDialog saveFileDialog = new OpenFileDialog();
                saveFileDialog.Filter         = "Text files (*.doc,*.docx)|*.doc;*.docx|All files (*.*)|*.*";
                if (saveFileDialog.ShowDialog() == true)
                {
                    pathReport          = Path.GetFileName(saveFileDialog.FileName);
                    Report              = new Model.Report();
                    Report.Report1      = File.ReadAllBytes(saveFileDialog.FileName);
                    Report.DateOfReport = SelectedDate;
                    reportRepository.AddReport(Report);
                    IsAddReportEnable    = false;
                    IsDeleteReportEnable = true;
                }
            });
            OpenReportCommand = new RelayCommand(() =>
            {
                pathReport = $"Сводка за {selectedDate.Date.ToShortDateString()} сутки.doc";

                var bytes = Report.Report1;
                try
                {
                    using (FileStream fs = new FileStream(pathReport, FileMode.Create, FileAccess.Write, FileShare.None))
                    {
                        foreach (var b in bytes)
                        {
                            fs.WriteByte(b);
                        }
                    }
                    Process prc            = new Process();
                    prc.StartInfo.FileName = pathReport;
                    //prc.EnableRaisingEvents = true;
                    //prc.Exited += Prc_Exited;
                    prc.Start();
                }
                catch (Exception)
                {
                    MyMessageBox _myMessageBox = new MyMessageBox();
                    Messenger.Default.Send("Данный файл уже открыт");
                    _myMessageBox.Show();
                }
            });
            ReadXMLDocCommand = new RelayCommand(() =>
            {
                StreamWriter fs = new StreamWriter("XML документ.txt", false, Encoding.GetEncoding(1251));
                fs.Write(emergencySituationRepositiry.ReadXMLDoc());
                Process prc            = new Process();
                prc.StartInfo.FileName = "XML документ.txt";
                prc.Start();
            });
            DeleteReportCommand = new RelayCommand(() =>
            {
                reportRepository.DeleteReport(SelectedDate);
                IsAddReportEnable    = true;
                IsDeleteReportEnable = false;
            });
            SelectedDateCommand = new RelayCommand(() =>
            {
                if ((Report = reportRepository.GetByDate(SelectedDate)) != null)
                {
                    IsAddReportEnable    = false;
                    IsDeleteReportEnable = true;
                }
                else
                {
                    IsAddReportEnable    = true;
                    IsDeleteReportEnable = false;
                }
                EmergencySituations.Clear();
                FillOutEmergencySituationsCollection();
            });
            SelectionChangedDataGridCommand = new RelayCommand(() =>
            {
                if (CurrentEmergency == null)
                {
                    IsEditEmergencyEnable = false;
                }
                else
                {
                    IsEditEmergencyEnable = true;
                }
            });
            UnLoadedCommand = new RelayCommand(() =>
            {
                string[] docList = Directory.GetFiles(Directory.GetCurrentDirectory(), "*.doc");
                foreach (var f in docList)
                {
                    try
                    {
                        File.Delete(f);
                    }
                    catch (IOException)
                    {
                        continue;
                    }
                }
                ViewModelLocator.Cleanup();
            });
            DeleteEmergencyCommand = new RelayCommand(() =>
            {
                emergencySituationRepositiry.DeleteEmergencySituation(CurrentEmergency.EmergencyID);
                EmergencySituations.Clear();
                FillOutEmergencySituationsCollection();
            });
            AboutProgrammCommand = new RelayCommand(() =>
            {
                MyMessageBox _myMessageBox = new MyMessageBox();
                Messenger.Default.Send($"Программное средство \nУчет оперативной информации \nо чрезвычайных ситуациях.\nАвтор Северина Н.И.");
                _myMessageBox.Show();
            });
            WriteXMLDocCommand = new RelayCommand(() =>
            {
                emergencySituationRepositiry.WriteXMLDoc();
                MyMessageBox _myMessageBox = new MyMessageBox();
                Messenger.Default.Send($"Информация о ЧС записана в\nEmergencySituations.xml документ");
                _myMessageBox.Show();
            });
        }