<template>
  <div>
    <!-- 使用 PageHeader 统一头部：包含返回键、标题和面包屑插槽 -->
    <PageHeader :title="`机床详情：${detail.name}`" :showBack="true">
      <template #breadcrumb>
        <el-breadcrumb separator="/" style="margin: 0 0 12px 0;">
          <el-breadcrumb-item><router-link :to="homePath">首页</router-link></el-breadcrumb-item>
          <el-breadcrumb-item><router-link :to="machinePath">设备管理</router-link></el-breadcrumb-item>
          <el-breadcrumb-item>{{ detail.name || '机床详情' }}</el-breadcrumb-item>
        </el-breadcrumb>
      </template>
    </PageHeader>
    <el-row :gutter="20">
      <el-col :span="12"><el-card shadow="hover"><template #header><span>基本信息</span></template>
        <el-descriptions :column="2" border size="small">
          <el-descriptions-item label="机床名称">{{detail.name}}</el-descriptions-item>
          <el-descriptions-item label="device_code">{{detail.deviceCode}}</el-descriptions-item>
          <el-descriptions-item label="车间">{{detail.workshopName}}</el-descriptions-item>
          <el-descriptions-item label="品牌">{{detail.brandName}}</el-descriptions-item>
          <el-descriptions-item label="IP地址">{{detail.ipAddress}}</el-descriptions-item>
          <el-descriptions-item label="绑定工人">{{detail.workerName||'-'}}</el-descriptions-item>
          <el-descriptions-item label="在线"><el-tag :type="detail.isOnline?'success':'danger'" size="small">{{detail.isOnline?'在线':'离线'}}</el-tag></el-descriptions-item>
          <el-descriptions-item label="启用"><el-tag :type="detail.isEnabled?'success':'danger'" size="small">{{detail.isEnabled?'启用':'停用'}}</el-tag></el-descriptions-item>
        </el-descriptions>
      </el-card></el-col>
      <el-col :span="12"><el-card shadow="hover"><template #header><span>实时状态</span></template>
        <el-descriptions :column="2" border size="small">
          <el-descriptions-item label="NC程序名">{{status.programName||'-'}}</el-descriptions-item>
          <el-descriptions-item label="零件数">{{status.partCount??'-'}}</el-descriptions-item>
          <el-descriptions-item label="运行状态">{{status.runStatus||'-'}}</el-descriptions-item>
          <el-descriptions-item label="操作模式">{{status.operationMode||'-'}}</el-descriptions-item>
          <el-descriptions-item label="主轴设定">{{status.spindleSpeedSet??'-'}}</el-descriptions-item>
          <el-descriptions-item label="进给设定">{{status.feedSpeedSet??'-'}}</el-descriptions-item>
          <el-descriptions-item label="主轴实际">{{status.spindleSpeedActual??'-'}}</el-descriptions-item>
          <el-descriptions-item label="主轴负载">{{status.spindleLoad??'-'}}%</el-descriptions-item>
        </el-descriptions>
      </el-card></el-col>
    </el-row>
    <el-row :gutter="20" class="mt-20">
      <el-col :span="12"><el-card shadow="hover"><template #header><span>今日产量</span></template>
        <el-table :data="todayProd" border stripe size="small">
          <el-table-column prop="programName" label="程序名"/><el-table-column prop="quantity" label="产量" align="center"/><el-table-column prop="runTime" label="运行时间" align="center"/><el-table-column prop="cuttingTime" label="切削时间" align="center"/>
        </el-table>
      </el-card></el-col>
      <el-col :span="12"><el-card shadow="hover"><template #header><span>7天产量趋势</span></template>
        <div ref="chartRef" style="height:250px"></div>
      </el-card></el-col>
    </el-row>
    <el-card shadow="hover" class="mt-20"><template #header><span>最近采集记录</span></template>
      <el-table :data="records" border stripe size="small">
        <el-table-column prop="collectTime" label="采集时间"/><el-table-column prop="programName" label="程序名"/><el-table-column prop="partCount" label="零件数" align="center"/><el-table-column prop="runStatus" label="运行状态"/>
      </el-table>
    </el-card>
  </div>
</template>
<script setup lang="ts">
import PageHeader from '@/components/PageHeader.vue'
import { ref, onMounted, nextTick, onBeforeUnmount } from 'vue'
import { useRoute } from 'vue-router'
import request from '@/utils/request'
import echarts from '@/utils/echarts'
import type { ECharts } from 'echarts/core'
import type { ApiResponse, Machine, MachineStatus } from '@/types'

/** 今日产量行 */
interface TodayProdRow { programName: string; quantity: number; runTime: number; cuttingTime: number }
/** 采集记录行 */
interface CollectRecordRow { collectTime: string; programName: string; partCount: number; runStatus: string }
/** 趋势数据项 */
interface TrendItem { date: string; quantity: number }

const route = useRoute()
// Mock 模式路径前缀处理
const isMockPath = typeof window !== 'undefined' && window.location.pathname.startsWith('/mock')
const homePath = isMockPath ? '/mock/dashboard' : '/dashboard'
const machinePath = isMockPath ? '/mock/machine' : '/machine'
const detail = ref<Machine>({} as Machine)
const status = ref<MachineStatus>({} as MachineStatus)
let statusInterval: number | undefined
const todayProd = ref<TodayProdRow[]>([])
const records = ref<CollectRecordRow[]>([])
const chartRef = ref<HTMLElement>()
let chart: ECharts | null = null

async function loadData() {
  const id = route.params.id
  const [d, s, t, r] = await Promise.all([
    request.get<Machine>(`/admin/machine/${id}`),
    request.get<MachineStatus>(`/admin/machine/${id}/status`),
    request.get<{ items: TodayProdRow[] }>(`/admin/machine/${id}/production/today`),
    request.get<{ items: CollectRecordRow[] }>(`/admin/machine/${id}/collect-records`),
  ])
  detail.value = d.data || {} as Machine
  status.value = s.data || {} as MachineStatus
  todayProd.value = t.data?.items || []
  records.value = r.data?.items || []
  const trend = await request.get<{ items: TrendItem[] }>(`/admin/machine/${id}/production/trend`)
  await nextTick()
  if (chartRef.value) {
    chart = echarts.init(chartRef.value)
    const items = trend.data?.items || []
    chart.setOption({ xAxis: { type: 'category', data: items.map((i: TrendItem) => i.date.slice(5)) }, yAxis: { type: 'value' }, series: [{ type: 'line', data: items.map((i: TrendItem) => i.quantity), smooth: true, areaStyle: { opacity: 0.1 } }], tooltip: { trigger: 'axis' }, grid: { left: 40, right: 20, top: 10, bottom: 30 } })
  }
}

async function fetchStatus() {
  const id = route.params.id
  const r = await request.get<MachineStatus>(`/admin/machine/${id}/status`)
  status.value = r.data || {} as MachineStatus
}

onMounted(() => {
  loadData()
  // 启动实时状态轮询，每10秒刷新一次
  statusInterval = window.setInterval(fetchStatus, 10000)
  // 初次进入时也刷新一次状态，保证信息及时
  fetchStatus()
})
onBeforeUnmount(() => { chart?.dispose(); if (typeof statusInterval !== 'undefined') clearInterval(statusInterval) })
</script>
