<template>
  <div class="min-h-screen bg-gray-50 dark:bg-gray-900">
    <!-- 顶部导航栏 -->
    <nav class="bg-white dark:bg-gray-800 shadow-sm">
      <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div class="flex justify-between h-16">
          <div class="flex items-center">
            <h1 class="text-xl font-bold text-gray-800 dark:text-white">物流管理</h1>
          </div>
          <div class="flex items-center space-x-4">
            <button 
              @click="handleExportReport"
              class="px-4 py-2 bg-green-600 text-white rounded-md hover:bg-green-700 flex items-center space-x-2"
            >
              <DownloadIcon class="h-5 w-5" />
              <span>导出报表</span>
            </button>
            <button class="p-2 rounded-full text-gray-600 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700">
              <SettingsIcon class="h-6 w-6" />
            </button>
          </div>
        </div>
      </div>
    </nav>

    <!-- 主要内容区域 -->
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      <!-- 搜索和筛选区域 -->
      <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6 mb-8">
        <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
          <div class="relative">
            <input
              v-model="searchText"
              @input="handleSearch"
              type="text"
              placeholder="搜索订单号/物流单号..."
              class="w-full pl-10 pr-4 py-2 border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
            />
            <SearchIcon class="absolute left-3 top-2.5 h-5 w-5 text-gray-400 dark:text-gray-500" />
          </div>
          <select 
            v-model="logisticsStatus"
            @change="handleStatusChange"
            class="border border-gray-300 dark:border-gray-600 rounded-md px-4 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
          >
            <option value="">所有状态</option>
            <option value="pending">待发货</option>
            <option value="shipped">已发货</option>
            <option value="in_transit">运输中</option>
            <option value="delivered">已送达</option>
            <option value="returned">已退回</option>
            <option value="exception">异常</option>
          </select>
          <select 
            v-model="logisticsCompany"
            @change="handleCompanyChange"
            class="border border-gray-300 dark:border-gray-600 rounded-md px-4 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
          >
            <option value="">所有物流公司</option>
            <option value="sf">顺丰速运</option>
            <option value="sto">申通快递</option>
            <option value="yto">圆通速递</option>
            <option value="zto">中通快递</option>
            <option value="ems">EMS</option>
          </select>
          <select 
            v-model="timeRange"
            @change="handleTimeRangeChange"
            class="border border-gray-300 dark:border-gray-600 rounded-md px-4 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
          >
            <option value="">所有时间</option>
            <option value="today">今天</option>
            <option value="week">本周</option>
            <option value="month">本月</option>
            <option value="quarter">本季度</option>
          </select>
        </div>
      </div>

      <!-- 物流统计卡片 -->
      <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
        <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
          <div class="flex items-center">
            <div class="p-3 rounded-full bg-blue-100 dark:bg-blue-900">
              <PackageIcon class="h-6 w-6 text-blue-600 dark:text-blue-400" />
            </div>
            <div class="ml-4">
              <p class="text-sm font-medium text-gray-600 dark:text-gray-400">待发货</p>
              <p class="text-2xl font-semibold text-gray-900 dark:text-white">56</p>
            </div>
          </div>
        </div>
        <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
          <div class="flex items-center">
            <div class="p-3 rounded-full bg-purple-100 dark:bg-purple-900">
              <TruckIcon class="h-6 w-6 text-purple-600 dark:text-purple-400" />
            </div>
            <div class="ml-4">
              <p class="text-sm font-medium text-gray-600 dark:text-gray-400">运输中</p>
              <p class="text-2xl font-semibold text-gray-900 dark:text-white">123</p>
            </div>
          </div>
        </div>
        <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
          <div class="flex items-center">
            <div class="p-3 rounded-full bg-green-100 dark:bg-green-900">
              <CheckCircleIcon class="h-6 w-6 text-green-600 dark:text-green-400" />
            </div>
            <div class="ml-4">
              <p class="text-sm font-medium text-gray-600 dark:text-gray-400">已送达</p>
              <p class="text-2xl font-semibold text-gray-900 dark:text-white">1,024</p>
            </div>
          </div>
        </div>
        <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
          <div class="flex items-center">
            <div class="p-3 rounded-full bg-red-100 dark:bg-red-900">
              <AlertTriangleIcon class="h-6 w-6 text-red-600 dark:text-red-400" />
            </div>
            <div class="ml-4">
              <p class="text-sm font-medium text-gray-600 dark:text-gray-400">异常订单</p>
              <p class="text-2xl font-semibold text-gray-900 dark:text-white">12</p>
            </div>
          </div>
        </div>
      </div>

      <!-- 物流分析图表 -->
      <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-8">
        <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
          <h3 class="text-lg font-medium text-gray-900 dark:text-white mb-4">物流时效分析</h3>
          <div ref="deliveryTimeChartRef" class="h-64"></div>
        </div>
        <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
          <h3 class="text-lg font-medium text-gray-900 dark:text-white mb-4">物流公司分布</h3>
          <div ref="companyDistributionChartRef" class="h-64"></div>
        </div>
      </div>

      <!-- 物流订单列表 -->
      <div class="bg-white dark:bg-gray-800 rounded-lg shadow overflow-hidden">
        <div class="overflow-x-auto">
          <table class="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
            <thead class="bg-gray-50 dark:bg-gray-700">
              <tr>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">订单信息</th>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">物流信息</th>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">收货信息</th>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">状态</th>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">操作</th>
              </tr>
            </thead>
            <tbody class="bg-white dark:bg-gray-800 divide-y divide-gray-200 dark:divide-gray-700">
              <tr v-for="order in paginatedOrders" :key="order.id" class="hover:bg-gray-50 dark:hover:bg-gray-700">
                <td class="px-6 py-4">
                  <div class="text-sm font-medium text-gray-900 dark:text-white">{{ order.orderNo }}</div>
                  <div class="text-sm text-gray-500 dark:text-gray-400">{{ order.createTime }}</div>
                </td>
                <td class="px-6 py-4">
                  <div class="text-sm font-medium text-gray-900 dark:text-white">{{ order.logisticsNo }}</div>
                  <div class="text-sm text-gray-500 dark:text-gray-400">{{ order.logisticsCompany }}</div>
                </td>
                <td class="px-6 py-4">
                  <div class="text-sm font-medium text-gray-900 dark:text-white">{{ order.receiverName }}</div>
                  <div class="text-sm text-gray-500 dark:text-gray-400">{{ order.receiverPhone }}</div>
                  <div class="text-sm text-gray-500 dark:text-gray-400">{{ order.receiverAddress }}</div>
                </td>
                <td class="px-6 py-4">
                  <span 
                    :class="[
                      'px-2 inline-flex text-xs leading-5 font-semibold rounded-full',
                      getStatusClass(order.status)
                    ]"
                  >
                    {{ getStatusText(order.status) }}
                  </span>
                </td>
                <td class="px-6 py-4 text-sm font-medium">
                  <button 
                    @click="handleViewOrder(order)"
                    class="action-button view-button"
                  >
                    <EyeIcon class="h-4 w-4 inline-block mr-1" />
                    查看
                  </button>
                  <button 
                    v-if="order.status === 'pending'"
                    @click="handleShipOrder(order)"
                    class="action-button ship-button"
                  >
                    <TruckIcon class="h-4 w-4 inline-block mr-1" />
                    发货
                  </button>
                  <button 
                    v-if="order.status === 'exception'"
                    @click="handleHandleException(order)"
                    class="action-button exception-button"
                  >
                    <AlertTriangleIcon class="h-4 w-4 inline-block mr-1" />
                    处理异常
                  </button>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>

      <!-- 分页 -->
      <div class="bg-white dark:bg-gray-800 px-4 py-3 flex items-center justify-between border-t border-gray-200 dark:border-gray-700 sm:px-6 mt-4">
        <div class="flex-1 flex justify-between sm:hidden">
          <button 
            @click="handlePageChange(currentPage - 1)"
            :disabled="currentPage === 1"
            class="pagination-button"
          >
            上一页
          </button>
          <button 
            @click="handlePageChange(currentPage + 1)"
            :disabled="currentPage === totalPages"
            class="pagination-button"
          >
            下一页
          </button>
        </div>
        <div class="hidden sm:flex-1 sm:flex sm:items-center sm:justify-between">
          <div>
            <p class="text-sm text-gray-700 dark:text-gray-300">
              显示 <span class="font-medium">{{ (currentPage - 1) * pageSize + 1 }}</span> 到 
              <span class="font-medium">{{ Math.min(currentPage * pageSize, filteredOrders.length) }}</span> 条，共 
              <span class="font-medium">{{ filteredOrders.length }}</span> 条
            </p>
          </div>
          <div>
            <nav class="relative z-0 inline-flex rounded-md shadow-sm -space-x-px" aria-label="Pagination">
              <button 
                @click="handlePageChange(currentPage - 1)"
                :disabled="currentPage === 1"
                class="relative inline-flex items-center px-2 py-2 rounded-l-md border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-sm font-medium text-gray-500 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-gray-600"
              >
                <ChevronLeftIcon class="h-5 w-5" />
              </button>
              <button 
                v-for="page in totalPages"
                :key="page"
                @click="handlePageChange(page)"
                :class="[
                  'relative inline-flex items-center px-4 py-2 border border-gray-300 dark:border-gray-600 text-sm font-medium',
                  currentPage === page ? 'bg-blue-600 text-white border-blue-600' : 'bg-white dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-600'
                ]"
              >
                {{ page }}
              </button>
              <button 
                @click="handlePageChange(currentPage + 1)"
                :disabled="currentPage === totalPages"
                class="relative inline-flex items-center px-2 py-2 rounded-r-md border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-sm font-medium text-gray-500 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-gray-600"
              >
                <ChevronRightIcon class="h-5 w-5" />
              </button>
            </nav>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import * as echarts from 'echarts'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart, PieChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
} from 'echarts/components'
import { 
  SearchIcon, 
  SettingsIcon, 
  ChevronLeftIcon, 
  ChevronRightIcon,
  PackageIcon,
  TruckIcon,
  CheckCircleIcon,
  AlertTriangleIcon,
  DownloadIcon,
  EyeIcon
} from 'lucide-vue-next'

// 注册必要的组件
echarts.use([
  CanvasRenderer,
  LineChart,
  PieChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
])

// 状态管理
const isLoading = ref(false)
const searchText = ref('')
const logisticsStatus = ref('')
const logisticsCompany = ref('')
const timeRange = ref('')
const currentPage = ref(1)
const pageSize = ref(10)

// 模拟数据
const mockOrders = ref([
  {
    id: 'L1001',
    orderNo: '202403200001',
    logisticsNo: 'SF1234567890',
    logisticsCompany: '顺丰速运',
    receiverName: '张三',
    receiverPhone: '13800138000',
    receiverAddress: '广东省深圳市南山区科技园路1号',
    status: 'pending',
    createTime: '2024-03-20 10:30:00'
  },
  {
    id: 'L1002',
    orderNo: '202403200002',
    logisticsNo: 'STO9876543210',
    logisticsCompany: '申通快递',
    receiverName: '李四',
    receiverPhone: '13900139000',
    receiverAddress: '北京市朝阳区建国路88号',
    status: 'shipped',
    createTime: '2024-03-19 14:20:00'
  },
  {
    id: 'L1003',
    orderNo: '202403200003',
    logisticsNo: 'YTO5678901234',
    logisticsCompany: '圆通速递',
    receiverName: '王五',
    receiverPhone: '13700137000',
    receiverAddress: '上海市浦东新区张江高科技园区',
    status: 'in_transit',
    createTime: '2024-03-18 09:15:00'
  },
  {
    id: 'L1004',
    orderNo: '202403200004',
    logisticsNo: 'ZTO3456789012',
    logisticsCompany: '中通快递',
    receiverName: '赵六',
    receiverPhone: '13600136000',
    receiverAddress: '浙江省杭州市西湖区文三路100号',
    status: 'delivered',
    createTime: '2024-03-17 16:45:00'
  },
  {
    id: 'L1005',
    orderNo: '202403200005',
    logisticsNo: 'EMS9012345678',
    logisticsCompany: 'EMS',
    receiverName: '钱七',
    receiverPhone: '13500135000',
    receiverAddress: '江苏省南京市鼓楼区中山路200号',
    status: 'exception',
    createTime: '2024-03-16 11:25:00'
  }
])

// 物流统计数据
const logisticsStats = ref({
  pendingShipment: 56,
  inTransit: 123,
  delivered: 1024,
  exception: 12
})

// 物流时效分析数据
const deliveryTimeAnalysis = ref([
  { date: '2024-03-01', avgTime: 2.5, maxTime: 4, minTime: 1 },
  { date: '2024-03-02', avgTime: 2.3, maxTime: 3.5, minTime: 1.2 },
  { date: '2024-03-03', avgTime: 2.7, maxTime: 4.2, minTime: 1.5 },
  { date: '2024-03-04', avgTime: 2.4, maxTime: 3.8, minTime: 1.3 },
  { date: '2024-03-05', avgTime: 2.6, maxTime: 4.1, minTime: 1.4 },
  { date: '2024-03-06', avgTime: 2.8, maxTime: 4.5, minTime: 1.6 },
  { date: '2024-03-07', avgTime: 2.5, maxTime: 4.3, minTime: 1.3 }
])

// 物流公司分布数据
const logisticsCompanyDistribution = ref([
  { company: '顺丰速运', count: 300, amount: 300000 },
  { company: '申通快递', count: 250, amount: 250000 },
  { company: '圆通速递', count: 200, amount: 200000 },
  { company: '中通快递', count: 180, amount: 180000 },
  { company: 'EMS', count: 70, amount: 70000 }
])

// 图表相关
const deliveryTimeChartRef = ref(null)
const companyDistributionChartRef = ref(null)
let deliveryTimeChart = null
let companyDistributionChart = null

// 初始化物流时效分析图表
const initDeliveryTimeChart = () => {
  if (!deliveryTimeChartRef.value) return
  
  if (deliveryTimeChart) {
    deliveryTimeChart.dispose()
  }
  
  deliveryTimeChart = echarts.init(deliveryTimeChartRef.value)
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      }
    },
    legend: {
      data: ['平均时效', '最长时效', '最短时效']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: deliveryTimeAnalysis.value.map(item => item.date),
      boundaryGap: false
    },
    yAxis: {
      type: 'value',
      name: '天数',
      min: 0,
      max: 5
    },
    series: [
      {
        name: '平均时效',
        type: 'line',
        data: deliveryTimeAnalysis.value.map(item => item.avgTime),
        smooth: true,
        lineStyle: {
          width: 3
        },
        itemStyle: {
          color: '#4F46E5'
        }
      },
      {
        name: '最长时效',
        type: 'line',
        data: deliveryTimeAnalysis.value.map(item => item.maxTime),
        smooth: true,
        lineStyle: {
          width: 2,
          type: 'dashed'
        },
        itemStyle: {
          color: '#EF4444'
        }
      },
      {
        name: '最短时效',
        type: 'line',
        data: deliveryTimeAnalysis.value.map(item => item.minTime),
        smooth: true,
        lineStyle: {
          width: 2,
          type: 'dashed'
        },
        itemStyle: {
          color: '#10B981'
        }
      }
    ]
  }
  deliveryTimeChart.setOption(option)
}

// 初始化物流公司分布图表
const initCompanyDistributionChart = () => {
  if (!companyDistributionChartRef.value) return
  
  if (companyDistributionChart) {
    companyDistributionChart.dispose()
  }
  
  companyDistributionChart = echarts.init(companyDistributionChartRef.value)
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c}单 ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '物流公司分布',
        type: 'pie',
        radius: '50%',
        data: logisticsCompanyDistribution.value.map(item => ({
          value: item.count,
          name: item.company
        })),
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        itemStyle: {
          borderRadius: 5,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: true,
          formatter: '{b}: {c}单'
        }
      }
    ]
  }
  companyDistributionChart.setOption(option)
}

// 监听窗口大小变化
const handleResize = () => {
  if (deliveryTimeChart) deliveryTimeChart.resize()
  if (companyDistributionChart) companyDistributionChart.resize()
}

// 计算属性
const filteredOrders = computed(() => {
  let result = [...mockOrders.value]
  
  // 搜索过滤
  if (searchText.value) {
    result = result.filter(order => 
      order.orderNo.includes(searchText.value) ||
      order.logisticsNo.includes(searchText.value)
    )
  }
  
  // 状态过滤
  if (logisticsStatus.value) {
    result = result.filter(order => order.status === logisticsStatus.value)
  }
  
  // 物流公司过滤
  if (logisticsCompany.value) {
    result = result.filter(order => order.logisticsCompany === logisticsCompany.value)
  }
  
  // 时间范围过滤
  if (timeRange.value) {
    const now = new Date()
    result = result.filter(order => {
      // 这里可以根据实际需求添加时间过滤逻辑
      return true
    })
  }
  
  return result
})

const paginatedOrders = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredOrders.value.slice(start, end)
})

const totalPages = computed(() => {
  return Math.ceil(filteredOrders.value.length / pageSize.value)
})

// 方法
const handleSearch = () => {
  currentPage.value = 1
}

const handleStatusChange = () => {
  currentPage.value = 1
}

const handleCompanyChange = () => {
  currentPage.value = 1
}

const handleTimeRangeChange = () => {
  currentPage.value = 1
}

const handlePageChange = (page) => {
  currentPage.value = page
}

const getStatusClass = (status) => {
  const classes = {
    pending: 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-300',
    shipped: 'bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-300',
    in_transit: 'bg-purple-100 text-purple-800 dark:bg-purple-900 dark:text-purple-300',
    delivered: 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-300',
    returned: 'bg-gray-100 text-gray-800 dark:bg-gray-900 dark:text-gray-300',
    exception: 'bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-300'
  }
  return classes[status] || 'bg-gray-100 text-gray-800 dark:bg-gray-900 dark:text-gray-300'
}

const getStatusText = (status) => {
  const texts = {
    pending: '待发货',
    shipped: '已发货',
    in_transit: '运输中',
    delivered: '已送达',
    returned: '已退回',
    exception: '异常'
  }
  return texts[status] || '未知状态'
}

const handleViewOrder = (order) => {
  console.log('查看订单:', order)
}

const handleShipOrder = (order) => {
  console.log('发货订单:', order)
}

const handleHandleException = (order) => {
  console.log('处理异常订单:', order)
}

const handleExportReport = () => {
  console.log('导出报表')
}

// 生命周期钩子
onMounted(() => {
  // 初始化图表
  initDeliveryTimeChart()
  initCompanyDistributionChart()
  
  // 添加窗口大小变化监听
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  // 移除窗口大小变化监听
  window.removeEventListener('resize', handleResize)
  
  // 销毁图表实例
  if (deliveryTimeChart) deliveryTimeChart.dispose()
  if (companyDistributionChart) companyDistributionChart.dispose()
})
</script>

<style scoped>
@media (max-width: 475px) {
  .grid {
    @apply grid-cols-1;
  }
  table {
    @apply block overflow-x-auto whitespace-nowrap;
  }
}

/* 操作按钮样式 */
.action-button {
  @apply text-sm font-medium mr-3;
}

.view-button {
  @apply text-blue-600 dark:text-blue-400 hover:text-blue-900 dark:hover:text-blue-300;
}

.ship-button {
  @apply text-green-600 dark:text-green-400 hover:text-green-900 dark:hover:text-green-300;
}

.exception-button {
  @apply text-red-600 dark:text-red-400 hover:text-red-900 dark:hover:text-red-300;
}

/* 分页样式 */
.pagination-button {
  @apply relative inline-flex items-center px-4 py-2 border border-gray-300 dark:border-gray-600 text-sm font-medium rounded-md text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-700 hover:bg-gray-50 dark:hover:bg-gray-600;
}

.pagination-button-active {
  @apply bg-blue-600 text-white border-blue-600;
}

/* 加载动画 */
.loading-spinner {
  @apply animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600;
}
</style> 