<template>
    <cwg-load-more-wrapper ref="loadMoreWrapperRef" :loading="loading" :finished="finished" :height='54'
        :refresher-enabled="true" @reach-bottom="loadMore" @refresh="handleRefresh">
        <view v-if="records.length > 0" class="records-list">
            <view v-for="record in records" :key="record.id" class="record-card" @click="goToDeductionDetail(record)">
                <view class="record-main">
                    <view class="record-left">
                        <view class="type-icon deduction-icon">
                            <cwg-icon class="icons" :name="getDeductionIcon(record.type || record.typeStr)" :size="20"
                                color="#ef4444" />
                        </view>
                    </view>

                    <view class="record-right">
                        <view class="record-info">
                            <view class="info-header">
                                <text class="record-type">{{ Math.abs(Number(record.amount || 0)) }}
                                    {{ record.currency || 'USD' }}</text>
                                <text class="record-detail"><cwg-icon name="icon_transfer" :size="18"
                                        color="#000" /></text>
                                <text class="record-type">{{ Math.abs(Number(record.receivedAmount || 0)) }}
                                    {{ record.receivedCurrency }}</text>
                                <view :class="['status-badge', getStatusBadgeClass(record.transactionStatus)]">
                                    <cwg-icon class="icons" :name="getStatusIcon(record.transactionStatus)" :size="12"
                                        :color="getStatusColor(record.transactionStatus)" />
                                    <text :class="['status-text', getStatusTextClass(record.transactionStatus)]">
                                        {{ getStatusText(record.transactionStatus) }}
                                    </text>
                                </view>
                            </view>
                        </view>
                    </view>
                </view>

                <view class="record-footer">
                    <text class="footer-time">{{ formatDateTime(record.addTime || record.time) }}</text>
                    <view class="footer-actions">
                        <text class="footer-order">
                            {{ t('DepositAddress.p2') }}: {{ formatOrderNo(record.address) }}
                        </text>
                        <cwg-icon class="footer-order-icon" name="copy" :size="14" color="#9ca3af"
                            @click.stop="copyOrderNo(record.address)" />
                    </view>
                </view>
            </view>
        </view>
        <cwg-empty-state v-else />
    </cwg-load-more-wrapper>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue';
import dayjs from 'dayjs';
import { useI18n } from 'vue-i18n';
import { showToast } from '@/utils/toast';
import { ucardApi, TransactionInfo } from '@/api/ucard';
import useRouter from "@/hooks/useRouter";
const router = useRouter();
import { withdrawStatus } from '@/utils/dataMap';
import useCardStore from '@/stores/use-card-store';

interface RecordItem extends TransactionInfo {
    type?: string | number;
    typeStr?: string;
    remark?: string;
    status?: string | number;
    addTime?: string | number;
    fee?: number;
    currency?: string;
    merchantOrderNo?: string;
    reason?: string;
    time?: string | number;
}

type NormalizedStatus = 'success' | 'wait_process' | 'fail';

const props = defineProps<{
    cardNo: string;
    typeIndex: number;
    statusIndex: number;
    dateFilter: string;
    typeOptions: string[];
    payoutCurrency: string;
}>();

const { t } = useI18n();

const records = ref<RecordItem[]>([]);
const page = ref(1);
const pageSize = 10;
const loading = ref(false);
const finished = ref(false);

const cardStore = useCardStore();
const normalizeStatus = (status?: string | number): NormalizedStatus => {
    if (!status) return 'wait_process';
    if (status == 4 || status == 5) return 'fail';
    if (status == 3) return 'success';
    return 'wait_process';
};

const getStatusText = (status?: string | number): string => {
    return t(withdrawStatus[status]);
};

const getStatusIcon = (status?: string | number): string => {
    const normalized = normalizeStatus(status);
    if (normalized === 'success') return 'checkmarkempty1';
    if (normalized === 'wait_process') return 'info1';
    return 'closeempty1';
};

const getStatusColor = (status?: string | number): string => {
    const normalized = normalizeStatus(status);
    if (normalized === 'success') return '#22c55e';
    if (normalized === 'wait_process') return '#eab308';
    return '#ef4444';
};

const getStatusBadgeClass = (status?: string | number) => `status-${normalizeStatus(status)}`;
const getStatusTextClass = (status?: string | number) => `status-text-${normalizeStatus(status)}`;

const getStatusValue = (index: number): NormalizedStatus | null => {
    if (index === 0) return null;
    const statusMap: NormalizedStatus[] = ['success', 'wait_process', 'fail'];
    return statusMap[index - 1];
};

const getDeductionIcon = (type?: string | number): string => {
    const typeStr = String(type || '');
    if (typeStr.includes('服务费') || typeStr === '1') return 'servicefee';
    if (typeStr.includes('手续费') || typeStr === '2') return 'handlingfee';
    return 'handlingfee';
};

const formatDateTime = (time?: string | number): string => {
    if (!time) return '--';
    try {
        let date: dayjs.Dayjs;
        if (typeof time === 'number') {
            if (time.toString().length === 10) {
                date = dayjs.unix(time);
            } else {
                date = dayjs(time);
            }
        } else {
            date = dayjs(time);
        }
        if (!date.isValid()) return '--';
        return date.format('YYYY-MM-DD HH:mm:ss');
    } catch (error) {
        return '--';
    }
};

const getDatePart = (time?: string | number): string => {
    if (!time) return '';
    try {
        let date: dayjs.Dayjs;
        if (typeof time === 'number') {
            if (time.toString().length === 10) {
                date = dayjs.unix(time);
            } else {
                date = dayjs(time);
            }
        } else {
            date = dayjs(time);
        }
        if (!date.isValid()) return '';
        return date.format('YYYY-MM-DD');
    } catch (error) {
        return '';
    }
};

const formatOrderNo = (orderNo?: string) => {
    if (!orderNo) return '--';
    if (orderNo.length <= 16) return orderNo;
    return orderNo.slice(0, 6) + '...' + orderNo.slice(-4);
};

const copyOrderNo = (orderNo?: string) => {
    if (!orderNo) return;
    uni.setClipboardData({
        data: orderNo,
        success: () => {
            uni.showToast({
                title: t('card.Msg.m8') || '复制成功',
                icon: 'success'
            });
        }
    });
};

const fetchRecords = async (isLoadMore = false) => {
    if (isLoadMore && finished.value) return;
    loading.value = true;
    try {
        const res = await ucardApi.getBlockchainWithdrawPage({
            cardNo: props.cardNo,
            payoutCurrency: props.payoutCurrency,
            transactionStatus: props.statusIndex == 0 ? undefined : props.statusIndex,
            startDate: props.dateFilter ? dayjs(props.dateFilter).format('YYYY-MM-DD') : undefined,
            endDate: props.dateFilter ? dayjs(props.dateFilter).format('YYYY-MM-DD') : undefined,
            page: { current: page.value, row: pageSize },
        });
        const data = res.code === 200 && Array.isArray(res.data) ? res.data : [];

        if (isLoadMore) {
            records.value.push(...data);
        } else {
            records.value = data;
        }
        if (data.length < pageSize) {
            finished.value = true;
        } else {
            finished.value = false;
        }
    } catch (error: any) {
        if (!isLoadMore) {
            records.value = [];
        }
        showToast(error?.message || String(error));
    } finally {
        loading.value = false;
    }
};

const goToDeductionDetail = (record: RecordItem) => {
    cardStore.saveOrderDetail(record);
    router.push({
        path: '/pages/wallet/withdraw-detail',
        query: { id: record.id }
    });
};

const loadMore = () => {
    if (finished.value || loading.value) return;
    page.value++;
    fetchRecords(true);
};

watch([() => props.dateFilter], () => {
    page.value = 1;
    finished.value = false;
    fetchRecords();
}, { immediate: false });
watch([() => props.payoutCurrency], () => {
    page.value = 1;
    finished.value = false;
    fetchRecords();
}, { immediate: false });
watch([() => props.statusIndex], () => {
    page.value = 1;
    finished.value = false;
    fetchRecords();
}, { immediate: false });

const loadMoreWrapperRef = ref<any>(null);

const refresh = async () => {
    page.value = 1;
    finished.value = false;
    await fetchRecords();
};

const handleRefresh = async () => {
    await refresh();
    // 停止下拉刷新动画
    if (loadMoreWrapperRef.value) {
        loadMoreWrapperRef.value.stopRefresh();
    }
};

onMounted(() => {
    fetchRecords();
});

defineExpose({
    refresh
});
</script>

<style scoped lang="scss">
@import "@/uni.scss";

.records-list {
    display: flex;
    flex-direction: column;
    gap: px2rpx(12);
    padding: px2rpx(16);
}

.record-card {
    background-color: #ffffff;
    border-radius: px2rpx(12);
    border: 1px solid #e5e7eb;
    overflow: hidden;
    transition: box-shadow 0.3s;
    padding: px2rpx(16);
    position: relative;
}

.record-card:active {
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.record-main {
    display: flex;
    align-items: flex-start;
    justify-content: space-between;
    padding-bottom: px2rpx(16);
}

.record-left {
    display: flex;
    align-items: flex-start;
    gap: px2rpx(12);
    min-width: 0;
}

.type-icon {
    width: px2rpx(40);
    height: px2rpx(40);
    border-radius: px2rpx(10);
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
}

.deduction-icon {
    background-color: #fef2f2;
}

.icons {
    width: px2rpx(20);
    height: px2rpx(20);
}

.record-info {
    flex: 1;
    min-width: 0;
    display: flex;
    flex-direction: column;
    gap: px2rpx(6);
}

.info-header {
    display: flex;
    align-items: center;
    gap: px2rpx(4);
    flex-wrap: wrap;
}

.record-type {
    font-size: px2rpx(15);
    color: #111827;
}

.status-badge {
    display: flex;
    align-items: center;
    gap: px2rpx(4);
    padding: px2rpx(3) px2rpx(8) px2rpx(3) px2rpx(3);
    border-radius: px2rpx(12);
    position: absolute;
    top: px2rpx(1);
    right: px2rpx(1);
}

.status-success {
    background-color: #f0fdf4;
}

.status-wait_process {
    background-color: #fefce8;
}

.status-fail {
    background-color: #fef2f2;
}

.status-text {
    font-size: px2rpx(11);
}

.status-text-success {
    color: #22c55e;
}

.status-text-wait_process {
    color: #eab308;
}

.status-text-fail {
    color: #ef4444;
}

.record-detail {
    font-size: px2rpx(13);
    color: #6b7280;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.record-right {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    gap: px2rpx(4);
    margin-left: px2rpx(12);
    flex-shrink: 0;

    .row {
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: space-around;

    }

    .l {
        flex: 1;
    }

    .r {
        display: flex;
        flex-direction: column;
        align-items: flex-start;
        gap: px2rpx(4);
        margin-left: px2rpx(12);
        flex-shrink: 0;
    }
}

.amount-deduction {
    font-size: px2rpx(18);
    color: #ef4444;
}

.fee-text {
    font-size: px2rpx(11);
    color: #9ca3af;
}

.record-footer {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding-top: px2rpx(16);
    border-top: 1px solid #f3f4f6;
}

.footer-time {
    font-size: px2rpx(11);
    color: #9ca3af;
}

.footer-actions {
    display: flex;
    align-items: center;
    gap: px2rpx(2);
}

.footer-detail {
    font-size: px2rpx(11);
    color: #2563eb;
}
</style>
