using Gestor.Application.Helpers; using Gestor.Application.Servicos; using Gestor.Application.Servicos.Ajuda; using Gestor.Application.Servicos.Ferramentas; using Gestor.Application.Servicos.Generic; using Gestor.Application.ViewModels.Generic; using Gestor.Common.Security; using Gestor.Model.API; using Gestor.Model.Common; using Gestor.Model.Domain.Common; using Gestor.Model.Domain.Generic; using Gestor.Model.Domain.Seguros; using Gestor.Model.License; using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Linq; using System.Runtime.CompilerServices; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace Gestor.Application.ViewModels { public class TutorialViewModel : BaseViewModel { private bool _fase1; private bool _fase2; private bool _fase3; private string _mensagem = "ESTAMOS PREPARANDO TUDO PRA VOCÊ INICIAR"; private string _nome; private string _usuario; private string _senha; private string _confirmacaoSenha; private ObservableCollection _seguradoras = new ObservableCollection(); private ObservableCollection _ramos = new ObservableCollection(); private bool _loadingVisibility; private long _idUsuario { get; set; } = (long)-1; public string ConfirmacaoSenha { get { return this._confirmacaoSenha; } set { this._confirmacaoSenha = value; base.OnPropertyChanged("ConfirmacaoSenha"); } } private Customer Empresa { get; set; } public bool Fase1 { get { return this._fase1; } set { this._fase1 = value; base.OnPropertyChanged("Fase1"); } } public bool Fase2 { get { return this._fase2; } set { this._fase2 = value; base.OnPropertyChanged("Fase2"); } } public bool Fase3 { get { return this._fase3; } set { this._fase3 = value; base.OnPropertyChanged("Fase3"); } } public bool LoadingVisibility { get { return this._loadingVisibility; } set { this._loadingVisibility = value; base.OnPropertyChanged("LoadingVisibility"); } } public string Mensagem { get { return this._mensagem; } set { this._mensagem = value; base.OnPropertyChanged("Mensagem"); } } public string Nome { get { return this._nome; } set { this._nome = value; base.OnPropertyChanged("Nome"); } } public ObservableCollection Ramos { get { return this._ramos; } set { this._ramos = value; base.OnPropertyChanged("Ramos"); } } public ObservableCollection Seguradoras { get { return this._seguradoras; } set { this._seguradoras = value; base.OnPropertyChanged("Seguradoras"); } } public string Senha { get { return this._senha; } set { this._senha = value; base.OnPropertyChanged("Senha"); } } public string Usuario { get { return this._usuario; } set { this._usuario = value; base.OnPropertyChanged("Usuario"); } } public TutorialViewModel() { base.EnableFields = true; } public async Task Concluir() { bool flag; SeguradoraServico seguradoraServico; RamoServico ramoServico; this.Fase3 = false; ObservableCollection ramos = this.Ramos; if (!ramos.All((Ramo x) => !x.get_Ativo())) { this.Mensagem = "ESTAMOS TERMINANDO AS CONFIGURAÇÕES INICIAIS E LOGO MAIS VOCÊ PODERÁ UTILIZAR."; if (await this.UsuarioInicial()) { seguradoraServico = new SeguradoraServico(); foreach (Seguradora seguradora in this.Seguradoras) { await seguradoraServico.Save(seguradora, null, true); if (seguradoraServico.Sucesso) { continue; } flag = false; seguradoraServico = null; ramoServico = null; return flag; } ramoServico = new RamoServico(); foreach (Ramo ramo in this.Ramos) { await ramoServico.Save(ramo, null); if (ramoServico.Sucesso) { continue; } flag = false; seguradoraServico = null; ramoServico = null; return flag; } await (new BaseServico()).LoadInicialParameters(); flag = true; } else { flag = false; } } else { await base.ShowMessage("NECESSÁRIO AO MENOS UM RAMO ATIVO PARA PROSSEGUIR.", "OK", "", false); this.Fase3 = true; flag = false; } seguradoraServico = null; ramoServico = null; return flag; } public async Task CriarBanco() { string str; string str1 = await (new ConnectionHelper()).VerifyConnection(); if (str1 != null) { str = str1; } else { Instancia.ExcluirCfg(); str = await this.VerificaEmpresa(); } return str; } public void DesativarRamos() { foreach (Ramo ramo in this.Ramos) { ramo.set_Ativo(false); } this.Ramos = new ObservableCollection(this.Ramos); } public void DesativarSeguradoras() { foreach (Seguradora seguradora in this.Seguradoras) { seguradora.set_Ativo(false); } this.Seguradoras = new ObservableCollection(this.Seguradoras); } public async Task IniciarConfiguracoes() { List seguradoras; base.EnableButtons = false; ConnectionHelper connectionHelper = new ConnectionHelper(); EmpresaServico empresaServico = new EmpresaServico(); Gestor.Model.Domain.Common.Empresa empresa = await empresaServico.BuscarEmpresaPorId((long)1); this.Empresa = await Connection.Get(string.Format("Customer/{0}", ApplicationHelper.IdFornecedor), true, false); if (empresa == null) { await empresaServico.Save(this.Empresa); } BaseServico baseServico = new BaseServico(); ControleArquivoDigital controleArquivoDigital = await baseServico.BuscarControle(); if (controleArquivoDigital == null) { controleArquivoDigital = new ControleArquivoDigital(); controleArquivoDigital.set_Catalogo(Connection.Catalog); controleArquivoDigital.set_Tabela("Arquivos"); } ControleArquivoDigital controleArquivoDigital1 = controleArquivoDigital; if (controleArquivoDigital1.get_Id() == 0) { await baseServico.SalvarControle(controleArquivoDigital1); } VendedorServico vendedorServico = new VendedorServico(); Vendedor vendedor = await vendedorServico.BuscarCorretora(); if (vendedor == null) { vendedor = new Vendedor(); vendedor.set_IdEmpresa((long)1); vendedor.set_Nome(this.Empresa.get_Name()); vendedor.set_Ativo(true); vendedor.set_Corretora(true); } Vendedor vendedor1 = vendedor; if (vendedor1.get_Id() == 0) { Repasse repasse = new Repasse(); repasse.set_Forma(new FormaRepasse?(1)); repasse.set_Incidencia(new TipoIncidencia?(1)); repasse.set_Ativo(true); repasse.set_Tipo(new TipoRepasse?(2)); repasse.set_ValorNovo(decimal.Zero); repasse.set_ValorRenovacao(decimal.Zero); await vendedorServico.Save(vendedor1, repasse); if (!vendedorServico.Sucesso) { connectionHelper = null; empresaServico = null; empresa = null; baseServico = null; vendedorServico = null; seguradoras = null; return; } } await (new Gestor.Application.Servicos.ArquivoDigitalServico()).Criar(); string str = await connectionHelper.AtualizarBanco(); if (str == null) { seguradoras = await (new SeguradoraServico()).BuscarSeguradoras(); List ramos = await (new RamoServico()).BuscarRamos(); TutorialViewModel observableCollection = this; List seguradoras1 = seguradoras; observableCollection.Seguradoras = new ObservableCollection( from x in seguradoras1 orderby x.get_Nome() select x); TutorialViewModel tutorialViewModel = this; List ramos1 = ramos; tutorialViewModel.Ramos = new ObservableCollection( from x in ramos1 orderby x.get_Nome() select x); base.EnableButtons = true; } else { await base.ShowMessage(str, "OK", "", false); } connectionHelper = null; empresaServico = null; empresa = null; baseServico = null; vendedorServico = null; seguradoras = null; } private async Task SalvarUsuario(Gestor.Model.Domain.Seguros.Usuario verificaUsuario) { long id; string ssoId; TutorialViewModel tutorialViewModel = this; Gestor.Model.Domain.Seguros.Usuario usuario = verificaUsuario; if (usuario != null) { id = usuario.get_Id(); } else { id = (long)0; } tutorialViewModel._idUsuario = id; Gestor.Model.Domain.Seguros.Usuario usuario1 = new Gestor.Model.Domain.Seguros.Usuario(); usuario1.set_Id(this._idUsuario); usuario1.set_Nome(this.Nome); usuario1.set_Login(this.Usuario); usuario1.set_Senha((new Token()).AggerEncrypt(this.Senha)); usuario1.set_Administrador(true); usuario1.set_Excluido(false); usuario1.set_IdEmpresa((long)1); usuario1.set_PermissaoAggilizador(new long?((long)1)); Gestor.Model.Domain.Seguros.Usuario usuario2 = verificaUsuario; if (usuario2 != null) { ssoId = usuario2.get_SsoId(); } else { ssoId = null; } usuario1.set_SsoId(ssoId); Gestor.Model.Domain.Seguros.Usuario usuario3 = usuario1; usuario3 = await (new UsuarioServico()).Save(usuario3); this._idUsuario = usuario3.get_Id(); Recursos.Usuario = usuario3; } public async Task UsuarioInicial() { bool flag; Gestor.Model.Domain.Seguros.Usuario usuario = await (new UsuarioServico()).BuscaUsuarioInicial(this.Usuario, this.Senha); if (usuario != null) { await this.SalvarUsuario(usuario); flag = true; } else { await base.ShowMessage("USUÁRIO JÁ EXISTE E A SENHA ESTÁ INCORRETA, REINICIE O SISTEMA!", "OK", "", false); flag = false; } return flag; } public async Task ValidarLogin() { bool flag; this.Fase1 = false; this.Mensagem = "ESTAMOS VALIDANDO AS INFORMAÇÕES"; if (string.IsNullOrEmpty(this.Usuario) || string.IsNullOrEmpty(this.Senha) || string.IsNullOrEmpty(this.ConfirmacaoSenha) || string.IsNullOrEmpty(this.Nome)) { await base.ShowMessage("NECESSÁRIO PREENCHER O NOME COMPLETO, USUÁRIO, SENHA E CONFIRMAÇÃO DA SENHA PARA PROSSEGUIR.", "OK", "", false); this.Fase1 = true; flag = true; } else if (!string.IsNullOrEmpty(this.Usuario) && !Regex.IsMatch(this.Usuario, "^(?!.*(@.*@|@\\.|\\.@|--|\\.\\.|-\\.|\\.-|-@|@-))[a-zA-Z0-9](?:[a-zA-Z0-9@.-]*[a-zA-Z0-9])?(?: [a-zA-Z0-9](?:[a-zA-Z0-9@.-]*[a-zA-Z0-9])?)?$")) { string[] newLine = new string[] { "USUÁRIO DEVE CONTER APENAS LETRAS E NÚMEROS,", Environment.NewLine, "NÃO DEVE CONTER MAIS DE UM ESPAÇO,", Environment.NewLine, "NÃO DEVE TER ESPAÇO NO INICIO E NO FIM.", Environment.NewLine, "EXEMPLO VALIDO:", Environment.NewLine, "USUARIO01 OU USUARIO 02 OU USUARIO.03" }; await base.ShowMessage(string.Concat(newLine), "OK", "", false); this.Fase1 = true; flag = true; } else if (this.Usuario.Length > 30) { await base.ShowMessage("USUÁRIO SOMENTE DEVE CONTER NO MÁXIMO 30 CARACTERES", "OK", "", false); this.Fase1 = true; flag = true; } else if (this.Senha != this.ConfirmacaoSenha) { await base.ShowMessage("A SENHA E A CONFIRMAÇÃO DA SENHA ESTÃO DIFERENTES, CORRIJA PARA PROSSEGUIR.", "OK", "", false); this.Fase1 = true; flag = true; } else if (await this.UsuarioInicial()) { while (this.Seguradoras.Count == 0) { await Task.Delay(25); } this.Fase1 = false; this.Fase2 = true; flag = true; } else { flag = false; } return flag; } public async Task ValidarSeguradoras() { this.Fase2 = false; ObservableCollection seguradoras = this.Seguradoras; if (!seguradoras.All((Seguradora x) => !x.get_Ativo())) { this.Fase2 = false; this.Fase3 = true; } else { await base.ShowMessage("NECESSÁRIO AO MENOS UMA SEGURADORA ATIVA PARA PROSSEGUIR.", "OK", "", false); this.Fase2 = true; } } public async Task VerificaAcesso() { bool flag; Instalacao instalacao; LicenseHelper licenseHelper = new LicenseHelper(); bool flag1 = false; if (!await licenseHelper.VerificarMaquina()) { base.Loading(false); while (!flag1) { List instalacoes = await licenseHelper.GetInstalacoes(); if (instalacoes.Count != 0) { List instalacaos = instalacoes; IOrderedEnumerable ultimoAcesso = from x in instalacaos orderby x.get_UltimoAcesso() descending select x; Instalacao instalacao1 = ultimoAcesso.FirstOrDefault((Instalacao x) => x.get_UsuarioId() == Recursos.Usuario.get_Id()); bool flag2 = instalacao1 != null; if (flag2) { flag2 = await base.ShowMessage(string.Concat("SEU ULTIMO ACESSO FOI NA MAQUINA ", instalacao1.get_NomeMaquina(), ". DESEJA SUBSTITUIR A LICENÇA PARA ESSA MAQUINA?"), "SIM", "NÃO", false); } if (!flag2) { instalacao = await base.ShowInstalacoes(instalacoes); } else { instalacao = instalacao1; } Instalacao instalacao2 = instalacao; if (instalacao2 != null) { await (new AjudaServico()).ExcluirInstalacao(instalacao2.get_Id()); flag2 = await licenseHelper.VerificarMaquina(); flag1 = flag2; instalacoes = null; instalacao1 = null; } else { await base.ShowMessage("MÁQUINA NÃO REGISTRADA", "OK", "", false); flag = false; licenseHelper = null; return flag; } } else { await base.ShowMessage("ACESSO NEGADO, NÃO EXISTEM LICENÇAS VÁLIDAS.", "OK", "", false); flag = false; licenseHelper = null; return flag; } } } flag = true; licenseHelper = null; return flag; } public async Task VerificaEmpresa() { string str; ConnectionHelper connectionHelper = new ConnectionHelper(); this.Empresa = await Connection.Get(string.Format("Customer/{0}", ApplicationHelper.IdFornecedor), true, false); EmpresaServico empresaServico = new EmpresaServico(); if (!connectionHelper.ExisteEmpresa()) { await empresaServico.Save(this.Empresa); if (!empresaServico.Sucesso) { str = "ERRO AO CRIAR BANCO DE DADOS"; connectionHelper = null; empresaServico = null; return str; } } else if (!connectionHelper.BDConvertido()) { str = "HOUVE UM ERRO NO ACESSO! REINICIE O SISTEMA!"; connectionHelper = null; empresaServico = null; return str; } str = null; connectionHelper = null; empresaServico = null; return str; } public async Task VerificarUsuario() { Instancia.ExcluirCfg(); Gestor.Model.Domain.Seguros.Usuario usuario = await (new UsuarioServico()).BuscarUsuarioPorId((long)1); if (usuario != null) { this.Nome = usuario.get_Nome(); this.Usuario = usuario.get_Login(); this._idUsuario = usuario.get_Id(); } } } }