;_Test_Evergabe.au3
;Includes AutoStandart
#include <File.au3>
#include <Array.au3>
#include <Debug.au3>
#include <winhttp.au3>
#include <Excel.au3>


#include <ButtonConstants.au3>
#include <EditConstants.au3>
#include <GUIConstantsEx.au3>
#include <ListViewConstants.au3>
#include <WindowsConstants.au3>
#include <GuiListView.au3>

Global $GsSMNr = ""
Global $GsBasePfad = @ScriptDir & "\..\EV\DBM\"
Global $GsBasePfad = @ScriptDir & "\..\EV\TP\2023\"
Global $Cloud_Pfad_Baubegleitung = "D:\Arbeit\OneDrive - Technik Partner AG\TP-DE\Aufträge\Eingang\_Baubegleitung\"
Global $Cloud_Pfad_Service_GF = "D:\Arbeit\OneDrive - Technik Partner AG\TP-DE\Aufträge\Eingang\_Service_GF\"
Global $Cloud_Pfad_STOE_TB = "D:\Arbeit\OneDrive - Technik Partner AG\TP-DE\Aufträge\Eingang\_Störung_Tiefbau_TP\"
Global $Cloud_Pfad_Tagesgeschaeft = "D:\Arbeit\OneDrive - Technik Partner AG\TP-DE\Aufträge\Eingang\_Tagesgeschäft\"
Global $Cloud_Pfad_Tiefbau_Dritte = "D:\Arbeit\OneDrive - Technik Partner AG\TP-DE\Aufträge\Eingang\_Tiefbau_Dritte\"

;~ _start_Evergabe()

;~ _Aktuelle_Auftraege()
;~ _testtst()
;~ ConsoleWrite("Fertig mit dem Task...")
;~ _test()

; ======= MINIMALTEST – BITTE GENAU SO TESTEN =====================
; ======= KONFIGURATION ==========================================
Global Const $LOGIN_URL   = "https://evergabe.telekom.de/public/login"
Global Const $DASHBOARD   = "https://evergabe.telekom.de/framework-agreement-call"
Global Const $USERNAME    = IniRead(@ScriptDir & "\..\daten\conf.ini", "EVergabe", "Benutzer", "xxx")
Global Const $PASSWORD    = IniRead(@ScriptDir & "\..\daten\conf.ini", "EVergabe", "Passwort", "xxx")


; COM-Fehler anzeigen
Global $oMyError = ObjEvent("AutoIt.Error", "_ComErrFunc")
Global $g_iReqCounter = 0 ; Zähler für 01.header.txt, 01.response.txt, ...

Func _ComErrFunc()
    Local $sMsg = "COM-Fehler!" & @CRLF & _
                  "Beschreibung: " & @error & @CRLF & _
                  "Zusatzzahl: "   & @extended & @CRLF
    ConsoleWrite("! " & $sMsg & @CRLF)
    MsgBox(16, "COM-Fehler", $sMsg)
EndFunc

; =================== Hilfsfunktionen ============================

Func _UrlEncode($s)
    Local $i, $ch, $sOut = ""
    For $i = 1 To StringLen($s)
        $ch = StringMid($s, $i, 1)
        Local $asc = Asc($ch)
        If ($asc >= 48 And $asc <= 57) Or _
           ($asc >= 65 And $asc <= 90) Or _
           ($asc >= 97 And $asc <= 122) Or _
           $ch = "-" Or $ch = "_" Or $ch = "." Or $ch = "~" Then
            $sOut &= $ch
        Else
            $sOut &= "%" & Hex($asc, 2)
        EndIf
    Next
    Return $sOut
EndFunc

Func _Pad2($i)
    If $i < 10 Then
        Return "0" & $i
    EndIf
    Return $i
EndFunc

; Speichert Request- und Response-Daten als NN.header.txt / NN.response.txt
Func _LogRequestResponse($sMethod, $sUrl, $sReqHeaders, $sReqBody, _
                         $iStatus, $sRespHeaders, $sRespBody)
    $g_iReqCounter += 1
    Local $sIdx = _Pad2($g_iReqCounter)

    ; ----- Header-Datei -----
    Local $sHeaderFile = $sIdx & ".header.txt"
    Local $sHeaderContent = ""
    $sHeaderContent &= "=== REQUEST " & $sIdx & " ===" & @CRLF
    $sHeaderContent &= "Method: " & $sMethod & @CRLF
    $sHeaderContent &= "URL: "    & $sUrl & @CRLF & @CRLF
    $sHeaderContent &= "[Request Headers]" & @CRLF & $sReqHeaders & @CRLF & @CRLF
    $sHeaderContent &= "[Request Body]"    & @CRLF & $sReqBody   & @CRLF

    FileWrite($sHeaderFile, $sHeaderContent)

    ; ----- Response-Datei -----
    Local $sRespFile = $sIdx & ".response.txt"
    Local $sRespContent = ""
    $sRespContent &= "=== RESPONSE " & $sIdx & " ===" & @CRLF
    $sRespContent &= "Status: " & $iStatus & @CRLF & @CRLF
    $sRespContent &= "[Response Headers]" & @CRLF & $sRespHeaders & @CRLF & @CRLF
    $sRespContent &= "[Response Body]"    & @CRLF & $sRespBody    & @CRLF

    FileWrite($sRespFile, $sRespContent)

    ; ----- Konsolen-Ausgabe -----
    ConsoleWrite("+ ==== REQUEST " & $sIdx & " " & $sMethod & " " & $sUrl & " ====" & @CRLF)
    ConsoleWrite($sReqHeaders & @CRLF)
    If $sReqBody <> "" Then
        ConsoleWrite("Body:" & @CRLF & $sReqBody & @CRLF)
    EndIf
    ConsoleWrite("+ ==== RESPONSE " & $sIdx & " (HTTP " & $iStatus & ") ====" & @CRLF)
    ConsoleWrite($sRespHeaders & @CRLF)
    ConsoleWrite("Body (erste 500 Zeichen):" & @CRLF & StringLeft($sRespBody, 500) & @CRLF)
EndFunc

Func _HttpCreate()
    Local $oHttp = ObjCreate("WinHttp.WinHttpRequest.5.1")
    If Not IsObj($oHttp) Then
        MsgBox(16, "Fehler", "WinHttp-Objekt konnte nicht erzeugt werden.")
        Exit
    EndIf

    ; Cookie Handling aktivieren
    $oHttp.Option(6) = True ; WinHttpRequestOption_EnableCookie
    Return $oHttp
EndFunc

Func _HttpGet($oHttp, $sUrl)
    If Not IsObj($oHttp) Then
        MsgBox(16, "Fehler", "HTTP-Objekt ist ungültig vor GET.")
        Exit
    EndIf

    Local $sMethod = "GET"
    Local $sReqHeaders = ""
    Local $sReqBody = ""

    ConsoleWrite("+ GET " & $sUrl & @CRLF)

    $oHttp.Open($sMethod, $sUrl, False)
    $oHttp.SetRequestHeader("User-Agent", _
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) eVergabeBot/1.0")

    ; Für Logging: Request-Header rekonstruieren (was wir selbst gesetzt haben)
    $sReqHeaders &= "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) eVergabeBot/1.0" & @CRLF

    $oHttp.Send()

    Local $iStatus = $oHttp.Status
    ; Response-Header holen
    Local $sAllRespHeaders = $oHttp.GetAllResponseHeaders()
    Local $sRespBody = $oHttp.ResponseText

    _LogRequestResponse($sMethod, $sUrl, $sReqHeaders, $sReqBody, _
                        $iStatus, $sAllRespHeaders, $sRespBody)

    Return $sRespBody
EndFunc

Func _HttpPost($oHttp, $sUrl, $sBody)
    If Not IsObj($oHttp) Then
        MsgBox(16, "Fehler", "HTTP-Objekt ist ungültig vor POST.")
        Exit
    EndIf

    Local $sMethod = "POST"
    Local $sReqHeaders = ""
    Local $sReqBody = $sBody

    ConsoleWrite("+ POST " & $sUrl & @CRLF)

    $oHttp.Open($sMethod, $sUrl, False)
    $oHttp.SetRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)")
    $oHttp.SetRequestHeader("Content-Type", "application/x-www-form-urlencoded")
    $oHttp.SetRequestHeader("Referer", $LOGIN_URL)

    ; Request-Header fürs Logging
    $sReqHeaders &= "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64)" & @CRLF
    $sReqHeaders &= "Content-Type: application/x-www-form-urlencoded" & @CRLF
    $sReqHeaders &= "Referer: " & $LOGIN_URL & @CRLF

    $oHttp.Send($sBody)

    Local $iStatus = $oHttp.Status
    Local $sAllRespHeaders = $oHttp.GetAllResponseHeaders()
    Local $sRespBody = $oHttp.ResponseText

    _LogRequestResponse($sMethod, $sUrl, $sReqHeaders, $sReqBody, _
                        $iStatus, $sAllRespHeaders, $sRespBody)

    Return $oHttp
EndFunc

Func _ExtractCsrf($sHtml, ByRef $sFieldName)
    ; Meta-Tag
    Local $aMeta = StringRegExp($sHtml, '(?i)<meta[^>]+name="csrf-token"[^>]+content="([^"]+)"', 3)
    If Not @error And UBound($aMeta) >= 1 Then
        $sFieldName = "_csrf"
        ConsoleWrite("+ CSRF (meta): " & $aMeta[0] & @CRLF)
        Return $aMeta[0]
    EndIf

    ; Hidden input
    Local $a = StringRegExp($sHtml, '(?i)name="([^"]*csrf[^"]*)"[^>]*value="([^"]+)"', 3)
    If @error Or UBound($a) < 2 Then
        ConsoleWrite("! CSRF-Token nicht gefunden" & @CRLF)
        FileWrite("debug_login_page.html", $sHtml)
        Exit
    EndIf
    $sFieldName = $a[0]
    ConsoleWrite("+ CSRF Feld: " & $a[0] & " = " & $a[1] & @CRLF)
    Return $a[1]
EndFunc

; ===================== HAUPT-PROGRAMM ============================

ConsoleWrite("+ AutoIt-Version: " & @AutoItVersion & @CRLF)

Local $oHttp = _HttpCreate()

; 1. Login-Seite holen
Local $sHtml = _HttpGet($oHttp, $LOGIN_URL)

; 2. CSRF-Token + Feldname
Local $sCsrfField = ""
Local $sCsrfValue = _ExtractCsrf($sHtml, $sCsrfField)

; 3. Cookies zu Debugzwecken
Local $sSetCookie = $oHttp.GetResponseHeader("Set-Cookie")
ConsoleWrite("+ Set-Cookie: " & $sSetCookie & @CRLF)

; 4. POST-Body bauen (Feldnamen an deine Login-Seite anpassen!)
; Beispiel für Yii2/Evergabeseite mit LoginForm[username]/LoginForm[password]:
Local $sBody = _
    "LoginForm[username]=" & _UrlEncode($USERNAME) & _
    "&LoginForm[password]=" & _UrlEncode($PASSWORD) & _
    "&" & $sCsrfField & "=" & _UrlEncode($sCsrfValue)

; 5. Login senden
$oHttp = _HttpPost($oHttp, $LOGIN_URL, $sBody)

Local $iStatus = $oHttp.Status
Local $sResp   = $oHttp.ResponseText

If $iStatus <> 302 And StringInStr($sResp, "Logout") = 0 Then
    ConsoleWrite("! Login fehlgeschlagen, HTTP " & $iStatus & @CRLF)
    ; Response ist bereits in NN.response.txt geloggt
    Exit
EndIf

ConsoleWrite("+ Login scheint erfolgreich, HTTP " & $iStatus & @CRLF)

; 6. Authentifizierte Dashboard-Abfrage (ebenfalls geloggt)
Local $sDash = _HttpGet($oHttp, $DASHBOARD)
Local $sTitle = StringRegExpReplace($sDash, "(?is).*?<title>(.*?)</title>.*", "\1")
ConsoleWrite("+ Dashboard-Titel: " & $sTitle & @CRLF)

Func _testtst()
	Global $hSession = _WinHttpOpen("Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:63.0) Gecko/20100101 Firefox/63.0")

	Global $aHosts[2][2]
	$aHosts[1][0] = "www.evergabe.telekom.de"
	$aHosts[1][1] = _WinHttpConnect($hSession, $aHosts[1][0])
	Global $sHeader = "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" & @CRLF & "Accept-Language: de,en-US;q=0.7,en;q=0.3" & @CRLF & "Accept-Encoding: gzip, deflate, br" & @CRLF

	$sUsername = IniRead(@ScriptDir & "\..\daten\conf.ini", "EVergabe", "Benutzer", "xxx")
	$sPasswort = IniRead(@ScriptDir & "\..\daten\conf.ini", "EVergabe", "Passwort", "xxx")

;~ 	$sUsername = "FK-Technikpartner"
;~ 	$sPasswort = "5@sLkx2rabv#"
	
	ConsoleWrite($sUsername &@CRLF)
	ConsoleWrite($sPasswort &@CRLF)
;~ FK-TechnikpartnerFK-Technikpartner

	
$sHeader = "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7"
$sLink = "/"
$sReferer = ""

$aHTML = _WinHttpSimpleSSLRequest( $aHosts[1][0], "GET", $sLink, $sReferer, Default, $sHeader, True, 1)
	_Write_to_Console("laden | " & $aHosts[1][0] & $sLink)
	If IsArray($aHTML) Then
		$aHTML[1] = StringReplace($aHTML[1], "amp;", "")
;~ 		$aHTML[1] = BinaryToString($aHTML[1], 4)
;~ 		_ArrayDisplay($aHTML)
		ConsoleWrite($aHTML[1])
	Else
		$aHTML = _WinHttpSimpleSSLRequest($aHosts[1][0], "GET", $sLink, $sReferer)
		$aHTML = StringReplace($aHTML, "amp;", "")
;~ 		$aHTML = BinaryToString($aHTML, 4)
		ConsoleWrite($aHTML)
	EndIf

MsgBox(64, "", "")
	$sRetrunLogin = _EV_Login($sUsername, $sPasswort)
	If $sRetrunLogin = "True" Then
;~ 		ConsoleWrite("Login Erfolgreich" & @CRLF)
		_Write_to_Console("Login Erfolgreich")
		$sHTML = _send_WinhttpS_GET($aHosts[1][1], "/framework-agreement-call", "https://www.evergabe.telekom.de/")

		$sDetailsID = "17675084"
		$aRrasd = _EV_GET_LEB_Liste($sDetailsID)
		_DebugArrayDisplay($aRrasd)

	EndIf

EndFunc   ;==>_testtst


Func _Aktuelle_Auftraege()
	Global $hSession = _WinHttpOpen("Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:63.0) Gecko/20100101 Firefox/63.0")
	Global $aAMasterListe[5]
	Global $aHosts[2][2]
	$aHosts[1][0] = "www.evergabe.telekom.de"
	$aHosts[1][1] = _WinHttpConnect($hSession, $aHosts[1][0])
	Global $sHeader = "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" & @CRLF & "Accept-Language: de,en-US;q=0.7,en;q=0.3" & @CRLF & "Accept-Encoding: gzip, deflate, br" & @CRLF

	$sUsername = IniRead(@ScriptDir & "\..\daten\conf.ini", "EVergabe", "Benutzer", "xxx")
	$sPasswort = IniRead(@ScriptDir & "\..\daten\conf.ini", "EVergabe", "Passwort", "xxx")

	$sUsername = "FK-Technikpartner"
	$sPasswort = "5@sLkx2rabv#"

;~ FK-TechnikpartnerFK-Technikpartner


	$sPfadNextCloud = "E:\OneDrive - Technik Partner Construction GmbH\TP-DE\"
	$aSearchInfo = _RecursiveFileListToArray($sPfadNextCloud, '', 2)
	$sPfadCloudPlanung = "E:\OneDrive - Technik Partner Construction GmbH\TP-DE\_Planung\MA\"
	$aSearchInfoP = _RecursiveFileListToArray($sPfadCloudPlanung, '', 2)


	$sRetrunLogin = _EV_Login($sUsername, $sPasswort)
	If $sRetrunLogin = "True" Then
		ConsoleWrite("Login Erfolgreich" & @CRLF)
		_Write_to_Console("Login Erfolgreich")
		$sHTML = _send_WinhttpS_GET($aHosts[1][1], "/framework-agreement-call", "https://www.evergabe.telekom.de/")
;~ 		ClipPut($sHTML)
;~ 		_Write_to_Console($sHTML)
;~ 		MsgBox(64,"erstmal","fertig")
		$sStatus = "-1"
		$aEV_Liste = _EV_Suche_Status_All($sStatus) ;Vertrag;SM;TitleEV;42erNr;StartDatum;EndDatum;DetailsIDEV;Status
;~ 		_DebugArrayDisplay($aEV_Liste)
		;4650009407|208602505|Hof 979244 Münstertal SM 208602505|4211387386|29.08.2022|30.09.2022|18168514|Neu
		$sWrite = "Vertrag|SMNr|Kurztext EV|AbrufNr EV|Startdatum|Enddatum|DetailsID|Status EV|CloudPFad|LEB Status EV|PlanPreis EV|Freigabedatum|Preis|RBU|Gutschrift|Avis"& @CRLF
		FileWrite(@ScriptDir & "\..\EV_Daten_" & @YEAR &"_" & @MON & "_" &@MDAY& ".txt", $sWrite)
		Dim $aMasterListe[UBound($aEV_Liste)][17]
		For $i = 0 To UBound($aEV_Liste) - 1
			$aMasterListe[$i][0] = $aEV_Liste[$i][0]
			$aMasterListe[$i][1] = $aEV_Liste[$i][1]
			$aMasterListe[$i][2] = $aEV_Liste[$i][2]
			$aMasterListe[$i][3] = $aEV_Liste[$i][3]
			$aMasterListe[$i][4] = $aEV_Liste[$i][4]
			$aMasterListe[$i][5] = $aEV_Liste[$i][5]
			$aMasterListe[$i][6] = $aEV_Liste[$i][6]
			$aMasterListe[$i][7] = $aEV_Liste[$i][7]

			$aAMasterListe[0] = $aEV_Liste[$i][0];Vertrag
			$aAMasterListe[1] = $aEV_Liste[$i][1];SMnr
			$aAMasterListe[2] = $aEV_Liste[$i][2];TitleEV
			$aAMasterListe[3] = $aEV_Liste[$i][3];42erNr
			$aAMasterListe[4] = $aEV_Liste[$i][6];DetailsIDEv

			Dim $aSuchErg[1]
			For $ii = 1 To UBound($aSearchInfo) - 1
				If StringInStr($aSearchInfo[$ii], $aEV_Liste[$i][1]) Then
					_ArrayAdd($aSuchErg, $aSearchInfo[$ii])
				EndIf
			Next

			If UBound($aSuchErg) > 1 Then
				_ArrayDelete($aSuchErg, 0)
				$aMasterListe[$i][8] = $aSuchErg[0]
			Else
				; Suche Aufträge in der Planung
				Dim $aSuchErg2[1]
				For $a = 1 To UBound($aSearchInfoP) - 1
					If StringInStr($aSearchInfoP[$a], $aEV_Liste[$i][1]) Then
						_ArrayAdd($aSuchErg2, $aSearchInfoP[$a])
					EndIf
				Next

				If UBound($aSuchErg2) > 1 Then
					_ArrayDelete($aSuchErg2, 0)
					$aMasterListe[$i][8] = $aSuchErg2[0]
				Else

					_Write_to_Console($aEV_Liste[$i][1] & " nicht in der Cloud gefunden!!!!")
					$aMasterListe[$i][8] = "NA " & $aEV_Liste[$i][1]
				EndIf
			EndIf

			;Abgrge Plan Preis
			$sSumme =  _EV_GET_PlanungsSumme($aEV_Liste[$i][6])
			$aMasterListe[$i][10] = $sSumme

			$stemp =  _EV_DDL_P83_GET_Bez($aEV_Liste[$i][6])
			_EV_DDL_LV_Planung($aEV_Liste[$i][6])
			; Abfrage EV Abgerechnet in Bemerkung
			$aLEB_Liste = _EV_GET_LEB_Liste($aEV_Liste[$i][6]) ;detailsID
			If IsArray($aLEB_Liste) Then
;~ 				_DebugArrayDisplay($aLEB_Liste)
				$sNeuText = ""
;~ 				$sNeuText =  _ArrayToString($aLEB_Liste, ";", -1, -1, 1, 3)
				For $iii = 0 To UBound($aLEB_Liste) - 1
					$sNeuText &= $aLEB_Liste[$iii][2] & "  Status: " & $aLEB_Liste[$iii][3] &$aLEB_Liste[$iii][4]& " ;"
				Next
				$aMasterListe[$i][9] = $sNeuText
				_Write_to_Console($sNeuText)
			Else
				$aMasterListe[$i][9] = "keine Abrechnung"
			EndIf
;~ 			_DebugArrayDisplay($aMasterListe)
			$sWrite = $aMasterListe[$i][0] & "|"& $aMasterListe[$i][1] & "|"& $aMasterListe[$i][2] & "|"& $aMasterListe[$i][3] & "|"& $aMasterListe[$i][4] & "|"& $aMasterListe[$i][5] & "|"& $aMasterListe[$i][6] & "|"& $aMasterListe[$i][7] & "|"& $aMasterListe[$i][8] & "|"& $aMasterListe[$i][9] & "|"& $aMasterListe[$i][10] & "|"&$aMasterListe[$i][11] & "|"&$aMasterListe[$i][12] & "|"&$aMasterListe[$i][13] & "|"&$aMasterListe[$i][14] & "|"&$aMasterListe[$i][15] & "|"&$aMasterListe[$i][16] & "|"& @CRLF
			FileWrite(@ScriptDir & "\..\EV_Daten_" & @YEAR &"_" & @MON & "_" &@MDAY& ".txt", $sWrite)
			ConsoleWrite($sWrite&@CRLF)
		Next

		_DebugArrayDisplay($aMasterListe)
	EndIf
EndFunc   ;==>_Aktuelle_Auftraege


Func _Suche_Cloud()




	$sPfadNextCloud = "D:\Arbeit\OneDrive - Technik Partner AG\TP-DE\"
	Local $sSuchtext = "208158851"
	If $sSuchtext = "" Then
		$sSuchtext = "*"
	EndIf
;~ 	MsgBox(64, "Suche los...",$sSuchtext & @CRLF & $sPfadNextCloud )
;~ 	$aSearchInfo = _RecursiveFileListToArray($sPfadNextCloud, $sSuchtext, 1)
	$aSearchInfo = _RecursiveFileListToArray($sPfadNextCloud, '', 2)
;~ _ArrayDisplay($aSearchInfo)
;~     _ArrayDisplay($aSearchInfo, "$aFileList")
	Dim $aSuchErg[1]


	For $i = 1 To UBound($aSearchInfo) - 1
		If StringInStr($aSearchInfo[$i], $sSuchtext) Then
			_ArrayAdd($aSuchErg, $aSearchInfo[$i])
		EndIf
	Next
;~ 	_ArrayDisplay($aSuchErg)
;~ 	MsgBox(64, "", UBound($aSuchErg))
	If UBound($aSuchErg) > 1 Then
		_ArrayDelete($aSuchErg, 0)
;~ 	_ArrayDisplay($aSuchErg)


		_Write_to_Console("Pfad Cloud; " & $aSuchErg[0])
		ShellExecute($aSuchErg[0])

	Else
		_Write_to_Console($sSuchtext & " nicht in der Cloud gefunden!!!!")

	EndIf

EndFunc   ;==>_Suche_Cloud

Func _start_Evergabe()
	Global $hSession = _WinHttpOpen("Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:63.0) Gecko/20100101 Firefox/63.0")

	Global $aHosts[2][2]
	$aHosts[1][0] = "www.evergabe.telekom.de"
	$aHosts[1][1] = _WinHttpConnect($hSession, $aHosts[1][0])
	Global $sHeader = "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" & @CRLF & "Accept-Language: de,en-US;q=0.7,en;q=0.3" & @CRLF & "Accept-Encoding: gzip, deflate, br" & @CRLF

	$sUsername = IniRead(@ScriptDir & "\..\daten\conf.ini", "EVergabe", "Benutzer", "xxx")
	$sPasswort = IniRead(@ScriptDir & "\..\daten\conf.ini", "EVergabe", "Passwort", "xxx")

	$sUsername = "FK-Technikpartner"
	$sPasswort = "5@sLkx2rabv#"

;~ FK-TechnikpartnerFK-Technikpartner

	$sRetrunLogin = _EV_Login($sUsername, $sPasswort)
	If $sRetrunLogin = "True" Then
;~ 		ConsoleWrite("Login Erfolgreich" & @CRLF)
		_Write_to_Console("Login Erfolgreich")
		$sHTML = _send_WinhttpS_GET($aHosts[1][1], "/framework-agreement-call", "https://www.evergabe.telekom.de/")
;~ 		ClipPut($sHTML)
;~ 		_Write_to_Console($sHTML)
;~ 		MsgBox(64,"erstmal","fertig")
		$sStatus = "-1"
		$aEV_Liste = _EV_Suche_Status_All($sStatus) ;Vertrag;SM;TitleEV;42erNr;StartDatum;EndDatum;DetailsIDEV;Status
		_DebugArrayDisplay($aEV_Liste)
;~ ;;Row|Col 0|Col 1|Col 2|Col 3|Col 4|Col 5|Col 6|Col 7
		;;# 0|4650009407|208602505|Hof 979244 Münstertal SM 208602505|4211387386|29.08.2022|30.09.2022|18168514|Neu


		$aListre = _EV_Suche_Status_All("-1")
		;_DebugArrayDisplay($aListre)
		For $i = 0 To UBound($aEV_Liste) - 1
			; SMnr suchen in EVergabe:
			$aArrayList = _EV_Search_SM($aEV_Liste[$i][1])
			;_DebugArrayDisplay($aArrayList)
			;Carl-Benz-Str. 578579 Neuhausen ob Eck SM 207268568|207268568|4210464751|17542106|4210464751/00010 Fremdleistung Tiefbau DBM|4650002630|06.09.2021|01.07.2022|Angenommen
			$GsSMNr = $aEV_Liste[$i][1]



			If IsArray($aArrayList) Then
				For $ia = 0 To UBound($aArrayList) - 1
					$aLEB_Liste = _EV_GET_LEB_Liste($aArrayList[$ia][3]) ; DetailsID übergeben

					_EV_DDL_P83_GET_Bez($aArrayList[$ia][3])
					_EV_DDL_LV_Planung($aArrayList[$ia][3])

					If IsArray($aLEB_Liste) Then

						For $ii = 0 To UBound($aLEB_Liste) - 1
							$aAufmass = _EV_GET_Aufma_positionen($aLEB_Liste[$ii][1])
;~ 							_DebugArrayDisplay($aAufmass)
							$sDateiname = $aLEB_Liste[$ii][1] & "_" & $aLEB_Liste[$ii][2] & "__" & $aLEB_Liste[$ii][3]
;~ 							_EVAufmLV_Export_Exel($aAufmass, $sDateiname)
							_EVAufmLV_Export_txt($aAufmass, $sDateiname)
							_EV_GET_DDL_Anlagen($aLEB_Liste[$ii][1])


						Next
					EndIf
				Next
			EndIf

		Next




	Else
		MsgBox(64, "Login Fehler", "Login war nicht erfolgreich")
	EndIf
EndFunc   ;==>_start_Evergabe

Func _test()

	$GsSMNr = "206288250"
	$sDeateilsID = "16941965"
	$sSheatID = "0007928495"



	Global $hSession = _WinHttpOpen("Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:63.0) Gecko/20100101 Firefox/63.0")

	Global $aHosts[2][2]
	$aHosts[1][0] = "www.evergabe.telekom.de"
	$aHosts[1][1] = _WinHttpConnect($hSession, $aHosts[1][0])
	Global $sHeader = "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" & @CRLF & "Accept-Language: de,en-US;q=0.7,en;q=0.3" & @CRLF & "Accept-Encoding: gzip, deflate, br" & @CRLF

	$sUsername = IniRead(@ScriptDir & "\..\daten\conf.ini", "EVergabe", "Benutzer", "xxx")
	$sPasswort = IniRead(@ScriptDir & "\..\daten\conf.ini", "EVergabe", "Passwort", "xxx")

	$sUsername = "EvTOOL"
	$sPasswort = "qS5ch#64"

	$sRetrunLogin = _EV_Login($sUsername, $sPasswort)
	If $sRetrunLogin = "True" Then
;~ 		$aArrayList = _EV_Search_SM($GsSMNr)
;~ 		If IsArray($aArrayList) Then
;~ 			For $ia = 0 To UBound($aArrayList) - 1
;~ 				$aLEB_Liste = _EV_GET_LEB_Liste($aArrayList[$ia][3]) ; DetailsID übergeben

;~ 				_EV_DDL_P83_GET_Bez($aArrayList[$ia][3])
;~ 				_EV_DDL_LV_Planung($aArrayList[$ia][3])
;~ 				If IsArray($aLEB_Liste) Then

;~ 					For $ii = 0 To UBound($aLEB_Liste) - 1
		_EV_GET_DDL_Anlagen($sSheatID)

		$aAufmass = _EV_GET_Aufma_positionen($sSheatID)
;~ _DebugArrayDisplay($aAufmass)
		$sDateiname = $sSheatID & "_" & "testadfasdf" & "__" & "adsfsadfasdfasdf"
;~ 		_EVAufmLV_Export_Exel($aAufmass, $sDateiname)
		_EVAufmLV_Export_txt($aAufmass, $sDateiname)
;~ MsgBox(64, "", "")
;~ 					Next
;~ 				EndIf
;~ 			Next
;~ 		EndIf
	Else
		MsgBox(64, "Login Fehler", "Login war nicht erfolgreich")
	EndIf
EndFunc   ;==>_test

Func _EV_Login($sUsername, $sPasswort)
	$sHTML = _send_WinhttpS_GET($aHosts[1][1], "/", "https://www.evergabe.telekom.de/")
	ClipPut($sHTML)
	MsgBox(64, "Startseite", "Quellcode")
	$aCSRF = StringRegExp($sHTML, '_csrf" value="([^=]+)', 3)
	If IsArray($aCSRF) Then
		$sHeader = "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" & @CRLF & "Accept-Language: de,en-US;q=0.7,en;q=0.3" & @CRLF & "Accept-Encoding: gzip, deflate, br" & @CRLF & "Content-Type: application/x-www-form-urlencoded" & @CRLF
		$sPosu = "_csrf=" & $aCSRF[0] & "%3D%3D&LoginForm%5Busername%5D=" & $sUsername & "&LoginForm%5Bpassword%5D=" & _URIEncode($sPasswort)
		$aHTML = _WinHttpSimpleSSLRequest($aHosts[1][1], "POST", "/public/login", "https://www.evergabe.telekom.de/", $sPosu, "", True)
		_DebugArrayDisplay($aHTML)
		ClipPut($sPosu)
		MsgBox(64, $sPosu, "")
		If IsArray($aHTML) Then

			If StringInStr($aHTML[1], 'Abmelden</a>') Then
				Return "True"
			Else
				Return "False"
			EndIf


		EndIf
	EndIf
	_Write_to_Console("Seitenfehler/Check Internetseite")
EndFunc   ;==>_EV_Login

; Function Name:   _RecursiveFileListToArray($sPath, $sPattern, $iFlag = 0, $iFormat = 1, $sDelim = @CRLF)
; Description::    gibt Verzeichnisse und/oder Dateien (rekursiv) zurück, die
;                  einem RegExp-Pattern entsprechen
; Parameter(s):    $sPath = Startverzeichnis
;                  $sPattern = ein beliebiges RexExp-Pattern für die Auswahl
;                  $iFlag = Auswahl
;                           0 = Dateien & Verzeichnisse
;                           1 = nur Dateien
;                           2 = nur Verzeichnisse
;                  $iFormat = Rückgabeformat
;                             0 = String
;                             1 = Array mit [0] = Anzahl
;                             2 = Nullbasiertes Array
;                  $sDelim = Trennzeichen für die String-Rückgabe
Func _RecursiveFileListToArray($sPath, $sPattern, $iFlag = 0, $iFormat = 1, $sDelim = @CRLF)
	Local $hSearch, $sFile, $sReturn = ''
	If StringRight($sPath, 1) <> '\' Then $sPath &= '\'
	$hSearch = FileFindFirstFile($sPath & '*.*')
	If @error Or $hSearch = -1 Then Return SetError(0, 0, $sReturn)
	While True
		$sFile = FileFindNextFile($hSearch)
		If @error Then ExitLoop
		If StringInStr(FileGetAttrib($sPath & $sFile), 'D') Then
			If StringRegExp($sPath & $sFile, $sPattern) And ($iFlag = 0 Or $iFlag = 2) Then $sReturn &= $sPath & $sFile & '\' & $sDelim
			$sReturn &= _RecursiveFileListToArray($sPath & $sFile & '\', $sPattern, $iFlag, 0)
			ContinueLoop
		EndIf
		If StringRegExp($sFile, $sPattern) And ($iFlag = 0 Or $iFlag = 1) Then $sReturn &= $sPath & $sFile & $sDelim
	WEnd
	FileClose($hSearch)
	If $iFormat Then Return StringSplit(StringTrimRight($sReturn, StringLen($sDelim)), $sDelim, $iFormat)
	Return $sReturn
EndFunc   ;==>_RecursiveFileListToArray

Func _EV_Suche_Status_All($sStatus)

;~ 	Dim $aStatus[12] = ["-1","NEU","ANGENOMME","AUSGEF%C3%9CHRT","ABGESCHLOSSEN","GEAENDERT","STORNO","LEB_FREIGEGEBEN","LEB_ABGELEHNT","LEB_IN_BEARBEITUNG","LEB_AKZEPTIERT","LEB_rbu"]

	$sHTML = _send_WinhttpS_GET($aHosts[1][1], "/framework-agreement-call/index?OrderRecallSearch%5Bhead_line%5D=&OrderRecallSearch%5Bdocument_no%5D=&OrderRecallSearch%5Bincoming_date%5D=&OrderRecallSearch%5Border_date%5D=&OrderRecallSearch%5Bgeneral_agreement_id%5D=&OrderRecallSearch%5Bdocument_state%5D=" & $sStatus, "https://www.evergabe.telekom.de")
	$aAnzBelgeGesamt = StringRegExp($sHTML, '<b>([^"<]+)</b> Belegen', 3)
	If IsArray($aAnzBelgeGesamt) Then
		$aAnzBelgeGesamt[0] = StringReplace($aAnzBelgeGesamt[0], ".", "")
	EndIf
;~ 	_ArrayDisplay($aAnzBelgeGesamt)
	If IsArray($aAnzBelgeGesamt) Then
		$sHTML = _send_WinhttpS_GET($aHosts[1][1], "/framework-agreement-call/index?OrderRecallSearch%5Blimit%5D=" & $aAnzBelgeGesamt[0] & "&OrderRecallSearch%5Bdocument_state%5D=" & $sStatus, "https://www.evergabe.telekom.de/")
;~ 	ClipPut($sHTML)
;~ 	_Write_to_Console($sHTML)
;~ 	MsgBox(64,"","")
		;MsgBox(0, "Status:" & $sStatus & " Belege:" & $aAnzBelgeGesamt[0], "Status:" & $sStatus & " Belege:" & $aAnzBelgeGesamt[0])
		;Abrufliste gefhilter nach Status
		;auslesen Titel
		;array's
		$aTitel = _EV_Abrufliste_GET_Title($sHTML)
		$aSMnr = _EV_Abrufliste_GET_Bedarfnr($sHTML) ;SMnr
		$aBelegEinDatum = _EV_Abrufliste_GET_Belegeingang($sHTML) ;Eingang E-Vergabe
		$aBelegNr42 = _EV_Abrufliste_GET_Belegnr($sHTML) ;42Nr
		$aAusfuehrungsfrist = _EV_Abrufliste_GET_Ausfuehrungsfrist($sHTML) ;Ausführungsfrist
		$aDetailID = _EV_Abrufliste_GET_DetailsID($sHTML) ;DetailsID intern für E-Vergabe
		$aRV = _EV_Abrufliste_GET_RV($sHTML) ;Rahmenvertrag
		$aStatus = _EV_Abrufliste_GET_Status($sHTML) ;Status Angenommen Abgelehnt usw.
		Dim $aListe[UBound($aTitel)][8]
		For $i = 0 To UBound($aTitel) - 1
			$aListe[$i][0] = $aRV[$i]
			$aListe[$i][1] = $aSMnr[$i]
			$aListe[$i][2] = $aTitel[$i]
			$aListe[$i][3] = $aBelegNr42[$i]
			$aListe[$i][4] = $aBelegEinDatum[$i]
			$aListe[$i][5] = $aAusfuehrungsfrist[$i]
			$aListe[$i][6] = $aDetailID[$i]
			$aListe[$i][7] = $aStatus[$i]
		Next
;~ 	_ArrayDisplay($aListe)
		Return $aListe


;~ 		_ArrayDisplay($aListe)
	EndIf
EndFunc   ;==>_EV_Suche_Status_All

Func _EV_GET_LEB_Liste($sDetailsID)
	;Detailsid,LEB,Title,Status
	;15564152|0006004494| 1. TA NVT 2V1011 Tiefbau Mollenberg|AKZEPTIERT

	$sHTML = _send_WinhttpS_GET($aHosts[1][1], "/sheet/index?c=1&importId=" & $sDetailsID & "&BapiEssrSearch%5Blimit%5D=20", "https://www.evergabe.telekom.de/framework-agreement-call/details?id=" & $sDetailsID & "&c=1")
	_Write_to_Console("https://www.evergabe.telekom.de/sheet/index?c=1&importId=" & $sDetailsID & "&BapiEssrSearch%5Blimit%5D=20")
;~ 	If StringInStr($sHTML, "LERF nicht") Then
;~ 		_Write_to_Console("LERF nicht möglich Auftrag noch nicht angenommen")
;~ 		MsgBox(64, "LEB nicht angenommen", "LEB nicht angenommen")
;~ 	Else
;~
;~ 	EndIf

	$aPages = StringRegExp($sHTML, 'Blimit%5D=\d+&page=(\d+)" data-page="\d+">\d+', 3)
;~ 	_ArrayDisplay($aPages)

	If IsArray($aPages) Then
		$aBelege = StringRegExp($sHTML, '<b>(\d+)</b> Belegen', 3)
		If IsArray($aBelege) Then
			$sPage = _nNumber($aPages, 1, 1)
;~ 			_Write_to_Console($sPage)
			Dim $aArray[1]

			For $i = 1 To $sPage
				$sHTML = _send_WinhttpS_GET($aHosts[1][1], "/sheet/index?c=1&importId=" & $sDetailsID & "&page=" & $i, "https://www.evergabe.telekom.de/framework-agreement-call/details?id=" & $sDetailsID & "&c=1")
;~ 				ClipPut($sHTML)
;~ 				MsgBox(0, "/framework-agreement-call/index", $aPages[$i])
;~ 				MsgBox(64, "", $aPages[$i])
				$aSheetId = StringRegExp($sHTML, 'sheetId=([^&]+)&c=1"', 3)
				$aTitle = StringRegExp($sHTML, '<strong>([^<]+)</strong><', 3)
				$aStatus = StringRegExp($sHTML, 'leb-status[^>]+.([^<]+)', 3)
				If IsArray($aSheetId) Then
					For $ii = 0 To UBound($aSheetId) - 1
						If StringInStr($aSheetId[$ii], "Schlussaufmass") Then
							_ArrayAdd($aArray, $aSheetId[$ii] & "#" & $aTitle[$ii] & "#" & $aStatus[$ii] & "#Schlussaufm.")
						Else
							_ArrayAdd($aArray, $aSheetId[$ii] & "#" & $aTitle[$ii] & "#" & $aStatus[$ii] & "#Teilaufm.")
						EndIf
					Next
;~ 					_ArrayDelete($aArray, 0)

				EndIf

			Next
;~ 			_ArrayDelete($aArray, 0)
			Dim $aReturn[UBound($aArray)][5]
			;_ArrayDisplay($aArray)
			For $i = 1 To UBound($aReturn) - 1
				$aSplitt = StringSplit($aArray[$i], "#")
;~ 				$aReturn[$i][0] = $aArray[0]
				$aReturn[$i][0] = $sDetailsID
				$aReturn[$i][1] = $aSplitt[1]
				$aReturn[$i][2] = $aSplitt[2]
				$aReturn[$i][3] = $aSplitt[3]
				$aReturn[$i][4] = $aSplitt[4]
			Next
			;_ArrayDisplay($aReturn)
			Return $aReturn
		EndIf

	Else
		Dim $aArray[1]
		;nur eine Seite
		$sHTML = _send_WinhttpS_GET($aHosts[1][1], "/sheet/index?c=1&importId=" & $sDetailsID, "https://www.evergabe.telekom.de/framework-agreement-call/details?id=" & $sDetailsID & "&c=1")
;~ 		ClipPut($sHTML)
		;MsgBox(0, "/framework-agreement-call/index", $aPages[$i])
;~ 		MsgBox(64, "", "")
		$aSheetId = StringRegExp($sHTML, 'sheetId=([^&]+)&c=1"', 3)
		$aTitle = StringRegExp($sHTML, '<strong>([^<]+)</strong><', 3)
		$aStatus = StringRegExp($sHTML, 'leb-status[^>]+.([^<]+)', 3)
		$aSchlussAuf = StringRegExp($sHTML, '"></td><td></td><td([^<]+)', 3)
;~ 		_DebugArrayDisplay($aTitle)
		If IsArray($aSheetId) Then
			For $ii = 0 To UBound($aSheetId) - 1
				If StringInStr($aSchlussAuf[$ii], "Schlussaufmass") Then
					_ArrayAdd($aArray, $aSheetId[$ii] & "#" & $aTitle[$ii] & "#" & $aStatus[$ii] & "#Schlussaufm.")
				Else
					_ArrayAdd($aArray, $aSheetId[$ii] & "#" & $aTitle[$ii] & "#" & $aStatus[$ii] & "#Teilaufm.")
				EndIf

			Next
			_ArrayDelete($aArray, 0)

			Dim $aReturn[UBound($aArray)][5]
			;_ArrayDisplay($aArray)
			For $i = 0 To UBound($aReturn) - 1
				$aSplitt = StringSplit($aArray[$i], "#")
				$aReturn[$i][0] = $sDetailsID
				$aReturn[$i][1] = $aSplitt[1]
				$aReturn[$i][2] = $aSplitt[2]
				$aReturn[$i][3] = $aSplitt[3]
				$aReturn[$i][4] = $aSplitt[4]
			Next
;~ 			_DebugArrayDisplay($aReturn)
			Return $aReturn
		EndIf

	EndIf
	;'sheetId=([^&]+)&c=1" title="([^"]+)' SheetID und Titel
	;'leb-status[^>]+.([^<]+)' Status

	;https://www.evergabe.telekom.de/sheet/index?c=1&importId=15564152
	;https://www.evergabe.telekom.de/sheet/index?c=1&importId=15564152&page=2
	;https://www.evergabe.telekom.de/sheet/index?c=1&importId=15564152&page=1
	;/sheet/index?c=1&importId=15564152&BapiEssrSearch%5Blimit%5D=10

EndFunc   ;==>_EV_GET_LEB_Liste

Func _EV_GET_Aufma_positionen($sLEB_NR)
	$sHTML = _send_WinhttpS_GET($aHosts[1][1], "/sheet-position/index?c=1&sheetId=" & $sLEB_NR, "https://www.evergabe.telekom.de/sheet/header?class=list-item&sheetId=" & $sLEB_NR & "&c=1")
;~ 	ClipPut($sHTML)
;~ 	_Write_to_Console($sHTML)
;~ 	MsgBox(0, "/sheet-position/index?c=1&sheetId=" & $sLEB_NR, "/sheet-position/index?c=1&sheetId=" & $sLEB_NR)
;~
	$iPages = _EV_LEP_POs_MaxPages($sHTML)
;~ 	MsgBox(64, "", $iPages)
	Dim $aAufM[1]
	For $i = 1 To $iPages
		$sHTML = _send_WinhttpS_GET($aHosts[1][1], "/sheet-position/index?c=1&sheetId=" & $sLEB_NR & "&page=" & $i, "https://www.evergabe.telekom.de/sheet/header?class=list-item&sheetId=" & $sLEB_NR & "&c=1")
;~ 		ClipPut($sHTML)
;~ 		MsgBox(0, $sLEB_NR, "")
		$aShowlinks = StringRegExp($sHTML, '(/sheet-position[^c]+c=1)">00', 3)
;~ 			_ArrayDisplay($aShowlinks)
		If IsArray($aShowlinks) Then
			For $ii = 0 To UBound($aShowlinks) - 1
				$sHTML = _send_WinhttpS_GET($aHosts[1][1], $aShowlinks[$ii], "https://www.evergabe.telekom.de/sheet/header?class=list-item&sheetId=" & $sLEB_NR & "&c=1")
;~ 				_Write_to_Console("https://www.evergabe.telekom.de/sheet/header?class=list-item&sheetId=" & $sLEB_NR & "&c=1")
				;ClipPut($sHTML)
;~ 				If $sLEB_NR = "0007615468" then
;~ 				ConsoleWrite($sHTML & @CRLF)
;~ 				MsgBox(0, $sLEB_NR, "asdf")
;~ 				EndIf
				$aPosNr = StringRegExp($sHTML, 'Position 0([^:]+)', 3)
				$aPosKurztext = StringRegExp($sHTML, 'Position 0[^:]+:.([^<]+)', 3)
				$aPosAbschnitt = StringRegExp($sHTML, 'sectionText]" value="([^"]+)', 3)
				$aPosMenge = StringRegExp($sHTML, 'quantity]" value="([^"]+)', 3)
				$aPosEinheit = StringRegExp($sHTML, 'unitOfQuantity]" value="([^"]+)', 3)
				$aBegrund = StringRegExp($sHTML, 'longText]" disabled>([^<]+)', 3)
				$aFaktor = StringRegExp($sHTML, 'Multiplier]" value="([^"]+)', 3)
				$aLeange = StringRegExp($sHTML, 'formulaValueLength]" value="([^"]+)', 3)
				$aBreite = StringRegExp($sHTML, 'formulaValueWidth]" value="([^"]+)', 3)
				$aTiefe = StringRegExp($sHTML, 'formulaValueDepth]" value="([^"]+)', 3)
				If IsArray($aPosNr) Then
					$sPosNr = $aPosNr[0]
				Else
					$sPosNr = ""
				EndIf
				If IsArray($aPosKurztext) Then
					$sPosKurztext = $aPosKurztext[0]
				Else
					$sPosKurztext = ""
				EndIf
				If IsArray($aPosAbschnitt) Then
					$sPosAbschnitt = $aPosAbschnitt[0]
				Else
					$sPosAbschnitt = ""
				EndIf
				If IsArray($aPosMenge) Then
					$sPosMenge = $aPosMenge[0]
				Else
					$sPosMenge = ""
				EndIf
				If IsArray($aPosEinheit) Then
					$sPosEinheit = $aPosEinheit[0]
				Else
					$sPosEinheit = ""
				EndIf
				If IsArray($aBegrund) Then
					$sBegrund = $aBegrund[0]
				Else
					$sBegrund = ""
				EndIf
				If IsArray($aFaktor) Then
					If $aFaktor[0] = "1" Then
						$sFaktor = "1,0"
					EndIf
					$sFaktor = $aFaktor[0]
				Else
					$sFaktor = "1,0"
				EndIf
				If IsArray($aLeange) Then
					$sLeange = $aLeange[0]
				Else
					$sLeange = ""
				EndIf
				If IsArray($aBreite) Then
					$sBreite = $aBreite[0]
				Else
					$sBreite = ""
				EndIf
				If IsArray($aTiefe) Then
					$sTiefe = $aTiefe[0]
				Else
					$sTiefe = ""
				EndIf
				If IsArray($aPosEinheit) Then

					Select
						Case $aPosEinheit[0] = "ST"
							$sFaktor = "1,0"
							$sLeange = ""
							$sBreite = ""
							$sTiefe = ""
						Case $aPosEinheit[0] = "LE"
							$sFaktor = "1,0"
							$sLeange = ""
							$sBreite = ""
							$sTiefe = ""
						Case $aPosEinheit[0] = "STD"
							$sFaktor = "1,0"
							$sLeange = ""
							$sBreite = ""
							$sTiefe = ""
						Case $aPosEinheit[0] = "M"
							$sBreite = ""
							$sTiefe = ""
							$sPosMenge = $sLeange
						Case $aPosEinheit[0] = "M2"
;~ 							$sLeange = ""
;~ 							$sBreite = ""
							$sPosMenge = $sLeange * $sBreite
						Case $aPosEinheit[0] = "M3"

							$sPosMenge = $sLeange * $sBreite * $sTiefe
					EndSelect
					_ArrayAdd($aAufM, $sPosAbschnitt & "#" & $sPosNr & "#" & $sFaktor & "#" & $sLeange & "#" & $sBreite & "#" & $sTiefe & "#" & $sPosMenge & "#" & $sPosEinheit & "#" & $sPosKurztext & "#" & $sBegrund & "#" & $sPosMenge)
;~ 						;_ArrayDisplay($aAufM)
				EndIf
			Next
		EndIf
	Next
	_ArrayDelete($aAufM, 0)
	Dim $aReturn[UBound($aAufM)][13]
	;_ArrayDisplay($aReturn)
	For $i = 0 To UBound($aAufM) - 1
		$aSplitt = StringSplit($aAufM[$i], "#")
		;_ArrayDisplay($aSplitt)
		$aReturn[$i][0] = $aSplitt[1]
		$aReturn[$i][1] = $aSplitt[2]
;~ 		if $aSplitt[3] = "1" Then
;~ 			$aReturn[$i][2] = StringReplace($aSplitt[3],"1","1.0")
;~ 		Else
;~ 			$aReturn[$i][2] = $aSplitt[3]
;~ 		EndIf
		$aReturn[$i][2] = $aSplitt[3]
		$aReturn[$i][3] = $aSplitt[4]
		$aReturn[$i][4] = $aSplitt[5]
		$aReturn[$i][5] = $aSplitt[6]
		$aReturn[$i][6] = $aSplitt[7]
		$aReturn[$i][7] = $aSplitt[8]
		$aReturn[$i][8] = $aSplitt[9]
		$aReturn[$i][9] = $aSplitt[10]
		$aReturn[$i][10] = $aSplitt[11]
	Next
;~ 	_ArrayDisplay($aReturn)
;~ 	MsgBox(64, "Array ohne Preise", "")
	$aArray = _EV_GET_Aufma_preise_to_Array($aReturn, $sLEB_NR)
	Return $aArray
;~ 	_ArrayDisplay($aArray)
EndFunc   ;==>_EV_GET_Aufma_positionen

Func _EV_GET_DDL_Anlagen($sLEB_NR)
	$sHTML = _send_WinhttpS_GET($aHosts[1][1], "/sheet/header?class=list-item&sheetId=" & $sLEB_NR & "&c=1", "https://www.evergabe.telekom.de//sheet/header?class=list-item&sheetId=" & $sLEB_NR)
;~ 	ClipPut($sHTML)
;~ 	_Write_to_Console($sHTML)
	$aAnlagenLink = StringRegExp($sHTML, '/file/sheet-attachment.c=1&f=([^"]+).*noopener">[^<]+', 3)
	$aAnlagenName = StringRegExp($sHTML, '/file/sheet-attachment.c=1&f=[^"]+.*noopener">([^<]+)', 3)
	If IsArray($aAnlagenLink) And IsArray($aAnlagenName) Then
;~ 		_DebugArrayDisplay($aAnlagenLink)
;~ 		_DebugArrayDisplay($aAnlagenName)
		For $i = 0 To UBound($aAnlagenName) - 1
;~ 				GET https://evergabe.telekom.de/file/sheet-attachment?c=1&f=959442&d=1 HTTP/1.1
;~ 	Host: evergabe.telekom.de
;~ 	Connection: keep-alive
;~ 	sec-ch-ua: "Google Chrome";v="93", " Not;A Brand";v="99", "Chromium";v="93"
;~ 	sec-ch-ua-mobile: ?0
;~ 	sec-ch-ua-platform: "Windows"
;~ 	Upgrade-Insecure-Requests: 1
;~ 	User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36
;~ 	Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
;~ 	Sec-Fetch-Site: same-origin
;~ 	Sec-Fetch-Mode: navigate
;~ 	Sec-Fetch-User: ?1
;~ 	Sec-Fetch-Dest: document
;~ 	Referer: https://evergabe.telekom.de/sheet/header?class=list-item&sheetId=0008109632&c=1
;~ 	Accept-Encoding: gzip, deflate, br
;~ 	Accept-Language: de-DE,de;q=0.9,en-US;q=0.8,en;q=0.7
;~ 	Cookie: EV_PHPSESSID=4bueubpp0uq243jrl3t758jeg2; OrderRecallSearch_document_state=2f1c8f1a05294aedf4773cc828350b57006b57c226c8f85e72c6a5bc03df96b41e09679df61d8df630b15de3c140b242431390f39d12f7320640529e1353df3aa%3A2%3A%7Bi%3A0%3Bs%3A32%3A%22OrderRecallSearch_document_state%22%3Bi%3A1%3Bs%3A2%3A%22-1%22%3B%7D; OrderRecallSearch_limit=36f3f250aeea8650ac33f0b2ce57b9d0402b2a65895c3076155dd06873766558e6b3d07e5edfaaed5e983755984ce650d8993f3654e4c72ef289bce2c46d5b25a%3A2%3A%7Bi%3A0%3Bs%3A23%3A%22OrderRecallSearch_limit%22%3Bi%3A1%3BN%3B%7D; OrderRecallSearch_sort=62c784b485fedb7853c73aabc8393c7cf27704bbdce8ff65ce6337d62767070743b3e9a40cca5c849e75731c25f83fb8f48ba19b1769345a0b23fa5db6980fb9a%3A2%3A%7Bi%3A0%3Bs%3A22%3A%22OrderRecallSearch_sort%22%3Bi%3A1%3BN%3B%7D; BapiEssrSearch_vs__status=8a6c38c3f9ec0826db7ededb735d5c40fd54e12ae2dc4a2bc305b41be76c78aebd938919171091b8ab529e8f554dd05cc81c45c10ce4ed768be127ff7520a342a%3A2%3A%7Bi%3A0%3Bs%3A25%3A%22BapiEssrSearch_vs__status%22%3Bi%3A1%3Bs%3A2%3A%22-1%22%3B%7D; AWSALB=pYKgYgH+EpnkLkUkn4dF+OFGl+7LX7yNa8YmFlcwzm4ONirC+CJfssftOFqNmmUe5n8Pq6uURHzLq6CWRxwNlc6uzvo5eoiFMDdX10LS7zAQ/fymaGWxAvDkxan3; AWSALBCORS=pYKgYgH+EpnkLkUkn4dF+OFGl+7LX7yNa8YmFlcwzm4ONirC+CJfssftOFqNmmUe5n8Pq6uURHzLq6CWRxwNlc6uzvo5eoiFMDdX10LS7zAQ/fymaGWxAvDkxan3
			$aHTML = _WinHttpSimpleSSLRequest($aHosts[1][1], "GET", "file/sheet-attachment?c=1&f=" & $aAnlagenLink[$i] & "&c=1", "https://evergabe.telekom.de/sheet/header?class=list-item&sheetId=" & $sLEB_NR & "&c=1", Default, $sHeader, False, 2)
			_Write_to_Console("File Download: | " & $GsBasePfad & $GsSMNr & "\Anlagen\" & $aAnlagenName[$i] & ".pdf")
			$hBild = FileOpen($GsBasePfad & $GsSMNr & "\Anlagen\" & $sLEB_NR & "\" & $aAnlagenName[$i] & ".pdf", 10)
			FileWrite($hBild, $aHTML)
			FileClose($hBild)


		Next
	EndIf
;~ 	MsgBox(0, "/sheet-position/index?c=1&sheetId=" & $sLEB_NR, "/sheet-position/index?c=1&sheetId=" & $sLEB_NR)
;~
EndFunc   ;==>_EV_GET_DDL_Anlagen

Func _EVAufmLV_Export_Exel($aArray, $sDateiname)
	$aDN = StringRegExp($sDateiname, "([^_]+)", 3)

	$sLEBNr = $aDN[0]
	$sTitle = $aDN[1]
	$sStatus = $aDN[2]
;~ 	LEB_vorlage.xlsx$sLEBNr

	FileCopy(@ScriptDir & "\..\daten\LEB_vorlage.xlsx", $GsBasePfad & "\LEB_vorlage.xlsx", $FC_OVERWRITE + $FC_CREATEPATH)
	$sPfadExcel = $GsBasePfad & "\LEB_vorlage.xlsx"
	Local $oExcel = _Excel_Open(False)
	If @error Then Exit MsgBox($MB_SYSTEMMODAL, "Excel UDF: _Excel_RangeRead Example", "Error creating the Excel application object." & @CRLF & "@error = " & @error & ", @extended = " & @extended)
	Local $oWorkbook = _Excel_BookOpen($oExcel, $sPfadExcel)
	If @error Then
		MsgBox($MB_SYSTEMMODAL, "Excel UDF: _Excel_RangeRead Example", "Error opening workbook '" & $sPfadExcel & @CRLF & "@error = " & @error & ", @extended = " & @extended)
		_Excel_Close($oExcel)
;~ 		Exit
	EndIf
;~ 	Local $aArray = _Listview2Array($frm_lv_evaufm)
;~ 	_ArrayDisplay($aArray)
	_Excel_RangeWrite($oWorkbook, $oWorkbook.Activesheet, $aArray, "B3")
	$iLastZeile = $oWorkbook.ActiveSheet.UsedRange.SpecialCells($xlCellTypeLastCell).Row

	With $oWorkbook.ActiveSheet.Range("A3:N" & $iLastZeile).Borders
		.LineStyle = 1
		.TintAndShade = 0
	EndWith

	_Excel_RangeWrite($oWorkbook, $oWorkbook.Activesheet, "=SUMME(N3:N" & $iLastZeile & ")", "N1")

	; Zeilen Nummer hinzufügen in 10 schritten
	_Excel_RangeWrite($oWorkbook, $oWorkbook.Activesheet, "10", "A3")
	_Excel_RangeWrite($oWorkbook, $oWorkbook.Activesheet, "20", "A4")



	If UBound($aArray) <= 1 Then
		$iStart = 3
;~ 			_Excel_RangeWrite($oWorkbook, $oWorkbook.Activesheet, "=SUMME(A" & $iStart+$i & ")+10", "A" & $iStart + $i+1)
		$sZNr = "=SUMME(A" & $iStart + 2 & ")+10"

		_Excel_RangeWrite($oWorkbook, $oWorkbook.Activesheet, $sZNr, "A5")
	Else
;~ 		MsgBox(64, UBound($aArray) - 2,  UBound($aArray))
		Dim $aZNr[UBound($aArray) - 2]
		$iStart = 3
		For $i = 0 To UBound($aArray) - 3
;~ 			_Excel_RangeWrite($oWorkbook, $oWorkbook.Activesheet, "=SUMME(A" & $iStart+$i & ")+10", "A" & $iStart + $i+1)
			$aZNr[$i] = "=SUMME(A" & $iStart + $i + 1 & ")+10"
		Next
;~ 		_ArrayDisplay($aZNr)
		_Excel_RangeWrite($oWorkbook, $oWorkbook.Activesheet, $aZNr, "A5")
	EndIf


;~ 	$sLEBNrREad =



	_Excel_RangeWrite($oWorkbook, $oWorkbook.Activesheet, $sLEBNr, "C1")
	_Excel_RangeWrite($oWorkbook, $oWorkbook.Activesheet, $sTitle & " => " & $sStatus, "J1")

	$oWorkbook.ActiveSheet.Columns.AutoFit

;~ 	$sDateiname = $sLEBNrREad


	_Excel_BookSaveAs($oWorkbook, $GsBasePfad & $GsSMNr & "\" & $sDateiname & ".xlsx", Default, True)
	_Excel_Close($oExcel, True, True)
;~
;~ 	Local $aWorkSheets = _Excel_SheetList($oWorkbook)
;~ 	_DebugArrayDisplay($aWorkSheets)
	FileDelete($sPfadExcel)
EndFunc   ;==>_EVAufmLV_Export_Exel

Func _EVAufmLV_Export_txt($aArray, $sDateiname)

	$hFileOpen = FileOpen($GsBasePfad & $GsSMNr & "\" & $sDateiname & ".txt", 10)
	FileWriteLine($hFileOpen, "[Aufmaßdaten]")
	_FileWriteFromArray($hFileOpen, $aArray)
	FileClose($hFileOpen)
EndFunc   ;==>_EVAufmLV_Export_txt

;Hilffunktions für Preise beim Array
Func _EV_GET_Aufma_preise_to_Array($aArray, $sLEB_NR)
	Global $aVertrag_Preis
	;https://www.evergabe.telekom.de/sheet/header?c=1&sheetId=0006119386
	$sHTML = _send_WinhttpS_GET($aHosts[1][1], "/sheet/header?c=1&sheetId=" & $sLEB_NR, "https://www.evergabe.telekom.de/sheet/header?class=list-item&sheetId=" & $sLEB_NR & "&c=1")
	;ClipPut($sHTML)
	;MsgBox(0, $sLEB_NR, "asdf")
	$aDetailID = StringRegExp($sHTML, 'details\?id=([^&]+)', 3)
	If IsArray($aDetailID) Then
		;https://www.evergabe.telekom.de/framework-agreement-call/details?id=15562026&c=1
		$sHTML = _send_WinhttpS_GET($aHosts[1][1], "/framework-agreement-call/details?id=" & $aDetailID[0] & "&c=1", "https://www.evergabe.telekom.de/sheet/header?class=list-item&sheetId=" & $sLEB_NR & "&c=1")
;~ 		ClipPut($sHTML)
;~ 		MsgBox(0, $sLEB_NR, "asdf")
		$aRVertrag = StringRegExp($sHTML, 'c=1">(\d+)/00010', 3)
		If IsArray($aRVertrag) Then

			$sFilePath = @ScriptDir & "\..\daten\LV\" & $aRVertrag[0] & ".txt"
			_FileReadToArray($sFilePath, $aVertrag_Preis)
			_ArrayDelete($aVertrag_Preis, 0)
			;_ArrayDisplay($aVertrag_Preis)
;~ 			_ArrayDisplay($aArray)
			For $ii = 0 To UBound($aArray) - 1
				For $i = 0 To UBound($aVertrag_Preis) - 1
					$aSplitt = StringSplit($aVertrag_Preis[$i], "|")
					;_ArrayDisplay($aSplitt)
					If $aSplitt[1] = $aArray[$ii][1] Then
						$aArray[$ii][11] = _replaceKom2Punkt($aSplitt[4])
						$aArray[$ii][10] = _replaceKom2Punkt($aArray[$ii][2]) * _replaceKom2Punkt($aArray[$ii][6])
						$aArray[$ii][12] = _replaceKom2Punkt($aSplitt[4]) * _replaceKom2Punkt($aArray[$ii][10])
					EndIf
				Next
			Next
		EndIf
	EndIf

	For $i = 0 To UBound($aArray) - 1
		If $aArray[$i][2] = 1 Then
			$aArray[$i][2] = 1.0
		EndIf

		$aArray[$i][2] = _replacePunkt2Koma($aArray[$i][2])
		$aArray[$i][3] = _replacePunkt2Koma($aArray[$i][3])
		$aArray[$i][4] = _replacePunkt2Koma($aArray[$i][4])
		$aArray[$i][5] = _replacePunkt2Koma($aArray[$i][5])
		$aArray[$i][6] = _replacePunkt2Koma($aArray[$i][6])
		$aArray[$i][10] = _replacePunkt2Koma($aArray[$i][10])
		$aArray[$i][11] = _replacePunkt2Koma($aArray[$i][11])
		$aArray[$i][12] = _replacePunkt2Koma($aArray[$i][12])
	Next
;~ 	_ArrayDisplay($aArray)
	Return $aArray
EndFunc   ;==>_EV_GET_Aufma_preise_to_Array

;SM Suchen mit 2 oder 3 Abrufen 206069376 => 3 Stück
Func _EV_Search_SM($sSMnr)
	;suche Aufmaß nach SMnr:
	$sHTML = _send_WinhttpS_GET($aHosts[1][1], "/framework-agreement-call?OrderRecallSearch%5Bhead_line%5D=" & $sSMnr & "&OrderRecallSearch%5Bdocument_no%5D=&OrderRecallSearch%5Bincoming_date%5D=&OrderRecallSearch%5Border_date%5D=&OrderRecallSearch%5Bgeneral_agreement_id%5D=&OrderRecallSearch%5Bdocument_state%5D=-1", "https://www.evergabe.telekom.de/framework-agreement-call")
	_Write_to_Console("Suche SM-Nr: | " & $sSMnr)
;~
;~ 		ClipPut($sHTML)
;~ 	_Write_to_Console($sHTML)
;~ 	MsgBox(64,"","")
	$aTitle = _EV_Abrufliste_GET_Title($sHTML)
	$aBedarfnr = _EV_Abrufliste_GET_Bedarfnr($sHTML) ;SMnr
	$aBelegEinDatum = _EV_Abrufliste_GET_Belegeingang($sHTML) ;Eingang E-Vergabe
	$aBelegnr = _EV_Abrufliste_GET_Belegnr($sHTML) ;42Nr
	$aAusfuehrungsfrist = _EV_Abrufliste_GET_Ausfuehrungsfrist($sHTML) ;Ausführungsfrist
	$aDetailID = _EV_Abrufliste_GET_DetailsID($sHTML) ;DetailsID intern für E-Vergabe
	$aRV = _EV_Abrufliste_GET_RV($sHTML) ;Rahmenvertrag
	$aStatus = _EV_Abrufliste_GET_Status($sHTML) ;Status Angenommen Abgelehnt usw.
	Dim $aReturn[UBound($aTitle)][9]
;~ 	_DebugArrayDisplay($aReturn)

	For $i = 0 To UBound($aTitle) - 1
		$aReturn[$i][0] = $aTitle[$i]
		$aReturn[$i][1] = $aBedarfnr[$i]
		$aReturn[$i][2] = $aBelegnr[$i]
		$aReturn[$i][3] = $aDetailID[$i]
		$aReturn[$i][4] = _EV_DDL_P83_GET_Bez($aDetailID[$i]) ; Bezeichnung auslesen
;~ 		$aReturn[$i][4] = $aRV[$i]
		$aReturn[$i][5] = $aRV[$i]
		$aReturn[$i][6] = $aBelegEinDatum[$i]
		$aReturn[$i][7] = $aAusfuehrungsfrist[$i]
		$aReturn[$i][8] = $aStatus[$i]

	Next
;~ 	_DebugArrayDisplay($aReturn)
	Return $aReturn
EndFunc   ;==>_EV_Search_SM

Func _EV_GET_PlanungsSumme($sDetailID)

	$sVertrag_temp = $aAMasterListe[0]
	$sSMNR_temp = $aAMasterListe[1]
	$sTitleEV_temp = $aAMasterListe[2]
	$s42erNr_temp = $aAMasterListe[3]
	$sDetailsIDEv_temp = $aAMasterListe[4]


	;https://www.evergabe.telekom.de/framework-agreement-call/details?id=18332809&c=1
	$sHTML = _send_WinhttpS_GET($aHosts[1][1], "/framework-agreement-call/details?id=" & $sDetailID & "&c=1", "https://www.evergabe.telekom.de/framework-agreement-call")
	$aHTML = _WinHttpSimpleSSLRequest($aHosts[1][1], "GET", "/file/service-positions?c=1&iid=" & $sDetailID & "&s=1&d=1", "https://www.evergabe.telekom.de/framework-agreement-call", Default, $sHeader, False, 2)
	_Write_to_Console("File Download: | " & "LV_" & $sDetailID & "_SM_" & $sSMNR_temp & ".pdf")
	$hBild = FileOpen($GsBasePfad & $GsSMNr & "\" & "LV_" & $sDetailID & "_SM_" & $sSMNR_temp & ".pdf", 10)
	FileWrite($hBild, $aHTML)
	FileClose($hBild)

	_Write_to_Console("PDF-File convert to TXT-File ")
	_XPDF_ToText($GsBasePfad & $GsSMNr & "\" & "LV_" & $sDetailID & "_SM_" & $sSMNR_temp & ".pdf",$GsBasePfad & $GsSMNr & "\" & "LV_" & $sDetailID & "_SM_" & $sSMNR_temp & ".txt")
	Local $sFileRead = FileRead($GsBasePfad & $GsSMNr & "\" & "LV_" & $sDetailID & "_SM_" & $sSMNR_temp & ".txt")
	$aSumme =  StringRegExp($sFileRead, 'Gesamtsumme in EUR.(\d+.\d+)', 3)
	if IsArray($aSumme) Then
		Return $aSumme[0]
	Else
		Return "NA"
	EndIf

EndFunc

Func _EV_DDL_P83_GET_Bez($sDetailID)
	;https://www.evergabe.telekom.de/framework-agreement-call/details?id=17005356&c=1
	;https://www.evergabe.telekom.de/file/gaeb-83?c=1&iid=17005356&f=p2000 ;P83 download link
	$sVertrag_temp = $aAMasterListe[0]
	$sSMNR_temp = $aAMasterListe[1]
	$sTitleEV_temp = $aAMasterListe[2]
	$s42erNr_temp = $aAMasterListe[3]
	$sDetailsIDEv_temp = $aAMasterListe[4]

	$sHTML = _send_WinhttpS_GET($aHosts[1][1], "/framework-agreement-call/details?id=" & $sDetailID & "&c=1", "https://www.evergabe.telekom.de/framework-agreement-call")
	$aHTML = _WinHttpSimpleSSLRequest($aHosts[1][1], "GET", "/file/gaeb-83?c=1&iid=" & $sDetailID & "&f=p2000", "https://www.evergabe.telekom.de/framework-agreement-call", Default, $sHeader, False, 2)
	_Write_to_Console("File Download: | " & "LV_" & $sDetailID & "_SM_" & $GsSMNr & ".p83")
	$hBild = FileOpen($GsBasePfad & $GsSMNr & "\" & "LV_" & $sDetailID & "_SM_" & $sSMNR_temp & ".p83", 10)
	FileWrite($hBild, $aHTML)
	FileClose($hBild)
;~ 	$aHTML = FileRead(@ScriptDir & "\..\test_" & $sDetailID & ".p83")
	$sFilePath = $GsBasePfad & $GsSMNr & "\" & "LV_" & $sDetailID & "_SM_" & $sSMNR_temp & ".p83"
	Local $hFileOpen = FileOpen($sFilePath, 1)
	If $hFileOpen = -1 Then
		MsgBox($MB_SYSTEMMODAL, "", "An error occurred when reading the file.")
		Return False
	EndIf

	; Read the contents of the file using the handle returned by FileOpen.
	Local $sFileRead = FileRead($hFileOpen)

	; Close the handle returned by FileOpen.
	FileClose($hFileOpen)
	$aBez = StringRegExp($sFileRead, '\[Bez]([^\[]+)', 3)
	If IsArray($aBez) Then
		FileDelete($sFilePath)
		Return $aBez[0]
	Else
		Return "NA"
	EndIf

EndFunc   ;==>_EV_DDL_P83_GET_Bez

Func _EV_DDL_LV_Planung($sDetailID)
	$sVertrag_temp = $aAMasterListe[0]
	$sSMNR_temp = $aAMasterListe[1]
	$sTitleEV_temp = $aAMasterListe[2]
	$s42erNr_temp = $aAMasterListe[3]
	$sDetailsIDEv_temp = $aAMasterListe[4]
	;test
	;https://www.evergabe.telekom.de/gaeb-viewer/index?c=1&id=3239890

	;https://www.evergabe.telekom.de/file/service-positions?c=1&iid=17542106&s=1&d=1
	$sHTML = _send_WinhttpS_GET($aHosts[1][1], "/framework-agreement-call/details?id=" & $sDetailID & "&c=1", "https://www.evergabe.telekom.de/framework-agreement-call")
	$aHTML = _WinHttpSimpleSSLRequest($aHosts[1][1], "GET", "/file/service-positions?c=1&iid=" & $sDetailID & "&s=1&d=1", "https://www.evergabe.telekom.de/framework-agreement-call", Default, $sHeader, False, 2)
	_Write_to_Console("File Download: | " & "PlanungsLV_Kurz_" & $sDetailID & "_SM_" & $GsSMNr & ".pdf")
	$hBild = FileOpen($GsBasePfad & $GsSMNr & "\" & "PlanungsLV_Kurz_" & $sDetailID & "_SM_" & $sSMNR_temp & ".pdf", 10)
	FileWrite($hBild, $aHTML)
	FileClose($hBild)
;~ 	$aHTML = FileRead(@ScriptDir & "\..\test_" & $sDetailID & ".p83")
;~ 	$sFilePath = $GsBasePfad & $GsSMNr & "\" & "PlanungsLV_Kurz_" & $sDetailID & "_SM_" & $sSMNR_temp & ".pdf"
;~ 	Local $hFileOpen = FileOpen($sFilePath, 1)
;~ 	If $hFileOpen = -1 Then
;~ 		MsgBox($MB_SYSTEMMODAL, "", "An error occurred when reading the file.")
;~ 		Return False
;~ 	EndIf

;~ 	; Read the contents of the file using the handle returned by FileOpen.
;~ 	Local $sFileRead = FileRead($hFileOpen)
EndFunc   ;==>_EV_DDL_LV_Planung

Func _EV_LEP_POs_MaxPages($sQuellcode)
	Local $aMaxPages = StringRegExp($sQuellcode, '(\d+)</b> Belegen', 3)
;~ 	_DebugArrayDisplay($aMaxPages)
	If IsArray($aMaxPages) Then
		$iMaxPages = Round(Int($aMaxPages[0]) / 20, 1)
;~ 		ConsoleWrite($iMaxPages & @CRLF)
		If StringInStr($iMaxPages, ".") Then
			$sSplit = StringSplit($iMaxPages, ".")
;~ 			_DebugArrayDisplay($sSplit)
			$iSplit = StringLeft($sSplit[2], 1)
			If $iSplit <= 5 Then
				$iMaxPages = Round(Int($aMaxPages[0]) / 20) + 1
			Else
				$iMaxPages = Round(Int($aMaxPages[0]) / 20)
			EndIf
		EndIf
		Return $iMaxPages
	Else
		Return "1"
	EndIf

EndFunc   ;==>_EV_LEP_POs_MaxPages

Func _EV_Abrufliste_GET_Title($sQuellcode)
	;Rückgabe Array sonst $error string
;~ 	local $aTitle = StringRegExp($sQuellcode, 'no-wrap" title="([^"]+)', 3)
	Local $aTitle = StringRegExp($sQuellcode, '(?m)no-wrap" title="([^"]+)', 3)
;~ 	_DebugArrayDisplay($aTitle)
	If IsArray($aTitle) Then
		For $i = 0 To UBound($aTitle) - 1
			$aTitle[$i] = StringReplace($aTitle[$i], "SM Auftragsnummer: 000", " SM ")
			$aTitle[$i] = StringReplace($aTitle[$i], @CR, " ") ;CR out
			$aTitle[$i] = StringReplace($aTitle[$i], @LF, " ") ;LF out
		Next
		Return $aTitle
	Else
		Return "Error"
	EndIf
EndFunc   ;==>_EV_Abrufliste_GET_Title

Func _EV_Abrufliste_GET_Bedarfnr($sQuellcode)
	;SMNr
	;Rückgabe Array sonst $error string
	Local $aBedarfnr = StringRegExp($sQuellcode, 'Bedarfsnr.: 0([^<]+)</td>', 3)
	If IsArray($aBedarfnr) Then
		Return $aBedarfnr
	Else
		Return "Error"
	EndIf
EndFunc   ;==>_EV_Abrufliste_GET_Bedarfnr

Func _EV_Abrufliste_GET_Belegeingang($sQuellcode)
	;42Nr
	;Rückgabe Array sonst $error string
	Local $aBelegeingang = StringRegExp($sQuellcode, 'Bedarfsnr.: [^<]+</td><td>[^<]+</td><td>([^<]+)', 3)
	If IsArray($aBelegeingang) Then
		Return $aBelegeingang
	Else
		Return "Error"
	EndIf
EndFunc   ;==>_EV_Abrufliste_GET_Belegeingang

Func _EV_Abrufliste_GET_Belegnr($sQuellcode)
	;42Nr
	;Rückgabe Array sonst $error string
	Local $aBelegnr = StringRegExp($sQuellcode, 'Bedarfsnr.: [^<]+</td><td>([^/]+)', 3)
	If IsArray($aBelegnr) Then
		Return $aBelegnr
	Else
		Return "Error"
	EndIf
EndFunc   ;==>_EV_Abrufliste_GET_Belegnr

Func _EV_Abrufliste_GET_Ausfuehrungsfrist($sQuellcode)
	;Ausführungsfrist
	;Rückgabe Array sonst $error string
	Local $aAusfuehrungsfrist = StringRegExp($sQuellcode, '(\d\d\.\d\d\.\d\d\d\d)</td><td><a href', 3)
	If IsArray($aAusfuehrungsfrist) Then
		Return $aAusfuehrungsfrist
	Else
		Return "Error"
	EndIf
EndFunc   ;==>_EV_Abrufliste_GET_Ausfuehrungsfrist

Func _EV_Abrufliste_GET_DetailsID($sQuellcode)
	;DetailsID intern für E-Vergabe
	;Rückgabe Array sonst $error string
	Local $aDetailsID = StringRegExp($sQuellcode, 'call/details.id=([^&]+)&c=1', 3)
	If IsArray($aDetailsID) Then
		Return $aDetailsID
	Else
		Return "Error"
	EndIf
EndFunc   ;==>_EV_Abrufliste_GET_DetailsID

Func _EV_Abrufliste_GET_RV($sQuellcode)
	;Rahmenvertrag
	;Rückgabe Array sonst $error string
	Local $aRV = StringRegExp($sQuellcode, '/framework-agreement/details.id=[^"]+">([^/]+)', 3)
	If IsArray($aRV) Then
		Return $aRV
	Else
		Return "Error"
	EndIf
EndFunc   ;==>_EV_Abrufliste_GET_RV

Func _EV_Abrufliste_GET_Status($sQuellcode)
	;Stauts
	;Rückgabe Array sonst $error string
	Local $aStatus = StringRegExp($sQuellcode, '/framework-agreement/details.id=[^"]+">[^"]+"[^>]+>([^<]+)', 3)
	If IsArray($aStatus) Then
		Return $aStatus
	Else
		Return "Error"
	EndIf
EndFunc   ;==>_EV_Abrufliste_GET_Status

Func _send_Winhttp_POST($sHost, $sLink, $sReferer, $sPostContend)
	$aHTML = _WinHttpSimpleRequest($sHost, "POST", $sLink, $sReferer, $sPostContend, $sHeader, True, 1)
	_Write_to_Console("laden| " & $aHosts[1][0] & $sLink)
	If IsArray($aHTML) Then
		$aHTML[1] = StringReplace($aHTML[1], "amp;", "")
;~ 		$aHTML[1] = BinaryToString($aHTML[1], 4)
;~ 		_ArrayDisplay($aHTML)
		Return $aHTML[1]
	Else
		$aHTML = _WinHttpSimpleRequest($sHost, "POST", $sLink, $sReferer, $sPostContend)
		$aHTML = StringReplace($aHTML, "amp;", "")
;~ 		$aHTML = BinaryToString($aHTML, 4)
		Return $aHTML
	EndIf
EndFunc   ;==>_send_Winhttp_POST

Func _send_Winhttp_GET($sHost, $sLink, $sReferer)
	Local $sHeader = "Content-Type: application/x-www-form-urlencoded"
	$aHTML = _WinHttpSimpleRequest($sHost, "GET", $sLink, $sReferer, Default, $sHeader, True, 1)
	_Write_to_Console("laden | " & $aHosts[1][0] & $sLink)
	If IsArray($aHTML) Then
		$aHTML[1] = StringReplace($aHTML[1], "amp;", "")
		$aHTML[1] = BinaryToString($aHTML[1], 4)

		Return $aHTML[1]
	Else
		$aHTML = _WinHttpSimpleRequest($sHost, "GET", $sLink, $sReferer)
		$aHTML = StringReplace($aHTML, "amp;", "")
		$aHTML = BinaryToString($aHTML, 4)
		Return $aHTML
	EndIf
EndFunc   ;==>_send_Winhttp_GET

Func _send_WinhttpS_GET($sHost, $sLink, $sReferer)
;~ 	Local $sHeader = "Content-Type: application/x-www-form-urlencoded" & @CRLF & $sHeader_lovoo
	$aHTML = _WinHttpSimpleSSLRequest($sHost, "GET", $sLink, $sReferer, Default, $sHeader, True, 1)
	_Write_to_Console("laden | " & $aHosts[1][0] & $sLink)
	If IsArray($aHTML) Then
		$aHTML[1] = StringReplace($aHTML[1], "amp;", "")
;~ 		$aHTML[1] = BinaryToString($aHTML[1], 4)
;~ 		_ArrayDisplay($aHTML)
		Return $aHTML[1]
	Else
		$aHTML = _WinHttpSimpleSSLRequest($sHost, "GET", $sLink, $sReferer)
		$aHTML = StringReplace($aHTML, "amp;", "")
;~ 		$aHTML = BinaryToString($aHTML, 4)
		Return $aHTML
	EndIf
EndFunc   ;==>_send_WinhttpS_GET

Func _send_WinhttpS_POST($sHost, $sLink, $sReferer, $sPostContend)
;~ 	Local $sHeader = "Content-Type: application/x-www-form-urlencoded" & @CRLF & $sHeader_lovoo
	$aHTML = _WinHttpSimpleSSLRequest($sHost, "POST", $sLink, $sReferer, $sPostContend, $sHeader, True, 1)
	_Write_to_Console("laden | " & $aHosts[1][0] & $sLink)
	If IsArray($aHTML) Then
		$aHTML[1] = StringReplace($aHTML[1], "amp;", "")
;~ 		$aHTML[1] = BinaryToString($aHTML[1], 4)
		Return $aHTML[1]
	Else
		$aHTML = _WinHttpSimpleSSLRequest($sHost, "POST", $sLink, $sReferer, $sPostContend)
		$aHTML = StringReplace($aHTML, "amp;", "")
;~ 		$aHTML = BinaryToString($aHTML, 4)
		Return $aHTML
	EndIf
EndFunc   ;==>_send_WinhttpS_POST

Func _URIEncode($sData)
	; Prog@ndy
	Local $aData = StringSplit(BinaryToString(StringToBinary($sData, 4), 1), "")
	Local $nChar
	$sData = ""
	For $i = 1 To $aData[0]
;~ 		ConsoleWrite($aData[$i] & @CRLF)
		$nChar = Asc($aData[$i])
		Switch $nChar
			Case 45, 46, 48 - 57, 65 To 90, 95, 97 To 122, 126
				$sData &= $aData[$i]
			Case 32
				$sData &= "+"
			Case Else
				$sData &= "%" & Hex($nChar, 2)
		EndSwitch
	Next
	Return $sData
EndFunc   ;==>_URIEncode

Func _URIDecode($sData)
	; Prog@ndy
	Local $aData = StringSplit(StringReplace($sData, "+", " ", 0, 1), "%")
	$sData = ""
	For $i = 2 To $aData[0]
		$aData[1] &= Chr(Dec(StringLeft($aData[$i], 2))) & StringTrimLeft($aData[$i], 2)
	Next
	Return BinaryToString(StringToBinary($aData[1], 1), 4)
EndFunc   ;==>_URIDecode

; Description ...: Returns the n biggest or smallest number
; Syntax.........: nNumber($numbers, $n, $dir = 0)
; Parameters ....: $numbers - the numbers either from a string or from an array
; $n - search for n biggest or smallest number where n is an integer
; $dir - 0 search for smallest number, 1 for biggest number
; Return values .: Success - Returns the appropriate number and set @error to 0
; Failure - Returns error code:
; 1 - Wrong delimiter in string! Valid is comma (,) only!
; 2 - No numbers found!
; 3 - n is not an integer
; 4 - n is not in boundary of amount of numbers
; Remarks .......: Needs the function CompSort() for sorting the internal array
; Author ........: UEZ
; Version .......: 0.90 Build 2010-11-11 Beta
; ================================================================================================================================
Func _nNumber($numbers, $n, $dir = 0)
	If IsArray($numbers) Then
		$num = _ArrayToString($numbers, ",")
		If @error Then Return SetError(1, 0, "Error! Wrong delimiter in string! Valide is comma (,) only!")
		$numbers = $num
	EndIf
	Local $aNum = StringRegExp($numbers, "(-\d+\.\d+|\d+\.\d+|\d+)", 3)
	If Not IsArray($aNum) Then Return SetError(2, 0, "Error! No numbers found!")
	If Not IsInt($n) Then Return SetError(3, 0, "Error! n is not an integer")
	If $n < 1 Or $n > UBound($aNum) - 1 Then Return SetError(4, 0, "Error! n is not in boundary of amount of numbers")
	_CompSort($aNum)
	If Not $dir Then Return SetError(0, 0, $aNum[$n - 1])     ;n smallest number
	Return SetError(0, 0, $aNum[UBound($aNum) - $n])     ;n biggest number
EndFunc   ;==>_nNumber

Func _CompSort(ByRef $aArray)
	Local $gap = UBound($aArray)
	Local $swaps, $i, $tmp
	Do
		$gap = Int($gap / 1.247330950103979)
		If $gap < 1 Then $gap = 1
		$i = 0
		$swaps = 0
		Do
			If Number($aArray[$i]) > Number($aArray[$i + $gap]) Then
				$tmp = Number($aArray[$i])
				$aArray[$i] = Number($aArray[$i + $gap])
				$aArray[$i + $gap] = $tmp
				$swaps = 1
			EndIf
			$i += 1
		Until $i + $gap > UBound($aArray) - 1
	Until $gap = 1 And $swaps = 0
EndFunc   ;==>_CompSort

Func _replaceKom2Punkt($sString)
	Return StringReplace($sString, ",", ".")
EndFunc   ;==>_replaceKom2Punkt

Func _replacePunkt2Koma($sString)
	Return StringReplace($sString, ".", ",")
EndFunc   ;==>_replacePunkt2Koma

Func _Write_to_Console($sText)
	ConsoleWrite($sText & @CRLF)
EndFunc   ;==>_Write_to_Console

Func _XPDF_ToText($sPDFFile, $sTXTFile, $iFirstPage = 1, $iLastPage = 0, $bLayout = True)
	Local $sXPDFToText = @ScriptDir & "\..\daten\pdftotext.exe"
	Local $sOptions

	If Not FileExists($sPDFFile) Then Return SetError(1, 0, 0)
	If Not FileExists($sXPDFToText) Then Return SetError(2, 0, 0)

	If $iFirstPage <> 1 Then $sOptions &= " -f " & $iFirstPage
	If $iLastPage <> 0 Then $sOptions &= " -l " & $iLastPage
	If $bLayout = True Then $sOptions &= " -layout"     ;das war standart
;~ 		If $bLayout = True Then $sOptions &= " −simple" ;ganz gut viele leerzeichen
;~ 			If $bLayout = True Then $sOptions &= " −raw" ;fast perfekt
	If $bLayout = False Then $sOptions &= " −table"     ;fast perfekt

	Local $iReturn = ShellExecuteWait($sXPDFToText, $sOptions & ' "' & $sPDFFile & '" "' & $sTXTFile & '"', @ScriptDir & "\..", "", @SW_HIDE)
	If $iReturn = 0 Then Return 1

	Return 0

EndFunc   ;==>_XPDF_ToText

Func _create_Gui_Ausw($aArrayList)
	#Region ### START Koda GUI section ### Form=c:\users\flo\documents\isn autoit studio\projects\aufmasscreaterv2\forms\frm_ausw.kxf
	Global $frm_ausw = GUICreate("AuftragsAuswahl", 919, 231, 777, 303)
	Global $lv_auswahl = GUICtrlCreateListView("Beschreibung|SMNr|42Nr|DetailsID|Bezeichnung|Rahemvertrag|Start Datum|End Datum|Status", 5, 5, 905, 150, -1, BitOR($WS_EX_CLIENTEDGE, $LVS_EX_GRIDLINES, $LVS_EX_FULLROWSELECT))
	GUICtrlSendMsg(-1, $LVM_SETCOLUMNWIDTH, 0, 120)
	GUICtrlSendMsg(-1, $LVM_SETCOLUMNWIDTH, 1, 80)
	GUICtrlSendMsg(-1, $LVM_SETCOLUMNWIDTH, 2, 80)
	GUICtrlSendMsg(-1, $LVM_SETCOLUMNWIDTH, 3, 60)
	GUICtrlSendMsg(-1, $LVM_SETCOLUMNWIDTH, 4, 220)
	GUICtrlSendMsg(-1, $LVM_SETCOLUMNWIDTH, 5, 90)
	GUICtrlSendMsg(-1, $LVM_SETCOLUMNWIDTH, 6, 80)
	GUICtrlSendMsg(-1, $LVM_SETCOLUMNWIDTH, 7, 80)
	GUICtrlSendMsg(-1, $LVM_SETCOLUMNWIDTH, 8, 80)
	Global $frm_ausw_txt_besch = GUICtrlCreateInput("", 5, 160, 121, 21)
	Global $frm_ausw_txt_smnr = GUICtrlCreateInput("", 130, 160, 81, 21)
	Global $frm_ausw_txt_42er = GUICtrlCreateInput("", 215, 160, 71, 21)
	Global $frm_ausw_txt_detailsid = GUICtrlCreateInput("", 290, 160, 56, 21)
	Global $txt_ausw_txt_bez = GUICtrlCreateInput("", 350, 160, 216, 21)
	Global $frm_ausw_txt_rv = GUICtrlCreateInput("", 570, 160, 86, 21)
	Global $frm_ausw_txt_sDatum = GUICtrlCreateInput("", 660, 160, 76, 21)
	Global $frm_ausw_txt_eDatum = GUICtrlCreateInput("", 740, 160, 76, 21)
	Global $frm_ausw_txt_status = GUICtrlCreateInput("", 820, 160, 91, 21)
	Global $frm_ausw_bt_best = GUICtrlCreateButton("übernehmen", 5, 185, 75, 25)
	GUISetState(@SW_SHOW)
	#EndRegion ### END Koda GUI section ###


	_GUICtrlListView_AddArray($lv_auswahl, $aArrayList)

	While 1
		$nMsg = GUIGetMsg()
		Switch $nMsg
			Case $GUI_EVENT_CLOSE
				Exit
			Case $frm_ausw_bt_best
				$iRow = _GUICtrlListView_GetSelectedIndices($lv_auswahl)
;~ 				ConsoleWrite($aTest & @CRLF)
				GUICtrlSetData($frm_ausw_txt_besch, _GUICtrlListView_GetItemText($lv_auswahl, Int($iRow), 0))
				GUICtrlSetData($frm_ausw_txt_smnr, _GUICtrlListView_GetItemText($lv_auswahl, Int($iRow), 1))
				GUICtrlSetData($frm_ausw_txt_42er, _GUICtrlListView_GetItemText($lv_auswahl, Int($iRow), 2))
				GUICtrlSetData($frm_ausw_txt_detailsid, _GUICtrlListView_GetItemText($lv_auswahl, Int($iRow), 3))
				GUICtrlSetData($txt_ausw_txt_bez, _GUICtrlListView_GetItemText($lv_auswahl, Int($iRow), 4))
				GUICtrlSetData($frm_ausw_txt_rv, _GUICtrlListView_GetItemText($lv_auswahl, Int($iRow), 5))
				GUICtrlSetData($frm_ausw_txt_sDatum, _GUICtrlListView_GetItemText($lv_auswahl, Int($iRow), 6))
				GUICtrlSetData($frm_ausw_txt_eDatum, _GUICtrlListView_GetItemText($lv_auswahl, Int($iRow), 7))
				GUICtrlSetData($frm_ausw_txt_status, _GUICtrlListView_GetItemText($lv_auswahl, Int($iRow), 8))
				GUICtrlSetData($frm_ausw_bt_best, _GUICtrlListView_GetItemText($lv_auswahl, Int($iRow), 9))
;~ 				_DebugArrayDisplay($aTest)
				ExitLoop

		EndSwitch
	WEnd
	Return GUICtrlRead($frm_ausw_txt_detailsid)
EndFunc   ;==>_create_Gui_Ausw
