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

      <!-- 搜索表单 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="用户ID">
          <el-input v-model="searchForm.userId" placeholder="用户ID/UID" clearable @keyup.enter="handleSearch" style="width: 120px" />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="searchForm.mobile" placeholder="手机号" clearable @keyup.enter="handleSearch" style="width: 140px" />
        </el-form-item>
        <el-form-item label="回收时间">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item>
          <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-form-item>
      </el-form>

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

    <!-- 回收订单详情弹窗 -->
    <RecoveryDetailDialog
      v-model="detailDialogVisible"
      :recovery-data="currentRecoveryData"
      @close="handleDetailClose"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Download, Search, Refresh } from '@element-plus/icons-vue'
import RecoveryOrderTable from './components/RecoveryOrderTable.vue'
import RecoveryDetailDialog from './components/RecoveryDetailDialog.vue'
import {
  getRecoveryOrders,
  exportRecoveryOrders,
  type OrderListRequest,
  type RecoveryOrderResponse
} from '@/api/business/order'

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

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

// 搜索表单
const searchForm = reactive({
  userId: '',
  mobile: ''
})
const dateRange = ref<[string, string] | null>(null)

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

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

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

// 搜索
const handleSearch = () => {
  // 清除所有搜索参数
  queryParams.userId = undefined
  queryParams.mobile = undefined
  queryParams.startDate = undefined
  queryParams.endDate = undefined
  
  // 合并新的搜索参数
  if (searchForm.userId) {
    const parsedUserId = parseInt(searchForm.userId)
    if (!isNaN(parsedUserId)) {
      queryParams.userId = parsedUserId
    }
  }
  if (searchForm.mobile) {
    queryParams.mobile = searchForm.mobile
  }
  if (dateRange.value && dateRange.value.length === 2) {
    queryParams.startDate = dateRange.value[0]
    queryParams.endDate = dateRange.value[1]
  }
  
  queryParams.page = 1
  fetchData()
}

// 重置
const handleReset = () => {
  searchForm.userId = ''
  searchForm.mobile = ''
  dateRange.value = null
  queryParams.userId = undefined
  queryParams.mobile = undefined
  queryParams.startDate = undefined
  queryParams.endDate = 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: RecoveryOrderResponse) => {
  currentRecoveryData.value = row
  detailDialogVisible.value = true
}

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

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

.search-form {
  margin-bottom: 16px;
}
</style>
