<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>

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

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

    <!-- 订单详情弹窗 -->
    <OrderDetailDialog
      v-model="detailDialogVisible"
      :order-id="currentOrderId"
      @close="handleDetailClose"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Download } from '@element-plus/icons-vue'
import OrderListSearchForm from './components/OrderListSearchForm.vue'
import OrderListTable from './components/OrderListTable.vue'
import OrderDetailDialog from './components/OrderDetailDialog.vue'
import {
  getComprehensiveOrders,
  exportComprehensiveOrders,
  type ComprehensiveOrderListRequest,
  type OrderListResponse
} from '@/api/business/order'

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

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

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

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

// 获取订单列表
const fetchData = async () => {
  loading.value = true
  try {
    const res = await getComprehensiveOrders(queryParams)
    orderList.value = res.data.list
    total.value = res.data.total
  } catch (error) {
    console.error('获取综合订单列表失败:', error)
    ElMessage.error('获取综合订单列表失败')
  } finally {
    loading.value = false
  }
}

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

// 重置
const handleReset = () => {
  queryParams.userId = undefined
  queryParams.mobile = undefined
  queryParams.orderNum = undefined
  queryParams.startDate = undefined
  queryParams.endDate = undefined
  queryParams.status = undefined
  queryParams.accountType = undefined
  queryParams.accountStatus = 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: OrderListResponse) => {
  currentOrderId.value = row.id
  detailDialogVisible.value = true
}

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

// 导出
const handleExport = async () => {
  exportLoading.value = true
  try {
    const blob = await exportComprehensiveOrders({
      userId: queryParams.userId,
      mobile: queryParams.mobile,
      orderNum: queryParams.orderNum,
      startDate: queryParams.startDate,
      endDate: queryParams.endDate,
      status: queryParams.status,
      accountType: queryParams.accountType,
      accountStatus: queryParams.accountStatus
    })
    
    // 创建下载链接
    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;
}
</style>
