| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141 |
- <script setup lang="ts">
- import { computed, onBeforeUnmount, onMounted, reactive, ref, watch } from 'vue'
- import { ElMessageBox } from 'element-plus'
- import { createAnnotation, deleteAnnotation, deletePretrain, fetchAnnotationConfig, fetchAnnotationsByIds, fetchPeriodDetail, fetchPretrainStatus, fetchQueryOptions, fetchSitePoints, fetchTimePoints, fetchTspluseRuler, fetchWaveWindow, getToken, login as apiLogin, logout as apiLogout, recordPretrain } from './api'
- import PeriodModal from './components/PeriodModal.vue'
- import { fixedAxisRange } from './utils/axis'
- import TimePointStrip from './components/TimePointStrip.vue'
- import WaveChart from './components/WaveChart.vue'
- import { STOPPED_COLOR, statusGradientColor } from './statusColor'
- import { DEVICE_POINT_TO_TYPE, DEVICE_POINTS, PRIMARY_DEVICE_POINT, type Annotation, type AnnotationLabel, type Cycle, type DevicePoint, type MeasurementType, type PeriodDetail, type QueryOption, type SitePoint, type TimePoint, type QueryOptionsResponse, type WaveWindowFile, type WaveWindowResponse } from './types'
- const queryMeta = ref<QueryOptionsResponse | null>(null)
- const selectedDevicePart = ref('')
- const selectedDevicePoints = ref<DevicePoint[]>([PRIMARY_DEVICE_POINT])
- const fileListPoint = ref<DevicePoint | string>(PRIMARY_DEVICE_POINT)
- const minTime = ref('')
- const maxTime = ref('')
- const selectedTimeRangePoint = ref<DevicePoint | ''>('')
- const windowSize = ref(4)
- const maxPoints = ref(200000)
- const noSampling = ref(false)
- const includeStopped = ref(false)
- const abnormalOnly = ref(false)
- const noCycleOnly = ref(false)
- const minStatus = ref<number | null>(null)
- const firstCycleOnly = ref(false)
- const sitePointOptions = ref<SitePoint[]>([])
- const selectedSitePoints = ref<string[]>([])
- const ruler = ref<{ min: number; max: number } | null>(null)
- const timePoints = ref<TimePoint[]>([])
- const referencePoints = ref<TimePoint[]>([])
- const startIndex = ref(0)
- const waveData = ref<WaveWindowResponse | null>(null)
- const chartMode = ref<'split' | 'merge'>('split')
- const chartDirty = ref(false)
- const queryLoading = ref(false)
- const timePointsLoading = ref(false)
- const waveLoading = ref(false)
- const errorMessage = ref('')
- const initialized = ref(false)
- const periodDetail = ref<PeriodDetail | null>(null)
- const periodVisible = ref(false)
- const periodLoading = ref(false)
- const annotationWidth = ref(10)
- const annotations = ref<Annotation[]>([])
- const annotationLoading = ref(false)
- const loggedIn = ref(false)
- const loginLoading = ref(false)
- const loginError = ref('')
- const loginForm = reactive({ username: '', password: '' })
- const waveChartRef = ref<InstanceType<typeof WaveChart> | null>(null)
- const recordedFileIds = ref<number[]>([])
- const recordingFileId = ref<number | null>(null)
- let queryDebounce: ReturnType<typeof setTimeout> | undefined
- let waveRequestId = 0
- const deviceParts = computed(() => queryMeta.value?.deviceParts ?? [])
- const devicePoints = computed(() => queryMeta.value?.devicePoints ?? DEVICE_POINTS)
- const unitNumber = computed(() => {
- const match = /^([789])号机组/.exec(selectedDevicePart.value)
- return match ? match[1] : null
- })
- const isPksMode = computed(() => firstCycleOnly.value && !!unitNumber.value)
- const pointModel = computed({
- get: () => (isPksMode.value
- ? [...selectedDevicePoints.value as unknown as string[], ...selectedSitePoints.value]
- : selectedDevicePoints.value as unknown as string[]),
- set: (value: string[]) => {
- const wave = value.filter((item) => (DEVICE_POINTS as readonly string[]).includes(item)) as DevicePoint[]
- const site = value.filter((item) => !(DEVICE_POINTS as readonly string[]).includes(item))
- selectedDevicePoints.value = wave
- selectedSitePoints.value = site
- },
- })
- const sitePointLabel = (point: SitePoint) => `${point.itemName} ${point.itemDescription}`.trim()
- const SITE_TAB_LABEL = '全场点位'
- const siteDescriptionMap = computed<Record<string, string>>(() => {
- const map: Record<string, string> = {}
- for (const item of sitePointOptions.value) map[item.itemName] = item.itemDescription
- return map
- })
- const siteDescription = (itemName: string) => siteDescriptionMap.value[itemName] || itemName
- const fileTabs = computed(() => {
- if (!isPksMode.value) return selectedDevicePoints.value as unknown as string[]
- return [
- ...selectedDevicePoints.value as unknown as string[],
- ...(selectedSitePoints.value.length ? [SITE_TAB_LABEL] : []),
- ]
- })
- const isSiteTab = computed(() => fileListPoint.value === SITE_TAB_LABEL)
- const windowSiteRows = computed(() => {
- if (!isSiteTab.value) return []
- return (waveData.value?.points ?? []).map((point, index) => ({
- index,
- sampleTime: point.sampleTime,
- values: Object.fromEntries(
- selectedSitePoints.value.map((itemName) => [itemName, point.siteValues?.[itemName] ?? null]),
- ),
- }))
- })
- const devicePointCounts = computed<Record<string, { pre: number | null; ab: number | null }>>(() => {
- const map: Record<string, { pre: number | null; ab: number | null }> = {}
- for (const point of devicePoints.value) {
- const pointName = `${selectedDevicePart.value}${point}`
- map[point] = {
- pre: queryMeta.value?.pretrainCounts?.[pointName] ?? null,
- ab: queryMeta.value?.abnormalCounts?.[pointName] ?? null,
- }
- }
- return map
- })
- function devicePointLabel(point: DevicePoint): string {
- const { pre, ab } = devicePointCounts.value[point] ?? { pre: null, ab: null }
- const inner: string[] = []
- if (pre != null) inner.push(String(pre))
- if (ab != null) inner.push(String(ab))
- return inner.length ? `${point} (${inner.join(' · ')})` : point
- }
- const selectedOptionRows = computed<QueryOption[]>(() => (
- queryMeta.value?.options.filter((row) => (
- row.devicePart === selectedDevicePart.value && selectedDevicePoints.value.includes(row.devicePoint)
- )) ?? []
- ))
- const timeRangeOptions = computed<QueryOption[]>(() => (
- queryMeta.value?.options.filter((row) => row.devicePart === selectedDevicePart.value) ?? []
- ))
- const selectedWindowPoints = computed(() => {
- const slice = timePoints.value.slice(startIndex.value, startIndex.value + stripWindowSize.value)
- return hasReference.value ? [...referencePoints.value, ...slice] : slice
- })
- const hasReference = computed(() => referencePoints.value.length > 0)
- const stripWindowSize = computed(() => Math.max(0, windowSize.value - (hasReference.value ? 1 : 0)))
- const maxStart = computed(() => Math.max(0, timePoints.value.length - stripWindowSize.value))
- const endIndex = computed(() => Math.min(timePoints.value.length, startIndex.value + stripWindowSize.value))
- const statusFilter = computed(() => {
- const list: string[] = []
- if (abnormalOnly.value) list.push('abnormal')
- if (noCycleOnly.value) list.push('no_cycle')
- return list
- })
- const currentCycles = computed(() => waveData.value?.cycles ?? [])
- const pressureAxis = computed(() => {
- const series = waveData.value?.series.find((item) => item.measurementType === '压力')
- if (!series) return null
- return fixedAxisRange('压力', series.min, series.max)
- })
- const currentSource = computed(() => waveData.value?.source ?? timePointsSource.value)
- const timePointsSource = ref<'database' | 'demo'>('demo')
- const availableTypeCount = computed(() => selectedOptionRows.value.reduce((total, row) => total + row.fileCount, 0))
- const annotatedFileIds = computed(() => [...new Set(annotations.value.map((item) => item.waveFileId))])
- const windowFiles = computed(() => (waveData.value?.files ?? []).filter((file) => file.devicePoint === fileListPoint.value))
- const primaryDevicePoint = computed(() => (
- waveData.value?.primaryPoint
- ?? (selectedDevicePoints.value.includes('压力盖侧')
- ? '压力盖侧'
- : selectedDevicePoints.value.includes('压力轴侧')
- ? '压力轴侧'
- : selectedDevicePoints.value[0])
- ))
- function toInputTime(value: string) {
- if (!value) return ''
- return value.replace('T', ' ').slice(0, 19)
- }
- function toApiTime(value: string) {
- return value ? value.replace('T', ' ') + (value.length === 16 ? ':00' : '') : undefined
- }
- function boundsForSelection() {
- const rows = selectedOptionRows.value
- if (!rows.length) return null
- const unionRows = rows.filter((row) => row.devicePoint === PRIMARY_DEVICE_POINT || row.devicePoint === '压力轴侧')
- const effective = unionRows.length ? unionRows : rows
- const min = effective.reduce((latest, row) => (row.minTime > latest ? row.minTime : latest), effective[0].minTime)
- const max = effective.reduce((earliest, row) => (row.maxTime < earliest ? row.maxTime : earliest), effective[0].maxTime)
- return { min: toInputTime(min), max: toInputTime(max) }
- }
- function syncTimeBounds(force = false) {
- const bounds = boundsForSelection()
- if (!bounds) return
- if (force || !minTime.value || minTime.value < bounds.min || minTime.value > bounds.max) minTime.value = bounds.min
- if (force || !maxTime.value || maxTime.value > bounds.max || maxTime.value < bounds.min) maxTime.value = bounds.max
- if (minTime.value > maxTime.value) {
- minTime.value = bounds.min
- maxTime.value = bounds.max
- }
- }
- function formatDateTime(value: string | undefined) {
- if (!value) return '未选择'
- return value.replace('T', ' ').slice(0, 16)
- }
- function statusText() {
- if (timePointsLoading.value) return '正在读取时间点'
- if (waveLoading.value) return '正在整理波形'
- if (!timePoints.value.length) return '等待查询'
- return '窗口已就绪'
- }
- async function loadOptions() {
- queryLoading.value = true
- errorMessage.value = ''
- try {
- const result = await fetchQueryOptions()
- queryMeta.value = result
- selectedDevicePart.value = result.deviceParts[0] ?? ''
- selectedTimeRangePoint.value = ''
- syncTimeBounds(true)
- initialized.value = true
- await loadTimePoints()
- } catch (error) {
- errorMessage.value = error instanceof Error ? error.message : '查询条件读取失败'
- } finally {
- queryLoading.value = false
- }
- }
- async function loadSitePoints() {
- if (!isPksMode.value || !selectedDevicePart.value) {
- sitePointOptions.value = []
- return
- }
- try {
- const result = await fetchSitePoints(selectedDevicePart.value)
- sitePointOptions.value = result.items
- } catch {
- sitePointOptions.value = []
- }
- }
- async function loadTspluseRuler() {
- try {
- ruler.value = await fetchTspluseRuler()
- } catch {
- ruler.value = null
- }
- }
- function firstRunningIndex(): number {
- const index = timePoints.value.findIndex((point) =>
- selectedDevicePoints.value.some((pointName) => (point.files[pointName]?.rpm ?? 0) > 0),
- )
- return index >= 0 ? index : 0
- }
- async function loadTimePoints() {
- if (!selectedDevicePart.value || !selectedDevicePoints.value.length) return
- timePointsLoading.value = true
- waveData.value = null
- errorMessage.value = ''
- try {
- const result = await fetchTimePoints({
- devicePart: selectedDevicePart.value,
- devicePoints: selectedDevicePoints.value,
- minTime: toApiTime(minTime.value),
- maxTime: toApiTime(maxTime.value),
- includeStopped: includeStopped.value,
- minStatus: noCycleOnly.value ? null : minStatus.value,
- statusFilter: statusFilter.value,
- sitePoints: isPksMode.value ? selectedSitePoints.value : [],
- })
- timePoints.value = result.points
- referencePoints.value = result.referencePoints ?? []
- timePointsSource.value = result.source
- startIndex.value = Math.max(
- 0,
- Math.min(firstRunningIndex(), Math.max(0, timePoints.value.length - stripWindowSize.value)),
- )
- chartDirty.value = true
- void loadAnnotations()
- } catch (error) {
- timePoints.value = []
- referencePoints.value = []
- errorMessage.value = error instanceof Error ? error.message : '时间点读取失败'
- } finally {
- timePointsLoading.value = false
- }
- }
- async function loadWaveWindowNow() {
- const points = selectedWindowPoints.value
- if (!points.length || !selectedDevicePart.value) {
- waveData.value = null
- chartDirty.value = false
- return
- }
- const requestId = ++waveRequestId
- waveLoading.value = true
- try {
- const result = await fetchWaveWindow({
- devicePart: selectedDevicePart.value,
- devicePoints: selectedDevicePoints.value,
- points,
- maxPoints: maxPoints.value,
- noSampling: noSampling.value,
- firstCycleOnly: firstCycleOnly.value,
- sitePoints: isPksMode.value ? selectedSitePoints.value : [],
- })
- if (requestId === waveRequestId) {
- waveData.value = result
- chartDirty.value = false
- }
- } catch (error) {
- if (requestId === waveRequestId) errorMessage.value = error instanceof Error ? error.message : '波形读取失败'
- } finally {
- if (requestId === waveRequestId) waveLoading.value = false
- }
- }
- function markChartDirty() {
- chartDirty.value = true
- }
- function scheduleTimePoints() {
- if (!initialized.value) return
- if (queryDebounce) clearTimeout(queryDebounce)
- queryDebounce = setTimeout(() => void loadTimePoints(), 180)
- }
- function formatRange(option: QueryOption) {
- return `${formatDateTime(option.minTime)} ~ ${formatDateTime(option.maxTime)}`
- }
- function onTimeRangeChange(value: DevicePoint | '') {
- if (!value) return
- const row = queryMeta.value?.options.find((item) => (
- item.devicePart === selectedDevicePart.value && item.devicePoint === value
- ))
- if (!row) return
- minTime.value = toInputTime(row.minTime)
- maxTime.value = toInputTime(row.maxTime)
- }
- function onDevicePartChange() {
- selectedTimeRangePoint.value = ''
- selectedSitePoints.value = []
- syncTimeBounds(true)
- scheduleTimePoints()
- }
- function onDevicePointsChange() {
- const points = selectedDevicePoints.value
- if (!points.length) {
- selectedDevicePoints.value = [PRIMARY_DEVICE_POINT]
- return
- }
- syncTimeBounds(true)
- scheduleTimePoints()
- }
- function onTimeChange() {
- if (minTime.value > maxTime.value) {
- errorMessage.value = '开始时间不能晚于结束时间'
- return
- }
- scheduleTimePoints()
- }
- function onStartIndexChange(value: number) {
- startIndex.value = Math.max(0, Math.min(value, maxStart.value))
- markChartDirty()
- }
- function onWindowSizeChange(value: number) {
- windowSize.value = Math.max(1, Math.min(200, Math.round(value || 1)))
- startIndex.value = Math.min(startIndex.value, maxStart.value)
- markChartDirty()
- }
- function resetWindow() {
- startIndex.value = 0
- markChartDirty()
- }
- function pageWindow(direction: -1 | 1) {
- const next = startIndex.value + direction * stripWindowSize.value
- startIndex.value = Math.max(0, Math.min(next, maxStart.value))
- markChartDirty()
- }
- function jumpToIndex(index: number) {
- onStartIndexChange(Number(index))
- }
- type JumpSegment = { text: string; color?: string }
- const jumpOptions = computed(() => timePoints.value.map((point, index) => {
- const text = point.sampleTime.replace('T', ' ')
- const segments: JumpSegment[] = [{ text }]
- const statuses: JumpSegment[] = []
- for (const devicePoint of selectedDevicePoints.value) {
- const file = point.files[devicePoint]
- if (!file || file.status === undefined) continue
- const color = file.rpm <= 0 ? STOPPED_COLOR : statusGradientColor(file.status, ruler.value)
- statuses.push({ text: String(file.status), color })
- }
- if (statuses.length) {
- segments.push({ text: ' (' })
- statuses.forEach((segment, i) => {
- if (i > 0) segments.push({ text: '·', color: '#8b9aa2' })
- segments.push(segment)
- })
- segments.push({ text: ')' })
- }
- const label = statuses.length
- ? `${text} (${statuses.map((segment) => segment.text).join('·')})`
- : text
- return { value: index, segments, label }
- }))
- function sampleTimeStyle(file: WaveWindowFile) {
- if (file.measurementType !== '压力') return undefined
- const color = file.rpm <= 0 ? STOPPED_COLOR : statusGradientColor(file.status, ruler.value)
- return { color }
- }
- function refresh() {
- void loadOptions()
- }
- async function openPeriod(cycle: Cycle) {
- periodVisible.value = true
- periodLoading.value = true
- periodDetail.value = null
- try {
- periodDetail.value = await fetchPeriodDetail(cycle.waveFileId, cycle.periodNo)
- } catch (error) {
- errorMessage.value = error instanceof Error ? error.message : '周期详情读取失败'
- periodVisible.value = false
- } finally {
- periodLoading.value = false
- }
- }
- function closePeriod() {
- periodVisible.value = false
- }
- async function loadAnnotationConfig() {
- try {
- const result = await fetchAnnotationConfig()
- annotationWidth.value = result.annotationWidth
- } catch {
- annotationWidth.value = 10
- }
- }
- async function loadAnnotations() {
- const ids = [...new Set(
- timePoints.value.flatMap((point) => (
- selectedDevicePoints.value
- .map((devicePoint) => point.files[devicePoint]?.id)
- .filter((id): id is number => id != null)
- )),
- )]
- if (!ids.length) {
- annotations.value = []
- return
- }
- try {
- const result = await fetchAnnotationsByIds(ids)
- annotations.value = result.annotations
- } catch {
- annotations.value = []
- }
- }
- type AnnotationBlock = {
- waveFileId: number
- periodStart: number
- periodEnd: number
- sampleIndexStart: number
- sampleIndexEnd: number
- }
- function annotationBlock(cycle: Cycle): AnnotationBlock | null {
- const width = Math.max(1, annotationWidth.value)
- const fileCycles = (waveData.value?.cycles ?? []).filter((item) => item.waveFileId === cycle.waveFileId)
- const maxPeriod = Math.max(1, ...fileCycles.map((item) => item.periodNo))
- let leftBound = 1
- let rightBound = maxPeriod
- const existing = annotations.value
- .filter((item) => item.waveFileId === cycle.waveFileId)
- .sort((a, b) => a.periodStart - b.periodStart)
- for (const item of existing) {
- if (item.periodEnd < cycle.periodNo) {
- leftBound = Math.max(leftBound, item.periodEnd + 1)
- } else if (item.periodStart > cycle.periodNo) {
- rightBound = Math.min(rightBound, item.periodStart - 1)
- } else {
- return null
- }
- }
- if (leftBound > rightBound) return null
- let start = Math.max(leftBound, cycle.periodNo - Math.floor((width - 1) / 2))
- let end = Math.min(rightBound, start + width - 1)
- start = Math.max(leftBound, end - width + 1)
- const startCycle = fileCycles.find((item) => item.periodNo === start)
- const endCycle = fileCycles.find((item) => item.periodNo === end)
- return {
- waveFileId: cycle.waveFileId,
- periodStart: start,
- periodEnd: end,
- sampleIndexStart: startCycle?.startSampleIndex ?? cycle.startSampleIndex,
- sampleIndexEnd: endCycle?.endSampleIndex ?? cycle.endSampleIndex,
- }
- }
- async function chooseLabel(block: AnnotationBlock): Promise<AnnotationLabel | null> {
- try {
- await ElMessageBox.confirm(
- `将在周期 ${block.periodStart} — ${block.periodEnd} 创建标注,请选择样本类型`,
- '创建标注',
- {
- confirmButtonText: '正常样本',
- cancelButtonText: '异常样本',
- distinguishCancelAndClose: true,
- type: 'info',
- closeOnClickModal: false,
- },
- )
- return '正常'
- } catch (action) {
- if (action === 'cancel') return '异常'
- return null
- }
- }
- async function onAnnotationToggle(cycle: Cycle) {
- if (annotationLoading.value) return
- const existing = annotations.value.find((item) => (
- item.waveFileId === cycle.waveFileId && cycle.periodNo >= item.periodStart && cycle.periodNo <= item.periodEnd
- ))
- if (existing) {
- try {
- await ElMessageBox.confirm(
- `取消该标注(${existing.label},周期 ${existing.periodStart} — ${existing.periodEnd})?`,
- '取消标注',
- { confirmButtonText: '取消标注', cancelButtonText: '保留', type: 'warning', closeOnClickModal: false },
- )
- } catch {
- return
- }
- annotationLoading.value = true
- try {
- await deleteAnnotation(existing.id)
- await loadAnnotations()
- } catch (error) {
- errorMessage.value = error instanceof Error ? error.message : '标注取消失败'
- } finally {
- annotationLoading.value = false
- }
- return
- }
- const block = annotationBlock(cycle)
- if (!block) return
- const label = await chooseLabel(block)
- if (!label) return
- annotationLoading.value = true
- try {
- await createAnnotation({
- wave_file_id: block.waveFileId,
- label,
- period_start: block.periodStart,
- period_end: block.periodEnd,
- sample_index_start: block.sampleIndexStart,
- sample_index_end: block.sampleIndexEnd,
- })
- await loadAnnotations()
- } catch (error) {
- errorMessage.value = error instanceof Error ? error.message : '标注创建失败'
- } finally {
- annotationLoading.value = false
- }
- }
- watch(selectedDevicePart, () => {
- if (initialized.value) onDevicePartChange()
- })
- watch(selectedDevicePoints, () => {
- if (initialized.value) onDevicePointsChange()
- }, { deep: true })
- watch([minTime, maxTime], () => {
- if (initialized.value) onTimeChange()
- })
- watch(windowSize, () => {
- if (initialized.value) onWindowSizeChange(windowSize.value)
- })
- watch(noSampling, () => {
- if (initialized.value && selectedWindowPoints.value.length) loadWaveWindowNow()
- })
- watch(includeStopped, () => {
- if (initialized.value) scheduleTimePoints()
- })
- watch(abnormalOnly, () => {
- if (initialized.value) scheduleTimePoints()
- })
- watch(noCycleOnly, () => {
- if (initialized.value) scheduleTimePoints()
- })
- watch(minStatus, () => {
- if (initialized.value) scheduleTimePoints()
- })
- watch(firstCycleOnly, () => {
- if (!initialized.value) return
- windowSize.value = firstCycleOnly.value ? 50 : 4
- markChartDirty()
- void loadWaveWindowNow()
- })
- watch([firstCycleOnly, unitNumber], async () => {
- if (!initialized.value) return
- if (isPksMode.value) {
- await loadSitePoints()
- if (selectedSitePoints.value.length) fileListPoint.value = SITE_TAB_LABEL
- } else {
- sitePointOptions.value = []
- }
- })
- watch(selectedSitePoints, (points) => {
- if (initialized.value && isPksMode.value) scheduleTimePoints()
- if (points.length) fileListPoint.value = SITE_TAB_LABEL
- })
- watch(waveData, () => void refreshPretrainStatus(), { deep: false })
- async function refreshPretrainStatus() {
- const ids = waveData.value?.files.map((file) => file.id) ?? []
- if (!ids.length) {
- recordedFileIds.value = []
- return
- }
- try {
- const result = await fetchPretrainStatus(ids)
- recordedFileIds.value = result.recorded
- } catch {
- recordedFileIds.value = []
- }
- }
- function locateFile(file: WaveWindowFile) {
- waveChartRef.value?.locateFile(file.pointIndex)
- }
- async function recordFile(file: WaveWindowFile) {
- if (recordedFileIds.value.includes(file.id) || recordingFileId.value != null) return
- recordingFileId.value = file.id
- try {
- const result = await recordPretrain({
- id: file.id,
- point_name: file.pointName,
- measurement_type: file.measurementType,
- rpm: file.rpm,
- sample_time: file.sampleTime,
- file_name: file.fileName,
- })
- if (result.recorded || result.already) {
- recordedFileIds.value = [...new Set([...recordedFileIds.value, file.id])]
- }
- } catch (error) {
- errorMessage.value = error instanceof Error ? error.message : '记录失败'
- } finally {
- recordingFileId.value = null
- }
- }
- async function deleteRecordedFile(file: WaveWindowFile) {
- if (!recordedFileIds.value.includes(file.id) || recordingFileId.value != null) return
- recordingFileId.value = file.id
- try {
- await deletePretrain(file.id)
- recordedFileIds.value = recordedFileIds.value.filter((id) => id !== file.id)
- } catch (error) {
- errorMessage.value = error instanceof Error ? error.message : '删除失败'
- } finally {
- recordingFileId.value = null
- }
- }
- async function handleLogin() {
- if (!loginForm.username || !loginForm.password) {
- loginError.value = '请输入账号和密码'
- return
- }
- loginLoading.value = true
- loginError.value = ''
- try {
- await apiLogin(loginForm.username, loginForm.password)
- loggedIn.value = true
- loginForm.password = ''
- await loadOptions()
- void loadTspluseRuler()
- void loadAnnotationConfig()
- } catch (error) {
- loginError.value = error instanceof Error ? error.message : '登录失败'
- } finally {
- loginLoading.value = false
- }
- }
- async function handleLogout() {
- await apiLogout()
- loggedIn.value = false
- waveData.value = null
- timePoints.value = []
- annotations.value = []
- }
- function onAuthExpired() {
- loggedIn.value = false
- waveData.value = null
- timePoints.value = []
- annotations.value = []
- }
- onMounted(() => {
- window.addEventListener('auth-expired', onAuthExpired)
- loggedIn.value = getToken() != null
- if (loggedIn.value) {
- void loadOptions()
- void loadTspluseRuler()
- void loadAnnotationConfig()
- }
- })
- onBeforeUnmount(() => {
- window.removeEventListener('auth-expired', onAuthExpired)
- if (queryDebounce) clearTimeout(queryDebounce)
- })
- </script>
- <template>
- <div v-if="!loggedIn" class="login-shell">
- <form class="login-card" @submit.prevent="handleLogin">
- <div class="login-brand">
- <div class="brand-mark"><span></span><span></span><span></span></div>
- <div>
- <div class="brand-kicker">COMPRESSOR / WAVE LAB</div>
- <h1>故障预测波形工作台</h1>
- </div>
- </div>
- <p class="login-hint">请登录后继续使用</p>
- <el-input v-model="loginForm.username" class="login-input" size="large" placeholder="账号" clearable @input="loginError = ''" />
- <el-input v-model="loginForm.password" class="login-input" size="large" type="password" show-password placeholder="密码" @keyup.enter="handleLogin" @input="loginError = ''" />
- <el-alert v-if="loginError" class="login-error" type="error" :closable="false" show-icon :title="loginError" />
- <el-button class="login-button" type="primary" size="large" :loading="loginLoading" native-type="submit">登 录</el-button>
- </form>
- </div>
- <div v-else class="app-shell">
- <header class="app-header">
- <div class="brand-lockup">
- <div class="brand-mark"><span></span><span></span><span></span></div>
- <div>
- <div class="brand-kicker">COMPRESSOR / WAVE LAB</div>
- <h1>故障预测波形工作台</h1>
- </div>
- </div>
- <div class="header-meta">
- <span class="live-indicator"><i></i> 浏览模式</span>
- <span class="header-date">{{ selectedDevicePart || '未选择机组与部位' }}</span>
- <el-button class="header-refresh" type="primary" plain :loading="queryLoading" @click="refresh">刷新</el-button>
- <el-button class="header-logout" plain @click="handleLogout">退出登录</el-button>
- </div>
- </header>
- <main class="workspace">
- <section class="query-panel panel">
- <div class="panel-heading compact-heading">
- <div>
- <h2>查询条件</h2>
- </div>
- <el-tag class="connection-badge" :type="currentSource === 'database' ? 'success' : 'warning'" effect="plain">
- {{ currentSource === 'database' ? '数据库已连接' : '演示数据' }}
- </el-tag>
- </div>
- <div class="query-grid">
- <label class="field field-point">
- <span class="field-label">机组与部位</span>
- <el-select
- v-model="selectedDevicePart"
- class="query-control"
- size="large"
- filterable
- :disabled="queryLoading"
- placeholder="输入机组、气缸或部位关键词"
- filter-placeholder="搜索机组与部位"
- >
- <el-option v-for="devicePart in deviceParts" :key="devicePart" :label="devicePart" :value="devicePart" />
- </el-select>
- </label>
- <div class="field field-types">
- <span class="field-label">测试点位</span>
- <el-select
- v-model="pointModel"
- class="query-control"
- size="large"
- multiple
- collapse-tags
- collapse-tags-tooltip
- :max-collapse-tags="2"
- placeholder="选择测试点位"
- >
- <template v-if="isPksMode">
- <el-option-group label="波形点位">
- <el-option
- v-for="point in devicePoints"
- :key="point"
- :label="devicePointLabel(point)"
- :value="point"
- >
- <span>{{ point }}</span>
- <template v-if="devicePointCounts[point]?.pre !== null || devicePointCounts[point]?.ab !== null">
- <span class="point-counts">
- (<span v-if="devicePointCounts[point]?.pre !== null">{{ devicePointCounts[point]?.pre }}</span><template v-if="devicePointCounts[point]?.pre !== null && devicePointCounts[point]?.ab !== null"> · </template><span v-if="devicePointCounts[point]?.ab !== null" class="abnormal-count">{{ devicePointCounts[point]?.ab }}</span>)
- </span>
- </template>
- </el-option>
- </el-option-group>
- <el-option-group label="全场点位 (PKS)">
- <el-option
- v-for="point in sitePointOptions"
- :key="point.itemName"
- :value="point.itemName"
- :label="sitePointLabel(point)"
- />
- </el-option-group>
- </template>
- <template v-else>
- <el-option
- v-for="point in devicePoints"
- :key="point"
- :label="devicePointLabel(point)"
- :value="point"
- >
- <span>{{ point }}</span>
- <template v-if="devicePointCounts[point]?.pre !== null || devicePointCounts[point]?.ab !== null">
- <span class="point-counts">
- (<span v-if="devicePointCounts[point]?.pre !== null">{{ devicePointCounts[point]?.pre }}</span><template v-if="devicePointCounts[point]?.pre !== null && devicePointCounts[point]?.ab !== null"> · </template><span v-if="devicePointCounts[point]?.ab !== null" class="abnormal-count">{{ devicePointCounts[point]?.ab }}</span>)
- </span>
- </template>
- </el-option>
- </template>
- </el-select>
- </div>
- <label class="field">
- <span class="field-label">开始时间</span>
- <el-date-picker
- v-model="minTime"
- class="query-control"
- size="large"
- type="datetime"
- value-format="YYYY-MM-DD HH:mm:ss"
- format="YYYY-MM-DD HH:mm:ss"
- :disabled="queryLoading"
- :disabled-date="(date: Date) => date < new Date(`${boundsForSelection()?.min ?? '1970-01-01 00:00:00'}`) || date > new Date(`${boundsForSelection()?.max ?? '2999-12-31 23:59:59'}`)"
- placeholder="选择开始时间"
- />
- </label>
- <label class="field">
- <span class="field-label">结束时间</span>
- <el-date-picker
- v-model="maxTime"
- class="query-control"
- size="large"
- type="datetime"
- value-format="YYYY-MM-DD HH:mm:ss"
- format="YYYY-MM-DD HH:mm:ss"
- :disabled="queryLoading"
- :disabled-date="(date: Date) => date < new Date(`${boundsForSelection()?.min ?? '1970-01-01 00:00:00'}`) || date > new Date(`${boundsForSelection()?.max ?? '2999-12-31 23:59:59'}`)"
- placeholder="选择结束时间"
- />
- </label>
- <el-button class="query-action query-button" type="primary" size="large" :loading="timePointsLoading" :disabled="!selectedDevicePart" @click="loadTimePoints">
- 查询时间点
- </el-button>
- <div class="query-row-2">
- <label class="field field-check">
- <span class="field-label">运行状态</span>
- <el-checkbox v-model="includeStopped" class="query-checkbox" size="large">停机</el-checkbox>
- <el-checkbox v-model="abnormalOnly" class="query-checkbox" size="large">异常</el-checkbox>
- <el-checkbox v-model="noCycleOnly" class="query-checkbox" size="large">无周期</el-checkbox>
- </label>
- <div class="field-second-group">
- <label class="field field-status">
- <span class="field-label">质心距离</span>
- <el-input-number
- v-model="minStatus"
- class="query-control"
- size="large"
- :min="0"
- :max="4"
- :step="1"
- :step-strictly="true"
- controls-position="right"
- :disabled="queryLoading || noCycleOnly"
- clearable
- placeholder="可空"
- :title="noCycleOnly ? '勾选无周期时忽略质心距离' : undefined"
- />
- </label>
- <label class="field field-first-cycle">
- <span class="field-label">首个周期</span>
- <el-checkbox v-model="firstCycleOnly" class="query-checkbox" size="large" :disabled="queryLoading">连续曲线</el-checkbox>
- </label>
- </div>
- <label class="field window-field">
- <span class="field-label">时间窗口 <em>文件数量</em></span>
- <el-input-number
- v-model="windowSize"
- class="query-control window-number"
- size="large"
- :min="1"
- :max="200"
- controls-position="right"
- :disabled="queryLoading"
- />
- </label>
- <label class="field field-time-range">
- <span class="field-label">时间段</span>
- <el-select
- v-model="selectedTimeRangePoint"
- class="query-control"
- size="large"
- clearable
- filterable
- :disabled="queryLoading"
- placeholder="选择测试点位"
- filter-placeholder="搜索测试点位"
- @change="onTimeRangeChange"
- >
- <el-option
- v-for="option in timeRangeOptions"
- :key="option.devicePoint"
- :value="option.devicePoint"
- :label="`${option.devicePoint} ${formatRange(option)}`"
- />
- </el-select>
- </label>
- </div>
- </div>
- <el-alert v-if="errorMessage" class="data-alert" type="error" :closable="false" show-icon :title="errorMessage" />
- </section>
- <section class="selection-panel panel">
- <TimePointStrip
- :points="timePoints"
- :device-points="selectedDevicePoints"
- :point-to-type="DEVICE_POINT_TO_TYPE"
- :start-index="startIndex"
- :window-size="stripWindowSize"
- :loading="timePointsLoading"
- :min-time="minTime"
- :max-time="maxTime"
- :annotated-file-ids="annotatedFileIds"
- :ruler="ruler"
- :site-points="isPksMode ? selectedSitePoints : []"
- :site-descriptions="siteDescriptionMap"
- @update:start-index="onStartIndexChange"
- />
- <div class="selection-controls">
- <div class="selection-readout">
- <span class="selection-accent"></span>
- <span>当前窗口覆盖 <strong>{{ selectedWindowPoints.length }}</strong> 个时间点</span>
- <span v-if="hasReference" class="reference-badge" title="始终保留一个 status=0 的正常数据用于对比,固定不随翻页变化">
- 正常对比:{{ formatDateTime(referencePoints[0]?.sampleTime) }}
- </span>
- </div>
- <div class="selection-actions">
- <el-button class="ghost-button" plain :disabled="!startIndex" @click="resetWindow">回到起点</el-button>
- <el-button class="ghost-button" plain :disabled="startIndex <= 0" @click="pageWindow(-1)">上一页</el-button>
- <el-button class="ghost-button" plain :disabled="startIndex >= timePoints.length - windowSize" @click="pageWindow(1)">下一页</el-button>
- <el-select-v2
- class="jump-select"
- :options="jumpOptions"
- :model-value="startIndex"
- :disabled="!timePoints.length"
- size="small"
- filterable
- placeholder="跳转"
- @update:model-value="jumpToIndex"
- >
- <template #default="{ item }">
- <template v-for="(segment, segmentIndex) in item.segments" :key="segmentIndex">
- <span v-if="segment.color" :style="{ color: segment.color }">{{ segment.text }}</span>
- <span v-else>{{ segment.text }}</span>
- </template>
- </template>
- </el-select-v2>
- <el-button
- class="ghost-button chart-query"
- :class="{ 'is-dirty': chartDirty }"
- type="primary"
- plain
- :loading="waveLoading"
- :disabled="waveLoading || !selectedWindowPoints.length"
- @click="loadWaveWindowNow"
- >查询图表</el-button>
- </div>
- </div>
- <div v-if="(waveData?.files.length || windowSiteRows.length)" class="window-files">
- <div class="window-files-title">
- <span>{{ isSiteTab ? '当前窗口 全场点位记录' : '当前窗口 wave_file 记录' }}</span>
- <el-radio-group v-model="fileListPoint" class="file-point-radio" size="small">
- <el-radio-button v-for="point in fileTabs" :key="point" :value="point">{{ point }}</el-radio-button>
- </el-radio-group>
- </div>
- <div class="window-files-scroll">
- <table v-if="isSiteTab" class="window-files-table">
- <thead>
- <tr>
- <th>#</th>
- <th>sample_time</th>
- <th v-for="itemName in selectedSitePoints" :key="itemName" :title="itemName">{{ siteDescription(itemName) }}</th>
- </tr>
- </thead>
- <tbody>
- <tr v-for="row in windowSiteRows" :key="row.index">
- <td class="mono">{{ row.index + 1 }}</td>
- <td class="mono">{{ row.sampleTime }}</td>
- <td v-for="itemName in selectedSitePoints" :key="itemName" class="mono">{{ row.values[itemName] ?? '—' }}</td>
- </tr>
- </tbody>
- </table>
- <table v-else class="window-files-table">
- <thead>
- <tr>
- <th>id</th>
- <th>point_name</th>
- <th>测试点位</th>
- <th>measurement_type</th>
- <th>rpm</th>
- <th>sample_time</th>
- <th>tspluse_status</th>
- <th>file_name</th>
- <th>操作</th>
- </tr>
- </thead>
- <tbody>
- <tr v-for="file in windowFiles" :key="file.id">
- <td class="mono">{{ file.id }}</td>
- <td>{{ file.pointName }}</td>
- <td>{{ file.devicePoint }}</td>
- <td>{{ file.measurementType }}</td>
- <td class="mono">{{ file.rpm }}</td>
- <td class="mono" :style="sampleTimeStyle(file)">{{ file.sampleTime.replace('T', ' ') }}</td>
- <td class="mono">{{ file.status ?? '' }}</td>
- <td class="file-name" :title="file.fileName">{{ file.fileName || '—' }}</td>
- <td class="actions">
- <el-button class="file-action" size="small" plain :disabled="!waveData" @click="locateFile(file)">定位</el-button>
- <el-button
- v-if="!recordedFileIds.includes(file.id)"
- class="file-action"
- size="small"
- type="primary"
- plain
- :loading="recordingFileId === file.id"
- @click="recordFile(file)"
- >记录</el-button>
- <el-button
- v-else
- class="file-action"
- size="small"
- type="danger"
- plain
- :loading="recordingFileId === file.id"
- @click="deleteRecordedFile(file)"
- >删除</el-button>
- </td>
- </tr>
- </tbody>
- </table>
- </div>
- </div>
- </section>
- <section class="chart-panel panel">
- <div class="panel-heading chart-heading">
- <div>
- <h2>波形预览</h2>
- </div>
- <div class="chart-actions">
- <span class="annotation-width">标度宽度:<strong>{{ annotationWidth }}</strong></span>
- <el-radio-group v-model="chartMode" class="mode-switch" size="small">
- <el-radio-button label="split">分图显示</el-radio-button>
- <el-radio-button label="merge">归一合并</el-radio-button>
- </el-radio-group>
- <el-switch
- v-model="noSampling"
- class="sampling-switch"
- size="small"
- active-text="不采样"
- inactive-text="采样"
- :disabled="waveLoading"
- />
- <div class="chart-status"><i :class="{ busy: waveLoading }"></i>{{ statusText() }}</div>
- </div>
- </div>
- <WaveChart
- ref="waveChartRef"
- :data="waveData"
- :points="selectedWindowPoints"
- :mode="chartMode"
- :loading="waveLoading"
- :annotations="annotations"
- :site-descriptions="siteDescriptionMap"
- @period-dblclick="openPeriod"
- @annotation-toggle="onAnnotationToggle"
- />
- </section>
- <aside class="insight-panel panel">
- <div class="panel-heading compact-heading">
- <div><h2>当前窗口</h2></div>
- <span class="readout-number">{{ String(selectedWindowPoints.length).padStart(2, '0') }}</span>
- </div>
- <div class="readout-grid">
- <div class="readout-card">
- <span>时间跨度</span>
- <div class="readout-value">
- <strong>{{ formatDateTime(selectedWindowPoints[0]?.sampleTime) }}</strong>
- <small>至 {{ formatDateTime(selectedWindowPoints[selectedWindowPoints.length - 1]?.sampleTime) }}</small>
- </div>
- </div>
- <div class="readout-card"><span>检测周期</span><strong>{{ currentCycles.length }}</strong></div>
- <div class="readout-card"><span>选择范围</span><strong>#{{ startIndex + 1 }} — #{{ endIndex }}</strong></div>
- <div class="readout-card"><span>显示策略</span><strong>MIN / MAX</strong></div>
- </div>
- <div class="data-footprint">
- <div><span>测试点位</span><strong>{{ [...selectedDevicePoints, ...(isPksMode ? selectedSitePoints : [])].join(' / ') || '未选择' }}</strong></div>
- <div><span>可用文件</span><strong>{{ availableTypeCount.toLocaleString() }}</strong></div>
- <div><span>抽样上限</span><strong>{{ maxPoints.toLocaleString() }} 点</strong></div>
- </div>
- </aside>
- </main>
- <PeriodModal :visible="periodVisible" :detail="periodDetail" :loading="periodLoading" :pressure-axis="pressureAxis" @close="closePeriod" />
- </div>
- </template>
|