<template>
  <div class="order-management">
    <!-- 左侧导航栏 -->
    <aside class="sidebar">
      <div class="logo">
        <div class="logo-icon"></div>
        <span>LOGO</span>
      </div>
      <nav class="nav-menu">
        <div class="nav-item" @click="goToDashboard">
          <el-icon><Grid /></el-icon>
          <span>数据仪表台</span>
        </div>
        <div class="nav-item" @click="goToMembers">
          <el-icon><User /></el-icon>
          <span>会员管理</span>
        </div>
        <div class="nav-item active">
          <el-icon><ShoppingCart /></el-icon>
          <span>订单管理</span>
        </div>
        <div class="nav-item" @click="goToAPI">
          <el-icon><Document /></el-icon>
          <span>API管理</span>
        </div>
        <div class="nav-item" @click="goToTasks">
          <el-icon><Document /></el-icon>
          <span>生成任务记录</span>
        </div>
        <div class="nav-item" @click="goToSettings">
          <el-icon><Setting /></el-icon>
          <span>系统设置</span>
        </div>
      </nav>
      <div class="sidebar-footer">
        <div class="online-users">
          当前在线用户: <span class="highlight">{{ systemStatus.onlineUsers }}/500</span>
        </div>
        <div class="system-uptime">
          系统运行时间: <span class="highlight">{{ systemStatus.systemUptime }}</span>
        </div>
      </div>
    </aside>

    <!-- 主内容区域 -->
    <main class="main-content">
      <!-- 顶部搜索栏 -->
      <header class="top-header">
        <div class="search-bar">
          <el-icon class="search-icon"><Search /></el-icon>
          <input type="text" placeholder="搜索你的想要的内容" class="search-input" />
        </div>
        <div class="header-actions">
          <el-icon class="notification-icon"><Bell /></el-icon>
          <el-icon class="message-icon"><ChatDotSquare /></el-icon>
          <div class="user-avatar">
            <img src="/images/backgrounds/welcome.jpg" alt="用户头像" />
            <el-icon class="dropdown-icon"><ArrowDown /></el-icon>
          </div>
        </div>
      </header>

      <!-- 订单管理内容 -->
      <div class="order-content">
        <div class="order-header">
          <h1 class="order-title">订单管理</h1>
          <div class="selection-info" v-if="selectedOrders.length > 0">
            已选择{{ selectedOrders.length }}项
          </div>
        </div>

        <!-- 筛选和操作栏 -->
        <div class="filter-bar">
          <div class="filter-controls">
            <el-select v-model="filters.orderType" placeholder="全部类型" @change="loadOrders">
              <el-option label="全部类型" value="" />
              <el-option label="会员订阅" value="SUBSCRIPTION" />
              <el-option label="视频生成" value="SERVICE" />
              <el-option label="产品订单" value="PRODUCT" />
            </el-select>
            
            <el-select v-model="filters.status" placeholder="全部状态" @change="loadOrders">
              <el-option label="全部状态" value="" />
              <el-option label="已完成" value="COMPLETED" />
              <el-option label="处理中" value="PROCESSING" />
              <el-option label="已取消" value="CANCELLED" />
              <el-option label="待支付" value="PENDING" />
            </el-select>
          </div>
          
          <div class="action-controls">
            <el-button 
              type="danger" 
              :disabled="selectedOrders.length === 0"
              @click="deleteSelectedOrders">
              删除
            </el-button>
          </div>
        </div>

        <!-- 订单表格 -->
        <div class="order-table-container">
          <table class="order-table">
            <thead>
              <tr>
                <th class="checkbox-column">
                  <el-checkbox 
                    v-model="selectAll" 
                    @change="toggleSelectAll"
                    :indeterminate="isIndeterminate">
                  </el-checkbox>
                </th>
                <th>订单编号</th>
                <th>用户名</th>
                <th>金额</th>
                <th>支付方式</th>
                <th>状态</th>
                <th>创建时间</th>
                <th>编辑</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="order in orders" :key="order.id" class="order-row">
                <td class="checkbox-column">
                  <el-checkbox 
                    v-model="selectedOrders" 
                    :value="order.id"
                    @change="updateSelection">
                  </el-checkbox>
                </td>
                <td class="order-number">{{ order.orderNumber }}</td>
                <td class="username">{{ order.user?.username || '未知用户' }}</td>
                <td class="amount">¥{{ formatAmount(order.totalAmount) }}</td>
                <td class="payment-method">
                  <div class="payment-icon" :class="getPaymentMethodClass(order.paymentMethod)">
                    <el-icon v-if="order.paymentMethod === 'ALIPAY'"><CreditCard /></el-icon>
                    <el-icon v-else-if="order.paymentMethod === 'WECHAT'"><CreditCard /></el-icon>
                    <el-icon v-else><CreditCard /></el-icon>
                  </div>
                </td>
                <td class="status">
                  <span class="status-tag" :class="getStatusClass(order.status)">
                    {{ getStatusText(order.status) }}
                  </span>
                </td>
                <td class="created-time">{{ formatDateTime(order.createdAt) }}</td>
                <td class="actions">
                  <span class="action-link" @click="viewOrder(order)">查看</span>
                  <span class="action-link delete" @click="deleteOrder(order)">删除</span>
                </td>
              </tr>
            </tbody>
          </table>
        </div>

        <!-- 分页 -->
        <div class="pagination-container">
          <div class="pagination">
            <button class="page-btn" @click="goToPage(currentPage - 1)" :disabled="currentPage <= 1">
              <el-icon><ArrowLeft /></el-icon>
            </button>
            
            <div class="page-numbers">
              <button 
                v-for="page in visiblePages" 
                :key="page"
                class="page-number"
                :class="{ active: page === currentPage }"
                @click="goToPage(page)">
                {{ page }}
              </button>
              <span v-if="showEllipsis" class="ellipsis">...</span>
              <button 
                v-if="totalPages > 1"
                class="page-number"
                :class="{ active: totalPages === currentPage }"
                @click="goToPage(totalPages)">
                {{ totalPages }}
              </button>
            </div>
            
            <button class="page-btn" @click="goToPage(currentPage + 1)" :disabled="currentPage >= totalPages">
              <el-icon><ArrowRight /></el-icon>
            </button>
          </div>
        </div>
      </div>
    </main>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Grid,
  User,
  ShoppingCart,
  Document,
  Setting,
  User as Search,
  Bell,
  User as ArrowDown,
  User as ArrowLeft,
  User as ArrowRight,
  User as View,
  User as Delete,
  CreditCard,
  Wallet,
  Money
} from '@element-plus/icons-vue'
import * as orderAPI from '@/api/orders'

const router = useRouter()

// 系统状态
const systemStatus = ref({
  onlineUsers: 87,
  systemUptime: '48小时32分'
})

// 订单数据
const orders = ref([])
const loading = ref(false)

// 筛选条件
const filters = reactive({
  orderType: '',
  status: '',
  search: ''
})

// 分页
const currentPage = ref(1)
const pageSize = ref(10)
const totalOrders = ref(0)

// 选择
const selectedOrders = ref([])
const selectAll = ref(false)

// 计算属性
const totalPages = computed(() => Math.ceil(totalOrders.value / pageSize.value))

const isIndeterminate = computed(() => {
  return selectedOrders.value.length > 0 && selectedOrders.value.length < orders.value.length
})

const visiblePages = computed(() => {
  const pages = []
  const start = Math.max(1, currentPage.value - 2)
  const end = Math.min(totalPages.value, start + 4)
  
  for (let i = start; i <= end; i++) {
    pages.push(i)
  }
  return pages
})

const showEllipsis = computed(() => {
  return totalPages.value > 5 && currentPage.value < totalPages.value - 2
})

// 加载订单数据
const loadOrders = async () => {
  try {
    loading.value = true
    
    const params = {
      page: currentPage.value - 1,
      size: pageSize.value,
      sortBy: 'createdAt',
      sortDir: 'desc'
    }
    
    if (filters.orderType) {
      params.orderType = filters.orderType
    }
    
    if (filters.status) {
      params.status = filters.status
    }
    
    if (filters.search) {
      params.search = filters.search
    }
    
    const response = await orderAPI.getOrders(params)
    
    if (response.success) {
      orders.value = response.data.content || []
      totalOrders.value = response.data.totalElements || 0
    } else {
      ElMessage.error(response.message || '加载订单数据失败')
    }
    
  } catch (error) {
    console.error('加载订单数据失败:', error)
    ElMessage.error('加载订单数据失败')
  } finally {
    loading.value = false
  }
}

// 格式化金额
const formatAmount = (amount) => {
  if (!amount) return '0.00'
  return parseFloat(amount).toFixed(2)
}

// 格式化日期时间
const formatDateTime = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    'COMPLETED': '已完成',
    'PROCESSING': '处理中',
    'CANCELLED': '已取消',
    'PENDING': '待支付',
    'CONFIRMED': '已确认',
    'PAID': '已支付',
    'SHIPPED': '已发货',
    'DELIVERED': '已送达',
    'REFUNDED': '已退款'
  }
  return statusMap[status] || status
}

// 获取状态样式类
const getStatusClass = (status) => {
  const classMap = {
    'COMPLETED': 'status-completed',
    'PROCESSING': 'status-processing',
    'CANCELLED': 'status-cancelled',
    'PENDING': 'status-pending',
    'CONFIRMED': 'status-confirmed',
    'PAID': 'status-paid',
    'SHIPPED': 'status-shipped',
    'DELIVERED': 'status-delivered',
    'REFUNDED': 'status-refunded'
  }
  return classMap[status] || ''
}

// 获取支付方式样式类
const getPaymentMethodClass = (method) => {
  const classMap = {
    'ALIPAY': 'payment-alipay',
    'WECHAT': 'payment-wechat',
    'PAYPAL': 'payment-paypal'
  }
  return classMap[method] || 'payment-default'
}

// 全选/取消全选
const toggleSelectAll = () => {
  if (selectAll.value) {
    selectedOrders.value = orders.value.map(order => order.id)
  } else {
    selectedOrders.value = []
  }
}

// 更新选择状态
const updateSelection = () => {
  selectAll.value = selectedOrders.value.length === orders.value.length
}

// 查看订单
const viewOrder = (order) => {
  router.push(`/orders/${order.id}`)
}

// 删除单个订单
const deleteOrder = async (order) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除订单 ${order.orderNumber} 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await orderAPI.deleteOrder(order.id)
    
    if (response.success) {
      ElMessage.success('订单删除成功')
      loadOrders()
    } else {
      ElMessage.error(response.message || '删除订单失败')
    }
    
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除订单失败:', error)
      ElMessage.error('删除订单失败')
    }
  }
}

// 批量删除订单
const deleteSelectedOrders = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedOrders.value.length} 个订单吗？`,
      '确认批量删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await orderAPI.deleteOrders(selectedOrders.value)
    
    if (response.success) {
      ElMessage.success(`批量删除成功，共删除 ${response.deletedCount} 个订单`)
      selectedOrders.value = []
      selectAll.value = false
      loadOrders()
    } else {
      ElMessage.error(response.message || '批量删除失败')
    }
    
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  }
}

// 分页导航
const goToPage = (page) => {
  if (page >= 1 && page <= totalPages.value) {
    currentPage.value = page
    loadOrders()
  }
}

// 导航功能
const goToDashboard = () => {
  router.push('/home')
}

const goToMembers = () => {
  router.push('/member-management')
}

const goToAPI = () => {
  router.push('/api-management')
}

const goToTasks = () => {
  router.push('/generate-task-record')
}

const goToSettings = () => {
  router.push('/system-settings')
}

onMounted(() => {
  loadOrders()
})
</script>

<style scoped>
.order-management {
  display: flex;
  min-height: 100vh;
  background: #f8fafc;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

/* 左侧导航栏 */
.sidebar {
  width: 320px;
  background: white;
  border-right: 1px solid #e2e8f0;
  display: flex;
  flex-direction: column;
  padding: 24px 0;
}

.logo {
  display: flex;
  align-items: center;
  padding: 0 28px;
  margin-bottom: 32px;
}

.logo-icon {
  width: 32px;
  height: 32px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 8px;
  margin-right: 12px;
}

.logo span {
  font-size: 20px;
  font-weight: 700;
  color: #1f2937;
}

.nav-menu {
  flex: 1;
  padding: 0 24px;
}

.nav-item {
  display: flex;
  align-items: center;
  padding: 18px 24px;
  margin-bottom: 6px;
  border-radius: 10px;
  cursor: pointer;
  transition: all 0.2s ease;
  color: #64748b;
  font-size: 16px;
}

.nav-item:hover {
  background: #f1f5f9;
  color: #334155;
}

.nav-item.active {
  background: #3b82f6;
  color: white;
}

.nav-item .el-icon {
  margin-right: 16px;
  font-size: 22px;
}

.nav-item span {
  font-size: 16px;
  font-weight: 500;
}

.sidebar-footer {
  padding: 0 32px 20px;
  margin-top: auto;
}

.online-users,
.system-uptime {
  font-size: 14px;
  color: #64748b;
  margin-bottom: 10px;
  line-height: 1.5;
}

.highlight {
  color: #3b82f6;
  font-weight: 600;
  font-size: 15px;
}

/* 主内容区域 */
.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: #f8fafc;
}

/* 顶部搜索栏 */
.top-header {
  background: white;
  padding: 16px 24px;
  border-bottom: 1px solid #e2e8f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-bar {
  position: relative;
  display: flex;
  align-items: center;
}

.search-icon {
  position: absolute;
  left: 12px;
  color: #9ca3af;
  font-size: 16px;
}

.search-input {
  padding: 8px 12px 8px 40px;
  border: 1px solid #d1d5db;
  border-radius: 8px;
  width: 300px;
  font-size: 14px;
  outline: none;
  transition: border-color 0.2s;
}

.search-input:focus {
  border-color: #3b82f6;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 16px;
}

.notification-icon,
.message-icon {
  font-size: 20px;
  color: #6b7280;
  cursor: pointer;
  transition: color 0.2s;
}

.notification-icon:hover,
.message-icon:hover {
  color: #3b82f6;
}

.user-avatar {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.user-avatar img {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  margin-right: 8px;
}

.dropdown-icon {
  font-size: 12px;
  color: #6b7280;
}

/* 订单内容 */
.order-content {
  flex: 1;
  padding: 24px;
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.order-title {
  font-size: 24px;
  font-weight: 600;
  color: #1f2937;
  margin: 0;
}

.selection-info {
  font-size: 14px;
  color: #6b7280;
}

/* 筛选栏 */
.filter-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 16px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.filter-controls {
  display: flex;
  gap: 16px;
}

.action-controls {
  display: flex;
  gap: 12px;
}

/* 订单表格 */
.order-table-container {
  background: white;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.order-table {
  width: 100%;
  border-collapse: collapse;
}

.order-table th {
  background: #f8fafc;
  padding: 16px;
  text-align: left;
  font-weight: 600;
  color: #374151;
  border-bottom: 1px solid #e5e7eb;
}

.order-table td {
  padding: 16px;
  border-bottom: 1px solid #f3f4f6;
}

.order-row:hover {
  background: #f9fafb;
}

.checkbox-column {
  width: 50px;
  text-align: center;
}

.order-number {
  font-family: 'Monaco', 'Menlo', monospace;
  font-weight: 500;
  color: #1f2937;
}

.username {
  font-weight: 500;
  color: #374151;
}

.amount {
  font-weight: 600;
  color: #059669;
}

.payment-method {
  display: flex;
  align-items: center;
}

.payment-icon {
  width: 24px;
  height: 24px;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 12px;
}

.payment-alipay {
  background: #1677ff;
}

.payment-wechat {
  background: #07c160;
}

.payment-paypal {
  background: #0070ba;
}

.payment-default {
  background: #6b7280;
}

.status-tag {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.status-completed {
  background: #dcfce7;
  color: #166534;
}

.status-processing {
  background: #dbeafe;
  color: #1e40af;
}

.status-cancelled {
  background: #fee2e2;
  color: #dc2626;
}

.status-pending {
  background: #fef3c7;
  color: #d97706;
}

.status-confirmed {
  background: #e0e7ff;
  color: #3730a3;
}

.status-paid {
  background: #d1fae5;
  color: #065f46;
}

.status-shipped {
  background: #dbeafe;
  color: #1e40af;
}

.status-delivered {
  background: #dcfce7;
  color: #166534;
}

.status-refunded {
  background: #f3e8ff;
  color: #7c3aed;
}

.created-time {
  color: #6b7280;
  font-size: 14px;
}

.actions {
  display: flex;
  gap: 16px;
}

.action-link {
  color: #3b82f6;
  cursor: pointer;
  font-size: 14px;
  transition: color 0.2s;
}

.action-link:hover {
  color: #1d4ed8;
}

.action-link.delete {
  color: #dc2626;
}

.action-link.delete:hover {
  color: #b91c1c;
}

/* 分页 */
.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 24px;
}

.pagination {
  display: flex;
  align-items: center;
  gap: 8px;
}

.page-btn {
  width: 32px;
  height: 32px;
  border: 1px solid #d1d5db;
  background: white;
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.2s;
}

.page-btn:hover:not(:disabled) {
  border-color: #3b82f6;
  color: #3b82f6;
}

.page-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.page-numbers {
  display: flex;
  gap: 4px;
}

.page-number {
  width: 32px;
  height: 32px;
  border: 1px solid #d1d5db;
  background: white;
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.2s;
  font-size: 14px;
}

.page-number:hover {
  border-color: #3b82f6;
  color: #3b82f6;
}

.page-number.active {
  background: #3b82f6;
  border-color: #3b82f6;
  color: white;
}

.ellipsis {
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #6b7280;
  font-size: 14px;
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .sidebar {
    width: 280px;
  }
  
  .search-input {
    width: 250px;
  }
}

@media (max-width: 768px) {
  .order-management {
    flex-direction: column;
  }
  
  .sidebar {
    width: 100%;
    height: auto;
  }
  
  .nav-menu {
    display: flex;
    overflow-x: auto;
    padding: 0 16px;
  }
  
  .nav-item {
    white-space: nowrap;
    margin-right: 16px;
    margin-bottom: 0;
  }
  
  .order-content {
    padding: 16px;
  }
  
  .filter-bar {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .filter-controls {
    justify-content: center;
  }
  
  .order-table-container {
    overflow-x: auto;
  }
  
  .order-table {
    min-width: 800px;
  }
}
</style>