using Dashboard.Contexto.Data;
using Dashboard.Contexto.Models;
using Dashboard.Dominio;
using Dashboard.Dominio.Components;
using Dashboard.Dominio.Interfaces;
using Dashboard.Dominio.Servicos.Relatorios;
using Dashboard.Dominio.ViewModel;
using Infraestrutura.ElmahLog;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Configuration;
using System.Web.Mvc;

namespace RelatorioIntegracao.Controllers
{
    public class TelemetriaPorHoraController : Controller
    {
        public ActionResult Index(string id = "", int? width = null, int? height = null, string firebird = "", string mysql = "", string filtros = "", string titulo = "", string fontColor = "", string backgroundColor = "", string Empresas = "", string Position = "", string requisicaointerna = "")
        {
            try
            {
                if (!String.IsNullOrEmpty(id))
                {// Caso tenha o id so retorna
                    return new JsonResult()
                    {
                        JsonRequestBehavior = JsonRequestBehavior.AllowGet
                    };
                }

                Filtro filtro = new Filtro(filtros);
                
                if (!String.IsNullOrEmpty(Empresas))
                {
                    Empresas = Empresas.Replace("&quot;", "\"");
                    filtro.AddFiltro("empresas", Empresas, String.Empty, Filtro.OPERADOR_LISTA);
                }

                DbContext context;
                ContextConfigService config = new ContextConfigService();

                if (!String.IsNullOrEmpty(mysql.Replace(",", "")))
                    context = config.ConfigMySql(mysql);
                else if (!String.IsNullOrEmpty(firebird.Replace(",", "")))
                    context = config.ConfigFirebird(firebird);
                else
                    context = new ContextEntity("ConnectionEntity");

                TelemetriaPorHoraService service = new TelemetriaPorHoraService(new Repository<Operacoes>(context), new Repository<TelemetriaHro>(context), new Repository<ConfiguracoesTelemetria>(context), filtro);

                IBaseViewModel viewModel = (IBaseViewModel)service.GetParams();
                Util.SetRequisicaoInterna = requisicaointerna.Trim().ToLower().Equals("1");

                viewModel.id = id;
                viewModel.width = width;
                viewModel.height = height;
                viewModel.firebird = firebird;
                viewModel.mysql = mysql;
                viewModel.filtros = filtros;
                viewModel.ServerAddress = WebConfigurationManager.AppSettings[Util.GetRequisicaoInterna];
                viewModel.DashboardTitle = titulo;
                viewModel.FontColor = fontColor;
                viewModel.BackgroundColor = backgroundColor;
                viewModel.Title = "Passageiros por FCV";
                viewModel.Empresas = Empresas;
                viewModel.Position = Position;
                viewModel.Requisicao = Util.GetRequisicaoInterna;
                viewModel.ViewAddress = WebConfigurationManager.AppSettings[Util.GetRequisicaoInterna] + "TelemetriaPorHora/ExportPdf";
                viewModel.dados.Add("ViewAddressData", WebConfigurationManager.AppSettings[Util.GetRequisicaoInterna] + "TelemetriaPorHora/GetData");
                viewModel.dados.Add("ViewAddresSubtipo", WebConfigurationManager.AppSettings[Util.GetRequisicaoInterna] + "TelemetriaPorHora/LoadSubtipo");
                viewModel.dados.Add("ViewAddresTipo", WebConfigurationManager.AppSettings[Util.GetRequisicaoInterna] + "TelemetriaPorHora/LoadTipo");
                viewModel.dados.Add("ViewAddressExcel", WebConfigurationManager.AppSettings[Util.GetRequisicaoInterna] + "TelemetriaPorHora/ExportExcel");
                viewModel.dados.Add("ViewAddresVinculacao", WebConfigurationManager.AppSettings[Util.GetRequisicaoInterna] + "TelemetriaPorHora/LoadVinculacao");
                viewModel.dados.Add("ViewAddresSubtipoVinculo", WebConfigurationManager.AppSettings[Util.GetRequisicaoInterna] + "TelemetriaPorHora/LoadSubtipoVinculacao");
                viewModel.dados.Add("ViewAddresCarregaOperacao", WebConfigurationManager.AppSettings[Util.GetRequisicaoInterna] + "TelemetriaPorHora/LoadOperacaoGrupoMacro");
                
                return View("Params", viewModel);
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
                return View("../Error/_404");
            }
        }

        public ActionResult GetData(string id = "", int? width = null, int? height = null, string firebird = "", string mysql = "", string titulo = "", string fontColor = "", string backgroundColor = "", string Empresas = "", string Position = "", int page = 0, string horaInicial = "", string horaFinal = "", string operacao = "", string tipo = "", string subTipo = "", string operacaoPagina = "", string tipo_relatorio = "", bool ranking_sintetico = false, bool pontos = false, string km_corte = "", string requisicao = "", bool agrupado = false)
        {
            try
            {
                IBaseViewModel viewModel;
                Filtro filtro = new Filtro();

                if (!String.IsNullOrEmpty(Empresas))
                {
                    Empresas = Empresas.Replace("&quot;", "");
                    filtro.AddFiltro("empresas", Empresas, String.Empty, Filtro.OPERADOR_LISTA);
                }

                filtro.AddFiltro("data", horaInicial, horaFinal, Filtro.OPERADOR_ENTRE);
                filtro.AddFiltro("operacao", operacao, null, Filtro.OPERADOR_IGUAL);
                filtro.AddFiltro("tipo", tipo, null, Filtro.OPERADOR_IGUAL);
                filtro.AddFiltro("subTipo", subTipo, null, Filtro.OPERADOR_LISTA);
                if (!ranking_sintetico)
                    filtro.AddFiltro("operacaoPagina", operacaoPagina, null, Filtro.OPERADOR_IGUAL);
                filtro.AddFiltro("tipo_relatorio", tipo_relatorio, null, Filtro.OPERADOR_IGUAL);
                filtro.AddFiltro("ranking_sintetico", ranking_sintetico.ToString(), null, Filtro.OPERADOR_IGUAL);
                filtro.AddFiltro("km_corte", km_corte, null, Filtro.OPERADOR_MAIOR);

                filtro.AddFiltro("pontos", pontos.ToString(), null, Filtro.OPERADOR_IGUAL);

                string strFiltro = filtro.ToString();

                DbContext context;
                ContextConfigService config = new ContextConfigService();

                if (!String.IsNullOrEmpty(mysql.Replace(",", "")))
                    context = config.ConfigMySql(mysql);
                else if (!String.IsNullOrEmpty(firebird.Replace(",", "")))
                    context = config.ConfigFirebird(firebird);
                else
                    context = new ContextEntity("ConnectionEntity");

                context.Database.Log = s => System.Diagnostics.Debug.WriteLine(s);

                TelemetriaPorHoraService service = new TelemetriaPorHoraService(new Repository<TelemetriaHro>(context), new Repository<TelemetriaHroa1>(context), new Repository<TelemetriaHroa2>(context), new Repository<TelemetriaHrom>(context), new Repository<TelemetriaRo>(context), new Repository<TelemetriaRoa1>(context), new Repository<TelemetriaRoa2>(context), new Repository<TelemetriaRom>(context), new Repository<AlarmesHroTelemetria>(context), new Repository<AlarmesHroa1Telemetria>(context), new Repository<AlarmesHroa2Telemetria>(context), new Repository<AlarmesHromTelemetria>(context), new Repository<AlarmesRoTelemetria>(context), new Repository<AlarmesRoa1Telemetria>(context), new Repository<AlarmesRoa2Telemetria>(context), new Repository<AlarmesRomTelemetria>(context), new Repository<OperacoesVinculacoesTabelas>(context), new Repository<Operacoes>(context), new Repository<Veiculos>(context), new Repository<Motoristas>(context), new Repository<Agrupamento>(context), new Repository<DescricaoAlarmesOperacao>(context), filtro);
                service.setTotalWidth((int)width);
                service.page = page;
                service.ranking_sintetico = ranking_sintetico;
                service.pontos = pontos;
                service.agrupado = agrupado;
                viewModel = (IBaseViewModel)service.GetData();

                if (viewModel != null)
                {
                    viewModel.id = id;
                    viewModel.width = width;
                    viewModel.height = height;
                    viewModel.firebird = firebird;
                    viewModel.mysql = mysql;
                    viewModel.filtros = strFiltro;
                    viewModel.ServerAddress = WebConfigurationManager.AppSettings[requisicao];
                    viewModel.DashboardTitle = titulo;
                    viewModel.FontColor = fontColor;
                    viewModel.BackgroundColor = backgroundColor;
                    viewModel.Title = "Passageiros Por FCV";
                    viewModel.Empresas = Empresas;
                    viewModel.Position = Position;
                    viewModel.Requisicao = requisicao;
                    viewModel.ViewAddress = WebConfigurationManager.AppSettings[requisicao] + "TelemetriaPorHora/ExportPdf";
                    viewModel.ServerAddress = WebConfigurationManager.AppSettings[requisicao];
                    viewModel.dados.Add("ViewAddressExcel", WebConfigurationManager.AppSettings[requisicao] + "TelemetriaPorHora/ExportExcel");
                    viewModel.dados.Add("ViewAddresCarregaOperacao", WebConfigurationManager.AppSettings[Util.GetRequisicaoInterna] + "TelemetriaPorHora/LoadOperacaoGrupoMacro");
                    viewModel.dados.Add("tipo_relatorio", tipo_relatorio);

                    return PartialView("Index", viewModel);
                }
                return null;
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
                return View("../Error/_404");
            }
        }

        public JsonResult ExportPdf(string firebird = "", string mysql = "", string filtros = "", string Empresas = "", bool pontos = false, int? orderBy = null, bool orderType = true, string requisicao = "", bool agrupado = false)
        {
            try
            {
                Filtro filtro = new Filtro(HttpUtility.HtmlDecode(HttpUtility.UrlDecode(filtros)));

                if (!String.IsNullOrEmpty(Empresas))
                    filtro.AddFiltro("empresas", Empresas.Replace("&quot;", ""), String.Empty, Filtro.OPERADOR_LISTA);

                filtro.AddFiltro("pontos", pontos.ToString(), null, Filtro.OPERADOR_IGUAL);

                DbContext context;
                ContextConfigService config = new ContextConfigService();

                if (!String.IsNullOrEmpty(mysql.Replace(",", "")))
                    context = config.ConfigMySql(mysql);
                else if (!String.IsNullOrEmpty(firebird.Replace(",", "")))
                    context = config.ConfigFirebird(firebird);
                else
                    context = new ContextEntity("ConnectionEntity");

                TelemetriaPorHoraService service = new TelemetriaPorHoraService(new Repository<TelemetriaHro>(context), new Repository<TelemetriaHroa1>(context), new Repository<TelemetriaHroa2>(context), new Repository<TelemetriaHrom>(context), new Repository<TelemetriaRo>(context), new Repository<TelemetriaRoa1>(context), new Repository<TelemetriaRoa2>(context), new Repository<TelemetriaRom>(context), new Repository<AlarmesHroTelemetria>(context), new Repository<AlarmesHroa1Telemetria>(context), new Repository<AlarmesHroa2Telemetria>(context), new Repository<AlarmesHromTelemetria>(context), new Repository<AlarmesRoTelemetria>(context), new Repository<AlarmesRoa1Telemetria>(context), new Repository<AlarmesRoa2Telemetria>(context), new Repository<AlarmesRomTelemetria>(context), new Repository<OperacoesVinculacoesTabelas>(context), new Repository<Operacoes>(context), new Repository<Veiculos>(context), new Repository<Motoristas>(context), new Repository<Agrupamento>(context), new Repository<DescricaoAlarmesOperacao>(context), filtro);
                service.Requisicao = requisicao;
                service.ranking_sintetico = Convert.ToBoolean(filtro.PegarValorCampo("ranking_sintetico"));
                service.pontos = pontos;
                service.agrupado = agrupado;
                service.orderBy = orderBy;
                service.orderType = orderType;

                return new JsonResult()
                {
                    Data = service.GeneratePDF(),
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet
                };
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
                return null;
            }
        }

        public JsonResult ExportExcel(string firebird = "", string mysql = "", string filtros = "", string Empresas = "", bool pontos = false, string requisicao = "")
        {
            try
            {
                Filtro filtro = new Filtro(HttpUtility.HtmlDecode(HttpUtility.UrlDecode(filtros)));

                if (!String.IsNullOrEmpty(Empresas))
                    filtro.AddFiltro("empresas", Empresas.Replace("&quot;", ""), String.Empty, Filtro.OPERADOR_LISTA);

                filtro.AddFiltro("pontos", pontos.ToString(), null, Filtro.OPERADOR_IGUAL);

                DbContext context;
                ContextConfigService config = new ContextConfigService();

                if (!String.IsNullOrEmpty(mysql.Replace(",", "")))
                    context = config.ConfigMySql(mysql);
                else if (!String.IsNullOrEmpty(firebird.Replace(",", "")))
                    context = config.ConfigFirebird(firebird);
                else
                    context = new ContextEntity("ConnectionEntity");

                TelemetriaPorHoraService service = new TelemetriaPorHoraService(new Repository<TelemetriaHro>(context), new Repository<TelemetriaHroa1>(context), new Repository<TelemetriaHroa2>(context), new Repository<TelemetriaHrom>(context), new Repository<TelemetriaRo>(context), new Repository<TelemetriaRoa1>(context), new Repository<TelemetriaRoa2>(context), new Repository<TelemetriaRom>(context), new Repository<AlarmesHroTelemetria>(context), new Repository<AlarmesHroa1Telemetria>(context), new Repository<AlarmesHroa2Telemetria>(context), new Repository<AlarmesHromTelemetria>(context), new Repository<AlarmesRoTelemetria>(context), new Repository<AlarmesRoa1Telemetria>(context), new Repository<AlarmesRoa2Telemetria>(context), new Repository<AlarmesRomTelemetria>(context), new Repository<OperacoesVinculacoesTabelas>(context), new Repository<Operacoes>(context), new Repository<Veiculos>(context), new Repository<Motoristas>(context), new Repository<Agrupamento>(context), new Repository<DescricaoAlarmesOperacao>(context), filtro);
                service.ranking_sintetico = Convert.ToBoolean(filtro.PegarValorCampo("ranking_sintetico"));
                service.pontos = pontos;
                service.Requisicao = requisicao;

                return new JsonResult()
                {
                    Data = service.GenerateExcel(),
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet
                };
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
                return null;
            }
        }

        public JsonResult LoadOperacaoGrupoMacro(string firebird = "", string mysql = "", string Empresas = "", string tipo = "", string grupo = "", string macro = "", string horaInicial = "", string horaFinal = "")
        {
            try
            {
                Filtro filtro = new Filtro();

                if (!String.IsNullOrEmpty(Empresas))
                    filtro.AddFiltro("empresas", Empresas.Replace("&quot;", "\""), String.Empty, Filtro.OPERADOR_LISTA);

                filtro.AddFiltro("data", horaInicial, horaFinal, Filtro.OPERADOR_ENTRE);
                filtro.AddFiltro("tipo", tipo, null, Filtro.OPERADOR_IGUAL);
                filtro.AddFiltro("grupo", grupo, null, Filtro.OPERADOR_SELECIONAR);
                filtro.AddFiltro("macro", macro, null, Filtro.OPERADOR_SELECIONAR);

                DbContext context;
                ContextConfigService config = new ContextConfigService();

                if (!String.IsNullOrEmpty(mysql.Replace(",", "")))
                    context = config.ConfigMySql(mysql);
                else if (!String.IsNullOrEmpty(firebird.Replace(",", "")))
                    context = config.ConfigFirebird(firebird);
                else
                    context = new ContextEntity("ConnectionEntity");

                TelemetriaPorHoraService service = new TelemetriaPorHoraService(new Repository<VinculacoesRegistros>(context), filtro);

                return Json(service.LoadOperacaoGrupoMacro(tipo, grupo, macro), JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
                return null;
            }
        }

        public JsonResult LoadVinculacao(string firebird = "", string mysql = "", string Empresas = "", string tipo = "")
        {
            try
            {
                Filtro filtro = new Filtro();

                if (!String.IsNullOrEmpty(Empresas))
                    filtro.AddFiltro("empresas", Empresas.Replace("&quot;", "\""), String.Empty, Filtro.OPERADOR_LISTA);

                filtro.AddFiltro("tipo", tipo, null, Filtro.OPERADOR_IGUAL);

                DbContext context;
                ContextConfigService config = new ContextConfigService();

                if (!String.IsNullOrEmpty(mysql.Replace(",", "")))
                    context = config.ConfigMySql(mysql);
                else if (!String.IsNullOrEmpty(firebird.Replace(",", "")))
                    context = config.ConfigFirebird(firebird);
                else
                    context = new ContextEntity("ConnectionEntity");

                TelemetriaPorHoraService service = new TelemetriaPorHoraService(new Repository<VinculacoesRegistros>(context), filtro);

                return Json(service.LoadVinculacoesRegistros(), JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
                return null;
            }
        }

        public JsonResult LoadSubtipoVinculacao(string firebird = "", string mysql = "", string Empresas = "", string horaInicial = "", string horaFinal = "", string operacao = "", string tipo = "", string vinculoPai = "")
        {
            try
            {
                Filtro filtro = new Filtro();

                if (!String.IsNullOrEmpty(Empresas))
                    filtro.AddFiltro("empresas", Empresas.Replace("&quot;", "\""), String.Empty, Filtro.OPERADOR_LISTA);

                filtro.AddFiltro("data", horaInicial, horaFinal, Filtro.OPERADOR_ENTRE);
                filtro.AddFiltro("operacao", operacao, null, Filtro.OPERADOR_IGUAL);
                filtro.AddFiltro("tipo", tipo, null, Filtro.OPERADOR_IGUAL);
                filtro.AddFiltro("vinculoPai", vinculoPai, null, Filtro.OPERADOR_LISTA);

                DbContext context;
                ContextConfigService config = new ContextConfigService();

                if (!String.IsNullOrEmpty(mysql.Replace(",", "")))
                    context = config.ConfigMySql(mysql);
                else if (!String.IsNullOrEmpty(firebird.Replace(",", "")))
                    context = config.ConfigFirebird(firebird);
                else
                    context = new ContextEntity("ConnectionEntity");

                TelemetriaPorHoraService service = new TelemetriaPorHoraService(
                    new Repository<TelemetriaHro>(context),
                    new Repository<TelemetriaHroa1>(context),
                    new Repository<TelemetriaHroa2>(context),
                    new Repository<TelemetriaHrom>(context),
                    new Repository<VinculacoesRegistros>(context),
                    new Repository<Motoristas>(context), 
                    filtro);

                return Json(service.LoadSubtipo(), JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
                return null;
            }
        }

        public JsonResult LoadSubtipo(string firebird = "", string mysql = "", string Empresas = "", string horaInicial = "", string horaFinal = "", string operacao = "", string tipo = "")
        {
            try
            {
                Filtro filtro = new Filtro();

                if (!String.IsNullOrEmpty(Empresas))
                    filtro.AddFiltro("empresas", Empresas.Replace("&quot;", "\""), String.Empty, Filtro.OPERADOR_LISTA);

                filtro.AddFiltro("data", horaInicial, horaFinal, Filtro.OPERADOR_ENTRE);
                filtro.AddFiltro("operacao", operacao, null, Filtro.OPERADOR_IGUAL);
                filtro.AddFiltro("tipo", tipo, null, Filtro.OPERADOR_IGUAL);

                DbContext context;
                ContextConfigService config = new ContextConfigService();

                if (!String.IsNullOrEmpty(mysql.Replace(",", "")))
                    context = config.ConfigMySql(mysql);
                else if (!String.IsNullOrEmpty(firebird.Replace(",", "")))
                    context = config.ConfigFirebird(firebird);
                else
                    context = new ContextEntity("ConnectionEntity");

                TelemetriaPorHoraService service = new TelemetriaPorHoraService(new Repository<TelemetriaHro>(context), new Repository<TelemetriaHroa1>(context), new Repository<TelemetriaHroa2>(context), new Repository<TelemetriaHrom>(context), new Repository<Veiculos>(context), new Repository<Motoristas>(context), new Repository<Agrupamento>(context), filtro);

                return Json(service.LoadSubtipo(), JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
                return null;
            }
        }

        public JsonResult LoadTipo(string firebird = "", string mysql = "", string Empresas = "", string operacao = "")
        {
            try
            {
                Filtro filtro = new Filtro();

                if (!String.IsNullOrEmpty(Empresas))
                    filtro.AddFiltro("empresas", Empresas.Replace("&quot;", "\""), String.Empty, Filtro.OPERADOR_LISTA);

                filtro.AddFiltro("operacao", operacao, null, Filtro.OPERADOR_IGUAL);

                DbContext context;
                ContextConfigService config = new ContextConfigService();

                if (!String.IsNullOrEmpty(mysql.Replace(",", "")))
                    context = config.ConfigMySql(mysql);
                else if (!String.IsNullOrEmpty(firebird.Replace(",", "")))
                    context = config.ConfigFirebird(firebird);
                else
                    context = new ContextEntity("ConnectionEntity");

                TelemetriaPorHoraService service = new TelemetriaPorHoraService(new Repository<Operacoes>(context), filtro);

                return Json(service.LoadTipo(), JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
                return null;
            }
        }
    }
}
