;** IMP_IBPT *******************************************************************
;*  IMPORTACAO DE CARGA TRIBUTARIA CONFORME IBPT                               *
;*******************************************************************************
;Autor           : Vise Informatica (VISERP)
;Desenvolvido    : 05/06/2013 por Bruno Carvalho 
;Ultima Alteracao: 10/02/2013 por Anivel Augusto Rodrigues
;Motivo Alteracao: Ajustes IBPT 0.0.6         
;Ultima Alteracao: 01/12/2014 por Luis Gustavo
;Motivo Alteracao: Implementado para importar tabela IBPT de SP e MG
;Ultima Alteracao: 02/06/2015 por Andrey Fillipe
;Motivo Alteracao: Ajustes para importar tabela IBPT de qualquer estado
;Ultima Alteracao: 21/10/2017 por Anivel Augusto Rodrigues
;Motivo Alteracao: Ajustes IBPT 17.2.B         
;Ultima Alteracao: 20/02/2018 por Anivel Augusto Rodrigues
;Motivo Alteracao: Ajustes IBPT 18.1.A         

;*******************************************************************************
;* Rotina                                                                      *
;*******************************************************************************
Proc converteparanumero(Valor)
private valor, i,s,newvalor

newvalor="0"
for i from 1 to len(valor)

  s=substr(valor,i,1)
  switch
    case s="," : s="."
    case s="." : s=","
  endswitch

  newvalor=newvalor+s
endfor

return newvalor
endproc

;*******************************************************************************
;* Rotina                                                                      *
;*******************************************************************************
Proc PegaDados()
private i,pos,posi

posi=1
For i From 1 To 13        
  Pos=SearchFrom(";",regtabelatmp["Texto"],posi)
  If pos=0 then pos=1000 EndIf
  Valor=RTrim(SubStr(regtabelatmp["Texto"],posi,(pos-posi)))
  
  switch
    case i=1  : [Codigo          ] = Valor 
    case i=2  : [Ex              ] = Valor          
    case i=3  : [Tipo            ] = Valor            
    case i=4  : [Descricao       ] = substr(Valor,2,len(valor)-2)
    case i=5  : [NacionalFederal ] = numval(Valor)
    case i=6  : [ImportadoFederal] = numval(Valor)
    case i=7  : [Estadual        ] = numval(Valor)
    case i=8  : [Municipal       ] = numval(Valor)
    case i=9  :      
          DT=AlinhM(Valor,10)
          [VigenciaInicio  ]=DateVal(SubStr(DT,1,2)+"."+
                                     SubStr(DT,4,2)+"."+
                                     SubStr(DT,7,4))
    case i=10 :
          DT=AlinhM(Valor,10)
          [VigenciaFim     ]=DateVal(SubStr(DT,1,2)+"."+
                                     SubStr(DT,4,2)+"."+
                                     SubStr(DT,7,4))
    case i=11 : [Chave           ] =Valor 
    case i=12 : [Versao          ] =Valor
    case i=13 : [Fonte           ] =Valor
  endswitch
  
  posi=pos+1
EndFor

EndProc

;*******************************************************************************
;* Importando Registros                                                        *
;*******************************************************************************
Proc Importacao(ARQ_TEMP)
Private tabelatmp,Registros,ARQ_TEMP, UF, pos, posf

Aguarde("Aguarde, Convertendo "+ARQ_TEMP)

tabelatmp=Cria_Tabela("","Texto(M70)")

If IsAssigned(varinner) Then release vars varinner  EndIf

FileRead ARQ_TEMP to varinner
Edit tabelatmp
pos=1
While True
 posf=searchFrom("\n",varinner,pos)
 if posf=0 then quitLoop endif
 [Texto]=substr(varinner,pos,(posf-pos))
 Down
 pos=posf+1
EndWhile
Do_It!
ClearAll

If IsAssigned(varinner) Then release vars varinner  EndIf

UF=substr(ARQ_TEMP,14,2)

Registros = 0
NR=nrecords(tabelatmp)

View tabela1
Edit tabelatmp

Scan
  copytoarray regtabelatmp 

  Barra(NR, RecNo())
  Aguarde("Aguarde, Importando IBPT "+BARRA_STRING)

  Registros=Registros + 1

  If Registros>1
     Then    
          Moveto Tabela1
          End 
          if not isblank([UF]) and not isblank([Codigo])
             then Down
          endif   
          [UF              ] = UF
          PegaDados()
  endif
  
  Moveto tabelatmp
EndScan 
Do_It!
ClearAll            

delete tabelatmp

For i From 1 to 3
  {Ask} TypeIn Tabela1 Enter
  Moveto [Ex    ] Check 
  Moveto [Tipo  ] Check 
  Switch
    Case i=1 : 
      Moveto [NacionalFederal ] TypeIn "Calc Average As NacionalFederal"
      Moveto [ImportadoFederal] TypeIn "Calc Average As ImportadoFederal"
      Moveto [Estadual        ] TypeIn "Calc Average As Estadual"
      Moveto [Municipal       ] TypeIn "Calc Average As Municipal"
    Case i=2 : 
      Moveto [NacionalFederal ] TypeIn "Calc Max As NacionalFederal"
      Moveto [ImportadoFederal] TypeIn "Calc Max As ImportadoFederal"
      Moveto [Estadual        ] TypeIn "Calc Max As Estadual"
      Moveto [Municipal       ] TypeIn "Calc Max As Municipal"
    Case i=3 : 
      Moveto [NacionalFederal ] TypeIn "Calc Min As NacionalFederal"
      Moveto [ImportadoFederal] TypeIn "Calc Min As ImportadoFederal"
      Moveto [Estadual        ] TypeIn "Calc Min As Estadual"
      Moveto [Municipal       ] TypeIn "Calc Min As Municipal"
  EndSwitch
  Do_It!
  ClearAll            
  
  View Tabela1
  CoEdit "Answer"
  Scan
    Moveto Tabela1
    End Down
    Switch
      Case i=1 : [Codigo] = "MEDIA"
      Case i=2 : [Codigo] = "MAIOR"
      Case i=3 : [Codigo] = "MENOR"
    EndSwitch
    [UF              ] = UF
    [Ex              ] = [Answer->Ex    ]
    [Tipo            ] = [Answer->Tipo  ]
    [NacionalFederal ] = NDecimal([Answer->NacionalFederal],2)
    [ImportadoFederal] = NDecimal([Answer->ImportadoFederal],2)
    [Estadual        ] = NDecimal([Answer->Estadual],2)
    [Municipal       ] = NDecimal([Answer->Municipal],2)
    
    Moveto "Answer"
  EndScan
  Do_It!
  ClearAll
EndFor

EndProc ;Importacao()

;*******************************************************************************
;* Carregar Lista                                                              *
;*******************************************************************************
Proc CarregarLista()

DynArray Array_Registro[]

Wcs=0
                          
Lista_DiretorioF(VSDGPASTA,"TIBPT*.csv")

For i from 1 to 7
  If Not IsFile(PrivDir()+"Dir.Txt")
     Then Sleep(1000)
          Loop
     Else Editor Open PrivDir()+"Dir.Txt"
          If ErrorCode()=27
             Then Sleep 1000
                  Loop
          EndIf
          
          While True
            Extrair_Linha()
            If IsBlank(ELinha) Then QuitLoop EndIf
            wcs=wcs+1
            Array_Registro[wcs] = Completa(SubStr(ELINHA,1,Len(ELINHA)-1),40," ")+" "
          EndWhile
          CancelEdit

          QuitLoop
  EndIf
EndFor

Endproc ;CarregarLista()

;*******************************************************************************
;* Rotina                                                                      *
;*******************************************************************************
Proc SD_Dialog(Disparo,Campo,Evento,Elemento)
Temp=True
MSG_CAMPO=""
                                    
TECLA=""
If Disparo="OPEN"  Then AoCriarShowDialog() EndIf
If Disparo="EVENT" And Evento["Type"]="KEY" Then
   Switch
     Case Evento["KeyCode"] =   9: Temp=False
     Case Evento["KeyCode"] = -59: Dialog_F1()
     Case (Evento["KeyCode"] <= -104 And Evento["KeyCode"] >= -113) Or
          Evento["KeyCode"]  = -139 Or  Evento["KeyCode"]  = -140:
          SYS_TECLA_ACIONADA=Evento["KeyCode"]
          Seta_Tecla_Acionada()
          CancelDialog
     Case Evento["KeyCode"] =  27:
          Temp=False
          Switch
            Case Campo="TG_Registro"      : Campo="NO"
            Case Campo="YES" Or Campo="NO": Campo="TG_Registro"
          EndSwitch
     Case Evento["KeyCode"] = 32 And Campo="TG_Registro":
          Temp=False
          If SubStr(Array_Registro[ControlValue("TG_Registro")],41,1)=" "
             Then Array_Registro[ControlValue("TG_Registro")]=SubStr(Array_Registro[ControlValue("TG_Registro")],1,40)+"X"
             Else Array_Registro[ControlValue("TG_Registro")]=SubStr(Array_Registro[ControlValue("TG_Registro")],1,40)+" "
          EndIf
     Case Evento["KeyCode"] = 13:
          Temp=False
          If Checa_TAG()
             Then Switch
                    Case Campo="TG_Registro": Campo="YES"
                  EndSwitch
          EndIf                     
   EndSwitch 
EndIf

Switch  
  Case Campo="TG_Registro":
       MSG_CAMPO="Selecione o arquivo"
       TECLA="Barra de Espa‡o=Marca/Desmarca"
EndSwitch

Monta_Prompt(MSG_CAMPO,TECLA)
Return Temp
EndProc

;*******************************************************************************
;* Rotina Principal                                                            *
;*******************************************************************************
AutoLib="\\Sistemas\\Cadastro\\Bib_Show,\\Sistemas\\Cadastro\\Bibliot"

COR_MENSAGEM="1"
Mensagem("- O arquivo deve conter o seguinte nome:// //"+
          "'TIBPT' e a sigla do estado que est  importando, com a exten‡„o .csv// //"+
          "Exemplo: TIBPTMG.csv////"+
          "- Coloque os arquivos no diret˘rio "+substr(directory(),1,2)+"\\IBPT")

IMPORTOU = False
Tabela1 = Cria_Temp(PrivDir())
Empty "TIBPT"
Copy "TIBPT" Tabela1

VSDGPASTA = substr(directory(),1,2)+"\\IBPT\\"

CarregarLista()

If DynArraySize(Array_Registro)=0 
   Then Mensagem ("Arquivo n„o encontrado no diret˘rio 'C:\Vise'.//Verifique o nome e a origem do arquivo.//Exemplo: 'TIBPTMG.csv'.")
   Else 
        While True
            
            ShowDialog "Importa‡„o Tabela IBPT" Proc "SD_Dialog"
            Trigger "OPEN","ARRIVE"
            Key "F1","ENTER","ESC",32,
                -104, -105, -106, -107, -108, -109, -110, -111, -112, -113, -139, -140  
             @ 02,12   Height 14 Width 56
            
            @ 00,02 ?? "Lista de arquivos"
            PickDynArray @1,01 Height 08 width 53
             Columns 1
              Array_Registro
               Tag "TG_Registro"
                To ArrayElement
            
              Pushbutton @ 10,17 width 11 "~O~k"      OK     Default Value "Ok" Tag "YES" To BottonValue
              Pushbutton @ 10,29 width 11 "~C~ancela" CANCEL                    Tag "NO"  To BottonValue
            
            EndDialog
            
            If Not RetVal Then QuitLoop EndIf
                 
            FAZ=False
            For i From 1 To DynArraySize(Array_Registro)
                If SubStr(Array_Registro[i],41,1) = "X"
                   Then QuitLoop
                   Else If i = DynArraySize(Array_Registro) 
                           Then FAZ=True
                        EndIf
                EndIf
            EndFor
            If FAZ 
               Then Mensagem("Nenhum arquivo selecionado !")
                    Loop
            EndIf
            
            ConfGeral("Deseja importar a carga tributaria conforme IBPT ?") 
            If OK="S"
               Then For k From 1 To DynArraySize(Array_Registro)
                      If SubStr(Array_Registro[k],41,1) = "X"
                         Then ARQ_TEMP =VSDGPASTA+SubStr(Array_Registro[k],1,7)+".csv"
                              Importacao(ARQ_TEMP)            
                              Add Tabela1 "TIBPT"
                              ClearAll
                      EndIf
                    EndFor
                    Mensagem("Importa‡„o realizada com sucesso !")
               Else Mensagem("Opera‡„o Cancelada !")     
            EndIf  
            QuitLoop 
        EndWhile    
EndIf
ClearAll
Release Vars All
Release Procs All
