am-freescan/am-web/src/views/lab/dimension/ComparisonPanel.vue

594 lines
18 KiB
Vue
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<template>
<section class="comparison-panel">
<div class="comparison-heading">
<div
><h3>尺寸比对</h3
><span class="secondary"
>仅有三维数模和扫描PLY时,可不选检测计划,直接生成偏差图;选用二维图纸时需选择检测计划。</span
></div
>
<div class="comparison-buttons">
<el-tag :type="health.available ? 'success' : 'info'">{{
health.available ? '计算服务就绪' : '计算服务未就绪'
}}</el-tag>
<el-button :loading="loading" @click="refresh(true)">刷新状态</el-button>
<el-button
v-hasPermi="['lab:result:query']"
@click="router.push('/lab/dimension/inspection-templates')"
>维护检测计划</el-button
>
</div>
</div>
<el-alert v-if="error" :title="error" type="error" :closable="false" />
<el-form label-position="top" class="comparison-options" :disabled="busy || savingInputs">
<el-form-item
label="检测计划"
:required="hasDrawing"
:error="options.planTemplateId && !selectedPlan ? '该计划已不可用,请重新选择' : ''"
>
<el-select
ref="planSelect"
v-model="options.planTemplateId"
filterable
clearable
:placeholder="hasDrawing ? '请选择检测计划(必填)' : '可不选,直接生成表面偏差图'"
class="plan-select"
>
<el-option-group v-for="group in planGroups" :key="group.label" :label="group.label">
<el-option
v-for="item in group.items"
:key="item.id"
:value="item.id"
:label="`${item.label} · V${item.version}`"
:disabled="item.kind === 'feature' && !health.feature_capabilities"
/>
</el-option-group>
</el-select>
<span v-if="!hasDrawing" class="secondary"
>不选计划时生成表面偏差图;如需检测尺寸或形位公差,可选择检测计划。</span
>
<span v-else-if="!catalog.length && !loading" class="secondary"
>暂无可用计划,请先点击“维护检测计划”录入并启用,再刷新状态。</span
>
</el-form-item>
<div class="comparison-fields">
<el-form-item label="扫描数据单位"
><el-select v-model="options.sourceScale"
><el-option
v-for="item in units"
:key="item.value"
:label="item.label"
:value="item.value" /></el-select
></el-form-item>
<el-form-item label="标准数模单位"
><el-select v-model="options.targetScale"
><el-option
v-for="item in units"
:key="item.value"
:label="item.label"
:value="item.value" /></el-select
></el-form-item>
<el-form-item label="表面偏差阈值(mm)"
><el-input-number v-model="options.tolerance" :min="0.001" :max="100" :precision="3"
/></el-form-item>
</div>
<div v-if="!deviationOnly" class="comparison-report"
><el-checkbox v-model="options.autoReport">计算后自动生成报告</el-checkbox></div
>
<section class="comparison-preprocessing" aria-label="点云预处理设置">
<h4>点云预处理设置</h4>
<el-checkbox v-model="options.sourceClean">扫描数据已清理,仅含被测零件</el-checkbox>
<el-checkbox v-model="options.reviewCleanup" :disabled="options.sourceClean"
>对齐前先人工确认点云清理</el-checkbox
>
</section>
</el-form>
<el-alert
v-if="featureTemplatesUnavailable && !deviationOnly"
title="CAD 特征计划暂不可用,请确认已执行增量升级;原有检测计划可继续使用。"
type="warning"
:closable="false"
/>
<el-alert
v-if="blockers.length"
class="comparison-checklist gap"
title="暂不能开始尺寸比对,请完成以下事项"
type="warning"
:closable="false"
show-icon
>
<ul class="comparison-blockers">
<li v-for="issue in blockers" :key="issue.key">
<span>{{ issue.text }}</span>
<el-button
v-if="canResolveIssue(issue.action)"
type="primary"
link
:disabled="busy || savingInputs || syncing"
@click="resolveIssue(issue.action)"
>{{ issue.label }}</el-button
>
</li>
</ul>
</el-alert>
<div class="comparison-buttons gap">
<el-button
type="primary"
:loading="busy"
:disabled="savingInputs || !ready || blockers.length > 0"
v-hasPermi="['lab:data:upload']"
@click="start"
>{{ busy ? '正在提交文件' : deviationOnly ? '生成偏差图' : '开始尺寸比对' }}</el-button
>
<el-button v-if="job.engine_id" type="primary" plain @click="expanded = true"
>打开比对工作区</el-button
>
<el-button
v-if="job.engine_id && ['ARCHIVE_ERROR', 'ARCHIVE_PENDING'].includes(job.status)"
:loading="syncing"
v-hasPermi="['lab:data:upload']"
@click="sync"
>重试成果归档</el-button
>
<span v-if="!blockers.length" class="comparison-ready">{{
deviationOnly
? '资料版本已保存,可直接生成表面偏差图。'
: '资料版本已保存,检测计划已选择,可以开始比对。'
}}</span>
</div>
<div v-if="job.id" class="comparison-status">
<div class="comparison-heading"
><strong>{{ labels[job.status] || job.status }}</strong
><span class="secondary">{{
sameInput ? '对应当前输入' : '历史比对,输入版本已更新'
}}</span></div
>
<p class="secondary"
>创建时间:{{ formatNullableDate(job.create_time) }} · 状态同步时间:{{
formatNullableDate(job.update_time)
}}</p
>
<el-progress
v-if="['SUBMITTING', 'PROCESSING'].includes(job.status)"
:percentage="50"
:indeterminate="true"
:show-text="false"
/>
<p v-if="job.last_error" class="comparison-error">{{ job.last_error }}</p>
<p v-else-if="job.status === 'ARCHIVED'"
>STL与PDF已成套归档,可在下方核对、查看并确认交付。</p
>
<p v-else-if="job.status === 'SURFACE_READY'"
>打开比对工作区查看、下载表面偏差图;此模式不生成测量报告,不作为 STL 与 PDF 成套交付。</p
>
<p v-else-if="job.status === 'REVIEW'">打开工作区确认清理、测量项或生成新版报告。</p>
<p v-else-if="job.status === 'UNKNOWN'"
>提交回执未确认,请核对计算服务记录。系统不会自动重复提交。</p
>
<p v-if="calculationActive" class="comparison-error"
>当前计算服务未提供取消计算接口。关闭工作区或离开页面不会停止计算,请等待结果,避免重复提交。</p
>
<p class="secondary"
>比对作业 {{ job.id
}}<span v-if="job.source_execution_id"> · 来源扫描 {{ job.source_execution_id }}</span
><span v-if="job.engine_revision"> · 成果版本 {{ job.engine_revision }}</span></p
>
</div>
<el-dialog
v-model="expanded"
title="尺寸比对工作区"
width="min(1600px, 97vw)"
top="2vh"
destroy-on-close
append-to-body
:before-close="closeWorkspace"
>
<el-alert
v-if="calculationActive"
title="计算仍在进行。关闭本窗口不会取消计算;当前计算服务未提供停止接口。"
type="info"
:closable="false"
show-icon
/>
<InspectionWorkbench
v-if="job.engine_id"
ref="workspace"
:key="job.engine_id"
:record-id="job.engine_id"
@changed="workspaceChanged"
@history="closeWorkspace(() => (expanded = false))"
/>
</el-dialog>
</section>
</template>
<script setup lang="ts">
import { formatNullableDate } from '@/utils/formatTime'
import * as Api from '@/api/lab/inspection'
import { onBeforeUnmount, watch, ref, reactive, computed, defineAsyncComponent } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import '@/views/lab/inspection/inspection.scss'
import { comparisonPollInterval } from '@/views/lab/scan-task/workbenchPolling.mjs'
import { comparisonBlockers } from './comparisonReadiness.mjs'
import { checkPermi } from '@/utils/permission'
const InspectionWorkbench = defineAsyncComponent(
() => import('@/views/lab/inspection/InspectionWorkbench.vue')
)
const props = defineProps<{
taskId: string
unitId: string
revision: number
ready: boolean
dirty: boolean
sourceChanged: boolean
active: boolean
inputs: { modelId: any; drawingId: any; cloudId: any }
selectedInputs?: { modelId: any; drawingId: any; cloudId: any }
savingInputs?: boolean
cloudFileCount?: number
}>()
const emit = defineEmits<{
changed: []
'open-materials': []
'save-inputs': []
'archive-cloud': []
}>()
const router = useRouter(),
job = ref<any>({}),
health = ref<any>({}),
catalog = ref<any[]>([]),
error = ref(''),
loading = ref(false),
busy = ref(false),
syncing = ref(false),
expanded = ref(false),
workspace = ref<any>()
const options = reactive({
planTemplateId: '',
sourceScale: 1,
targetScale: 1,
tolerance: 1,
autoReport: true,
sourceClean: false,
reviewCleanup: false
})
const planSelect = ref<any>()
const featureTemplatesUnavailable = ref(false)
const planGroups = computed(() =>
[
{
label: 'CAD 特征计划(基准 / 形位公差)',
items: catalog.value.filter((item) => item.kind === 'feature')
},
{ label: '原有检测计划', items: catalog.value.filter((item) => item.kind !== 'feature') }
].filter((group) => group.items.length)
)
const selectedPlan = computed(() =>
catalog.value.find((plan) => plan.id === options.planTemplateId)
)
const hasDrawing = computed(() => !!(props.selectedInputs || props.inputs).drawingId)
const deviationOnly = computed(() => !hasDrawing.value && !options.planTemplateId)
const units = [
{ value: 1, label: '毫米 mm' },
{ value: 1000, label: '米 m' },
{ value: 0.001, label: '微米 μm' }
]
const labels: Record<string, string> = {
SUBMITTING: '正在提交资料',
UNKNOWN: '提交结果待核对',
PROCESSING: '计算处理中',
REVIEW: '待人工核对',
ARCHIVE_PENDING: '计算完成,正在归档',
ARCHIVE_ERROR: '计算完成,成果归档待处理',
ARCHIVED: '成果已成套归档',
SURFACE_READY: '表面偏差图已生成',
FAILED: '比对失败'
}
const sameInput = computed(() => {
// Historical snapshots stored Snowflake IDs as JSON integers; preserve them before parsing.
try {
const frozen = JSON.parse(
(job.value.input_json || '{}').replace(/"id"\s*:\s*(\d{16,})(?=\s*[,}])/g, '"id":"$1"')
)
return (
String(frozen.model?.id || '') === String(props.inputs.modelId || '') &&
String(frozen.drawing?.id || '') === String(props.inputs.drawingId || '') &&
String(frozen.cloud?.id || '') === String(props.inputs.cloudId || '')
)
} catch {
return false
}
})
const pendingSameInput = computed(
() =>
sameInput.value &&
['SUBMITTING', 'UNKNOWN', 'PROCESSING', 'REVIEW', 'ARCHIVE_PENDING', 'ARCHIVE_ERROR'].includes(
job.value.status
)
)
const calculationActive = computed(() =>
['SUBMITTING', 'UNKNOWN', 'PROCESSING'].includes(job.value.status)
)
const blockers = computed(() =>
comparisonBlockers({
unitId: props.unitId,
inputs: props.selectedInputs || props.inputs,
dirty: props.dirty,
sourceChanged: props.sourceChanged,
planId: options.planTemplateId,
plans: catalog.value,
healthAvailable: health.value.available,
featureAvailable: !!health.value.feature_capabilities,
pending: pendingSameInput.value,
cloudFileCount: props.cloudFileCount
})
)
function canResolveIssue(action: string) {
if (['save', 'archive'].includes(action)) return checkPermi(['lab:data:upload'])
return action !== 'workspace' || !!job.value.engine_id
}
function resolveIssue(action: string) {
if (action === 'save') emit('save-inputs')
else if (action === 'archive') emit('archive-cloud')
else if (action === 'materials') emit('open-materials')
else if (action === 'plan') {
planSelect.value?.$el?.scrollIntoView({ block: 'center', behavior: 'smooth' })
planSelect.value?.focus()
} else if (action === 'refresh') void refresh(true)
else if (action === 'workspace' && job.value.engine_id) expanded.value = true
}
let timer: ReturnType<typeof setTimeout> | undefined,
generation = 0,
abort: AbortController | undefined
let lastDelivery = ''
let suspended = false
function schedulePoll(token: number) {
clearTimeout(timer)
const delay = comparisonPollInterval(job.value.status)
if (delay && token === generation && props.active && !suspended && !document.hidden)
timer = setTimeout(() => refresh(), delay)
}
async function refresh(withHealth = false) {
if (!props.active || !props.unitId || suspended || document.hidden || loading.value) return
const current = generation
loading.value = true
error.value = ''
try {
const [currentJob, state, plans] = await Promise.all([
Api.comparison(props.taskId, props.unitId, abort?.signal),
withHealth ? Api.health() : Promise.resolve(null),
withHealth ? Api.comparisonTemplates() : Promise.resolve(null)
])
if (current !== generation) return
job.value = currentJob || {}
if (state) health.value = state
if (plans) {
catalog.value = plans.templates || []
featureTemplatesUnavailable.value = !!plans.featureTemplatesUnavailable
}
const delivery = String(job.value.delivery_id || '')
if (delivery && lastDelivery && delivery !== lastDelivery) emit('changed')
if (delivery && !lastDelivery) emit('changed')
lastDelivery = delivery
} catch (e: any) {
if (current === generation && !abort?.signal.aborted)
error.value = e?.message || '读取比对状态失败'
} finally {
if (current === generation) {
loading.value = false
schedulePoll(current)
}
}
}
watch(
() => [props.taskId, props.unitId, props.active],
async () => {
generation++
abort?.abort()
abort = new AbortController()
clearTimeout(timer)
loading.value = false
job.value = {}
lastDelivery = ''
if (props.active && props.unitId && props.unitId !== '0') await refresh(true)
},
{ immediate: true }
)
async function start() {
if (busy.value || props.savingInputs || !props.ready) return
if (blockers.value.length) {
ElMessage.warning(blockers.value[0].text)
return
}
const token = generation
busy.value = true
error.value = ''
try {
const started = await Api.startComparison({
taskId: props.taskId,
unitId: props.unitId,
revision: props.revision,
...options
})
if (token !== generation) return
job.value = started
schedulePoll(token)
emit('changed')
if (job.value.engine_id) expanded.value = true
} catch (e: any) {
if (token === generation) {
const failure = e?.message || '提交失败,请刷新状态后核对'
await refresh()
if (token === generation) error.value = failure
}
} finally {
busy.value = false
}
}
async function sync() {
if (syncing.value || !job.value.engine_id) return
syncing.value = true
try {
await Api.sync(job.value.engine_id)
await refresh()
emit('changed')
ElMessage.success('已更新归档状态')
} catch (e: any) {
error.value = e?.message || '归档尚未完成'
} finally {
syncing.value = false
}
}
async function workspaceChanged() {
await refresh()
emit('changed')
}
async function canLeave() {
return !expanded.value || !workspace.value || (await workspace.value.confirmLeave())
}
async function closeWorkspace(done: () => void) {
if (await canLeave()) {
done()
await workspaceChanged()
}
}
defineExpose({ canLeave })
function visibilityChanged() {
if (document.hidden) clearTimeout(timer)
else if (props.active && comparisonPollInterval(job.value.status)) void refresh()
}
onMounted(() => document.addEventListener('visibilitychange', visibilityChanged))
onActivated(() => {
suspended = false
if (props.active) void refresh()
})
onDeactivated(() => {
suspended = true
clearTimeout(timer)
generation++
abort?.abort()
abort = new AbortController()
loading.value = false
})
onBeforeUnmount(() => {
generation++
clearTimeout(timer)
abort?.abort()
document.removeEventListener('visibilitychange', visibilityChanged)
})
</script>
<style scoped>
.comparison-panel {
margin: 16px 0 24px;
}
.comparison-heading {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
flex-wrap: wrap;
}
.comparison-heading h3 {
margin: 0 0 6px;
}
.comparison-buttons {
display: flex;
align-items: center;
gap: 10px;
flex-wrap: wrap;
}
.comparison-options {
margin-top: 18px;
}
.plan-select {
max-width: 620px;
}
.comparison-fields {
display: grid;
grid-template-columns: repeat(3, minmax(140px, 1fr));
gap: 16px;
}
.comparison-fields :deep(.el-select),
.comparison-fields :deep(.el-input-number) {
width: 100%;
}
.comparison-report {
margin: 0 0 12px;
}
.comparison-preprocessing {
padding-top: 12px;
border-top: 1px solid var(--el-border-color-lighter);
}
.comparison-preprocessing h4 {
margin: 0 0 8px;
font-size: 14px;
font-weight: 500;
}
.comparison-preprocessing .el-checkbox {
display: flex;
margin-right: 0;
}
.comparison-status {
padding: 14px 0;
border-top: 1px solid var(--el-border-color-lighter);
}
.comparison-status p {
margin: 10px 0;
}
.comparison-error {
color: var(--el-color-warning);
white-space: pre-wrap;
}
.comparison-blockers {
padding-left: 18px;
margin: 8px 0 0;
}
.comparison-blockers li {
margin: 7px 0;
line-height: 1.6;
}
.comparison-blockers .el-button {
height: auto;
margin-left: 12px;
white-space: normal;
}
.comparison-ready {
font-size: 13px;
color: var(--el-color-success);
}
.secondary {
font-size: 12px;
color: var(--el-text-color-secondary);
overflow-wrap: anywhere;
}
.gap {
margin-top: 16px;
}
@media (width <= 700px) {
.comparison-fields {
grid-template-columns: 1fr;
}
}
</style>