$ErrorActionPreference = "Stop"

$root = Split-Path $PSScriptRoot -Parent
$item = Get-ChildItem -Path $root -File -Filter "*.xlsx" |
    Where-Object { $_.Name -like "*Sheet*.xlsx" } |
    Sort-Object LastWriteTime -Descending |
    Select-Object -First 1

if (-not $item) {
    throw "Workbook not found"
}

$statusDone = -join @(
    [char]0x5DF2,
    [char]0x81EA,
    [char]0x52A8,
    [char]0x5316
)

$excel = New-Object -ComObject Excel.Application
$excel.Visible = $false
$excel.DisplayAlerts = $false

try {
    $wb = $excel.Workbooks.Open($item.FullName)
    for ($sheetIndex = 1; $sheetIndex -le $wb.Worksheets.Count; $sheetIndex++) {
        $ws = $wb.Worksheets.Item($sheetIndex)
        for ($row = 2; $row -le $ws.UsedRange.Rows.Count; $row++) {
            $status = ([string]$ws.Cells.Item($row, 13).Text).Trim()
            if ($status -eq $statusDone) {
                Write-Output ($ws.Name + "|" + $ws.Cells.Item($row, 1).Text + "|" + $ws.Cells.Item($row, 5).Text)
            }
        }
    }
    $wb.Close($false)
}
finally {
    $excel.Quit()
    [System.Runtime.InteropServices.Marshal]::ReleaseComObject($excel) | Out-Null
    [GC]::Collect()
    [GC]::WaitForPendingFinalizers()
}
