<template>
  <module-container title="模块一 运行数据分析">
    <div class="module-one-content">
      <!-- 新增：统计卡片行 -->
      <div class="stats-row">
        <div class="stat-card">
          <div class="stat-card-inner">
            <div class="stat-left">
              <div class="stat-label">查堵总数（所有大队）</div>
              <div class="stat-content">
                <div class="stat-value">{{ totalBlockedCount }}</div>
                <div class="stat-unit">起</div>
              </div>
            </div>
            <div class="stat-right">
              <div class="stat-title">查堵总数</div>
              <div ref="chart0a" class="echarts-small"></div>
            </div>
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-card-inner">
            <div class="stat-left">
              <div class="stat-label">总查堵万分率</div>
              <div class="stat-content">
                <div class="stat-value">{{ totalBlockedRate.toFixed(2) }}</div>
                <div class="stat-unit">‱</div>
              </div>
            </div>
            <div class="stat-right">
              <div class="stat-title">总查堵万分率</div>
              <div ref="chart0b" class="echarts-small"></div>
            </div>
          </div>
        </div>
      </div>

      <!-- 第一行：每日查堵数量 -->
      <div class="chart-row">
        <div class="chart-item">
          <div class="chart-title">每日查堵数量（总表）</div>
          <div ref="chart1" class="echarts"></div>
        </div>
        <div class="chart-item">
          <div class="chart-title">每日查堵数量（大队对比表）</div>
          <div ref="chart2" class="echarts"></div>
        </div>
      </div>

      <!-- 第二行：每日查堵万分率 -->
      <div class="chart-row">
        <div class="chart-item">
          <div class="chart-title">每日查堵万分率</div>
          <div ref="chart3" class="echarts"></div>
        </div>
        <div class="chart-item">
          <div class="chart-title">每日查堵万分率（大队对比表）</div>
          <div ref="chart4" class="echarts"></div>
        </div>
      </div>

      <!-- 第三行：每日过检图像数 -->
      <div class="chart-row">
        <div class="chart-item">
          <div class="chart-title">每日过检图像数（行检+旅检总表）</div>
          <div ref="chart5" class="echarts"></div>
        </div>
        <div class="chart-item">
          <div class="chart-title">每日过检图像数（行检+旅检大队对比表）</div>
          <div ref="chart6" class="echarts"></div>
        </div>
      </div>

      <!-- 第四行：查堵物品分布和区域查堵数量分布 -->
      <div class="chart-row">
        <div class="chart-item">
          <div class="chart-title">查堵物品分布</div>
          <div ref="chart7" class="echarts"></div>
        </div>
        <div class="chart-item">
          <div class="chart-title">区域查堵数量分布</div>
          <div ref="chart8" class="echarts"></div>
        </div>
      </div>

      <!-- 第五行：查堵类型分布 -->
      <div class="chart-row full-width">
        <div class="chart-item">
          <div class="chart-title">查堵类型分布</div>
          <div ref="chart9" class="echarts"></div>
        </div>
      </div>

      <!-- 第六行：查堵时间段过检行李数及万分率 -->
      <div class="chart-row full-width">
        <div class="chart-item">
          <div class="chart-title">查堵时间段过检行李数及万分率（总表）</div>
          <div ref="chart10" class="echarts"></div>
        </div>
      </div>

      <!-- 第七行：每日过检行李数及万分率 -->
      <div class="chart-row full-width">
        <div class="chart-item">
          <div class="chart-title">每日过检行李数及万分率</div>
          <div ref="chart11" class="echarts"></div>
        </div>
      </div>

      <!-- 第八行：查堵-AI复查图像总数 -->
      <div class="chart-row full-width">
        <div class="chart-item">
          <div class="chart-title">查堵-AI复查图像总数</div>
          <div ref="chart12" class="echarts"></div>
        </div>
      </div>

      <!-- 第九行：AI漏判和误判图像总数 -->
      <div class="chart-row">
        <div class="chart-item">
          <div class="chart-title">查堵-AI漏判图像总数</div>
          <div ref="chart13" class="echarts"></div>
        </div>
        <div class="chart-item">
          <div class="chart-title">查堵-AI误判图像总数</div>
          <div ref="chart14" class="echarts"></div>
        </div>
      </div>
    </div>
  </module-container>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import * as echarts from 'echarts'
import { formatDateHy } from '@/utils/index.js'
import ModuleContainer from './ModuleContainer.vue'
import { useEcharts } from '@/hooks/chart.js'
import {
  totalCount,
  brigadeChart,
  totalRate,
  brigadeRateChart,
  dailyTrend,
  dailyBrigadeComparison,
  dailyRateTrend,
  dailyBrigadeRateComparison,
  dailyLuggageTrend,
  dailyBrigadeLuggageComparison,
  itemDistribution,
  areaDistribution,
  discriminationDistribution,
  timePeriodStats,
  dailyLuggageAndRate,
  aiImageStats,
  aiMissImageStats,
  aiErrorImageStats
} from '@/api/blockingData/blockingDataScreen.js'

// 接收筛选参数
const props = defineProps({
  filterParams: {
    type: Object,
    default: () => ({})
  }
})
const totalBlockedCount = ref(0)
const totalBlockedRate = ref(0)
// 处理filterParams，将dateRange拆分为startTime和endTime
const processFilterParams = (params) => {
  const { dateRange, ...rest } = params
  const processed = { ...rest }

  if (dateRange && Array.isArray(dateRange) && dateRange.length === 2) {
    processed.startTime = formatDateHy(dateRange[0])
    processed.endTime = formatDateHy(dateRange[1])
  }
  if (processed.brigadeId == 'all') {
    delete processed.brigadeId
  }
  if (processed.terminalId == 'all') {
    delete processed.terminalId
  }

  return processed
}



// 图表引用
const chart0a = ref(null)
const chart0b = ref(null)
const chart1 = ref(null)
const chart2 = ref(null)
const chart3 = ref(null)
const chart4 = ref(null)
const chart5 = ref(null)
const chart6 = ref(null)
const chart7 = ref(null)
const chart8 = ref(null)
const chart9 = ref(null)
const chart10 = ref(null)
const chart11 = ref(null)
const chart12 = ref(null)
const chart13 = ref(null)
const chart14 = ref(null)

// 图表设置函数
const { setOption: setOption0a } = useEcharts(chart0a)
const { setOption: setOption0b } = useEcharts(chart0b)
const { setOption: setOption1 } = useEcharts(chart1)
const { setOption: setOption2 } = useEcharts(chart2)
const { setOption: setOption3 } = useEcharts(chart3)
const { setOption: setOption4 } = useEcharts(chart4)
const { setOption: setOption5 } = useEcharts(chart5)
const { setOption: setOption6 } = useEcharts(chart6)
const { setOption: setOption7 } = useEcharts(chart7)
const { setOption: setOption8 } = useEcharts(chart8)
const { setOption: setOption9 } = useEcharts(chart9)
const { setOption: setOption10 } = useEcharts(chart10)
const { setOption: setOption11 } = useEcharts(chart11)
const { setOption: setOption12 } = useEcharts(chart12)
const { setOption: setOption13 } = useEcharts(chart13)
const { setOption: setOption14 } = useEcharts(chart14)

// 加载所有数据
const loadData = async () => {
  const queryParams = processFilterParams(props.filterParams)

  try {
    // 统计卡片数据
    const [totalCountRes, totalRateRes] = await Promise.allSettled([
      totalCount(queryParams),
      totalRate(queryParams)
    ])

    totalBlockedCount.value = totalCountRes.value?.data?.totalBlockedCount || 0
    totalBlockedRate.value = totalRateRes.value?.data?.totalBlockedRate || 0


    const [brigadeChartRes, brigadeRateRes] = await Promise.allSettled([
      brigadeChart(queryParams),
      brigadeRateChart(queryParams)
    ])

    const brigadeChartData = brigadeChartRes.value?.data || []
    const brigadeRateData = brigadeRateRes.value?.data || []

    const chart0aOption = {
      grid: {
        left: '5%',
        top: '5%',
        right: '5%',
        bottom: '5%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: brigadeChartData.map(d => d.brigadeName),
        show: true,
        axisLine: { lineStyle: { color: '#999' } },
        axisLabel: { fontSize: 10, color: '#666' }
      },
      yAxis: {
        type: 'value',
        show: true,
        axisLine: { lineStyle: { color: '#999' } },
        axisLabel: { fontSize: 10, color: '#666' }
      },
      series: [{
        type: 'bar',
        data: brigadeChartData.map(d => d.totalBlockedCount),
        itemStyle: { color: '#3b82f6' },
        barWidth: 12,
        label: {
          show: true,
          position: 'top',
          fontSize: 10
        }
      }]
    }

    const chart0bOption = {
      grid: {
        left: '5%',
        top: '5%',
        right: '5%',
        bottom: '5%',
        containLabel: true
      },
      xAxis: {
        type: 'value',
        show: true,
        axisLine: { lineStyle: { color: '#999' } },
        axisLabel: { fontSize: 10, color: '#666' }
      },
      yAxis: {
        type: 'category',
        data: brigadeRateData.map(d => d.brigadeName),
        show: true,
        axisLine: { lineStyle: { color: '#999' } },
        axisLabel: { fontSize: 10, color: '#666' }
      },
      series: [{
        type: 'bar',
        data: brigadeRateData.map(d => Number(d.avgBlockedRate.toFixed(2))),
        itemStyle: { color: '#3b82f6' },
        barWidth: 8,
        label: {
          show: true,
          position: 'right',
          fontSize: 10,
          formatter: '{c}'
        }
      }]
    }

    setOption0a(chart0aOption)
    setOption0b(chart0bOption)

    // 每日查堵数量
    const [dailyTrendRes, dailyBrigadeRes] = await Promise.allSettled([
      dailyTrend(queryParams),
      dailyBrigadeComparison(queryParams)
    ])
    console.log(dailyTrendRes, dailyBrigadeRes, 1)

    const trendData = dailyTrendRes?.value?.data || []
    const brigadeData = dailyBrigadeRes?.value?.data || []

    setOption1(lineChartOption(
      trendData.map(d => d.totalBlockedCount),
      '#3b82f6',
      '查堵数量',
      trendData.map(d => d.statDate ? d.statDate.split('T')[0] : '')
    ))

    const uniqueBrigades = [...new Set(brigadeData.map(d => d.brigadeName))]
    const allDates = [...new Set(brigadeData.map(d => d.statDate ? d.statDate.split('T')[0] : ''))].sort()
    const brigadeDatasets = uniqueBrigades.map(brigadeName => {
      return allDates.map(date => {
        const found = brigadeData.find(d =>
          d.brigadeName === brigadeName && d.statDate && d.statDate.split('T')[0] === date
        )
        return found ? found.totalBlockedCount : 0
      })
    })

    setOption2(multiLineChartOption(
      brigadeDatasets,
      ['#3b82f6', '#22c55e', '#f97316'],
      uniqueBrigades,
      allDates
    ))

    // 每日查堵万分率
    const [dailyRateTrendRes, dailyBrigadeRateRes] = await Promise.allSettled([
      dailyRateTrend(queryParams),
      dailyBrigadeRateComparison(queryParams)
    ])
    console.log(dailyRateTrendRes, dailyBrigadeRateRes, 3)
    const rateTrendData = dailyRateTrendRes?.value?.data || []
    const rateBrigadeData = dailyBrigadeRateRes?.value?.data || []

    setOption3(lineChartOption(
      rateTrendData.map(d => d.avgBlockedRate),
      '#ec4899',
      '万分率',
      rateTrendData.map(d => d.statDate ? d.statDate.split('T')[0] : '')
    ))

    const rateAllDates = [...new Set(rateBrigadeData.map(d => d.statDate ? d.statDate.split('T')[0] : ''))].sort()
    const rateUniqueBrigades = [...new Set(rateBrigadeData.map(d => d.brigadeName))]
    const rateBrigadeDatasets = rateUniqueBrigades.map(brigadeName => {
      return rateAllDates.map(date => {
        const found = rateBrigadeData.find(d =>
          d.brigadeName === brigadeName && d.statDate && d.statDate.split('T')[0] === date
        )
        return found ? found.avgBlockedRate : 0
      })
    })

    setOption4(multiLineChartOption(
      rateBrigadeDatasets,
      ['#3b82f6', '#22c55e', '#f97316'],
      rateUniqueBrigades,
      rateAllDates
    ))

    // 每日过检图像数
    const [dailyLuggageTrendRes, dailyBrigadeLuggageRes] = await Promise.allSettled([
      dailyLuggageTrend(queryParams),
      dailyBrigadeLuggageComparison(queryParams)
    ])

    const luggageTrendData = dailyLuggageTrendRes?.value?.data || []
    const luggageBrigadeData = dailyBrigadeLuggageRes?.value?.data || []
    console.log(luggageTrendData, luggageBrigadeData, 555)
    if (luggageTrendData.length > 0) {
      setOption5(lineChartOption(
        luggageTrendData.map(d => d.totalLuggageCount),
        '#8b5cf6',
        '过检图像数',
        luggageTrendData.map(d => d.statDate ? d.statDate.split('T')[0] : '')
      ))
    }


    const luggageAllDates = [...new Set(luggageBrigadeData.map(d => d.statDate ? d.statDate.split('T')[0] : ''))].sort()
    const luggageUniqueBrigades = [...new Set(luggageBrigadeData.map(d => d.brigadeName))]
    const luggageBrigadeDatasets = luggageUniqueBrigades.map(brigadeName => {
      return luggageAllDates.map(date => {
        const found = luggageBrigadeData.find(d =>
          d.brigadeName === brigadeName && d.statDate && d.statDate.split('T')[0] === date
        )
        return found ? found.totalLuggageCount : 0
      })
    })
    if (luggageBrigadeDatasets.length > 0) {
      setOption6(multiLineChartOption(
        luggageBrigadeDatasets,
        ['#3b82f6', '#22c55e', '#f97316'],
        luggageUniqueBrigades,
        luggageAllDates
      ))
    }

    // 查堵物品分布和区域查堵数量分布
    const [itemDistRes, areaDistRes] = await Promise.allSettled([
      itemDistribution(queryParams),
      areaDistribution(queryParams)
    ])
    console.log(itemDistRes, areaDistRes, 55555)
    const itemDistData = itemDistRes?.value?.data || []
    if (itemDistData.length > 0) {
      setOption7({
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          data: itemDistData.map(d => d.missCheckItem)
        },
        series: [
          {
            name: '查堵物品分布',
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            itemStyle: {
              
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: true,
              formatter: '{b}\n{c} ({d}%)',
              fontSize: 10
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '14',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: true
            },
            data: itemDistData.map((d, index) => ({
              value: d.count,
              name: d.missCheckItem,
              itemStyle: {
                color: ['#3b82f6', '#22c55e', '#f97316', '#ec4899', '#8b5cf6', '#14b8a6'][index % 6]
              }
            }))
          }
        ]
      })
    }


    const areaDistData = areaDistRes?.value?.data || {}
    
    // 提取数据
    const brigadeNames = areaDistData.brigadeNames || []
    const luggageDataList = areaDistData.luggageDataList || []
    const blockedDataList = areaDistData.blockedDataList || []
    
    // 柱状图数据（过检行李数）
    const barSeries = [
      {
        name: 'T1旅检行李数',
        type: 'bar',
        data: brigadeNames.map(brigade => {
          const item = luggageDataList.find(d => d.brigadeName === brigade)
          return item ? item.t1PassengerLuggageCount : 0
        }),
        itemStyle: { color: '#3b82f6' },
        label: { show: true, position: 'top', fontSize: 10, color: '#3b82f6' }
      },
      {
        name: 'T2旅检行李数',
        type: 'bar',
        data: brigadeNames.map(brigade => {
          const item = luggageDataList.find(d => d.brigadeName === brigade)
          return item ? item.t2PassengerLuggageCount : 0
        }),
        itemStyle: { color: '#22c55e' },
        label: { show: true, position: 'top', fontSize: 10, color: '#22c55e' }
      },
      {
        name: 'T1行检行李数',
        type: 'bar',
        data: brigadeNames.map(brigade => {
          const item = luggageDataList.find(d => d.brigadeName === brigade)
          return item ? item.t1CargoLuggageCount : 0
        }),
        itemStyle: { color: '#f97316' },
        label: { show: true, position: 'top', fontSize: 10, color: '#f97316' }
      },
      {
        name: 'T2行检行李数',
        type: 'bar',
        data: brigadeNames.map(brigade => {
          const item = luggageDataList.find(d => d.brigadeName === brigade)
          return item ? item.t2CargoLuggageCount : 0
        }),
        itemStyle: { color: '#ec4899' },
        label: { show: true, position: 'top', fontSize: 10, color: '#ec4899' }
      }
    ]
    
    // 折线图数据（查堵数）
    const lineSeries = [
      {
        name: 'T1旅检查堵数',
        type: 'line',
        yAxisIndex: 1,
        data: brigadeNames.map(brigade => {
          const item = blockedDataList.find(d => d.brigadeName === brigade)
          return item ? item.t1PassengerBlockedCount : 0
        }),
        itemStyle: { color: '#3b82f6' },
        lineStyle: { width: 3 },
        symbol: 'circle',
        symbolSize: 8,
        label: { show: true, position: 'top', fontSize: 10, color: '#3b82f6' }
      },
      {
        name: 'T2旅检查堵数',
        type: 'line',
        yAxisIndex: 1,
        data: brigadeNames.map(brigade => {
          const item = blockedDataList.find(d => d.brigadeName === brigade)
          return item ? item.t2PassengerBlockedCount : 0
        }),
        itemStyle: { color: '#22c55e' },
        lineStyle: { width: 3 },
        symbol: 'circle',
        symbolSize: 8,
        label: { show: true, position: 'top', fontSize: 10, color: '#22c55e' }
      },
      {
        name: 'T1行检查堵数',
        type: 'line',
        yAxisIndex: 1,
        data: brigadeNames.map(brigade => {
          const item = blockedDataList.find(d => d.brigadeName === brigade)
          return item ? item.t1CargoBlockedCount : 0
        }),
        itemStyle: { color: '#f97316' },
        lineStyle: { width: 3 },
        symbol: 'circle',
        symbolSize: 8,
        label: { show: true, position: 'top', fontSize: 10, color: '#f97316' }
      },
      {
        name: 'T2行检查堵数',
        type: 'line',
        yAxisIndex: 1,
        data: brigadeNames.map(brigade => {
          const item = blockedDataList.find(d => d.brigadeName === brigade)
          return item ? item.t2CargoBlockedCount : 0
        }),
        itemStyle: { color: '#ec4899' },
        lineStyle: { width: 3 },
        symbol: 'circle',
        symbolSize: 8,
        label: { show: true, position: 'top', fontSize: 10, color: '#ec4899' }
      }
    ]
    
    setOption8({
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross'
        },
        formatter: function(params) {
          let result = params[0].name + '<br/>'
          params.forEach(param => {
            if (param.seriesType === 'bar') {
              result += `${param.marker} ${param.seriesName}: ${param.value.toLocaleString()} 件<br/>`
            } else {
              result += `${param.marker} ${param.seriesName}: ${param.value} 次<br/>`
            }
          })
          return result
        }
      },
      legend: {
       
        data: [
          'T1旅检行李数', 'T2旅检行李数', 'T1行检行李数', 'T2行检行李数',
          'T1旅检查堵数', 'T2旅检查堵数', 'T1行检查堵数', 'T2行检查堵数'
        ]
      },
      grid: {
       top: '80',
        left: '3%',
        right: '4%',
         bottom: '1%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: brigadeNames,
        // axisLabel: {
        //   rotate: 45
        // }
      },
      yAxis: [
        {
          type: 'value',
          name: '行李数',
          position: 'left',
          axisLine: {
            lineStyle: {
              color: '#3b82f6'
            }
          },
          axisLabel: {
            formatter: '{value} 件'
          }
        },
        {
          type: 'value',
          name: '查堵数',
          position: 'right',
          axisLine: {
            lineStyle: {
              color: '#ec4899'
            }
          },
          axisLabel: {
            formatter: '{value} 次'
          }
        }
      ],
      series: [...barSeries, ...lineSeries]
    })


    // 查堵类型分布
    const discDistRes = await discriminationDistribution(queryParams)
    const discDistData = discDistRes.data || []
    
    // 按discriminationType分组数据
    const groupedData = {}
    discDistData.forEach(item => {
      if (!groupedData[item.discriminationType]) {
        groupedData[item.discriminationType] = []
      }
      groupedData[item.discriminationType].push(item)
    })
    
    // 提取所有missCheckItem作为横坐标
    const allMissCheckItems = [...new Set(discDistData.map(d => d.missCheckItem))]
    
    // 为每个discriminationType创建数据系列
    const seriesData = Object.keys(groupedData).map((type, index) => {
      const data = allMissCheckItems.map(item => {
        const found = groupedData[type].find(d => d.missCheckItem === item)
        return found ? found.count : 0
      })
      const color = ['#3b82f6', '#22c55e', '#f97316', '#ec4899', '#8b5cf6', '#14b8a6'][index % 6]
      return {
        name: type,
        type: 'bar',
        data: data,
        itemStyle: { color: color },
        label: { show: true, position: 'top', fontSize: 10, color: color }
      }
    })
    
    setOption9({
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      legend: {
        data: Object.keys(groupedData)
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: allMissCheckItems,
        axisLabel: {
          rotate: 45
        }
      },
      yAxis: {
        type: 'value'
      },
      series: seriesData
    })

    // 查堵时间段过检行李数及万分率
    const timePeriodRes = await timePeriodStats(queryParams)
    const timePeriodData = timePeriodRes.data || []
    
    setOption10({
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross'
        },
        formatter: function(params) {
          let result = params[0].name + '<br/>'
          params.forEach(param => {
            if (param.seriesName === '过检行李数') {
              result += `${param.marker} ${param.seriesName}: ${param.value} 件<br/>`
            } else {
              result += `${param.marker} ${param.seriesName}: ${param.value} ‰<br/>`
            }
          })
          return result
        }
      },
      legend: {
        data: ['过检行李数', '查堵万分率']
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: timePeriodData.map(d => d.timePeriod),
        axisLabel: {
          rotate: 45
        }
      },
      yAxis: [
        {
          type: 'value',
          name: '过检行李数',
          position: 'left',
          axisLine: {
            lineStyle: {
              color: '#3b82f6'
            }
          },
          axisLabel: {
            formatter: '{value} 件'
          }
        },
        {
          type: 'value',
          name: '查堵万分率',
          position: 'right',
          axisLine: {
            lineStyle: {
              color: '#ec4899'
            }
          },
          axisLabel: {
            formatter: '{value} ‰'
          }
        }
      ],
      series: [
        {
          name: '过检行李数',
          type: 'bar',
          yAxisIndex: 0,
          data: timePeriodData.map(d => d.totalLuggageCount),
          itemStyle: { color: '#3b82f6' },
          label: { show: true, position: 'top', fontSize: 10, color: '#3b82f6' }
        },
        {
          name: '查堵万分率',
          type: 'line',
          yAxisIndex: 1,
          data: timePeriodData.map(d => d.blockRate),
          itemStyle: { color: '#ec4899' },
          lineStyle: { width: 3 },
          symbol: 'circle',
          symbolSize: 8,
          label: { show: true, position: 'top', fontSize: 10, color: '#ec4899' }
        }
      ]
    })

    // 每日过检行李数及万分率
    const dailyLuggageRes = await dailyLuggageAndRate(queryParams)
    const dailyLuggageData = dailyLuggageRes.data || []
    
    setOption11({
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross'
        },
        formatter: function(params) {
          let result = params[0].name + '<br/>'
          params.forEach(param => {
            if (param.seriesName === '过检行李数') {
              result += `${param.marker} ${param.seriesName}: ${param.value} 件<br/>`
            } else {
              result += `${param.marker} ${param.seriesName}: ${param.value} ‰<br/>`
            }
          })
          return result
        }
      },
      legend: {
        data: ['过检行李数', '查堵万分率']
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: dailyLuggageData.map(d => d.timePeriod),
        axisLabel: {
          rotate: 45
        }
      },
      yAxis: [
        {
          type: 'value',
          name: '过检行李数',
          position: 'left',
          axisLine: {
            lineStyle: {
              color: '#3b82f6'
            }
          },
          axisLabel: {
            formatter: '{value} 件'
          }
        },
        {
          type: 'value',
          name: '查堵万分率',
          position: 'right',
          axisLine: {
            lineStyle: {
              color: '#ec4899'
            }
          },
          axisLabel: {
            formatter: '{value} ‰'
          }
        }
      ],
      series: [
        {
          name: '过检行李数',
          type: 'bar',
          yAxisIndex: 0,
          data: dailyLuggageData.map(d => d.totalLuggageCount),
          itemStyle: { color: '#3b82f6' },
          label: { show: true, position: 'top', fontSize: 10, color: '#3b82f6' }
        },
        {
          name: '查堵万分率',
          type: 'line',
          yAxisIndex: 1,
          data: dailyLuggageData.map(d => d.blockRate),
          itemStyle: { color: '#ec4899' },
          lineStyle: { width: 3 },
          symbol: 'circle',
          symbolSize: 8,
          label: { show: true, position: 'top', fontSize: 10, color: '#ec4899' }
        }
      ]
    })

    // AI复查图像总数
    const aiImageRes = await aiImageStats(queryParams)
    const aiImageData = aiImageRes.data || []
    
    setOption12({
      tooltip: {
        trigger: 'axis',
        formatter: function(params) {
          return `${params[0].name}<br/>AI复查图像数: ${params[0].value} 张`
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: aiImageData.map(d => d.statDate ? d.statDate.split('T')[0] : ''),
        axisLabel: {
          rotate: 45
        }
      },
      yAxis: {
        type: 'value',
        name: '图像数',
        axisLabel: {
          formatter: '{value} 张'
        }
      },
      series: [
        {
          name: 'AI复查图像数',
          type: 'line',
          data: aiImageData.map(d => d.totalBlockedCount),
          itemStyle: { color: '#14b8a6' },
          lineStyle: { width: 3 },
          symbol: 'circle',
          symbolSize: 8,
          label: { show: true, position: 'top', fontSize: 10, color: '#14b8a6' },
          areaStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [
                { offset: 0, color: 'rgba(20, 184, 166, 0.3)' },
                { offset: 1, color: 'rgba(20, 184, 166, 0.1)' }
              ]
            }
          }
        }
      ]
    })

    // AI漏判和误判图像总数
    const [aiMissRes, aiErrorRes] = await Promise.all([
      aiMissImageStats(queryParams),
      aiErrorImageStats(queryParams)
    ])

    const aiMissData = aiMissRes.data || []
    const aiErrorData = aiErrorRes.data || []

    // AI漏判图像数
    setOption13({
      tooltip: {
        trigger: 'axis',
        formatter: function(params) {
          return `${params[0].name}<br/>AI漏判图像数: ${params[0].value} 张`
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: aiMissData.map(d => d.statDate ? d.statDate.split('T')[0] : ''),
        axisLabel: {
          rotate: 45
        }
      },
      yAxis: {
        type: 'value',
        name: '图像数',
        axisLabel: {
          formatter: '{value} 张'
        }
      },
      series: [
        {
          name: 'AI漏判图像数',
          type: 'line',
          data: aiMissData.map(d => d.totalBlockedCount),
          itemStyle: { color: '#ef4444' },
          lineStyle: { width: 3 },
          symbol: 'circle',
          symbolSize: 8,
          label: { show: true, position: 'top', fontSize: 10, color: '#ef4444' },
          areaStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [
                { offset: 0, color: 'rgba(239, 68, 68, 0.3)' },
                { offset: 1, color: 'rgba(239, 68, 68, 0.1)' }
              ]
            }
          }
        }
      ]
    })

    // AI误判图像数
    setOption14({
      tooltip: {
        trigger: 'axis',
        formatter: function(params) {
          return `${params[0].name}<br/>AI误判图像数: ${params[0].value} 张`
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: aiErrorData.map(d => d.statDate ? d.statDate.split('T')[0] : ''),
        axisLabel: {
          rotate: 45
        }
      },
      yAxis: {
        type: 'value',
        name: '图像数',
        axisLabel: {
          formatter: '{value} 张'
        }
      },
      series: [
        {
          name: 'AI误判图像数',
          type: 'line',

          data: aiErrorData.map(d => d.totalBlockedCount),
          itemStyle: { color: '#f97316' },
          lineStyle: { width: 3 },
          symbol: 'circle',
          symbolSize: 8,
          label: { show: true, position: 'top', fontSize: 10, color: '#f97316' },
          areaStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [
                { offset: 0, color: 'rgba(249, 115, 22, 0.3)' },
                { offset: 1, color: 'rgba(249, 115, 22, 0.1)' }
              ]
            }
          }
        }
      ]
    })

  } catch (error) {
    console.error('加载数据失败:', error)
  }
}



// 折线图配置（总表）
const lineChartOption = (data, color, title, xAxisData = []) => ({
  tooltip: {
    trigger: 'axis',
    axisPointer: { type: 'line' }
  },
  grid: {
    left: '10%',
    top: '15%',
    right: '5%',
    bottom: '15%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    data: xAxisData,
    axisLine: { lineStyle: { color: '#999' } },
    axisLabel: { fontSize: 10, color: '#666', rotate: 0 }
  },
  yAxis: {
    type: 'value',
    axisLine: { lineStyle: { color: '#999' } },
    axisLabel: { fontSize: 10, color: '#666' },
    splitLine: { lineStyle: { color: '#eee' } }
  },
  series: [{
    name: title,
    type: 'line',
    smooth: true,
    symbol: 'circle',
    symbolSize: 6,
    data: data,
    itemStyle: { color: color },
    lineStyle: { color: color },
    label: {
      show: true,
      position: 'top',
      fontSize: 10,
      color: color
    }
  }]
})

// 多折线图配置（大队对比）
const multiLineChartOption = (dataList, colors, legends, xAxisData = []) => ({
  tooltip: {
    trigger: 'axis',
    axisPointer: { type: 'line' }
  },
  grid: {
    left: '10%',
    top: '15%',
    right: '5%',
    bottom: '15%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    data: xAxisData,
    axisLine: { lineStyle: { color: '#999' } },
    axisLabel: { fontSize: 10, color: '#666', rotate: 0 }
  },
  yAxis: {
    type: 'value',
    axisLine: { lineStyle: { color: '#999' } },
    axisLabel: { fontSize: 10, color: '#666' },
    splitLine: { lineStyle: { color: '#eee' } }
  },
  legend: {
    top: 0,
    right: 10,
    textStyle: { fontSize: 10 }
  },
  series: dataList.map((data, index) => ({
    name: legends[index],
    type: 'line',
    smooth: true,
    symbol: 'circle',
    symbolSize: 6,
    data: data,
    itemStyle: { color: colors[index] },
    lineStyle: { color: colors[index] },
    label: {
      show: true,
      position: 'top',
      fontSize: 10,
      color: colors[index]
    }
  }))
})

// 环形饼图配置
const ringPieOption = (data, colors) => ({
  color: colors,
  series: [{
    type: 'pie',
    radius: ['45%', '70%'],
    center: ['50%', '55%'],
    data: data,
    label: {
      show: true,
      formatter: '{b}\n{c}%',
      fontSize: 10
    },
    labelLine: {
      show: true,
      length: 15,
      length2: 10
    }
  }]
})

// 柱状图配置
const barChartOption = (data, color, isHorizontal = false) => ({
  grid: {
    left: '15%',
    top: '15%',
    right: '5%',
    bottom: '15%',
    containLabel: true
  },
  xAxis: {
    type: isHorizontal ? 'value' : 'category',
    data: isHorizontal ? null : data.map(d => d.name),
    axisLine: { lineStyle: { color: '#999' } },
    axisLabel: { fontSize: 10, color: '#666' }
  },
  yAxis: {
    type: isHorizontal ? 'category' : 'value',
    data: isHorizontal ? data.map(d => d.name) : null,
    axisLine: { lineStyle: { color: '#999' } },
    axisLabel: { fontSize: 10, color: '#666' },
    splitLine: { lineStyle: { color: '#eee' } }
  },
  series: [{
    type: 'bar',
    data: isHorizontal ? data.map(d => d.value) : data,
    itemStyle: { color: color },
    barWidth: isHorizontal ? 15 : 20
  }]
})

// 双Y轴柱状图配置（用于行李数和万分率）
const dualAxisBarChartOption = (data1, data2, color1, color2) => ({
  grid: {
    left: '10%',
    top: '15%',
    right: '10%',
    bottom: '15%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    data: [],
    axisLine: { lineStyle: { color: '#999' } },
    axisLabel: { fontSize: 10, color: '#666' }
  },
  yAxis: [
    {
      type: 'value',
      name: '行李数',
      axisLine: { lineStyle: { color: color1 } },
      axisLabel: { fontSize: 10, color: color1 }
    },
    {
      type: 'value',
      name: '万分率',
      axisLine: { lineStyle: { color: color2 } },
      axisLabel: { fontSize: 10, color: color2 }
    }
  ],
  series: [
    {
      name: '行李数',
      type: 'bar',
      data: data1,
      itemStyle: { color: color1 },
      barWidth: 15
    },
    {
      name: '万分率',
      type: 'line',
      yAxisIndex: 1,
      smooth: true,
      data: data2,
      itemStyle: { color: color2 },
      lineStyle: { color: color2 }
    }
  ]
})



// 监听filterParams变化
watch(() => props.filterParams, () => {
  loadData()
}, { deep: true })

onMounted(() => {
  loadData()
})
</script>

<style lang="less" scoped>
.module-one-content {
  height: 100%;
  display: flex;
  flex-direction: column;
  gap: 10px;
  overflow-y: auto;

}

.stats-row {
  display: flex;
  gap: 10px;
  flex-shrink: 0;
}

.stat-card {
  flex: 1;


  min-height: 120px;
}

.stat-card-inner {
  display: flex;
  height: 100%;
  align-items: center;
  gap: 10px;

}

.stat-left {
  background: #fff;
  border-radius: 6px;
  border: 1px solid #eee;
  padding: 15px;
  height: 100%;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  flex: 1;
  display: flex;
  align-items: center;
  flex-direction: column;

  padding-right: 15px;
}

.stat-label {
  width: 100%;
  font-size: 17px;
  color: black;
  margin-bottom: 8px;
}

.stat-content {
  margin-top: 15%;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.stat-value {
  font-size: 80px;
  font-weight: bold;
  color: #3b82f6;

}

.stat-unit {
  font-size: 24px;
  font-weight: bold;
  color: #3b82f6;
}

.stat-right {
  background: #fff;
  border-radius: 6px;
  border: 1px solid #eee;
  padding: 15px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  height: 100%;
}

.stat-title {
  font-size: 17px;
  color: black;
  margin-bottom: 5px;
  font-weight: 500;
}

.echarts-small {
  width: 100%;
  height: 300px;
  min-height: 300px;
}

.chart-row {
  display: flex;
  gap: 10px;
  flex-shrink: 0;
}

.chart-row.full-width {
  flex-direction: column;
}

.chart-item {
  flex: 1;
  background: #fff;
  border-radius: 6px;
  padding: 15px;
  border: 1px solid #eee;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  display: flex;
  flex-direction: column;
  min-height: 400px;
}

.chart-row.full-width .chart-item {
  flex: none;
  height: 280px;
}

.chart-title {
  font-size: 17px;
  color: black;
  margin-bottom: 5px;
  text-align: left;
}

.echarts {
  flex: 1;
  width: 100%;
  min-height: 0;
}
</style>