param(
    [Parameter(Mandatory=$true)][string]$InputDirectory,
    [Parameter(Mandatory=$true)][string]$PdfDirectory
)

$ErrorActionPreference = 'Stop'
New-Item -ItemType Directory -Force -Path $PdfDirectory | Out-Null

$wdAlignParagraphCenter = 1
$wdAlignParagraphRight = 2
$wdAlignParagraphJustify = 3
$wdLineSpaceMultiple = 5
$wdPageBreak = 7
$wdFormatPDF = 17
$wdFieldPage = 33
$wdHeaderFooterPrimary = 1
$wdCollapseEnd = 0
$wdColorWhite = 16777215
$wdColorDarkBlue = 9655585
$wdColorBlue = 11621185
$wdColorGray = 8421504

$word = New-Object -ComObject Word.Application
$word.Visible = $false
$word.DisplayAlerts = 0

try {
    Get-ChildItem -LiteralPath $InputDirectory -Filter '*.docx' | ForEach-Object {
        $doc = $word.Documents.Open($_.FullName)
        try {
            $doc.PageSetup.PaperSize = 2  # Letter
            $doc.PageSetup.TopMargin = $word.InchesToPoints(0.82)
            $doc.PageSetup.BottomMargin = $word.InchesToPoints(0.78)
            $doc.PageSetup.LeftMargin = $word.InchesToPoints(0.9)
            $doc.PageSetup.RightMargin = $word.InchesToPoints(0.9)
            $doc.PageSetup.HeaderDistance = $word.InchesToPoints(0.35)
            $doc.PageSetup.FooterDistance = $word.InchesToPoints(0.35)

            $normal = $doc.Styles.Item(-1)
            $normal.Font.Name = 'Calibri'
            $normal.Font.NameFarEast = 'Microsoft YaHei'
            $normal.Font.Size = 10.5
            $normal.Font.Color = 0
            $normal.ParagraphFormat.Alignment = $wdAlignParagraphJustify
            $normal.ParagraphFormat.SpaceBefore = 0
            $normal.ParagraphFormat.SpaceAfter = 6
            $normal.ParagraphFormat.LineSpacingRule = $wdLineSpaceMultiple
            $normal.ParagraphFormat.LineSpacing = 15.5

            $title = $doc.Styles.Item(-63)
            $title.Font.Name = 'Calibri'
            $title.Font.NameFarEast = 'Microsoft YaHei'
            $title.Font.Size = 25
            $title.Font.Bold = $true
            $title.Font.Color = $wdColorDarkBlue
            $title.ParagraphFormat.Alignment = $wdAlignParagraphCenter
            $title.ParagraphFormat.SpaceBefore = 115
            $title.ParagraphFormat.SpaceAfter = 10
            $title.ParagraphFormat.KeepWithNext = $true

            $subtitle = $doc.Styles.Item(-75)
            $subtitle.Font.NameFarEast = 'Microsoft YaHei'
            $subtitle.Font.Name = 'Calibri'
            $subtitle.Font.Size = 14
            $subtitle.Font.Color = $wdColorGray
            $subtitle.ParagraphFormat.Alignment = $wdAlignParagraphCenter
            $subtitle.ParagraphFormat.SpaceAfter = 30

            $headingSettings = @(
                @{ Id=-2; Size=16; Before=16; After=8; Color=$wdColorBlue },
                @{ Id=-3; Size=13; Before=12; After=6; Color=$wdColorBlue },
                @{ Id=-4; Size=11.5; Before=9; After=4; Color=$wdColorDarkBlue }
            )
            foreach ($h in $headingSettings) {
                $style = $doc.Styles.Item($h.Id)
                $style.Font.Name = 'Calibri'
                $style.Font.NameFarEast = 'Microsoft YaHei'
                $style.Font.Size = $h.Size
                $style.Font.Bold = $true
                $style.Font.Color = $h.Color
                $style.ParagraphFormat.SpaceBefore = $h.Before
                $style.ParagraphFormat.SpaceAfter = $h.After
                $style.ParagraphFormat.KeepWithNext = $true
                $style.ParagraphFormat.KeepTogether = $true
                $style.ParagraphFormat.PageBreakBefore = $false
            }

            foreach ($p in $doc.Paragraphs) {
                $p.Range.Font.NameFarEast = 'Microsoft YaHei'
                if ($p.Range.Text.Trim() -eq '目录') {
                    $p.Alignment = $wdAlignParagraphCenter
                    $p.Range.Font.Size = 18
                    $p.Range.Font.Bold = $true
                    $p.Range.Font.Color = $wdColorDarkBlue
                }
            }

            foreach ($table in $doc.Tables) {
                $table.AllowAutoFit = $true
                $table.AutoFitBehavior(2)
                $table.Rows.AllowBreakAcrossPages = $true
                $table.Range.Font.Name = 'Calibri'
                $table.Range.Font.NameFarEast = 'Microsoft YaHei'
                $table.Range.Font.Size = 9
                $table.Range.ParagraphFormat.SpaceAfter = 2
                $table.Range.ParagraphFormat.LineSpacingRule = 0
                $table.Borders.Enable = 1
                if ($table.Rows.Count -gt 0) {
                    $table.Rows.Item(1).Range.Font.Bold = $true
                    $table.Rows.Item(1).Range.Font.Color = $wdColorWhite
                    $table.Rows.Item(1).Shading.BackgroundPatternColor = $wdColorDarkBlue
                    $table.Rows.Item(1).HeadingFormat = $true
                }
                $table.Range.Cells.VerticalAlignment = 1
            }

            foreach ($section in $doc.Sections) {
                $header = $section.Headers.Item($wdHeaderFooterPrimary)
                $header.Range.Text = '大规模多智能体网络流量建模与预测'
                $header.Range.Font.NameFarEast = 'Microsoft YaHei'
                $header.Range.Font.Name = 'Calibri'
                $header.Range.Font.Size = 8.5
                $header.Range.Font.Color = $wdColorGray
                $header.Range.ParagraphFormat.Alignment = 0

                $footer = $section.Footers.Item($wdHeaderFooterPrimary)
                $footer.Range.Text = '参赛材料初稿  |  '
                $footer.Range.Font.NameFarEast = 'Microsoft YaHei'
                $footer.Range.Font.Name = 'Calibri'
                $footer.Range.Font.Size = 8.5
                $footer.Range.Font.Color = $wdColorGray
                $footer.Range.ParagraphFormat.Alignment = $wdAlignParagraphRight
                $range = $footer.Range
                $range.Collapse($wdCollapseEnd)
                [void]$footer.Range.Fields.Add($range, $wdFieldPage)
            }

            if ($doc.TablesOfContents.Count -gt 0) {
                $doc.TablesOfContents.Item(1).Update()
            }
            $doc.Fields.Update() | Out-Null
            $doc.Repaginate()
            $doc.Save()
            $pdfPath = Join-Path $PdfDirectory ($_.BaseName + '.pdf')
            $doc.ExportAsFixedFormat($pdfPath, $wdFormatPDF)
        }
        finally {
            $doc.Close($true)
            [System.Runtime.InteropServices.Marshal]::ReleaseComObject($doc) | Out-Null
        }
    }
}
finally {
    $word.Quit()
    [System.Runtime.InteropServices.Marshal]::ReleaseComObject($word) | Out-Null
    [GC]::Collect()
    [GC]::WaitForPendingFinalizers()
}
