' 诊断 2: 批处理下 Work=NULL — 验证 (a) BasePart 直接转 Part 操作 (b) SetDisplay 签名
Option Strict Off
Imports System
Imports System.IO
Imports System.Text
Imports NXOpen
Imports NXOpen.UF

Module DebugSave
    Sub Main()
        Dim lw As ListingWindow = Session.GetSession().ListingWindow
        lw.Open()
        Dim sb As New StringBuilder()
        Dim outPath As String = Path.Combine(Directory.GetCurrentDirectory(), "KC_master.prt")
        sb.AppendLine("CWD=" & Directory.GetCurrentDirectory())

        ' (a) SetDisplay 签名反射
        Dim pc As NXOpen.PartCollection = Session.GetSession().Parts
        For Each mi As System.Reflection.MethodInfo In pc.GetType().GetMethods()
            If mi.Name = "SetDisplay" OrElse mi.Name = "Open" Then sb.AppendLine("SIG: " & mi.ToString())
        Next

        Dim partLoadStatus1 As NXOpen.PartLoadStatus = Nothing
        Dim basePart1 As NXOpen.BasePart = Session.GetSession().Parts.OpenBaseDisplay(outPath, partLoadStatus1)
        sb.AppendLine("basePart1=" & (If(basePart1 Is Nothing, "NULL", basePart1.FullPath)))
        sb.AppendLine("Work=" & (If(Session.GetSession().Parts.Work Is Nothing, "NULL", "非空")))

        ' (b) 直接转换 BasePart → Part 并操作
        Dim p1 As Part = CType(basePart1, Part)
        sb.AppendLine("p1 cast ok, FullPath=" & p1.FullPath & " IsModified(before)=" & p1.IsModified)
        Dim ufs As UFSession = UFSession.GetUFSession()
        ufs.Modl.EditExp("bore=50")
        ufs.Modl.Update()
        sb.AppendLine("p1.IsModified(after EditExp+Update)=" & p1.IsModified)
        ' 对比 Save 与 SaveAs 在批处理下的落盘行为
        Dim pss As NXOpen.PartSaveStatus = p1.Save(NXOpen.BasePart.SaveComponents.True, NXOpen.BasePart.CloseAfterSave.False)
        If pss IsNot Nothing Then pss.Dispose()
        sb.AppendLine("after Save: size=" & (New FileInfo(outPath)).Length & " mtime=" & File.GetLastWriteTime(outPath))
        Dim asPath As String = Path.Combine(Directory.GetCurrentDirectory(), "KC_master_as.prt")
        Dim pss2 As NXOpen.PartSaveStatus = p1.SaveAs(asPath)
        If pss2 IsNot Nothing Then pss2.Dispose()
        sb.AppendLine("after SaveAs: exists=" & File.Exists(asPath) & " size=" & (If(File.Exists(asPath), (New FileInfo(asPath)).Length, 0)))
        File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), "debug-save.txt"), sb.ToString(), Encoding.UTF8)
        lw.WriteLine(sb.ToString())
    End Sub
End Module
