<template>
  <module-container title="模块四 放行速率分析">
    <div class="module-four-content">
      <div class="chart-row">
        <div class="chart-item">
          <div class="chart-title">T1航站楼放行速率</div>
          <div ref="rateChart1" class="echarts"></div>
        </div>
        <div class="chart-item">
          <div class="chart-title">T2航站楼放行速率</div>
          <div ref="rateChart2" class="echarts"></div>
        </div>
      </div>
      <div class="chart-row">
        <div class="chart-item">
          <div class="chart-title">大队总平均速率对比（国内）</div>
          <div ref="rateChart3" class="echarts"></div>
        </div>
        <div class="chart-item">
          <div class="chart-title">大队总平均速率对比（国际+中转）</div>
          <div ref="rateChart4" class="echarts"></div>
        </div>
      </div>
    </div>
  </module-container>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, watch } from 'vue'
import * as echarts from 'echarts'
import ModuleContainer from './ModuleContainer.vue'
import { useEcharts } from '@/hooks/chart.js'
import { t1RateStats, t2RateStats, insideRateStats, outsideRateStats } from '@/api/blockingData/blockingDataScreen.js'
import { formatDateHy } from '@/utils/index.js'

// 接收筛选参数
const props = defineProps({
  filterParams: {
    type: Object,
    default: () => ({})
  }
})

const rateChart1 = ref(null)
const rateChart2 = ref(null)
const rateChart3 = ref(null)
const rateChart4 = ref(null)

const { setOption: setOption1 } = useEcharts(rateChart1)
const { setOption: setOption2 } = useEcharts(rateChart2)
const { setOption: setOption3 } = useEcharts(rateChart3)
const { setOption: setOption4 } = useEcharts(rateChart4)

// 处理filterParams，将dateRange拆分为startTime和endTime
const processFilterParams = (params) => {
  const { dateRange, ...rest } = params
  const processed = { ...rest }

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

  return processed
}

// 数据加载函数
const loadData = async () => {
  try {
    const queryParams = processFilterParams(props.filterParams)
    console.log('查询参数:', queryParams)

    // 并行请求所有速率数据
    const [t1RateRes, t2RateRes, insideRateRes, outsideRateRes] = await Promise.allSettled([
      t1RateStats(queryParams),
      t2RateStats(queryParams),
      insideRateStats(queryParams),
      outsideRateStats(queryParams)
    ])

    console.log('T1速率响应:', t1RateRes)
    console.log('T2速率响应:', t2RateRes)
    console.log('国内速率响应:', insideRateRes)
    console.log('国际中转速率响应:', outsideRateRes)

    // T1航站楼放行速率
    const t1RateData = t1RateRes?.value?.data || []
    console.log('T1速率数据:', t1RateData)
    console.log('T1速率数据长度:', t1RateData.length)
    console.log('T1速率数据类型:', typeof t1RateData)
    console.log('T1速率数据是否为数组:', Array.isArray(t1RateData))
    console.log('T1速率数据:', t1RateData)
    if (t1RateData.length > 0) {
      const dates = [...new Set(t1RateData.map(d => d.statDate))].sort()
      
      const seriesData = [
        {
          name: 'T1-A区速率（高峰期时段）',
          type: 'line',
          data: dates.map(date => {
            const item = t1RateData.find(d => d.statDate === date)
            return item ? item.t1AAreaRatePeak : 0
          }),
          itemStyle: { color: '#3b82f6' },
          lineStyle: { width: 3 },
          symbol: 'circle',
          symbolSize: 8
        },
        {
          name: 'T1-B区速率（高峰期时段）',
          type: 'line',
          data: dates.map(date => {
            const item = t1RateData.find(d => d.statDate === date)
            return item ? item.t1BAreaRatePeak : 0
          }),
          itemStyle: { color: '#22c55e' },
          lineStyle: { width: 3 },
          symbol: 'circle',
          symbolSize: 8
        }
      ]

      console.log('准备设置T1图表选项')
      console.log('日期数据:', dates)
      console.log('系列数据:', seriesData)

      setOption1({
        tooltip: {
          trigger: 'axis',
          formatter: function(params) {
            let result = params[0].name + '<br/>'
            params.forEach(param => {
              result += `${param.marker} ${param.seriesName}: ${param.value} 件/小时<br/>`
            })
            return result
          }
        },
        legend: {
          data: ['T1-A区速率（高峰期时段）', 'T1-B区速率（高峰期时段）']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: dates,
          axisLabel: {
            rotate: 45
          }
        },
        yAxis: {
          type: 'value',
          name: '速率',
          axisLabel: {
            formatter: '{value} 件/小时'
          }
        },
        series: seriesData
      })
      console.log('T1图表设置完成')
    }

    // T2航站楼放行速率
    const t2RateData = t2RateRes?.value?.data || []
    if (t2RateData.length > 0) {
      const dates = [...new Set(t2RateData.map(d => d.statDate))].sort()
      
      const seriesData = [
        {
          name: 'T2-国内速率（高峰期时段）',
          type: 'line',
          data: dates.map(date => {
            const item = t2RateData.find(d => d.statDate === date)
            return item ? item.t2DomesticRatePeak : 0
          }),
          itemStyle: { color: '#3b82f6' },
          lineStyle: { width: 3 },
          symbol: 'circle',
          symbolSize: 8
        },
        {
          name: 'T2-国际速率（高峰期时段）',
          type: 'line',
          data: dates.map(date => {
            const item = t2RateData.find(d => d.statDate === date)
            return item ? item.t2InternationalRatePeak : 0
          }),
          itemStyle: { color: '#22c55e' },
          lineStyle: { width: 3 },
          symbol: 'circle',
          symbolSize: 8
        }
      ]

      setOption2({
        tooltip: {
          trigger: 'axis',
          formatter: function(params) {
            let result = params[0].name + '<br/>'
            params.forEach(param => {
              result += `${param.marker} ${param.seriesName}: ${param.value} 件/小时<br/>`
            })
            return result
          }
        },
        legend: {
          data: ['T2-国内速率（高峰期时段）', 'T2-国际速率（高峰期时段）']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: dates,
          axisLabel: {
            rotate: 45
          }
        },
        yAxis: {
          type: 'value',
          name: '速率',
          axisLabel: {
            formatter: '{value} 件/小时'
          }
        },
        series: seriesData
      })
    }

    // 大队总平均速率对比（国内）
    const insideRateData = insideRateRes?.value?.data || []
    if (insideRateData.length > 0) {
      const dates = [...new Set(insideRateData.map(d => d.statDate))].sort()
      const brigadeNames = [...new Set(insideRateData.map(d => d.dutyBrigadeName))]
      
      const seriesData = brigadeNames.map((brigade, index) => ({
        name: brigade,
        type: 'line',
        data: dates.map(date => {
          const item = insideRateData.find(d => d.statDate === date && d.dutyBrigadeName === brigade)
          return item ? item.avgRatePeak : 0
        }),
        itemStyle: {
          color: ['#3b82f6', '#22c55e', '#f97316', '#ec4899', '#8b5cf6'][index % 5]
        },
        lineStyle: { width: 3 },
        symbol: 'circle',
        symbolSize: 8
      }))

      setOption3({
        tooltip: {
          trigger: 'axis',
          formatter: function(params) {
            let result = params[0].name + '<br/>'
            params.forEach(param => {
              result += `${param.marker} ${param.seriesName}: ${param.value} 件/小时<br/>`
            })
            return result
          }
        },
        legend: {
          data: brigadeNames
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: dates,
          axisLabel: {
            rotate: 45
          }
        },
        yAxis: {
          type: 'value',
          name: '速率',
          axisLabel: {
            formatter: '{value} 件/小时'
          }
        },
        series: seriesData
      })
    }

    // 大队总平均速率对比（国际+中转）
    const outsideRateData = outsideRateRes?.value?.data || []
    if (outsideRateData.length > 0) {
      const dates = [...new Set(outsideRateData.map(d => d.statDate))].sort()
      const brigadeNames = [...new Set(outsideRateData.map(d => d.dutyBrigadeName))]
      
      const seriesData = brigadeNames.map((brigade, index) => ({
        name: brigade,
        type: 'line',
        data: dates.map(date => {
          const item = outsideRateData.find(d => d.statDate === date && d.dutyBrigadeName === brigade)
          return item ? item.avgRatePeak : 0
        }),
        itemStyle: {
          color: ['#3b82f6', '#22c55e', '#f97316', '#ec4899', '#8b5cf6'][index % 5]
        },
        lineStyle: { width: 3 },
        symbol: 'circle',
        symbolSize: 8
      }))

      setOption4({
        tooltip: {
          trigger: 'axis',
          formatter: function(params) {
            let result = params[0].name + '<br/>'
            params.forEach(param => {
              result += `${param.marker} ${param.seriesName}: ${param.value} 件/小时<br/>`
            })
            return result
          }
        },
        legend: {
          data: brigadeNames
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: dates,
          axisLabel: {
            rotate: 45
          }
        },
        yAxis: {
          type: 'value',
          name: '速率',
          axisLabel: {
            formatter: '{value} 件/小时'
          }
        },
        series: seriesData
      })
    }

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

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



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

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

.chart-row {
  flex: 1;
  display: flex;
  gap: 10px;
  min-height: 400px;
  height: 400px;
}

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

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

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