<template>
  <div class="run-screen-container">
    <!-- 页面标题 -->
    <div class="page-title">
      <h1>盛世鹰眸质控系统[生产运行]（安检站）</h1>
    </div>

    <!-- 模块一：运行数据 -->
    <div class="module-title-wrapper">
      <div class="module-title">模块一：运行数据</div>
    </div>



    <!-- 第一行 -->
    <el-row :gutter="20" class="row-margin">
      <!-- 左边50%：两个div -->
      <el-col :span="12">
        <el-row :gutter="20" style="height: 100%;">
          <el-col :span="12">
            <div class="data-card">
              <div class="card-title">旅检过检总人数</div>
              <div class="card-value-wrapper" style="color: #E8B140;">
                <span class="card-value">{{ runData.passengerTotal }}</span>
                <span class="card-unit">人</span>
              </div>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="data-card">
              <div class="card-title">行检过检总行李数</div>
              <div class="card-value-wrapper" style="color: #26B6BE;">
                <span class="card-value">{{ runData.luggageTotal }}</span>
                <span class="card-unit">件</span>
              </div>
            </div>
          </el-col>
        </el-row>
      </el-col>
      <!-- 右边50%：T1旅检过检人数折线图 -->
      <el-col :span="12">
        <div class="chart-card">
          <div class="chart-title">T1旅检过检人数</div>
          <div ref="t1TravelChart" class="chart-container"></div>
        </div>
      </el-col>
    </el-row>

    <!-- 第二行 -->
    <el-row :gutter="20" class="row-margin">
      <el-col :span="12">
        <div class="chart-card">
          <div class="chart-title">T2旅检过检人数</div>
          <div ref="t2TravelChart" class="chart-container"></div>
        </div>
      </el-col>
      <el-col :span="12">
        <div class="chart-card">
          <div class="chart-title">行检过检数</div>
          <div ref="luggageChart" class="chart-container"></div>
        </div>
      </el-col>
    </el-row>

    <!-- 第三行 -->
    <el-row :gutter="20" class="row-margin">
      <el-col :span="8">
        <div class="data-card">
          <div class="card-title">国内货站总过检数</div>
          <div class="card-value-wrapper" style="color: #E8B140;padding: 30px;">
            <span class="card-value">{{ runData.domesticCargoTotal }}</span>
            <span class="card-unit">件</span>
          </div>
        </div>
      </el-col>
      <el-col :span="8">
        <div class="data-card">
          <div class="card-title">国际货站总过检数</div>
          <div class="card-value-wrapper" style="color: #26B6BE;padding: 30px;">
            <span class="card-value">{{ runData.intlCargoTotal }}</span>
            <span class="card-unit">件</span>
          </div>
        </div>
      </el-col>
      <el-col :span="8">
        <div class="data-card">
          <div class="card-title">道口车辆过检数</div>
          <div class="card-value-wrapper" style="color: #5680C9;padding: 30px;">
            <span class="card-value">{{ runData.vehicleCheckTotal }}</span>
            <span class="card-unit">辆</span>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 第四行 -->
    <el-row :gutter="20" class="row-margin">
      <el-col :span="12">
        <div class="chart-card">
          <div class="chart-title">货物过检数</div>
          <div ref="cargoChart" class="chart-container"></div>
        </div>
      </el-col>
      <el-col :span="12">
        <div class="chart-card">
          <div class="chart-title">车辆过检数</div>
          <div ref="vehicleChart" class="chart-container"></div>
        </div>
      </el-col>
    </el-row>


    <!-- 模块二：查获/收缴数据 -->
    <div class="module-title-wrapper">
      <div class="module-title">模块二：查获/收缴数据</div>
    </div>



    <!-- 第一行 -->
    <el-row :gutter="20" class="row-margin">
      <el-col :span="12">
        <div class="chart-card">
          <div class="chart-title">查获数据</div>
          <div ref="seizePieChart" class="chart-container"></div>
        </div>
      </el-col>
      <el-col :span="12">
        <div class="chart-card">
          <div class="chart-title">大队查获数对比图</div>
          <div ref="teamSeizeBarChart" class="chart-container"></div>
        </div>
      </el-col>
    </el-row>

    <!-- 第二行 -->
    <el-row :gutter="20" class="row-margin">
      <el-col :span="12">
        <div class="chart-card">
          <div class="chart-title">T1区域各大队查获数对比图</div>
          <div ref="t1TeamBarChart" class="chart-container"></div>
        </div>
      </el-col>
      <el-col :span="12">
        <div class="chart-card">
          <div class="chart-title">T2区域各大队查获数对比图</div>
          <div ref="t2TeamBarChart" class="chart-container"></div>
        </div>
      </el-col>
    </el-row>

    <!-- 第三行 -->
    <el-row :gutter="20" class="row-margin">
      <el-col :span="12">
        <div class="chart-card">
          <div class="chart-title">不合格充电宝劝阻数组</div>
          <div ref="powerBankPieChart" class="chart-container"></div>
        </div>
      </el-col>
      <el-col :span="12">
        <div class="chart-card">
          <div class="chart-title">待检区收缴禁限带物品数据表</div>
          <div ref="waitingAreaPieChart" class="chart-container"></div>
        </div>
      </el-col>
    </el-row>

  </div>
</template>

<script setup name="RunScreen">
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import * as echarts from 'echarts'
import {
  getOperationSummary,
  getT1PassengerTrend,
  getT2PassengerTrend,
  getLuggageCheckTrend,
  getCargoTrend,
  getVehicleCheckTrend,
  getSeizureCategory,
  getBrigadeSeizureCompare,
  getPowerBankSummary,
  getPendingConfiscate
} from '@/api/runData/runScreen.js'

// 图表引用
const t1TravelChart = ref(null)
const t2TravelChart = ref(null)
const luggageChart = ref(null)
const cargoChart = ref(null)
const vehicleChart = ref(null)
const seizePieChart = ref(null)
const teamSeizeBarChart = ref(null)
const t1TeamBarChart = ref(null)
const t2TeamBarChart = ref(null)
const powerBankPieChart = ref(null)
const waitingAreaPieChart = ref(null)

// 图表实例
let t1TravelChartInstance = null
let t2TravelChartInstance = null
let luggageChartInstance = null
let cargoChartInstance = null
let vehicleChartInstance = null
let seizePieChartInstance = null
let teamSeizeBarChartInstance = null
let t1TeamBarChartInstance = null
let t2TeamBarChartInstance = null
let powerBankPieChartInstance = null
let waitingAreaPieChartInstance = null

// 运行数据
const runData = ref({
  travelInspectionTotal: 0,
  luggageInspectionTotal: 0,
  domesticCargoTotal: 0,
  internationalCargoTotal: 0,
  vehicleInspectionTotal: 0
})

const t1PassengerData = ref([])
const t2PassengerData = ref([])
const luggageCheckData = ref([])
const cargoData = ref([])
const vehicleCheckData = ref([])
const seizureCategoryData = ref([])
const brigadeSeizureData = ref([])
const powerBankData = ref({})
const pendingConfiscateData = ref({})

async function loadData() {
  try {
    const query = {}
    
    const [
      summaryRes,
      t1PassengerRes,
      t2PassengerRes,
      luggageRes,
      cargoRes,
      vehicleRes,
      seizureRes,
      brigadeRes,
      powerBankRes,
      pendingRes
    ] = await Promise.all([
      getOperationSummary(query),
      getT1PassengerTrend(query),
      getT2PassengerTrend(query),
      getLuggageCheckTrend(query),
      getCargoTrend(query),
      getVehicleCheckTrend(query),
      getSeizureCategory(query),
      getBrigadeSeizureCompare(query),
      getPowerBankSummary(query),
      getPendingConfiscate(query)
    ])
    
    if (summaryRes.data) {
      runData.value = summaryRes.data
    }
    
    if (t1PassengerRes.data) {
      t1PassengerData.value = t1PassengerRes.data
    }
    
    if (t2PassengerRes.data) {
      t2PassengerData.value = t2PassengerRes.data
    }
    
    if (luggageRes.data) {
      luggageCheckData.value = luggageRes.data
    }
    
    if (cargoRes.data) {
      cargoData.value = cargoRes.data
    }
    
    if (vehicleRes.data) {
      vehicleCheckData.value = vehicleRes.data
    }
    
    if (seizureRes.data) {
      seizureCategoryData.value = seizureRes.data
    }
    
    if (brigadeRes.data) {
      brigadeSeizureData.value = brigadeRes.data
    }
    
    if (powerBankRes.data) {
      powerBankData.value = powerBankRes.data
    }
    
    if (pendingRes.data) {
      pendingConfiscateData.value = pendingRes.data
    }
    
    nextTick(() => {
      initCharts()
    })
  } catch (error) {
    console.error('加载数据失败:', error)
  }
}

// 初始化所有图表
function initCharts() {
  // T1旅检过检人数折线图
  if (t1TravelChart.value) {
    t1TravelChartInstance = echarts.init(t1TravelChart.value)
    const t1Data = t1PassengerData.value || []
    t1TravelChartInstance.setOption({
      tooltip: { trigger: 'axis' },
      legend: { data: ['A区', 'B区'], top: 30 },
      xAxis: {
        type: 'category',
        data: t1Data.map(item => item.recordDate || item.azone || '')
      },
      yAxis: { type: 'value' },
      series: [
        {
          name: 'A区',
          data: t1Data.map(item => item.azone || 0),
          type: 'line',
          smooth: true,
          lineStyle: { color: '#E8B140' },
          areaStyle: { color: 'rgba(232, 177, 64, 0.2)' }
        },
        {
          name: 'B区',
          data: t1Data.map(item => item.bzone || 0),
          type: 'line',
          smooth: true,
          lineStyle: { color: '#5470c6' },
          areaStyle: { color: 'rgba(84, 112, 198, 0.2)' }
        }
      ]
    })
  }

  // T2旅检过检人数折线图
  if (t2TravelChart.value) {
    t2TravelChartInstance = echarts.init(t2TravelChart.value)
    const t2Data = t2PassengerData.value || []
    t2TravelChartInstance.setOption({
      tooltip: { trigger: 'axis' },
      legend: { data: ['国内旅检', '国际旅检'], top: 30 },
      xAxis: {
        type: 'category',
        data: t2Data.map(item => item.recordDate || '')
      },
      yAxis: { type: 'value' },
      series: [
        {
          name: '国内旅检',
          data: t2Data.map(item => item.domesticPassenger || 0),
          type: 'line',
          smooth: true,
          lineStyle: { color: '#91cc75' },
          areaStyle: { color: 'rgba(145, 204, 117, 0.2)' }
        },
        {
          name: '国际旅检',
          data: t2Data.map(item => item.intlPassenger || 0),
          type: 'line',
          smooth: true,
          lineStyle: { color: '#fac858' },
          areaStyle: { color: 'rgba(250, 200, 88, 0.2)' }
        }
      ]
    })
  }

  // 行检过检数折线图
  if (luggageChart.value) {
    luggageChartInstance = echarts.init(luggageChart.value)
    const luggageData = luggageCheckData.value || []
    luggageChartInstance.setOption({
      tooltip: { trigger: 'axis' },
      legend: { data: ['T1行检', 'T2行检'], top: 30 },
      xAxis: {
        type: 'category',
        data: luggageData.map(item => item.recordDate || '')
      },
      yAxis: { type: 'value' },
      series: [
        {
          name: 'T1行检',
          data: luggageData.map(item => item.t1LuggageCheck || 0),
          type: 'line',
          smooth: true,
          lineStyle: { color: '#ee6666' },
          areaStyle: { color: 'rgba(238, 102, 102, 0.2)' }
        },
        {
          name: 'T2行检',
          data: luggageData.map(item => item.t2LuggageCheck || 0),
          type: 'line',
          smooth: true,
          lineStyle: { color: '#73c0de' },
          areaStyle: { color: 'rgba(115, 192, 222, 0.2)' }
        }
      ]
    })
  }

  // 货物过检数折线图
  if (cargoChart.value) {
    cargoChartInstance = echarts.init(cargoChart.value)
    const cargoTrendData = cargoData.value || []
    cargoChartInstance.setOption({
      tooltip: { trigger: 'axis' },
      legend: { data: ['国内货站', '国际货站'], top: 30 },
      xAxis: {
        type: 'category',
        data: cargoTrendData.map(item => item.recordDate || '')
      },
      yAxis: { type: 'value' },
      series: [
        {
          name: '国内货站',
          data: cargoTrendData.map(item => item.domesticCargo || 0),
          type: 'line',
          smooth: true,
          lineStyle: { color: '#E8B140' },
          areaStyle: { color: 'rgba(232, 177, 64, 0.2)' }
        },
        {
          name: '国际货站',
          data: cargoTrendData.map(item => item.intlCargo || 0),
          type: 'line',
          smooth: true,
          lineStyle: { color: '#26B6BE' },
          areaStyle: { color: 'rgba(38, 182, 190, 0.2)' }
        }
      ]
    })
  }

  // 车辆过检数折线图
  if (vehicleChart.value) {
    vehicleChartInstance = echarts.init(vehicleChart.value)
    const vehicleData = vehicleCheckData.value || []
    vehicleChartInstance.setOption({
      tooltip: { trigger: 'axis' },
      legend: { data: ['南侧车检', '北侧车检'], top: 30 },
      xAxis: {
        type: 'category',
        data: vehicleData.map(item => item.recordDate || '')
      },
      yAxis: { type: 'value' },
      series: [
        {
          name: '南侧车检',
          data: vehicleData.map(item => item.southVehicleCheck || 0),
          type: 'line',
          smooth: true,
          lineStyle: { color: '#E8B140' },
          areaStyle: { color: 'rgba(232, 177, 64, 0.2)' }
        },
        {
          name: '北侧车检',
          data: vehicleData.map(item => item.northVehicleCheck || 0),
          type: 'line',
          smooth: true,
          lineStyle: { color: '#5470c6' },
          areaStyle: { color: 'rgba(84, 112, 198, 0.2)' }
        }
      ]
    })
  }

  // 查获数据环形图
  if (seizePieChart.value) {
    seizePieChartInstance = echarts.init(seizePieChart.value)
    const seizureData = seizureCategoryData.value || []
    seizePieChartInstance.setOption({
      tooltip: { trigger: 'item', formatter: '{b}: {c} ({d}%)' },
      legend: { orient: 'vertical', right: 10, top: 'center' },
      series: [{
        name: '查获数据',
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['40%', '50%'],
        data: seizureData.map(item => ({ name: item.name, value: item.total })),
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        label: {
          formatter: '{b}: {c} ({d}%)'
        }
      }]
    })
  }

  // 大队查获数对比柱状图
  if (teamSeizeBarChart.value) {
    teamSeizeBarChartInstance = echarts.init(teamSeizeBarChart.value)
    const brigadeData = brigadeSeizureData.value || []
    const shifts = [...new Set(brigadeData.map(item => item.shift))]
    const brigades = [...new Set(brigadeData.map(item => item.brigade))]
    const series = brigades.map(brigade => ({
      name: brigade,
      data: shifts.map(shift => {
        const item = brigadeData.find(d => d.shift === shift && d.brigade === brigade)
        return item ? item.grandTotal : 0
      }),
      type: 'bar',
      label: {
        show: true,
        position: 'top',
        formatter: '{c}'
      }
    }))
    teamSeizeBarChartInstance.setOption({
      tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
      legend: { data: brigades, top: 30 },
      xAxis: {
        type: 'category',
        data: shifts
      },
      yAxis: { type: 'value' },
      series: series
    })
  }

  // T1区域各大队查获数对比柱状图
  if (t1TeamBarChart.value) {
    t1TeamBarChartInstance = echarts.init(t1TeamBarChart.value)
    const brigadeData = brigadeSeizureData.value || []
    const shifts = [...new Set(brigadeData.map(item => item.shift))]
    const brigades = [...new Set(brigadeData.map(item => item.brigade))]
    const series = brigades.map(brigade => ({
      name: brigade,
      data: shifts.map(shift => {
        const item = brigadeData.find(d => d.shift === shift && d.brigade === brigade)
        return item ? item.t1Total : 0
      }),
      type: 'bar',
      label: {
        show: true,
        position: 'top',
        formatter: '{c}'
      }
    }))
    t1TeamBarChartInstance.setOption({
      tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
      legend: { data: brigades, top: 30 },
      xAxis: {
        type: 'category',
        data: shifts
      },
      yAxis: { type: 'value' },
      series: series
    })
  }

  // T2区域各大队查获数对比柱状图
  if (t2TeamBarChart.value) {
    t2TeamBarChartInstance = echarts.init(t2TeamBarChart.value)
    const brigadeData = brigadeSeizureData.value || []
    const shifts = [...new Set(brigadeData.map(item => item.shift))]
    const brigades = [...new Set(brigadeData.map(item => item.brigade))]
    const series = brigades.map(brigade => ({
      name: brigade,
      data: shifts.map(shift => {
        const item = brigadeData.find(d => d.shift === shift && d.brigade === brigade)
        return item ? item.t2Total : 0
      }),
      type: 'bar',
      label: {
        show: true,
        position: 'top',
        formatter: '{c}'
      }
    }))
    t2TeamBarChartInstance.setOption({
      tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
      legend: { data: brigades, top: 30 },
      xAxis: {
        type: 'category',
        data: shifts
      },
      yAxis: { type: 'value' },
      series: series
    })
  }

  // 不合格充电宝劝阻数组环形图
  if (powerBankPieChart.value) {
    powerBankPieChartInstance = echarts.init(powerBankPieChart.value)
    const pbData = powerBankData.value || {}
    const powerBankChartData = [
      { name: '邮寄', value: pbData.mailTotal || 0 },
      { name: '暂存', value: pbData.tempStoreTotal || 0 },
      { name: '自弃', value: pbData.abandonTotal || 0 },
      { name: '召回', value: pbData.recallTotal || 0 },
      { name: '无3C标识', value: pbData.no3cTotal || 0 },
      { name: '标识不清', value: pbData.unclearMarkTotal || 0 },
      { name: '超规数量', value: pbData.excessQtyTotal || 0 },
      { name: '其他', value: pbData.bothTotal || 0 }
    ].filter(item => item.value > 0)
    
    powerBankPieChartInstance.setOption({
      tooltip: { trigger: 'item', formatter: '{b}: {c} ({d}%)' },
      legend: { orient: 'vertical', right: 10, top: 'center' },
      series: [{
        name: '不合格充电宝',
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['40%', '50%'],
        data: powerBankChartData,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        label: {
          formatter: '{b}: {c} ({d}%)'
        }
      }]
    })
  }

  // 待检区收缴禁限带物品数据表环形图
  if (waitingAreaPieChart.value) {
    waitingAreaPieChartInstance = echarts.init(waitingAreaPieChart.value)
    const pendingData = pendingConfiscateData.value || {}
    const pendingChartData = [
      { name: '火种', value: pendingData.fireSourceTotal || 0 },
      { name: '液态物品', value: pendingData.liquidTotal || 0 },
      { name: '其他', value: pendingData.otherTotal || 0 }
    ].filter(item => item.value > 0)
    
    waitingAreaPieChartInstance.setOption({
      tooltip: { trigger: 'item', formatter: '{b}: {c} ({d}%)' },
      legend: { orient: 'vertical', right: 10, top: 'center' },
      series: [{
        name: '禁限带物品',
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['40%', '50%'],
        data: pendingChartData,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        label: {
          formatter: '{b}: {c} ({d}%)'
        }
      }]
    })
  }
}

// 窗口大小变化时重新调整图表大小
function handleResize() {
  const charts = [
    t1TravelChartInstance, t2TravelChartInstance, luggageChartInstance,
    cargoChartInstance, vehicleChartInstance, seizePieChartInstance,
    teamSeizeBarChartInstance, t1TeamBarChartInstance, t2TeamBarChartInstance,
    powerBankPieChartInstance, waitingAreaPieChartInstance
  ]

  charts.forEach(chart => {
    if (chart) {
      chart.resize()
    }
  })
}

// 组件挂载时初始化图表
onMounted(() => {
  loadData()
  window.addEventListener('resize', handleResize)
})

// 组件卸载时销毁图表
onUnmounted(() => {
  const charts = [
    t1TravelChartInstance, t2TravelChartInstance, luggageChartInstance,
    cargoChartInstance, vehicleChartInstance, seizePieChartInstance,
    teamSeizeBarChartInstance, t1TeamBarChartInstance, t2TeamBarChartInstance,
    powerBankPieChartInstance, waitingAreaPieChartInstance
  ]

  charts.forEach(chart => {
    if (chart) {
      chart.dispose()
    }
  })

  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
.run-screen-container {
  padding: 20px;
  background: #f0f2f5;
  min-height: 100vh;
}

.page-title {
  text-align: center;
  margin-bottom: 30px;
}

.page-title h1 {
  font-size: 28px;
  color: #333;
  font-weight: bold;
  margin: 0;
}

.module-title-wrapper {
  text-align: center;
  width: 100%;
  background: #fff;
  border-radius: 8px;
  padding: 15px 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.module-title {
  font-size: 20px;
  font-weight: bold;
  color: #333;
  margin: 0;
}

.module-section {
  width: 100%;
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.row-margin {
  margin-bottom: 20px;
}

.data-card {
  background: #fff;
  border-radius: 8px;
  padding: 15px;
  color: #333;
  height: 100%;


  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  border: 1px solid #e6e8eb;
}

.card-title {
  font-size: 16px;
  color: #333;
  font-weight: bold;
  text-align: left;
}

.card-value-wrapper {
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.card-value {
  font-size: 50px;
  font-weight: bold;

}

.card-unit {
  font-size: 16px;

}

.chart-card {
  background: #fff;
  border-radius: 8px;
  padding: 15px;
  border: 1px solid #e6e8eb;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  height: 300px;
}

.chart-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 15px;
  text-align: left;
}

.chart-container {
  width: 100%;
  height: calc(100% - 30px);
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .data-card {
    height: 100px;
  }

  .card-value {
    font-size: 30px;
  }

  .chart-card {
    height: 250px;
  }
}

@media (max-width: 768px) {
  .run-screen-container {
    padding: 10px;
  }

  .module-section {
    padding: 15px;
  }

  .data-card {
    height: 80px;
    padding: 15px;
  }

  .card-title {
    font-size: 14px;
  }

  .card-value {
    font-size: 20px;
  }

  .chart-card {
    height: 200px;
  }
}
</style>