using Agger.Registro; using Gestor.Application.Actions; using Gestor.Application.Drawers; using Gestor.Application.Helpers; using Gestor.Application.Servicos; using Gestor.Application.Servicos.Ferramentas; using Gestor.Application.Servicos.Generic; using Gestor.Application.Servicos.Seguros; using Gestor.Application.ViewModels; using Gestor.Application.ViewModels.Command; using Gestor.Application.ViewModels.Generic; using Gestor.Common.Security; using Gestor.Common.Validation; using Gestor.Model.API; using Gestor.Model.Common; using Gestor.Model.Domain.Common; using Gestor.Model.Domain.Configuracoes; using Gestor.Model.Domain.Ferramentas; using Gestor.Model.Domain.Generic; using Gestor.Model.Domain.Seguros; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Linq; using System.Net.Http; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Input; namespace Gestor.Application.ViewModels.Seguros { public class ClienteViewModel : BaseSegurosViewModel { private const int NumeroMaximoCadastros = 9; private readonly ClienteServico _servico; private const string AddCentralSegurado = "ADICIONAR CENTRAL SEGURADO"; private const string UpdateCentralSegurado = "ALTERAR DADOS/SENHA CENTRAL SEGURADO"; private bool _visibilityLogAntigo = Recursos.Configuracoes.Any(new Func((ConfiguracaoSistema x) => x.get_Configuracao() == 22)); private ObservableCollection _telefones = new ObservableCollection(); private ObservableCollection _emails = new ObservableCollection(); private ObservableCollection _enderecos = new ObservableCollection(); private ObservableCollection _contatos = new ObservableCollection(); private ObservableCollection _vinculos = new ObservableCollection(); private Cliente _vinculo; private bool _isLoading; private bool _clienteExcluido; private DateTime? _nascimentoCliente; private DateTime? _habilitaCliente; private DateTime? _vencimentoHabCliente; private DateTime? _expedicaoCliente; private Cliente _selectedCliente; private string _fieldNascimento = "NASCIMENTO"; private string _fieldDocumento = "CPF"; private Visibility _visibilityJuridica = Visibility.Collapsed; private Visibility _visibilityFisica = Visibility.Collapsed; private bool _enableAddTelephone = true; private bool _enableAddAddress = true; private bool _enableAddEmail = true; private bool _enableAddContact = true; private string _profissaoText; private string _atividadeText; private bool _saving; private ObservableCollection _origens; private OrigemCliente _selectedOrigem; public Visibility AddUsuarioCentralSeguradoVisibility { get; set; } = (string.IsNullOrEmpty(Connection.UrlCentralSegurado) ? Visibility.Collapsed : Visibility.Visible); public string AtividadeText { get { return this._atividadeText; } set { this._atividadeText = value; base.OnPropertyChanged("AtividadeText"); } } public bool ClienteExcluido { get { return this._clienteExcluido; } set { this._clienteExcluido = value; base.OnPropertyChanged("ClienteExcluido"); } } private Cliente ClienteSelecionado { get; set; } public ICommand CommandAddUsuarioCentralSegurado { get; set; } public ObservableCollection Contatos { get { return this._contatos; } set { this._contatos = value; base.OnPropertyChanged("Contatos"); } } public ObservableCollection Emails { get { return this._emails; } set { this._emails = value; base.OnPropertyChanged("Emails"); } } public bool EnableAddAddress { get { return this._enableAddAddress; } set { this._enableAddAddress = value; base.OnPropertyChanged("EnableAddAddress"); } } public bool EnableAddContact { get { return this._enableAddContact; } set { this._enableAddContact = value; base.OnPropertyChanged("EnableAddContact"); } } public bool EnableAddEmail { get { return this._enableAddEmail; } set { this._enableAddEmail = value; base.OnPropertyChanged("EnableAddEmail"); } } public bool EnableAddTelephone { get { return this._enableAddTelephone; } set { this._enableAddTelephone = value; base.OnPropertyChanged("EnableAddTelephone"); } } public ObservableCollection Enderecos { get { return this._enderecos; } set { this._enderecos = value; base.OnPropertyChanged("Enderecos"); } } public DateTime? ExpedicaoCliente { get { return this._expedicaoCliente; } set { this._expedicaoCliente = value; base.OnPropertyChanged("ExpedicaoCliente"); } } public string FieldDocumento { get { return this._fieldDocumento; } set { this._fieldDocumento = value; base.OnPropertyChanged("FieldDocumento"); } } public string FieldNascimento { get { return this._fieldNascimento; } set { this._fieldNascimento = value; base.OnPropertyChanged("FieldNascimento"); } } public DateTime? HabilitaCliente { get { return this._habilitaCliente; } set { this._habilitaCliente = value; base.OnPropertyChanged("HabilitaCliente"); } } private bool Invoke { get; } private bool IsJuridica { get; set; } public bool IsLoading { get { return this._isLoading; } set { this._isLoading = value; base.OnPropertyChanged("IsLoading"); } } public string LabelAddUsuarioCentralSegurado { get { if (this.SelectedCliente != null && this.SelectedCliente.get_EstaNaCentralSegurado()) { return "ALTERAR DADOS/SENHA CENTRAL SEGURADO"; } return "ADICIONAR CENTRAL SEGURADO"; } } public DateTime? NascimentoCliente { get { return this._nascimentoCliente; } set { this._nascimentoCliente = value; base.OnPropertyChanged("NascimentoCliente"); } } public ObservableCollection Origens { get { return this._origens; } set { this._origens = value; base.OnPropertyChanged("Origens"); if (this.Origens != null) { this.SelectedOrigem = this.Origens.FirstOrDefault(); } } } public string ProfissaoText { get { return this._profissaoText; } set { this._profissaoText = value; base.OnPropertyChanged("ProfissaoText"); } } public bool Salvando { get; set; } public Cliente SelectedCliente { get { return this._selectedCliente; } set { long? nullable; this._selectedCliente = value; this.WorkOnSelectedCliente(value); if (value != null) { nullable = new long?(value.get_Id()); } else { nullable = null; } base.VerificarEnables(nullable); base.OnPropertyChanged("SelectedCliente"); base.OnPropertyChanged("LabelAddUsuarioCentralSegurado"); } } public OrigemCliente SelectedOrigem { get { return this._selectedOrigem; } set { this._selectedOrigem = value; base.OnPropertyChanged("SelectedOrigem"); } } public ObservableCollection Telefones { get { return this._telefones; } set { this._telefones = value; base.OnPropertyChanged("Telefones"); } } public DateTime? VencimentoHabCliente { get { return this._vencimentoHabCliente; } set { this._vencimentoHabCliente = value; base.OnPropertyChanged("VencimentoHabCliente"); } } public Cliente Vinculo { get { return this._vinculo; } set { this._vinculo = value; base.OnPropertyChanged("Vinculo"); } } public ObservableCollection Vinculos { get { return this._vinculos; } set { if (value != null && value.Count > 0 && this.SelectedCliente != null) { foreach (ClienteVinculo clienteVinculo in value) { if (clienteVinculo.get_Cliente2().get_Id() != this.SelectedCliente.get_Id()) { continue; } clienteVinculo.set_Parentesco(Funcoes.ParentescoInverso(clienteVinculo.get_Parentesco())); } } this._vinculos = value; base.OnPropertyChanged("Vinculos"); } } public Visibility VisibilityFisica { get { return this._visibilityFisica; } set { this._visibilityFisica = value; base.OnPropertyChanged("VisibilityFisica"); } } public Visibility VisibilityJuridica { get { return this._visibilityJuridica; } set { this._visibilityJuridica = value; base.OnPropertyChanged("VisibilityJuridica"); } } public bool VisibilityLogAntigo { get { return this._visibilityLogAntigo; } set { this._visibilityLogAntigo = value; base.OnPropertyChanged("VisibilityLogAntigo"); } } public ClienteViewModel(Cliente cliente = null, bool invoke = true) { this.Invoke = invoke; this._servico = new ClienteServico(); this.ClienteSelecionado = cliente ?? MainViewModel.ClienteSelecionado; this.SelecionaCliente(this.ClienteSelecionado); this.CommandAddUsuarioCentralSegurado = new RelayCommand(() => this.AddUsuarioCentralSegurado()); } public async void AbrirLogAntigo() { base.Loading(true); string str = await this._servico.BuscarLogAntigo(this.SelectedCliente.get_Id()); base.Loading(false); if (!string.IsNullOrEmpty(str)) { base.ShowDrawer(new LogSistemaAntigo(this.SelectedCliente.get_Id(), str), 0, false); } else { await base.ShowMessage("NÃO HÁ LOG PARA ESSE CLIENTE", "OK", "", false); } } public async void AddUsuarioCentralSegurado() { string str; string str1; string str2; string str3; string str4; string str5; string str6; string str7; if (this.SelectedCliente != null && this.SelectedCliente.get_Emails().Count != 0) { base.Loading(true); str7 = "CLIENTE CADASTRADO/ALTERADO COM SUCESSO!"; try { str = (this.SelectedCliente.get_Telefones().Count == 0 ? string.Empty : string.Concat("(", this.SelectedCliente.get_Telefones()[0].get_Prefixo(), ") ", this.SelectedCliente.get_Telefones()[0].get_Numero())); string str8 = str; bool count = this.SelectedCliente.get_Enderecos().Count > 0; Token token = new Token(); UsuarioCentralSegurado usuarioCentralSegurado = new UsuarioCentralSegurado(); usuarioCentralSegurado.set_Id(""); usuarioCentralSegurado.set_Senha(""); usuarioCentralSegurado.set_Serial(token.Encrypt(Recursos.Empresa.get_Serial())); usuarioCentralSegurado.set_FornecedorId(ApplicationHelper.IdFornecedor); usuarioCentralSegurado.set_Nome(token.Encrypt(this.SelectedCliente.get_Nome())); usuarioCentralSegurado.set_Documento(token.Encrypt(this.SelectedCliente.get_Documento().Clear())); usuarioCentralSegurado.set_Email(token.Encrypt(this.SelectedCliente.get_Emails()[0].get_Email())); usuarioCentralSegurado.set_IdEmpresa(this.SelectedCliente.get_IdEmpresa()); usuarioCentralSegurado.set_Telefone(token.Encrypt(str8)); str1 = (count ? token.Encrypt(this.SelectedCliente.get_Enderecos()[0].get_Endereco()) : string.Empty); usuarioCentralSegurado.set_Rua(str1); str2 = (count ? token.Encrypt(this.SelectedCliente.get_Enderecos()[0].get_Numero()) : string.Empty); usuarioCentralSegurado.set_Numero(str2); str3 = (count ? token.Encrypt(this.SelectedCliente.get_Enderecos()[0].get_Bairro()) : string.Empty); usuarioCentralSegurado.set_Bairro(str3); str4 = (count ? token.Encrypt(this.SelectedCliente.get_Enderecos()[0].get_Cidade()) : string.Empty); usuarioCentralSegurado.set_Cidade(str4); str5 = (count ? token.Encrypt(this.SelectedCliente.get_Enderecos()[0].get_Estado()) : string.Empty); usuarioCentralSegurado.set_Estado(str5); str6 = (count ? token.Encrypt(this.SelectedCliente.get_Enderecos()[0].get_Cep()) : string.Empty); usuarioCentralSegurado.set_Cep(str6); usuarioCentralSegurado.set_Corretora(token.Encrypt(Recursos.Empresa.get_Nome())); usuarioCentralSegurado.set_UriCorretora(token.Encrypt(Connection.UrlCentralSegurado)); UsuarioCentralSegurado usuarioCentralSegurado1 = usuarioCentralSegurado; using (HttpClient httpClient = new HttpClient()) { StringContent stringContent = new StringContent(JsonConvert.SerializeObject(usuarioCentralSegurado1), Encoding.UTF8, "application/json"); Uri centralSegurado = Address.get_CentralSegurado(); string[] strArrays = new string[] { "Usuario" }; Uri uri = centralSegurado.Append(strArrays); string[] strArrays1 = new string[] { "AddAggerApp" }; Uri uri1 = uri.Append(strArrays1); HttpResponseMessage httpResponseMessage = await httpClient.PostAsync(uri1, stringContent); await this._servico.AddCentralSegurado(this.SelectedCliente.get_Id(), httpResponseMessage.get_IsSuccessStatusCode()); if (!httpResponseMessage.get_IsSuccessStatusCode()) { string str9 = await httpResponseMessage.get_Content().ReadAsStringAsync(); str7 = string.Concat("HOUVE(RAM) O(S) SEGUINTE(S) ERROS: ", str9.Replace(";", ", ").ToUpper()); } httpResponseMessage = null; } httpClient = null; } catch { str7 = "HOUVERAM ERROS AO CADASTRAR/ALTERAR O CLIENTE!"; } base.OnPropertyChanged("LabelAddUsuarioCentralSegurado"); base.Loading(false); await base.ShowMessage(str7, "OK", "", false); } str7 = null; } public async void CancelarAlteracao() { base.Loading(true); this.IsLoading = true; base.Alterar(false); await this.CarregaCliente(this.ClienteSelecionado); this.Salvando = false; this.IsLoading = false; base.Loading(false); } public async Task CarregaCliente(Cliente value) { bool count; bool flag; bool count1; bool flag1; bool count2; bool flag2; bool count3; Cliente cliente; if (value == null || value.get_Id() == 0) { this.SelectedCliente = null; this.Telefones = null; this.Enderecos = null; this.Emails = null; this.Contatos = null; this.Vinculos = null; this.Origens = null; } else { cliente = value; if (value.get_Id() != 0) { cliente = await this._servico.BuscarCliente(value.get_Id()); Cliente cliente1 = cliente; ObservableCollection observableCollection = await this._servico.BuscarTelefonesAsync(value.get_Id()); cliente1.set_Telefones(observableCollection); cliente1 = null; ClienteViewModel clienteViewModel = this; ObservableCollection telefones = cliente.get_Telefones(); if (telefones != null) { count = telefones.Count <= 9; } else { count = false; } clienteViewModel.EnableAddTelephone = count; cliente1 = cliente; ObservableCollection observableCollection1 = await this._servico.BuscarEmailsAsync(value.get_Id()); cliente1.set_Emails(observableCollection1); cliente1 = null; ClienteViewModel clienteViewModel1 = this; ObservableCollection emails = cliente.get_Emails(); if (emails != null) { flag = emails.Count <= 9; } else { flag = false; } clienteViewModel1.EnableAddEmail = flag; cliente1 = cliente; ObservableCollection observableCollection2 = await this._servico.BuscarEnderecosAsync(value.get_Id()); cliente1.set_Enderecos(observableCollection2); cliente1 = null; ClienteViewModel clienteViewModel2 = this; ObservableCollection enderecos = cliente.get_Enderecos(); if (enderecos != null) { count1 = enderecos.Count <= 9; } else { count1 = false; } clienteViewModel2.EnableAddAddress = count1; cliente1 = cliente; ObservableCollection observableCollection3 = await this._servico.BuscarContatosAsync(value.get_Id()); cliente1.set_Contatos(observableCollection3); cliente1 = null; ClienteViewModel clienteViewModel3 = this; ObservableCollection contatos = cliente.get_Contatos(); if (contatos != null) { flag1 = contatos.Count <= 9; } else { flag1 = false; } clienteViewModel3.EnableAddContact = flag1; cliente1 = cliente; ObservableCollection observableCollection4 = await this._servico.BuscarVinculosAsync(value.get_Id()); cliente1.set_Vinculos(observableCollection4); cliente1 = null; this.Origens = await this._servico.BuscarOrigens(value.get_Id()); this.Telefones = cliente.get_Telefones(); ObservableCollection telefones1 = this.Telefones; if (telefones1 != null) { count2 = telefones1.Count == 0; } else { count2 = false; } if (count2) { this.IncluirTelefone(); } this.Emails = cliente.get_Emails(); ObservableCollection emails1 = this.Emails; if (emails1 != null) { flag2 = emails1.Count == 0; } else { flag2 = false; } if (flag2) { this.IncluirEmail(); } this.Enderecos = cliente.get_Enderecos(); ObservableCollection enderecos1 = this.Enderecos; if (enderecos1 != null) { count3 = enderecos1.Count == 0; } else { count3 = false; } if (count3) { this.IncluirEndereco(); } this.Contatos = cliente.get_Contatos(); this.Vinculos = cliente.get_Vinculos(); } if (!cliente.get_DocumentoPrincipal().HasValue) { cliente.set_DocumentoPrincipal(new TipoDocumento?(0)); } if (cliente.get_ResponsavelAssinatura() == null) { Cliente cliente2 = cliente; ResponsavelAssinatura responsavelAssinatura = new ResponsavelAssinatura(); responsavelAssinatura.set_IdCliente(cliente.get_Id()); cliente2.set_ResponsavelAssinatura(responsavelAssinatura); } this.SelectedCliente = cliente; this.JuridicaouFisica(this.SelectedCliente.get_Documento()); this.SelectedCliente.Initialize(); ObservableCollection telefones2 = this.SelectedCliente.get_Telefones(); if (telefones2 != null) { List list = telefones2.ToList(); list.ForEach((ClienteTelefone telefone) => telefone.Initialize()); } else { } ObservableCollection enderecos2 = this.SelectedCliente.get_Enderecos(); if (enderecos2 != null) { List clienteEnderecos = enderecos2.ToList(); clienteEnderecos.ForEach((ClienteEndereco endereco) => endereco.Initialize()); } else { } ObservableCollection contatos1 = this.SelectedCliente.get_Contatos(); if (contatos1 != null) { List maisContatos = contatos1.ToList(); maisContatos.ForEach((MaisContato contato) => contato.Initialize()); } else { } ObservableCollection emails2 = this.SelectedCliente.get_Emails(); if (emails2 != null) { List clienteEmails = emails2.ToList(); clienteEmails.ForEach((ClienteEmail email) => email.Initialize()); } else { } ObservableCollection vinculos = this.SelectedCliente.get_Vinculos(); if (vinculos != null) { List clienteVinculos = vinculos.ToList(); clienteVinculos.ForEach((ClienteVinculo vinculo) => vinculo.Initialize()); } else { } this.Initialized = true; } cliente = null; } public async void Excluir() { Cliente selectedCliente; if (this.SelectedCliente != null && this.SelectedCliente.get_Id() != 0) { if (await (new ApoliceServico()).BuscarApolicesAsync(this.SelectedCliente.get_Id(), 4, null).Count > 0) { await base.ShowMessage("NÃO É POSSÍVEL EXCLUIR O CLIENTE POIS POSSUI APÓLICES CADASTRADAS.", "OK", "", false); } else if (await base.ShowMessage("DESEJA EXCLUIR?", "SIM", "NÃO", false)) { selectedCliente = this.SelectedCliente; selectedCliente.set_Excluido(true); if (await this._servico.Delete(selectedCliente)) { this.ClienteSelecionado = null; MainViewModel.ClienteSelecionado = null; Action limparCliente = Gestor.Application.Actions.Actions.LimparCliente; if (limparCliente != null) { limparCliente(); } else { } Cliente cliente = new Cliente(); cliente.set_IdEmpresa(Recursos.Usuario.get_IdEmpresa()); cliente.set_DocumentoPrincipal(new TipoDocumento?(0)); cliente.set_ClienteDesde(new DateTime?(Funcoes.GetNetworkTime().Date)); this.SelectedCliente = cliente; ObservableCollection observableCollection = new ObservableCollection(); ClienteTelefone clienteTelefone = new ClienteTelefone(); clienteTelefone.set_Cliente(this.SelectedCliente); clienteTelefone.set_Tipo(new TipoTelefone?(1)); clienteTelefone.set_Ordem(new int?(1)); observableCollection.Add(clienteTelefone); this.Telefones = observableCollection; ObservableCollection observableCollection1 = new ObservableCollection(); ClienteEndereco clienteEndereco = new ClienteEndereco(); clienteEndereco.set_Cliente(this.SelectedCliente); clienteEndereco.set_Ordem(new int?(1)); observableCollection1.Add(clienteEndereco); this.Enderecos = observableCollection1; ObservableCollection observableCollection2 = new ObservableCollection(); ClienteEmail clienteEmail = new ClienteEmail(); clienteEmail.set_Cliente(this.SelectedCliente); clienteEmail.set_Ordem(new int?(1)); observableCollection2.Add(clienteEmail); this.Emails = observableCollection2; this.Contatos = new ObservableCollection(); this.Vinculos = new ObservableCollection(); this.Origens = new ObservableCollection(); string str = string.Format("EXCLUIU CLIENTE \"{0}\", ID: {1}", selectedCliente.get_Nome(), selectedCliente.get_Id()); base.RegistrarAcao(str, selectedCliente.get_Id(), new TipoTela?(1), string.Format("CLIENTE \"{0}\", ID: {1}", this.SelectedCliente.get_Nome(), this.SelectedCliente.get_Id())); base.ToggleSnackBar("CLIENTE EXCLUÍDO COM SUCESSO", true); } } } selectedCliente = null; } public void ExcluirContato(MaisContato contato) { this.EnableAddContact = this.Contatos.Count <= 9; this.Contatos.Remove(contato); } public async void ExcluirEmail(ClienteEmail email) { if (this.Emails.Count < 2) { List configuracoes = Recursos.Configuracoes; if (configuracoes.All((ConfiguracaoSistema x) => x.get_Configuracao() != 29)) { await base.ShowMessage("É NECESSÁRIO TER AO MENOS UM CONTATO DE E-MAIL CADASTRADO.", "OK", "", false); return; } } this.EnableAddEmail = this.Emails.Count <= 9; this.Emails.Remove(email); } public async void ExcluirEndereco(ClienteEndereco endereco) { if (this.Enderecos.Count >= 2) { this.EnableAddAddress = this.Enderecos.Count <= 9; this.Enderecos.Remove(endereco); } else { await base.ShowMessage("É NECESSÁRIO TER AO MENOS UM ENDEREÇO CADASTRADO.", "OK", "", false); } } public async Task ExcluirOrigem(OrigemCliente origem) { ClienteViewModel clienteViewModel = this; clienteViewModel.Origens.Remove(origem); clienteViewModel.OnPropertyChanged("Origens"); } public async void ExcluirTelefone(ClienteTelefone telefone) { if (this.Telefones.Count >= 2) { this.EnableAddTelephone = this.Telefones.Count <= 9; this.Telefones.Remove(telefone); } else { await base.ShowMessage("É NECESSÁRIO TER AO MENOS UM CONTATO TELEFÔNICO CADASTRADO.", "OK", "", false); } } public void ExcluirVinculo(ClienteVinculo vinculo) { this.Vinculos.Remove(vinculo); } public void IncluirCliente() { DateTime date = Funcoes.GetNetworkTime().Date; Cliente cliente = new Cliente(); cliente.set_IdEmpresa(Recursos.Usuario.get_IdEmpresa()); cliente.set_DocumentoPrincipal(new TipoDocumento?(0)); cliente.set_ClienteDesde(new DateTime?(date)); cliente.set_ResponsavelAssinatura(new ResponsavelAssinatura()); this.SelectedCliente = cliente; this.NascimentoCliente = new DateTime?(date); this.HabilitaCliente = new DateTime?(date); this.VencimentoHabCliente = new DateTime?(date); this.ExpedicaoCliente = new DateTime?(date); ObservableCollection observableCollection = new ObservableCollection(); ClienteTelefone clienteTelefone = new ClienteTelefone(); clienteTelefone.set_Cliente(this.SelectedCliente); clienteTelefone.set_Tipo(new TipoTelefone?(1)); clienteTelefone.set_Ordem(new int?(1)); observableCollection.Add(clienteTelefone); this.Telefones = observableCollection; ObservableCollection observableCollection1 = new ObservableCollection(); ClienteEndereco clienteEndereco = new ClienteEndereco(); clienteEndereco.set_Cliente(this.SelectedCliente); clienteEndereco.set_Ordem(new int?(1)); observableCollection1.Add(clienteEndereco); this.Enderecos = observableCollection1; ObservableCollection observableCollection2 = new ObservableCollection(); ClienteEmail clienteEmail = new ClienteEmail(); clienteEmail.set_Cliente(this.SelectedCliente); clienteEmail.set_Ordem(new int?(1)); observableCollection2.Add(clienteEmail); this.Emails = observableCollection2; this.Contatos = new ObservableCollection(); this.Vinculos = new ObservableCollection(); this.Origens = new ObservableCollection(); this.Salvando = true; base.Alterar(true); } public void IncluirContato() { if (this.SelectedCliente == null) { return; } if (this.Contatos == null) { this.Contatos = new ObservableCollection(); } MaisContato maisContato = new MaisContato(); maisContato.set_Cliente(this.SelectedCliente); MaisContato maisContato1 = maisContato; this.EnableAddContact = this.Contatos.Count < 9; this.Contatos.Add(maisContato1); base.OnPropertyChanged("IncluirContato"); } public void IncluirEmail() { if (this.SelectedCliente == null) { return; } if (this.Emails == null) { this.Emails = new ObservableCollection(); } this.EnableAddEmail = this.Emails.Count < 9; ClienteEmail clienteEmail = new ClienteEmail(); clienteEmail.set_Cliente(this.SelectedCliente); clienteEmail.set_Ordem(new int?(this.Emails.Count + 1)); this.Emails.Add(clienteEmail); base.OnPropertyChanged("IncluirEmail"); } public void IncluirEndereco() { if (this.SelectedCliente == null) { return; } if (this.Enderecos == null) { this.Enderecos = new ObservableCollection(); } this.EnableAddAddress = this.Enderecos.Count < 9; ClienteEndereco clienteEndereco = new ClienteEndereco(); clienteEndereco.set_Cliente(this.SelectedCliente); clienteEndereco.set_Ordem(new int?(this.Enderecos.Count + 1)); this.Enderecos.Add(clienteEndereco); base.OnPropertyChanged("IncluirEndereco"); } public async Task IncluirOrigem(string name) { if (this.SelectedCliente != null && !string.IsNullOrWhiteSpace(name)) { if (this.Origens == null) { this.Origens = new ObservableCollection(); } if (!this.Origens.Any((OrigemCliente x) => { string str; string nome = x.get_Nome(); if (nome != null) { str = nome.Trim(); } else { str = null; } return str == name.Trim(); })) { ObservableCollection origens = this.Origens; OrigemCliente origemCliente = new OrigemCliente(); origemCliente.set_Cliente(this.SelectedCliente); origemCliente.set_Nome(name); origemCliente.set_TipoOrigem((long)1); origens.Insert(0, origemCliente); base.OnPropertyChanged("Origens"); } else { await base.ShowMessage(string.Concat("JÁ EXISTE UMA ORIGEM ", name, ". PROCESSO CANCELADO."), "OK", "", false); } } } public void IncluirTelefone() { if (this.SelectedCliente == null) { return; } if (this.Telefones == null) { this.Telefones = new ObservableCollection(); } this.EnableAddTelephone = this.Telefones.Count < 9; ClienteTelefone clienteTelefone = new ClienteTelefone(); clienteTelefone.set_Cliente(this.SelectedCliente); clienteTelefone.set_Tipo(new TipoTelefone?(1)); clienteTelefone.set_Ordem(new int?(this.Telefones.Count + 1)); this.Telefones.Add(clienteTelefone); base.OnPropertyChanged("IncluirTelefone"); } public bool IncluirVinculo() { if (this.Vinculo == null || this.Vinculo.get_Id() == this.SelectedCliente.get_Id()) { return false; } if (this.Vinculos == null) { this.Vinculos = new ObservableCollection(); } if (this.Vinculos.Any((ClienteVinculo x) => { if (x.get_Cliente1().get_Id() == this.Vinculo.get_Id()) { return true; } return x.get_Cliente2().get_Id() == this.Vinculo.get_Id(); })) { return false; } ClienteVinculo clienteVinculo = new ClienteVinculo(); clienteVinculo.set_Cliente1(this.SelectedCliente); clienteVinculo.set_Cliente2(this.Vinculo); this.Vinculos.Add(clienteVinculo); this.Vinculo = null; base.OnPropertyChanged("IncluirVinculo"); return true; } public void JuridicaouFisica(string documento) { if (this.SelectedCliente == null) { return; } this.ProfissaoText = ""; this.AtividadeText = ""; if (documento != null && ValidationHelper.OnlyNumber(documento).Length <= 11) { this.VisibilityJuridica = Visibility.Collapsed; this.VisibilityFisica = Visibility.Visible; this.FieldNascimento = "NASCIMENTO"; this.FieldDocumento = "CPF"; this.SelectedCliente.set_Atividade(null); this.IsJuridica = false; return; } this.VisibilityJuridica = Visibility.Visible; this.VisibilityFisica = Visibility.Collapsed; this.FieldNascimento = "FUNDAÇÃO"; this.FieldDocumento = "CNPJ"; this.SelectedCliente.set_Profissao(null); this.IsJuridica = true; } public async Task>> Salvar() { List> keyValuePairs; long num; long? nullable; List list; List clienteVinculos; ObservableCollection observableCollection; ObservableCollection observableCollection1; List origemClientes; bool id; bool salvando; long? nullable1; long? nullable2; ClienteViewModel.u003cu003ec__DisplayClass146_0 variable; Cliente selectedCliente; Func func = null; ObservableCollection telefones = this.Telefones; List clienteTelefones = ( from x in telefones where !string.IsNullOrEmpty(x.get_Numero()) select x).ToList(); ObservableCollection enderecos = this.Enderecos; List clienteEnderecos = ( from x in enderecos where !string.IsNullOrEmpty(x.get_Endereco()) select x).ToList(); ObservableCollection contatos = this.Contatos; if (contatos != null) { list = ( from x in contatos where !string.IsNullOrEmpty(x.get_Nome()) select x).ToList(); } else { list = null; } List maisContatos = list; ObservableCollection emails = this.Emails; List clienteEmails = ( from x in emails where !string.IsNullOrEmpty(x.get_Email()) select x).ToList(); ObservableCollection vinculos = this.Vinculos; if (vinculos != null) { clienteVinculos = vinculos.Where((ClienteVinculo x) => { if (x.get_Cliente2() == null) { return false; } return x.get_Parentesco().HasValue; }).ToList(); } else { clienteVinculos = null; } List clienteVinculos1 = clienteVinculos; if (clienteVinculos1 != null && this.ClienteSelecionado != null) { List clienteVinculos2 = clienteVinculos1; Func func1 = func; if (func1 == null) { Func id1 = (ClienteVinculo c) => c.get_Cliente2().get_Id() == this.ClienteSelecionado.get_Id(); Func func2 = id1; func = id1; func1 = func2; } foreach (ClienteVinculo clienteVinculo in clienteVinculos2.Where(func1)) { clienteVinculo.set_Parentesco(Funcoes.ParentescoInverso(clienteVinculo.get_Parentesco())); } } this.SelectedCliente.set_Telefones(new ObservableCollection(clienteTelefones)); this.SelectedCliente.set_Enderecos(new ObservableCollection(clienteEnderecos)); Cliente cliente = this.SelectedCliente; if (maisContatos != null) { observableCollection = new ObservableCollection(maisContatos); } else { observableCollection = null; } cliente.set_Contatos(observableCollection); this.SelectedCliente.set_Emails(new ObservableCollection(clienteEmails)); Cliente selectedCliente1 = this.SelectedCliente; if (clienteVinculos1 != null) { observableCollection1 = new ObservableCollection(clienteVinculos1); } else { observableCollection1 = null; } selectedCliente1.set_Vinculos(observableCollection1); Cliente cliente1 = this.SelectedCliente; ObservableCollection origens = this.Origens; if (origens != null) { origemClientes = origens.ToList(); } else { origemClientes = null; } cliente1.set_Origens(origemClientes); if (ValidationHelper.OnlyNumber(this.SelectedCliente.get_Documento()).Length <= 11 && !string.IsNullOrWhiteSpace(this.ProfissaoText) && this.SelectedCliente.get_Profissao() == null) { ProfissaoServico profissaoServico = new ProfissaoServico(); selectedCliente = this.SelectedCliente; ProfissaoServico profissaoServico1 = profissaoServico; Profissao profissao = new Profissao(); profissao.set_Nome(this.ProfissaoText); profissao.set_Codigo("0"); Profissao profissao1 = profissao; num = await profissaoServico.FindLastId(); profissao1.set_Id(num + (long)1); Profissao profissao2 = await profissaoServico1.Save(profissao); profissaoServico1 = null; profissao1 = null; profissao = null; selectedCliente.set_Profissao(profissao2); selectedCliente = null; if (profissaoServico.Sucesso) { profissaoServico = null; } else { keyValuePairs = null; variable = null; clienteEmails = null; return keyValuePairs; } } if (ValidationHelper.OnlyNumber(this.SelectedCliente.get_Documento()).Length > 11 && !string.IsNullOrWhiteSpace(this.AtividadeText) && this.SelectedCliente.get_Atividade() == null) { AtividadeServico atividadeServico = new AtividadeServico(); selectedCliente = this.SelectedCliente; AtividadeServico atividadeServico1 = atividadeServico; Atividade atividade = new Atividade(); atividade.set_Nome(this.AtividadeText); atividade.set_Cnac("0"); Atividade atividade1 = atividade; num = await atividadeServico.FindLastId(); atividade1.set_Id(num + (long)1); Atividade atividade2 = await atividadeServico1.Save(atividade); atividadeServico1 = null; atividade1 = null; atividade = null; selectedCliente.set_Atividade(atividade2); selectedCliente = null; if (atividadeServico.Sucesso) { atividadeServico = null; } else { keyValuePairs = null; variable = null; clienteEmails = null; return keyValuePairs; } } if (this.IsJuridica) { this.SelectedCliente.set_Cei(null); this.SelectedCliente.set_Rne(null); this.SelectedCliente.set_Caepf(null); } List> keyValuePairs1 = this.SelectedCliente.Validate(); clienteEmails.ForEach((ClienteEmail x) => keyValuePairs1.AddRange(x.Validate())); List> keyValuePairs2 = keyValuePairs1; keyValuePairs2.AddRange(await this.Validate()); keyValuePairs2 = null; foreach (MaisContato contato in this.Contatos) { keyValuePairs1.AddRange(contato.Validate()); } foreach (ClienteVinculo vinculo in this.Vinculos) { keyValuePairs1.AddRange(vinculo.Validate()); } if (keyValuePairs1.Count <= 0) { bool flag = this.SelectedCliente.get_Id() == (long)0; this._saving = true; Cliente clienteSelecionado = this.ClienteSelecionado; if (clienteSelecionado != null) { id = clienteSelecionado.get_Id() != (long)0; } else { id = true; } if (id) { Cliente clienteSelecionado1 = this.ClienteSelecionado; if (clienteSelecionado1 != null) { nullable1 = new long?(clienteSelecionado1.get_Id()); } else { nullable = null; nullable1 = nullable; } long? nullable3 = nullable1; Cliente selectedCliente2 = this.SelectedCliente; if (selectedCliente2 != null) { nullable2 = new long?(selectedCliente2.get_Id()); } else { nullable = null; nullable2 = nullable; } long? nullable4 = nullable2; if (nullable3.GetValueOrDefault() != nullable4.GetValueOrDefault() | nullable3.HasValue != nullable4.HasValue) { goto Label2; } salvando = this.Salvando; goto Label1; } Label2: salvando = false; Label1: bool flag1 = salvando; if (flag1) { flag1 = await base.ShowMessage("NÃO FOI POSSIVEL INCLUIR UM NOVO SEGURADO, TENTE NOVAMENTE", "OK", "", false); } if (!flag1) { this.SelectedCliente = await this._servico.Save(this.SelectedCliente, this.Salvando); if (this._servico.Sucesso) { if (this.Invoke) { Action selectCliente = Gestor.Application.Actions.Actions.SelectCliente; if (selectCliente != null) { selectCliente(this.SelectedCliente); } else { } } await this.CarregaCliente(this.SelectedCliente); string str = (flag ? "INCLUIU" : "ALTEROU"); base.RegistrarAcao(string.Concat(str, " CLIENTE \"", this.SelectedCliente.get_Nome(), "\""), this.SelectedCliente.get_Id(), new TipoTela?(1), string.Format("CLIENTE \"{0}\", ID: {1}", this.SelectedCliente.get_Nome(), this.SelectedCliente.get_Id())); base.ToggleSnackBar("CLIENTE SALVO COM SUCESSO", true); if (this.Invoke) { ConsultaViewModel.DocumentoSelecionado = null; Action atualizaContatos = Gestor.Application.Actions.Actions.AtualizaContatos; if (atualizaContatos != null) { atualizaContatos(); } else { } if (flag) { MainViewModel.ClienteSelecionado = this.SelectedCliente; if (await base.ShowMessage("DESEJA INCLUIR UMA APÓLICE AGORA?", "SIM", "NÃO", false)) { Action acessaTela = Gestor.Application.Actions.Actions.AcessaTela; if (acessaTela != null) { acessaTela(2, ""); } else { } } } } this.Salvando = false; base.Alterar(false); this._saving = false; keyValuePairs = null; } else { keyValuePairs = null; } } else { keyValuePairs = null; } } else { keyValuePairs = keyValuePairs1; } variable = null; clienteEmails = null; return keyValuePairs; } public async void SelecionaCliente(Cliente value) { if (!this._saving || !this.Invoke) { if (value == null) { this.ClienteSelecionado = new Cliente(); value = this.ClienteSelecionado; } base.Loading(true); await base.PermissaoTela(1); await this.CarregaCliente(value); base.Loading(false); } } public async Task Validate(ClienteEmail item) { bool flag; if (!ValidationHelper.ValidateMail(item.get_Email())) { await base.ShowMessage("ENDEREÇO DE E-MAIL INVÁLIDO", "OK", "", false); flag = false; } else { flag = true; } return flag; } private async Task>> Validate() { List clientes; long id; List> keyValuePairs = new List>(); bool flag = !string.IsNullOrEmpty(this.SelectedCliente.get_Nome()); TipoDocumento? documentoPrincipal = this.SelectedCliente.get_DocumentoPrincipal(); if (documentoPrincipal.HasValue) { switch (documentoPrincipal.GetValueOrDefault()) { case 0: { if (ValidationHelper.ValidateDocument(this.SelectedCliente.get_Documento())) { break; } flag = false; break; } case 1: { if (ValidationHelper.ValidateRne(this.SelectedCliente.get_Rne())) { break; } flag = false; break; } case 2: { if (ValidationHelper.ValidateCei(this.SelectedCliente.get_Cei())) { break; } flag = false; break; } case 3: { if (ValidationHelper.ValidateCaepf(this.SelectedCliente.get_Caepf())) { break; } flag = false; break; } } } if (ValidationHelper.ValidateDocument(this.SelectedCliente.get_Documento())) { documentoPrincipal = this.SelectedCliente.get_DocumentoPrincipal(); if (documentoPrincipal.GetValueOrDefault() == 0 & documentoPrincipal.HasValue) { this.SelectedCliente.set_Documento(ValidationHelper.FormatDocument(this.SelectedCliente.get_Documento())); } } if (!ValidationHelper.ValidateDocument(this.SelectedCliente.get_Documento())) { clientes = new List(); } else { clientes = await (new ClienteServico()).BuscarCliente(this.SelectedCliente.get_Documento(), null, 2); } List clientes1 = clientes; if (!this.IsJuridica) { if (!ValidationHelper.ValidateCei(this.SelectedCliente.get_Cei())) { clientes = new List(); } else { clientes = await (new ClienteServico()).BuscarCliente(this.SelectedCliente.get_Cei(), null, 2); } List clientes2 = clientes; if (!ValidationHelper.ValidateRne(this.SelectedCliente.get_Rne())) { clientes = new List(); } else { clientes = await (new ClienteServico()).BuscarCliente(this.SelectedCliente.get_Rne(), null, 2); } List clientes3 = clientes; if (!ValidationHelper.ValidateCaepf(this.SelectedCliente.get_Caepf())) { clientes = new List(); } else { clientes = await (new ClienteServico()).BuscarCliente(this.SelectedCliente.get_Caepf(), null, 2); } List clientes4 = clientes; List clientes5 = clientes1; List clientes6 = clientes2; if (clientes6 == null) { clientes6 = new List(); } clientes5.AddRange(clientes6); List clientes7 = clientes1; List clientes8 = clientes3; if (clientes8 == null) { clientes8 = new List(); } clientes7.AddRange(clientes8); List clientes9 = clientes1; List clientes10 = clientes4; if (clientes10 == null) { clientes10 = new List(); } clientes9.AddRange(clientes10); clientes2 = null; clientes3 = null; } string nome = ""; string str = ""; if (clientes1.Count > 0) { clientes1.ForEach((Cliente x) => { if (x.get_Id() == this.SelectedCliente.get_Id()) { return; } if (x.get_IdEmpresa() != this.SelectedCliente.get_IdEmpresa()) { return; } if (!string.IsNullOrEmpty(this.SelectedCliente.get_Documento()) && x.get_Documento() == this.SelectedCliente.get_Documento()) { flag = false; nome = x.get_Nome(); } if (!string.IsNullOrEmpty(this.SelectedCliente.get_Cei()) && x.get_Cei() == this.SelectedCliente.get_Cei()) { str = " (CEI)"; flag = false; nome = x.get_Nome(); } if (!string.IsNullOrEmpty(this.SelectedCliente.get_Rne()) && x.get_Rne() == this.SelectedCliente.get_Rne()) { str = " (RNE)"; flag = false; nome = x.get_Nome(); } if (!string.IsNullOrEmpty(this.SelectedCliente.get_Caepf()) && x.get_Caepf() == this.SelectedCliente.get_Caepf()) { str = " (CAEPF)"; flag = false; nome = x.get_Nome(); } }); } if (!flag && clientes1.Count((Cliente x) => x.get_Id() != this.SelectedCliente.get_Id()) > 0) { if (await (new VendedorUsuarioServico()).FindVinculoByUsuario(Recursos.Usuario.get_Id())) { Cliente cliente = clientes1.FirstOrDefault(); if (cliente != null) { id = cliente.get_Id(); } else { id = (long)0; } List vendedors = await (new VendedorServico()).BuscarVinculosCliente(id); string str1 = string.Join("|", from vendedor in vendedors select vendedor.get_Nome()); List> keyValuePairs1 = keyValuePairs; string[] strArrays = new string[] { "O DOCUMENTO", str, " JÁ ESTÁ CADASTRADO PARA O CLIENTE ", nome, ".\nEXISTENTE NO VINCULO COM VENDEDORES: ", str1, " " }; keyValuePairs1.Add(new KeyValuePair("Documento", string.Concat(strArrays))); } else { keyValuePairs.Add(new KeyValuePair("Documento", string.Concat("O DOCUMENTO", str, " JÁ ESTÁ CADASTRADO PARA O CLIENTE ", nome))); } } if (this.SelectedCliente.get_Telefones() == null || this.SelectedCliente.get_Telefones().Count == 0) { keyValuePairs.Add(new KeyValuePair("Telefones", "NECESSITA-SE AO MENOS UM TELEFONE VÁLIDO.")); } List configuracoes = Recursos.Configuracoes; if (configuracoes.All((ConfiguracaoSistema x) => x.get_Configuracao() != 29) && (this.SelectedCliente.get_Emails() == null || this.SelectedCliente.get_Emails().Count == 0)) { keyValuePairs.Add(new KeyValuePair("Emails|E-MAILS", "NECESSITA-SE AO MENOS UM E-MAIL VÁLIDO.")); } if (this.SelectedCliente.get_Enderecos() == null || this.SelectedCliente.get_Enderecos().Count == 0) { keyValuePairs.Add(new KeyValuePair("Enderecos|ENDEREÇOS", "NECESSITA-SE AO MENOS UM ENDEREÇO VÁLIDO.")); } List> keyValuePairs2 = keyValuePairs; keyValuePairs = null; clientes1 = null; return keyValuePairs2; } private async void WorkOnSelectedCliente(Cliente value) { DateTime networkTime; DateTime? nullable; DateTime? primeiraHabilitacao; DateTime? vencimentoHabilitacao; DateTime? expedicao; Cliente cliente; if (value != null && value.get_Id() != 0 && !this.IsLoading) { base.Loading(true); cliente = await this._servico.BuscarCliente(value.get_Id()); if (cliente.get_ResponsavelAssinatura() == null) { Cliente cliente1 = cliente; ResponsavelAssinatura responsavelAssinatura = new ResponsavelAssinatura(); responsavelAssinatura.set_IdCliente(cliente.get_Id()); cliente1.set_ResponsavelAssinatura(responsavelAssinatura); } Cliente cliente2 = cliente; ObservableCollection observableCollection = await this._servico.BuscarTelefonesAsync(value.get_Id()); cliente2.set_Telefones(observableCollection); cliente2 = null; cliente2 = cliente; ObservableCollection observableCollection1 = await this._servico.BuscarEmailsAsync(value.get_Id()); cliente2.set_Emails(observableCollection1); cliente2 = null; cliente2 = cliente; ObservableCollection observableCollection2 = await this._servico.BuscarEnderecosAsync(value.get_Id()); cliente2.set_Enderecos(observableCollection2); cliente2 = null; cliente2 = cliente; ObservableCollection observableCollection3 = await this._servico.BuscarContatosAsync(value.get_Id()); cliente2.set_Contatos(observableCollection3); cliente2 = null; cliente2 = cliente; ObservableCollection observableCollection4 = await this._servico.BuscarVinculosAsync(value.get_Id()); cliente2.set_Vinculos(observableCollection4); cliente2 = null; this.Origens = await this._servico.BuscarOrigens(value.get_Id()); Cliente cliente3 = cliente; TipoDocumento? documentoPrincipal = cliente.get_DocumentoPrincipal(); cliente3.set_DocumentoPrincipal(new TipoDocumento?(documentoPrincipal.GetValueOrDefault())); this.ClienteExcluido = cliente.get_Excluido(); if (this.SelectedCliente != null) { DomainBase.Copy(this.SelectedCliente, cliente); this.JuridicaouFisica(this.SelectedCliente.get_Documento()); this.SelectedCliente.Initialize(); this.ClienteSelecionado = cliente; } ClienteViewModel clienteViewModel = this; if (value == null || !value.get_Nascimento().HasValue) { networkTime = Funcoes.GetNetworkTime(); nullable = new DateTime?(networkTime.Date); } else { nullable = value.get_Nascimento(); } clienteViewModel.NascimentoCliente = nullable; ClienteViewModel clienteViewModel1 = this; if (value == null || !value.get_PrimeiraHabilitacao().HasValue) { networkTime = Funcoes.GetNetworkTime(); primeiraHabilitacao = new DateTime?(networkTime.Date); } else { primeiraHabilitacao = value.get_PrimeiraHabilitacao(); } clienteViewModel1.HabilitaCliente = primeiraHabilitacao; ClienteViewModel clienteViewModel2 = this; if (value == null || !value.get_VencimentoHabilitacao().HasValue) { networkTime = Funcoes.GetNetworkTime(); vencimentoHabilitacao = new DateTime?(networkTime.Date); } else { vencimentoHabilitacao = value.get_VencimentoHabilitacao(); } clienteViewModel2.VencimentoHabCliente = vencimentoHabilitacao; ClienteViewModel clienteViewModel3 = this; if (value == null || !value.get_Expedicao().HasValue) { networkTime = Funcoes.GetNetworkTime(); expedicao = new DateTime?(networkTime.Date); } else { expedicao = value.get_Expedicao(); } clienteViewModel3.ExpedicaoCliente = expedicao; this.Initialized = true; base.Loading(false); } cliente = null; } } }