' 母模构建 (管线验证版): 模板部件 + STEP 导入真实几何 + 注入参数化表达式
' 用法: WorkingDirectory=母模目录, 目录内放 src.step (真实 STEP) 与 KC_master.prt (模板副本)
Option Strict Off
Imports System
Imports System.IO
Imports System.Text
Imports NXOpen
Imports NXOpen.UF

Module ImportMaster
    Sub Main()
        Dim lw As ListingWindow = Session.GetSession().ListingWindow
        lw.Open()
        Dim cur As String = Directory.GetCurrentDirectory()
        Dim outPath As String = Path.Combine(cur, "KC_master.prt")
        Dim srcStep As String = Path.Combine(cur, "src.step")
        If Not File.Exists(outPath) OrElse Not File.Exists(srcStep) Then
            lw.WriteLine("缺文件: " & outPath & " / " & srcStep)
            Return
        End If
        Dim partLoadStatus1 As NXOpen.PartLoadStatus = Nothing
        Session.GetSession().Parts.OpenBaseDisplay(outPath, partLoadStatus1)
        Dim w As Part = Session.GetSession().Parts.Work
        If w Is Nothing Then
            lw.WriteLine("打开失败")
            Return
        End If

        ' 导入真实 STEP 到当前工作部件 (WorkPart; 前提: 模板副本必须可写, FileOpenFlag 打开源文件)
        Dim imp As NXOpen.Step214Importer = Session.GetSession().DexManager.CreateStep214Importer()
        imp.InputFile = srcStep
        imp.ImportTo = NXOpen.Step214Importer.ImportToOption.WorkPart
        imp.FileOpenFlag = True
        imp.Commit()
        imp.Destroy()
        lw.WriteLine("STEP 已导入到工作部件")

        Dim ufs As UFSession = UFSession.GetUFSession()
        ufs.Modl.Update()

        ' 注入参数化表达式
        Dim mm As NXOpen.Unit = w.UnitCollection.FindObject("MilliMeter")
        If mm IsNot Nothing Then
            w.Expressions.CreateExpressionWithUnit("Number", "bore=32", mm)
            w.Expressions.CreateExpressionWithUnit("Number", "stroke=10", mm)
        Else
            w.Expressions.CreateExpression("Number", "bore=32")
            w.Expressions.CreateExpression("Number", "stroke=10")
        End If
        w.Expressions.CreateExpression("Number", "magOn=0")
        w.Expressions.CreateExpression("Number", "mountIdx=0")
        lw.WriteLine("表达式已注入")

        Dim pss As NXOpen.PartSaveStatus = w.Save(NXOpen.BasePart.SaveComponents.True, NXOpen.BasePart.CloseAfterSave.False)
        If pss IsNot Nothing Then pss.Dispose()
        lw.WriteLine("已保存: " & outPath)
    End Sub
End Module
