Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- namespace CRG08KDHT.ViewModel
- {
- public class CiclosViewModel : ViewModelBase
- {
- public RelayCommand AdicionarCicloCommand { get; }
- public RelayCommand AbrirSecagensCommand { get; }
- public RelayCommand AbrirRelatorioCommand { get; }
- public RelayCommand AtualizarCommand { get; }
- public RelayCommand ExcluirCommand { get; }
- public RelayCommand GerenciarProdutosCommand { get; }
- public RelayCommand FinalizarCommand { get; }
- public RelayCommand ImportarCommand { get; }
- public RelayCommand ExportarCommand { get; }
- public RelayCommand SairCommand { get; }
- public RelayCommand AbrirFiltroCommand { get; }
- public RelayCommand AplicarFiltroCommand { get; }
- public RelayCommand FecharFiltroCommand { get; }
- public RelayCommand ResetarFiltroCommand { get; }
- public RelayCommand AbrirAlterarCommand { get; }
- public RelayCommand SalvarAlterarCommand { get; }
- public RelayCommand CancelarAlterarCommand { get; }
- public ObservableCollection<Ciclo> CiclosEmAndamento { get; set; }
- public ObservableCollection<Ciclo> CiclosFinalizados { get; set; }
- public ICollectionView FilteredCiclosFinalizados
- {
- get
- {
- var source = CollectionViewSource.GetDefaultView(CiclosFinalizados);
- Filtro = FiltrosSecagensAccess.GetFiltro();
- source.Filter = (p) =>
- {
- var c = (Ciclo)p;
- var aparelhoOk = !Filtro.ApenasAparelho || c.Crg == Filtro.Aparelho;
- var dataOk = Filtro.QualquerData ||
- (Filtro.Ultimas24Horas && c.DataInicio >= DateTime.Now.AddDays(-1)) ||
- (Filtro.UltimaSemana && c.DataInicio >= DateTime.Now.AddDays(-7)) ||
- (Filtro.UltimoMes && c.DataInicio >= DateTime.Now.AddMonths(-1)) ||
- (Filtro.Personalizado && c.DataInicio >= Filtro.DataInicio && c.DataFim <= Filtro.DataFim);
- return aparelhoOk && dataOk;
- };
- return source;
- }
- }
- public ObservableCollection<Ciclo> CiclosEmAndamentoSelecionados { get; set; }
- public ObservableCollection<Ciclo> CiclosFinalizadosSelecionados { get; set; }
- public CiclosViewModel()
- {
- if (IsInDesignMode) return;
- AdicionarCicloCommand = new RelayCommand(AdicionarCiclo);
- AbrirSecagensCommand = new RelayCommand(AbrirSecagens);
- AbrirRelatorioCommand = new RelayCommand(AbrirRelatorio, CanAbrirRelatorio);
- AtualizarCommand = new RelayCommand(Atualizar, CanAtualizar);
- ExcluirCommand = new RelayCommand(Excluir, CanExcluir);
- GerenciarProdutosCommand = new RelayCommand(GerenciarProdutos);
- FinalizarCommand = new RelayCommand(Finalizar, CanFinalizar);
- ImportarCommand = new RelayCommand(Importar, CanImportar);
- ExportarCommand = new RelayCommand(Exportar, CanExportar);
- SairCommand = new RelayCommand(Sair);
- AbrirFiltroCommand = new RelayCommand(AbrirFiltro);
- AplicarFiltroCommand = new RelayCommand(AplicarFiltro);
- ResetarFiltroCommand = new RelayCommand(ResetarFiltro);
- FecharFiltroCommand = new RelayCommand(FecharFiltro);
- AbrirAlterarCommand = new RelayCommand(AbrirAlterar, CanAbrirAlterar);
- SalvarAlterarCommand = new RelayCommand(SalvarAlterar);
- CancelarAlterarCommand = new RelayCommand(CancelarAlterar);
- CiclosEmAndamentoSelecionados = new ObservableCollection<Ciclo>();
- CiclosFinalizadosSelecionados = new ObservableCollection<Ciclo>();
- CiclosEmAndamento = new ObservableCollection<Ciclo>();
- CiclosFinalizados = new ObservableCollection<Ciclo>();
- RefreshEmAndamento();
- RefreshFinalizados();
- }
- private FiltroSecagens _filtro;
- public FiltroSecagens Filtro
- {
- get => _filtro;
- set => Set(() => Filtro, ref _filtro, value);
- }
- public List<int> AparelhosDisponiveis => Enumerable.Range(1, 32).ToList();
- private bool _filtroAberto = false;
- public bool FiltroAberto
- {
- get => _filtroAberto;
- set
- {
- if (Set(() => FiltroAberto, ref _filtroAberto, value))
- {
- RaisePropertyChanged(() => OverlayAberto);
- }
- }
- }
- private string _alterarDescricaoText;
- public string AlterarDescricaoText
- {
- get => _alterarDescricaoText;
- set => Set(() => AlterarDescricaoText, ref _alterarDescricaoText, value);
- }
- private bool _alterarAberto;
- public bool AlterarAberto
- {
- get => _alterarAberto;
- set
- {
- if (Set(() => AlterarAberto, ref _alterarAberto, value))
- {
- RaisePropertyChanged(() => OverlayAberto);
- }
- }
- }
- private Ciclo _secagemEmEdicao;
- public Ciclo SecagemEmEdicao
- {
- get => _secagemEmEdicao;
- set => Set(() => SecagemEmEdicao, ref _secagemEmEdicao, value);
- }
- public bool OverlayAberto => FiltroAberto || AlterarAberto;
- public string AvisoFiltroStr
- {
- get
- {
- if (TabControlIndex == 0) return string.Empty;
- var filteredCount = FilteredCiclosFinalizados.Cast<Ciclo>().Count();
- if (CiclosFinalizados.Count == 0 || CiclosFinalizados.Count == filteredCount) return string.Empty;
- var sobra = CiclosFinalizados.Count - filteredCount;
- if (sobra > 1)
- {
- return $"{sobra} secagens ocultas devido ao filtro.";
- }
- else
- {
- return $"{sobra} secagem oculta devido ao filtro.";
- }
- }
- }
- private bool _isLoading = false;
- public bool IsLoading
- {
- get => _isLoading;
- set => Set(() => IsLoading, ref _isLoading, value);
- }
- private string _loadingText = string.Empty;
- public string LoadingText
- {
- get => _loadingText;
- set => Set(() => LoadingText, ref _loadingText, value);
- }
- private int _tabControlIndex = 0;
- public int TabControlIndex
- {
- get => _tabControlIndex;
- set
- {
- if (Set(() => TabControlIndex, ref _tabControlIndex, value))
- {
- RaisePropertyChanged(() => AvisoFiltroStr);
- }
- }
- }
- public void AdicionarCiclo()
- {
- var wnd = new SelecionarComunicacao();
- Navigator.OpenWindowAsDialog(wnd);
- if (!wnd.ViewModel.Confirmado)
- {
- return;
- }
- List<int> listaBytes;
- int crg = -1;
- if (wnd.ViewModel.IsPendrive)
- {
- var pdWindow = new SelecionarArquivoPendrive();
- Navigator.OpenWindowAsDialog(pdWindow);
- var pdVm = (SelecionarArquivoPendriveViewModel)pdWindow.DataContext;
- if (!pdVm.Confirmado) return;
- crg = pdVm.AparelhoSelecionado;
- listaBytes = File.ReadAllBytes(pdVm.ArquivoSelecionado.CaminhoCompleto).Select(b => Convert.ToInt32(b)).ToList();
- }
- else
- {
- LoadingText = "Carregando a secagem...";
- IsLoading = true;
- Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, new ThreadStart(delegate { }));
- listaBytes = CrgCommunication.PuxarSecagemDoAparelho(wnd.ViewModel.AparelhoSelecionado);
- crg = wnd.ViewModel.AparelhoSelecionado;
- IsLoading = false;
- }
- if (listaBytes == null || listaBytes.Count == 0)
- {
- MessageBox.Show(messageBoxText: "Algum erro ocorreu ao puxar a secagem!",
- caption: "Erro", button: MessageBoxButton.OK,
- icon: MessageBoxImage.Error);
- return;
- }
- var ciclo = CrgDecifrator.DecifrarSecagem(listaBytes);
- if (ciclo == null)
- {
- MessageBox.Show(messageBoxText: "Algum erro ocorreu ao puxar a secagem!",
- caption: "Erro", button: MessageBoxButton.OK,
- icon: MessageBoxImage.Error);
- return;
- }
- ciclo.Crg = crg;
- var ret = CiclosAccess.AtualizarCiclo(ciclo);
- if (ret == 0)
- {
- MessageBox.Show(messageBoxText: "Secagem já está presente!",
- caption: "", button: MessageBoxButton.OK,
- icon: MessageBoxImage.Information);
- }
- else if (ret == 1)
- {
- MessageBox.Show(messageBoxText: "Secagem atualizada com sucesso!",
- caption: "", button: MessageBoxButton.OK,
- icon: MessageBoxImage.Information);
- }
- else if (ret == 2)
- {
- var add = new AdicionarCiclo(ciclo);
- Navigator.OpenWindowAsDialog(add);
- if (((AdicionarCicloViewModel)add.DataContext).Confirmado)
- {
- CiclosAccess.SalvarCiclo(ciclo);
- MessageBox.Show(messageBoxText: "Secagem adicionada com sucesso!",
- caption: "", button: MessageBoxButton.OK,
- icon: MessageBoxImage.Information);
- }
- else
- {
- return;
- }
- }
- //var db = new CrgContext();
- //var existente = db.Ciclos.Include(c => c.DadosTratamento).FirstOrDefault(x =>
- // x.NumeroSerie == ciclo.NumeroSerie && x.NumeroSecagem == ciclo.NumeroSecagem &&
- // x.Crg == ciclo.Crg)
- // ;
- //if (existente != null)
- //{
- // if (existente.NumeroLeituras == ciclo.NumeroLeituras ||
- // existente.DadosTratamento.LeiturasTratamento.Count ==
- // ciclo.DadosTratamento.LeiturasTratamento.Count)
- // {
- // MessageBox.Show("Esta secagem já está atualizada.");
- // return;
- // }
- // else
- // {
- // ciclo.Id = existente.Id;
- // db.Ciclos.AddOrUpdate(ciclo);
- // }
- //}
- //else
- //{
- // var add = new AdicionarCiclo(ciclo);
- // Navigator.OpenWindowAsDialog(add);
- // if (((AdicionarCicloViewModel) add.DataContext).Confirmado)
- // {
- // db.Ciclos.Add(ciclo);
- // }
- // else
- // {
- // return;
- // }
- //}
- //db.SaveChanges();
- RefreshEmAndamento();
- RefreshFinalizados();
- }
- public void AbrirSecagens()
- {
- var wnd = new HistoricoSecagens();
- Navigator.OpenWindowAsDialog(wnd);
- }
- public void AbrirRelatorio()
- {
- var ciclos = TabControlIndex == 0 ? CiclosEmAndamentoSelecionados : CiclosFinalizadosSelecionados;
- if (ciclos.Count == 1)
- {
- var detalhesCiclo = new DetalhesCiclo(ciclos[0]);
- Navigator.OpenWindowAsDialog(detalhesCiclo);
- }
- else if (ciclos.Count > 1)
- {
- MessageBox.Show(messageBoxText: "Você deve ter apenas 1 ciclo selecionado para abrir o relatório.",
- caption: "", button: MessageBoxButton.OK, icon: MessageBoxImage.Information);
- }
- else
- {
- MessageBox.Show(messageBoxText: "Selecione um ciclo para abrir o relatório.",
- caption: "", button: MessageBoxButton.OK, icon: MessageBoxImage.Stop);
- }
- }
- public bool CanAbrirRelatorio()
- {
- var ciclos = TabControlIndex == 0 ? CiclosEmAndamentoSelecionados : CiclosFinalizadosSelecionados;
- return ciclos.Count == 1;
- }
- public void Atualizar()
- {
- var ciclo = CiclosEmAndamentoSelecionados.First();
- LoadingText = "Atualizando a secagem...";
- IsLoading = true;
- Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, new ThreadStart(delegate { }));
- var secagem = CrgCommunication.PuxarSecagemDoAparelho(ciclo.Crg, new Model.Items.ItemHistoricoSecagem
- {
- Crg = ciclo.Crg,
- DataInicio = ciclo.DataInicio,
- NumeroSecagem = ciclo.NumeroSecagem
- });
- if (secagem == null || secagem.Count == 0)
- {
- IsLoading = false;
- MessageBox.Show(messageBoxText: "Erro ao atualizar a secagem!",
- caption: "Erro", button: MessageBoxButton.OK,
- icon: MessageBoxImage.Error);
- return;
- }
- var novoCiclo = CrgDecifrator.DecifrarSecagem(secagem);
- novoCiclo.Crg = ciclo.Crg;
- if (novoCiclo == null)
- {
- IsLoading = false;
- MessageBox.Show(messageBoxText: "Erro ao atualizar a secagem!",
- caption: "Erro", button: MessageBoxButton.OK,
- icon: MessageBoxImage.Error);
- return;
- }
- var ret = CiclosAccess.AtualizarCiclo(novoCiclo);
- if (ret == 0)
- {
- IsLoading = false;
- MessageBox.Show(messageBoxText: "A secagem já está atualizada!",
- caption: "", button: MessageBoxButton.OK, icon: MessageBoxImage.Information);
- return;
- }
- else if (ret == 1)
- {
- IsLoading = false;
- MessageBox.Show(messageBoxText: "Secagem atualizada com sucesso!",
- caption: "", button: MessageBoxButton.OK, icon: MessageBoxImage.Information);
- }
- else if (ret == 2)
- {
- IsLoading = false;
- MessageBox.Show(messageBoxText: "Secagem não encontrada no aparelho!",
- caption: "Erro", button: MessageBoxButton.OK,
- icon: MessageBoxImage.Error);
- return;
- }
- RefreshEmAndamento();
- RefreshFinalizados();
- }
- public bool CanAtualizar()
- {
- return TabControlIndex == 0 && CiclosEmAndamentoSelecionados.Count == 1;
- }
- public void Excluir()
- {
- var ciclos = TabControlIndex == 0 ? CiclosEmAndamentoSelecionados : CiclosFinalizadosSelecionados;
- if (MessageBox.Show($"Deseja realmente excluir a secagem selecionada?",
- "Tem certeza?",
- MessageBoxButton.YesNo,
- MessageBoxImage.Question) != MessageBoxResult.Yes)
- {
- return;
- }
- var db = new CrgContext();
- var ciclosId = ciclos.Select(x => x.Id).ToList();
- db.Ciclos.RemoveRange(db.Ciclos.Where(c => ciclosId.Contains(c.Id))
- .Include(c => c.LeiturasCiclo)
- .Include(c => c.DadosTratamento)
- .Include(c => c.DadosTratamento.LeiturasTratamento)
- .Include(c => c.Programa)
- .Include(c => c.Programa.Fases)
- .Include(c => c.Interrupcoes)
- .Include(c => c.Produtos));
- db.SaveChanges();
- RefreshEmAndamento();
- RefreshFinalizados();
- }
- public bool CanExcluir()
- {
- var ciclos = TabControlIndex == 0 ? CiclosEmAndamentoSelecionados : CiclosFinalizadosSelecionados;
- return ciclos.Count >= 1;
- }
- public void GerenciarProdutos()
- {
- Navigator.OpenWindowAsDialog(new GerenciarGenerico());
- }
- public void Finalizar()
- {
- var ciclos = CiclosEmAndamentoSelecionados;
- if (MessageBox.Show("Deseja enviar a secagem selecionada para os ciclos finalizados?",
- "Tem certeza?",
- MessageBoxButton.YesNo,
- MessageBoxImage.Question) != MessageBoxResult.Yes)
- {
- return;
- }
- var db = new CrgContext();
- foreach (var ciclo in ciclos)
- {
- ciclo.Finalizado = true;
- db.Ciclos.AddOrUpdate(ciclo);
- }
- db.SaveChanges();
- RefreshEmAndamento();
- RefreshFinalizados();
- }
- public bool CanFinalizar()
- {
- return TabControlIndex == 0 && CiclosEmAndamentoSelecionados.Count >= 1;
- }
- public void Importar()
- {
- var od = new OpenFileDialog()
- {
- Filter = "*.CRG08KDHTsec | *.CRG08KDHTsec"
- };
- od.ShowDialog(Navigator.GetWindowByDataContext(this));
- if (string.IsNullOrWhiteSpace(od.FileName) || !od.FileName.Contains(".CRG08KDHTsec"))
- {
- MessageBox.Show(messageBoxText: "Nome do arquivo inválido!",
- caption: "Inválido!", button: MessageBoxButton.OK,
- icon: MessageBoxImage.Error);
- return;
- }
- var buff = File.ReadAllBytes(od.FileName);
- var listaCiclos = ObjectConverter.ByteArrayToObject(buff);
- if (listaCiclos != null && listaCiclos is List<Ciclo> lista)
- {
- var msgs = new List<string>();
- foreach (var ciclo in lista)
- {
- if (MessageBox.Show($"Deseja incluir a secagem {ciclo.NumeroSecagem} do aparelho {ciclo.Crg} com período de {ciclo.DataInicio:dd/MM/yyyy HH:mm} até {ciclo.DataFim:dd/MM/yyyy HH:mm}?",
- "Inclusão", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
- {
- ciclo.Id = -1;
- var atRes = CiclosAccess.AtualizarCiclo(ciclo);
- if (atRes == 0)
- {
- msgs.Add($"Secagem {ciclo.NumeroSecagem} ({ciclo.DataInicio:dd/MM/yyyy HH:mm} até {ciclo.DataFim:dd/MM/yyyy HH:mm}) já está atualizada!");
- }
- if (atRes == 1)
- {
- msgs.Add($"Secagem {ciclo.NumeroSecagem} ({ciclo.DataInicio:dd/MM/yyyy HH:mm} até {ciclo.DataFim:dd/MM/yyyy HH:mm}) atualizada com sucesso!");
- continue;
- }
- if (atRes == 2)
- {
- CiclosAccess.SalvarCiclo(ciclo);
- msgs.Add($"Secagem {ciclo.NumeroSecagem} ({ciclo.DataInicio:dd/MM/yyyy HH:mm} até {ciclo.DataFim:dd/MM/yyyy HH:mm}) adicionada com sucesso!");
- }
- }
- }
- if (msgs.Count > 0)
- {
- var str = "Logs de importação:";
- foreach (var msg in msgs)
- {
- str += Environment.NewLine + msg;
- }
- MessageBox.Show(str);
- RefreshEmAndamento();
- RefreshFinalizados();
- }
- }
- else
- {
- MessageBox.Show(messageBoxText: "Arquivo inválido!",
- caption: "Erro", button: MessageBoxButton.OK,
- icon: MessageBoxImage.Error);
- }
- }
- public bool CanImportar()
- {
- return true;
- }
- public void Exportar()
- {
- var od = new SaveFileDialog
- {
- Filter = "*.CRG08KDHTsec|*.CRG08KDHTsec"
- };
- od.ShowDialog(Navigator.GetWindowByDataContext(this));
- if (string.IsNullOrWhiteSpace(od.FileName) || !od.FileName.Contains(".CRG08KDHTsec"))
- {
- return;
- }
- List<Ciclo> lista;
- if (TabControlIndex == 0)
- {
- lista = CiclosEmAndamentoSelecionados.ToList();
- }
- else
- {
- lista = CiclosFinalizadosSelecionados.ToList();
- }
- var CiclosCompletos = new List<Ciclo>();
- foreach(var Ciclo in lista)
- {
- var CicloCompleto = CiclosAccess.RetornarCiclo(Ciclo.Id);
- if(CicloCompleto != null)
- {
- CiclosCompletos.Add(CicloCompleto);
- }
- }
- var bArray = ObjectConverter.ObjectToByteArray(CiclosCompletos);
- File.WriteAllBytes(od.FileName, bArray);
- if (lista.Count == 1)
- {
- MessageBox.Show(messageBoxText: "Secagem exportada com sucesso!",
- caption: "", button: MessageBoxButton.OK, icon: MessageBoxImage.Information);
- }
- //else
- //{
- // MessageBox.Show("Secagens exportadas com sucesso!");
- //}
- }
- public bool CanExportar()
- {
- if (TabControlIndex == 0)
- {
- return CiclosEmAndamentoSelecionados.Count >= 1;
- }
- else
- {
- return CiclosFinalizadosSelecionados.Count >= 1;
- }
- }
- public void Sair()
- {
- Navigator.CloseWindowByDataContext(this);
- }
- public void AbrirFiltro()
- {
- FiltroAberto = true;
- }
- public void AplicarFiltro()
- {
- FiltrosSecagensAccess.SalvarFiltro(Filtro);
- RefreshFiltro();
- FiltroAberto = false;
- }
- public void ResetarFiltro()
- {
- FiltrosSecagensAccess.SalvarFiltro(new FiltroSecagens
- {
- ApenasAparelho = false,
- Aparelho = 1,
- DataInicio = DateTime.Now,
- DataFim = DateTime.Now,
- QualquerData = true
- });
- RefreshFiltro();
- FiltroAberto = false;
- }
- public void RefreshFiltro()
- {
- RaisePropertyChanged(() => Filtro);
- FilteredCiclosFinalizados.Refresh();
- RaisePropertyChanged(() => AvisoFiltroStr);
- }
- public void FecharFiltro()
- {
- FiltroAberto = false;
- RaisePropertyChanged(() => Filtro);
- }
- public void AbrirAlterar()
- {
- SecagemEmEdicao = CiclosEmAndamentoSelecionados.First();
- AlterarDescricaoText = SecagemEmEdicao.Descricao;
- AlterarAberto = true;
- var wnd = Navigator.GetWindowByDataContext(this) as Ciclos;
- FocusManager.SetFocusedElement(wnd, wnd.TxtAlterarDescricao);
- wnd.TxtAlterarDescricao.CaretIndex = wnd.TxtAlterarDescricao.Text.Length-1;
- }
- public bool CanAbrirAlterar()
- {
- return CiclosEmAndamentoSelecionados.Count == 1 && TabControlIndex == 0;
- }
- public void SalvarAlterar()
- {
- CiclosAccess.AtualizarDescricao(SecagemEmEdicao, AlterarDescricaoText);
- RefreshEmAndamento();
- AlterarAberto = false;
- }
- public void CancelarAlterar()
- {
- AlterarAberto = false;
- }
- public void RefreshEmAndamento()
- {
- CiclosEmAndamento.Clear();
- var db = new CrgContext();
- var ciclosEmAndamento = db.Ciclos.Where(x => x.Finalizado == false)
- .OrderBy(x => x.Crg)
- .ThenBy(x => x.DataInicio).ToList();
- foreach (var ciclo in ciclosEmAndamento)
- {
- CiclosEmAndamento.Add(ciclo);
- }
- }
- public void RefreshFinalizados()
- {
- CiclosFinalizados.Clear();
- var db = new CrgContext();
- var ciclosFinalizados = db.Ciclos.Where(x => x.Finalizado)
- .OrderBy(x => x.Crg)
- .ThenBy(x => x.DataInicio).ToList();
- foreach (var ciclo in ciclosFinalizados)
- {
- CiclosFinalizados.Add(ciclo);
- }
- RefreshFiltro();
- RaisePropertyChanged(() => AvisoFiltroStr);
- }
- }
- }
Add Comment
Please, Sign In to add comment