<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="isMock ? '/mock/dashboard' : '/dashboard'">首页</router-link></el-breadcrumb-item>
          <el-breadcrumb-item><router-link :to="isMock ? '/mock/worker' : '/worker'">工人管理</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.code}}</el-descriptions-item>
          <el-descriptions-item label="姓名">{{detail.name}}</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-item label="绑定机床数">{{detail.machineCount||0}}</el-descriptions-item>
        </el-descriptions>
      </el-card></el-col>
      <el-col :span="12"><el-card shadow="hover"><template #header><span>7天产量趋势</span></template>
        <div ref="chartRef" style="height:200px"></div>
      </el-card></el-col>
    </el-row>
    <el-card shadow="hover" class="mt-20"><template #header><span>绑定机床</span></template>
      <el-table :data="machines" border stripe size="small">
        <el-table-column label="机床名称"><template #default="{row}"><router-link :to="machineDetailPath(row)" style="color: var(--el-color-primary); cursor: pointer; text-decoration: none;">{{row.machineName}}</router-link></template></el-table-column>
        <el-table-column prop="deviceCode" label="device_code"/><el-table-column prop="workshopName" label="车间"/><el-table-column prop="brandName" label="品牌"/>
        <el-table-column label="在线" align="center"><template #default="{row}"><el-tag :type="row.isOnline?'success':'danger'" size="small">{{row.isOnline?'在线':'离线'}}</el-tag></template></el-table-column>
        <el-table-column prop="programName" label="当前程序"/>
      </el-table>
    </el-card>
    <el-card shadow="hover" class="mt-20"><template #header><span>今日产量</span></template>
      <el-table :data="todayProd" border stripe size="small">
        <el-table-column prop="machineName" label="机床名称"/><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>
  </div>
</template>
<script setup lang="ts">
import { useMockPath } from '@/composables/useMockPath'
import PageHeader from '@/components/PageHeader.vue'
import type { ApiResponse, Worker } from '@/types'
import {ref,onMounted,nextTick,onBeforeUnmount} from 'vue'
import {useRoute} from 'vue-router'
import request from '@/utils/request'
import echarts from '@/utils/echarts'
// 引入 ECharts 的类型定义，便于 TS 断言
import type { ECharts } from 'echarts/core'
const route=useRoute()
const { isMock } = useMockPath()
const detail=ref<Worker>({} as Worker);const machines=ref<Array<{ machineName: string; deviceCode?: string; workshopName?: string; isOnline?: boolean; programName?: string }>>([]);const todayProd=ref<Array<{ machineName?: string; programName?: string; quantity?: number; runTime?: number }>>([])
const chartRef=ref<HTMLElement>();let chart: ECharts | null = null
async function loadData(){
  const id=route.params.id
  const [d,m,t] = await Promise.all([
    request.get<Worker>(`/admin/worker/${id}`),
    request.get<{ items: any[] }>(`/admin/worker/${id}/machines`),
    request.get<{ items: any[] }>(`/admin/worker/${id}/production/today`),
  ])
  detail.value = d.data || ({} as Worker)
  machines.value = m.data?.items || []
  todayProd.value = t.data?.items || []
  const trend:any=await request.get(`/admin/worker/${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:any)=>i.date.slice(5))},yAxis:{type:'value'},series:[{type:'line',data:items.map((i:any)=>i.quantity),smooth:true,areaStyle:{opacity:0.1}}],tooltip:{trigger:'axis'},grid:{left:40,right:20,top:10,bottom:30}})}
}
onMounted(loadData);onBeforeUnmount(()=>{chart?.dispose()})
function machineDetailPath(row:any){
  const base = window.location.pathname.startsWith('/mock') ? '/mock/machine/' : '/machine/'
  return base + (row.machineId ?? row.id)
}
</script>
