<template>
  <doc-alert title="【MES】生产与质量管控首页" url="https://doc.iocoder.cn/mes/" />

  <!-- 第一行：统计卡片 -->
  <el-row :gutter="16" class="mb-4">
    <el-col :span="6">
      <el-card class="stat-card" shadow="never">
        <div class="flex flex-col">
          <div class="flex justify-between items-center mb-1">
            <span class="text-gray-500 text-base font-medium">今日工单数</span>
            <Icon icon="ep:document" class="text-[32px] text-blue-400" />
          </div>
          <span class="text-3xl font-bold text-gray-700">{{ statsData.dailyOrderCount }}</span>
          <el-divider class="my-2" />
          <div class="flex justify-between items-center text-gray-400 text-sm">
            <span>进行中</span>
            <span class="text-green-500">{{ statsData.inProgressOrderCount }}</span>
          </div>
        </div>
      </el-card>
    </el-col>
    <el-col :span="6">
      <el-card class="stat-card" shadow="never">
        <div class="flex flex-col">
          <div class="flex justify-between items-center mb-1">
            <span class="text-gray-500 text-base font-medium">今日产量</span>
            <Icon icon="ep:box" class="text-[32px] text-orange-400" />
          </div>
          <span class="text-3xl font-bold text-gray-700">{{ statsData.dailyProductionCount }}</span>
          <el-divider class="my-2" />
          <div class="flex justify-between items-center text-gray-400 text-sm">
            <span>完成率</span>
            <span class="text-green-500">{{ statsData.completionRate }}%</span>
          </div>
        </div>
      </el-card>
    </el-col>
    <el-col :span="6">
      <el-card class="stat-card" shadow="never">
        <div class="flex flex-col">
          <div class="flex justify-between items-center mb-1">
            <span class="text-gray-500 text-base font-medium">合格率</span>
            <Icon icon="ep:checked" class="text-[32px] text-green-400" />
          </div>
          <span class="text-3xl font-bold text-gray-700">{{ statsData.qualifiedRate }}%</span>
          <el-divider class="my-2" />
          <div class="flex justify-between items-center text-gray-400 text-sm">
            <span>不合格数</span>
            <span class="text-red-500">{{ statsData.unqualifiedCount }}</span>
          </div>
        </div>
      </el-card>
    </el-col>
    <el-col :span="6">
      <el-card class="stat-card" shadow="never">
        <div class="flex flex-col">
          <div class="flex justify-between items-center mb-1">
            <span class="text-gray-500 text-base font-medium">质检记录</span>
            <Icon icon="ep:document-checked" class="text-[32px] text-purple-400" />
          </div>
          <span class="text-3xl font-bold text-gray-700">{{ statsData.qualityCheckCount }}</span>
          <el-divider class="my-2" />
          <div class="flex justify-between items-center text-gray-400 text-sm">
            <span>今日新增</span>
            <span class="text-green-500">+{{ statsData.newQualityCheckCount }}</span>
          </div>
        </div>
      </el-card>
    </el-col>
  </el-row>

  <!-- 第二行：生产管控图表 -->
  <el-row :gutter="16" class="mb-4">
    <el-col :span="16">
      <el-card class="chart-card" shadow="never">
        <template #header>
          <div class="flex items-center justify-between">
            <span class="text-base font-medium text-gray-600">生产趋势</span>
            <el-radio-group
              v-model="productionTimeRange"
              @change="handleProductionTimeRangeChange"
              size="small"
            >
              <el-radio-button label="week">本周</el-radio-button>
              <el-radio-button label="month">本月</el-radio-button>
              <el-radio-button label="quarter">本季度</el-radio-button>
            </el-radio-group>
          </div>
        </template>
        <div class="h-[350px]">
          <Echart :options="productionTrendOptions" :height="340" />
        </div>
      </el-card>
    </el-col>
    <el-col :span="8">
      <el-card class="chart-card" shadow="never">
        <template #header>
          <div class="flex items-center">
            <span class="text-base font-medium text-gray-600">工单状态分布</span>
          </div>
        </template>
        <div class="h-[350px]">
          <Echart :options="orderStatusOptions" :height="340" />
        </div>
      </el-card>
    </el-col>
  </el-row>

  <!-- 第三行：质量管控图表 -->
  <el-row :gutter="16" class="mb-4">
    <el-col :span="12">
      <el-card class="chart-card" shadow="never">
        <template #header>
          <div class="flex items-center justify-between">
            <span class="text-base font-medium text-gray-600">质量趋势分析</span>
            <el-radio-group
              v-model="qualityTimeRange"
              @change="handleQualityTimeRangeChange"
              size="small"
            >
              <el-radio-button label="week">本周</el-radio-button>
              <el-radio-button label="month">本月</el-radio-button>
              <el-radio-button label="quarter">本季度</el-radio-button>
            </el-radio-group>
          </div>
        </template>
        <div class="h-[350px]">
          <Echart :options="qualityTrendOptions" :height="340" />
        </div>
      </el-card>
    </el-col>
    <el-col :span="12">
      <el-card class="chart-card" shadow="never">
        <template #header>
          <div class="flex items-center justify-between">
            <span class="text-base font-medium text-gray-600">损耗率分布</span>
            <el-select
              v-model="selectedProduct"
              placeholder="选择产品"
              size="small"
              @change="handleProductChange"
              style="width: 700px"
            >
              <el-option
                v-for="item in productOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </div>
        </template>
        <div class="h-[350px]">
          <Echart :options="lossRateOptions" :height="340" />
        </div>
      </el-card>
    </el-col>
  </el-row>

  <!-- 第四行：生产状态和质检看板 -->
  <el-row :gutter="16">
    <el-col :span="14">
      <el-card shadow="never" class="h-[360px]">
        <template #header>
          <div class="flex items-center justify-between">
            <span class="text-base font-medium text-gray-600">进行中的工单</span>
            <el-button type="primary" link @click="viewAllOrders">查看全部</el-button>
          </div>
        </template>
        <el-table :data="inProgressOrders" stripe style="width: 100%" height="280px">
          <el-table-column prop="code" label="工单编号" width="120" />
          <el-table-column prop="name" label="工单名称" width="150" />
          <el-table-column prop="productName" label="产品名称" width="150" />
          <el-table-column prop="planQuantity" label="计划数量" width="90" />
          <el-table-column prop="producedQuantity" label="已生产数量" width="100" />
          <el-table-column prop="progress" label="进度">
            <template #default="scope">
              <el-progress
                :percentage="scope.row.progress"
                :status="getProgressStatus(scope.row.progress)"
              />
            </template>
          </el-table-column>
          <!--          <el-table-column label="操作" width="120">-->
          <!--            <template #default="scope">-->
          <!--              <el-button type="primary" link @click="viewOrderDetail(scope.row)">详情</el-button>-->
          <!--              <el-button type="success" link @click="updateOrderStatus(scope.row)">更新</el-button>-->
          <!--            </template>-->
          <!--          </el-table-column>-->
        </el-table>
      </el-card>
    </el-col>
    <el-col :span="10">
      <el-card shadow="never" class="h-[360px]">
        <template #header>
          <div class="flex items-center justify-between">
            <span class="text-base font-medium text-gray-600">最近质检记录</span>
            <el-button type="primary" link @click="viewAllQualityChecks">查看全部</el-button>
          </div>
        </template>
        <el-table :data="recentQualityChecks" stripe style="width: 100%" height="280px">
          <el-table-column prop="code" label="编号" width="120" />
          <el-table-column prop="productName" label="产品名称" width="150" />
          <el-table-column prop="processName" label="工序名称" width="120" />
          <el-table-column prop="qualified" label="是否合格" width="90">
            <template #default="scope">
              <el-tag :type="scope.row.qualified ? 'success' : 'danger'">
                {{ scope.row.qualified ? '合格' : '不合格' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="lossRate" label="损耗率">
            <template #default="scope"> {{ scope.row.lossRate }}% </template>
          </el-table-column>
          <!--          <el-table-column label="操作" width="80">-->
          <!--            <template #default="scope">-->
          <!--              <el-button type="primary" link @click="viewQualityDetail(scope.row)">详情</el-button>-->
          <!--            </template>-->
          <!--          </el-table-column>-->
        </el-table>
      </el-card>
    </el-col>
  </el-row>

  <!-- 第五行：生产日报表 -->
  <el-row :gutter="16" class="mt-4">
    <el-col :span="12">
      <el-card shadow="never" class="h-[460px]">
        <template #header>
          <div class="flex items-center justify-between">
            <span class="text-base font-medium text-gray-600">甜菊糖生产报表</span>
            <div class="flex items-center gap-2">
              <el-select v-model="steviaShift" size="small" @change="handleSteviaDateChange">
                <el-option label="甲班" value="A" />
                <el-option label="乙班" value="B" />
              </el-select>
              <el-date-picker
                v-model="steviaReportDate"
                type="date"
                placeholder="选择日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                size="small"
                @change="handleSteviaDateChange"
              />
            </div>
          </div>
        </template>
        <div
          class="report-placeholder flex flex-col items-center justify-center h-[360px] border border-dashed border-gray-200 rounded-md"
        >
          <div v-if="!steviaReport" class="text-gray-400 text-center">
            <el-icon class="mr-2 text-lg"><Loading /></el-icon>
            加载中...
          </div>
          <template v-else>
            <div class="w-full px-4">
              <div class="flex justify-between items-center mb-4">
                <div class="text-gray-600">
                  <span class="font-medium">{{ steviaReport.productName }}</span>
                  <span class="text-sm ml-2">{{ steviaShift === 'A' ? '甲班' : '乙班' }}</span>
                </div>
                <div class="text-2xl font-bold text-blue-500"
                >产量：{{ steviaReport.totalProducedQuantity ?? 0 }}</div
                >
              </div>

              <el-divider content-position="center">原料消耗</el-divider>

              <div class="overflow-y-auto h-[160px] mb-3">
                <el-table :data="steviaReport.materialUsages || []" size="small" border stripe>
                  <el-table-column prop="materialName" label="原料名称" min-width="120" />
                  <el-table-column prop="quantity" label="消耗量" width="110">
                    <template #default="scope">
                      <span>{{ scope.row.quantity }}</span>
                      <span class="text-gray-400 ml-1 text-xs">{{ scope.row.unit }}</span>
                    </template>
                  </el-table-column>
                </el-table>
              </div>

              <el-divider content-position="center">能耗汇总</el-divider>
              <div class="grid grid-cols-3 gap-3 text-center">
                <div>
                  <div class="text-gray-500 text-xs">用电(度)</div>
                  <div class="text-base font-semibold">{{ steviaEnergy?.electricity ?? '-' }}</div>
                </div>
                <div>
                  <div class="text-gray-500 text-xs">用水(吨)</div>
                  <div class="text-base font-semibold">{{ steviaEnergy?.water ?? '-' }}</div>
                </div>
                <div>
                  <div class="text-gray-500 text-xs">煤耗(吨)</div>
                  <div class="text-base font-semibold">{{ steviaEnergy?.coal ?? '-' }}</div>
                </div>
              </div>
            </div>
          </template>
        </div>
      </el-card>
    </el-col>
    <el-col :span="12">
      <el-card shadow="never" class="h-[460px]">
        <template #header>
          <div class="flex items-center justify-between">
            <span class="text-base font-medium text-gray-600">番茄酱生产报表</span>
            <div class="flex items-center gap-2">
              <el-select v-model="tomatoShift" size="small" @change="handleTomatoSauceDateChange">
                <el-option label="甲班" value="A" />
                <el-option label="乙班" value="B" />
              </el-select>
              <el-date-picker
                v-model="tomatoSauceReportDate"
                type="date"
                placeholder="选择日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                size="small"
                @change="handleTomatoSauceDateChange"
              />
            </div>
          </div>
        </template>
        <div
          class="report-placeholder flex flex-col items-center justify-center h-[360px] border border-dashed border-gray-200 rounded-md"
        >
          <div v-if="!tomatoReport" class="text-gray-400 text-center">
            <el-icon class="mr-2 text-lg"><Loading /></el-icon>
            加载中...
          </div>
          <template v-else>
            <div class="w-full px-4">
              <div class="flex justify-between items-center mb-4">
                <div class="text-gray-600">
                  <span class="font-medium">{{ tomatoReport.productName }}</span>
                  <span class="text-sm ml-2">{{ tomatoShift === 'A' ? '甲班' : '乙班' }}</span>
                </div>
                <div class="text-2xl font-bold text-blue-500"
                >产量：{{ tomatoReport.totalProducedQuantity ?? 0 }}</div
                >
              </div>

              <el-divider content-position="center">原料消耗</el-divider>

              <div class="overflow-y-auto h-[160px] mb-3">
                <el-table :data="tomatoReport.materialUsages || []" size="small" border stripe>
                  <el-table-column prop="materialName" label="原料名称" min-width="120" />
                  <el-table-column prop="quantity" label="消耗量" width="110">
                    <template #default="scope">
                      <span>{{ scope.row.quantity }}</span>
                      <span class="text-gray-400 ml-1 text-xs">{{ scope.row.unit }}</span>
                    </template>
                  </el-table-column>
                </el-table>
              </div>

              <el-divider content-position="center">能耗汇总</el-divider>
              <div class="grid grid-cols-3 gap-3 text-center">
                <div>
                  <div class="text-gray-500 text-xs">用电(度)</div>
                  <div class="text-base font-semibold">{{ tomatoEnergy?.electricity ?? '-' }}</div>
                </div>
                <div>
                  <div class="text-gray-500 text-xs">用水(吨)</div>
                  <div class="text-base font-semibold">{{ tomatoEnergy?.water ?? '-' }}</div>
                </div>
                <div>
                  <div class="text-gray-500 text-xs">煤耗(吨)</div>
                  <div class="text-base font-semibold">{{ tomatoEnergy?.coal ?? '-' }}</div>
                </div>
              </div>
            </div>
          </template>
        </div>
      </el-card>
    </el-col>
  </el-row>
</template>

<script setup lang="ts" name="MESHome">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { EChartsOption } from 'echarts'
import { Echart } from '@/components/Echart'
import { Icon } from '@/components/Icon'
import { Loading } from '@element-plus/icons-vue'
import dayjs from 'dayjs'
import {
  getHomeStats,
  getProductionTrend,
  getOrderStatusDistribution,
  getQualityTrend,
  getLossRateDistribution,
  getInProgressOrders,
  getRecentQualityChecks
} from '@/api/mes/home'
import { ProductApi } from '@/api/erp/product/product'
import { ElMessage } from 'element-plus'
import { YVHgetProductionReport } from '@/api/mes/production/workorder'
import { getEnergyConsumptionSummary } from '@/api/energy/consumption'

// 物料消耗类型定义
interface MaterialUsage {
  materialId: number
  materialCode: string
  materialName: string
  unit: string
  quantity: number
}

// 生产报表响应类型
interface ProductionReport {
  productId: number
  productName: string
  totalProducedQuantity: number
  materialUsages: MaterialUsage[]
}

// 能耗汇总类型
interface EnergySummary {
  electricity: number
  water: number
  coal: number
}

defineOptions({ name: 'MESHome' })

const router = useRouter()

// 统计数据，将从API获取
const statsData = reactive({
  dailyOrderCount: 0,
  inProgressOrderCount: 0,
  dailyProductionCount: 0,
  completionRate: 0,
  qualifiedRate: 0,
  unqualifiedCount: 0,
  qualityCheckCount: 0,
  newQualityCheckCount: 0
})

// 时间范围选择
const productionTimeRange = ref('week')
const qualityTimeRange = ref('week')
const selectedProduct = ref('')

// 生产日报表日期选择
const steviaReportDate = ref(new Date().toISOString().split('T')[0])
const tomatoSauceReportDate = ref(new Date().toISOString().split('T')[0])
// 班次选择: A=甲班(8:00-20:00), B=乙班(20:00-次日8:00)
const steviaShift = ref('A')
const tomatoShift = ref('A')

// 报表产品ID与当日产量
const steviaProductId = ref<number | string | null>(null)
const tomatoSauceProductId = ref<number | string | null>(null)
// 报表数据
const steviaReport = ref<ProductionReport | null>(null)
const tomatoReport = ref<ProductionReport | null>(null)
// 能耗汇总
const steviaEnergy = ref<EnergySummary | null>(null)
const tomatoEnergy = ref<EnergySummary | null>(null)
// 产品选项
const productOptions = ref<{ value: number | string; label: string }[]>([])

// 生产趋势图表配置
const productionTrendOptions = reactive<EChartsOption>({
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    }
  },
  legend: {
    data: ['计划产量', '实际产量', '合格产量']
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: [
    {
      type: 'category',
      data: []
    }
  ],
  yAxis: [
    {
      type: 'value',
      name: '数量'
    }
  ],
  series: [
    {
      name: '计划产量',
      type: 'bar',
      emphasis: {
        focus: 'series'
      },
      data: []
    },
    {
      name: '实际产量',
      type: 'bar',
      emphasis: {
        focus: 'series'
      },
      data: []
    },
    {
      name: '合格产量',
      type: 'bar',
      emphasis: {
        focus: 'series'
      },
      data: []
    }
  ]
})

// 工单状态分布图表配置
const orderStatusOptions = reactive<EChartsOption>({
  tooltip: {
    trigger: 'item',
    formatter: '{a} <br/>{b} : {c} ({d}%)'
  },
  legend: {
    orient: 'vertical',
    left: 'left',
    data: [] as string[]
  },
  series: [
    {
      name: '工单状态',
      type: 'pie',
      radius: '65%',
      center: ['50%', '50%'],
      data: [],
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }
  ]
})

// 质量趋势图表配置
const qualityTrendOptions = reactive<EChartsOption>({
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'cross',
      crossStyle: {
        color: '#999'
      }
    }
  },
  legend: {
    data: ['合格率', '不合格数']
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: [
    {
      type: 'category',
      data: [],
      axisPointer: {
        type: 'shadow'
      }
    }
  ],
  yAxis: [
    {
      type: 'value',
      name: '合格率(%)',
      min: 80,
      max: 100,
      axisLabel: {
        formatter: '{value}%'
      }
    },
    {
      type: 'value',
      name: '不合格数',
      axisLabel: {
        formatter: '{value}'
      }
    }
  ],
  series: [
    {
      name: '合格率',
      type: 'line',
      yAxisIndex: 0,
      data: []
    },
    {
      name: '不合格数',
      type: 'bar',
      yAxisIndex: 1,
      data: []
    }
  ]
})

// 损耗率分布图表配置
const lossRateOptions = reactive<EChartsOption>({
  tooltip: {
    trigger: 'item'
  },
  legend: {
    top: 'top'
  },
  series: [
    {
      name: '损耗率分布',
      type: 'pie',
      radius: ['40%', '70%'],
      avoidLabelOverlap: false,
      itemStyle: {
        borderRadius: 10,
        borderColor: '#fff',
        borderWidth: 2
      },
      label: {
        show: false,
        position: 'center'
      },
      emphasis: {
        label: {
          show: true,
          fontSize: 16,
          fontWeight: 'bold'
        }
      },
      labelLine: {
        show: false
      },
      data: []
    }
  ]
})

// 进行中的工单和最近质检记录
const inProgressOrders = ref<any[]>([])
const recentQualityChecks = ref<any[]>([])

// 获取进度状态
const getProgressStatus = (progress) => {
  if (progress >= 80) return 'success'
  if (progress >= 50) return ''
  return 'warning'
}

// 获取生产报表数据（通用）
const fetchProductionReport = async (
  productId: number | string,
  dateStr: string,
  shift: string
): Promise<ProductionReport | null> => {
  // 根据班次设置时间范围
  // 甲班: 8:00-20:00, 乙班: 20:00-次日8:00
  let startTime: string
  let endTime: string

  if (shift === 'A') {
    // 甲班: 当日8:00 - 当日20:00
    startTime = dayjs(dateStr).hour(8).minute(0).second(0).format('YYYY-MM-DD HH:mm:ss')
    endTime = dayjs(dateStr).hour(20).minute(0).second(0).format('YYYY-MM-DD HH:mm:ss')
  } else {
    // 乙班: 当日20:00 - 次日8:00
    startTime = dayjs(dateStr).hour(20).minute(0).second(0).format('YYYY-MM-DD HH:mm:ss')
    endTime = dayjs(dateStr).add(1, 'day').hour(8).minute(0).second(0).format('YYYY-MM-DD HH:mm:ss')
  }

  try {
    const res = await YVHgetProductionReport({ productId, startTime, endTime })
    // 兼容两种结构：{code,data,msg} 或 {data} 或 直接数据
    const data = (res as any)?.data ?? res
    return (data as ProductionReport) ?? null
  } catch (error) {
    console.error('获取生产报表失败', error)
    return null
  }
}

// 计算班次时间范围
const computeShiftRange = (dateStr: string, shift: string) => {
  if (shift === 'A') {
    return {
      startTime: dayjs(dateStr).hour(8).minute(0).second(0).format('YYYY-MM-DD HH:mm:ss'),
      endTime: dayjs(dateStr).hour(20).minute(0).second(0).format('YYYY-MM-DD HH:mm:ss')
    }
  }
  return {
    startTime: dayjs(dateStr).hour(20).minute(0).second(0).format('YYYY-MM-DD HH:mm:ss'),
    endTime: dayjs(dateStr).add(1, 'day').hour(8).minute(0).second(0).format('YYYY-MM-DD HH:mm:ss')
  }
}

// 拉取报表 + 能耗（甜菊糖）
const updateSteviaDailyCount = async () => {
  try {
    if (!steviaProductId.value) return
    console.log('获取甜菊糖生产报表，参数:', {
      productId: steviaProductId.value,
      date: steviaReportDate.value,
      shift: steviaShift.value
    })
    const { startTime, endTime } = computeShiftRange(steviaReportDate.value, steviaShift.value)
    const [report, energy] = await Promise.all([
      fetchProductionReport(steviaProductId.value, steviaReportDate.value, steviaShift.value),
      getEnergyConsumptionSummary({ startTime, endTime })
    ])
    steviaReport.value = report
    steviaEnergy.value = energy
    console.log('甜菊糖生产报表结果:', steviaReport.value, '能耗:', steviaEnergy.value)
  } catch (e) {
    ElMessage.error('获取甜菊糖生产报表或能耗失败')
    console.error(e)
  }
}

// 拉取报表 + 能耗（番茄酱）
const updateTomatoDailyCount = async () => {
  try {
    if (!tomatoSauceProductId.value) return
    console.log('获取番茄酱生产报表，参数:', {
      productId: tomatoSauceProductId.value,
      date: tomatoSauceReportDate.value,
      shift: tomatoShift.value
    })
    const { startTime, endTime } = computeShiftRange(tomatoSauceReportDate.value, tomatoShift.value)
    const [report, energy] = await Promise.all([
      fetchProductionReport(
        tomatoSauceProductId.value,
        tomatoSauceReportDate.value,
        tomatoShift.value
      ),
      getEnergyConsumptionSummary({ startTime, endTime })
    ])
    tomatoReport.value = report
    tomatoEnergy.value = energy
    console.log('番茄酱生产报表结果:', tomatoReport.value, '能耗:', tomatoEnergy.value)
  } catch (e) {
    ElMessage.error('获取番茄酱生产报表或能耗失败')
    console.error(e)
  }
}

// 获取统计数据
const fetchStatsData = async () => {
  try {
    const res = await getHomeStats()
    // 检查返回数据结构，适应不同的后端返回格式
    const data = res.data || res
    if (data) {
      Object.assign(statsData, data)
    } else {
      console.error('获取统计数据失败: 无效的数据格式', res)
    }
  } catch (error) {
    ElMessage.error('获取统计数据失败')
    console.error('获取统计数据失败', error)
  }
}

// 获取生产趋势数据
const fetchProductionTrend = async (timeRange = 'week') => {
  try {
    const res = await getProductionTrend({ timeRange })
    // 检查返回数据结构，适应不同的后端返回格式
    const data = res.data || res

    if (data && productionTrendOptions.xAxis && productionTrendOptions.xAxis[0]) {
      // 确保有xAxis数据，如果没有则提供默认值
      productionTrendOptions.xAxis[0].data = data.xAxis || [
        '周一',
        '周二',
        '周三',
        '周四',
        '周五',
        '周六',
        '周日'
      ]
    }

    if (productionTrendOptions.series) {
      if (productionTrendOptions.series[0]) {
        productionTrendOptions.series[0].data = data?.planData || []
      }
      if (productionTrendOptions.series[1]) {
        productionTrendOptions.series[1].data = data?.actualData || []
      }
      if (productionTrendOptions.series[2]) {
        productionTrendOptions.series[2].data = data?.qualifiedData || []
      }
    }
  } catch (error) {
    ElMessage.error('获取生产趋势数据失败')
    console.error('获取生产趋势数据失败', error)
  }
}

// 获取工单状态分布数据
const fetchOrderStatusDistribution = async () => {
  try {
    const res = await getOrderStatusDistribution()
    // 检查返回数据结构，适应不同的后端返回格式
    const data = res.data || res

    if (data && Array.isArray(data) && data.length > 0) {
      if (orderStatusOptions.legend) {
        ;(orderStatusOptions.legend as any).data = data.map((item) => item.name)
      }

      if (orderStatusOptions.series && orderStatusOptions.series[0]) {
        orderStatusOptions.series[0].data = data
      }
    } else {
      // 设置默认值
      const defaultData = [
        { value: 5, name: '草稿' },
        { value: 7, name: '生产中' },
        { value: 12, name: '已完成' }
      ]
      if (orderStatusOptions.legend) {
        ;(orderStatusOptions.legend as any).data = defaultData.map((item) => item.name)
      }
      if (orderStatusOptions.series && orderStatusOptions.series[0]) {
        orderStatusOptions.series[0].data = defaultData
      }
      console.warn('工单状态数据为空，使用默认值', data)
    }
  } catch (error) {
    ElMessage.error('获取工单状态分布数据失败')
    console.error('获取工单状态分布数据失败', error)
  }
}

// 获取质量趋势数据
const fetchQualityTrend = async (timeRange = 'week') => {
  try {
    const res = await getQualityTrend({ timeRange })
    // 检查返回数据结构，适应不同的后端返回格式
    const data = res.data || res

    if (data && qualityTrendOptions.xAxis && qualityTrendOptions.xAxis[0]) {
      // 确保有xAxis数据，如果没有则提供默认值
      qualityTrendOptions.xAxis[0].data = data.xAxis || [
        '周一',
        '周二',
        '周三',
        '周四',
        '周五',
        '周六',
        '周日'
      ]
    }

    if (qualityTrendOptions.series) {
      if (qualityTrendOptions.series[0]) {
        qualityTrendOptions.series[0].data = data?.qualifiedRateData || []
      }
      if (qualityTrendOptions.series[1]) {
        qualityTrendOptions.series[1].data = data?.unqualifiedCountData || []
      }
    }
  } catch (error) {
    ElMessage.error('获取质量趋势数据失败')
    console.error('获取质量趋势数据失败', error)
  }
}

// 获取损耗率分布数据
const fetchLossRateDistribution = async (productId) => {
  try {
    const res = await getLossRateDistribution({ productId })
    // 检查返回数据结构，适应不同的后端返回格式
    const data = res.data || res

    if (data && lossRateOptions.series && lossRateOptions.series[0]) {
      lossRateOptions.series[0].data = Array.isArray(data) ? data : []
    }
  } catch (error) {
    ElMessage.error('获取损耗率分布数据失败')
    console.error('获取损耗率分布数据失败', error)
  }
}

// 获取产品列表
const fetchProductList = async () => {
  try {
    const res = await ProductApi.getProductSimpleList()
    const data = res.data || res

    if (data && Array.isArray(data)) {
      productOptions.value = data.map((item: any) => ({
        value: item.id,
        label: item.name
      }))

      if (productOptions.value.length > 0) {
        selectedProduct.value = productOptions.value[0].value
        fetchLossRateDistribution(selectedProduct.value)
      }

      // 自动识别甜菊糖与番茄酱产品ID
      const stevia = data.find((x: any) => String(x.name).includes('甜菊糖'))
      const tomato = data.find((x: any) => String(x.name).includes('番茄酱'))
      steviaProductId.value = stevia?.id ?? null
      tomatoSauceProductId.value = tomato?.id ?? null

      // 初始化查询当日产量
      if (steviaProductId.value) await updateSteviaDailyCount()
      if (tomatoSauceProductId.value) await updateTomatoDailyCount()
    }
  } catch (error) {
    ElMessage.error('获取产品列表失败')
    console.error('获取产品列表失败', error)
  }
}

// 获取进行中的工单
const fetchInProgressOrders = async () => {
  try {
    const res = await getInProgressOrders()
    // 检查返回数据结构，适应不同的后端返回格式
    const data = res.data || res

    inProgressOrders.value = Array.isArray(data) ? (data as any[]) : []
  } catch (error) {
    ElMessage.error('获取进行中工单数据失败')
    console.error('获取进行中工单数据失败', error)
  }
}

// 获取最近质检记录
const fetchRecentQualityChecks = async () => {
  try {
    const res = await getRecentQualityChecks()
    // 检查返回数据结构，适应不同的后端返回格式
    const data = res.data || res

    recentQualityChecks.value = Array.isArray(data) ? (data as any[]) : []
  } catch (error) {
    ElMessage.error('获取最近质检记录失败')
    console.error('获取最近质检记录失败', error)
  }
}

// 时间范围变更处理
const handleProductionTimeRangeChange = (range) => {
  fetchProductionTrend(range)
}

const handleQualityTimeRangeChange = (range) => {
  fetchQualityTrend(range)
}

const handleProductChange = (productId) => {
  fetchLossRateDistribution(productId)
}

// 查看全部工单
const viewAllOrders = () => {
  router.push('/mes/mes/workorder')
}

// 查看全部质检记录
const viewAllQualityChecks = () => {
  router.push('/mes/quality/processquality')
}

// 查看工单详情
const viewOrderDetail = (row) => {
  router.push(`/mes/production/workorder?id=${row.id}`)
}

// 查看质检详情
const viewQualityDetail = (row) => {
  router.push(`/mes/quality/processquality?id=${row.id}`)
}

// 更新工单状态
const updateOrderStatus = (row) => {
  console.log('Update order status:', row)
  // 实际项目中应该打开相应的表单进行状态更新
}

// 生产日报表日期变更处理
const handleSteviaDateChange = async (date) => {
  await updateSteviaDailyCount()
}

const handleTomatoSauceDateChange = async (date) => {
  await updateTomatoDailyCount()
}

onMounted(() => {
  console.log('MES Home dashboard mounted')

  // 加载所有数据
  fetchStatsData()
  fetchProductionTrend(productionTimeRange.value)
  fetchOrderStatusDistribution()
  fetchQualityTrend(qualityTimeRange.value)
  fetchProductList() // 获取产品列表
  fetchInProgressOrders()
  fetchRecentQualityChecks()
})
</script>

<style scoped>
.stat-card {
  height: 180px;
  transition: all 0.3s;
}

.stat-card:hover {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transform: translateY(-5px);
}

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

.mb-4 {
  margin-bottom: 16px;
}

.mt-4 {
  margin-top: 16px;
}

/* 进度条样式 */
:deep(.el-progress-bar__inner) {
  transition: width 0.6s ease;
}

/* 表格行鼠标悬停效果 */
:deep(.el-table__row:hover) {
  background-color: #f5f7fa;
}

/* 报表占位符样式 */
.report-placeholder {
  background-color: #f8f9fa;
}
</style>
