<script setup>
import SearchField from '@/components/SearchField.vue';
import SearchPanel from '@/components/SearchPanel.vue';
import { FinanceService } from '@/service/FinanceService';
import { useToast } from 'primevue/usetoast';
import { ref } from 'vue';

const toast = useToast();

const withdrawals = ref([]);
const loading = ref(false);

const totalRecords = ref(0);
const page = ref(1);
const rows = ref(10);

const orderID = ref(null);
const tenantID = ref(null);
const tenantCode = ref('');
const tenantName = ref('');
const userID = ref(null);
const username = ref('');
const status = ref('');
const createdAtFrom = ref(null);
const createdAtTo = ref(null);
const paidAtFrom = ref(null);
const paidAtTo = ref(null);
const amountPaidMin = ref(null);
const amountPaidMax = ref(null);
const sortField = ref('id');
const sortOrder = ref(-1);

const statusOptions = [
    { label: '全部', value: '' },
    { label: 'created', value: 'created' },
    { label: 'paid', value: 'paid' },
    { label: 'failed', value: 'failed' }
];

const approveDialogVisible = ref(false);
const approveLoading = ref(false);
const approveOrder = ref(null);

const rejectDialogVisible = ref(false);
const rejectLoading = ref(false);
const rejectOrder = ref(null);
const rejectReason = ref('');

function formatDate(value) {
    if (!value) return '-';
    if (String(value).startsWith('0001-01-01')) return '-';
    const date = new Date(value);
    if (Number.isNaN(date.getTime())) return String(value);
    return date.toLocaleString();
}

function formatCny(amountInCents) {
    const amount = Number(amountInCents) / 100;
    if (!Number.isFinite(amount)) return '-';
    return new Intl.NumberFormat('zh-CN', { style: 'currency', currency: 'CNY' }).format(amount);
}

function getStatusSeverity(value) {
    switch (value) {
        case 'paid':
            return 'success';
        case 'created':
            return 'warn';
        case 'failed':
            return 'danger';
        default:
            return 'secondary';
    }
}

async function loadWithdrawals() {
    loading.value = true;
    try {
        const result = await FinanceService.listWithdrawals({
            page: page.value,
            limit: rows.value,
            id: orderID.value || undefined,
            tenant_id: tenantID.value || undefined,
            tenant_code: tenantCode.value,
            tenant_name: tenantName.value,
            user_id: userID.value || undefined,
            username: username.value,
            status: status.value,
            created_at_from: createdAtFrom.value || undefined,
            created_at_to: createdAtTo.value || undefined,
            paid_at_from: paidAtFrom.value || undefined,
            paid_at_to: paidAtTo.value || undefined,
            amount_paid_min: amountPaidMin.value || undefined,
            amount_paid_max: amountPaidMax.value || undefined,
            sortField: sortField.value,
            sortOrder: sortOrder.value
        });
        withdrawals.value = result.items;
        totalRecords.value = result.total;
    } catch (error) {
        toast.add({ severity: 'error', summary: '加载失败', detail: error?.message || '无法加载提现列表', life: 4000 });
    } finally {
        loading.value = false;
    }
}

function onSearch() {
    page.value = 1;
    loadWithdrawals();
}

function onReset() {
    orderID.value = null;
    tenantID.value = null;
    tenantCode.value = '';
    tenantName.value = '';
    userID.value = null;
    username.value = '';
    status.value = '';
    createdAtFrom.value = null;
    createdAtTo.value = null;
    paidAtFrom.value = null;
    paidAtTo.value = null;
    amountPaidMin.value = null;
    amountPaidMax.value = null;
    sortField.value = 'id';
    sortOrder.value = -1;
    page.value = 1;
    rows.value = 10;
    loadWithdrawals();
}

function onPage(event) {
    page.value = (event.page ?? 0) + 1;
    rows.value = event.rows ?? rows.value;
    loadWithdrawals();
}

function onSort(event) {
    sortField.value = event.sortField ?? sortField.value;
    sortOrder.value = event.sortOrder ?? sortOrder.value;
    loadWithdrawals();
}

function openApproveDialog(order) {
    approveOrder.value = order;
    approveDialogVisible.value = true;
}

async function confirmApprove() {
    const id = approveOrder.value?.id;
    if (!id) return;
    approveLoading.value = true;
    try {
        await FinanceService.approveWithdrawal(id);
        toast.add({ severity: 'success', summary: '已批准', detail: `订单ID: ${id}`, life: 3000 });
        approveDialogVisible.value = false;
        await loadWithdrawals();
    } catch (error) {
        toast.add({ severity: 'error', summary: '操作失败', detail: error?.message || '无法批准提现', life: 4000 });
    } finally {
        approveLoading.value = false;
    }
}

function openRejectDialog(order) {
    rejectOrder.value = order;
    rejectReason.value = '';
    rejectDialogVisible.value = true;
}

async function confirmReject() {
    const id = rejectOrder.value?.id;
    if (!id || !rejectReason.value.trim()) return;
    rejectLoading.value = true;
    try {
        await FinanceService.rejectWithdrawal(id, { reason: rejectReason.value.trim() });
        toast.add({ severity: 'success', summary: '已驳回', detail: `订单ID: ${id}`, life: 3000 });
        rejectDialogVisible.value = false;
        await loadWithdrawals();
    } catch (error) {
        toast.add({ severity: 'error', summary: '操作失败', detail: error?.message || '无法驳回提现', life: 4000 });
    } finally {
        rejectLoading.value = false;
    }
}

loadWithdrawals();
</script>

<template>
    <div class="card">
        <div class="flex items-center justify-between mb-4">
            <h4 class="m-0">提现审核</h4>
        </div>

        <SearchPanel :loading="loading" @search="onSearch" @reset="onReset">
            <SearchField label="OrderID">
                <InputNumber v-model="orderID" :min="1" placeholder="精确匹配" class="w-full" />
            </SearchField>
            <SearchField label="TenantID">
                <InputNumber v-model="tenantID" :min="1" placeholder="精确匹配" class="w-full" />
            </SearchField>
            <SearchField label="Tenant Code">
                <InputText v-model="tenantCode" placeholder="模糊匹配" class="w-full" @keyup.enter="onSearch" />
            </SearchField>
            <SearchField label="Tenant Name">
                <InputText v-model="tenantName" placeholder="模糊匹配" class="w-full" @keyup.enter="onSearch" />
            </SearchField>
            <SearchField label="UserID">
                <InputNumber v-model="userID" :min="1" placeholder="精确匹配" class="w-full" />
            </SearchField>
            <SearchField label="用户名">
                <IconField>
                    <InputIcon>
                        <i class="pi pi-search" />
                    </InputIcon>
                    <InputText v-model="username" placeholder="模糊匹配" class="w-full" @keyup.enter="onSearch" />
                </IconField>
            </SearchField>
            <SearchField label="状态">
                <Select v-model="status" :options="statusOptions" optionLabel="label" optionValue="value" placeholder="请选择" class="w-full" />
            </SearchField>
            <SearchField label="创建时间 From">
                <DatePicker v-model="createdAtFrom" showIcon showButtonBar placeholder="开始时间" class="w-full" />
            </SearchField>
            <SearchField label="创建时间 To">
                <DatePicker v-model="createdAtTo" showIcon showButtonBar placeholder="结束时间" class="w-full" />
            </SearchField>
            <SearchField label="支付时间 From">
                <DatePicker v-model="paidAtFrom" showIcon showButtonBar placeholder="开始时间" class="w-full" />
            </SearchField>
            <SearchField label="支付时间 To">
                <DatePicker v-model="paidAtTo" showIcon showButtonBar placeholder="结束时间" class="w-full" />
            </SearchField>
            <SearchField label="金额 Min">
                <InputNumber v-model="amountPaidMin" :min="0" placeholder=">= 0" class="w-full" />
            </SearchField>
            <SearchField label="金额 Max">
                <InputNumber v-model="amountPaidMax" :min="0" placeholder=">= 0" class="w-full" />
            </SearchField>
        </SearchPanel>

        <DataTable
            :value="withdrawals"
            dataKey="id"
            :loading="loading"
            lazy
            :paginator="true"
            :rows="rows"
            :totalRecords="totalRecords"
            :first="(page - 1) * rows"
            :rowsPerPageOptions="[10, 20, 50, 100]"
            sortMode="single"
            :sortField="sortField"
            :sortOrder="sortOrder"
            @page="onPage"
            @sort="onSort"
            currentPageReportTemplate="显示第 {first} - {last} 条，共 {totalRecords} 条"
            paginatorTemplate="FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink CurrentPageReport RowsPerPageDropdown"
            scrollable
            scrollHeight="flex"
            responsiveLayout="scroll"
        >
            <Column field="id" header="订单ID" sortable style="min-width: 7rem" />
            <Column header="租户" style="min-width: 16rem">
                <template #body="{ data }">
                    <div class="flex flex-col">
                        <span class="font-medium">{{ data.tenant?.name || '-' }}</span>
                        <span class="text-xs text-muted-color">Code: {{ data.tenant?.code || '-' }}</span>
                    </div>
                </template>
            </Column>
            <Column header="申请人" style="min-width: 12rem">
                <template #body="{ data }">
                    <span v-if="data.buyer?.username">{{ data.buyer.username }}</span>
                    <span v-else class="text-muted-color">{{ data.buyer?.id ?? '-' }}</span>
                </template>
            </Column>
            <Column field="amount_paid" header="金额" sortable style="min-width: 10rem">
                <template #body="{ data }">
                    {{ formatCny(data.amount_paid) }}
                </template>
            </Column>
            <Column field="status" header="状态" style="min-width: 10rem">
                <template #body="{ data }">
                    <Tag :value="data.status_description || data.status || '-'" :severity="getStatusSeverity(data.status)" />
                </template>
            </Column>
            <Column field="created_at" header="创建时间" sortable style="min-width: 14rem">
                <template #body="{ data }">
                    {{ formatDate(data.created_at) }}
                </template>
            </Column>
            <Column field="paid_at" header="支付时间" sortable style="min-width: 14rem">
                <template #body="{ data }">
                    {{ formatDate(data.paid_at) }}
                </template>
            </Column>
            <Column header="操作" style="min-width: 12rem">
                <template #body="{ data }">
                    <div class="flex items-center gap-2">
                        <Button label="通过" icon="pi pi-check" size="small" severity="success" :disabled="data.status !== 'created'" @click="openApproveDialog(data)" />
                        <Button label="驳回" icon="pi pi-times" size="small" severity="danger" :disabled="data.status !== 'created'" @click="openRejectDialog(data)" />
                    </div>
                </template>
            </Column>
        </DataTable>
    </div>

    <Dialog v-model:visible="approveDialogVisible" :modal="true" :style="{ width: '420px' }">
        <template #header>
            <div class="flex items-center gap-2">
                <span class="font-medium">确认通过提现吗？</span>
            </div>
        </template>
        <div class="text-sm text-muted-color">确认后将标记为已支付，请确保外部打款已完成。</div>
        <template #footer>
            <Button label="取消" icon="pi pi-times" text @click="approveDialogVisible = false" :disabled="approveLoading" />
            <Button label="确认通过" icon="pi pi-check" severity="success" @click="confirmApprove" :loading="approveLoading" />
        </template>
    </Dialog>

    <Dialog v-model:visible="rejectDialogVisible" :modal="true" :style="{ width: '520px' }">
        <template #header>
            <div class="flex items-center gap-2">
                <span class="font-medium">驳回提现申请</span>
            </div>
        </template>
        <div class="flex flex-col gap-4">
            <div>
                <label class="block font-medium mb-2">驳回原因</label>
                <InputText v-model="rejectReason" placeholder="请输入驳回原因" class="w-full" />
            </div>
        </div>
        <template #footer>
            <Button label="取消" icon="pi pi-times" text @click="rejectDialogVisible = false" :disabled="rejectLoading" />
            <Button label="确认驳回" icon="pi pi-check" severity="danger" @click="confirmReject" :loading="rejectLoading" :disabled="!rejectReason.trim()" />
        </template>
    </Dialog>
</template>
