@echo off
setlocal
set "LUBAN_CLEAN_SELF=%~f0"
where powershell.exe >nul 2>nul
if errorlevel 1 (
 echo PowerShell is unavailable. Please contact support.
 pause
 exit /b 1
)
powershell.exe -NoLogo -NoProfile -STA -Command "$s=[IO.File]::ReadAllText($env:LUBAN_CLEAN_SELF,[Text.Encoding]::UTF8);$p=$s.Substring($s.LastIndexOf('# POWERSHELL_PAYLOAD')+20); & ([ScriptBlock]::Create($p))"
set "result=%errorlevel%"
echo.
pause
exit /b %result%
# POWERSHELL_PAYLOAD
$ErrorActionPreference='Stop'
$title='鲁班计价配置清理'
$script:report=''
function Result($text,$icon) {
 Write-Host $text
 try {[Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms') | Out-Null; [System.Windows.Forms.MessageBox]::Show($text,$title,[System.Windows.Forms.MessageBoxButtons]::OK,[System.Windows.Forms.MessageBoxIcon]$icon) | Out-Null} catch {}
}
try {
 $base=[IO.Path]::GetFullPath($env:APPDATA)
 $target=[IO.Path]::GetFullPath((Join-Path $base '鲁班计价'))
 if ([IO.Path]::GetDirectoryName($target) -ne $base.TrimEnd('\')) {throw '目标路径检查失败'}
 Write-Host ('清理目标：'+$target)
 if (!(Test-Path -LiteralPath $target)) {Result '无需清理：没有找到“鲁班计价”配置文件夹。未修改其他目录。' 'Information';exit 0}
 if (Get-Process -Name QuantStar,Luban -ErrorAction SilentlyContinue) {throw '请先保存工程并退出鲁班计价，再运行本工具。'}
 $item=Get-Item -LiteralPath $target -Force
 if (!$item.PSIsContainer -or ($item.Attributes -band [IO.FileAttributes]::ReparsePoint)) {throw '目标不是普通文件夹，已停止。'}
 function CheckTree($dir) {
  foreach($child in (Get-ChildItem -LiteralPath $dir -Force)) {
   if ($child.Attributes -band [IO.FileAttributes]::ReparsePoint) {throw '配置中包含链接，已停止。'}
   if ($child.PSIsContainer) {CheckTree $child.FullName}
  }
 }
 CheckTree $target
 $backup=Join-Path $base ('鲁班计价_清理备份_'+[DateTime]::Now.ToString('yyyyMMdd_HHmmss')+'_'+[Guid]::NewGuid().ToString('N').Substring(0,6))
 Move-Item -LiteralPath $target -Destination $backup -ErrorAction Stop
 if (Test-Path -LiteralPath $target) {throw '原目录仍然存在，请联系技术支持。'}
 $message="清理成功：原配置目录已移走。`r`n现在可以重新打开鲁班计价测试。`r`n`r`n备份位置："+$backup+"`r`n`r`n注意：这代表配置清理成功，是否解决原故障还需重试。"
 $report=Join-Path $base '鲁班计价_清理结果.txt'
 $message | Out-File -LiteralPath $report -Encoding UTF8
 Result ($message+"`r`n结果记录："+$report) 'Information'
 exit 0
} catch {Result ('清理未完成：'+$_.Exception.Message+'。请截取此提示发给技术支持。') 'Error';exit 1}
