<template>
  <div class="page-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>发货订单</span>
          <el-button type="primary" @click="handleExport" :loading="exportLoading">
            <el-icon><Download /></el-icon>导出
          </el-button>
        </div>
      </template>

      <!-- 搜索表单 -->
      <ShippingSearchForm @search="handleSearch" @reset="handleReset" />

      <!-- 统计信息 -->
      <div class="stats-bar" v-if="stats">
        <el-tag type="info" size="large">
          数据条数: <span class="stats-value">{{ stats.totalCount }}</span>
        </el-tag>
        <el-tag type="warning" size="large">
          全部价值: <span class="stats-value">¥{{ stats.totalValue?.toFixed(2) || '0.00' }}</span>
        </el-tag>
        <el-tag type="success" size="large">
          本页总发货价值: <span class="stats-value">¥{{ stats.pageValue?.toFixed(2) || '0.00' }}</span>
        </el-tag>
      </div>

      <!-- 订单表格 -->
      <ShippingOrderTable
        :data="orderList"
        :loading="loading"
        :total="total"
        :page="queryParams.page"
        :page-size="queryParams.pageSize"
        @page-change="handlePageChange"
        @size-change="handleSizeChange"
        @view-detail="handleViewDetail"
        @cancel-ship="handleCancelShip"
      />
    </el-card>

    <!-- 发货订单详情弹窗 -->
    <ShippingDetailDialog
      v-model="detailDialogVisible"
      :send-id="currentSendId"
      @close="handleDetailClose"
      @shipped="handleShipped"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Download } from '@element-plus/icons-vue'
import ShippingSearchForm from './components/ShippingSearchForm.vue'
import ShippingOrderTable from './components/ShippingOrderTable.vue'
import ShippingDetailDialog from './components/ShippingDetailDialog.vue'
import {
  getShippingOrders,
  getShippingStats,
  exportShippingOrders,
  cancelShippingOrder,
  type ShippingOrderListRequest,
  type ShippingOrderResponse,
  type ShippingStatsResponse
} from '@/api/business/order'

// 列表数据
const loading = ref(false)
const orderList = ref<ShippingOrderResponse[]>([])
const total = ref(0)

// 统计数据
const stats = ref<ShippingStatsResponse | null>(null)

// 导出状态
const exportLoading = ref(false)

// 查询参数
const queryParams = reactive<ShippingOrderListRequest>({
  page: 1,
  pageSize: 20
})

// 详情弹窗
const detailDialogVisible = ref(false)
const currentSendId = ref<number | null>(null)

// 获取发货订单列表
const fetchData = async () => {
  loading.value = true
  try {
    const [listRes, statsRes] = await Promise.all([
      getShippingOrders(queryParams),
      getShippingStats(queryParams)
    ])
    orderList.value = listRes.data.list
    total.value = listRes.data.total
    stats.value = statsRes.data
  } catch (error) {
    console.error('获取发货订单列表失败:', error)
    ElMessage.error('获取发货订单列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = (params: Partial<ShippingOrderListRequest>) => {
  // 清除所有搜索参数
  queryParams.userId = undefined
  queryParams.mobile = undefined
  queryParams.sendNum = undefined
  queryParams.startDate = undefined
  queryParams.endDate = undefined
  queryParams.status = undefined
  // 合并新的搜索参数
  Object.assign(queryParams, params)
  queryParams.page = 1
  fetchData()
}

// 重置
const handleReset = () => {
  queryParams.userId = undefined
  queryParams.mobile = undefined
  queryParams.sendNum = undefined
  queryParams.startDate = undefined
  queryParams.endDate = undefined
  queryParams.status = undefined
  queryParams.page = 1
  fetchData()
}

// 分页
const handlePageChange = (page: number) => {
  queryParams.page = page
  fetchData()
}

const handleSizeChange = (size: number) => {
  queryParams.pageSize = size
  queryParams.page = 1
  fetchData()
}

// 查看详情
const handleViewDetail = (row: ShippingOrderResponse) => {
  currentSendId.value = row.id
  detailDialogVisible.value = true
}

// 关闭详情弹窗
const handleDetailClose = () => {
  currentSendId.value = null
}

// 发货成功回调
const handleShipped = () => {
  fetchData()
}

// 取消发货
const handleCancelShip = async (row: ShippingOrderResponse) => {
  try {
    await ElMessageBox.confirm(
      '确定要取消发货吗？取消后奖品将返回用户盒柜',
      '取消发货确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await cancelShippingOrder(row.id)
    ElMessage.success('取消发货成功')
    fetchData()
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('取消发货失败:', error)
      ElMessage.error('取消发货失败')
    }
  }
}

// 导出
const handleExport = async () => {
  exportLoading.value = true
  try {
    const blob = await exportShippingOrders({
      userId: queryParams.userId,
      mobile: queryParams.mobile,
      sendNum: queryParams.sendNum,
      startDate: queryParams.startDate,
      endDate: queryParams.endDate,
      status: queryParams.status
    })
    
    // 创建下载链接
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `发货订单_${new Date().toISOString().slice(0, 10)}.csv`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  } finally {
    exportLoading.value = false
  }
}

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

<style scoped>
.page-container {
  padding: 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.stats-bar {
  display: flex;
  gap: 16px;
  margin-bottom: 16px;
  padding: 12px;
  background: #f5f7fa;
  border-radius: 4px;
}

.stats-value {
  font-weight: 600;
  margin-left: 4px;
}
</style>
