<template>
    <div class="order-withdraw-page table_form-container">
        <!-- 搜索区域：按设计图保留订单号、开始时间、结束时间，并补一个导出按钮 -->
        <OrderWithdrawSearch :buttonLoading="loading" :search-form="searchForm" :search-options="searchOptions" @search="handleSearch"
            @reset="handleReset">
            <template #button>
                <el-button type="primary" @click="handleExport">
                    导出
                </el-button>
            </template>
        </OrderWithdrawSearch>

        <!-- 列表区域 -->
        <OrderWithdrawTable :table-data="pagedTableData" :columns="tableColumnsOptions" :highlight-current-row="false" :loading="loading" />

        <!-- 分页区域：保持和订单模块其他页面一致的交互结构 -->
        <OrderWithdrawPagination v-model="currentPage" v-model:pageSizeValue="pageSize" :total="total"
            @pagination-change="handlePaginationChange" />
    </div>
</template>

<script setup lang="ts">
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'

defineOptions({
  name: 'Withdraw'
})
import { computed, onMounted, ref } from 'vue'
import OrderWithdrawSearch from '@/components/common/Search.vue'
import OrderWithdrawTable from '@/components/common/Table.vue'
import OrderWithdrawPagination from '@/components/common/Pagination.vue'
import { exportToExcel } from '@/utils/exportToExcel'
import { usePageLoading } from '@/composables/useLoading'
import { search, tableColumns } from './options'
import { getWithdrawOrderList } from '@/api/modules/capital/withdraw'

// 提现订单数据结构（展示用）
interface WithdrawOrderListItem {
    id: number
    user_id: number
    order_no: string
    channel_id: number
    amount: string
    withdraw_fee: string
    status: number
    created_at: string
    updated_at: string
    user?: {
        username?: string
    }
    withdraw_currency?: {
        symbol?: string
    }
    real_currency?: {
        symbol?: string
    }
    channel?: {
        name?: string
    }
}

interface WithdrawOrderVo {
    id: number
    user_id: number
    order_no: string
    channel_id: number
    amount: string
    withdraw_fee: string
    status: number
    created_at: string
    updated_at: string
    // 映射嵌套字段到扁平化字段
    user_name: string
    withdraw_currency_symbol: string
    real_currency_symbol: string
    channel_name: string
}

// 搜索表单结构
interface SearchFormData {
    user_name: string
    startTime: string
    endTime: string
}

// 搜索项配置
const searchOptions = ref(search)

// 搜索表单
const createDefaultSearchForm = (): SearchFormData => ({
    user_name: '',
    startTime: dayjs().startOf('day').format('YYYY-MM-DD HH:mm:ss'),
    endTime: dayjs().endOf('day').format('YYYY-MM-DD HH:mm:ss'),
})

const searchForm = ref<SearchFormData>(createDefaultSearchForm())

// 列表数据
const tableData = ref<WithdrawOrderVo[]>([])

// 表格列配置
const tableColumnsOptions = ref(tableColumns)

// 分页状态
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 加载状态
const { loading, startLoading, stopLoading } = usePageLoading()

// 将接口数据映射为展示用数据
const mapToVo = (item: WithdrawOrderListItem): WithdrawOrderVo => {
    return {
        ...item,
        user_name: item.user?.username || '',
        withdraw_currency_symbol: item.withdraw_currency?.symbol || '',
        real_currency_symbol: item.real_currency?.symbol || '',
        channel_name: item.channel?.name || '',
        // 状态字段保持原值，表格列配置中的 options 会自动映射标签
    }
}

// 获取列表数据
const fetchList = async () => {
    startLoading()
    try {
        const data = await getWithdrawOrderList({
            page: currentPage.value,
            page_size: pageSize.value,
            start_time: searchForm.value.startTime || undefined,
            end_time: searchForm.value.endTime || undefined,
            user_name: searchForm.value.user_name || undefined,
        })
        tableData.value = ((data as any)?.data || []).map(mapToVo)
        // 如果接口返回总数有 total 字段，可以这里设置
        total.value = (data as any)?.total || tableData.value.length
        stopLoading()
    } catch (error) {
        stopLoading()
        console.error('获取提现订单列表失败', error)
        // ElMessage.error('获取提现订单列表失败')
    }
}

// 搜索
const handleSearch = () => {
    currentPage.value = 1
    fetchList()
}

// 重置
const handleReset = () => {
    searchForm.value = createDefaultSearchForm()
    currentPage.value = 1
    fetchList()
}

// 导出
const handleExport = async () => {
    await exportToExcel({
        tableData: tableData.value,
        columns: tableColumnsOptions.value,
        title: '导出提现订单',
        defaultFileNamePrefix: '提现订单',
    })
}

// 分页切换
const handlePaginationChange = (page: { currentPage: number; pageSize: number }) => {
    currentPage.value = page.currentPage
    pageSize.value = page.pageSize
    fetchList()
}

// 当前页数据
const pagedTableData = computed(() => {
    return tableData.value
})

// 页面加载时获取数据
onMounted(() => {
    fetchList()
})
</script>

<style scoped lang="scss">
.order-withdraw-page {
    // min-height: 100%;

    // 覆盖公共搜索组件的拉伸行为，让控件尺寸更接近设计图。
    :deep(.search-container .el-form) {
        display: flex;
        flex-wrap: wrap;
        align-items: center;
    }

    :deep(.search-container .el-form-item) {
        flex: 0 0 auto;
        margin-bottom: 8px;
    }

    :deep(.search-container .el-input),
    :deep(.search-container .el-select),
    :deep(.search-container .el-date-editor) {
        width: 100%;
    }

    :deep(.table-container) {
        height: calc(100vh - 220px);
    }
}
</style>

