<template>
  <div class="machine-production">
    <!-- 筛选栏 -->
    <el-form :inline="true" :model="filters" class="filter-bar">
      <el-form-item label="日期范围">
        <el-date-picker
          v-model="filters.dateRange"
          type="daterange"
          value-format="YYYY-MM-DD"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </el-form-item>
      <el-form-item label="车间">
        <el-select v-model="filters.workshopId" placeholder="请选择车间" clearable style="min-width:200px">
          <el-option
            v-for="w in options.workshops"
            :key="w.id"
            :label="w.name"
            :value="w.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="机床">
        <el-select
          v-model="filters.machineId"
          placeholder="请选择机床"
          clearable
          filterable
          style="min-width:200px"
        >
          <el-option
            v-for="m in options.machines"
            :key="m.id"
            :label="m.name"
            :value="m.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="loadData">查询</el-button>
        <el-button @click="resetFilters">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 统计卡片 -->
    <el-row :gutter="16" class="stat-row">
      <el-col :span="6">
        <el-card shadow="hover">
          <div class="stat-card">
            <div class="stat-label">
              总产量
              <el-tooltip content="选定时间范围内所有机床的总产量。" placement="top">
                <span class="info-icon">ⓘ</span>
              </el-tooltip>
            </div>
            <div class="stat-value">
              {{ summary.totalQuantity != null ? summary.totalQuantity.toLocaleString() : '-' }}
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <div class="stat-card">
            <div class="stat-label">
              运行机床数
              <el-tooltip content="选定时间范围内有产量记录的机床数量。" placement="top">
                <span class="info-icon">ⓘ</span>
              </el-tooltip>
            </div>
            <div class="stat-value">
              {{ summary.runningMachineCount != null ? summary.runningMachineCount : '-' }}
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <div class="stat-card">
            <div class="stat-label">
              平均单产
              <el-tooltip content="平均每台机床的产量。" placement="top">
                <span class="info-icon">ⓘ</span>
              </el-tooltip>
            </div>
            <div class="stat-value">
              {{ summary.avgPerMachine != null ? summary.avgPerMachine.toFixed(2) : '-' }}
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <div class="stat-card">
            <div class="stat-label">
              最高单产机床
              <el-tooltip content="产量最高的机床名称。" placement="top">
                <span class="info-icon">ⓘ</span>
              </el-tooltip>
            </div>
            <div class="stat-value top-machine-name">
              {{ summary.topMachineName || '-' }}
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表行 -->
    <el-row :gutter="16" class="chart-row">
      <el-col :span="12">
        <el-card shadow="hover">
          <template #header>
            <span class="card-title">机床产量柱状图</span>
          </template>
          <div ref="barChartRef" style="height: 300px"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card shadow="hover">
          <template #header>
            <span class="card-title">各机床产量占比</span>
          </template>
          <div ref="pieChartRef" style="height: 300px"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 明细表格 -->
    <el-card shadow="hover" class="table-card">
      <template #header>
        <span class="card-title">明细排行</span>
      </template>
      <el-table :data="tableData" stripe size="small" v-loading="loading">
        <el-table-column prop="rank" label="排名" width="60" align="center" />
        <el-table-column prop="machineName" label="机床名称" width="120" />
        <el-table-column prop="programName" label="程序名" show-overflow-tooltip />
        <el-table-column prop="totalQuantity" label="产量" width="100" align="center" />
        <el-table-column label="运行时间" width="100" align="center">
          <template #default="{ row }">{{ row.runTime }}h</template>
        </el-table-column>
        <el-table-column prop="dayStatus" label="日状态" width="80" align="center" />
      </el-table>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onBeforeUnmount, nextTick } from 'vue'
import request from '@/utils/request'
import echarts from '@/utils/echarts'
import type { ECharts } from 'echarts/core'
import type { ApiResponse } from '@/types'

/** 机床产量汇总 */
interface MachineProductionSummary {
  totalQuantity: number
  runningMachineCount: number
  avgPerMachine: number
  topMachineName: string
}

/** 机床产量排行条目 */
interface MachineProductionItem {
  rank: number
  machineName: string
  programName: string
  totalQuantity: number
  runTime: number
  dayStatus: string
}

/** 下拉选项 */
interface DropdownOption {
  id: number
  name: string
}

// ---------- 状态 ----------
const loading = ref(false)
const tableData = ref<MachineProductionItem[]>([])
const summary = ref<Partial<MachineProductionSummary>>({})

const filters = reactive({
  dateRange: [] as string[],
  workshopId: '' as string | number,
  machineId: '' as string | number,
})

const options = reactive({
  workshops: [] as DropdownOption[],
  machines: [] as DropdownOption[],
})

// ---------- ECharts ----------
const barChartRef = ref<HTMLElement>()
const pieChartRef = ref<HTMLElement>()
let barChart: ECharts | null = null
let pieChart: ECharts | null = null

/** 初始化柱状图 */
function initBarChart() {
  if (!barChartRef.value || !tableData.value.length) return
  if (barChart) barChart.dispose()
  barChart = echarts.init(barChartRef.value)
  const names = tableData.value.map((i) => i.machineName)
  const quantities = tableData.value.map((i) => i.totalQuantity)
  barChart.setOption({
    tooltip: {
      trigger: 'axis',
      formatter: (params: { name: string; value: number }[]) => {
        const item = params[0]
        return `${item.name}<br/>产量: ${item.value} 件`
      },
    },
    grid: { left: 50, right: 20, top: 20, bottom: 40 },
    xAxis: {
      type: 'category',
      data: names,
      axisLabel: { fontSize: 12, rotate: names.length > 6 ? 30 : 0 },
    },
    yAxis: { type: 'value', name: '件', axisLabel: { fontSize: 12 } },
    series: [
      {
        type: 'bar',
        data: quantities,
        itemStyle: {
          color: '#409EFF',
          borderRadius: [4, 4, 0, 0],
        },
        barWidth: '50%',
      },
    ],
  })
}

/** 初始化饼图 */
function initPieChart() {
  if (!pieChartRef.value || !tableData.value.length) return
  if (pieChart) pieChart.dispose()
  pieChart = echarts.init(pieChartRef.value)
  const pieData = tableData.value.map((i) => ({
    value: i.totalQuantity,
    name: i.machineName,
  }))
  pieChart.setOption({
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c}件 ({d}%)',
    },
    series: [
      {
        type: 'pie',
        radius: ['40%', '65%'],
        center: ['50%', '50%'],
        label: {
          show: true,
          formatter: '{b}: {c}件 ({d}%)',
          fontSize: 12,
        },
        data: pieData,
        emphasis: {
          label: { fontSize: 14, fontWeight: 'bold' },
        },
      },
    ],
  })
}

/** 销毁所有图表 */
function disposeCharts() {
  barChart?.dispose()
  pieChart?.dispose()
  barChart = null
  pieChart = null
}

// ---------- 数据加载 ----------
/** 格式化日期 */
function fmtDate(d: Date): string {
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
}

/** 加载下拉选项 */
async function loadOptions() {
  try {
    const [wsRes, mcRes] = await Promise.all([
      request.get<{ items: DropdownOption[] }>('/admin/workshop/list'),
      request.get<{ items: DropdownOption[] }>('/admin/machine/list'),
    ])
    options.workshops = wsRes.data?.items ?? []
    options.machines = mcRes.data?.items ?? []
  } catch {
    // 保持容错，无法获取下拉项时不阻塞页面
  }
}

/** 核心加载函数：同时请求汇总和明细 */
async function loadData() {
  loading.value = true
  try {
    const params: Record<string, string | number> = {
      startDate: filters.dateRange[0] ?? '',
      endDate: filters.dateRange[1] ?? '',
      workshopId: filters.workshopId ?? '',
      machineId: filters.machineId ?? '',
    }

    const [summaryRes, listRes] = await Promise.all([
      request.get<MachineProductionSummary>(
        '/admin/production/machine/summary',
        { params }
      ),
      request.get<{ items: MachineProductionItem[] }>(
        '/admin/production/machine/list',
        { params }
      ),
    ])

    summary.value = summaryRes.data ?? {}
    tableData.value = listRes.data?.items ?? []

    // 图表刷新
    disposeCharts()
    await nextTick()
    initBarChart()
    initPieChart()
  } catch {
    // API 不存在时 catch 错误不阻塞
  } finally {
    loading.value = false
  }
}

/** 重置筛选条件并重新加载 */
function resetFilters() {
  const today = new Date()
  const todayStr = fmtDate(today)
  filters.dateRange = [todayStr, todayStr]
  filters.workshopId = ''
  filters.machineId = ''
  loadData()
}

// ---------- 生命周期 ----------
onMounted(async () => {
  // 默认日期：今天到今天
  const today = new Date()
  const todayStr = fmtDate(today)
  filters.dateRange = [todayStr, todayStr]

  await loadOptions()
  loadData()
})

onBeforeUnmount(() => {
  disposeCharts()
})
</script>

<style scoped lang="scss">
.machine-production {
  padding: 0;

  .filter-bar {
    margin-bottom: 16px;
  }

  .stat-row {
    margin-bottom: 16px;

    .el-card {
      height: 100%;
    }

    .stat-card {
      text-align: center;
      padding: 10px 0;

      .stat-label {
        font-size: 14px;
        color: #909399;
        margin-bottom: 8px;

        .info-icon {
          margin-left: 2px;
          font-size: 13px;
          color: #c0c4cc;
          cursor: help;
          vertical-align: middle;

          &:hover {
            color: #409eff;
          }
        }
      }

      .stat-value {
        font-size: 28px;
        font-weight: bold;
        color: #303133;
      }

      .top-machine-name {
        font-size: 20px;
      }
    }
  }

  .chart-row {
    margin-bottom: 16px;
  }

  .card-title {
    font-size: 15px;
    font-weight: 500;
  }

  .table-card {
    :deep(.el-card__body) {
      padding: 0;
    }
  }
}
</style>
