<template>
    <div class="withdraw-record-page">
        <!-- 导航栏 -->
        <s-header name="提现记录" :noback="false" :isBorder="false"></s-header>
        <div class="content-container">
            <!-- 统计卡片 -->
            <div class="stats-card">
                <div class="stats-content">
                    <div class="stats-icon-box">
                        <van-icon name="bar-chart-o" class="stats-icon" />
                    </div>
                    <div class="stats-text">
                        <div class="stats-title">提现记录</div>
                        <div class="stats-info">
                            <span class="stats-number">{{ total }}</span>
                            <span class="stats-unit">{{ $t('device.makeRecord.total') }}</span>
                        </div>
                    </div>
                    <!-- 右侧操作按钮 -->
                    <div class="action-buttons">
                        <van-icon name="filter-o" class="action-icon" @click="showFilter = true" />
                        <van-icon name="down" class="action-icon" @click="showExport = true" />
                    </div>
                </div>
            </div>

            <!-- 筛选弹窗 -->
            <van-popup v-model:show="showFilter" position="right" class="filter-popup">
                <div class="popup-header">
                    <h3>{{ $t('device.makeRecord.condition') }}</h3>
                    <van-icon name="cross" @click="showFilter = false" />
                </div>

                <div class="filter-content">
                    <!-- 提现单号输入 -->
                    <div class="filter-item">
                        <label>提现单号</label>
                        <van-field v-model="filter.orderNo" placeholder="请输入提现单号" clearable />
                    </div>

                    <!-- 提现状态单选 -->
                    <div class="filter-item">
                        <label>提现状态</label>
                        <van-radio-group v-model="filter.status">
                            <van-cell-group>
                                <van-cell v-for="status in statusOptions" :key="status.value" clickable
                                    @click="filter.status = status.value">
                                    <template #title>
                                        <span class="status-label">{{ status.label }}</span>
                                    </template>
                                    <template #right-icon>
                                        <van-radio :name="status.value" />
                                    </template>
                                </van-cell>
                            </van-cell-group>
                        </van-radio-group>
                    </div>

                    <!-- 时间范围 -->
                    <div class="filter-item">
                        <label>提现时间</label>
                        <div class="date-picker">
                            <van-field v-model="filter.startTime" :placeholder="$t('device.makeRecord.startTime')"
                                @click="showStartPicker = true" />
                            <van-field v-model="filter.endTime" :placeholder="$t('device.makeRecord.endTime')"
                                @click="showEndPicker = true" />
                        </div>
                    </div>
                </div>

                <!-- 底部操作 -->
                <div class="popup-footer">
                    <van-button type="default" @click="handleReset">重置</van-button>
                    <van-button type="primary" @click="handleConfirmFilter">筛选</van-button>
                </div>
            </van-popup>

            <!-- 时间选择器 -->
            <van-popup v-model:show="showStartPicker" position="bottom">
                <van-date-picker :columns-type="columnsType" v-model="startDate" @confirm="handleStartConfirm"
                    @cancel="showStartPicker = false" />
            </van-popup>
            <van-popup v-model:show="showEndPicker" position="bottom">
                <van-date-picker :columns-type="columnsType" v-model="endDate" @confirm="handleEndConfirm"
                    @cancel="showEndPicker = false" />
            </van-popup>

            <!-- 导出弹窗 -->
            <van-dialog v-model:show="showExport" :title="$t('device.makeRecord.export')"
                :message="$t('device.makeRecord.exportTips')" show-cancel-button @confirm="handleExport">
            </van-dialog>

            <!-- 记录列表 -->
            <van-list v-model:loading="loading" :finished="finished" finished-text="没有更多了" @load="loadRecords">
                <div class="record-list">
                    <div v-for="item in records" :key="item.id" class="record-card" :class="[`status-${item.status}`]">
                        <div class="card-header">
                            <div class="status-amount">
                                <div class="status-badge">
                                    <van-icon name="cash-back-record" class="status-icon" />
                                    <span class="status-text">{{ statusText(item.status) }}</span>
                                    <div class="amount">￥{{ formatAmount(item.amount) }}</div>
                                </div>
                            </div>
                            <van-icon v-if="item.status === 0" name="replay" class="refresh-icon" @click.stop="refreshStatus(item.orderNo)" />
                        </div>

                        <div class="card-content">
                            <div class="info-item">
                                <van-icon name="description" class="info-icon" />
                                <span class="info-text">单号：{{ item.orderNo }}</span>
                            </div>

                            <div class="info-item">
                                <van-icon name="clock" class="info-icon" />
                                <span class="info-text">申请时间：{{ showDateTime(item.createDate) }}</span>
                            </div>

                            <div class="info-item" v-if="item.status === 1">
                                <van-icon name="clock" class="info-icon" />
                                <span class="info-text">到账时间：{{ showDateTime(item.arrivalDate) || '--' }}</span>
                            </div>
                        </div>

                        <div v-if="item.status === 2" class="error-tip">
                            <van-icon name="warning" />
                            <span>{{ item.resultMsg || '系统处理异常' }}</span>
                        </div>
                    </div>
                </div>
            </van-list>
        </div>
    </div>
</template>

<script>
import { $M_ExportFile, getLoginUser } from "../../common/js/utils";
import sHeader from "../../components/SimpleHeader";
import { ref, reactive } from 'vue';
import { withdrawRecord, exportWithdrawRecord, withdrawStatus } from "../../service/purse/index";
import { showFailToast } from "vant";
import dateUtil from "../../utils/dateUtil";


export default {
    components: { sHeader },
    setup() {
        const user = getLoginUser();
        const filter = reactive({
            adminId: user.type > 1 ? user.id : '', // 用户账户id
            status: '', // 提现状态 0：处理中 1：提现成功 2：提现失败
            payPlatform: user.type > 1 ? user.payPlatform : '', // 支付平台
            orderNo: '', // 提现单号
            current: 0, // 页数
            size: 10, // 页大小
            startTime: "", // 开始时间
            endTime: "", // 结束时间
        });
        const records = ref([]);
        const loading = ref(false);
        const finished = ref(false);
        const total = ref(0);

        const showFilter = ref(false);
        const showExport = ref(false);

        // 时间选择
        const columnsType = ref(["year", "month", "day"]);
        const showStartPicker = ref(false);
        const showEndPicker = ref(false);
        const startDate = ref([new Date().getFullYear(), new Date().getMonth() + 1, new Date().getDate()]);
        const endDate = ref([new Date().getFullYear(), new Date().getMonth() + 1, new Date().getDate()]);
        // 时间选择
        const handleStartConfirm = ({ selectedValues }) => {
            console.log(selectedValues.join('/'));
            filter.startTime = selectedValues.join('/');
            showStartPicker.value = false;
        }

        // 时间选择
        const handleEndConfirm = ({ selectedValues }) => {
            console.log(selectedValues.join('/'));
            filter.endTime = selectedValues.join('/');
            showEndPicker.value = false;
        }
        // 状态选项
        const statusOptions = [
            { label: '全部状态', value: '' },
            { label: '处理中', value: 0 },
            { label: '提现成功', value: 1 },
            { label: '提现失败', value: 2 }
        ];

        // 加载记录
        const loadRecords = async () => {
            if (!finished.value) {
                filter.current = filter.current + 1;
                await getWithdrawRecords();
            }
        };

        // 获取提现记录
        const getWithdrawRecords = async () => {
            finished.value = false;
            const { data } = await withdrawRecord(filter);
            if (data.code) {
                records.value = records.value.concat(
                    data.data.records
                );
                total.value = data.data.total;
                if (records.value.length === data.data.total) {
                    finished.value = true;
                }
                loading.value = false;
            } else {
                showFailToast(data.message);
            }
        };

        // 状态标签类型
        const statusTagType = (status) => {
            console.log(status);
            const statusMap = {
                0: 'warning',
                1: 'success',
                2: 'danger'
            };
            return statusMap[status];
        };

        // 重置
        const handleReset = () => {
            filter.status = "";
            filter.startTime = "";
            filter.endTime = "";
            filter.orderNo = "";
        }

        // 确认
        const handleConfirmFilter = async () => {
            showFilter.value = false;
            filter.current = 1;
            records.value = [];
            await getWithdrawRecords();
        }
        // 导出记录
        const handleExport = async () => {
            const { headers, data } = await exportWithdrawRecord(Object.assign({}, filter));
            $M_ExportFile(data, headers);
        };

        // 查询提现状态
        const refreshStatus = async (orderNo) => {
            const { data } = await withdrawStatus({ adminId: user.id, orderNo: orderNo });
            if (data.code === '00000') {
                setTimeout(async () => {
                    filter.current = 1;
                    records.value = [];
                    await getWithdrawRecords();
                }, 500);
            }
        };

        const showDateTime = (date) => {
            if (!date) {
                return "";
            }
            const currentDate = new Date(dateUtil.formateDate(new Date(date), "yyyy/MM/dd hh:mm:ss"));
            return dateUtil.timeZoneDate(currentDate);
        };

        const statusText = (status) => {
            switch (status) {
                case 0:
                    return '处理中';
                case 1:
                    return '提现成功';
                case 2:
                    return '提现失败';
            }
        };


        // 格式化金额
        const formatAmount = (amount) => {
            return new Intl.NumberFormat('en-US', {
                minimumFractionDigits: 2,
                maximumFractionDigits: 2
            }).format(Number(amount))
        };

        return {
            filter,
            records,
            loading,
            finished,
            statusOptions,
            statusTagType,
            loadRecords,
            statusText,
            formatAmount,
            showDateTime,
            total,

            showFilter,
            showExport,
            showStartPicker,
            showEndPicker,
            startDate,
            endDate,
            columnsType,

            refreshStatus,
            handleStartConfirm,
            handleEndConfirm,
            handleExport,
            handleReset,
            handleConfirmFilter,
        };
    },
};
</script>

<style lang="less" scoped>
.withdraw-record-page {
    --primary-color: #2c87c8;
    --success-color: #38b48d;
    --warning-color: #ff9500;
    --error-color: #ff4d4f;
    --text-primary: #1a1a1a;
    --text-secondary: #666;
    --background-light: #f8f9ff;

    background: #f8f9ff;
    overflow-y: auto;
    // min-height: 100vh;
}

.filter-bar {
    padding: 12px 16px;
    background: white;
    display: flex;
    gap: 12px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);

    .van-search {
        flex: 1;
        padding: 0;

        :deep(.van-field__left-icon) {
            margin-right: 8px;
        }
    }

    .filter-buttons {
        display: flex;
        gap: 8px;

        .van-button {
            border-radius: 16px;
            padding: 0 12px;
            border: 1px solid #eee;

            &::before {
                display: none;
            }
        }
    }
}

.stats-card {
    background: #ffffff;
    border-radius: 12px;
    padding: 18px;
    margin: 16px 15px;
    position: relative;
    overflow: hidden;

    &::before {
        content: "";
        position: absolute;
        top: -20px;
        right: -20px;
        width: 80px;
        height: 80px;
        background: #f0f3ff;
        border-radius: 50%;
    }

    .stats-content {
        display: flex;
        align-items: center;
        position: relative;
        z-index: 1;
    }

    .stats-icon-box {
        width: 36px; // 容器尺寸缩小
        height: 36px; // 容器尺寸缩小
        background: linear-gradient(135deg, #4e6bdd 0%, #6b8eff 100%);
        border-radius: 8px; // 圆角缩小
        margin-right: 12px; // 右边距缩小
        display: flex;
        align-items: center;
        justify-content: center;

        .stats-icon {
            font-size: 18px;
            color: white;
        }
    }

    .stats-text {
        .stats-title {
            color: #666;
            font-size: 12px;
            margin-bottom: 4px;
        }

        .stats-info {
            display: flex;
            align-items: baseline;

            .stats-number {
                color: #4e6bdd;
                font-size: 22px;
                font-weight: 600;
                margin-right: 6px;
            }

            .stats-unit {
                color: #999;
                font-size: 12px;
            }
        }
    }

    .action-buttons {
        display: flex;
        gap: 16px; // 增大按钮间距
        margin-left: auto; // 确保右对齐

        .action-icon {
            font-size: 24px; // 增大图标尺寸
            color: #ffffff; // 白色图标
            padding: 8px; // 增大点击区域
            background: #4e6bdd; // 主题色背景
            border-radius: 8px; // 圆角匹配整体风格
            box-shadow: 0 2px 6px rgba(78, 107, 221, 0.3); // 添加投影
            transition: all 0.2s ease;

            // 悬停效果
            &:active {
                transform: scale(0.95);
                background: #3b5ab3;
                box-shadow: 0 1px 3px rgba(78, 107, 221, 0.2);
            }

        }

        // 单独设置导出按钮颜色
        .van-icon-down {
            background: #66bb6a; // 绿色表示导出操作

            &:active {
                background: #4caf50;
            }
        }
    }
}

.filter-popup {
    width: 75%;
    height: 100%;

    .popup-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 16px;
        border-bottom: 1px solid #eee;

        h3 {
            margin: 0;
            font-size: 18px;
        }

        .van-icon {
            font-size: 20px;
            color: #999;
        }
    }

    .filter-content {
        padding: 16px;

        .filter-item {
            margin-bottom: 20px;

            label {
                font-size: 14px;
                color: #606266;
                margin-bottom: 8px;
                display: block;
            }

            // 设备编号输入框样式
            .van-field {
                background: #f5f7fa;
                border-radius: 4px;
                padding: 10px 12px;

                &::placeholder {
                    color: #c0c4cc;
                }
            }

            .van-radio-group {
                width: 100%;
            }

            .van-cell {

                // 选中状态样式
                &--selected {
                    background-color: #f0f3ff;

                    .status-label {
                        color: #4e6bdd;
                    }
                }
            }

            .van-radio__icon--checked .van-icon {
                background-color: #4e6bdd;
                border-color: #4e6bdd;
            }

            .date-picker {
                display: grid;
                grid-template-columns: 1fr 1fr;
                gap: 8px;
            }
        }
    }

    .popup-footer {
        position: fixed;
        bottom: 0;
        left: 0;
        right: 0;
        display: flex;
        gap: 12px;
        padding: 16px;
        background: #fff;
        border-top: 1px solid #eee;

        .van-button {
            flex: 1;
        }
    }
}

.record-list {
    padding: 0 16px 20px;

    .record-card {
        background: white;
        border-radius: 12px;
        padding: 16px;
        margin-bottom: 12px;
        box-shadow: 0 2px 12px rgba(25, 43, 114, 0.08);
        position: relative;
        overflow: hidden;

        // 状态色条
        &::before {
            content: "";
            position: absolute;
            left: 0;
            top: 0;
            bottom: 0;
            width: 4px;
            background: var(--status-color);
        }

        .card-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            margin-bottom: 12px;

            .status-amount {
                display: flex;
                align-items: center;
                gap: 12px;

                .status-badge {
                    display: flex;
                    align-items: center;
                    gap: 6px;
                    background: rgba(var(--status-rgb), 0.1);
                    padding: 6px 10px;
                    border-radius: 20px;

                    .status-icon {
                        font-size: 16px;
                        color: var(--status-color);
                    }

                    .status-text {
                        font-size: 13px;
                        font-weight: 500;
                        color: var(--status-color);
                    }
                }

                .amount {
                    font-size: 20px;
                    font-weight: 600;
                    color: #000000;
                    letter-spacing: 0.5px;
                }
            }

            .refresh-icon {
                font-size: 18px;
                color: #2c87c8;
                padding: 6px;
                border-radius: 50%;
                transition: all 0.3s ease;
                cursor: pointer;

                &:hover {
                    background: rgba(77, 106, 221, 0.1);
                    transform: rotate(360deg);
                }
            }
        }

        .card-content {
            .info-item {
                display: flex;
                align-items: center;
                gap: 8px;
                padding: 8px 0;
                border-bottom: 1px solid #f5f5f5;

                &:last-child {
                    border-bottom: none;
                }

                .info-icon {
                    font-size: 14px;
                    color: #999;
                    flex-shrink: 0;
                }

                .info-text {
                    font-size: 13px;
                    color: #666;
                    word-break: break-all;
                }
            }
        }

        .error-tip {
            margin-top: 12px;
            padding: 10px;
            background: #fff2f0;
            border-radius: 6px;
            display: flex;
            align-items: center;
            gap: 6px;
            font-size: 12px;
            color: var(--status-color);

            .van-icon {
                font-size: 14px;
                flex-shrink: 0;
            }
        }

        // 状态颜色定义
        &.status-0 {
            // 处理中
            --status-color: #ff9500;
            --status-rgb: 255, 149, 0;
        }

        &.status-1 {
            // 成功
            --status-color: #38b48d;
            --status-rgb: 56, 180, 141;
        }

        &.status-2 {
            // 失败
            --status-color: #ff4d4f;
            --status-rgb: 255, 77, 79;
        }
    }

    @media (max-width: 375px) {
        .record-card {
            padding: 12px;

            .card-header {
                .status-amount {
                    flex-direction: column;
                    align-items: flex-start;
                    gap: 8px;

                    .amount {
                        font-size: 18px;
                    }
                }
            }

            .card-content {
                .info-text {
                    font-size: 12px;
                }
            }
        }
    }

}

.export-footer {
    position: fixed;
    bottom: 20px;
    left: 50%;
    transform: translateX(-50%);

    .van-button {
        box-shadow: 0 4px 12px rgba(77, 106, 221, 0.2);
    }
}
</style>