<template>
  <div class="transport-container">
    <h1>运输跟踪</h1>
    <div v-if="loading" class="loading-indicator">数据加载中...</div>
    <div v-if="error" class="error-message">数据加载失败，请稍后重试。</div>
    <div v-if="!loading && !error" class="transport-content">
      <!-- 运输路线地图 -->
      <div class="map-section">
        <h3>运输路线</h3>
        <div class="map-container">
          <div ref="transportMap" class="map-placeholder" style="width: 100%; height: 400px;"></div>
        </div>
      </div>
      
      <!-- 运输车辆列表 -->
      <div class="vehicles-section">
        <h3>运输车辆</h3>
        <div class="vehicles-list">
          <a-table :dataSource="vehiclesData" :columns="vehicleColumns" :pagination="false" />
        </div>
      </div>
      
      <!-- 运输异常告警 -->
      <div class="alerts-section">
        <h3>运输异常告警</h3>
        <div class="alerts-list">
          <div 
            v-for="(alert, index) in transportAlerts" 
            :key="index" 
            class="alert-item"
            :class="alert.level"
          >
            <div class="alert-icon">
              <span v-if="alert.level === 'high'">⚠️</span>
              <span v-else-if="alert.level === 'medium'">⚠️</span>
              <span v-else>ℹ️</span>
            </div>
            <div class="alert-content">
              <div class="alert-title">{{ alert.title }}</div>
              <div class="alert-desc">{{ alert.desc }}</div>
              <div class="alert-time">{{ alert.time }}</div>
            </div>
            <div class="alert-status">{{ alert.status }}</div>
          </div>
        </div>
      </div>
      
      <!-- 运输统计 -->
      <div class="stats-section">
        <h3>运输统计</h3>
        <div class="stats-grid">
          <div class="stat-card" v-for="(stat, index) in transportStats" :key="index">
            <div class="stat-title">{{ stat.title }}</div>
            <div class="stat-value">{{ stat.value }}</div>
            <div class="stat-desc">{{ stat.desc }}</div>
          </div>
        </div>
      </div>
      
      <!-- 运输效率分析 -->
      <div class="efficiency-section">
        <h3>运输效率分析</h3>
        <div class="chart-container">
          <div ref="efficiencyChart" class="chart-placeholder" style="width: 100%; height: 300px;"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, onBeforeUnmount } from 'vue';
import axios from 'axios';
import * as echarts from 'echarts';

export default {
  name: 'Transport',
  setup() {
    const vehiclesData = ref([]);
    const transportStats = ref([]);
    const transportAlerts = ref([]);
    const loading = ref(true);
    const error = ref(false);
    const transportMap = ref(null);
    const efficiencyChart = ref(null);
    
    let mapInstance = null;
    let chartInstance = null;
    
    // 车辆表格列定义
    const vehicleColumns = ref([
      { title: '车牌号', dataIndex: 'plateNumber', key: 'plateNumber' },
      { title: '司机', dataIndex: 'driver', key: 'driver' },
      { title: '出发地', dataIndex: 'origin', key: 'origin' },
      { title: '目的地', dataIndex: 'destination', key: 'destination' },
      { title: '状态', dataIndex: 'status', key: 'status' },
      { title: '预计到达', dataIndex: 'eta', key: 'eta' },
    ]);
    
    // 运输统计数据
    transportStats.value = [
      { title: '今日运输', value: '24车次', desc: '较昨日 +5%' },
      { title: '在途运输', value: '8车次', desc: '正常运输中' },
      { title: '平均时效', value: '4.2小时', desc: '较上周 -0.3小时' },
      { title: '异常运输', value: '1车次', desc: '需关注处理' },
    ];
    
    // 运输异常告警数据
    transportAlerts.value = [
      { 
        level: 'high', 
        title: '运输延误', 
        desc: '蒙H54321从西乌旗牧场C到上海加工中心已延误2小时', 
        time: '2023-08-20 14:30',
        status: '处理中'
      },
      { 
        level: 'medium', 
        title: '路线偏离', 
        desc: '蒙H12345从锡市牧场A到北京屠宰场偏离预定路线5公里', 
        time: '2023-08-20 13:45',
        status: '已确认'
      },
      { 
        level: 'low', 
        title: '温度异常', 
        desc: '蒙H67890冷藏车厢温度超过标准值0.5℃', 
        time: '2023-08-20 12:15',
        status: '已处理'
      }
    ];

    const fetchData = async () => {
      try {
        loading.value = true;
        error.value = false;
        // 模拟获取运输数据
        vehiclesData.value = [
          { 
            key: '1', 
            plateNumber: '蒙H12345', 
            driver: '张三', 
            origin: '锡市牧场A', 
            destination: '北京屠宰场', 
            status: '运输中', 
            eta: '2023-08-20 15:30' 
          },
          { 
            key: '2', 
            plateNumber: '蒙H67890', 
            driver: '李四', 
            origin: '东乌旗牧场B', 
            destination: '呼和浩特产中心', 
            status: '已完成', 
            eta: '2023-08-20 14:15' 
          },
          { 
            key: '3', 
            plateNumber: '蒙H54321', 
            driver: '王五', 
            origin: '西乌旗牧场C', 
            destination: '上海加工中心', 
            status: '延误', 
            eta: '2023-08-20 16:45' 
          },
        ];
      } catch (err) {
        error.value = true;
        console.error('获取运输数据失败:', err);
      } finally {
        loading.value = false;
      }
    };

    // 初始化地图
    const initMap = () => {
      if (transportMap.value) {
        mapInstance = echarts.init(transportMap.value);
        mapInstance.setOption({
          title: {
            text: '运输路线图',
            left: 'center'
          },
          tooltip: {
            trigger: 'item'
          },
          geo: {
            map: 'china',
            roam: false,
            zoom: 1.2,
            center: [116.0, 44.0], // 锡林郭勒盟位置
            itemStyle: {
              areaColor: '#e7e8ea'
            }
          },
          series: [
            {
              type: 'lines',
              coordinateSystem: 'geo',
              lineStyle: {
                color: '#4CAF50',
                width: 2,
                opacity: 0.8,
                curveness: 0.2
              },
              data: [
                {
                  coords: [[116.08, 43.95], [116.40, 39.90]] // 锡林浩特到北京
                },
                {
                  coords: [[116.08, 43.95], [111.65, 40.82]] // 锡林浩特到呼和浩特
                },
                {
                  coords: [[116.08, 43.95], [121.47, 31.23]] // 锡林浩特到上海
                }
              ]
            },
            {
              type: 'effectScatter',
              coordinateSystem: 'geo',
              symbolSize: 10,
              data: [
                { name: '锡林浩特', value: [116.08, 43.95] },
                { name: '北京', value: [116.40, 39.90] },
                { name: '呼和浩特', value: [111.65, 40.82] },
                { name: '上海', value: [121.47, 31.23] }
              ]
            }
          ]
        });
      }
    };
    
    // 初始化效率分析图表
    const initEfficiencyChart = () => {
      if (efficiencyChart.value) {
        chartInstance = echarts.init(efficiencyChart.value);
        chartInstance.setOption({
          tooltip: {
            trigger: 'axis'
          },
          legend: {
            data: ['实际时效', '计划时效']
          },
          xAxis: {
            type: 'category',
            data: ['1月', '2月', '3月', '4月', '5月', '6月']
          },
          yAxis: {
            type: 'value',
            name: '小时'
          },
          series: [
            {
              name: '实际时效',
              type: 'bar',
              data: [4.2, 3.8, 4.0, 4.5, 3.9, 4.1],
              itemStyle: { color: '#4CAF50' }
            },
            {
              name: '计划时效',
              type: 'bar',
              data: [4.0, 4.0, 4.0, 4.0, 4.0, 4.0],
              itemStyle: { color: '#2196F3' }
            }
          ]
        });
      }
    };

    // 窗口大小改变时重绘图表
    const resizeCharts = () => {
      if (mapInstance) {
        mapInstance.resize();
      }
      if (chartInstance) {
        chartInstance.resize();
      }
    };

    onMounted(() => {
      fetchData();
      initMap();
      initEfficiencyChart();
      window.addEventListener('resize', resizeCharts);
    });

    onBeforeUnmount(() => {
      window.removeEventListener('resize', resizeCharts);
      if (mapInstance) {
        mapInstance.dispose();
      }
      if (chartInstance) {
        chartInstance.dispose();
      }
    });

    return {
      vehiclesData,
      transportStats,
      transportAlerts,
      vehicleColumns,
      loading,
      error,
      transportMap,
      efficiencyChart
    };
  }
};
</script>

<style scoped>
.transport-container {
  padding: 20px;
  height: 100%;
  overflow-y: auto;
}

.transport-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.map-section,
.vehicles-section,
.alerts-section,
.stats-section,
.efficiency-section {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.map-section h3,
.vehicles-section h3,
.alerts-section h3,
.stats-section h3,
.efficiency-section h3 {
  margin-top: 0;
  color: #333;
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
}

.stat-card {
  background: #f8f9fa;
  border-radius: 6px;
  padding: 15px;
  text-align: center;
}

.stat-title {
  font-size: 14px;
  color: #666;
  margin-bottom: 5px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #4CAF50;
  margin-bottom: 5px;
}

.stat-desc {
  font-size: 12px;
  color: #999;
}

.alerts-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.alert-item {
  display: flex;
  align-items: center;
  padding: 15px;
  border-radius: 6px;
  border-left: 4px solid #ccc;
}

.alert-item.high {
  background-color: #ffebee;
  border-left-color: #f44336;
}

.alert-item.medium {
  background-color: #fff3e0;
  border-left-color: #ff9800;
}

.alert-item.low {
  background-color: #e3f2fd;
  border-left-color: #2196f3;
}

.alert-icon {
  font-size: 24px;
  margin-right: 15px;
}

.alert-content {
  flex: 1;
}

.alert-title {
  font-weight: bold;
  margin-bottom: 5px;
}

.alert-desc {
  font-size: 14px;
  color: #666;
  margin-bottom: 5px;
}

.alert-time {
  font-size: 12px;
  color: #999;
}

.alert-status {
  font-size: 12px;
  padding: 4px 8px;
  border-radius: 4px;
  background-color: #e0e0e0;
}

.loading-indicator,
.error-message {
  text-align: center;
  padding: 20px;
  font-size: 16px;
  color: #666;
}

.error-message {
  color: #ff4d4f;
}

@media (max-width: 768px) {
  .transport-container {
    padding: 10px;
  }
  
  .stats-grid {
    grid-template-columns: 1fr 1fr;
  }
  
  .alert-item {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .alert-icon {
    margin-bottom: 10px;
  }
}
</style>