<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="handleAddCampaign"
              class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 flex items-center space-x-2"
            >
              <PlusIcon class="h-5 w-5" />
              <span>新增活动</span>
            </button>
            <button 
              @click="handleExportData"
              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="campaignType"
            @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="discount">折扣活动</option>
            <option value="coupon">优惠券</option>
            <option value="flash">限时抢购</option>
            <option value="group">拼团活动</option>
          </select>
          <select 
            v-model="campaignStatus"
            @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="draft">草稿</option>
            <option value="pending">待审核</option>
            <option value="active">进行中</option>
            <option value="ended">已结束</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">
              <MegaphoneIcon 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">{{ mockCampaigns.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">
              <ActivityIcon 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">{{ mockCampaigns.filter(campaign => campaign.status === 'active').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-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">{{ mockCampaigns.filter(campaign => campaign.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">{{ mockCampaigns.filter(campaign => campaign.status === 'ended').length }}</p>
            </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>
                <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="campaign in paginatedCampaigns" :key="campaign.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-md object-cover" :src="campaign.image" :alt="campaign.name">
                    </div>
                    <div class="ml-4">
                      <div class="text-sm font-medium text-gray-900 dark:text-white">{{ campaign.name }}</div>
                      <div class="text-sm text-gray-500 dark:text-gray-400">{{ campaign.code }}</div>
                    </div>
                  </div>
                </td>
                <td class="px-6 py-4">
                  <span :class="['type-tag', `type-${campaign.type}`]">
                    {{ campaign.type === 'discount' ? '折扣活动' : 
                       campaign.type === 'coupon' ? '优惠券' : 
                       campaign.type === 'flash' ? '限时抢购' : '拼团活动' }}
                  </span>
                </td>
                <td class="px-6 py-4">
                  <div class="text-sm text-gray-900 dark:text-white">{{ campaign.startTime }}</div>
                  <div class="text-sm text-gray-500 dark:text-gray-400">{{ campaign.endTime }}</div>
                </td>
                <td class="px-6 py-4">
                  <div class="text-sm text-gray-900 dark:text-white">{{ campaign.participants }}</div>
                </td>
                <td class="px-6 py-4">
                  <span :class="['status-tag', `status-${campaign.status}`]">
                    {{ campaign.status === 'draft' ? '草稿' : 
                       campaign.status === 'pending' ? '待审核' : 
                       campaign.status === 'active' ? '进行中' : '已结束' }}
                  </span>
                </td>
                <td class="px-6 py-4 text-sm font-medium">
                  <button 
                    @click="handleViewCampaign(campaign)"
                    class="action-button view-button"
                  >
                    <EyeIcon class="h-4 w-4 inline-block mr-1" />
                    查看
                  </button>
                  <button 
                    @click="handleEditCampaign(campaign)"
                    class="action-button edit-button"
                  >
                    <EditIcon class="h-4 w-4 inline-block mr-1" />
                    编辑
                  </button>
                  <button 
                    @click="handleDeleteCampaign(campaign)"
                    class="action-button delete-button"
                  >
                    <TrashIcon 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, filteredCampaigns.length) }}</span> 条，共 
              <span class="font-medium">{{ filteredCampaigns.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 { 
  LineChart,
  BarChart,
  PieChart,
  ScatterChart
} from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  DataZoomComponent
} from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'
import { 
  SearchIcon, 
  SettingsIcon, 
  ChevronLeftIcon, 
  ChevronRightIcon,
  MegaphoneIcon,
  ActivityIcon,
  ClockIcon,
  XCircleIcon,
  DownloadIcon,
  PlusIcon,
  EyeIcon,
  EditIcon,
  TrashIcon
} from 'lucide-vue-next'

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

// 状态管理
const isLoading = ref(false)
const searchText = ref('')
const campaignType = ref('')
const campaignStatus = ref('')
const timeRange = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const totalCampaigns = ref(100)

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

// 模拟数据
const mockCampaigns = ref([
  {
    id: 'C1001',
    name: '春季新品促销',
    code: 'SPRING2024',
    type: 'discount',
    status: 'active',
    startTime: '2024-03-01',
    endTime: '2024-03-31',
    budget: 50000,
    spent: 35000,
    impressions: 120000,
    clicks: 15000,
    conversions: 1200,
    roi: 2.5,
    image: defaultImages.product,
    participants: 1200,
    products: [
      {
        id: 'P1001',
        name: 'iPhone 15 Pro',
        image: defaultImages.product,
        price: 8999,
        discount: 0.9
      },
      {
        id: 'P1002',
        name: 'MacBook Pro',
        image: defaultImages.product,
        price: 12999,
        discount: 0.95
      }
    ],
    targetAudience: {
      age: '18-35',
      gender: 'all',
      interests: ['科技', '数码']
    }
  },
  {
    id: 'C1002',
    name: '会员专享优惠',
    code: 'VIP2024',
    type: 'membership',
    status: 'active',
    startTime: '2024-03-15',
    endTime: '2024-04-15',
    budget: 30000,
    spent: 12000,
    impressions: 80000,
    clicks: 8000,
    conversions: 600,
    roi: 1.8,
    image: defaultImages.product,
    participants: 800,
    products: [
      {
        id: 'P1003',
        name: 'AirPods Pro',
        image: defaultImages.product,
        price: 1999,
        discount: 0.85
      },
      {
        id: 'P1004',
        name: 'iPad Pro',
        image: defaultImages.product,
        price: 6999,
        discount: 0.9
      }
    ],
    targetAudience: {
      age: '25-45',
      gender: 'all',
      interests: ['音乐', '娱乐']
    }
  },
  {
    id: 'C1003',
    name: '限时秒杀活动',
    code: 'FLASH2024',
    type: 'flash_sale',
    status: 'completed',
    startTime: '2024-02-20',
    endTime: '2024-02-21',
    budget: 20000,
    spent: 20000,
    impressions: 150000,
    clicks: 20000,
    conversions: 1800,
    roi: 3.2,
    image: defaultImages.product,
    participants: 1800,
    products: [
      {
        id: 'P1005',
        name: 'Apple Watch',
        image: defaultImages.product,
        price: 2999,
        discount: 0.7
      }
    ],
    targetAudience: {
      age: '20-40',
      gender: 'all',
      interests: ['健康', '运动']
    }
  }
])

// 营销统计数据
const marketingStats = ref({
  totalCampaigns: 1234,
  activeCampaigns: 56,
  completedCampaigns: 1024,
  cancelledCampaigns: 154
})

// 计算属性
const filteredCampaigns = computed(() => {
  let result = [...mockCampaigns.value]
  
  // 搜索过滤
  if (searchText.value) {
    result = result.filter(campaign => 
      campaign.name.includes(searchText.value) ||
      campaign.code.includes(searchText.value)
    )
  }
  
  // 类型过滤
  if (campaignType.value) {
    result = result.filter(campaign => campaign.type === campaignType.value)
  }
  
  // 状态过滤
  if (campaignStatus.value) {
    result = result.filter(campaign => campaign.status === campaignStatus.value)
  }
  
  // 时间范围过滤
  if (timeRange.value) {
    const now = new Date()
    result = result.filter(campaign => {
      const startTime = new Date(campaign.startTime)
      const endTime = new Date(campaign.endTime)
      
      switch (timeRange.value) {
        case 'today':
          return startTime <= now && endTime >= now
        case 'week':
          const weekStart = new Date(now.setDate(now.getDate() - now.getDay()))
          const weekEnd = new Date(weekStart)
          weekEnd.setDate(weekStart.getDate() + 6)
          return startTime <= weekEnd && endTime >= weekStart
        case 'month':
          const monthStart = new Date(now.getFullYear(), now.getMonth(), 1)
          const monthEnd = new Date(now.getFullYear(), now.getMonth() + 1, 0)
          return startTime <= monthEnd && endTime >= monthStart
        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 startTime <= quarterEnd && endTime >= quarterStart
        default:
          return true
      }
    })
  }
  
  return result
})

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

const totalPages = computed(() => {
  return Math.ceil(filteredCampaigns.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 handleAddCampaign = () => {
  console.log('新增活动')
}

const handleViewCampaign = (campaign) => {
  console.log('查看活动:', campaign)
}

const handleEditCampaign = (campaign) => {
  console.log('编辑活动:', campaign)
}

const handleDeleteCampaign = (campaign) => {
  console.log('删除活动:', campaign)
}

const handleExportData = () => {
  console.log('导出数据')
}

// 生命周期钩子
onMounted(() => {
  // 初始化数据
  console.log('营销管理页面已加载')
})
</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-discount {
  @apply bg-blue-100 dark:bg-blue-900 text-blue-800 dark:text-blue-400;
}

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

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

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

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

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

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

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

.status-ended {
  @apply bg-red-100 dark:bg-red-900 text-red-800 dark:text-red-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> 