class Contabilidade::Relatorios::MapeamentosController < ApplicationController
	include ControllerConcern
	include ContabilidadeControllerConcern

	before_action :authenticate_usuario!
	before_action :autoriza_usuario!, except: [:imprimir]
	before_action :disponibiliza_dependencias

	def imprimir
		bloqueia_usuario_com_base_em :read, "contabilidade/mapeamentos"
		relatorio = params[:relatorio]

		if respond_to? relatorio.to_s, :private
			loa = CombinePDF.new
			loa << CombinePDF.parse(send(relatorio))
			send_data loa.to_pdf, filename: "#{relatorio}.pdf", type: "application/pdf", disposition: 'inline'
		else
			redirect_to :back, alert: 'Relatório selecionado não existe'
		end
	end

	def sem_lancamentos
		@template = "contabilidade/relatorios/mapeamentos/sem_lancamentos.pdf.slim"
		orientation = 'Portrait'

		@classe_selecionada = Object.const_get(params[:modelo_de_ativacao])
		coluna_de_data = @classe_selecionada.pesquisa_coluna("data")

		# # PESQUISA POR UMA COLUNA NO MODELO COM DATA E SELECIONA A PRIMEIRA ENCONTRADA OU A PRIMEIRA CONTENDO PARTE DO NOME DO MODELO
		# lista_de_palavras = params[:modelo_de_ativacao].downcase.split("::")
		# colunas_de_data = @classe_selecionada.column_names.select { |str| str.include?("data") }
		# if colunas_de_data.size > 1
		# 	coluna_de_data = colunas_de_data.grep(/#{lista_de_palavras.join('|')}/).first
		# 	if coluna_de_data.nil? && colunas_de_data.size > 0
		# 		coluna_de_data = colunas_de_data.first
		# 	end
		# else
		# 	coluna_de_data = colunas_de_data.first
		# end

		condicoes = []
		if params[:natureza_da_receita_id].present? && @classe_selecionada.column_names.include?("natureza_da_receita_id")
			condicoes << "natureza_da_receita_id = #{params[:natureza_da_receita_id]}"
		end

		if params[:sub_elemento_de_despesa_id].present? && @classe_selecionada.column_names.include?("sub_elemento_de_despesa_id")
			condicoes << "sub_elemento_de_despesa_id = #{params[:sub_elemento_de_despesa_id]}"
		end

		if params[:unidade_orcamentaria_id].present? && @classe_selecionada.column_names.include?("unidade_orcamentaria_id")
			condicoes << "#{@classe_selecionada.table_name}.unidade_orcamentaria_id = #{params[:unidade_orcamentaria_id]}"
		end

		if params[:conta_extra_orcamentaria_id].present? && @classe_selecionada.column_names.include?("conta_extra_orcamentaria_id")
			condicoes << "conta_extra_orcamentaria_id = #{params[:conta_extra_orcamentaria_id]}"
		end

		if coluna_de_data.present?
			ids_gerados = Contabilidade::MovimentacaoDoPlanoDeContas.where("data_de_lancamento between '#{params[:data_inicial].to_date.year}-1-1' and '#{params[:data_inicial].to_date.year}-12-31' and gerador_type = ?", params[:modelo_de_ativacao]).pluck(:gerador_id)
			if ids_gerados.empty?
				@registros = @classe_selecionada.where("#{coluna_de_data} between ? and ?", params[:data_inicial].to_date, params[:data_final].to_date).where(" #{condicoes.join(" AND ")}").order(coluna_de_data).all
			else
				@registros = @classe_selecionada.where("#{coluna_de_data} between ? and ? and id not in (?)", params[:data_inicial].to_date, params[:data_final].to_date, ids_gerados).where(" #{condicoes.join(" AND ")}").order(coluna_de_data).all
			end
		else
			ids_gerados = Contabilidade::MovimentacaoDoPlanoDeContas.where("gerador_type = ?", params[:modelo_de_ativacao]).pluck(:gerador_id)
			if ids_gerados.empty?
				@registros = @classe_selecionada.where(" #{condicoes.join(" AND ")}").all
			else
				@registros = @classe_selecionada.where("id not in (?)", ids_gerados).where(" #{condicoes.join(" AND ")}").order(coluna_de_data).all
			end
		end

		render_to_string pdf: "mapeamento",
			template: @template,
			orientation: orientation,
			disable_smart_shrinking: true,

			dpi: '96',
			header: {
				html: {
					template: 'layouts/_cabecalho_pdf_mapeamento.html.slim',
					locals: {
						titulo1: "RELATÓRIO DE MODELOS SEM LANÇAMENTOS DE EVENTOS",
						titulo2: "",
						titulo3: "#{@nome_relatorio}",
						titulo4: ""
					}
				},
				spacing: 5
			},
			footer: {
				html: {
					template: 'layouts/_rodape_pdf.html.slim'
				}
			},
			margin: @configuracoes.margens_customizadas(top: 0)
	end

	def conferencia
		@template = "contabilidade/relatorios/mapeamentos/conferencia.pdf.slim"
		orientation = 'Portrait'

		@classe_selecionada = Object.const_get(params[:modelo_de_ativacao])
		coluna_de_data = @classe_selecionada.pesquisa_coluna("data")

		condicoes = []
		if params[:natureza_da_receita_id].present? && @classe_selecionada.column_names.include?("natureza_da_receita_id")
			condicoes << "natureza_da_receita_id = #{params[:natureza_da_receita_id]}"
		end

		if params[:sub_elemento_de_despesa_id].present? && @classe_selecionada.column_names.include?("sub_elemento_de_despesa_id")
			condicoes << "sub_elemento_de_despesa_id = #{params[:sub_elemento_de_despesa_id]}"
		end

		if params[:unidade_orcamentaria_id].present? && @classe_selecionada.column_names.include?("unidade_orcamentaria_id")
			condicoes << "#{@classe_selecionada.table_name}.unidade_orcamentaria_id = #{params[:unidade_orcamentaria_id]}"
		end

		if params[:conta_extra_orcamentaria_id].present? && @classe_selecionada.column_names.include?("conta_extra_orcamentaria_id")
			condicoes << "conta_extra_orcamentaria_id = #{params[:conta_extra_orcamentaria_id]}"
		end

		if coluna_de_data.present?
			@registros = @classe_selecionada.where("#{coluna_de_data} between ? and ?", params[:data_inicial].to_date, params[:data_final].to_date).joins(:movimentacoes_do_plano_de_contas).where(" #{condicoes.join(" AND ")}").all.uniq
		else
			@registros = @classe_selecionada.joins(:movimentacoes_do_plano_de_contas).where(" #{condicoes.join(" AND ")}").all.uniq
		end

		if params[:minimo_de_eventos].present?
			@registros = @registros.map { |i| i if i.movimentacoes_do_plano_de_contas.debito.size >= params[:minimo_de_eventos].to_i }.compact
		end

		if params[:maximo_de_eventos].present?
			@registros = @registros.map { |i| i if i.movimentacoes_do_plano_de_contas.debito.size <= params[:maximo_de_eventos].to_i }.compact
		end

		render_to_string pdf: "mapeamento",
			template: @template,
			orientation: orientation,
			disable_smart_shrinking: true,
			no_stop_slow_scripts: true,

			dpi: '96',
			header: {
				html: {
					template: 'layouts/_cabecalho_pdf_mapeamento.html.slim',
					locals: {
						titulo1: "RELATÓRIO DE MODELOS SEM LANÇAMENTOS DE EVENTOS",
						titulo2: "",
						titulo3: "#{@nome_relatorio}",
						titulo4: ""
					}
				},
				spacing: 5
			},
			footer: {
				html: {
					template: 'layouts/_rodape_pdf.html.slim'
				}
			},
			margin: @configuracoes.margens_customizadas(top: 0)
	end

	def rgf
		@anexo = params[:numero_anexo]
		@quadrimestre = params[:quadrimestre]
		@ano = orcamento_atual.exercicio

		if params[:unidade_gestora].present?
			@unidade_gestora = params[:unidade_gestora]
		else
			@unidade_gestora = 'CONSOLIDADO'
		end

		@orcamento_anterior = Orcamento.where(exercicio: orcamento_atual.exercicio - 1).first

		if @anexo == '1'
			@data_final = Date.new(orcamento_atual.exercicio, @quadrimestre.to_i * 4, 1)
			@data_inicial = @data_final - 11.months
			@periodo = (@data_inicial..@data_final).to_a.map { |i| i if i.day == 1}.compact

			@mes_final = @quadrimestre.to_i * 4

			@existe_unidade_do_rpps = Loa::UnidadeOrcamentaria.joins(orgao: :orcamento).where("orcamento_id = ? and rpps is true", orcamento_atual.id).first.present?
		end

		@template = ""
		if @anexo == '1'
			@template = "contabilidade/relatorios/mapeamentos/rgf_anexo01.pdf.slim"
			@nome_relatorio = "DEMONSTRATIVO DA DESPESA COM PESSOAL"
			orientation = 'Landscape'
		elsif @anexo == '2'
			@template = "contabilidade/relatorios/mapeamentos/rgf_anexo02.pdf.slim"
			@nome_relatorio = "DEMONSTRATIVO DA DIVÍDA CONSOLIDADA LÍQUIDA"
			orientation = 'Portrait'
		elsif @anexo == '3'
			@template = "contabilidade/relatorios/mapeamentos/rgf_anexo03.pdf.slim"
			@nome_relatorio = "DEMONSTRATIVO DAS GARANTIAS E CONTRAGARANTIAS DE VALORES"
			orientation = 'Portrait'
		elsif @anexo == '4'
			@template = "contabilidade/relatorios/mapeamentos/rgf_anexo04.pdf.slim"
			@nome_relatorio = "DEMONSTRATIVO DAS OPERAÇÕES DE CRÉDITO"
			orientation = 'Landscape'
		elsif @anexo == '5'
			@template = "contabilidade/relatorios/mapeamentos/rgf_anexo05.pdf.slim"
			@nome_relatorio = "DEMONSTRATIVO DA DISPONIBILIDADE DE CAIXA E DOS RESTOS A PAGAR"
			orientation = 'Landscape'
		elsif @anexo == '6'
			@template = "contabilidade/relatorios/mapeamentos/rgf_anexo06.pdf.slim"
			@nome_relatorio = "DEMONSTRATIVO SIMPLIFICADO DO RELATÓRIO DE GESTÃO FISCAL"
			orientation = 'Portrait'
		end

		render_to_string pdf: "mapeamento",
			template: @template,
			orientation: orientation,
			disable_smart_shrinking: true,
			
			dpi: '96',
			header: {
				html: {
					template: 'layouts/_cabecalho_pdf_mapeamento.html.slim',
					locals: {
						titulo1: "#{@unidade_gestora}",
						titulo2: "RELATÓRIO DE GESTÃO FISCAL",
						titulo3: "#{@nome_relatorio}",
						titulo4: "Quadrimestre: #{params[:quadrimestre]}º Quadrimestre / Exercicio: #{@ano.to_s}"
					}
				},
				spacing: 5
			},
			footer: {
				html: {
					template: 'layouts/_rodape_pdf.html.slim'
				}
			},
			margin: @configuracoes.margens_customizadas(top: 0)
	end

	def imprimir_erros
		@erros = Contabilidade::ErroDeMovimentacaoPcasp.all

		respond_to do |format|
			format.pdf do
				render pdf: "cidadaos",
				orientation: 'Portrait',
				header: {
					html: {
						template: 'layouts/_cabecalho_pdf.html.slim',
						locals: { titulo1: 'Lista de Erros dos Eventos PCASP' , titulo2: "" }
					},
					spacing: 5
				},
				footer: { right: '[page]', font_size: 8 },
				disable_smart_shrinking: true,
				dpi: '96',
				margin: @configuracoes.margens_customizadas(top: 10)
			end
		end
	end

	def imprimir2
		@anexo = params[:numero_anexo]
		@bimestre_mes = params[:mes_de_referencia].to_i
		@periodo_atual = @bimestre_mes * 2
		@periodo_anterior = @periodo_atual - 2

		@data_final = Date.new(orcamento_atual.exercicio, @bimestre_mes.to_i * 2, 1)
		@data_inicial = @data_final - 11.months
		@periodo = (@data_inicial..@data_final).to_a.map { |i| i if i.day == 1}.compact
		@orcamento_anterior = Orcamento.where(exercicio: orcamento_atual.exercicio - 1).first


		# @numero_do_mes_incial = 1
		# @numero_do_mes_final = @bimestre.to_i
		# @numero_de_colunas_de_mes = @numero_do_mes_final - @numero_do_mes_incial
		# @data_inicial = '01/01/' + contexto_atual.exercicio.to_s
		# @data_final = '01/' + params[:bimestre].to_s.rjust(2, "0") + '/' + contexto_atual.exercicio.to_s


		# @meses = []
		# @data_referencia = @data_inicial.to_date
		# while @data_referencia.to_date < @data_final.to_date
		# 	@meses << [@data_referencia.month.to_i, @data_referencia.year.to_i]
		# 	@data_referencia = @data_referencia.to_date + 1.month
		# end

		if params[:unidade_gestora].present?
			@unidade_gestora = params[:unidade_gestora]
		else
			@unidade_gestora = 'CONSOLIDADO'
		end
	end

	def rreo
		@anexo = params[:numero_anexo]
		@bimestre_mes = params[:mes_de_referencia].to_i
		@periodo_atual = @bimestre_mes * 2
		@periodo_anterior = @periodo_atual - 2

		@data_final = Date.new(orcamento_atual.exercicio, @bimestre_mes.to_i * 2, 1)
		@data_inicial = @data_final - 11.months
		@periodo = (@data_inicial..@data_final).to_a.map { |i| i if i.day == 1}.compact
		@orcamento_anterior = Orcamento.where(exercicio: orcamento_atual.exercicio - 1).first

		@campos_manuais = Contabilidade::PeriodoMatrizDeSaldoContabil.where('mes_referencia = ? AND ano_referencia = ?', @data_final.month, orcamento_atual.exercicio).last.mapeamentos_manuais rescue Contabilidade::PeriodoMatrizDeSaldoContabil.none

		# @numero_do_mes_incial = 1
		# @numero_do_mes_final = @bimestre.to_i
		# @numero_de_colunas_de_mes = @numero_do_mes_final - @numero_do_mes_incial
		# @data_inicial = '01/01/' + contexto_atual.exercicio.to_s
		# @data_final = '01/' + params[:bimestre].to_s.rjust(2, "0") + '/' + contexto_atual.exercicio.to_s


		# @meses = []
		# @data_referencia = @data_inicial.to_date
		# while @data_referencia.to_date < @data_final.to_date
		# 	@meses << [@data_referencia.month.to_i, @data_referencia.year.to_i]
		# 	@data_referencia = @data_referencia.to_date + 1.month
		# end

		if params[:unidade_gestora].present?
			@unidade_gestora = params[:unidade_gestora]
		else
			@unidade_gestora = 'CONSOLIDADO'
		end

		@template = ""
		if @anexo == '1'
			@template = "contabilidade/relatorios/mapeamentos/rreo_anexo01.pdf.slim"
			@nome_relatorio = "BALANÇO ORÇAMENTÁRIO"
		elsif @anexo == '2'
			@template = "contabilidade/relatorios/mapeamentos/rreo_anexo02.pdf.slim"
			@nome_relatorio = "DEMONSTRATIVO DA EXECUÇÃO DAS DESPESAS POR FUNÇÃO/SUBFUNÇÃO"
		elsif @anexo == '3'
			@template = "contabilidade/relatorios/mapeamentos/rreo_anexo03.pdf.slim"
			@nome_relatorio = "DEMONSTRATIVO DA RECEITA CORRENTE LÍQUIDA"
		elsif @anexo == '4'
			@template = "contabilidade/relatorios/mapeamentos/rreo_anexo04.pdf.slim"
			@nome_relatorio = "DEMONSTRATIVO DAS RECEITAS E DESPESAS PREVIDENCIÁRIAS"
		elsif @anexo == '5'
			@template = "contabilidade/relatorios/mapeamentos/rreo_anexo05.pdf.slim"
			@nome_relatorio = "#"
		elsif @anexo == '6'
			@template = "contabilidade/relatorios/mapeamentos/rreo_anexo06.pdf.slim"
			@nome_relatorio = "DEMONSTRATIVO DOS RESULTADOS PRIMÁRIO E NOMINAL"
		elsif @anexo == '7'
			@template = "contabilidade/relatorios/mapeamentos/rreo_anexo07.pdf.slim"
			@nome_relatorio = "DEMONSTRATIVO DOS RESTOS A PAGAR POR PODER E ÓRGAO"
		elsif @anexo == '8'
			@template = "contabilidade/relatorios/mapeamentos/rreo_anexo08.pdf.slim"
			@nome_relatorio = "DEMONSTRATIVO DAS RECEITAS E DESPESAS COM MANUTENÇÃO E DESENVOLVIMENTO DO ENSINO - MDE"
		elsif @anexo == '9'
			@template = "contabilidade/relatorios/mapeamentos/rreo_anexo09.pdf.slim"
			@nome_relatorio = "Op. de Crédito e Desp. de Capital"
		elsif @anexo == '10'
			@template = "contabilidade/relatorios/mapeamentos/rreo_anexo10.pdf.slim"
			@nome_relatorio = "#"
		elsif @anexo == '11'
			@template = "contabilidade/relatorios/mapeamentos/rreo_anexo11.pdf.slim"
			@nome_relatorio = "Alienação de Ativos"
		elsif @anexo == '12'
			@template = "contabilidade/relatorios/mapeamentos/rreo_anexo12.pdf.slim"
			@nome_relatorio = "DEMONSTRATIVO DAS RECEITAS E DESPESAS COM AÇOES E SERVIÇOS PÚBLICOS DE SAÚDE"
		elsif @anexo == '13'
			@template = "contabilidade/relatorios/mapeamentos/rreo_anexo13.pdf.slim"
			@nome_relatorio = "DEMONSTRATIVO DAS PARCERIAS PÚBLICAS-PRIVADAS"
		elsif @anexo == '14'
			@template = "contabilidade/relatorios/mapeamentos/rreo_anexo14.pdf.slim"
			@nome_relatorio = "DEMONSTRATIVO SIMPLIFICADO DO RELATÓRIO RESUMIDO DA EXECUÇÃO ORÇAMENTÁRIA"
		end

		render_to_string pdf: "mapeamento",
			template: @template,
			orientation: 'Landscape',
			disable_smart_shrinking: true,
			
			dpi: '96',
			header: {
				html: {
					template: 'layouts/_cabecalho_pdf_mapeamento.html.slim',
					locals: {
						titulo1: "#{@unidade_gestora}",
						titulo2: "RELATÓRIO RESUMIDO DA EXECUÇÃO ORÇAMENTÁRIA",
						titulo3: "#{@nome_relatorio}",
						titulo4: "#{@meses_de_competencia[@periodo_atual - 1]} a #{@meses_de_competencia[@periodo_atual]} de 2023/Bimestre #{@meses_de_competencia[@periodo_atual - 1]}-#{@meses_de_competencia[@periodo_atual]}  "
					}
				},
				spacing: 5
			},
			footer: {
				html: {
					template: 'layouts/_rodape_pdf.html.slim'
				}
			},
			margin: @configuracoes.margens_customizadas(top: 10)
	end

	def disponibiliza_dependencias
		@configuracoes = Configuracao.last

		@meses_de_competencia = ['',"Janeiro","Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro" , "Outubro", "Novembro", "Dezembro"]
	
	end
end
