<template>
  <div class="program-production">
    <!-- 筛选栏 -->
    <el-form :inline="true" class="filter-bar" :model="filters">
      <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-input v-model="filters.programName" placeholder="输入程序名" style="width: 240px" clearable />
      </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="选定时间范围内所有NC程序的总产量。" placement="top">
                <span class="info-icon">ⓘ</span>
              </el-tooltip>
            </div>
            <div class="stat-value">{{ 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="选定时间范围内有产量记录的NC程序数量。" placement="top">
                <span class="info-icon">ⓘ</span>
              </el-tooltip>
            </div>
            <div class="stat-value">{{ summary.runningProgramCount ?? '-' }}</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="平均每个NC程序的产量。" placement="top">
                <span class="info-icon">ⓘ</span>
              </el-tooltip>
            </div>
            <div class="stat-value">{{ summary.avgPerProgram?.toFixed(1) ?? '-' }}</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="产量最高的NC程序名称。" placement="top">
                <span class="info-icon">ⓘ</span>
              </el-tooltip>
            </div>
            <div class="stat-value top-program">{{ summary.topProgramName ?? '-' }}</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">
              程序产量柱状图
              <el-tooltip content="各NC程序的产量对比。" placement="top">
                <span class="info-icon">ⓘ</span>
              </el-tooltip>
            </span>
          </template>
          <div ref="barChartRef" style="height: 320px"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card shadow="hover">
          <template #header>
            <span class="card-title">
              程序产量饼图
              <el-tooltip content="各NC程序产量占比分布。" placement="top">
                <span class="info-icon">ⓘ</span>
              </el-tooltip>
            </span>
          </template>
          <div ref="pieChartRef" style="height: 320px"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 明细表格 -->
    <el-card shadow="hover" class="table-card">
      <template #header>
        <span class="card-title">
          程序产量明细
          <el-tooltip content="按产量降序排列，展示每个NC程序的详细统计数据。" placement="top">
            <span class="info-icon">ⓘ</span>
          </el-tooltip>
        </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="programName" label="程序名" show-overflow-tooltip />
        <el-table-column prop="machineCount" label="涉及机床数" width="100" align="center" />
        <el-table-column prop="totalQuantity" label="总产量" width="100" align="center" />
        <el-table-column label="平均单机" width="100" align="center">
          <template #default="{ row }">{{ row.avgPerMachine?.toFixed(1) ?? '-' }}</template>
        </el-table-column>
        <el-table-column label="占比" width="100" align="center">
          <template #default="{ row }">{{ row.percentage?.toFixed(1) ?? '-' }}%</template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

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

/** 程序产量汇总 */
interface ProgramSummary {
  totalQuantity: number
  runningProgramCount: number
  avgPerProgram: number
  topProgramName: string
}

/** 程序产量明细行 */
interface ProgramListItem {
  rank: number
  programName: string
  machineCount: number
  totalQuantity: number
  avgPerMachine: number
  percentage: number
}

// 筛选条件
const filters = reactive({
  dateRange: [] as string[],
  programName: ''
})

// 统计数据
const loading = ref(false)
const summary = ref<ProgramSummary>({} as ProgramSummary)
const tableData = ref<ProgramListItem[]>([])

// 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
  barChart?.dispose()
  barChart = echarts.init(barChartRef.value)
  const names = tableData.value.map(item => item.programName)
  const quantities = tableData.value.map(item => item.totalQuantity)
  barChart.setOption({
    tooltip: {
      trigger: 'axis',
      formatter: (params: { name: string; value: number }[]) => {
        const p = params[0]
        return `${p.name}<br/>产量: ${p.value} 件`
      }
    },
    grid: { left: 50, right: 20, top: 20, bottom: 40 },
    xAxis: {
      type: 'category',
      data: names,
      axisLabel: { fontSize: 11, rotate: names.length > 8 ? 30 : 0 }
    },
    yAxis: { type: 'value', name: '产量(件)', axisLabel: { fontSize: 12 } },
    series: [{
      type: 'bar',
      data: quantities,
      barWidth: '50%',
      itemStyle: {
        color: '#E6A23C',
        borderRadius: [4, 4, 0, 0]
      }
    }]
  })
}

/** 初始化饼图 */
function initPieChart() {
  if (!pieChartRef.value || !tableData.value.length) return
  pieChart?.dispose()
  pieChart = echarts.init(pieChartRef.value)
  const pieData = tableData.value.map(item => ({
    value: item.totalQuantity,
    name: item.programName
  }))
  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: 11
      },
      data: pieData,
      emphasis: {
        label: { fontSize: 14, fontWeight: 'bold' }
      }
    }]
  })
}

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

/** 加载数据 */
async function loadData() {
  loading.value = true
  try {
    const params = {
      startDate: filters.dateRange?.[0] ?? '',
      endDate: filters.dateRange?.[1] ?? '',
      programName: filters.programName ?? ''
    }
    const [summaryRes, listRes] = await Promise.all([
      request.get<ProgramSummary>('/admin/production/program/summary', { params }),
      request.get<{ items: ProgramListItem[] }>('/admin/production/program/list', { params })
    ])
    summary.value = summaryRes.data ?? ({} as ProgramSummary)
    tableData.value = listRes.data?.items ?? []

    // 重建图表
    disposeCharts()
    await nextTick()
    initBarChart()
    initPieChart()
  } finally {
    loading.value = false
  }
}

/** 重置筛选条件 */
function resetFilters() {
  const today = new Date()
  const fmt = (d: Date) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
  filters.dateRange = [fmt(today), fmt(today)]
  filters.programName = ''
  loadData()
}

/** 初始化 */
function init() {
  const today = new Date()
  const fmt = (d: Date) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
  filters.dateRange = [fmt(today), fmt(today)]
  loadData()
}

onMounted(init)
onUnmounted(disposeCharts)
</script>

<style scoped lang="scss">
.program-production {
  padding: 20px;

  .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-program {
          font-size: 20px;
          color: #e6a23c;
        }
      }
    }
  }

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

  .table-card {
    margin-bottom: 16px;
  }

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

    .info-icon {
      margin-left: 4px;
      font-size: 14px;
      color: #b0b5bd;
      cursor: help;

      &:hover {
        color: #409eff;
      }
    }
  }
}
</style>
