<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="afterSalesType"
            @change="handleTypeChange"
            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="refund">退款</option>
            <option value="return">退货</option>
            <option value="exchange">换货</option>
            <option value="repair">维修</option>
          </select>
          <select 
            v-model="afterSalesStatus"
            @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="processing">处理中</option>
            <option value="completed">已完成</option>
            <option value="rejected">已拒绝</option>
            <option value="cancelled">已取消</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">
              <ClipboardListIcon 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">23</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-yellow-100 dark:bg-yellow-900">
              <ClockIcon class="h-6 w-6 text-yellow-600 dark:text-yellow-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">15</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">156</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">
              <XCircleIcon 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">8</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 class="h-64">
            <!-- 这里可以集成图表库，如 ECharts 或 Chart.js -->
            <div id="afterSalesTrendChart" class="flex items-center justify-center h-full text-gray-500 dark:text-gray-400"></div>
          </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 class="h-64">
            <!-- 这里可以集成图表库，如 ECharts 或 Chart.js -->
            <div id="afterSalesDistributionChart" class="flex items-center justify-center h-full text-gray-500 dark:text-gray-400"></div>
          </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="afterSales in paginatedAfterSales" :key="afterSales.id" class="hover:bg-gray-50 dark:hover:bg-gray-700">
                <td class="px-6 py-4">
                  <div class="flex items-center">
                    <div class="ml-4">
                      <div class="text-sm font-medium text-gray-900 dark:text-white">售后单号: {{ afterSales.id }}</div>
                      <div class="text-sm text-gray-500 dark:text-gray-400">{{ afterSales.createTime }}</div>
                    </div>
                  </div>
                </td>
                <td class="px-6 py-4">
                  <div class="flex items-center">
                    <div class="ml-4">
                      <div class="text-sm font-medium text-gray-900 dark:text-white">订单号: {{ afterSales.orderId }}</div>
                      <div class="text-sm text-gray-500 dark:text-gray-400">{{ afterSales.productName }}</div>
                    </div>
                  </div>
                </td>
                <td class="px-6 py-4">
                  <div class="text-sm font-medium text-gray-900 dark:text-white">{{ afterSales.type === 'refund' ? '退款' : 
                                                                                  afterSales.type === 'return' ? '退货' : 
                                                                                  afterSales.type === 'exchange' ? '换货' : '维修' }}</div>
                  <div class="text-sm text-gray-500 dark:text-gray-400">{{ afterSales.reason }}</div>
                </td>
                <td class="px-6 py-4">
                  <span :class="['status-tag', `status-${afterSales.status}`]">
                    {{ afterSales.status === 'pending' ? '待处理' : 
                       afterSales.status === 'processing' ? '处理中' : 
                       afterSales.status === 'completed' ? '已完成' : 
                       afterSales.status === 'rejected' ? '已拒绝' : '已取消' }}
                  </span>
                </td>
                <td class="px-6 py-4 text-sm font-medium">
                  <button 
                    @click="handleViewAfterSales(afterSales)"
                    class="action-button view-button"
                  >
                    <EyeIcon class="h-4 w-4 inline-block mr-1" />
                    查看
                  </button>
                  <button 
                    @click="handleProcessAfterSales(afterSales)"
                    class="action-button process-button"
                  >
                    <CheckIcon 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, filteredAfterSales.length) }}</span> 条，共 
              <span class="font-medium">{{ filteredAfterSales.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 { 
  SearchIcon, 
  SettingsIcon, 
  ChevronLeftIcon, 
  ChevronRightIcon,
  ClipboardListIcon,
  ClockIcon,
  CheckCircleIcon,
  XCircleIcon,
  DownloadIcon,
  EyeIcon,
  CheckIcon
} from 'lucide-vue-next'
import * as echarts from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart, PieChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  DataZoomComponent,
  VisualMapComponent
} from 'echarts/components'

// 注册 ECharts 组件
echarts.use([
  CanvasRenderer,
  LineChart,
  PieChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  DataZoomComponent,
  VisualMapComponent
])

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

// 模拟数据
const mockAfterSales = ref([
  {
    id: 'AS1001',
    orderId: 'O1001',
    productName: 'iPhone 13 Pro',
    type: 'refund',
    reason: '商品质量问题',
    status: 'pending',
    createTime: '2024-03-20 10:30:00',
    processTime: '',
    completeTime: '',
    amount: 8999,
    description: '手机屏幕有划痕',
    images: [],
    processNotes: ''
  },
  {
    id: 'AS1002',
    orderId: 'O1002',
    productName: 'MacBook Pro',
    type: 'return',
    reason: '商品与描述不符',
    status: 'processing',
    createTime: '2024-03-19 14:20:00',
    processTime: '2024-03-19 15:30:00',
    completeTime: '',
    amount: 12999,
    description: '配置与页面描述不一致',
    images: ['image1.jpg', 'image2.jpg'],
    processNotes: '已联系客户确认退货地址'
  },
  {
    id: 'AS1003',
    orderId: 'O1003',
    productName: 'AirPods Pro',
    type: 'exchange',
    reason: '商品损坏',
    status: 'completed',
    createTime: '2024-03-18 09:15:00',
    processTime: '2024-03-18 10:30:00',
    completeTime: '2024-03-19 16:00:00',
    amount: 1999,
    description: '耳机右耳无法充电',
    images: ['image3.jpg'],
    processNotes: '已换新，客户已确认收货'
  },
  {
    id: 'AS1004',
    orderId: 'O1004',
    productName: 'Apple Watch',
    type: 'repair',
    reason: '商品故障',
    status: 'rejected',
    createTime: '2024-03-17 16:45:00',
    processTime: '2024-03-17 17:30:00',
    completeTime: '2024-03-17 18:00:00',
    amount: 3299,
    description: '手表无法开机',
    images: ['image4.jpg'],
    processNotes: '经检测为人为损坏，不在保修范围内'
  },
  {
    id: 'AS1005',
    orderId: 'O1005',
    productName: 'iPad Pro',
    type: 'refund',
    reason: '商品未收到',
    status: 'cancelled',
    createTime: '2024-03-16 11:25:00',
    processTime: '',
    completeTime: '2024-03-16 12:30:00',
    amount: 6799,
    description: '物流显示已签收，但未收到商品',
    images: [],
    processNotes: '客户取消申请，商品已找到'
  }
])

// 售后统计数据
const afterSalesStats = ref({
  pending: 23,
  processing: 15,
  completed: 156,
  rejected: 8
})

// 售后趋势数据
const afterSalesTrends = ref([
  { date: '2024-03-01', refunds: 10, returns: 5, exchanges: 3, repairs: 2 },
  { date: '2024-03-02', refunds: 12, returns: 6, exchanges: 4, repairs: 1 },
  { date: '2024-03-03', refunds: 15, returns: 7, exchanges: 5, repairs: 3 },
  { date: '2024-03-04', refunds: 18, returns: 8, exchanges: 6, repairs: 2 },
  { date: '2024-03-05', refunds: 20, returns: 9, exchanges: 7, repairs: 4 },
  { date: '2024-03-06', refunds: 22, returns: 10, exchanges: 8, repairs: 3 },
  { date: '2024-03-07', refunds: 25, returns: 12, exchanges: 9, repairs: 4 }
])

// 售后类型分布
const afterSalesDistribution = ref([
  { type: '退款', value: 120 },
  { type: '退货', value: 80 },
  { type: '换货', value: 50 },
  { type: '维修', value: 30 }
])

// 计算属性
const filteredAfterSales = computed(() => {
  let result = [...mockAfterSales.value]
  
  // 搜索过滤
  if (searchText.value) {
    result = result.filter(afterSales => 
      afterSales.id.includes(searchText.value) ||
      afterSales.orderId.includes(searchText.value)
    )
  }
  
  // 类型过滤
  if (afterSalesType.value) {
    result = result.filter(afterSales => afterSales.type === afterSalesType.value)
  }
  
  // 状态过滤
  if (afterSalesStatus.value) {
    result = result.filter(afterSales => afterSales.status === afterSalesStatus.value)
  }
  
  // 时间范围过滤
  if (timeRange.value) {
    const now = new Date()
    result = result.filter(afterSales => {
      // 这里可以根据实际需求添加时间过滤逻辑
      return true
    })
  }
  
  return result
})

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

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

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

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

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

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

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

const handleViewAfterSales = (afterSales) => {
  console.log('查看售后:', afterSales)
}

const handleProcessAfterSales = (afterSales) => {
  console.log('处理售后:', afterSales)
}

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

// 图表实例
const trendChart = ref(null)
const distributionChart = ref(null)

// 初始化趋势图表
const initTrendChart = () => {
  const chartDom = document.getElementById('afterSalesTrendChart')
  if (!chartDom) return
  
  trendChart.value = echarts.init(chartDom)
  const option = {
    title: {
      text: '售后趋势分析',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['退款', '退货', '换货', '维修'],
      bottom: 0
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: afterSalesTrends.value.map(item => item.date)
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '退款',
        type: 'line',
        data: afterSalesTrends.value.map(item => item.refunds)
      },
      {
        name: '退货',
        type: 'line',
        data: afterSalesTrends.value.map(item => item.returns)
      },
      {
        name: '换货',
        type: 'line',
        data: afterSalesTrends.value.map(item => item.exchanges)
      },
      {
        name: '维修',
        type: 'line',
        data: afterSalesTrends.value.map(item => item.repairs)
      }
    ]
  }
  trendChart.value.setOption(option)
}

// 初始化分布图表
const initDistributionChart = () => {
  const chartDom = document.getElementById('afterSalesDistributionChart')
  if (!chartDom) return
  
  distributionChart.value = echarts.init(chartDom)
  const option = {
    title: {
      text: '售后类型分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '售后类型',
        type: 'pie',
        radius: '50%',
        data: afterSalesDistribution.value.map(item => ({
          name: item.type,
          value: item.value
        })),
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  distributionChart.value.setOption(option)
}

// 监听窗口大小变化
const handleResize = () => {
  trendChart.value?.resize()
  distributionChart.value?.resize()
}

// 生命周期钩子
onMounted(() => {
  // 初始化数据
  console.log('售后管理页面已加载')
  
  // 初始化图表
  initTrendChart()
  initDistributionChart()
  
  // 添加窗口大小变化监听
  window.addEventListener('resize', handleResize)
})

// 组件卸载时清理
onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  trendChart.value?.dispose()
  distributionChart.value?.dispose()
})
</script>

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

/* 状态标签样式 */
.status-tag {
  @apply px-2 inline-flex text-xs leading-5 font-semibold rounded-full;
}

.status-pending {
  @apply bg-yellow-100 dark:bg-yellow-900 text-yellow-800 dark:text-yellow-400;
}

.status-processing {
  @apply bg-blue-100 dark:bg-blue-900 text-blue-800 dark:text-blue-400;
}

.status-completed {
  @apply bg-green-100 dark:bg-green-900 text-green-800 dark:text-green-400;
}

.status-rejected {
  @apply bg-red-100 dark:bg-red-900 text-red-800 dark:text-red-400;
}

.status-cancelled {
  @apply bg-gray-100 dark:bg-gray-900 text-gray-800 dark:text-gray-400;
}

/* 操作按钮样式 */
.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;
}

.process-button {
  @apply text-green-600 dark:text-green-400 hover:text-green-900 dark:hover:text-green-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> 