<template>
  <div class="d-flex flex-column h-100">
    <!-- 页面头部 -->
    <v-toolbar density="compact" class="flex-shrink-0">
      <v-toolbar-title>订单管理</v-toolbar-title>
      <v-spacer />
      <v-btn
        icon="mdi-refresh"
        :loading="loading"
        @click="fetchData"
      />
      <v-btn
        color="primary"
        prepend-icon="mdi-download"
        :loading="exporting"
        @click="exportData"
      >
        导出
      </v-btn>
    </v-toolbar>

    <!-- 筛选栏 - 粘性定位 -->
    <v-sheet class="flex-shrink-0 pa-4 sticky-filter">
      <v-row dense>
        <v-col cols="12" sm="6" md="3">
          <v-text-field
            v-model="filters.search"
            label="搜索订单号/客户名"
            prepend-inner-icon="mdi-magnify"
            clearable
            hide-details
            @update:model-value="debouncedFetch"
          />
        </v-col>
        <v-col cols="12" sm="6" md="2">
          <v-select
            v-model="filters.status"
            :items="statusOptions"
            label="状态"
            clearable
            hide-details
            @update:model-value="fetchData"
          />
        </v-col>
        <v-col cols="12" sm="6" md="3">
          <v-text-field
            v-model="filters.dateRange"
            label="日期范围"
            prepend-inner-icon="mdi-calendar"
            readonly
            hide-details
            @click="showDatePicker = true"
          />
        </v-col>
        <v-col cols="12" sm="6" md="2">
          <v-btn
            variant="outlined"
            block
            @click="resetFilters"
          >
            重置筛选
          </v-btn>
        </v-col>
      </v-row>
    </v-sheet>

    <v-divider />

    <!-- 主内容区 - 可滚动 -->
    <div class="flex-grow-1 overflow-y-auto" style="min-height: 0">
      <!-- 加载状态 -->
      <v-skeleton-loader
        v-if="loading && !orders.length"
        type="table-heading, table-row@8"
        class="ma-4"
      />

      <!-- 空状态 -->
      <v-empty-state
        v-else-if="!orders.length"
        icon="mdi-package-variant"
        title="暂无订单"
        text="当前筛选条件下没有找到订单记录"
      >
        <template #actions>
          <v-btn variant="outlined" @click="resetFilters">
            清除筛选
          </v-btn>
          <v-btn color="primary" @click="fetchData">
            刷新
          </v-btn>
        </template>
      </v-empty-state>

      <!-- 数据表格 -->
      <v-data-table-server
        v-else
        v-model:items-per-page="pagination.pageSize"
        v-model:page="pagination.page"
        :headers="headers"
        :items="orders"
        :items-length="pagination.total"
        :loading="loading"
        fixed-header
        hover
        @update:options="onOptionsChange"
      >
        <!-- 订单号 - 可点击 -->
        <template #item.orderNo="{ item }">
          <a
            href="#"
            class="text-primary text-decoration-none"
            @click.prevent="viewDetail(item)"
          >
            {{ item.orderNo }}
          </a>
        </template>

        <!-- 客户名 - 截断 + Tooltip -->
        <template #item.customerName="{ value }">
          <v-tooltip :text="value" location="top">
            <template #activator="{ props }">
              <span
                v-bind="props"
                class="text-truncate d-inline-block"
                style="max-width: 120px"
              >
                {{ value }}
              </span>
            </template>
          </v-tooltip>
        </template>

        <!-- 金额 - 格式化 -->
        <template #item.amount="{ value }">
          <span class="font-weight-medium">
            ¥{{ formatNumber(value) }}
          </span>
        </template>

        <!-- 状态 - Chip -->
        <template #item.status="{ value }">
          <v-chip
            :color="getStatusColor(value)"
            size="small"
            variant="tonal"
          >
            {{ getStatusText(value) }}
          </v-chip>
        </template>

        <!-- 备注 - 多行截断 -->
        <template #item.remark="{ value }">
          <div v-if="value" class="remark-cell">
            <v-tooltip :text="value" location="top" max-width="300">
              <template #activator="{ props }">
                <span v-bind="props" class="line-clamp-2">
                  {{ value }}
                </span>
              </template>
            </v-tooltip>
          </div>
          <span v-else class="text-grey">-</span>
        </template>

        <!-- 操作列 -->
        <template #item.actions="{ item }">
          <v-btn
            icon="mdi-eye"
            size="small"
            variant="text"
            @click="viewDetail(item)"
          />
          <v-btn
            icon="mdi-pencil"
            size="small"
            variant="text"
            :disabled="item.status === 'completed'"
            @click="editOrder(item)"
          />
          <v-menu>
            <template #activator="{ props }">
              <v-btn
                v-bind="props"
                icon="mdi-dots-vertical"
                size="small"
                variant="text"
              />
            </template>
            <v-list density="compact">
              <v-list-item @click="copyOrderNo(item)">
                <template #prepend>
                  <v-icon size="small">mdi-content-copy</v-icon>
                </template>
                <v-list-item-title>复制订单号</v-list-item-title>
              </v-list-item>
              <v-list-item
                :disabled="item.status !== 'pending'"
                @click="cancelOrder(item)"
              >
                <template #prepend>
                  <v-icon size="small" color="error">mdi-cancel</v-icon>
                </template>
                <v-list-item-title class="text-error">取消订单</v-list-item-title>
              </v-list-item>
            </v-list>
          </v-menu>
        </template>

        <!-- 空数据插槽 -->
        <template #no-data>
          <v-empty-state
            icon="mdi-database-off"
            title="暂无数据"
            text="请尝试调整筛选条件"
          />
        </template>
      </v-data-table-server>
    </div>

    <!-- 底部统计栏 -->
    <v-sheet class="flex-shrink-0 pa-2 border-t d-flex align-center justify-space-between">
      <span class="text-body-2 text-grey">
        共 {{ pagination.total }} 条记录
      </span>
      <span class="text-body-2">
        已选 <strong>{{ selectedCount }}</strong> 条
        <v-btn
          v-if="selectedCount > 0"
          variant="text"
          size="small"
          color="primary"
          @click="batchAction"
        >
          批量操作
        </v-btn>
      </span>
    </v-sheet>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useDebounceFn } from '@vueuse/core'
import type { Order, OrderStatus } from '@/types/order'
import { orderApi } from '@/api/modules/order'
import { useSnackbar } from '@/composables/useSnackbar'

// Composables
const snackbar = useSnackbar()

// State
const loading = ref(false)
const exporting = ref(false)
const showDatePicker = ref(false)
const orders = ref<Order[]>([])
const selectedCount = ref(0)

const filters = reactive({
  search: '',
  status: null as OrderStatus | null,
  dateRange: '',
})

const pagination = reactive({
  page: 1,
  pageSize: 20,
  total: 0,
})

// Table Headers
const headers = [
  { title: '订单号', key: 'orderNo', width: 160 },
  { title: '客户名称', key: 'customerName', width: 150 },
  { title: '金额', key: 'amount', width: 120, align: 'end' as const },
  { title: '状态', key: 'status', width: 100 },
  { title: '备注', key: 'remark', width: 200 },
  { title: '创建时间', key: 'createdAt', width: 170 },
  { title: '操作', key: 'actions', width: 140, sortable: false },
]

const statusOptions = [
  { title: '全部', value: null },
  { title: '待处理', value: 'pending' },
  { title: '处理中', value: 'processing' },
  { title: '已完成', value: 'completed' },
  { title: '已取消', value: 'cancelled' },
]

// Methods
async function fetchData() {
  loading.value = true
  try {
    const result = await orderApi.getPage({
      page: pagination.page,
      pageSize: pagination.pageSize,
      search: filters.search || undefined,
      status: filters.status || undefined,
    })
    orders.value = result.list
    pagination.total = result.total
  } catch (error) {
    console.error('Failed to fetch orders:', error)
  } finally {
    loading.value = false
  }
}

const debouncedFetch = useDebounceFn(fetchData, 300)

function onOptionsChange(options: { page: number; itemsPerPage: number }) {
  pagination.page = options.page
  pagination.pageSize = options.itemsPerPage
  fetchData()
}

function resetFilters() {
  filters.search = ''
  filters.status = null
  filters.dateRange = ''
  pagination.page = 1
  fetchData()
}

async function exportData() {
  exporting.value = true
  try {
    const blob = await orderApi.export(filters)
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = `orders_${Date.now()}.xlsx`
    a.click()
    URL.revokeObjectURL(url)
    snackbar.success('导出成功')
  } catch (error) {
    snackbar.error('导出失败')
  } finally {
    exporting.value = false
  }
}

function viewDetail(item: Order) {
  // Navigate to detail page
}

function editOrder(item: Order) {
  // Open edit dialog
}

function copyOrderNo(item: Order) {
  navigator.clipboard.writeText(item.orderNo)
  snackbar.success('订单号已复制')
}

function cancelOrder(item: Order) {
  // Show confirm dialog
}

function batchAction() {
  // Show batch action menu
}

// Helpers
function formatNumber(value: number): string {
  return value.toLocaleString('zh-CN', { minimumFractionDigits: 2 })
}

function getStatusColor(status: OrderStatus): string {
  const colors: Record<OrderStatus, string> = {
    pending: 'warning',
    processing: 'info',
    completed: 'success',
    cancelled: 'grey',
  }
  return colors[status] || 'grey'
}

function getStatusText(status: OrderStatus): string {
  const texts: Record<OrderStatus, string> = {
    pending: '待处理',
    processing: '处理中',
    completed: '已完成',
    cancelled: '已取消',
  }
  return texts[status] || status
}

onMounted(fetchData)
</script>

<style scoped>
.sticky-filter {
  position: sticky;
  top: 0;
  z-index: 1;
}

.remark-cell {
  max-width: 180px;
}

.line-clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}
</style>
