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

        <common-table ref="pageRef" :pageConfig="pageConfig" :columns="columns">
            <template #toolbar>
                <div class="flex items-center mb-4">
                    <el-statistic
                        :value="statistics.sumMoney"
                        title="累计申请金额"
                        :precision="2"
                        value-style="font-size:30px"
                        class="mr-20"
                    />
                    <el-statistic
                        :value="statistics.unAuditMoney"
                        title="待审核补贴"
                        :precision="2"
                        value-style="font-size:30px"
                        class="mr-20"
                    />
                    <el-statistic
                        :value="statistics.auditMoney"
                        title="已审核补贴金额"
                        :precision="2"
                        value-style="font-size:30px"
                        class="mr-20"
                    />
                </div>

                <div class="common-title mb-4">交易记录</div>

                <!-- 状态 1-待审核 2-审核通过 3-审核拒绝 4-未提交 5-已放弃 -->
                <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="3" />
                    <el-radio-button label="未提交" value="4" />
                    <el-radio-button label="用户放弃" value="5" />
                </el-radio-group>

                <el-button
                    type="primary"
                    @click="handleBatchAudit"
                    v-permission="'finance:subsidyReview:audit'"
                    style="margin-left: 20px"
                >
                    批量审核
                </el-button>
            </template>

            <template #type="{ row }">
                <dict-data
                    code="order_compensation_type"
                    type="text"
                    :model-value="row.type"
                />
            </template>
            <template #status="{ row }">
                <dict-data
                    code="order_compensation_status"
                    type="text"
                    :model-value="row.status"
                />
            </template>

            <template #orderId="{ row }">
                <el-button type="primary" link @click="handleOrderId(row)">{{
                    row.orderId
                }}</el-button>
            </template>

            <template #action="{ row }">
                <div>
                    <el-button
                        type="primary"
                        link
                        v-if="row.status == 1"
                        v-permission="'finance:subsidyReview:audit'"
                        @click="handleAudit(row)"
                    >
                        [审核]
                    </el-button>
                    <el-button
                        type="primary"
                        link
                        v-permission="'finance:subsidyReview:log'"
                        @click="handleLog(row)"
                    >
                        [操作日志]
                    </el-button>
                    <!-- 替客户申请 showSubmit -->
                    <el-button
                        type="danger"
                        link
                        v-if="row.showSubmit == 1"
                        v-permission="'finance:subsidyReview:showSubmit'"
                        @click="handleShowSubmit(row)"
                    >
                        [替客户申请]
                    </el-button>
                </div>
            </template>
        </common-table>

        <orderDetail ref="orderDetailRef" />

        <!-- 操作日志弹窗 -->
        <log-dialog ref="logDialogRef" />

        <!-- 批量审核弹窗 -->
        <batch-audit ref="batchAuditRef" @success="handleBatchAuditSuccess" />
    </ele-page>
</template>

<script setup>
    import { ref, reactive, onMounted, getCurrentInstance } from 'vue';
    import CommonTable from '@/components/CommonPage/CommonTable.vue';
    import pageSearch from './page-search.vue';
    import request from '@/utils/request';
    import OrderDetail from '@/views/recycleOrder/components/order-detail.vue';
    import LogDialog from './components/log-dialog.vue';
    import BatchAudit from './components/batch-audit.vue';
    import { ElMessage } from 'element-plus';
    import { rowKey } from 'element-plus/es/components/table-v2/src/common';
    defineOptions({ name: 'SubsidyReview' });

    const { proxy } = getCurrentInstance();
    // 添加统计数据的响应式对象
    const statistics = reactive({
        sumMoney: 0,
        unAuditMoney: 0,
        auditMoney: 0
    });

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

    const orderDetailRef = ref(null);
    const handleOrderId = (row) => {
        orderDetailRef.value?.handleOpen(row);
    };

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

    const useStatus = ref('');
    function handleStatusChange(value) {
        useStatus.value = value;
        pageConfig.params.status = value;
        reload();
    }

    /** 表格列配置 */
    const columns = ref([
        { type: 'selection', width: 55, align: 'center' },
        { label: '申请时间', prop: 'submitTime', align: 'center', width: 180 },
        { label: '用户ID', prop: 'userId', align: 'center' },
        { label: '用户昵称', prop: 'nickName', align: 'center' },
        {
            label: '对方账户',
            prop: 'nickName2',
            align: 'center',
            formatter: (row) => '小程序余额'
        },
        { label: '结算金额', prop: 'compensationMoney', align: 'center' },
        { label: '交易状态', prop: 'status', align: 'center', slot: 'status' },
        {
            label: '交易类型',
            prop: 'type',
            align: 'center',
            slot: 'type'
        },
        {
            label: '订单编号',
            prop: 'orderId',
            align: 'center',
            minWidth: 120,
            slot: 'orderId'
        },
        {
            columnKey: 'action',
            label: '操作',
            width: 150,
            align: 'center',
            slot: 'action',
            fixed: 'right'
        }
    ]);

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

    const pageConfig = reactive({
        pageUrl: '/order/orderCompensationLog/pagelist',
        fileName: '补贴审核',
        cacheKey: 'subsidyReview',
        rowKey: 'id',
        params: {
            status: useStatus.value
        }
    });

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

    // 审核
    const handleAudit = (row) => {
        // 使用批量审核的弹窗，传入单个ID
        batchAuditRef.value?.open([row.id]);
    };

    // 日志弹窗引用
    const logDialogRef = ref(null);

    // 操作日志
    const handleLog = (row) => {
        logDialogRef.value?.open(row);
    };

    // 批量审核
    const batchAuditRef = ref(null);
    const handleBatchAudit = () => {
        const selectedRows = pageRef.value?.getSelections() || [];
        if (selectedRows.length === 0) {
            ElMessage.warning('请先选择要审核的记录');
            return;
        }

        // 只能审核待审核状态的记录
        const pendingRows = selectedRows.filter((row) => row.status == 1);
        if (pendingRows.length === 0) {
            ElMessage.warning('请选择待审核状态的记录');
            return;
        }

        if (pendingRows.length !== selectedRows.length) {
            ElMessage.warning(
                '只能审核待审核状态的记录，已自动过滤其他状态的记录'
            );
        }

        const ids = pendingRows.map((row) => row.id);
        batchAuditRef.value?.open(ids);
    };

    const handleBatchAuditSuccess = () => {
        // 批量审核成功后刷新表格和统计数据
        reload();
        fetchStatistics();
        // 清空选中状态
        pageRef.value?.tableRef?.clearSelection();
    };

    //替客户申请
    const handleShowSubmit = (row) => {
        pageRef.value.messageBoxConfirm({
            message: '确定替客户申请吗？',
            fetch: () =>
                proxy.$http.post(
                    `/order/orderCompensationLog/adminSubmitAudit/${row.id}`
                )
        });
    };
</script>
