<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="serviceType"
            @change="handleServiceTypeChange"
            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="consult">咨询</option>
            <option value="complaint">投诉</option>
            <option value="refund">退款</option>
            <option value="technical">技术支持</option>
          </select>
          <select 
            v-model="status"
            @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="resolved">已解决</option>
            <option value="closed">已关闭</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">
              <HeadphonesIcon 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">{{ mockTickets.length }}</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">
              <ClockIcon 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">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-yellow-100 dark:bg-yellow-900">
              <AlertTriangleIcon 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">{{ mockTickets.filter(ticket => ticket.status === 'pending').length }}</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">{{ mockTickets.filter(ticket => ticket.type === 'complaint').length }}</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="trendChartRef" 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="typeChartRef" 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="userGrowthChartRef" 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="userLevelChartRef" 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>
                <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="ticket in paginatedTickets" :key="ticket.id" class="hover:bg-gray-50 dark:hover:bg-gray-700">
                <td class="px-6 py-4">
                  <div class="flex items-center">
                    <div class="flex-shrink-0 h-10 w-10">
                      <img class="h-10 w-10 rounded-full object-cover" :src="ticket.customer.avatar" :alt="ticket.customer.name">
                    </div>
                    <div class="ml-4">
                      <div class="text-sm font-medium text-gray-900 dark:text-white">{{ ticket.title }}</div>
                      <div class="text-sm text-gray-500 dark:text-gray-400">{{ ticket.customer.name }}</div>
                    </div>
                  </div>
                </td>
                <td class="px-6 py-4">
                  <span :class="['type-tag', `type-${ticket.type}`]">
                    {{ ticket.type === 'consult' ? '咨询' : 
                       ticket.type === 'complaint' ? '投诉' : 
                       ticket.type === 'refund' ? '退款' : '技术支持' }}
                  </span>
                </td>
                <td class="px-6 py-4">
                  <div class="flex items-center">
                    <div class="flex-shrink-0 h-8 w-8">
                      <img class="h-8 w-8 rounded-full object-cover" :src="ticket.agent.avatar" :alt="ticket.agent.name">
                    </div>
                    <div class="ml-3">
                      <div class="text-sm font-medium text-gray-900 dark:text-white">{{ ticket.agent.name }}</div>
                    </div>
                  </div>
                </td>
                <td class="px-6 py-4">
                  <div class="text-sm text-gray-900 dark:text-white">{{ ticket.createTime }}</div>
                </td>
                <td class="px-6 py-4">
                  <span :class="['status-tag', `status-${ticket.status}`]">
                    {{ ticket.status === 'pending' ? '待处理' : 
                       ticket.status === 'processing' ? '处理中' : 
                       ticket.status === 'resolved' ? '已解决' : '已关闭' }}
                  </span>
                </td>
                <td class="px-6 py-4 text-sm font-medium">
                  <button 
                    @click="handleViewTicket(ticket)"
                    class="action-button view-button"
                  >
                    <EyeIcon class="h-4 w-4 inline-block mr-1" />
                    查看
                  </button>
                  <button 
                    @click="handleAssignTicket(ticket)"
                    class="action-button edit-button"
                  >
                    <UserPlusIcon class="h-4 w-4 inline-block mr-1" />
                    分配
                  </button>
                  <button 
                    @click="handleCloseTicket(ticket)"
                    class="action-button delete-button"
                  >
                    <XIcon 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, filteredTickets.length) }}</span> 条，共 
              <span class="font-medium">{{ filteredTickets.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,
  UsersIcon,
  ActivityIcon,
  TrendingUpIcon,
  TargetIcon,
  DownloadIcon,
  EyeIcon,
  UserPlusIcon,
  XIcon,
  HeadphonesIcon,
  ClockIcon,
  AlertTriangleIcon,
  XCircleIcon
} from 'lucide-vue-next'

// 注册所有图标组件
const icons = {
  SearchIcon,
  SettingsIcon,
  ChevronLeftIcon,
  ChevronRightIcon,
  UsersIcon,
  ActivityIcon,
  TrendingUpIcon,
  TargetIcon,
  DownloadIcon,
  EyeIcon,
  UserPlusIcon,
  XIcon,
  HeadphonesIcon,
  ClockIcon,
  AlertTriangleIcon,
  XCircleIcon
}

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

// 状态管理
const isLoading = ref(false)
const searchText = ref('')
const serviceType = ref('')
const status = ref('')
const timeRange = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const totalTickets = ref(100)

// 默认图片
const defaultImages = {
  avatar: 'https://images.unsplash.com/photo-1535713875002-d1d0cf377fde?w=200&h=200&fit=crop&auto=format'
}

const mockTickets = ref([
  {
    id: 'T1001',
    customer: {
      id: 'U1001',
      name: '张三',
      level: 'vip',
      avatar: defaultImages.avatar
    },
    type: 'product',
    title: '商品质量问题',
    content: '收到的智能手表屏幕有划痕，要求换货',
    status: 'pending',
    priority: 'high',
    agent: {
      id: 'A1001',
      name: '客服小王',
      avatar: defaultImages.avatar
    },
    createTime: '2024-03-20 10:30:00',
    updateTime: '2024-03-20 10:30:00',
    responseTime: 0,
    resolutionTime: 0
  },
  {
    id: 'T1002',
    customer: {
      id: 'U1002',
      name: '李四',
      level: 'normal',
      avatar: defaultImages.avatar
    },
    type: 'delivery',
    title: '物流问题',
    content: '订单已发货3天，物流信息未更新',
    status: 'processing',
    priority: 'medium',
    agent: {
      id: 'A1002',
      name: '客服小李',
      avatar: defaultImages.avatar
    },
    createTime: '2024-03-19 14:20:00',
    updateTime: '2024-03-19 15:30:00',
    responseTime: 70,
    resolutionTime: 0
  },
  {
    id: 'T1003',
    customer: {
      id: 'U1003',
      name: '王五',
      level: 'vip',
      avatar: defaultImages.avatar
    },
    type: 'refund',
    title: '退款申请',
    content: '商品与描述不符，申请退款',
    status: 'completed',
    priority: 'high',
    agent: {
      id: 'A1001',
      name: '客服小王',
      avatar: defaultImages.avatar
    },
    createTime: '2024-03-18 09:15:00',
    updateTime: '2024-03-18 11:30:00',
    responseTime: 30,
    resolutionTime: 135
  },
  {
    id: 'T1004',
    customer: {
      id: 'U1004',
      name: '赵六',
      level: 'normal',
      avatar: defaultImages.avatar
    },
    type: 'complaint',
    title: '服务投诉',
    content: '客服态度不好，要求道歉',
    status: 'processing',
    priority: 'high',
    agent: {
      id: 'A1003',
      name: '客服小张',
      avatar: defaultImages.avatar
    },
    createTime: '2024-03-17 16:45:00',
    updateTime: '2024-03-17 17:00:00',
    responseTime: 15,
    resolutionTime: 0
  },
  {
    id: 'T1005',
    customer: {
      id: 'U1005',
      name: '钱七',
      level: 'vip',
      avatar: defaultImages.avatar
    },
    type: 'product',
    title: '商品咨询',
    content: '想了解新品的具体参数',
    status: 'completed',
    priority: 'low',
    agent: {
      id: 'A1002',
      name: '客服小李',
      avatar: defaultImages.avatar
    },
    createTime: '2024-03-16 11:25:00',
    updateTime: '2024-03-16 11:40:00',
    responseTime: 15,
    resolutionTime: 15
  }
])

// 客服统计数据
const serviceStats = ref({
  totalTickets: 1234,
  avgResponseTime: 25,
  pendingTickets: 56,
  complaintTickets: 12
})

// 工单类型分布
const ticketTypeDistribution = ref([
  { type: 'product', value: 450 },
  { type: 'delivery', value: 300 },
  { type: 'refund', value: 250 },
  { type: 'complaint', value: 150 },
  { type: 'other', value: 84 }
])

// 客服绩效数据
const agentPerformance = ref([
  {
    id: 'A1001',
    name: '客服小王',
    avatar: defaultImages.avatar,
    totalTickets: 280,
    avgResponseTime: 20,
    avgResolutionTime: 45,
    satisfactionRate: 0.95
  },
  {
    id: 'A1002',
    name: '客服小李',
    avatar: defaultImages.avatar,
    totalTickets: 250,
    avgResponseTime: 25,
    avgResolutionTime: 50,
    satisfactionRate: 0.92
  },
  {
    id: 'A1003',
    name: '客服小张',
    avatar: defaultImages.avatar,
    totalTickets: 200,
    avgResponseTime: 30,
    avgResolutionTime: 60,
    satisfactionRate: 0.88
  }
])

// 图表相关
const trendChartRef = ref(null)
const typeChartRef = ref(null)
const userGrowthChartRef = ref(null)
const userLevelChartRef = ref(null)
let trendChart = null
let typeChart = null
let userGrowthChart = null
let userLevelChart = null

// 模拟用户增长数据
const mockUserGrowthData = ref([
  { date: '2024-01', value: 1000 },
  { date: '2024-02', value: 1200 },
  { date: '2024-03', value: 1500 },
  { date: '2024-04', value: 1800 },
  { date: '2024-05', value: 2000 },
  { date: '2024-06', value: 2200 }
])

// 模拟用户等级分布数据
const mockUserLevelData = ref([
  { value: 500, name: '普通用户' },
  { value: 300, name: 'VIP用户' },
  { value: 200, name: 'SVIP用户' },
  { value: 100, name: '钻石用户' }
])

// 初始化趋势图表
const initTrendChart = () => {
  if (!trendChartRef.value) return
  
  if (trendChart) {
    trendChart.dispose()
  }
  
  trendChart = echarts.init(trendChartRef.value)
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
      boundaryGap: false
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '工单数量',
        type: 'line',
        data: [120, 132, 101, 134, 90, 230, 210],
        smooth: true,
        areaStyle: {
          opacity: 0.3
        },
        lineStyle: {
          width: 3
        },
        itemStyle: {
          color: '#4F46E5'
        }
      }
    ]
  }
  trendChart.setOption(option)
}

// 初始化类型分布图表
const initTypeChart = () => {
  if (!typeChartRef.value) return
  
  if (typeChart) {
    typeChart.dispose()
  }
  
  typeChart = echarts.init(typeChartRef.value)
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      top: 'middle'
    },
    series: [
      {
        name: '工单类型',
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['60%', '50%'],
        data: [
          { value: 235, name: '咨询' },
          { value: 274, name: '投诉' },
          { value: 310, name: '退款' },
          { value: 335, name: '技术支持' }
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        itemStyle: {
          borderRadius: 5,
          borderColor: '#fff',
          borderWidth: 2
        }
      }
    ]
  }
  typeChart.setOption(option)
}

// 初始化用户增长趋势图表
const initUserGrowthChart = () => {
  if (!userGrowthChartRef.value) return
  
  if (userGrowthChart) {
    userGrowthChart.dispose()
  }
  
  userGrowthChart = echarts.init(userGrowthChartRef.value)
  const option = {
    tooltip: {
      trigger: 'axis',
      formatter: '{b}<br/>{a}: {c}人'
    },
    xAxis: {
      type: 'category',
      data: mockUserGrowthData.value.map(item => item.date),
      axisLabel: {
        rotate: 45
      }
    },
    yAxis: {
      type: 'value',
      name: '用户数量'
    },
    series: [
      {
        name: '用户数量',
        type: 'line',
        data: mockUserGrowthData.value.map(item => item.value),
        smooth: true,
        areaStyle: {
          opacity: 0.3
        },
        lineStyle: {
          width: 3
        },
        itemStyle: {
          color: '#4F46E5'
        }
      }
    ]
  }
  userGrowthChart.setOption(option)
}

// 初始化用户等级分布图表
const initUserLevelChart = () => {
  if (!userLevelChartRef.value) return
  
  if (userLevelChart) {
    userLevelChart.dispose()
  }
  
  userLevelChart = echarts.init(userLevelChartRef.value)
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c}人 ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '用户等级',
        type: 'pie',
        radius: '50%',
        data: mockUserLevelData.value,
        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}人'
        }
      }
    ]
  }
  userLevelChart.setOption(option)
}

// 监听窗口大小变化
const handleResize = () => {
  if (trendChart) trendChart.resize()
  if (typeChart) typeChart.resize()
  if (userGrowthChart) userGrowthChart.resize()
  if (userLevelChart) userLevelChart.resize()
}

// 计算属性
const filteredTickets = computed(() => {
  let result = [...mockTickets.value]
  
  // 搜索过滤
  if (searchText.value) {
    result = result.filter(ticket => 
      ticket.title.includes(searchText.value) ||
      ticket.customer.name.includes(searchText.value) ||
      ticket.agent.name.includes(searchText.value)
    )
  }
  
  // 类型过滤
  if (serviceType.value) {
    result = result.filter(ticket => ticket.type === serviceType.value)
  }
  
  // 状态过滤
  if (status.value) {
    result = result.filter(ticket => ticket.status === status.value)
  }
  
  // 时间范围过滤
  if (timeRange.value) {
    const now = new Date()
    result = result.filter(ticket => {
      const createTime = new Date(ticket.createTime)
      
      switch (timeRange.value) {
        case 'today':
          return createTime.toDateString() === now.toDateString()
        case 'week':
          const weekStart = new Date(now.setDate(now.getDate() - now.getDay()))
          const weekEnd = new Date(weekStart)
          weekEnd.setDate(weekStart.getDate() + 6)
          return createTime >= weekStart && createTime <= weekEnd
        case 'month':
          const monthStart = new Date(now.getFullYear(), now.getMonth(), 1)
          const monthEnd = new Date(now.getFullYear(), now.getMonth() + 1, 0)
          return createTime >= monthStart && createTime <= monthEnd
        case 'quarter':
          const quarter = Math.floor(now.getMonth() / 3)
          const quarterStart = new Date(now.getFullYear(), quarter * 3, 1)
          const quarterEnd = new Date(now.getFullYear(), quarter * 3 + 3, 0)
          return createTime >= quarterStart && createTime <= quarterEnd
        default:
          return true
      }
    })
  }
  
  return result
})

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

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

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

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

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

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

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

const handleViewTicket = (ticket) => {
  console.log('查看工单:', ticket)
}

const handleAssignTicket = (ticket) => {
  console.log('分配工单:', ticket)
}

const handleCloseTicket = (ticket) => {
  console.log('关闭工单:', ticket)
}

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

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

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

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

/* 工单类型标签样式 */
.type-tag {
  @apply px-2 inline-flex text-xs leading-5 font-semibold rounded-full;
}

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

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

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

.type-technical {
  @apply bg-purple-100 dark:bg-purple-900 text-purple-800 dark:text-purple-400;
}

/* 工单状态标签样式 */
.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-resolved {
  @apply bg-green-100 dark:bg-green-900 text-green-800 dark:text-green-400;
}

.status-closed {
  @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;
}

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

.delete-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> 