﻿@echo off
chcp 65001 >nul
setlocal enabledelayedexpansion
title PACS PIXEON

rem === PASTA BASE (sempre a mesma, independente de onde rodar) ===
set "BASE=C:\PACS_Download"
set "EXAMES=%BASE%\Exames"
set "CRED=%BASE%\.creds"

rem === CRIAR PASTAS SE NAO EXISTIREM ===
if not exist "%BASE%" mkdir "%BASE%"
if not exist "%EXAMES%" mkdir "%EXAMES%"

rem === CRIAR CREDENCIAIS SE NAO EXISTIREM ===
if not exist "%CRED%" (
    powershell -NoProfile -Command "[Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes('medico:medico'))" >"%CRED%" 2>nul
)

rem === CRIAR ATALHO SE NAO EXISTIR ===
if not exist "%USERPROFILE%\Desktop\BAIXAR_PACS.lnk" (
    powershell -NoProfile -Command "$s=(New-Object -Com WScript.Shell).CreateShortcut('%USERPROFILE%\Desktop\BAIXAR_PACS.lnk');$s.TargetPath='C:\PACS_Download\START.cmd';$s.WorkingDirectory='C:\PACS_Download';$s.Save()" 2>nul
)

rem === AUTO-COPIAR PARA C:\PACS_Download SE NAO ESTIVER LA ===
if not exist "%BASE%\START.cmd" (
    if exist "%~f0" copy "%~f0" "%BASE%\START.cmd" >nul 2>&1
)

rem === ATUALIZAR COPIA SE PRECISO ===
if /i not "%~f0"=="%BASE%\START.cmd" (
    if exist "%~f0" copy /y "%~f0" "%BASE%\START.cmd" >nul 2>&1
)

rem ========================================
rem A PARTIR DAQUI = DOWNLOAD INTERATIVO
rem ========================================

echo ==========================================
echo   PACS PIXEON - DOWNLOAD DE EXAMES
echo   Unimed Copa - Tomografia
echo ==========================================
echo.

rem Ler credencial
set /p AUTH=<"%CRED%"
set "AUTH=Basic %AUTH%"

echo Conectando ao PACS...
echo.

rem Chamar PowerShell para buscar estudos e mostrar na tela
powershell -NoProfile -ExecutionPolicy Bypass -Command ^
  "$auth = '%AUTH%';" ^
  "$h = @{Authorization=$auth; Accept='application/json'};" ^
  "try {" ^
  "  $s = Invoke-RestMethod -Uri 'http://10.102.180.12:4215/pacs-services/studies' -Headers $h -TimeoutSec 30;" ^
  "  $count = 0;" ^
  "  $ids = @();" ^
  "  foreach ($p in $s.PSObject.Properties) {" ^
  "    $count++;" ^
  "    if ($count -le 10) {" ^
  "      Write-Host ('  ' + $count + '. ID: ' + $p.Name) -ForegroundColor White;" ^
  "    }" ^
  "    $ids += $p.Name;" ^
  "  }" ^
  "  Write-Host '';" ^
  "  Write-Host ('Total: ' + $count + ' estudo(s)') -ForegroundColor Cyan;" ^
  "  $ids -join ',' | Out-File '%BASE%\lista.txt' -Encoding UTF8;" ^
  "} catch {" ^
  "  Write-Host ('ERRO: ' + $_.Exception.Message) -ForegroundColor Red;" ^
  "  exit 1;" ^
  "}"

if errorlevel 1 (
    echo.
    echo Falha ao conectar. Verifique se o PACS esta acessivel.
    echo.
    pause
    exit /b 1
)

echo.
echo ==========================================
echo  Digite os NUMEROS dos exames (ex: 1,3,5)
echo  ou digite TODOS para baixar tudo
echo  ou digite SAIR para cancelar
echo ==========================================
echo.
set /p ESCOLHA="Escolha: "

if /i "%ESCOLHA%"=="SAIR" (
    echo Cancelado.
    pause
    exit /b 0
)

rem Converter "TODOS" em lista completa
if /i "%ESCOLHA%"=="TODOS" (
    powershell -NoProfile -Command "$f = Get-Content '%BASE%\lista.txt'; $f" >"%BASE%\sel.txt" 2>nul
    set "ESCOLHA=TODOS"
    goto download
)

rem Converter numeros em IDs via PowerShell
powershell -NoProfile -Command ^
  "$ids = Get-Content '%BASE%\lista.txt' -Raw;" ^
  "$ids = $ids.Trim().Split(',');" ^
  "$nums = '%ESCOLHA%'.Split(',');" ^
  "$sel = @();" ^
  "foreach ($n in $nums) {" ^
  "  $i = [int]$n - 1;" ^
  "  if ($i -ge 0 -and $i -lt $ids.Count) {" ^
  "    $sel += $ids[$i];" ^
  "  }" ^
  "}" ^
  "$sel -join ',' | Out-File '%BASE%\sel.txt' -Encoding UTF8;"

:download
echo.
echo ==========================================
echo  INICIANDO DOWNLOAD
echo ==========================================
echo.

rem Ler selecao
set /p SEL_LIST=<"%BASE%\sel.txt"

if "%SEL_LIST%"=="" (
    echo Nenhum exame selecionado.
    pause
    exit /b 0
)

rem Executar download via PowerShell
powershell -NoProfile -ExecutionPolicy Bypass -Command ^
  "$auth = '%AUTH%';" ^
  "$h = @{Authorization=$auth; Accept='application/json'};" ^
  "$url = 'http://10.102.180.12:4215';" ^
  "$s = Invoke-RestMethod -Uri \"$url/pacs-services/studies\" -Headers $h -TimeoutSec 30;" ^
  "$sel = '%SEL_LIST%'.Split(',');" ^
  "$ok = 0; $fail = 0;" ^
  "foreach ($id in $sel) {" ^
  "  $id = $id.Trim();" ^
  "  if ($id -eq '') { continue };" ^
  "  $file = 'C:\PACS_Download\Exames\' + $id + '.dcm';" ^
  "  if (Test-Path $file) { Write-Host ('  PULA: ' + $id) -ForegroundColor Gray; continue };" ^
  "  $stud = $s.$id;" ^
  "  if ($stud -and $stud.Value.VR -eq 'UR' -and $stud.Value.Value.StartsWith('/')) {" ^
  "    $dl = $url + $stud.Value.Value;" ^
  "    Write-Host ('  Baixando: ' + $id) -ForegroundColor Yellow;" ^
  "    try {" ^
  "      Invoke-RestMethod -Uri $dl -Headers $h -OutFile $file -TimeoutSec 180;" ^
  "      $sz = [math]::Round((Get-Item $file).Length/1MB, 2);" ^
  "      Write-Host ('  OK: ' + $id + ' (' + $sz + ' MB)') -ForegroundColor Green;" ^
  "      $ok++;" ^
  "    } catch {" ^
  "      Write-Host ('  FALHA: ' + $id + ' - ' + $_.Exception.Message) -ForegroundColor Red;" ^
  "      $fail++;" ^
  "    }" ^
  "    Start-Sleep -Milliseconds 300;" ^
  "  } else {" ^
  "    Write-Host ('  SEM URI: ' + $id) -ForegroundColor Red;" ^
  "    $fail++;" ^
  "  }" ^
  "}" ^
  "Write-Host '';" ^
  "Write-Host '==============================' -ForegroundColor Cyan;" ^
  "Write-Host ('  Baixados: ' + $ok) -ForegroundColor Green;" ^
  "Write-Host ('  Falhas: ' + $fail) -ForegroundColor Red;" ^
  "Write-Host ('  Local: C:\PACS_Download\Exames') -ForegroundColor White;" ^
  "Write-Host '==============================' -ForegroundColor Cyan;"

echo.
echo Arquivos em: C:\PACS_Download\Exames
echo.
pause