using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Net.Http; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Input; 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.Seguros; 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; 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((ConfiguracaoSistema x) => (int)x.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)2; private Visibility _visibilityFisica = (Visibility)2; 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; private Cliente ClienteSelecionado { get; set; } private bool Invoke { get; } public Visibility AddUsuarioCentralSeguradoVisibility { get; set; } = (Visibility)(string.IsNullOrEmpty(Connection.UrlCentralSegurado) ? 2 : 0); public ICommand CommandAddUsuarioCentralSegurado { get; set; } public string LabelAddUsuarioCentralSegurado { get { if (SelectedCliente == null || !SelectedCliente.EstaNaCentralSegurado) { return "ADICIONAR CENTRAL SEGURADO"; } return "ALTERAR DADOS/SENHA CENTRAL SEGURADO"; } } public bool VisibilityLogAntigo { get { return _visibilityLogAntigo; } set { _visibilityLogAntigo = value; OnPropertyChanged("VisibilityLogAntigo"); } } public ObservableCollection Telefones { get { return _telefones; } set { _telefones = value; OnPropertyChanged("Telefones"); } } public ObservableCollection Emails { get { return _emails; } set { _emails = value; OnPropertyChanged("Emails"); } } public ObservableCollection Enderecos { get { return _enderecos; } set { _enderecos = value; OnPropertyChanged("Enderecos"); } } public ObservableCollection Contatos { get { return _contatos; } set { _contatos = value; OnPropertyChanged("Contatos"); } } public ObservableCollection Vinculos { get { return _vinculos; } set { if (value != null && value.Count > 0 && SelectedCliente != null) { foreach (ClienteVinculo item in value) { if (((DomainBase)item.Cliente2).Id == ((DomainBase)SelectedCliente).Id) { item.Parentesco = Funcoes.ParentescoInverso(item.Parentesco); } } } _vinculos = value; OnPropertyChanged("Vinculos"); } } public Cliente Vinculo { get { return _vinculo; } set { _vinculo = value; OnPropertyChanged("Vinculo"); } } public bool Salvando { get; set; } public bool IsLoading { get { return _isLoading; } set { _isLoading = value; OnPropertyChanged("IsLoading"); } } public bool ClienteExcluido { get { return _clienteExcluido; } set { _clienteExcluido = value; OnPropertyChanged("ClienteExcluido"); } } public DateTime? NascimentoCliente { get { return _nascimentoCliente; } set { _nascimentoCliente = value; OnPropertyChanged("NascimentoCliente"); } } public DateTime? HabilitaCliente { get { return _habilitaCliente; } set { _habilitaCliente = value; OnPropertyChanged("HabilitaCliente"); } } public DateTime? VencimentoHabCliente { get { return _vencimentoHabCliente; } set { _vencimentoHabCliente = value; OnPropertyChanged("VencimentoHabCliente"); } } public DateTime? ExpedicaoCliente { get { return _expedicaoCliente; } set { _expedicaoCliente = value; OnPropertyChanged("ExpedicaoCliente"); } } public Cliente SelectedCliente { get { return _selectedCliente; } set { _selectedCliente = value; WorkOnSelectedCliente(value); VerificarEnables((value != null) ? new long?(((DomainBase)value).Id) : null); OnPropertyChanged("SelectedCliente"); OnPropertyChanged("LabelAddUsuarioCentralSegurado"); } } private bool IsJuridica { get; set; } public string FieldNascimento { get { return _fieldNascimento; } set { _fieldNascimento = value; OnPropertyChanged("FieldNascimento"); } } public string FieldDocumento { get { return _fieldDocumento; } set { _fieldDocumento = value; OnPropertyChanged("FieldDocumento"); } } public Visibility VisibilityJuridica { get { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return _visibilityJuridica; } set { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) _visibilityJuridica = value; OnPropertyChanged("VisibilityJuridica"); } } public Visibility VisibilityFisica { get { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return _visibilityFisica; } set { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) _visibilityFisica = value; OnPropertyChanged("VisibilityFisica"); } } public bool EnableAddTelephone { get { return _enableAddTelephone; } set { _enableAddTelephone = value; OnPropertyChanged("EnableAddTelephone"); } } public bool EnableAddAddress { get { return _enableAddAddress; } set { _enableAddAddress = value; OnPropertyChanged("EnableAddAddress"); } } public bool EnableAddEmail { get { return _enableAddEmail; } set { _enableAddEmail = value; OnPropertyChanged("EnableAddEmail"); } } public bool EnableAddContact { get { return _enableAddContact; } set { _enableAddContact = value; OnPropertyChanged("EnableAddContact"); } } public string ProfissaoText { get { return _profissaoText; } set { _profissaoText = value; OnPropertyChanged("ProfissaoText"); } } public string AtividadeText { get { return _atividadeText; } set { _atividadeText = value; OnPropertyChanged("AtividadeText"); } } public ObservableCollection Origens { get { return _origens; } set { _origens = value; OnPropertyChanged("Origens"); if (Origens != null) { SelectedOrigem = Origens.FirstOrDefault(); } } } public OrigemCliente SelectedOrigem { get { return _selectedOrigem; } set { _selectedOrigem = value; OnPropertyChanged("SelectedOrigem"); } } public ClienteViewModel(Cliente cliente = null, bool invoke = true) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_009b: Unknown result type (might be due to invalid IL or missing references) Invoke = invoke; _servico = new ClienteServico(); ClienteSelecionado = cliente ?? MainViewModel.ClienteSelecionado; SelecionaCliente(ClienteSelecionado); CommandAddUsuarioCentralSegurado = new RelayCommand(delegate { AddUsuarioCentralSegurado(); }); } public async void SelecionaCliente(Cliente value) { if (!_saving || !Invoke) { if (value == null) { ClienteSelecionado = new Cliente(); value = ClienteSelecionado; } Loading(isLoading: true); await PermissaoTela((TipoTela)1); await CarregaCliente(value); Loading(isLoading: false); } } public async Task CarregaCliente(Cliente value) { if (value == null || ((DomainBase)value).Id == 0L) { SelectedCliente = null; Telefones = null; Enderecos = null; Emails = null; Contatos = null; Vinculos = null; Origens = null; return; } Cliente cliente = value; if (((DomainBase)value).Id != 0L) { cliente = await _servico.BuscarCliente(((DomainBase)value).Id); Cliente val = cliente; val.Telefones = await _servico.BuscarTelefonesAsync(((DomainBase)value).Id); ClienteViewModel clienteViewModel = this; ObservableCollection telefones = cliente.Telefones; clienteViewModel.EnableAddTelephone = telefones != null && telefones.Count <= 9; val = cliente; val.Emails = await _servico.BuscarEmailsAsync(((DomainBase)value).Id); ClienteViewModel clienteViewModel2 = this; ObservableCollection emails = cliente.Emails; clienteViewModel2.EnableAddEmail = emails != null && emails.Count <= 9; val = cliente; val.Enderecos = await _servico.BuscarEnderecosAsync(((DomainBase)value).Id); ClienteViewModel clienteViewModel3 = this; ObservableCollection enderecos = cliente.Enderecos; clienteViewModel3.EnableAddAddress = enderecos != null && enderecos.Count <= 9; val = cliente; val.Contatos = await _servico.BuscarContatosAsync(((DomainBase)value).Id); ClienteViewModel clienteViewModel4 = this; ObservableCollection contatos = cliente.Contatos; clienteViewModel4.EnableAddContact = contatos != null && contatos.Count <= 9; val = cliente; val.Vinculos = await _servico.BuscarVinculosAsync(((DomainBase)value).Id); Origens = await _servico.BuscarOrigens(((DomainBase)value).Id); Telefones = cliente.Telefones; ObservableCollection telefones2 = Telefones; if (telefones2 != null && telefones2.Count == 0) { IncluirTelefone(); } Emails = cliente.Emails; ObservableCollection emails2 = Emails; if (emails2 != null && emails2.Count == 0) { IncluirEmail(); } Enderecos = cliente.Enderecos; ObservableCollection enderecos2 = Enderecos; if (enderecos2 != null && enderecos2.Count == 0) { IncluirEndereco(); } Contatos = cliente.Contatos; Vinculos = cliente.Vinculos; } if (!cliente.DocumentoPrincipal.HasValue) { cliente.DocumentoPrincipal = (TipoDocumento)0; } if (cliente.ResponsavelAssinatura == null) { cliente.ResponsavelAssinatura = new ResponsavelAssinatura { IdCliente = ((DomainBase)cliente).Id }; } SelectedCliente = cliente; JuridicaouFisica(SelectedCliente.Documento); ((DomainBase)SelectedCliente).Initialize(); SelectedCliente.Telefones?.ToList().ForEach(delegate(ClienteTelefone telefone) { ((DomainBase)telefone).Initialize(); }); SelectedCliente.Enderecos?.ToList().ForEach(delegate(ClienteEndereco endereco) { ((DomainBase)endereco).Initialize(); }); SelectedCliente.Contatos?.ToList().ForEach(delegate(MaisContato contato) { ((DomainBase)contato).Initialize(); }); SelectedCliente.Emails?.ToList().ForEach(delegate(ClienteEmail email) { ((DomainBase)email).Initialize(); }); SelectedCliente.Vinculos?.ToList().ForEach(delegate(ClienteVinculo vinculo) { ((DomainBase)vinculo).Initialize(); }); Initialized = true; } private async void WorkOnSelectedCliente(Cliente value) { if (value != null && ((DomainBase)value).Id != 0L && !IsLoading) { Loading(isLoading: true); Cliente cliente = await _servico.BuscarCliente(((DomainBase)value).Id); if (cliente.ResponsavelAssinatura == null) { cliente.ResponsavelAssinatura = new ResponsavelAssinatura { IdCliente = ((DomainBase)cliente).Id }; } Cliente val = cliente; val.Telefones = await _servico.BuscarTelefonesAsync(((DomainBase)value).Id); val = cliente; val.Emails = await _servico.BuscarEmailsAsync(((DomainBase)value).Id); val = cliente; val.Enderecos = await _servico.BuscarEnderecosAsync(((DomainBase)value).Id); val = cliente; val.Contatos = await _servico.BuscarContatosAsync(((DomainBase)value).Id); val = cliente; val.Vinculos = await _servico.BuscarVinculosAsync(((DomainBase)value).Id); Origens = await _servico.BuscarOrigens(((DomainBase)value).Id); cliente.DocumentoPrincipal = cliente.DocumentoPrincipal.GetValueOrDefault(); ClienteExcluido = cliente.Excluido; if (SelectedCliente != null) { DomainBase.Copy(SelectedCliente, cliente); JuridicaouFisica(SelectedCliente.Documento); ((DomainBase)SelectedCliente).Initialize(); ClienteSelecionado = cliente; } NascimentoCliente = ((value != null && value.Nascimento.HasValue) ? value.Nascimento : new DateTime?(Funcoes.GetNetworkTime().Date)); HabilitaCliente = ((value != null && value.PrimeiraHabilitacao.HasValue) ? value.PrimeiraHabilitacao : new DateTime?(Funcoes.GetNetworkTime().Date)); VencimentoHabCliente = ((value != null && value.VencimentoHabilitacao.HasValue) ? value.VencimentoHabilitacao : new DateTime?(Funcoes.GetNetworkTime().Date)); ExpedicaoCliente = ((value != null && value.Expedicao.HasValue) ? value.Expedicao : new DateTime?(Funcoes.GetNetworkTime().Date)); Initialized = true; Loading(isLoading: false); } } public void JuridicaouFisica(string documento) { if (SelectedCliente != null) { ProfissaoText = ""; AtividadeText = ""; if (documento == null || ValidationHelper.OnlyNumber(documento).Length > 11) { VisibilityJuridica = (Visibility)0; VisibilityFisica = (Visibility)2; FieldNascimento = "FUNDAÇÃO"; FieldDocumento = "CNPJ"; SelectedCliente.Profissao = null; IsJuridica = true; } else { VisibilityJuridica = (Visibility)2; VisibilityFisica = (Visibility)0; FieldNascimento = "NASCIMENTO"; FieldDocumento = "CPF"; SelectedCliente.Atividade = null; IsJuridica = false; } } } public void IncluirEmail() { //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Expected O, but got Unknown if (SelectedCliente != null) { if (Emails == null) { Emails = new ObservableCollection(); } EnableAddEmail = Emails.Count < 9; ClienteEmail item = new ClienteEmail { Cliente = SelectedCliente, Ordem = Emails.Count + 1 }; Emails.Add(item); OnPropertyChanged("IncluirEmail"); } } public void IncluirTelefone() { //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Expected O, but got Unknown if (SelectedCliente != null) { if (Telefones == null) { Telefones = new ObservableCollection(); } EnableAddTelephone = Telefones.Count < 9; ClienteTelefone item = new ClienteTelefone { Cliente = SelectedCliente, Tipo = (TipoTelefone)1, Ordem = Telefones.Count + 1 }; Telefones.Add(item); OnPropertyChanged("IncluirTelefone"); } } public async Task IncluirOrigem(string name) { if (SelectedCliente != null && !string.IsNullOrWhiteSpace(name)) { if (Origens == null) { Origens = new ObservableCollection(); } if (Origens.Any((OrigemCliente x) => x.Nome?.Trim() == name.Trim())) { await ShowMessage("JÁ EXISTE UMA ORIGEM " + name + ". PROCESSO CANCELADO."); return; } Origens.Insert(0, new OrigemCliente { Cliente = SelectedCliente, Nome = name, TipoOrigem = 1L }); OnPropertyChanged("Origens"); } } public void IncluirEndereco() { //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Expected O, but got Unknown if (SelectedCliente != null) { if (Enderecos == null) { Enderecos = new ObservableCollection(); } EnableAddAddress = Enderecos.Count < 9; ClienteEndereco item = new ClienteEndereco { Cliente = SelectedCliente, Ordem = Enderecos.Count + 1 }; Enderecos.Add(item); OnPropertyChanged("IncluirEndereco"); } } public void IncluirContato() { //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Expected O, but got Unknown if (SelectedCliente != null) { if (Contatos == null) { Contatos = new ObservableCollection(); } MaisContato item = new MaisContato { Cliente = SelectedCliente }; EnableAddContact = Contatos.Count < 9; Contatos.Add(item); OnPropertyChanged("IncluirContato"); } } public bool IncluirVinculo() { //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_006e: Expected O, but got Unknown if (Vinculo == null || ((DomainBase)Vinculo).Id == ((DomainBase)SelectedCliente).Id) { return false; } if (Vinculos == null) { Vinculos = new ObservableCollection(); } if (Vinculos.Any((ClienteVinculo x) => ((DomainBase)x.Cliente1).Id == ((DomainBase)Vinculo).Id || ((DomainBase)x.Cliente2).Id == ((DomainBase)Vinculo).Id)) { return false; } ClienteVinculo item = new ClienteVinculo { Cliente1 = SelectedCliente, Cliente2 = Vinculo }; Vinculos.Add(item); Vinculo = null; OnPropertyChanged("IncluirVinculo"); return true; } public async void ExcluirTelefone(ClienteTelefone telefone) { if (Telefones.Count < 2) { await ShowMessage("É NECESSÁRIO TER AO MENOS UM CONTATO TELEFÔNICO CADASTRADO."); return; } EnableAddTelephone = Telefones.Count <= 9; Telefones.Remove(telefone); } public async void ExcluirEmail(ClienteEmail email) { if (Emails.Count < 2 && Recursos.Configuracoes.All((ConfiguracaoSistema x) => (int)x.Configuracao != 29)) { await ShowMessage("É NECESSÁRIO TER AO MENOS UM CONTATO DE E-MAIL CADASTRADO."); return; } EnableAddEmail = Emails.Count <= 9; Emails.Remove(email); } public async void ExcluirEndereco(ClienteEndereco endereco) { if (Enderecos.Count < 2) { await ShowMessage("É NECESSÁRIO TER AO MENOS UM ENDEREÇO CADASTRADO."); return; } EnableAddAddress = Enderecos.Count <= 9; Enderecos.Remove(endereco); } public void ExcluirContato(MaisContato contato) { EnableAddContact = Contatos.Count <= 9; Contatos.Remove(contato); } public void ExcluirVinculo(ClienteVinculo vinculo) { Vinculos.Remove(vinculo); } public async Task Validate(ClienteEmail item) { if (ValidationHelper.ValidateMail(((EmailBase)item).Email)) { return true; } await ShowMessage("ENDEREÇO DE E-MAIL INVÁLIDO"); return false; } public void IncluirCliente() { //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Expected O, but got Unknown //IL_004c: Expected O, but got Unknown //IL_0083: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_00a0: Unknown result type (might be due to invalid IL or missing references) //IL_00b1: Expected O, but got Unknown //IL_00bd: Unknown result type (might be due to invalid IL or missing references) //IL_00c2: Unknown result type (might be due to invalid IL or missing references) //IL_00ce: Unknown result type (might be due to invalid IL or missing references) //IL_00df: Expected O, but got Unknown //IL_00eb: Unknown result type (might be due to invalid IL or missing references) //IL_00f0: Unknown result type (might be due to invalid IL or missing references) //IL_00fc: Unknown result type (might be due to invalid IL or missing references) //IL_010d: Expected O, but got Unknown DateTime date = Funcoes.GetNetworkTime().Date; SelectedCliente = new Cliente { IdEmpresa = Recursos.Usuario.IdEmpresa, DocumentoPrincipal = (TipoDocumento)0, ClienteDesde = date, ResponsavelAssinatura = new ResponsavelAssinatura() }; NascimentoCliente = date; HabilitaCliente = date; VencimentoHabCliente = date; ExpedicaoCliente = date; Telefones = new ObservableCollection { new ClienteTelefone { Cliente = SelectedCliente, Tipo = (TipoTelefone)1, Ordem = 1 } }; Enderecos = new ObservableCollection { new ClienteEndereco { Cliente = SelectedCliente, Ordem = 1 } }; Emails = new ObservableCollection { new ClienteEmail { Cliente = SelectedCliente, Ordem = 1 } }; Contatos = new ObservableCollection(); Vinculos = new ObservableCollection(); Origens = new ObservableCollection(); Salvando = true; Alterar(alterar: true); } public async void CancelarAlteracao() { Loading(isLoading: true); IsLoading = true; Alterar(alterar: false); await CarregaCliente(ClienteSelecionado); Salvando = false; IsLoading = false; Loading(isLoading: false); } public async void Excluir() { if (SelectedCliente == null || ((DomainBase)SelectedCliente).Id == 0L) { return; } if ((await new ApoliceServico().BuscarApolicesAsync(((DomainBase)SelectedCliente).Id, (FiltroStatusDocumento)4)).Count > 0) { await ShowMessage("NÃO É POSSÍVEL EXCLUIR O CLIENTE POIS POSSUI APÓLICES CADASTRADAS."); } else if (await ShowMessage("DESEJA EXCLUIR?", "SIM", "NÃO")) { Cliente cliente = SelectedCliente; cliente.Excluido = true; if (await _servico.Delete(cliente)) { ClienteSelecionado = null; MainViewModel.ClienteSelecionado = null; Gestor.Application.Actions.Actions.LimparCliente?.Invoke(); SelectedCliente = new Cliente { IdEmpresa = Recursos.Usuario.IdEmpresa, DocumentoPrincipal = (TipoDocumento)0, ClienteDesde = Funcoes.GetNetworkTime().Date }; Telefones = new ObservableCollection { new ClienteTelefone { Cliente = SelectedCliente, Tipo = (TipoTelefone)1, Ordem = 1 } }; Enderecos = new ObservableCollection { new ClienteEndereco { Cliente = SelectedCliente, Ordem = 1 } }; Emails = new ObservableCollection { new ClienteEmail { Cliente = SelectedCliente, Ordem = 1 } }; Contatos = new ObservableCollection(); Vinculos = new ObservableCollection(); Origens = new ObservableCollection(); string descricao = $"EXCLUIU CLIENTE \"{cliente.Nome}\", ID: {((DomainBase)cliente).Id}"; RegistrarAcao(descricao, ((DomainBase)cliente).Id, (TipoTela)1, $"CLIENTE \"{SelectedCliente.Nome}\", ID: {((DomainBase)SelectedCliente).Id}"); ToggleSnackBar("CLIENTE EXCLUÍDO COM SUCESSO"); } } } public async Task>> Salvar() { List list = Telefones.Where((ClienteTelefone x) => !string.IsNullOrEmpty(((TelefoneBase)x).Numero)).ToList(); List list2 = Enderecos.Where((ClienteEndereco x) => !string.IsNullOrEmpty(((EnderecoBase)x).Endereco)).ToList(); List list3 = Contatos?.Where((MaisContato x) => !string.IsNullOrEmpty(x.Nome)).ToList(); List emails = Emails.Where((ClienteEmail x) => !string.IsNullOrEmpty(((EmailBase)x).Email)).ToList(); List list4 = Vinculos?.Where((ClienteVinculo x) => x.Cliente2 != null && x.Parentesco.HasValue).ToList(); if (list4 != null && ClienteSelecionado != null) { foreach (ClienteVinculo item in list4.Where((ClienteVinculo c) => ((DomainBase)c.Cliente2).Id == ((DomainBase)ClienteSelecionado).Id)) { item.Parentesco = Funcoes.ParentescoInverso(item.Parentesco); } } SelectedCliente.Telefones = new ObservableCollection(list); SelectedCliente.Enderecos = new ObservableCollection(list2); SelectedCliente.Contatos = ((list3 != null) ? new ObservableCollection(list3) : null); SelectedCliente.Emails = new ObservableCollection(emails); SelectedCliente.Vinculos = ((list4 != null) ? new ObservableCollection(list4) : null); SelectedCliente.Origens = Origens?.ToList(); if (ValidationHelper.OnlyNumber(SelectedCliente.Documento).Length <= 11 && !string.IsNullOrWhiteSpace(ProfissaoText) && SelectedCliente.Profissao == null) { ProfissaoServico profissaoServico = new ProfissaoServico(); Cliente selectedCliente = SelectedCliente; ProfissaoServico profissaoServico2 = profissaoServico; Profissao val = new Profissao(); val.Nome = ProfissaoText; val.Codigo = "0"; Profissao val2 = val; ((DomainBase)val2).Id = await profissaoServico.FindLastId() + 1; selectedCliente.Profissao = await profissaoServico2.Save(val); if (!profissaoServico.Sucesso) { return null; } } if (ValidationHelper.OnlyNumber(SelectedCliente.Documento).Length > 11 && !string.IsNullOrWhiteSpace(AtividadeText) && SelectedCliente.Atividade == null) { AtividadeServico atividadeServico = new AtividadeServico(); Cliente selectedCliente = SelectedCliente; AtividadeServico atividadeServico2 = atividadeServico; Atividade val3 = new Atividade(); val3.Nome = AtividadeText; val3.Cnac = "0"; Atividade val4 = val3; ((DomainBase)val4).Id = await atividadeServico.FindLastId() + 1; selectedCliente.Atividade = await atividadeServico2.Save(val3); if (!atividadeServico.Sucesso) { return null; } } if (IsJuridica) { SelectedCliente.Cei = null; SelectedCliente.Rne = null; SelectedCliente.Caepf = null; } List> errorMessages = SelectedCliente.Validate(); emails.ForEach(delegate(ClienteEmail x) { errorMessages.AddRange(x.Validate()); }); List> list5 = errorMessages; list5.AddRange(await Validate()); foreach (MaisContato contato in Contatos) { errorMessages.AddRange(contato.Validate()); } foreach (ClienteVinculo vinculo in Vinculos) { errorMessages.AddRange(vinculo.Validate()); } if (errorMessages.Count > 0) { return errorMessages; } bool insert = ((DomainBase)SelectedCliente).Id == 0; _saving = true; Cliente clienteSelecionado = ClienteSelecionado; int num2; if (clienteSelecionado == null || ((DomainBase)clienteSelecionado).Id != 0) { Cliente clienteSelecionado2 = ClienteSelecionado; long? num = ((clienteSelecionado2 != null) ? new long?(((DomainBase)clienteSelecionado2).Id) : null); Cliente selectedCliente2 = SelectedCliente; if (num == ((selectedCliente2 != null) ? new long?(((DomainBase)selectedCliente2).Id) : null)) { num2 = (Salvando ? 1 : 0); goto IL_0815; } } num2 = 0; goto IL_0815; IL_0815: bool flag = (byte)num2 != 0; if (flag) { flag = await ShowMessage("NÃO FOI POSSIVEL INCLUIR UM NOVO SEGURADO, TENTE NOVAMENTE"); } if (flag) { return null; } SelectedCliente = await _servico.Save(SelectedCliente, Salvando); if (!_servico.Sucesso) { return null; } if (Invoke) { Gestor.Application.Actions.Actions.SelectCliente?.Invoke(SelectedCliente); } await CarregaCliente(SelectedCliente); string text = (insert ? "INCLUIU" : "ALTEROU"); RegistrarAcao(text + " CLIENTE \"" + SelectedCliente.Nome + "\"", ((DomainBase)SelectedCliente).Id, (TipoTela)1, $"CLIENTE \"{SelectedCliente.Nome}\", ID: {((DomainBase)SelectedCliente).Id}"); ToggleSnackBar("CLIENTE SALVO COM SUCESSO"); if (Invoke) { ConsultaViewModel.DocumentoSelecionado = null; Gestor.Application.Actions.Actions.AtualizaContatos?.Invoke(); if (insert) { MainViewModel.ClienteSelecionado = SelectedCliente; if (await ShowMessage("DESEJA INCLUIR UMA APÓLICE AGORA?", "SIM", "NÃO")) { Gestor.Application.Actions.Actions.AcessaTela?.Invoke((TipoTela)2, ""); } } } Salvando = false; Alterar(alterar: false); _saving = false; return null; } private async Task>> Validate() { List> errors = new List>(); bool valida = !string.IsNullOrEmpty(SelectedCliente.Nome); switch (SelectedCliente.DocumentoPrincipal) { case 0L: if (!ValidationHelper.ValidateDocument(SelectedCliente.Documento)) { valida = false; } break; case 1L: if (!ValidationHelper.ValidateRne(SelectedCliente.Rne)) { valida = false; } break; case 2L: if (!ValidationHelper.ValidateCei(SelectedCliente.Cei)) { valida = false; } break; case 3L: if (!ValidationHelper.ValidateCaepf(SelectedCliente.Caepf)) { valida = false; } break; } if (ValidationHelper.ValidateDocument(SelectedCliente.Documento) && SelectedCliente.DocumentoPrincipal == (TipoDocumento?)0) { SelectedCliente.Documento = ValidationHelper.FormatDocument(SelectedCliente.Documento); } List list = ((!ValidationHelper.ValidateDocument(SelectedCliente.Documento)) ? new List() : (await new ClienteServico().BuscarCliente(SelectedCliente.Documento, null, (TipoFiltroCliente)2))); List clienteBase = list; if (!IsJuridica) { list = ((!ValidationHelper.ValidateCei(SelectedCliente.Cei)) ? new List() : (await new ClienteServico().BuscarCliente(SelectedCliente.Cei, null, (TipoFiltroCliente)2))); List clienteCei = list; list = ((!ValidationHelper.ValidateRne(SelectedCliente.Rne)) ? new List() : (await new ClienteServico().BuscarCliente(SelectedCliente.Rne, null, (TipoFiltroCliente)2))); List clienteRne = list; list = ((!ValidationHelper.ValidateCaepf(SelectedCliente.Caepf)) ? new List() : (await new ClienteServico().BuscarCliente(SelectedCliente.Caepf, null, (TipoFiltroCliente)2))); List list2 = list; clienteBase.AddRange(clienteCei ?? new List()); clienteBase.AddRange(clienteRne ?? new List()); clienteBase.AddRange(list2 ?? new List()); } string nome = ""; string docDuplicado = ""; if (clienteBase.Count > 0) { clienteBase.ForEach(delegate(Cliente x) { if (((DomainBase)x).Id != ((DomainBase)SelectedCliente).Id && x.IdEmpresa == SelectedCliente.IdEmpresa) { if (!string.IsNullOrEmpty(SelectedCliente.Documento) && x.Documento == SelectedCliente.Documento) { valida = false; nome = x.Nome; } if (!string.IsNullOrEmpty(SelectedCliente.Cei) && x.Cei == SelectedCliente.Cei) { docDuplicado = " (CEI)"; valida = false; nome = x.Nome; } if (!string.IsNullOrEmpty(SelectedCliente.Rne) && x.Rne == SelectedCliente.Rne) { docDuplicado = " (RNE)"; valida = false; nome = x.Nome; } if (!string.IsNullOrEmpty(SelectedCliente.Caepf) && x.Caepf == SelectedCliente.Caepf) { docDuplicado = " (CAEPF)"; valida = false; nome = x.Nome; } } }); } if (!valida && clienteBase.Count((Cliente x) => ((DomainBase)x).Id != ((DomainBase)SelectedCliente).Id) > 0) { if (!(await new VendedorUsuarioServico().FindVinculoByUsuario(((DomainBase)Recursos.Usuario).Id))) { errors.Add(new KeyValuePair("Documento", "O DOCUMENTO" + docDuplicado + " JÁ ESTÁ CADASTRADO PARA O CLIENTE " + nome)); } else { Cliente? obj = clienteBase.FirstOrDefault(); long idCliente = ((obj != null) ? ((DomainBase)obj).Id : 0); string text = string.Join("|", (await new VendedorServico().BuscarVinculosCliente(idCliente)).Select((Vendedor vendedor) => vendedor.Nome)); errors.Add(new KeyValuePair("Documento", "O DOCUMENTO" + docDuplicado + " JÁ ESTÁ CADASTRADO PARA O CLIENTE " + nome + ".\nEXISTENTE NO VINCULO COM VENDEDORES: " + text + " ")); } } if (SelectedCliente.Telefones == null || SelectedCliente.Telefones.Count == 0) { errors.Add(new KeyValuePair("Telefones", "NECESSITA-SE AO MENOS UM TELEFONE VÁLIDO.")); } if (Recursos.Configuracoes.All((ConfiguracaoSistema x) => (int)x.Configuracao != 29) && (SelectedCliente.Emails == null || SelectedCliente.Emails.Count == 0)) { errors.Add(new KeyValuePair("Emails|E-MAILS", "NECESSITA-SE AO MENOS UM E-MAIL VÁLIDO.")); } if (SelectedCliente.Enderecos == null || SelectedCliente.Enderecos.Count == 0) { errors.Add(new KeyValuePair("Enderecos|ENDEREÇOS", "NECESSITA-SE AO MENOS UM ENDEREÇO VÁLIDO.")); } return errors; } public async Task ExcluirOrigem(OrigemCliente origem) { Origens.Remove(origem); OnPropertyChanged("Origens"); } public async void AbrirLogAntigo() { Loading(isLoading: true); string text = await _servico.BuscarLogAntigo(((DomainBase)SelectedCliente).Id); Loading(isLoading: false); if (string.IsNullOrEmpty(text)) { await ShowMessage("NÃO HÁ LOG PARA ESSE CLIENTE"); } else { ShowDrawer(new LogSistemaAntigo(((DomainBase)SelectedCliente).Id, text), 0, close: false); } } public async void AddUsuarioCentralSegurado() { if (SelectedCliente == null || SelectedCliente.Emails.Count == 0) { return; } Loading(isLoading: true); string message = "CLIENTE CADASTRADO/ALTERADO COM SUCESSO!"; try { string text = ((SelectedCliente.Telefones.Count == 0) ? string.Empty : ("(" + ((TelefoneBase)SelectedCliente.Telefones[0]).Prefixo + ") " + ((TelefoneBase)SelectedCliente.Telefones[0]).Numero)); bool flag = SelectedCliente.Enderecos.Count > 0; Token val = new Token(); UsuarioCentralSegurado val2 = new UsuarioCentralSegurado { Id = "", Senha = "", Serial = val.Encrypt(Recursos.Empresa.Serial), FornecedorId = ApplicationHelper.IdFornecedor, Nome = val.Encrypt(SelectedCliente.Nome), Documento = val.Encrypt(SelectedCliente.Documento.Clear()), Email = val.Encrypt(((EmailBase)SelectedCliente.Emails[0]).Email), IdEmpresa = SelectedCliente.IdEmpresa, Telefone = val.Encrypt(text), Rua = (flag ? val.Encrypt(((EnderecoBase)SelectedCliente.Enderecos[0]).Endereco) : string.Empty), Numero = (flag ? val.Encrypt(((EnderecoBase)SelectedCliente.Enderecos[0]).Numero) : string.Empty), Bairro = (flag ? val.Encrypt(((EnderecoBase)SelectedCliente.Enderecos[0]).Bairro) : string.Empty), Cidade = (flag ? val.Encrypt(((EnderecoBase)SelectedCliente.Enderecos[0]).Cidade) : string.Empty), Estado = (flag ? val.Encrypt(((EnderecoBase)SelectedCliente.Enderecos[0]).Estado) : string.Empty), Cep = (flag ? val.Encrypt(((EnderecoBase)SelectedCliente.Enderecos[0]).Cep) : string.Empty), Corretora = val.Encrypt(Recursos.Empresa.Nome), UriCorretora = val.Encrypt(Connection.UrlCentralSegurado) }; HttpClient client = new HttpClient(); try { StringContent val3 = new StringContent(JsonConvert.SerializeObject((object)val2), Encoding.UTF8, "application/json"); Uri uri = Address.CentralSegurado.Append("Usuario").Append("AddAggerApp"); HttpResponseMessage response = await client.PostAsync(uri, (HttpContent)(object)val3); await _servico.AddCentralSegurado(((DomainBase)SelectedCliente).Id, response.IsSuccessStatusCode); if (!response.IsSuccessStatusCode) { message = "HOUVE(RAM) O(S) SEGUINTE(S) ERROS: " + (await response.Content.ReadAsStringAsync()).Replace(";", ", ").ToUpper(); } } finally { ((IDisposable)client)?.Dispose(); } } catch { message = "HOUVERAM ERROS AO CADASTRAR/ALTERAR O CLIENTE!"; } OnPropertyChanged("LabelAddUsuarioCentralSegurado"); Loading(isLoading: false); await ShowMessage(message); } }