from selenium import webdriver
import pyautogui as pt
import shutil
import threading
import os
import re
import json
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from time import sleep
from selenium.common.exceptions import TimeoutException
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.support import expected_conditions as EC
from datetime import date, timedelta

try:
	import extract_data

except:
	try:
		from . import extract_data
	except:
		pass

try:
    import models_ as db
except:
    try:
        import models as db
    except:
        pass
try:
	from . import modulos
except:
	try:
		import modulos
	except:
		pass

pasta_bots=os.path.join(os.path.expanduser("~"), "api/estrutura_api/api/utils/bots")

data_vigente_={'mes':int(date.today().month),'ano':date.today().year}

class PastaAlocacao:
	def __init__(self, cnpj=None, mes=None, ano=None, pasta=None, arquivo=None):
		self.cnpj=cnpj
		self.mes=mes
		self.ano=ano
		self.pasta=pasta
		self.arquivo=arquivo

	def retornar_pasta(self, modo='user'):
		if self.cnpj!=None and self.mes!=None and self.mes!=None and self.ano!=None and self.pasta!=None and self.arquivo!=None:
			verificar_dados=[self.cnpj, self.mes, self.mes, self.ano, self.pasta, self.arquivo]
		try:
			match str(modo):	
				case 'user':
					pasta_user=os.path.expanduser('~')
					return pasta_user
				case 'especifica' if verificar_dados:
					pasta_arquivos=os.path.join(os.path.expanduser('~'),f'.arquivos_api/{self.cnpj}/{self.mes}/{self.ano}/{self.pasta}/{self.arquivo}')
					os.makedirs(pasta_arquivos, exist_ok=True)
					
					return pasta_arquivos
				
		except Exception as e:
			raise e


def formatar_data(data=None,mode='str_format'):
	if mode=='str_format' and data!=None:
		mes_formatado=None
		match data:
			case '01'| 1:
				mes_formatado=f'{data}-jan'
			case '02'|2:
				mes_formatado=f'{data}-fev'
			case '03'|3:
				mes_formatado=f'{data}-mar'
			case '04'|4:
				mes_formatado=f'{data}-abr'
			case '05'|5:
				mes_formatado=f'{data}-mai'
			case '06'|6:
				mes_formatado=f'{data}-jun'
			case '07'|7:
				mes_formatado=f'{data}-jul'
			case '08'|8:
				mes_formatado=f'{data}-ago'
			case '09'|9:
				mes_formatado=f'{data}-set'
			case '10'|10:
				mes_formatado=f'{data}-out'
			case '11'|11:
				mes_formatado=f'{data}-nov'
			case '12'|12:
				mes_formatado=f'-{data}-dez'
	if mode=='int':
		mes_formatado=int(re.sub(r'\D','',str(data)))
	
	return mes_formatado

class MoverArquivos:
	def __init__(self,destino, dados, data:dict):
		print(f"Requeste converter | mes -> {data['mes']}, ano -> {data['ano']}")
	
		with open(destino,'w',encoding='utf-8') as f: f.write(dados)
		sleep(5)
		try:
			if os.path.isfile(os.path.abspath(destino)):
				refinamento_pasta=str(destino).replace('/', ' ').split()
				print(f"Efetuando extração do arquivo html -> pasta:{os.path.join(refinamento_pasta[0], refinamento_pasta[1])} arquivo:{str(refinamento_pasta[-1])[5:]}")

				# info_company=db.RequestDB('').parametro_linha(parametro=['cnpj', f'{refinamento_pasta[1]}'], cliente='192.168.1.186')
				# extract_data.extrai_info(file_nfe_html=str(refinamento_pasta[-1])[5:], codigo_dominio=info_company[0]['codigo'], razao=info_company[0]['razao'], regime=info_company[0]['modalidade'], cnpj=refinamento_pasta[1], path=os.path.join(refinamento_pasta[0],f"{refinamento_pasta[1]}/{data['mes']}/{data['ano']}/nfe/xml"), data_=data)
		except Exception as e:
			print(f'Err ao extrair nota -> {e}')

class MoverArquivos_:
	def __init__(self, origem, destino):
		pasta_destino=os.path.join(PastaAlocacao('').retornar_pasta(), f'.arquivos_api/{destino}')
		os.makedirs(pasta_destino, exist_ok=True)
		shutil.move(origem, pasta_destino)

class ScriptJS:
	def inserir_ie(driver, ie):
		#Efetua a execução do script de inserção do ie
		try:
			driver.execute_script(f"document.querySelector('iframe#iframeCenter').contentDocument.querySelectorAll('input')[5].value='{ie}'")
		except:
			try:
				driver.switch_to.frame(driver.find_element(By.ID, 'iframeCenter'))
				driver.find_element(By.CLASS_NAME, "ui-inputfield.ui-inputmask.ui-widget.ui-state-default.ui-corner-all").send_keys(f"{ie}")

				driver.switch_to.default_content()
			except Exception as e:
				print(f"Error -> {e}")
		sleep(1)
		return 

	def inserir_data(driver, data):
		#Insere a data vigente para extração das notas na sefaz
		primeiro_dia_mes_anterior=date.today().replace(day=1)
		ultimo_dia_mes_anterior_=(primeiro_dia_mes_anterior-timedelta(days=1)).day
		ultimo_dia_mes_anterior=str(date.today().day)
		mes_anterior=str(data)[:2]
		if str(mes_anterior)=='02':
			ultimo_dia_mes_anterior='28'
		driver.execute_script(f"document.querySelector('iframe#iframeCenter').contentDocument.querySelectorAll('input')[6].value='01/{str(int(date.today().month))}/2025'")
		sleep(0.5)
		driver.execute_script(f"document.querySelector('iframe#iframeCenter').contentDocument.querySelectorAll('input')[7].value='{str(date.today().day)}/{str(date.today().month)}/2025'")
		sleep(1)
		return
	
	def efetuar_click(driver, id_frame, button_id:list, mode='id'):
		driver.switch_to.frame(driver.find_element(By.ID, f"{id_frame}"))
		sleep(0.5)
		match mode:
			case 'id': 
				try:
					driver.find_element(By.ID, f"{button_id[1]}").click()
				except:
					try:
						driver.execute_script(f"document.querySelector('#{button_id[0]}').click()")
					except Exception as e:
						raise e
			case 'class_':
				try:
					driver.find_element(By.CLASS_NAME, f"{button_id[1]}").click()
				except:
					try:
						driver.execute_script(f"document.querySelector('.{button_id[0]}').click()")
					except Exception as e:
						raise e
					
		driver.switch_to.default_content()
		sleep(1)
		return

	def retornar_log(driver, script):
		retorno_log=''
		try:
			retorno_log=driver.execute_script(f'{script}')
		except:
			pass
		sleep(1)
		return retorno_log

class SwitchContent:
	def __init__(self, driver, id_frame):
		self.driver=driver
		self.id_frame=id_frame
		pass
	def to_frame(self):
		self.driver.switch_to.frame(By.ID, f"{self.id_frame}")
		return
	def to_default(self):
		self.driver.switch_to.default_content()
		return

class Request_sefaz_info:
	def __init__(self, ie, driver, cnpj, data_vigente:dict=None):
		notas_emissor=[]
		notas_destinatario=[]
		
		if data_vigente==None:
			data_vigente={'mes':data_vigente_['mes'],'ano':data_vigente_['ano']}
			data_vigente['mes']=formatar_data(data=data_vigente['mes'])
		else:
			data_vigente['mes']=formatar_data(data=data_vigente['mes'])
		try:
			for raiz, _, files in os.walk(PastaAlocacao(cnpj=cnpj, mes=data_vigente['mes'], ano=data_vigente['ano'], pasta='nfe', arquivo='xls').retornar_pasta(modo='especifica')):
				for sub in _:
					print(f"PASTA -> {os.path.join(raiz, sub)}")
					os.rmdir(os.path.join(raiz, sub))

		except:
			pass

		def request_nfe_page():
			driver.execute_script("document.querySelector('iframe#iframeMenu').contentDocument.querySelectorAll('a')[101].click()")

		print(f"EMPRESA EM EXECUÇÃO -> {cnpj}")

		def verificar_popup():
			try:
				WebDriverWait(driver,10)
				alert=driver.switch_to.alert
				print(alert.text)
				alert=WebDriverWait(driver,10).until(lambda d:d.switch_to.alert)
				print(f'TEXTO DO ALERTA: {alert.text}')
				print("RETORNANDO ERRO DE POPUP")
				sleep(100)
				alert.accept()
				alert.click()
			except:
				pass

		def wait_page(driver):
			print('WAIT FUNCTION CALLED')
			timeout=0
			estado_page=driver.execute_script("return document.readyState")
			while estado_page!='complete':
				timeout+=1
				estado_page=driver.execute_script("return document.readyState")

				print(f'Aguardando pagina carregar! {timeout} segundos, estado:{estado_page}')
				if timeout==10:
					pt.press('enter')
					print('Timeout excedido')
					break
			return
		
		#OLD Func
		def requisitar_convert_xml(file_html, data):
			sleep(2.5)
			#pasta_alocar=PastaAlocacao(cnpj=cnpj, mes=data_vigente['mes'], ano=data_vigente['ano'], pasta='nfe', arquivo='xml').retornar_pasta(modo='especifica')
			pasta_alocar=os.path.join(os.path.expanduser('~'),f'.arquivos_api/{cnpj}/{(str(data_vigente["mes"]))}/{str(data_vigente['ano'])}/nfe/xml')
			empresa_inf=db.SQLConn().parametro_readline(param=['cnpj', f'{cnpj}'])
			print(f"PASTA DE ALOCAÇÃO XML -> {pasta_alocar}")
			#Requisista o modulo de extração e conversão para xml
			extract_data.extrai_info(file_nfe_html=file_html, codigo_dominio=empresa_inf['codigo'], razao=empresa_inf['razao'], regime=empresa_inf['modalidade'], cnpj=cnpj, path=pasta_alocar, data_=data)

		driver.set_page_load_timeout(10)
		request_nfe_page()
		sleep(0.55)
		
		aba_inicial=driver.current_window_handle
		try:
			primeiro_dia_mes_anterior=date.today().replace(day=1)
			ultimo_dia_mes_anterior=(primeiro_dia_mes_anterior-timedelta(days=1)).day
			mes_anterior=formatar_data(data=data_vigente['mes'],mode='int')
			
			sleep(0.55)
			ScriptJS.inserir_ie(driver, ie)
			sleep(2.5)
			ScriptJS.inserir_data(driver,data=data_vigente['mes'])
			sleep(0.55)
			ScriptJS.efetuar_click(driver=driver, id_frame='iframeCenter',button_id=['ui-button.ui-widget.ui-state-default.ui-corner-all.ui-button-text-only','ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only'], mode='class_')
			
			sleep(1.5)

			variavel_log=ScriptJS.retornar_log(driver, "return document.querySelector('iframe#iframeCenter').contentDocument.querySelector('.ui-datatable-scrollable-body').children[0].children[1].childNodes[0].className")
			
			#VERIFICAÇÃO SE CONSTA NOTAS NO RETORNO DE THREAD
			try:
				notas_consta=1 if driver.execute_script("return document.querySelector('iframe#iframeCenter').contentDocument.querySelector('.ui-datatable-scrollable-body table tbody').children[0].className")=="ui-widget-content ui-datatable-even" else 0
			except:
				try:
					notas_consta=1 if driver.execute_script("return document.querySelector('.ui-datatable-scrollable-body table tbody').children[0].className")=="ui-widget-content ui-datatable-even" else 0
				except:
					pass
			folder_path_=os.path.join(os.path.expanduser("~"),f'.arquivos_api/{cnpj}/{data_vigente['mes']}/{data_vigente['ano']}/nfe/xml')
			folder_path=PastaAlocacao(cnpj=cnpj, mes=data_vigente['mes'], ano=data_vigente['ano'], pasta='nfe', arquivo='html').retornar_pasta(modo='especifica')
			
			try:
				count_notas=int(os.listdir(folder_path))
			except:
				count_notas=0
				
			folder_company=cnpj
			FILE_EXIST=1 if f'emissor_xls' not in os.listdir(PastaAlocacao(cnpj=cnpj, mes=data_vigente['mes'], ano=data_vigente['ano'], pasta='nfe', arquivo='xls').retornar_pasta(modo='especifica')) else 0
			paginas_ativas=len(driver.find_elements(By.CSS_SELECTOR, "ui-paginator-pages > a"))
			if FILE_EXIST==1:

				sleep(0.55)
				pages_count=ScriptJS.retornar_log(driver, "return document.querySelector('iframe#iframeCenter').contentDocument.querySelector('.ui-paginator-next.ui-state-default.ui-corner-all').className")
				#Requisição das notas em lote
				if variavel_log=='ui-widget-content ui-datatable-even':

					while str(pages_count)=='ui-paginator-next ui-state-default ui-corner-all':
						print('REQUEST LOOP 0ª')

						try:
							content_notas=ScriptJS.retornar_log(driver, "return parseInt(document.querySelector('iframe#iframeCenter').contentDocument.querySelector('.ui-datatable-scrollable-body').children[0].children[1].children.length)")
						except:
							try:
								content_notas=ScriptJS.retornar_log(driver, "return parseInt(document.querySelector('.ui-datatable-scrollable-body').children[0].children[1].childNodes.length)")
							except:
								pass

						sleep(0.25)
						for i in range(0,int(content_notas)):
							print(f"CONTAGEM -> {i}")
							try:
								numero_nota=driver.execute_script(f"return document.querySelector('iframe#iframeCenter').contentDocument.querySelector('.ui-datatable-scrollable-body').children[0].children[1].children[{i}].children[7].innerHTML")
								sleep(0.5)
								print(f"{i}ª -> {numero_nota}")
								notas_emissor.append(numero_nota)

								if not os.path.isfile(os.path.join(folder_path, f'NF-e_emissor_{mes_anterior}-2025_{numero_nota}.html')):
									print(f"NUMERO DA NOTA -> {numero_nota}")
									##BOTÃO CLICK PARA ALTERAR
									try:
										driver.execute_script(f"document.querySelector('iframe#iframeCenter').contentDocument.querySelectorAll('.ui-datatable-data.ui-widget-content tr')[{i}].children[4].children[1].click()")
										print("REQUESTE CLICK")
										# driver.execute_script(f"document.querySelector('iframe#iframeCenter').contentDocument.querySelector('.ui-datatable-scrollable-body').children[0].children[1].children[{i}].children[4].children[0].click()")
									except:
										try:
											driver.execute_script(f"document.querySelector('iframe#iframeCenter').contentDocument.querySelector('.ui-datatable-scrollable-body').children[0].children[1].children[{i}].children[4].children[0].click()")
											print("REQUESTE CLICK 1")
										except:
											try:
												driver.execute_script(f"document.querySelector('.ui-datatable-scrollable-body').children[0].children[1].childNodes[{i}].children[4].children[0].click()")
												print("REQUESTE CLICK 2")
											except:
												try:
													driver.execute_script(f"document.querySelectorAll('.ui-datatable-data.ui-widget-content tr')[{i}].children[4].children[1].click()")
													print("REQUESTE CLICK 3")
												except Exception as e:
														print(f"ERROR -> {e}")
														driver.quit()
									sleep(1)
									pt.press('enter')
									sleep(0.55)
									
									# wait_page(driver)#debug testing

									abas=driver.window_handles #retorna todas as abas ativas na sessão atual do navegador
									driver.switch_to.window(abas[-1]) #efetua a alteração pra ultima aba aberta
									print('Alterado a pagina')
									
									try:
										#OLD
										# with open(os.path.join(folder_path, f'NF-e_emissor_{mes_anterior}-2025_{count_notas}.html'), 'w', encoding='utf-8') as file:
										# 	file.write(driver.find_element(By.ID, "imprNFeComplRest").get_attribute('outerHTML'))
										
										print(f"EFETUANDO LEITURA DA NOTA -> {count_notas+1} - {count_notas}")
										threading.Thread(target=requisitar_convert_xml, args=(f'NF-e_emissor_{mes_anterior}-2025_{numero_nota}.html', data_vigente, )).start()
										MoverArquivos(destino=os.path.join(folder_path, f'NF-e_emissor_{mes_anterior}-2025_{numero_nota}.html'), dados=driver.find_element(By.ID, "imprNFeComplRest").get_attribute('outerHTML'), data=data_vigente)
									except Exception as e:
										with open(os.path.abspath(f'{pasta_bots}/nfe_extrator_erros/LOG_ERROR_REQUISICAO.txt'),'a',encoding='utf-8') as f:f.write(f'ERRO AO RETORNAR NF-e, 1º MODULO  EMPRESA {cnpj}, {e} -> Data/Hora: {date.today()}\n')
										sleep(0.55)
										pt.press('enter')
										pass
									count_notas+=1
								else:
									print(f'NF-e Nº{numero_nota} já baixada')
									count_notas+=1
									continue

								sleep(0.25)
								if len(abas)>1: 
									driver.close()
								driver.switch_to.window(aba_inicial)
								sleep(0.25)
							except:
								print(f'Error {driver.title} via while')
								continue
						
						print('Request next page')
						##BOTÃO CLICK PARA ALTERAR
						
						# linha_next=driver.find_elements(By.CSS_SELECTOR, "ui-paginator.ui-paginator-bottom.ui-widget-header.ui-corner-bottom > a")
						# linha_next[2].click()

						pages_count=ScriptJS.retornar_log(driver, "return document.querySelector('iframe#iframeCenter').contentDocument.querySelector('.ui-paginator-next.ui-state-default.ui-corner-all').className")
						try:
							driver.execute_script("document.querySelector('iframe#iframeCenter').contentDocument.querySelector('.ui-paginator-next.ui-state-default.ui-corner-all').click()")
						except:
							try:
								driver.execute_script("document.querySelector('.ui-paginator-next.ui-state-default').click()")
							except:
								pass

						sleep(5)
			
					try:
						try:
							content_notas=ScriptJS.retornar_log(driver, "return parseInt(document.querySelector('iframe#iframeCenter').contentDocument.querySelector('.ui-datatable-scrollable-body').children[0].children[1].childNodes.length)")
						except:
							try:
								content_notas=ScriptJS.retornar_log(driver, "return parseInt(document.querySelector('.ui-datatable-scrollable-body').children[0].children[1].childNodes.length)")
							except:
								pass
						for i in range(int(content_notas)):
							print('REQUEST LOOP 1ª')
							try:
								numero_nota=driver.execute_script(f"return document.querySelector('iframe#iframeCenter').contentDocument.querySelector('.ui-datatable-scrollable-body').children[0].children[1].children[{i}].children[7].innerHTML")
								sleep(0.5)
								print(f"{i}ª -> {numero_nota}")
								notas_emissor.append(numero_nota)

								if not os.path.isfile(os.path.join(folder_path, f'NF-e_emissor_{mes_anterior}-2025_{numero_nota}.html')):
									try:
										driver.execute_script(f"document.querySelector('iframe#iframeCenter').contentDocument.querySelectorAll('.ui-datatable-data.ui-widget-content tr')[{i}].children[4].children[1].click()")
										print("REQUESTE CLICK")
										# driver.execute_script(f"document.querySelector('iframe#iframeCenter').contentDocument.querySelector('.ui-datatable-scrollable-body').children[0].children[1].children[{i}].children[4].children[0].click()")
									except:
										try:
											driver.execute_script(f"document.querySelector('iframe#iframeCenter').contentDocument.querySelector('.ui-datatable-scrollable-body').children[0].children[1].children[{i}].children[4].children[0].click()")
											print("REQUESTE CLICK 1")
										except:
											try:
												driver.execute_script(f"document.querySelector('.ui-datatable-scrollable-body').children[0].children[1].childNodes[{i}].children[4].children[0].click()")
												print("REQUESTE CLICK 2")
											except:
												try:
													driver.execute_script(f"document.querySelectorAll('.ui-datatable-data.ui-widget-content tr')[{i}].children[4].children[1].click()")
													print("REQUESTE CLICK 3")
												except Exception as e:
														print(f"ERROR -> {e}")
														driver.quit()
									#BOTÃO CLICK PARA ALTERAR
									sleep(1)
									pt.press('enter')
									sleep(0.55)
									# wait_page(driver)#debug testing
									
									abas=driver.window_handles #retorna todas as abas ativas na sessão atual do navegador
									driver.switch_to.window(abas[-1]) #efetua a alteração pra ultima aba aberta
									print('Alterado a pagina')
									
									try:
										#OLD
										# with open(os.path.join(folder_path, f'NF-e_emissor_{mes_anterior}-2025_{count_notas}.html'), 'w', encoding='utf-8') as file:
										# 	file.write(driver.find_element(By.ID, "imprNFeComplRest").get_attribute('outerHTML'))
										

										threading.Thread(target=requisitar_convert_xml, args=(f'NF-e_emissor_{mes_anterior}-2025_{numero_nota}.html', data_vigente, )).start()
										MoverArquivos(destino=os.path.join(folder_path, f'NF-e_emissor_{mes_anterior}-2025_{numero_nota}.html'), dados=driver.find_element(By.ID, "imprNFeComplRest").get_attribute('outerHTML'),data=data_vigente)
										
										
									except Exception as e:
										with open(os.path.abspath(f'{pasta_bots}/nfe_extrator_erros/LOG_ERROR_REQUISICAO.txt'),'a',encoding='utf-8') as f:f.write(f'ERRO AO RETORNAR NF-e, 2º MODULO  EMPRESA {cnpj}, {e} -> Data/Hora: {date.today()}\n')
										sleep(0.55)
										pt.press('enter')
										pass
									count_notas+=1
								else:
									print(f'NF-e Nº{numero_nota} já baixada')
									count_notas+=1

								sleep(0.55)
								if len(abas)>1:
									driver.close()
								driver.switch_to.window(aba_inicial)
								sleep(0.55)
							except:
								print(f'Error {driver.title}')
								continue
					except:
						pass
					
					#EFETUA O DOWNLOAD DO XLS E MOVE DIRETO PARA A PASTA DA EMPRESA
					#BOTÃO CLICK PARA EFETUAR ALTERAÇÃO
					try:
						driver.execute_script("document.querySelector('iframe#iframeCenter').contentDocument.querySelectorAll('div.ui-widget-header.ui-corner-top a')[0].click()")
						sleep(5)
						path_download=os.path.join(PastaAlocacao('').retornar_pasta(), 'downloads')
						last_file=sorted(os.listdir(path_download), key=lambda f: os.path.getmtime(os.path.join(path_download, f)), reverse=True)

						print(f'Pasta download {path_download} file:{last_file[0]} nome_padrão:{str(last_file[0])[:28]}')
						if str(last_file[0]).endswith('xls') and str(last_file[0])[:28]=='ConsultaNFeEmitidasRecebidas':
							MoverArquivos_(origem=os.path.join(path_download, last_file[0]), destino=os.path.join(f'{cnpj}/{data_vigente['mes']}/{data_vigente['ano']}/nfe','xls/emissor_xls'))
							
							# shutil.move(os.path.join(path_download, last_file[0]), os.path.join(f'arquivosApi/{cnpj}/{data_vigente['mes']}/{data_vigente['ano']}/nfe',f'NF-e_{mes_anterior}_emissor-{date.today().year}.xls' ))
						sleep(5)
					except ValueError as e:
						print(f'Error to move file XLSX -> {e}')
						return
				else:
					try:
						content_notas=ScriptJS.retornar_log(driver, "return parseInt(document.querySelector('iframe#iframeCenter').contentDocument.querySelector('.ui-datatable-scrollable-body').children[0].children[1].children.length)")
					except:
						try:
							content_notas=ScriptJS.retornar_log(driver, "return parseInt(document.querySelector('.ui-datatable-scrollable-body').children[0].children[1].childNodes.length)")
						except:
							pass
					# content_notas=ScriptJS.retornar_log(driver,"return parseInt(document.querySelector('iframe#iframeCenter').contentDocument.querySelector('.ui-datatable-scrollable-body').children[0].children[1].childNodes.length)")
					for i in range(0,int(content_notas)):
						print(f'REQUEST LOOP 2ª - indice:{i}')
				
						try:
							numero_nota=driver.execute_script(f"return document.querySelector('iframe#iframeCenter').contentDocument.querySelector('.ui-datatable-scrollable-body').children[0].children[1].children[{i}].children[7].innerHTML")
							sleep(0.5)
							print(f"{i}ª -> {numero_nota}")
							notas_emissor.append(numero_nota)


							if not os.path.isfile(os.path.join(folder_path, f'NF-e_emissor_{mes_anterior}-2025_{numero_nota}.html')):
								try:
										driver.execute_script(f"document.querySelector('iframe#iframeCenter').contentDocument.querySelectorAll('.ui-datatable-data.ui-widget-content tr')[{i}].children[4].children[1].click()")
										print("REQUESTE CLICK")
										# driver.execute_script(f"document.querySelector('iframe#iframeCenter').contentDocument.querySelector('.ui-datatable-scrollable-body').children[0].children[1].children[{i}].children[4].children[0].click()")
								except:
									try:
										driver.execute_script(f"document.querySelector('iframe#iframeCenter').contentDocument.querySelector('.ui-datatable-scrollable-body').children[0].children[1].children[{i}].children[4].children[0].click()")
										print("REQUESTE CLICK 1")
									except:
										try:
											driver.execute_script(f"document.querySelector('.ui-datatable-scrollable-body').children[0].children[1].childNodes[{i}].children[4].children[0].click()")
											print("REQUESTE CLICK 2")
										except:
											try:
												driver.execute_script(f"document.querySelectorAll('.ui-datatable-data.ui-widget-content tr')[{i}].children[4].children[1].click()")
												print("REQUESTE CLICK 3")
											except Exception as e:
													print(f"ERROR -> {e}")
													driver.quit()
								sleep(1)
								pt.press('enter')
								sleep(0.55)
								
								# wait_page(driver)#debug testing
								
								abas=driver.window_handles #retorna todas as abas ativas na sessão atual do navegador
								driver.switch_to.window(abas[-1]) #efetua a alteração pra ultima aba aberta
								print('Alterado a pagina')

								try:
									#OLD
									# with open(os.path.join(folder_path, f'NF-e_emissor_{mes_anterior}-2025_{count_notas}.html'), 'w', encoding='utf-8') as file:
									# 	file.write(driver.find_element(By.ID, "imprNFeComplRest").get_attribute('outerHTML'))
									

									threading.Thread(target=requisitar_convert_xml, args=(f'NF-e_emissor_{mes_anterior}-2025_{numero_nota}.html', data_vigente, )).start()
									MoverArquivos(destino=os.path.join(folder_path, f'NF-e_emissor_{mes_anterior}-2025_{numero_nota}.html'), dados=driver.find_element(By.ID, "imprNFeComplRest").get_attribute('outerHTML'),data=data_vigente)
									count_notas+=1
										
								except Exception as e:
									with open(os.path.abspath(f'{pasta_bots}/nfe_extrator_erros/LOG_ERROR_REQUISICAO.txt'),'a',encoding='utf-8') as f:f.write(f'ERRO AO RETORNAR NF-e, 3º MODULO  EMPRESA {cnpj}, {e} -> Data/Hora: {date.today()}\n')

									sleep(0.55)
									pt.press('enter')
									pass
							else:
								print(f'NF-e Nº{numero_nota} já baixada')
								count_notas+=1

							sleep(0.55)
							if len(abas)>1:
								driver.close()
							driver.switch_to.window(aba_inicial)
							sleep(0.55)
						except Exception as e:
							print(f'Error {e}')
							continue

					#EFETUA O DOWNLOAD DO XLS E MOVE PARA A PASTA DA EMPRESA
					#BOTÃO CLICK PARA ALTERAÇÃO
					try:
						driver.execute_script("document.querySelector('iframe#iframeCenter').contentDocument.querySelectorAll('div.ui-widget-header.ui-corner-top a')[0].click()")
						sleep(5)
						path_download=os.path.join(PastaAlocacao('').retornar_pasta(), 'downloads')
						last_file=sorted(os.listdir(path_download), key=lambda f: os.path.getmtime(os.path.join(path_download, f)), reverse=True)
						print(f'Pasta download {path_download} file:{last_file[0]} nome_padrão:{str(last_file[0])[:28]}')

						if str(last_file[0]).endswith('xls') and str(last_file[0])[:28]=='ConsultaNFeEmitidasRecebidas':
							MoverArquivos_(origem=os.path.join(path_download, last_file[0]), destino=os.path.join(f'{cnpj}/{data_vigente['mes']}/{data_vigente['ano']}/nfe/','xls/emissor_xls'))
							
							# shutil.move(os.path.join(path_download, last_file[0]), os.path.join(f'arquivosApi/{cnpj}/{data_vigente['mes']}/{data_vigente['ano']}/nfe',f'NF-e_{mes_anterior}_emissor-{date.today().year}.xls' ))
						sleep(5)
					except ValueError as e:
						print(f'Error to move file XLSX -> {e}')
						return
										
			elif variavel_log=='ui-widget-content ui-datatable-empty-message' and FILE_EXIST==0:
				print('Não constam arquivos')
				
				if f'emissor_xls' not in os.listdir(PastaAlocacao(cnpj=cnpj, mes=data_vigente['mes'], ano=data_vigente['ano'], pasta='nfe', arquivo='xls').retornar_pasta(modo='especifica')):
					try:
						driver.execute_script("document.querySelector('iframe#iframeCenter').contentDocument.querySelectorAll('div.ui-widget-header.ui-corner-top a')[0].click()")
						sleep(2.5)
						path_download=os.path.join(PastaAlocacao('').retornar_pasta(), 'downloads')
						last_file=sorted(os.listdir(path_download), key=lambda f: os.path.getmtime(os.path.join(path_download, f)), reverse=True)
						print(f'Pasta download {path_download} file:{last_file[0]} nome_padrão:{str(last_file[0])[:28]}')
						if str(last_file[0]).endswith('xls') and str(last_file[0])[:28]=='ConsultaNFeEmitidasRecebidas':
							MoverArquivos_(origem=os.path.join(path_download, last_file[0]), destino=os.path.join(f'{cnpj}/{data_vigente['mes']}/{data_vigente['ano']}/nfe','xls/destinatario_xls'))
							
							# shutil.move(os.path.join(path_download, last_file[0]), os.path.join(f'arquivos_api/{cnpj}/{data_vigente['mes']}/{data_vigente['ano']}/nfe',f'NF-e_{mes_anterior}_destinatario-{date.today().year}.xls' ))
						sleep(5)
					except ValueError as e:
						print(f'Error to move file XLSX -> {e}')
						return
				pass
			else:
				print('Arquivo já baixado')
				pass
		except TimeoutException as e:
			print(driver.execute_script("return document.readyState"))
			print(f'Requisitou erro {e}')
		
			
		#request por parte destinatario
		print('ETAPA DESTINATARIO')
		#BOTÃO CLICK PARA ALTERAÇÃO
		driver.execute_script("document.querySelector('iframe#iframeCenter').contentDocument.querySelector('span.ui-radiobutton-icon.ui-icon-blank.ui-c').click()")
		sleep(0.55)

		ScriptJS.efetuar_click(driver=driver, id_frame='iframeCenter',button_id=['ui-button.ui-widget.ui-state-default.ui-corner-all.ui-button-text-only','ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only'], mode='class_')
		try:
			driver.execute_script("document.querySelector('iframe#iframeCenter').contentDocument.querySelectorAll('.ui-paginator-pages a')[0].click()")
		except:
			try:
				driver.execute_script("document.querySelectorAll('.ui-paginator-pages a')[0].click()")
			except:
				pass

		sleep(0.55)
		aba_inicial=driver.current_window_handle
		#VERIFICAÇÃO SE CONSTA NOTAS NO RETORNO DE THREAD
		
		notas_consta=0
		try:
			notas_consta=1 if driver.execute_script("return document.querySelector('iframe#iframeCenter').contentDocument.querySelector('.ui-datatable-scrollable-body table tbody').children[0].className")=="ui-widget-content ui-datatable-even" else 0
		except:
			try:
				notas_consta=1 if driver.execute_script("return document.querySelector('.ui-datatable-scrollable-body table tbody').children[0].className")=="ui-widget-content ui-datatable-even" else 0
			except:
				pass
		
		try:
			if notas_consta==1:
				primeiro_dia_mes_anterior=date.today().replace(day=1)
				ultimo_dia_mes_anterior=(primeiro_dia_mes_anterior-timedelta(days=1)).day
				mes_anterior=formatar_data(data=data_vigente['mes'],mode='int')
				sleep(0.55)
				ScriptJS.inserir_ie(driver,ie)
				#driver.execute_script(f"document.querySelector('iframe#iframeCenter').contentDocument.querySelectorAll('input')[5].value='{ie}'")
				
				sleep(0.5)
				ScriptJS.inserir_data(driver,data=data_vigente['mes'])
				# driver.execute_script(f"document.querySelector('iframe#iframeCenter').contentDocument.querySelectorAll('input')[6].value='01/{mes_anterior}/2025'")
				# driver.execute_script(f"document.querySelector('iframe#iframeCenter').contentDocument.querySelectorAll('input')[7].value='{ultimo_dia_mes_anterior}/{mes_anterior}/2025'")
				sleep(0.55)
				#BOTÃO CLICK PARA EFETUAR ALTERAÇÃO
				driver.execute_script("document.querySelector('iframe#iframeCenter').contentDocument.querySelectorAll('button')[0].click()")
				sleep(0.55)
				variavel_log=ScriptJS.retornar_log(driver, "return document.querySelector('iframe#iframeCenter').contentDocument.querySelector('.ui-datatable-scrollable-body').children[0].children[1].childNodes[0].className")
				
				try:
					paginas_ativas=len(driver.execute_script("return document.querySelector('iframe#iframeCenter').contentDocument.querySelectorAll('.ui-paginator-pages a').length"))					
				except:
					try:
						paginas_ativas=len(driver.find_elements(By.CSS_SELECTOR, "ui-paginator-pages > a"))
					except:
						paginas_ativas=1
						print("ERROR paginas ativas default")

				pages_count=ScriptJS.retornar_log(driver, "return document.querySelector('iframe#iframeCenter').contentDocument.querySelector('.ui-paginator-next.ui-state-default.ui-corner-all').className")
				
				folder_company=cnpj
				FILE_EXIST=1 if f'destinatario_xls' not in os.listdir(PastaAlocacao(cnpj=cnpj, mes=data_vigente['mes'], ano=data_vigente['ano'], pasta='nfe', arquivo='xls').retornar_pasta(modo='especifica')) else 0
				
				print(f"File exist -> {FILE_EXIST}")
				
				if FILE_EXIST==1:
					folder_path=PastaAlocacao(cnpj=cnpj, mes=data_vigente['mes'], ano=data_vigente['ano'], pasta='nfe', arquivo='html').retornar_pasta(modo='especifica')
					try:
						count_notas=int(os.listdir(folder_path))
					except:
						count_notas=0
					sleep(0.55)
					print("REQUESTE DESTINATARIO ")
				
					#Requisição em lote das notas
					try:
						driver.execute_script("document.querySelectorAll('.ui-paginator-page')[0].click()")
					except:
						pass
					
					if variavel_log=='ui-widget-content ui-datatable-even':
						print("requeste while")
						while str(pages_count)=='ui-paginator-next ui-state-default ui-corner-all':
							print('REQUEST LOOP 3ª')
							try:
								content_notas=ScriptJS.retornar_log(driver, "return parseInt(document.querySelector('iframe#iframeCenter').contentDocument.querySelector('.ui-datatable-scrollable-body').children[0].children[1].childNodes.length)")
							except:
								try:
									content_notas=ScriptJS.retornar_log(driver, "return parseInt(document.querySelector('.ui-datatable-scrollable-body').children[0].children[1].childNodes.length)")
								except:
									pass
							sleep(0.25)
							for i in range(0,int(content_notas)):
								try:
									numero_nota=driver.execute_script(f"return document.querySelector('iframe#iframeCenter').contentDocument.querySelector('.ui-datatable-scrollable-body').children[0].children[1].children[{i}].children[7].innerHTML")
									sleep(0.5)
									print(f"{i}ª -> {numero_nota}")
									notas_destinatario.append(numero_nota)


									if not os.path.isfile(os.path.join(folder_path, f'NF-e_destinatario_{mes_anterior}-2025_{numero_nota}.html')):
										try:
											driver.execute_script(f"document.querySelector('iframe#iframeCenter').contentDocument.querySelectorAll('.ui-datatable-data.ui-widget-content tr')[{i}].children[4].children[1].click()")
											print("REQUESTE CLICK")
											# driver.execute_script(f"document.querySelector('iframe#iframeCenter').contentDocument.querySelector('.ui-datatable-scrollable-body').children[0].children[1].children[{i}].children[4].children[0].click()")
										except:
											try:
												driver.execute_script(f"document.querySelector('iframe#iframeCenter').contentDocument.querySelector('.ui-datatable-scrollable-body').children[0].children[1].children[{i}].children[4].children[0].click()")
												print("REQUESTE CLICK 1")
											except:
												try:
													driver.execute_script(f"document.querySelector('.ui-datatable-scrollable-body').children[0].children[1].childNodes[{i}].children[4].children[0].click()")
													print("REQUESTE CLICK 2")
												except:
													try:
														driver.execute_script(f"document.querySelectorAll('.ui-datatable-data.ui-widget-content tr')[{i}].children[4].children[1].click()")
														print("REQUESTE CLICK 3")
													except Exception as e:
															print(f"ERROR -> {e}")
															driver.quit()
										sleep(1)
										pt.press('enter')
										sleep(0.55)

										# wait_page(driver)#debug testing
										abas=driver.window_handles #retorna todas as abas ativas na sessão atual do navegador
										driver.switch_to.window(abas[-1]) #efetua a alteração pra ultima aba aberta
										print('Alterado a pagina')

										try:
											#OLD
											# with open(os.path.join(folder_path, f'NF-e_destinatario_{mes_anterior}-2025_{count_notas}.html'), 'w', encoding='utf-8') as file:
											# 	file.write(driver.find_element(By.ID, "imprNFeComplRest").get_attribute('outerHTML'))
											

											threading.Thread(target=requisitar_convert_xml, args=(f'NF-e_destinatario_{mes_anterior}-2025_{numero_nota}.html', data_vigente, )).start()
											MoverArquivos(destino=os.path.join(folder_path, f'NF-e_destinatario_{mes_anterior}-2025_{numero_nota}.html'), dados=driver.find_element(By.ID, "imprNFeComplRest").get_attribute('outerHTML'),data=data_vigente)
											
											count_notas+=1
										except Exception as e:
											with open(os.path.abspath(f'{pasta_bots}/nfe_extrator_erros/LOG_ERROR_REQUISICAO.txt'),'a',encoding='utf-8') as f:f.write(f'ERRO AO RETORNAR NF-e, 4º MODULO  EMPRESA {cnpj}, {e} -> Data/Hora: {date.today()}\n')
											sleep(0.55)
											pt.press('enter')
											
											pass
									else:
										print(f'NF-e Nº{numero_nota} já baixada')
										count_notas+=1
										continue
									sleep(0.25)
									if len(abas)>1: 
										driver.close()
									driver.switch_to.window(aba_inicial)
									sleep(0.25)
								except:
									print(f'Error {driver.title} via while')
									continue
							print('Request next page')
							
							try:
								driver.execute_script("document.querySelector('iframe#iframeCenter').contentDocument.querySelector('.ui-paginator-next.ui-state-default.ui-corner-all').click()")
							except:
								try:
									driver.execute_script("document.querySelector('.ui-paginator-next.ui-state-default').click()")
								except:
									pass
							# driver.execute_script("document.querySelector('iframe#iframeCenter').contentDocument.querySelector('.ui-paginator-next.ui-state-default.ui-corner-all').click()")
							# sleep(5)
							pages_count=ScriptJS.retornar_log(driver, "return document.querySelector('iframe#iframeCenter').contentDocument.querySelector('.ui-paginator-next.ui-state-default.ui-corner-all').className")

						try:					
							try:
								content_notas=ScriptJS.retornar_log(driver, "return parseInt(document.querySelector('iframe#iframeCenter').contentDocument.querySelector('.ui-datatable-scrollable-body').children[0].children[1].childNodes.length)")
							except:
								try:
									content_notas=ScriptJS.retornar_log(driver, "return parseInt(document.querySelector('.ui-datatable-scrollable-body').children[0].children[1].childNodes.length)")
								except:
									pass
							for i in range(int(content_notas)):
								print('REQUEST LOOP 4ª')
								try:
									numero_nota=driver.execute_script(f"return document.querySelector('iframe#iframeCenter').contentDocument.querySelector('.ui-datatable-scrollable-body').children[0].children[1].children[{i}].children[7].innerHTML")
									sleep(0.5)
									print(f"{i}ª -> {numero_nota}")
									notas_destinatario.append(numero_nota)

									if not os.path.isfile(os.path.join(folder_path, f'NF-e_destinatario_{mes_anterior}-2025_{numero_nota}.html')):
										try:
											driver.execute_script(f"document.querySelector('iframe#iframeCenter').contentDocument.querySelectorAll('.ui-datatable-data.ui-widget-content tr')[{i}].children[4].children[1].click()")
											print("REQUESTE CLICK")
											# driver.execute_script(f"document.querySelector('iframe#iframeCenter').contentDocument.querySelector('.ui-datatable-scrollable-body').children[0].children[1].children[{i}].children[4].children[0].click()")
										except:
											try:
												driver.execute_script(f"document.querySelector('iframe#iframeCenter').contentDocument.querySelector('.ui-datatable-scrollable-body').children[0].children[1].children[{i}].children[4].children[0].click()")
												print("REQUESTE CLICK 1")
											except:
												try:
													driver.execute_script(f"document.querySelector('.ui-datatable-scrollable-body').children[0].children[1].childNodes[{i}].children[4].children[0].click()")
													print("REQUESTE CLICK 2")
												except:
													try:
														driver.execute_script(f"document.querySelectorAll('.ui-datatable-data.ui-widget-content tr')[{i}].children[4].children[1].click()")
														print("REQUESTE CLICK 3")
													except Exception as e:
															print(f"ERROR -> {e}")
															driver.quit()
										#BOTÃO CLICK PARA ALTERAR
										sleep(1)
										pt.press('enter')
										sleep(0.55)
										# wait_page(driver)#debug testing
										
										abas=driver.window_handles #retorna todas as abas ativas na sessão atual do navegador
										driver.switch_to.window(abas[-1]) #efetua a alteração pra ultima aba aberta
										print('Alterado a pagina')
										
										try:
											#OLD
											# with open(os.path.join(folder_path, f'NF-e_emissor_{mes_anterior}-2025_{count_notas}.html'), 'w', encoding='utf-8') as file:
											# 	file.write(driver.find_element(By.ID, "imprNFeComplRest").get_attribute('outerHTML'))
											

											threading.Thread(target=requisitar_convert_xml, args=(f'NF-e_destinatario_{mes_anterior}-2025_{numero_nota}.html', data_vigente, )).start()
											MoverArquivos(destino=os.path.join(folder_path, f'NF-e_destinatario_{mes_anterior}-2025_{numero_nota}.html'), dados=driver.find_element(By.ID, "imprNFeComplRest").get_attribute('outerHTML'),data=data_vigente)
											
											
										except Exception as e:
											with open(os.path.abspath(f'{pasta_bots}/nfe_extrator_erros/LOG_ERROR_REQUISICAO.txt'),'a',encoding='utf-8') as f:f.write(f'ERRO AO RETORNAR NF-e, 2º MODULO  EMPRESA {cnpj}, {e} -> Data/Hora: {date.today()}\n')
											sleep(0.55)
											pt.press('enter')
											pass
										count_notas+=1
									else:
										print(f'NF-e Nº{numero_nota} já baixada')
										count_notas+=1

									sleep(0.55)
									if len(abas)>1:
										driver.close()
									driver.switch_to.window(aba_inicial)
									sleep(0.55)
								except:
									print(f'Error {driver.title}')
									continue
						
							#REQUISIÇÃO DO XLS
							try:
								driver.execute_script("document.querySelector('iframe#iframeCenter').contentDocument.querySelectorAll('div.ui-widget-header.ui-corner-top a')[0].click()")
								sleep(5)
								#bloco responsavel pelo tratamento do arquivo xls baixado
								path_download=os.path.join(PastaAlocacao('').retornar_pasta(), 'downloads')
								last_file=sorted(os.listdir(path_download), key=lambda f: os.path.getmtime(os.path.join(path_download, f)), reverse=True)
								print(f'Pasta download {path_download} file:{last_file[0]} nome_padrão:{str(last_file[0])[:28]}')

								if str(last_file[0]).endswith('xls') and str(last_file[0])[:28]=='ConsultaNFeEmitidasRecebidas':
									MoverArquivos_(origem=os.path.join(path_download, last_file[0]), destino=os.path.join(f'{cnpj}/{data_vigente['mes']}/{data_vigente['ano']}/nfe','xls/destinatario_xls'))
									
									# shutil.move(os.path.join(path_download, last_file[0]), os.path.join(f'arquivosApi/{cnpj}/{data_vigente['mes']}/{data_vigente['ano']}/nfe',f'NF-e_{mes_anterior}_destinatario-{date.today().year}.xls' ))
								sleep(5)
							except ValueError as e:
								print(f'Error to move file XLSX -> {e}')
								return
						except:
							pass
					
						sleep(0.55)
		
					else:
						print("Retornando contagem de notas")
						# content_notas=driver.execute_script("return parseInt(document.querySelector('iframe#iframeCenter').contentDocument.querySelector('.ui-datatable-scrollable-body').children[0].children[1].childNodes.length)")
						try:
							content_notas=ScriptJS.retornar_log(driver, "return parseInt(document.querySelector('iframe#iframeCenter').contentDocument.querySelector('.ui-datatable-scrollable-body').children[0].children[1].children.length)")
						except:
							try:
								content_notas=ScriptJS.retornar_log(driver, "return parseInt(document.querySelector('.ui-datatable-scrollable-body').children[0].children[1].childNodes.length)")
							except:
								pass
						for i in range(0,int(content_notas)):
							print('REQUEST LOOP 5ª')

							try:
								numero_nota=driver.execute_script(f"return document.querySelector('iframe#iframeCenter').contentDocument.querySelector('.ui-datatable-scrollable-body').children[0].children[1].children[{i}].children[7].innerHTML")
								sleep(0.5)
								print(f"{i}ª -> {numero_nota}")
								notas_destinatario.append(numero_nota)


								if not os.path.isfile(os.path.join(folder_path, f'NF-e_destinatario_{mes_anterior}-2025_{numero_nota}.html')):
									try:
										driver.execute_script(f"document.querySelector('iframe#iframeCenter').contentDocument.querySelectorAll('.ui-datatable-data.ui-widget-content tr')[{i}].children[4].children[1].click()")
										print("REQUESTE CLICK")
										# driver.execute_script(f"document.querySelector('iframe#iframeCenter').contentDocument.querySelector('.ui-datatable-scrollable-body').children[0].children[1].children[{i}].children[4].children[0].click()")
									except:
										try:
											driver.execute_script(f"document.querySelector('iframe#iframeCenter').contentDocument.querySelector('.ui-datatable-scrollable-body').children[0].children[1].children[{i}].children[4].children[0].click()")
											print("REQUESTE CLICK 1")
										except:
											try:
												driver.execute_script(f"document.querySelector('.ui-datatable-scrollable-body').children[0].children[1].childNodes[{i}].children[4].children[0].click()")
												print("REQUESTE CLICK 2")
											except:
												try:
													driver.execute_script(f"document.querySelectorAll('.ui-datatable-data.ui-widget-content tr')[{i}].children[4].children[1].click()")
													print("REQUESTE CLICK 3")
												except Exception as e:
														print(f"ERROR -> {e}")
														driver.quit()
									sleep(1)
									pt.press('enter')
									sleep(0.55)
									
									abas=driver.window_handles #retorna todas as abas ativas na sessão atual do navegador
									driver.switch_to.window(abas[-1]) #efetua a alteração pra ultima aba aberta
									print('Alterado a pagina')

									try:

										threading.Thread(target=requisitar_convert_xml, args=(f'NF-e_destinatario_{mes_anterior}-2025_{numero_nota}.html', data_vigente, )).start()
										MoverArquivos(destino=os.path.join(folder_path, f'NF-e_destinatario_{mes_anterior}-2025_{numero_nota}.html'), dados=driver.find_element(By.ID, "imprNFeComplRest").get_attribute('outerHTML'),data=data_vigente)
										count_notas+=1
											
									except Exception as e:
										with open(os.path.abspath(f'{pasta_bots}/nfe_extrator_erros/LOG_ERROR_REQUISICAO.txt'),'a',encoding='utf-8') as f:f.write(f'ERRO AO RETORNAR NF-e, 6º MODULO  EMPRESA {cnpj}, {e} -> Data/Hora: {date.today()}\n')
										
										sleep(0.55)
										pt.press('enter')
										pass
								else:
									print(f'NF-e Nº{numero_nota} já baixada')
									count_notas+=1

								sleep(0.55)
								if len(abas)>1:
									driver.close()
								driver.switch_to.window(aba_inicial)
								sleep(0.55)
							except:
								print(f'Error {driver.title}')
								continue
					
						sleep(0.55)
						#REQUISIÇÃO DO XLS
						try:
							driver.execute_script("document.querySelector('iframe#iframeCenter').contentDocument.querySelectorAll('div.ui-widget-header.ui-corner-top a')[0].click()")
							sleep(5)
							
							path_download=os.path.join(PastaAlocacao('').retornar_pasta(), 'downloads')
							last_file=sorted(os.listdir(path_download), key=lambda f: os.path.getmtime(os.path.join(path_download, f)), reverse=True)
							print(f'Pasta download {path_download} file:{last_file[0]} nome_padrão:{str(last_file[0])[:28]}')
							if str(last_file[0]).endswith('xls') and str(last_file[0])[:28]=='ConsultaNFeEmitidasRecebidas':
								MoverArquivos_(origem=os.path.join(path_download, last_file[0]), destino=os.path.join(f'{cnpj}/{data_vigente['mes']}/{data_vigente['ano']}/nfe','xls/destinatario_xls'))
								
								# shutil.move(os.path.join(path_download, last_file[0]), os.path.join(f'arquivos_api/{cnpj}/{data_vigente['mes']}/{data_vigente['ano']}/nfe',f'NF-e_{mes_anterior}_destinatario-{date.today().year}.xls' ))
							sleep(5)
						except ValueError as e:
							print(f'Error to move file XLSX -> {e}')
							return
						
				elif variavel_log=='ui-widget-content ui-datatable-empty-message' and FILE_EXIST==0:
					print('Não constam arquivos')
					return
				else:
					print('Arquivo já baixado')
					pass
			else:
				if f'destinatario_xls' not in os.listdir(PastaAlocacao(cnpj=cnpj, mes=data_vigente['mes'], ano=data_vigente['ano'], pasta='nfe', arquivo='xls').retornar_pasta(modo='especifica')):
					try:
						driver.execute_script("document.querySelector('iframe#iframeCenter').contentDocument.querySelectorAll('div.ui-widget-header.ui-corner-top a')[0].click()")
						sleep(2.5)
						path_download=os.path.join(PastaAlocacao('').retornar_pasta(), 'downloads')
						last_file=sorted(os.listdir(path_download), key=lambda f: os.path.getmtime(os.path.join(path_download, f)), reverse=True)
						print(f'Pasta download {path_download} file:{last_file[0]} nome_padrão:{str(last_file[0])[:28]}')
						if str(last_file[0]).endswith('xls') and str(last_file[0])[:28]=='ConsultaNFeEmitidasRecebidas':
							MoverArquivos_(origem=os.path.join(path_download, last_file[0]), destino=os.path.join(f'{cnpj}/{data_vigente['mes']}/{data_vigente['ano']}/nfe','xls/destinatario_xls'))
							
							# shutil.move(os.path.join(path_download, last_file[0]), os.path.join(f'arquivos_api/{cnpj}/{data_vigente['mes']}/{data_vigente['ano']}/nfe',f'NF-e_{mes_anterior}_destinatario-{date.today().year}.xls' ))
						sleep(5)
					except ValueError as e:
						print(f'Error to move file XLSX -> {e}')
						return
				print("Não consta notas")
			
			#RETORNA A QUANTIDADE DE NFE EXTRAIDAS
			print(f"notas emissor -> {notas_emissor} notas destinatario -> {notas_destinatario}")
			try:
				notas=[i for i in os.listdir(os.path.join(os.path.expanduser("~"), f".arquivos_api/{cnpj}/{data_vigente['mes']}/{data_vigente['ano']}/nfe/xml"))]
				with open(f'{pasta_bots}/nfe_extrator_erros/controle_nfe.json','r') as f: dados_nfe=json.load(f)
				data=str(date.today())
				if isinstance(dados_nfe, list):
					dados_nfe.append({f"{cnpj}":data, "nfe":int(notas)})
					with open(f'{pasta_bots}/nfe_extrator_erros/controle_nfe.json','w') as f:json.dump(dados_nfe,f,indent=4,ensure_ascii=False)
			except:
				pass
		except TimeoutException as e:
			print(driver.execute_script("return document.readyState"))
			print(f'Requisitou erro {e}')
        
		return

