<template>
    <ele-page flex-table>
        <page-search @search="reload" />

        <common-table
            ref="pageRef"
            :pageConfig="pageConfig"
            :columns="columns"
            :tools="false"
        >
            <template #toolbar>
                <div class="flex flex-wrap items-center mb-4">
                    <el-statistic
                        :value="statistics.totalWithdrawMoney"
                        title="提现累计金额"
                        :precision="2"
                        value-style="font-size:30px"
                        class="mr-10"
                    />
                    <el-statistic
                        :value="statistics.unWithdrawMoney"
                        title="待提现金额"
                        :precision="2"
                        value-style="font-size:30px"
                        class="mr-10"
                    />
                    <el-statistic
                        :value="statistics.auditWithdrawMoney"
                        title="提现中金额(待审核)"
                        value-style="font-size:30px"
                        class="mr-10"
                        :precision="2"
                    />
                    <el-statistic
                        :value="statistics.withdrawSuccessMoney"
                        title="已提现金额"
                        :precision="2"
                        value-style="font-size:30px"
                        class="mr-10"
                    />
                    <el-statistic
                        :value="statistics.averageWithdrawDuration"
                        title="平均提现时长"
                        value-style="font-size:30px"
                        class="mr-10"
                        :precision="2"
                    />
                    <el-statistic
                        :value="statistics.noWithdrawMoney"
                        title="长期不提现金额"
                        value-style="font-size:30px"
                        class="mr-10"
                        :precision="2"
                    />
                </div>
                <div class="flex items-center mb-4">
                    <el-statistic
                        :value="statistics.withdrawSuccessMoneyWx"
                        title="微信已提现金额"
                        value-style="font-size:30px"
                        class="mr-10"
                        :precision="2"
                    />
                    <el-statistic
                        :value="statistics.withdrawSuccessMoneyZfb"
                        title="支付宝已提现金额"
                        value-style="font-size:30px"
                        class="mr-10"
                        :precision="2"
                    />
                    <el-statistic
                        :value="statistics.inWithdrawMoneyWx"
                        title="微信提现中金额(未冻结)"
                        value-style="font-size:30px"
                        class="mr-10"
                        :precision="2"
                    />
                    <el-statistic
                        :value="statistics.inWithdrawFreezeMoneyWx"
                        title="微信提现中金额(已冻结)"
                        value-style="font-size:30px"
                        class="mr-10"
                        :precision="2"
                    />
                    <el-statistic
                        :value="statistics.withdrawCountWx"
                        title="微信提现笔数"
                        value-style="font-size:30px"
                        class="mr-10"
                        :precision="0"
                    />
                    <el-statistic
                        :value="statistics.inWithdrawMoneyZfb"
                        title="支付宝提现中金额"
                        value-style="font-size:30px"
                        class="mr-10"
                        :precision="2"
                    />
                    <el-statistic
                        :value="statistics.withdrawCountZfb"
                        title="支付宝提现笔数"
                        value-style="font-size:30px"
                        class="mr-10"
                        :precision="0"
                    />
                </div>

                <div class="flex items-center mb-6">
                    <div class="common-title mr-10">交易记录</div>
                    <el-button
                        type="primary"
                        v-permission="'finance:withdrawal:batchAudit'"
                        @click="handleStepAudit()"
                    >
                        一键审核
                    </el-button>
                </div>

                <el-radio-group
                    @change="handleStatusChange"
                    v-model="useStatus"
                >
                    <el-radio-button label="全部" value="" />
                    <el-radio-button label="待审核" value="1" />
                    <el-radio-button label="待确认" value="2" />
                    <el-radio-button label="提现完成" value="4" />
                    <el-radio-button label="提现失败" value="5" />
                    <el-radio-button label="长期不提现用户" value="6" />
                </el-radio-group>
            </template>

            <template #status="{ row }">
                {{ statusDicts.find((d) => d.value == row.status)?.label }}
            </template>
            <template #nickName="{ row }">
                <el-button type="primary" link @click="handleDetail(row)">
                    {{ row.nickName }}
                </el-button>
            </template>

            <template #action="{ row }">
                <div>
                    <el-button
                        type="primary"
                        link
                        v-permission="'finance:withdrawal:detail'"
                        @click="handleUpdate(row)"
                    >
                        [详情]
                    </el-button>
                    <el-button
                        type="primary"
                        link
                        v-if="row.status == 1"
                        v-permission="'finance:withdrawal:audit'"
                        @click="handleChangeStatus(row)"
                    >
                        [审核]
                    </el-button>
                </div>
            </template>
        </common-table>

        <!-- 审核弹窗 -->
        <audit-dialog ref="auditDialogRef" @success="reload" />

        <!-- 详情弹窗 -->
        <detail-dialog ref="detailDialogRef" />
        <customer-detail ref="detailRef" />
    </ele-page>
</template>

<script setup>
    import { ref, reactive, onMounted } from 'vue';
    import CommonTable from '@/components/CommonPage/CommonTable.vue';
    import pageSearch from './components/page-search.vue';
    import { useDictData } from '@/utils/use-dict-data';
    import request from '@/utils/request';
    import auditDialog from './components/audit-dialog.vue';
    import detailDialog from './components/detail-dialog.vue';
    import customerDetail from '@/views/customer/list/components/customer-detail.vue';

    defineOptions({ name: 'Withdrawal' });

    // 添加统计数据的响应式对象
    const statistics = reactive({
        totalWithdrawMoney: 0,
        unWithdrawMoney: 0,
        auditWithdrawMoney: 0,
        withdrawSuccessMoney: 0,
        averageWithdrawDuration: 0,
        noWithdrawMoney: 0,
        withdrawSuccessMoneyWx: 0,
        withdrawSuccessMoneyZfb: 0,
        inWithdrawMoneyWx: 0,
        inWithdrawFreezeMoneyWx: 0,
        withdrawCountWx: 0,
        inWithdrawMoneyZfb: 0,
        withdrawCountZfb: 0
    });

    // 获取统计数据
    async function fetchStatistics(where) {
        try {
            const res = await request.get('/sys/finance/withdrawSum', {
                params: where
            });
            if (res.data.code === 200) {
                Object.assign(statistics, res.data.data);
            }
        } catch (error) {
            console.error('获取统计数据失败:', error);
        }
    }

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

    const [statusDicts] = useDictData(['withdrawal_status']);

    const useStatus = ref('');
    function handleStatusChange(value) {
        if (value === '6') {
            pageConfig.pageUrl = '/sys/finance/noWithdrawList';
            pageConfig.params.status = value;
            pageRef.value?.reload();
        } else {
            pageConfig.pageUrl = '/sys/finance/withdrawList';
            pageConfig.params.status = value;
            pageRef.value?.reload({ status: value });
        }
    }

    //提现类型 	string
    const withdrawTypeDicts = ref([
        { label: '微信', value: 1 },
        { label: '支付宝', value: 2 }
    ]);
    /** 表格列配置 */
    const columns = ref([
        {
            type: 'selection',
            columnKey: 'selection',
            width: 50,
            align: 'center',
            fixed: 'left'
        },
        {
            label: '提现时间',
            prop: 'createTime',
            align: 'center',
            width: 180,
            formatter: (row) => row.createTime || '--'
        },
        {
            label: '用户名',
            prop: 'nickName',
            align: 'center',
            minWidth: 140,
            slot: 'nickName'
        },
        {
            label: '支付单号/流水号',
            prop: 'transferNo',
            align: 'center',
            minWidth: 160,
            formatter: (row) => row.transferNo || '--'
        },
        {
            label: '对方账户',
            prop: 'withdrawType',
            align: 'center',
            formatter: (row) =>
                withdrawTypeDicts.value.find((d) => d.value == row.withdrawType)
                    ?.label || '--'
        },
        // restmoney
        {
            label: '金额',
            prop: 'withdrawMoney',
            align: 'center',
            formatter: (row) =>
                useStatus.value == 6 ? row.restMoney : row.withdrawMoney
        },
        {
            label: '交易状态',
            prop: 'status',
            align: 'center',
            formatter: (row) =>
                statusDicts.value.find((d) => d.dictValue == row.status)
                    ?.dictLabel || '--'
        },
        {
            label: '交易类型',
            prop: 'withdrawType',
            align: 'center',
            formatter: (row) => '提现'
        },
        {
            columnKey: 'action',
            label: '操作',
            width: 140,
            align: 'center',
            slot: 'action',
            fixed: 'right'
        }
    ]);

    /** 页面组件实例 */
    const pageRef = ref(null);
    const auditDialogRef = ref(null);
    const detailDialogRef = ref(null);

    const pageConfig = reactive({
        pageUrl: '/sys/finance/withdrawList',
        fileName: '提现管理',
        cacheKey: 'withdrawalTable',
        params: {
            status: ''
        }
    });

    //详情页面
    const detailRef = ref(null);
    function handleDetail(row, type) {
        row.id = row.userId;
        detailRef.value?.handleOpen(row, type);
    }

    //刷新表格
    function reload(where) {
        pageRef.value?.reload(where);

        // 刷新统计数据
        console.log('刷新统计数据', where);
        fetchStatistics(where);
    }

    //审核
    function handleChangeStatus(row) {
        auditDialogRef.value?.handleOpen(row.id);
    }

    //详情
    function handleUpdate(row) {
        detailDialogRef.value?.handleOpen(row);
    }

    //一键审核
    function handleStepAudit() {
        const selections = pageRef.value?.getSelections();
        if (!selections?.length) {
            ElMessage.warning('请至少选择一条数据');
            return;
        }
        auditDialogRef.value?.handleOpen(selections.map((item) => item.id));
    }
</script>
