<template>
  <div class="statistics-container">
    <el-card class="filter-card">
      <div class="filter-header">
        <h3>工单统计分析</h3>
      </div>

      <!-- 筛选条件 -->
      <el-form :inline="true" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="分组维度" required style="margin-bottom: 0;">
              <el-select
                v-model="groupFields"
                placeholder="请选择分组维度（至少选择一项）"
                multiple
                style="width: calc(100% - 200px); min-width: 400px;"
                clearable
              >
                <el-option label="维保中心" value="gxt_center" />
                <el-option label="场站" value="pcs_station_name" />
                <el-option label="品牌" value="brand" />
                <el-option label="机型" value="model" />
              </el-select>
              <el-button icon="Refresh" @click="resetQuery" style="margin-left: 10px;">重置</el-button>
              <el-button type="success" icon="Download" @click="handleExport">导出</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 展示模式切换 -->
    <el-card class="display-mode-card">
      <el-radio-group v-model="displayMode" @change="handleDisplayModeChange">
        <el-radio-button value="table">表格展示</el-radio-button>
        <el-radio-button value="chart">图表展示</el-radio-button>
      </el-radio-group>
    </el-card>

    <!-- 表格展示 -->
    <div v-if="displayMode === 'table'">
      <!-- 维保工单统计 -->
      <el-card class="table-card">
        <template #header>
          <div class="card-header">
            <span>维保工单统计</span>
          </div>
        </template>
        <el-table
          v-loading="loading"
          :data="filteredStatisticsList"
          border
          style="width: 100%"
          :default-sort="{ prop: 'work_order_count', order: 'descending' }"
        >
          <template #empty>
            <el-empty description="请选择分组维度后查看统计数据" />
          </template>
          <el-table-column
            v-for="field in selectedGroupFields"
            :key="field.prop"
            :prop="field.prop"
            :label="field.label"
            :min-width="120"
          />

          <el-table-column label="维保工单数" prop="work_order_count" width="120" sortable>
            <template #default="scope">
              <el-tag type="primary">{{ scope.row.work_order_count || 0 }}</el-tag>
            </template>
          </el-table-column>

          <el-table-column label="分数来源" align="center">
            <el-table-column label="年检数" prop="annual_inspection_count" width="80" sortable>
              <template #default="scope">
                {{ scope.row.annual_inspection_count || 0 }}
              </template>
            </el-table-column>

            <el-table-column label="年检分数" prop="annual_inspection_score" width="90" sortable>
              <template #default="scope">
                <el-tag type="success">{{ (scope.row.annual_inspection_score || 0).toFixed(1) }}</el-tag>
              </template>
            </el-table-column>

            <el-table-column label="半年检数" prop="semi_annual_inspection_count" width="90" sortable>
              <template #default="scope">
                {{ scope.row.semi_annual_inspection_count || 0 }}
              </template>
            </el-table-column>

            <el-table-column label="半年检分数" prop="semi_annual_inspection_score" width="100" sortable>
              <template #default="scope">
                <el-tag type="success">{{ (scope.row.semi_annual_inspection_score || 0).toFixed(1) }}</el-tag>
              </template>
            </el-table-column>

            <el-table-column label="螺栓检数" prop="bolt_inspection_count" width="90" sortable>
              <template #default="scope">
                {{ scope.row.bolt_inspection_count || 0 }}
              </template>
            </el-table-column>

            <el-table-column label="螺栓检分数" prop="bolt_inspection_score" width="100" sortable>
              <template #default="scope">
                <el-tag type="success">{{ (scope.row.bolt_inspection_score || 0).toFixed(1) }}</el-tag>
              </template>
            </el-table-column>
          </el-table-column>

          <el-table-column label="总分数" prop="total_score" width="100" sortable>
            <template #default="scope">
              <el-tag type="danger">{{ (scope.row.total_score || 0).toFixed(1) }}</el-tag>
            </template>
          </el-table-column>

          <el-table-column label="工时来源（小时）" align="center">
            <el-table-column label="接单时长" prop="total_accept_duration" width="100" sortable>
              <template #default="scope">
                {{ (scope.row.total_accept_duration || 0).toFixed(1) }}
              </template>
            </el-table-column>

            <el-table-column label="准备时长" prop="total_prepare_duration" width="100" sortable>
              <template #default="scope">
                {{ (scope.row.total_prepare_duration || 0).toFixed(1) }}
              </template>
            </el-table-column>

            <el-table-column label="操作时长" prop="total_operation_duration" width="100" sortable>
              <template #default="scope">
                {{ (scope.row.total_operation_duration || 0).toFixed(1) }}
              </template>
            </el-table-column>

            <el-table-column label="总工时" prop="total_duration" width="100" sortable>
              <template #default="scope">
                <el-tag type="warning">{{ (scope.row.total_duration || 0).toFixed(1) }}</el-tag>
              </template>
            </el-table-column>
          </el-table-column>
        </el-table>
      </el-card>

      <!-- 维修工单统计 -->
      <el-card class="table-card" style="margin-top: 20px;">
        <template #header>
          <div class="card-header">
            <span>维修工单统计</span>
          </div>
        </template>
        <el-table
          v-loading="repairLoading"
          :data="processedRepairData"
          border
          style="width: 100%"
          :default-sort="{ prop: 'repair_order_count', order: 'descending' }"
        >
          <template #empty>
            <el-empty description="请选择分组维度后查看统计数据" />
          </template>
          <el-table-column
            v-for="field in selectedGroupFields"
            :key="field.prop"
            :prop="field.prop"
            :label="field.label"
            :min-width="120"
          />

          <el-table-column label="维修工单数" prop="repair_order_count" width="120" sortable>
            <template #default="scope">
              <el-tag type="primary">{{ scope.row.repair_order_count || 0 }}</el-tag>
            </template>
          </el-table-column>

          <!-- 动态生成维修类型列 -->
          <el-table-column
            v-for="type in maintenanceTypes"
            :key="type + '_group'"
            :label="type + '类项目'"
            align="center"
          >
            <el-table-column :label="type + '类项目数'" width="100">
              <template #default="scope">
                {{ scope.row.types?.[type]?.count || 0 }}
              </template>
            </el-table-column>

            <el-table-column :label="type + '类分数'" width="100">
              <template #default="scope">
                <el-tag type="success">{{ (scope.row.types?.[type]?.score || 0).toFixed(1) }}</el-tag>
              </template>
            </el-table-column>
          </el-table-column>

          <el-table-column label="总分数" prop="total_score" width="100" sortable>
            <template #default="scope">
              <el-tag type="danger">{{ (scope.row.total_score || 0).toFixed(1) }}</el-tag>
            </template>
          </el-table-column>

          <el-table-column label="工时来源（小时）" align="center">
            <el-table-column label="接单时长" prop="total_accept_duration" width="100" sortable>
              <template #default="scope">
                {{ (scope.row.total_accept_duration || 0).toFixed(1) }}
              </template>
            </el-table-column>

            <el-table-column label="准备时长" prop="total_prepare_duration" width="100" sortable>
              <template #default="scope">
                {{ (scope.row.total_prepare_duration || 0).toFixed(1) }}
              </template>
            </el-table-column>

            <el-table-column label="操作时长" prop="total_operation_duration" width="100" sortable>
              <template #default="scope">
                {{ (scope.row.total_operation_duration || 0).toFixed(1) }}
              </template>
            </el-table-column>

            <el-table-column label="总工时" prop="total_duration" width="100" sortable>
              <template #default="scope">
                <el-tag type="warning">{{ (scope.row.total_duration || 0).toFixed(1) }}</el-tag>
              </template>
            </el-table-column>
          </el-table-column>
        </el-table>
      </el-card>

      <!-- 维保运行统计 -->
      <el-card class="table-card" style="margin-top: 20px;">
        <template #header>
          <div class="card-header">
            <span>维保运行统计</span>
          </div>
        </template>
        <el-table
          v-loading="runtimeLoading"
          :data="runtimeScoreData"
          border
          style="width: 100%"
          :default-sort="{ prop: 'total_score', order: 'descending' }"
        >
          <template #empty>
            <el-empty description="请选择分组维度后查看统计数据" />
          </template>
          <el-table-column
            v-for="field in selectedGroupFields"
            :key="field.prop"
            :prop="field.prop"
            :label="field.label"
            :min-width="120"
          />

          <el-table-column label="设备数量" prop="device_count" width="100" sortable>
            <template #default="scope">
              {{ scope.row.device_count || 0 }}
            </template>
          </el-table-column>

          <el-table-column label="运行时间分数来源" align="center">
            <el-table-column label="<10小时" prop="under_10_hours_score" width="100" sortable>
              <template #default="scope">
                <el-tag type="success">{{ (scope.row.under_10_hours_score || 0).toFixed(1) }}</el-tag>
              </template>
            </el-table-column>

            <el-table-column label="10-240小时" prop="range_10_240_score" width="120" sortable>
              <template #default="scope">
                <el-tag type="primary">{{ (scope.row.range_10_240_score || 0).toFixed(1) }}</el-tag>
              </template>
            </el-table-column>

            <el-table-column label="240-270小时" prop="range_240_270_score" width="130" sortable>
              <template #default="scope">
                <el-tag type="warning">{{ (scope.row.range_240_270_score || 0).toFixed(1) }}</el-tag>
              </template>
            </el-table-column>

            <el-table-column label="270-300小时" prop="range_270_300_score" width="130" sortable>
              <template #default="scope">
                <el-tag type="danger">{{ (scope.row.range_270_300_score || 0).toFixed(1) }}</el-tag>
              </template>
            </el-table-column>

            <el-table-column label=">300小时" prop="over_300_score" width="110" sortable>
              <template #default="scope">
                <el-tag type="danger">{{ (scope.row.over_300_score || 0).toFixed(1) }}</el-tag>
              </template>
            </el-table-column>
          </el-table-column>

          <el-table-column label="总分数" prop="total_score" width="100" sortable>
            <template #default="scope">
              <el-tag type="danger">{{ (scope.row.total_score || 0).toFixed(1) }}</el-tag>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>

    <!-- 图表展示 -->
    <el-card v-if="displayMode === 'chart'" class="chart-card">
      <el-row :gutter="20">
        <!-- 工单数量统计图 -->
        <el-col :span="12">
          <div class="chart-wrapper">
            <h4>工单数量统计</h4>
            <div ref="orderCountChart" style="width: 100%; height: 350px;"></div>
          </div>
        </el-col>

        <!-- 工时统计图 -->
        <el-col :span="12">
          <div class="chart-wrapper">
            <h4>工时统计</h4>
            <div ref="durationChart" style="width: 100%; height: 350px;"></div>
          </div>
        </el-col>
      </el-row>

      <el-row :gutter="20" style="margin-top: 20px;">
        <!-- 分数统计图 -->
        <el-col :span="12">
          <div class="chart-wrapper">
            <h4>工单分数统计</h4>
            <div ref="scoreChart" style="width: 100%; height: 350px;"></div>
          </div>
        </el-col>

        <!-- 工时来源分布图 -->
        <el-col :span="12">
          <div class="chart-wrapper">
            <h4>工时来源分布</h4>
            <div ref="durationSourceChart" style="width: 100%; height: 350px;"></div>
          </div>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script setup name="Statistics">
import { ref, reactive, onMounted, computed, nextTick, watch } from 'vue'
import { getGroupStatistics, getRepairOrderStatistics, getMaintenanceTypes, getRuntimeScoreStatistics } from '@/api/gxt/statistics'
import * as echarts from 'echarts'

// 加载状态
const loading = ref(false)
const repairLoading = ref(false)
const runtimeLoading = ref(false)

// 展示模式
const displayMode = ref('table')

// 分组字段
const groupFields = ref(['gxt_center'])

// 统计数据
const statisticsList = ref([])
const repairStatisticsList = ref([])
const runtimeScoreList = ref([])
const maintenanceTypes = ref([]) // 维修类型列表

// 图表实例
const orderCountChart = ref(null)
const durationChart = ref(null)
const scoreChart = ref(null)
const durationSourceChart = ref(null)

let orderCountChartInstance = null
let durationChartInstance = null
let scoreChartInstance = null
let durationSourceChartInstance = null

// 计算选中的分组字段
const selectedGroupFields = computed(() => {
  const fieldMap = {
    'gxt_center': { prop: 'gxt_center', label: '维保中心' },
    'pcs_station_name': { prop: 'pcs_station_name', label: '场站' },
    'brand': { prop: 'brand', label: '品牌' },
    'model': { prop: 'model', label: '机型' }
  }
  return groupFields.value.map(field => fieldMap[field])
})

// 过滤后的维保工单统计数据（去除工单数为0的行）
const filteredStatisticsList = computed(() => {
  return statisticsList.value.filter(item => (item.work_order_count || 0) > 0)
})

// 获取维修类型列表
const getMaintenanceTypesList = async () => {
  try {
    const response = await getMaintenanceTypes()
    if (response.code === 200) {
      maintenanceTypes.value = response.data || []
    }
  } catch (error) {
    console.error('获取维修类型失败', error)
  }
}

// 处理维修工单数据 - 将行数据转换为按组聚合的格式
const processedRepairData = computed(() => {
  if (!repairStatisticsList.value || repairStatisticsList.value.length === 0) {
    return []
  }

  // 按分组字段聚合数据
  const groupedData = {}

  repairStatisticsList.value.forEach(item => {
    // 生成分组key - 支持多字段组合
    const groupKey = groupFields.value.map(field => {
      // 支持多种字段命名方式：下划线和驼峰
      const value = item[field] || item[field.replace(/_/g, '')] || ''
      return value
    }).join('_')

    if (!groupedData[groupKey]) {
      // 初始化分组数据
      const groupData = {}
      groupFields.value.forEach(field => {
        groupData[field] = item[field] || item[field.replace(/_/g, '')] || ''
      })

      groupedData[groupKey] = {
        ...groupData,
        repair_order_count: 0,
        total_accept_duration: 0,
        total_prepare_duration: 0,
        total_operation_duration: 0,
        total_duration: 0,
        types: {}
      }
    }

    const maintenanceType = item.maintenance_type || item.maintenanceType
    if (maintenanceType) {
      groupedData[groupKey].types[maintenanceType] = {
        count: item.type_count || item.typeCount || 0,
        score: item.type_score || item.typeScore || 0
      }
    }

    groupedData[groupKey].repair_order_count += (item.type_count || item.typeCount || 0)
    groupedData[groupKey].total_accept_duration += (item.total_accept_duration || item.totalAcceptDuration || 0)
    groupedData[groupKey].total_prepare_duration += (item.total_prepare_duration || item.totalPrepareDuration || 0)
    groupedData[groupKey].total_operation_duration += (item.total_operation_duration || item.totalOperationDuration || 0)
    groupedData[groupKey].total_duration += (item.total_duration || item.totalDuration || 0)
  })

  // 过滤掉工单数为0的行，并计算总分数
  return Object.values(groupedData).filter(item => item.repair_order_count > 0).map(item => {
    // 计算总分数：所有类型的分数总和
    let totalScore = 0
    Object.values(item.types || {}).forEach(type => {
      totalScore += (type.score || 0)
    })
    return {
      ...item,
      total_score: totalScore
    }
  })
})

// 维保运行统计数据
const runtimeScoreData = computed(() => {
  return runtimeScoreList.value.filter(item => (item.device_count || 0) > 0)
})

// 查询统计数据
const getStatisticsList = async () => {
  // 验证是否选择了分组维度
  if (!groupFields.value || groupFields.value.length === 0) {
    statisticsList.value = []
    return
  }

  loading.value = true
  try {
    const params = {
      groupFields: groupFields.value.join(',')
    }

    console.log('维保工单查询参数:', params)

    const response = await getGroupStatistics(params)
    if (response.code === 200) {
      statisticsList.value = response.data || []
      console.log('维保工单返回数据:', response.data)

      // 如果是图表模式，更新图表
      if (displayMode.value === 'chart') {
        nextTick(() => {
          updateCharts()
        })
      }
    }
  } catch (error) {
    console.error('获取统计数据失败', error)
  } finally {
    loading.value = false
  }
}

// 查询维修工单统计数据
const getRepairStatisticsList = async () => {
  // 验证是否选择了分组维度
  if (!groupFields.value || groupFields.value.length === 0) {
    repairStatisticsList.value = []
    return
  }

  repairLoading.value = true
  try {
    const params = {
      groupFields: groupFields.value.join(',')
    }

    console.log('维修工单查询参数:', params)

    const response = await getRepairOrderStatistics(params)
    if (response.code === 200) {
      repairStatisticsList.value = response.data || []
      console.log('维修工单返回数据:', response.data)
      console.log('处理后的维修工单数据:', processedRepairData.value)

      // 如果是图表模式，更新图表
      if (displayMode.value === 'chart') {
        nextTick(() => {
          updateRepairCharts()
        })
      }
    }
  } catch (error) {
    console.error('获取维修工单统计数据失败', error)
  } finally {
    repairLoading.value = false
  }
}

// 查询维保运行统计数据
const getRuntimeScoreStatisticsList = async () => {
  // 验证是否选择了分组维度
  if (!groupFields.value || groupFields.value.length === 0) {
    runtimeScoreList.value = []
    return
  }

  runtimeLoading.value = true
  try {
    const params = {
      groupFields: groupFields.value.join(',')
    }

    console.log('维保运行统计查询参数:', params)

    const response = await getRuntimeScoreStatistics(params)
    if (response.code === 200) {
      runtimeScoreList.value = response.data || []
      console.log('维保运行统计返回数据:', response.data)
    }
  } catch (error) {
    console.error('获取维保运行统计数据失败', error)
  } finally {
    runtimeLoading.value = false
  }
}

// 查询按钮
const handleQuery = () => {
  getStatisticsList()
  getRepairStatisticsList()
  getRuntimeScoreStatisticsList()
}

// 重置按钮
const resetQuery = () => {
  groupFields.value = ['gxt_center']
  getStatisticsList()
  getRepairStatisticsList()
  getRuntimeScoreStatisticsList()
}

// 导出按钮
const handleExport = () => {
  // TODO: 实现导出功能
  console.log('导出功能待实现')
}

// 展示模式切换
const handleDisplayModeChange = () => {
  if (displayMode.value === 'chart') {
    nextTick(() => {
      initCharts()
      updateCharts()
      updateRepairCharts()
    })
  }
}

// 初始化图表
const initCharts = () => {
  if (orderCountChart.value && !orderCountChartInstance) {
    orderCountChartInstance = echarts.init(orderCountChart.value)
  }
  if (durationChart.value && !durationChartInstance) {
    durationChartInstance = echarts.init(durationChart.value)
  }
  if (scoreChart.value && !scoreChartInstance) {
    scoreChartInstance = echarts.init(scoreChart.value)
  }
  if (durationSourceChart.value && !durationSourceChartInstance) {
    durationSourceChartInstance = echarts.init(durationSourceChart.value)
  }
}

// 更新图表
const updateCharts = () => {
  if (!statisticsList.value || statisticsList.value.length === 0) {
    return
  }

  // 获取分组标签
  const labels = statisticsList.value.map(item => {
    return groupFields.value.map(field => item[field]).filter(Boolean).join('-')
  })

  // 工单数量统计图
  if (orderCountChartInstance) {
    const option = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      legend: {
        data: ['维保工单', '维修工单']
      },
      xAxis: {
        type: 'category',
        data: labels,
        axisLabel: {
          interval: 0,
          rotate: 30
        }
      },
      yAxis: {
        type: 'value',
        name: '数量'
      },
      series: [
        {
          name: '维保工单',
          type: 'bar',
          data: statisticsList.value.map(item => item.work_order_count || 0),
          itemStyle: { color: '#409EFF' }
        },
        {
          name: '维修工单',
          type: 'bar',
          data: statisticsList.value.map(item => item.repair_order_count || 0),
          itemStyle: { color: '#67C23A' }
        }
      ]
    }
    orderCountChartInstance.setOption(option)
  }

  // 工时统计图
  if (durationChartInstance) {
    const totalDuration = statisticsList.value.reduce((sum, item) => sum + (item.total_duration || 0), 0)
    const totalAccept = statisticsList.value.reduce((sum, item) => sum + (item.total_accept_duration || 0), 0)
    const totalPrepare = statisticsList.value.reduce((sum, item) => sum + (item.total_prepare_duration || 0), 0)
    const totalOperation = statisticsList.value.reduce((sum, item) => sum + (item.total_operation_duration || 0), 0)

    const option = {
      tooltip: {
        trigger: 'axis'
      },
      legend: {
        data: ['总工时', '接单时长', '准备时长', '操作时长']
      },
      xAxis: {
        type: 'category',
        data: labels,
        axisLabel: {
          interval: 0,
          rotate: 30
        }
      },
      yAxis: {
        type: 'value',
        name: '小时'
      },
      series: [
        {
          name: '总工时',
          type: 'line',
          data: statisticsList.value.map(item => (item.total_duration || 0).toFixed(1)),
          itemStyle: { color: '#E6A23C' }
        },
        {
          name: '接单时长',
          type: 'line',
          data: statisticsList.value.map(item => (item.total_accept_duration || 0).toFixed(1)),
          itemStyle: { color: '#409EFF' }
        },
        {
          name: '准备时长',
          type: 'line',
          data: statisticsList.value.map(item => (item.total_prepare_duration || 0).toFixed(1)),
          itemStyle: { color: '#67C23A' }
        },
        {
          name: '操作时长',
          type: 'line',
          data: statisticsList.value.map(item => (item.total_operation_duration || 0).toFixed(1)),
          itemStyle: { color: '#F56C6C' }
        }
      ]
    }
    durationChartInstance.setOption(option)
  }

  // 分数统计图
  if (scoreChartInstance) {
    const annualScore = statisticsList.value.reduce((sum, item) => sum + (item.annual_inspection_score || 0), 0)
    const semiAnnualScore = statisticsList.value.reduce((sum, item) => sum + (item.semi_annual_inspection_score || 0), 0)
    const boltScore = statisticsList.value.reduce((sum, item) => sum + (item.bolt_inspection_score || 0), 0)

    const option = {
      tooltip: {
        trigger: 'axis'
      },
      legend: {
        data: ['年检分数', '半年检分数', '螺栓检分数']
      },
      xAxis: {
        type: 'category',
        data: labels,
        axisLabel: {
          interval: 0,
          rotate: 30
        }
      },
      yAxis: {
        type: 'value',
        name: '分数'
      },
      series: [
        {
          name: '年检分数',
          type: 'bar',
          data: statisticsList.value.map(item => (item.annual_inspection_score || 0).toFixed(1)),
          itemStyle: { color: '#409EFF' }
        },
        {
          name: '半年检分数',
          type: 'bar',
          data: statisticsList.value.map(item => (item.semi_annual_inspection_score || 0).toFixed(1)),
          itemStyle: { color: '#67C23A' }
        },
        {
          name: '螺栓检分数',
          type: 'bar',
          data: statisticsList.value.map(item => (item.bolt_inspection_score || 0).toFixed(1)),
          itemStyle: { color: '#E6A23C' }
        }
      ]
    }
    scoreChartInstance.setOption(option)
  }

  // 工时来源分布图
  if (durationSourceChartInstance) {
    const totalAccept = statisticsList.value.reduce((sum, item) => sum + (item.total_accept_duration || 0), 0)
    const totalPrepare = statisticsList.value.reduce((sum, item) => sum + (item.total_prepare_duration || 0), 0)
    const totalOperation = statisticsList.value.reduce((sum, item) => sum + (item.total_operation_duration || 0), 0)

    const option = {
      tooltip: {
        trigger: 'item'
      },
      legend: {
        orient: 'vertical',
        left: 'left'
      },
      series: [
        {
          name: '工时来源',
          type: 'pie',
          radius: '50%',
          data: [
            { value: totalAccept.toFixed(1), name: '接单时长', itemStyle: { color: '#E6A23C' } },
            { value: totalPrepare.toFixed(1), name: '准备时长', itemStyle: { color: '#409EFF' } },
            { value: totalOperation.toFixed(1), name: '操作时长', itemStyle: { color: '#67C23A' } }
          ],
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    }
    durationSourceChartInstance.setOption(option)
  }
}

// 更新维修工单图表
const updateRepairCharts = () => {
  if (!processedRepairData.value || processedRepairData.value.length === 0 || maintenanceTypes.value.length === 0) {
    return
  }

  // 获取分组标签
  const labels = processedRepairData.value.map(item => {
    return groupFields.value.map(field => item[field]).filter(Boolean).join('-')
  })

  // 动态生成系列数据
  if (scoreChartInstance) {
    const colors = ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C', '#909399', '#00C9FF', '#FFB800']
    const series = maintenanceTypes.value.map((type, index) => ({
      name: type + '类分数',
      type: 'bar',
      data: processedRepairData.value.map(item => (item.types?.[type]?.score || 0).toFixed(1)),
      itemStyle: { color: colors[index % colors.length] }
    }))

    const option = {
      tooltip: {
        trigger: 'axis'
      },
      legend: {
        data: maintenanceTypes.value.map(type => type + '类分数')
      },
      xAxis: {
        type: 'category',
        data: labels,
        axisLabel: {
          interval: 0,
          rotate: 30
        }
      },
      yAxis: {
        type: 'value',
        name: '分数'
      },
      series: series
    }
    scoreChartInstance.setOption(option)
  }
}

// 监听分组维度变化，自动查询
watch(groupFields, () => {
  getStatisticsList()
  getRepairStatisticsList()
  getRuntimeScoreStatisticsList()
}, { deep: true })

// 监听窗口大小变化
const handleResize = () => {
  orderCountChartInstance?.resize()
  durationChartInstance?.resize()
  scoreChartInstance?.resize()
  durationSourceChartInstance?.resize()
}

onMounted(() => {
  getMaintenanceTypesList()
  getStatisticsList()
  getRepairStatisticsList()
  getRuntimeScoreStatisticsList()
  window.addEventListener('resize', handleResize)
})

// 组件销毁时清理
import { onBeforeUnmount } from 'vue'
onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize)
  orderCountChartInstance?.dispose()
  durationChartInstance?.dispose()
  scoreChartInstance?.dispose()
  durationSourceChartInstance?.dispose()
})
</script>

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

  .filter-card {
    margin-bottom: 20px;

    .filter-header {
      margin-bottom: 20px;

      h3 {
        margin: 0;
        font-size: 18px;
        color: #303133;
      }
    }

    :deep(.el-form-item) {
      margin-bottom: 15px;
    }

    :deep(.el-select),
    :deep(.el-date-picker) {
      width: 100%;
    }
  }

  .display-mode-card {
    margin-bottom: 20px;
    text-align: center;
  }

  .table-card {
    :deep(.el-table) {
      font-size: 13px;

      th {
        background-color: #f5f7fa;
        font-weight: 600;
      }
    }
  }

  .chart-card {
    .chart-wrapper {
      padding: 15px;
      background: #f9f9f9;
      border-radius: 8px;

      h4 {
        margin: 0 0 15px 0;
        font-size: 16px;
        color: #303133;
        text-align: center;
      }
    }
  }
}
</style>
