<template>
    <div class="withdraw-check table_form-container">
        <!-- 搜索区域：复用项目内搜索组件 -->
        <WithdrawSearch :search-form="searchForm" :search-options="searchOptions" @search="handleSearch" @reset="handleReset">
            <template #button>
                <el-button type="success" :loading="approveLoading" @click="handleApprove">通过</el-button>
                <el-button type="danger" plain :loading="rejectLoading" @click="handleReject">驳回</el-button>
            </template>
        </WithdrawSearch>

        <!-- 列表区域：使用公共 Table 组件 -->
        <Table
            ref="tableRef"
            :table-data="tableData"
            :columns="tableColumns"
            row-key="id"
            :loading="loading"
            :show-selection="true"
            @selection-change="handleSelectionChange"
        />

        <!-- 分页区域：复用项目内分页组件 -->
        <WithdrawPagination v-model="currentPage" v-model:pageSizeValue="pageSize" :total="total"
            @pagination-change="handlePaginationChange" />
    </div>
</template>

<script lang="ts" setup>

defineOptions({
  name: 'WithdrawCheck'
})
import { ElMessage, ElMessageBox } from 'element-plus'
import { computed, onMounted, ref } from 'vue'
import dayjs from 'dayjs'
import WithdrawSearch from '@/components/common/Search.vue'
import Table from '@/components/common/Table.vue'
import { usePageLoading } from '@/composables/useLoading'
import WithdrawPagination from '@/components/common/Pagination.vue'
import { withdrawCheckSearch, withdrawCheckTableColumns } from './options'
import { getWithdrawReviewList, withdrawReviewOrder } from '@/api/modules/capital/withdraw'

// 表格单行数据结构
interface TableRow {
    id: number
    trade_id: string
    return_trade_id: string | null
    user_id: number
    withdraw_currency: {
        id: number
        symbol: string
    }
    withdraw_amount: string
    real_currency: {
        id: number
        symbol: string
    }
    real_amount: string
    rate: string
    status: number
    channel_id: number
    withdraw_fee_handle: string
    withdraw_point_diff: string
    withdraw_service_fee: string
    withdraw_head_fee: string
    withdraw_risk_fee: string
    withdraw_address: string
    beneficiary_name: string | null
    beneficiary_bank_name: string | null
    swift_bic_code: string | null
    beneficiary_bank_address: string | null
    beneficiary_bank_account: string | null
    created_at: string
    updated_at: string
    deleted_at: string | null
    user: {
        id: number
        username: string
    }
    channel: {
        id: number
        name: string
    }
}

// 转换后的表格数据
interface TransformedTableRow {
    id: number
    trade_id: string
    user_name: string
    withdraw_currency_symbol: string
    withdraw_amount: string
    real_currency_symbol: string
    real_amount: string
    rate: string
    channel_name: string
    withdraw_service_fee: string
    withdraw_head_fee: string
    withdraw_fee_handle: string
    withdraw_point_diff: string
    withdraw_risk_fee: string
    withdraw_address: string
    created_at: string
}

// 搜索配置和表格配置
const searchOptions = ref(withdrawCheckSearch)
const searchForm = ref({
    user_name: '',
    timeRange: [] as string[]
})

const { loading, startLoading, stopLoading } = usePageLoading()
// 表格、勾选状态和 loading 状态
const tableColumns = computed(() => withdrawCheckTableColumns)
const tableData = ref<TransformedTableRow[]>([])
const selectedRows = ref<TableRow[]>([])

// 审核操作 loading 状态
const approveLoading = ref(false)
const rejectLoading = ref(false)

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

// 获取默认时间范围（一周）
const getDefaultTimeRange = () => {
    const end = dayjs()
    const start = end.subtract(7, 'day')
    return [start.format('YYYY-MM-DD HH:mm:ss'), end.format('YYYY-MM-DD HH:mm:ss')]
}

// 初始化时间范围
searchForm.value.timeRange = getDefaultTimeRange()

// 转换接口数据为表格数据
const transformTableData = (data: TableRow[]): TransformedTableRow[] => {
    return data.map(item => ({
        id: item.id,
        trade_id: item.trade_id,
        user_name: item.user?.username || '-',
        withdraw_currency_symbol: item.withdraw_currency?.symbol || '-',
        withdraw_amount: item.withdraw_amount,
        real_currency_symbol: item.real_currency?.symbol || '-',
        real_amount: item.real_amount,
        rate: item.rate,
        channel_name: item.channel?.name || '-',
        withdraw_service_fee: item.withdraw_service_fee,
        withdraw_head_fee: item.withdraw_head_fee,
        withdraw_fee_handle: item.withdraw_fee_handle,
        withdraw_point_diff: item.withdraw_point_diff,
        withdraw_risk_fee: item.withdraw_risk_fee,
        withdraw_address: item.withdraw_address,
        created_at: item.created_at
    }))
}

// 列表响应数据结构
interface ListResponse {
    data: TableRow[]
    total: number
}

// 获取列表数据
const getList = async () => {
    startLoading()
    selectedRows.value = []
    
    const [start_time, end_time] = searchForm.value.timeRange || []
    
    try {
        const res = await getWithdrawReviewList({
            page: currentPage.value,
            page_size: pageSize.value,
            start_time: start_time || undefined,
            end_time: end_time || undefined,
            user_name: searchForm.value.user_name || undefined
        }) as unknown as ListResponse
        
        tableData.value = transformTableData(res.data || [])
        total.value = res.total || 0
    } catch (error) {
        console.error('获取提现审核列表失败:', error)
        ElMessage.error('获取列表失败')
    } finally {
        stopLoading()
    }
}

// 页面初始化时加载一次列表
onMounted(() => {
    getList()
})

// 搜索：回到第一页再重新筛选
const handleSearch = () => {
    currentPage.value = 1
    getList()
}

// 重置：恢复默认搜索条件
const handleReset = () => {
    searchForm.value = {
        user_name: '',
        timeRange: getDefaultTimeRange()
    }
    currentPage.value = 1
    getList()
}

// 表格勾选变化
const handleSelectionChange = (rows: TableRow[]) => {
    // 根据选中行的 id 找到原始数据
    selectedRows.value = rows
}

// 审核通过
const handleApprove = async () => {
    if (!selectedRows.value.length) {
        ElMessage.warning('请先选择要通过的记录')
        return
    }
    
    try {
        await ElMessageBox.confirm(
            `确定要通过 ${selectedRows.value.length} 条提现记录吗？`,
            '审核确认',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        )
        
        approveLoading.value = true
        
        for (const row of selectedRows.value) {
            await withdrawReviewOrder({
                id: row.id,
                status: 2
            })
        }
        
        ElMessage.success('审核通过成功')
        getList()
    } catch (error: any) {
        if (error !== 'cancel') {
            ElMessage.error(error.message || '审核通过失败')
        }
    } finally {
        approveLoading.value = false
    }
}

// 审核驳回
const handleReject = async () => {
    if (!selectedRows.value.length) {
        ElMessage.warning('请先选择要驳回的记录')
        return
    }
    
    try {
        await ElMessageBox.confirm(
            `确定要驳回 ${selectedRows.value.length} 条提现记录吗？`,
            '审核确认',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        )
        
        rejectLoading.value = true
        
        for (const row of selectedRows.value) {
            await withdrawReviewOrder({
                id: row.id,
                status: 4
            })
        }
        
        ElMessage.success('审核驳回成功')
        getList()
    } catch (error: any) {
        if (error !== 'cancel') {
            ElMessage.error(error.message || '审核驳回失败')
        }
    } finally {
        rejectLoading.value = false
    }
}

// 导出
const handleExport = () => {
    ElMessage.info('导出功能开发中')
}

// 分页变化
const handlePaginationChange = (page: { currentPage: number; pageSize: number }) => {
    currentPage.value = page.currentPage
    pageSize.value = page.pageSize
    getList()
}
</script>

<style scoped lang="scss">
.withdraw-check { 

    // 覆盖公共搜索组件默认的弹性拉伸，让当前页搜索项宽度按配置展示
    :deep(.search-container .el-form) {
        flex-wrap: wrap;
        align-items: center;
    }

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

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

    // 表格容器高度预留给顶部搜索区和底部分页
    .table-wrapper {
        height: calc(100vh - 210px);
        background: #fff;
        border-radius: 6px;
        overflow: hidden;
    }
}
</style>
