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.Helpers;
using System.Web.Mvc;

namespace RelatorioIntegracao.Controllers
{
    public class MacrosController : Controller
    {

        public MacrosService GetMacros(string mysql, string firebird, IFiltro filtro)
        {
            try
            {
                MacrosService service = null;
                DbContext context;
                DbContext contextFirebird;
                ContextConfigService config = new ContextConfigService();
                var isMySQL = !String.IsNullOrEmpty(mysql.Replace(",", ""));
                var isFirebird = !String.IsNullOrEmpty(firebird.Replace(",", ""));
                if (isMySQL) context = config.ConfigMySql(mysql);
                else if (isFirebird) context = config.ConfigFirebird(firebird);
                else context = new ContextEntity("ConnectionEntity");

                service = new MacrosService(new Repository<TabelasRepositorio>(context), new Repository<Motoristas>(context), new Repository<Coletores>(context), 
                    new Repository<SetoresRealizados>(context), new Repository<Configuracoes>(context), new Repository<Operacoes>(context),
                    new Repository<GruposControleVeiculos>(context), new Repository<VinculacaoUsuarioGiseyes>(context), filtro, context);

                return service;
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
                return null;
            }
        }

        public ActionResult Index(string id = "", int? width = null, int? height = null, string firebird = "", string mysql = "", string filtros = "", string Empresas = "", string requisicaointerna = "")
        {
            try
            {
                Filtro filtro = new Filtro(filtros);

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

                if (!String.IsNullOrEmpty(id))
                    return new JsonResult() { JsonRequestBehavior = JsonRequestBehavior.AllowGet };

                filtro.AddFiltro("data", "", "", "hoje");
                MacrosService service = GetMacros(mysql, firebird, 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.Empresas = Empresas;
                viewModel.filtros = filtros;

                viewModel.ViewAddress = WebConfigurationManager.AppSettings[Util.GetRequisicaoInterna] + "Macros/ExportPdf";
                viewModel.ServerAddress = WebConfigurationManager.AppSettings[Util.GetRequisicaoInterna];

                viewModel.dados.Add("ViewAddressVeiculos", WebConfigurationManager.AppSettings[Util.GetRequisicaoInterna] + "Macros/LoadVeiculos");
                viewModel.dados.Add("ViewAddressMacro", WebConfigurationManager.AppSettings[Util.GetRequisicaoInterna] + "Macros/LoadMacros");
                viewModel.dados.Add("ViewAddressFiltrosMacro", WebConfigurationManager.AppSettings[Util.GetRequisicaoInterna] + "Macros/LoadFiltrosMacros");
                viewModel.dados.Add("ViewAddressData", WebConfigurationManager.AppSettings[Util.GetRequisicaoInterna] + "Macros/GetData");
                viewModel.dados.Add("ViewAddressExcel", WebConfigurationManager.AppSettings[Util.GetRequisicaoInterna] + "Macros/ExportExcel");
                return View("Params", viewModel);
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
                return View("../Error/_404");
            }
        }

        public JsonResult LoadFiltrosMacros(string firebird = "", string mysql = "", string macros = "")
        {
            try
            {
                Filtro filtro = new Filtro();
                filtro.AddFiltro("macros", macros, String.Empty, "selecionar");
                MacrosService service = GetMacros(mysql, firebird, filtro);
                return Json(service.LoadFiltrosMacros(), JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
                return null;
            }
        }

        public JsonResult LoadMacros(string firebird = "", string mysql = "", string dataInicio = "", string dataFim = "", string veiculos = "")
        {
            try
            {
                Filtro filtro = new Filtro();
                filtro.AddFiltro("dataSetores", dataInicio + " 00:00:00", dataFim + " 23:59:59", "entre");
                filtro.AddFiltro("veiculos", veiculos, String.Empty, "selecionar");
                MacrosService service = GetMacros(mysql, firebird, filtro);
                return Json(service.LoadMacros(), JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
                return null;
            }
        }

        public JsonResult LoadVeiculos(string firebird = "", string mysql = "", string Empresas = "", string operacoes = "", string dataInicio = "", string dataFim = "", string grupodecontrole = "", string macrosetor = "", int codigoUsuarioDashboard = 0)
        {
            try
            {
                Filtro filtro = new Filtro();

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

                filtro.AddFiltro("data", dataInicio, dataFim, Filtro.OPERADOR_ENTRE);

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

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

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

                MacrosService service = GetMacros(mysql, firebird, filtro);
                return Json(service.LoadVeiculos(codigoUsuarioDashboard), JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
                return null;
            }
        }

        public ActionResult GetData(string id = "", int? width = null, int? height = null, string firebird = "", string mysql = "", string dataInicio = "", string dataFim = "", string macros = "", string FiltrosMacros = "")
        {
            try
            {
                IBaseViewModel viewModel;
                Filtro filtro = new Filtro();

                filtro.AddFiltro("dataSetores", dataInicio + " 00:00:00", dataFim + " 23:59:59", "entre");
                filtro.AddFiltro("macros", macros, String.Empty, "selecionar");
                filtro.AddFiltro("filtroMacros", FiltrosMacros, String.Empty, "selecionar");

                if (!filtro.ContemValores())
                    return new JsonResult() { JsonRequestBehavior = JsonRequestBehavior.AllowGet };

                MacrosService service = GetMacros(mysql, firebird, filtro);
                viewModel = (IBaseViewModel)service.GetData();
                viewModel.id = id;
                viewModel.width = width;
                viewModel.height = height;
                viewModel.firebird = firebird;
                viewModel.mysql = mysql;
                viewModel.filtros = filtro.ToString();
                viewModel.ViewAddress = WebConfigurationManager.AppSettings[Util.GetRequisicaoInterna] + "Macros/ExportPdf";
                viewModel.ServerAddress = WebConfigurationManager.AppSettings[Util.GetRequisicaoInterna];
                viewModel.dados.Add("ViewAddressExcel", WebConfigurationManager.AppSettings[Util.GetRequisicaoInterna] + "Macros/ExportExcel");
                return View("Index", viewModel);
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
                return View("../Error/_404");
            }
        }

        public JsonResult ExportPdf(string firebird = "", string mysql = "", string filtros = "")
        {
            try
            {
                Filtro filtro = new Filtro(HttpUtility.HtmlDecode(HttpUtility.UrlDecode(filtros)));
                MacrosService service = GetMacros(mysql, firebird, filtro);
                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 = "")
        {
            try
            {
                Filtro filtro = new Filtro(HttpUtility.HtmlDecode(HttpUtility.UrlDecode(filtros)));
                MacrosService service = GetMacros(mysql, firebird, filtro);
                return new JsonResult()
                {
                    Data = service.GenerateExcel(),
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet
                };
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
                return null;
            }
        }
    }
}
