<#
.SYNOPSIS
    阳泉婚礼宝典 - 桌面版安装脚本
.DESCRIPTION
    创建桌面快捷方式、开始菜单快捷方式、注册表卸载项
#>
#Requires -Version 2

[CmdletBinding()]
param(
    [switch]$Silent,
    [string]$InstallPath = ""
)

$ErrorActionPreference = "Stop"

# ===== 基本信息 =====
$APP_NAME       = "阳泉婚礼宝典"
$APP_EXEC       = "start.bat"
$APP_STOP       = "stop.bat"
$APP_ICON       = "resources\app.ico"
$APP_ID         = "YangquanWedding"
$APP_URL        = "http://127.0.0.1:8080/index.php"
$APP_VERSION    = "1.0.0"
$APP_PUBLISHER  = "阳泉婚礼宝典"

# ===== 路径解析 =====
$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Definition
if ([string]::IsNullOrEmpty($InstallPath)) {
    $InstallPath = $ScriptDir
}
$InstallPath = (Resolve-Path $InstallPath).Path
$ExePath     = Join-Path $InstallPath $APP_EXEC
$StopPath    = Join-Path $InstallPath $APP_STOP
$IconPath    = Join-Path $InstallPath $APP_ICON
if (-not (Test-Path $IconPath)) {
    $IconPath = $ExePath
}

# ===== 系统路径 =====
$DesktopDir   = [System.Environment]::GetFolderPath("Desktop")
$StartMenuDir = Join-Path ([System.Environment]::GetFolderPath("StartMenu")) ("Programs\" + $APP_NAME)
$UninstallKey = "HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall\" + $APP_ID

# ===== 辅助函数 =====
function Write-Color($Text, $Color) {
    if (-not $Silent) {
        if ($Color) {
            Write-Host -ForegroundColor $Color $Text
        } else {
            Write-Host $Text
        }
    }
}

function Create-Shortcut {
    param(
        [Parameter(Mandatory=$true)][string]$TargetPath,
        [Parameter(Mandatory=$true)][string]$ShortcutPath,
        [Parameter(Mandatory=$false)][string]$Arguments = "",
        [Parameter(Mandatory=$false)][string]$WorkingDir = "",
        [Parameter(Mandatory=$false)][string]$IconLocation = "",
        [Parameter(Mandatory=$false)][string]$Description = ""
    )
    $WshShell = New-Object -ComObject WScript.Shell
    $Shortcut = $WshShell.CreateShortcut($ShortcutPath)
    $Shortcut.TargetPath = $TargetPath
    if ($Arguments)    { $Shortcut.Arguments = $Arguments }
    if ($WorkingDir)   { $Shortcut.WorkingDirectory = $WorkingDir }
    if ($IconLocation) { $Shortcut.IconLocation = $IconLocation }
    if ($Description)  { $Shortcut.Description = $Description }
    $Shortcut.WindowStyle = 7
    $Shortcut.Save()
    [System.Runtime.InteropServices.Marshal]::ReleaseComObject($WshShell) | Out-Null
    return (Test-Path $ShortcutPath)
}

function Show-MsgBox {
    param([string]$Msg, [string]$Title, [string]$IconStr)
    if ($Silent) { return }
    try {
        Add-Type -AssemblyName System.Windows.Forms
        $iconEnum = [System.Windows.Forms.MessageBoxIcon]::Information
        if ($IconStr -eq "Error") { $iconEnum = [System.Windows.Forms.MessageBoxIcon]::Error }
        elseif ($IconStr -eq "Warning") { $iconEnum = [System.Windows.Forms.MessageBoxIcon]::Warning }
        $titleVal = $APP_NAME
        if ($Title) { $titleVal = $Title }
        [System.Windows.Forms.MessageBox]::Show($Msg, $titleVal, [System.Windows.Forms.MessageBoxButtons]::OK, $iconEnum) | Out-Null
    } catch { }
}

# PS 2.0 兼容的注册表属性设置（Set-ItemProperty -Type 仅 PS 3.0+ 支持）
function Set-RegProperty {
    param(
        [Parameter(Mandatory=$true)][string]$Path,
        [Parameter(Mandatory=$true)][string]$Name,
        [Parameter(Mandatory=$true)]$Value,
        [Parameter(Mandatory=$true)][string]$Type
    )
    $existing = Get-ItemProperty -Path $Path -Name $Name -ErrorAction SilentlyContinue
    if ($existing) {
        Set-ItemProperty -Path $Path -Name $Name -Value $Value
    } else {
        New-ItemProperty -Path $Path -Name $Name -Value $Value -PropertyType $Type -Force | Out-Null
    }
}

# ===== 安装开始 =====
Write-Color "================================================" Cyan
Write-Color ("     " + $APP_NAME + " - 桌面版安装程序 v" + $APP_VERSION) Cyan
Write-Color "================================================" Cyan
Write-Color ""

# 检查必要文件
if (-not (Test-Path $ExePath)) {
    $errMsg = "安装失败：找不到 " + $APP_EXEC + "`n请在正确的目录中运行本安装脚本。"
    Write-Color ("[ERROR] " + $errMsg) Red
    Show-MsgBox $errMsg "安装失败" "Error"
    exit 1
}

Write-Color ("[INFO] 安装目录: " + $InstallPath) Gray
Write-Color ("[INFO] 桌面目录: " + $DesktopDir) Gray
Write-Color ("[INFO] 开始菜单: " + $StartMenuDir) Gray
Write-Color ""

# 构造参数（避免反引号转义双引号）
$CmdArg      = '/c "' + $ExePath + '"'
$StopArg     = '/c "' + $StopPath + '"'
$UninstallPS = Join-Path $InstallPath "uninstall.ps1"
$UninstallArg = '-NoProfile -ExecutionPolicy Bypass -File "' + $UninstallPS + '"'

# 1) 创建桌面快捷方式
Write-Color "[1/4] 创建桌面快捷方式..."
try {
    $DesktopLnk = Join-Path $DesktopDir ($APP_NAME + ".lnk")
    $ok = Create-Shortcut -TargetPath "cmd.exe" `
                          -ShortcutPath $DesktopLnk `
                          -Arguments $CmdArg `
                          -WorkingDir $InstallPath `
                          -IconLocation ($IconPath + ",0") `
                          -Description ("启动 " + $APP_NAME)
    if ($ok) {
        Write-Color "  [OK] 桌面快捷方式已创建" Green
    } else {
        throw "快捷方式文件未生成"
    }
} catch {
    Write-Color ("  [WARN] 桌面快捷方式创建失败: " + $_) Yellow
}

# 2) 创建开始菜单目录和快捷方式
Write-Color "[2/4] 创建开始菜单快捷方式..."
try {
    New-Item -ItemType Directory -Force -Path $StartMenuDir | Out-Null

    # 启动
    $StartMenuLnk = Join-Path $StartMenuDir ($APP_NAME + ".lnk")
    $ok = Create-Shortcut -TargetPath "cmd.exe" `
                          -ShortcutPath $StartMenuLnk `
                          -Arguments $CmdArg `
                          -WorkingDir $InstallPath `
                          -IconLocation ($IconPath + ",0") `
                          -Description ("启动 " + $APP_NAME)
    if ($ok) { Write-Color "  [OK] 开始菜单[启动]快捷方式已创建" Green }

    # 停止
    $StopLnk = Join-Path $StartMenuDir "停止服务器.lnk"
    Create-Shortcut -TargetPath "cmd.exe" `
                    -ShortcutPath $StopLnk `
                    -Arguments $StopArg `
                    -WorkingDir $InstallPath `
                    -IconLocation ($IconPath + ",0") `
                    -Description ("停止 " + $APP_NAME + " 服务器") | Out-Null

    # 卸载
    $UninstallLnk = Join-Path $StartMenuDir "卸载.lnk"
    Create-Shortcut -TargetPath "powershell.exe" `
                    -ShortcutPath $UninstallLnk `
                    -Arguments $UninstallArg `
                    -WorkingDir $InstallPath `
                    -IconLocation ($IconPath + ",0") `
                    -Description ("卸载 " + $APP_NAME) | Out-Null

    # 直接打开网站
    $WebLnk = Join-Path $StartMenuDir "启动浏览器访问.lnk"
    Create-Shortcut -TargetPath "http://127.0.0.1:8080/index.php" `
                    -ShortcutPath $WebLnk `
                    -IconLocation ($IconPath + ",0") `
                    -Description ("在浏览器中打开 " + $APP_NAME) | Out-Null
} catch {
    Write-Color ("  [WARN] 开始菜单快捷方式创建失败: " + $_) Yellow
}

# 3) 写入注册表
Write-Color "[3/4] 写入卸载信息..."
try {
    $keyParent = Split-Path $UninstallKey -Parent
    if (-not (Test-Path $UninstallKey)) {
        New-Item -Path $keyParent -Name $APP_ID -Force | Out-Null
    }
    Set-RegProperty -Path $UninstallKey -Name "DisplayName"     -Value $APP_NAME -Type String
    Set-RegProperty -Path $UninstallKey -Name "DisplayVersion"  -Value $APP_VERSION -Type String
    Set-RegProperty -Path $UninstallKey -Name "Publisher"       -Value $APP_PUBLISHER -Type String
    Set-RegProperty -Path $UninstallKey -Name "InstallDate"     -Value (Get-Date -Format "yyyyMMdd") -Type String
    Set-RegProperty -Path $UninstallKey -Name "InstallLocation" -Value $InstallPath -Type String
    Set-RegProperty -Path $UninstallKey -Name "UninstallString" -Value ("powershell.exe " + $UninstallArg) -Type String
    Set-RegProperty -Path $UninstallKey -Name "DisplayIcon"     -Value ($IconPath + ",0") -Type String
    Set-RegProperty -Path $UninstallKey -Name "NoModify"        -Value 1 -Type DWord
    Set-RegProperty -Path $UninstallKey -Name "NoRepair"        -Value 1 -Type DWord

    # PS 2.0 兼容：不用 -File，用 Where-Object 过滤
    $totalSize = (Get-ChildItem $InstallPath -Recurse -ErrorAction SilentlyContinue | Where-Object { -not $_.PSIsContainer } | Measure-Object Length -Sum).Sum
    if ($totalSize) {
        $sizeKB = [int]($totalSize / 1KB)
        Set-RegProperty -Path $UninstallKey -Name "EstimatedSize" -Value $sizeKB -Type DWord
    }
    Write-Color "  [OK] 卸载信息已写入注册表 (控制面板 -> 程序和功能)" Green
} catch {
    Write-Color ("  [WARN] 注册表写入失败: " + $_) Yellow
}

# 4) 创建首次运行标记文件
Write-Color "[4/4] 完成安装信息记录..."
$InstalledFlag = Join-Path $InstallPath ".installed"
$flagContent = "[Installed]`r`nDate = " + (Get-Date -Format "yyyy-MM-dd HH:mm:ss") + "`r`nVersion = " + $APP_VERSION + "`r`nPath = " + $InstallPath
Set-Content -Path $InstalledFlag -Value $flagContent -Encoding UTF8
Write-Color "  [OK] 安装信息已记录" Green

# 完成
Write-Color ""
Write-Color "================================================" Green
Write-Color ("         桌面版安装完成!   " + $APP_NAME) Green
Write-Color "================================================" Green
Write-Color ""
Write-Color "桌面和开始菜单已添加以下快捷方式：" White
Write-Color ("  - " + $APP_NAME + " (启动服务器 + 自动打开浏览器)") Gray
Write-Color "  - 停止服务器 (停止 PHP 内置服务器)" Gray
Write-Color "  - 启动浏览器访问 (直接打开管理页面)" Gray
Write-Color "  - 卸载 (移除所有快捷方式和注册表项)" Gray
Write-Color ""
Write-Color "启动后会自动打开浏览器访问 http://127.0.0.1:8080" Gray

if (-not $Silent) {
    Write-Color ""
    $launch = Read-Host ("是否现在立即启动 " + $APP_NAME + "? (Y/n)")
    if (($launch -ne "n") -and ($launch -ne "N")) {
        Start-Process -FilePath "cmd.exe" -ArgumentList $CmdArg -WorkingDirectory $InstallPath -WindowStyle Minimized
        Start-Sleep -Seconds 2
        Start-Process $APP_URL
    }
    $doneMsg = $APP_NAME + " 桌面版安装完成!`n`n桌面和开始菜单已添加快捷方式。`n`n启动后会自动打开浏览器访问 http://127.0.0.1:8080"
    Show-MsgBox $doneMsg "安装完成" "Information"
}

exit 0
