<template>
  <div class="order-list-container">
    <!-- 搜索和筛选区域 -->
    <div class="filter-section">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input
            v-model="filters.orderNo"
            placeholder="出库单号"
            clearable
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-select
            v-model="filters.status"
            placeholder="状态"
            clearable
            @change="handleSearch"
          >
            <el-option label="全部" value="" />
            <el-option label="草稿" value="DRAFT" />
            <el-option label="出库中" value="EXECUTING" />
            <el-option label="已暂停" value="PAUSED" />
            <el-option label="已完成" value="COMPLETED" />
            <el-option label="已取消" value="CANCELED" />
          </el-select>
        </el-col>
        <el-col :span="8">
          <el-date-picker
            v-model="filters.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            @change="handleSearch"
          />
        </el-col>
        <el-col :span="6" class="action-buttons">
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 订单列表表格 -->
    <div class="table-section">
      <el-table
        :data="filteredOrders"
        stripe
        highlight-current-row
        @row-click="handleRowClick"
        v-loading="loading"
        height="calc(100vh - 220px)"
      >
        <el-table-column prop="orderNo" label="出库单号" width="180" fixed>
          <template #default="{ row }">
            <div class="order-no-cell">
              <span class="order-no">{{ row.orderNo }}</span>
              <el-tag
                :type="getStatusType(row.status)"
                size="small"
                effect="light"
              >
                {{ getStatusText(row.status) }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="warehouseName" label="仓库" width="120" />
        
        <el-table-column prop="operatorName" label="操作员" width="100" />
        
        <el-table-column label="状态进度" width="150">
          <template #default="{ row }">
            <div class="status-progress">
              <el-progress 
                v-if="row.completionRate !== undefined"
                :percentage="row.completionRate"
                :status="row.completionRate >= 100 ? 'success' : 'primary'"
                :stroke-width="8"
                :show-text="false"
              />
              <span v-else class="no-data">--</span>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="totalAmount" label="总金额" width="120" align="right">
          <template #default="{ row }">
            ¥{{ formatAmount(row.totalAmount) }}
          </template>
        </el-table-column>
        
        <el-table-column prop="createdAt" label="创建时间" width="160">
          <template #default="{ row }">
            {{ formatDateTime(row.createdAt) }}
          </template>
        </el-table-column>
        
        <el-table-column prop="confirmedAt" label="确认时间" width="160">
          <template #default="{ row }">
            {{ row.confirmedAt ? formatDateTime(row.confirmedAt) : '--' }}
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button 
                v-if="row.status === 'DRAFT'"
                type="primary" 
                size="small"
                @click.stop="handleEdit(row)"
              >
                <el-icon><Edit /></el-icon>
                编辑
              </el-button>
              
              <el-button 
                v-if="row.status === 'DRAFT' || row.status === 'EXECUTING' || row.status === 'PAUSED'"
                type="success" 
                size="small"
                @click.stop="handleStartOutbound(row)"
              >
                <!-- <el-icon><PlayCircle /></el-icon> -->
                {{ row.status === 'EXECUTING' ? '继续出库' : '开始出库' }}
              </el-button>
              
              <el-dropdown 
                v-if="row.status === 'DRAFT'"
                @command="(command) => handleCommand(command, row)"
                size="small"
              >
                <el-button type="warning" size="small">
                  更多<el-icon><ArrowDown /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="cancel">
                      <el-icon><Close /></el-icon>取消订单
                    </el-dropdown-item>
                    <el-dropdown-item command="delete" divided>
                      <el-icon><Delete /></el-icon>删除
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
              
              <el-button 
                v-if="row.status === 'COMPLETED'"
                type="info" 
                size="small"
                @click.stop="handleViewDetails(row)"
              >
                <el-icon><View /></el-icon>
                查看详情
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页器 -->
    <div class="pagination-section">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Search, 
  Refresh, 
  Edit, 
  ArrowDown, 
  Close, 
  Delete, 
  View 
} from '@element-plus/icons-vue'


const props = defineProps({
  orders: {
    type: Array,
    default: () => []
  }
})
const emit = defineEmits()

// 响应式数据
const filters = ref({
  orderNo: '',
  status: '',
  dateRange: []
})

const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

const loading = ref(false)

// 计算属性
const filteredOrders = computed(() => {
  let result = [...props.orders]
  
  // 按订单号过滤
  if (filters.value.orderNo) {
    result = result.filter(order => 
      order.orderNo.toLowerCase().includes(filters.value.orderNo.toLowerCase())
    )
  }
  
  // 按状态过滤
  if (filters.value.status) {
    result = result.filter(order => order.status === filters.value.status)
  }
  
  // 按日期范围过滤
  if (filters.value.dateRange?.length === 2) {
    const [start, end] = filters.value.dateRange
    const startDate = new Date(start)
    const endDate = new Date(end)
    endDate.setHours(23, 59, 59, 999)
    
    result = result.filter(order => {
      const createDate = new Date(order.createdAt)
      return createDate >= startDate && createDate <= endDate
    })
  }
  
  // 计算完成率（模拟数据）
  result.forEach(order => {
    if (order.status === 'COMPLETED') {
      order.completionRate = 100
    } else if (order.status === 'DRAFT') {
      order.completionRate = 0
    } else {
      // 模拟计算完成率
      order.completionRate = Math.floor(Math.random() * 60) + 20
    }
  })
  
  // 更新分页总数
  pagination.value.total = result.length
  
  // 分页处理
  const start = (pagination.value.currentPage - 1) * pagination.value.pageSize
  const end = start + pagination.value.pageSize
  return result.slice(start, end)
})

// 方法
const handleSearch = () => {
  pagination.value.currentPage = 1
  loading.value = true
  // 模拟搜索延迟
  setTimeout(() => {
    loading.value = false
  }, 500)
}

const handleReset = () => {
  filters.value = {
    orderNo: '',
    status: '',
    dateRange: []
  }
  pagination.value.currentPage = 1
  handleSearch()
}

const handleRowClick = (row) => {
  emit('select-order', row)
}

const handleEdit = (order) => {
  emit('edit-order', order)
}

const handleStartOutbound = (order) => {
  emit('start-outbound', order)
}

const handleViewDetails = (order) => {
  ElMessage.info(`查看订单详情: ${order.orderNo}`)
  // 实际项目中这里可以跳转到详情页或打开详情对话框
}

const handleCommand = async (command, order) => {
  switch (command) {
    case 'cancel':
      await handleCancelOrder(order)
      break
    case 'delete':
      await handleDeleteOrder(order)
      break
  }
}

const handleCancelOrder = async (order) => {
  try {
    await ElMessageBox.confirm(
      `确定要取消出库单 ${order.orderNo} 吗？`,
      '确认取消',
      { type: 'warning' }
    )
    ElMessage.success('订单已取消')
    // 实际项目中这里应该调用API更新状态
  } catch (error) {
    // 用户取消
  }
}

const handleDeleteOrder = async (order) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除出库单 ${order.orderNo} 吗？删除后无法恢复。`,
      '确认删除',
      { 
        type: 'error',
        confirmButtonText: '确定删除',
        cancelButtonText: '取消'
      }
    )
    emit('delete-order', order)
  } catch (error) {
    // 用户取消
  }
}

const handleSizeChange = (size) => {
  pagination.value.pageSize = size
}

const handleCurrentChange = (page) => {
  pagination.value.currentPage = page
}

const getStatusType = (status) => {
  const map= {
    'DRAFT': 'info',
    'EXECUTING': 'primary',
    'PAUSED': 'warning',
    'COMPLETED': 'success',
    'CANCELED': 'danger'
  }
  return map[status] || 'info'
}

const getStatusText = (status) => {
  const map= {
    'DRAFT': '草稿',
    'EXECUTING': '出库中',
    'PAUSED': '已暂停',
    'COMPLETED': '已完成',
    'CANCELED': '已取消'
  }
  return map[status] || status
}

const formatDateTime = (dateString) => {
  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 formatAmount = (amount) => {
  return amount.toLocaleString('zh-CN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  })
}
</script>

<style scoped>
.order-list-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: white;
  border-radius: 8px;
  padding: 20px;
}

.filter-section {
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
}

.action-buttons {
  display: flex;
  gap: 10px;
  justify-content: flex-end;
}

.table-section {
  flex: 1;
  overflow: hidden;
}

.order-no-cell {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.order-no {
  font-weight: 600;
  font-family: 'Monaco', 'Consolas', monospace;
}

.status-progress {
  width: 120px;
}

.no-data {
  color: #909399;
  font-style: italic;
}

.pagination-section {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-table__row) {
  cursor: pointer;
  transition: background-color 0.3s;
}

:deep(.el-table__row:hover) {
  background-color: #f5f7fa;
}

:deep(.el-table__row.current-row) {
  background-color: #ecf5ff !important;
  box-shadow: 0 0 0 1px #409eff inset;
}
</style>