<template>
    <div class="app-container">

        <!-- 搜索栏 -->
        <el-form :model="queryParams" :inline="true" class="search-form">
            <el-form-item>
                <el-input
                    v-model="queryParams.memberId"
                    placeholder="用户UID"
                    clearable
                    style="width:130px"
                    @keyup.enter="handleQuery"
                />
            </el-form-item>
            <el-form-item>
                <el-date-picker
                    v-model="queryParams.timeRange"
                    type="daterange"
                    start-placeholder="预警开始时间"
                    end-placeholder="预警结束时间"
                    style="width:280px"
                    value-format="YYYY-MM-DD"
                />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" :icon="Search" @click="handleQuery">搜索</el-button>
                <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
                <el-button type="danger" @click="handleCancelAll">一键取消告警</el-button>
            </el-form-item>
        </el-form>

        <!-- 表格 -->
        <el-table :data="tableData" v-loading="loading" border stripe style="width:100%">
            <el-table-column label="序号" type="index" width="70" align="center" />
            <el-table-column label="预警时间" prop="createdAt" min-width="170" align="center">
                <template #default="{ row }">{{ formatDate(row.createdAt) }}</template>
            </el-table-column>
            <el-table-column label="UID" prop="memberId" min-width="120" align="center" />
            <el-table-column label="领取体验金次数" prop="receiptCount" min-width="140" align="center">
                <template #default="{ row }">
                    <span :class="row.receiptCount >= 5 ? 'text-danger' : ''">{{ row.receiptCount }}</span>
                </template>
            </el-table-column>
            <el-table-column label="体验金收益" prop="profitAmount" min-width="130" align="center">
                <template #default="{ row }">
                    <span :class="Number(row.profitAmount) >= 100 ? 'text-danger' : ''">
                        {{ Number(row.profitAmount).toFixed(2) }}
                    </span>
                </template>
            </el-table-column>
            <el-table-column label="状态" prop="status" min-width="110" align="center">
                <template #default="{ row }">
                    <el-tag :type="row.status === 0 ? 'danger' : 'info'" size="small">
                        {{ row.status === 0 ? '告警' : '已取消告警' }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="操作" min-width="120" align="center">
                <template #default="{ row }">
                    <el-button
                        link
                        type="danger"
                        :disabled="row.status !== 0"
                        @click="handleCancel(row)"
                    >取消预警</el-button>
                </template>
            </el-table-column>
        </el-table>

        <el-pagination
            v-model:current-page="queryParams.pageNo"
            v-model:page-size="queryParams.pageSize"
            :total="total"
            :page-sizes="[15, 30, 50]"
            layout="total, sizes, prev, pager, next"
            class="mt-4"
            @size-change="fetchList"
            @current-change="fetchList"
        />

    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Search, Refresh } from "@element-plus/icons-vue";
import {
    experienceGiftRiskAlertPageQuery,
    cancelExperienceGiftRiskAlert,
    cancelAllExperienceGiftRiskAlerts,
} from "@/api/activity/index";

const loading = ref(false);
const tableData = ref<any[]>([]);
const total = ref(0);

const defaultQuery = () => ({
    memberId: "",
    timeRange: null as string[] | null,
    pageNo: 1,
    pageSize: 15,
});
const queryParams = reactive(defaultQuery());

function formatDate(val: any) {
    if (!val) return "-";
    return String(val).replace("T", " ").substring(0, 19);
}

async function fetchList() {
    loading.value = true;
    try {
        const [startTime, endTime] = queryParams.timeRange || [];
        const res: any = await experienceGiftRiskAlertPageQuery({
            memberId: queryParams.memberId || undefined,
            startTime: startTime || undefined,
            endTime: endTime || undefined,
            pageNo: queryParams.pageNo,
            pageSize: queryParams.pageSize,
        });
        if (res.code === 0) {
            tableData.value = res.data?.content || [];
            total.value = res.data?.totalElements || 0;
        }
    } finally {
        loading.value = false;
    }
}

function handleQuery() {
    queryParams.pageNo = 1;
    fetchList();
}

function resetQuery() {
    Object.assign(queryParams, defaultQuery());
    fetchList();
}

function handleCancel(row: any) {
    ElMessageBox.confirm(`确认取消用户 ${row.memberId} 的告警？取消后不可恢复。`, "提示", {
        confirmButtonText: "确认取消",
        cancelButtonText: "返回",
        type: "warning",
    }).then(async () => {
        const res: any = await cancelExperienceGiftRiskAlert(row.id);
        if (res.code === 0) {
            ElMessage.success("已取消告警");
            fetchList();
        } else {
            ElMessage.error(res.message || "操作失败");
        }
    }).catch(() => {});
}

function handleCancelAll() {
    ElMessageBox.confirm("确认一键取消所有告警状态的预警记录？取消后不可恢复。", "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "返回",
        type: "warning",
    }).then(async () => {
        const res: any = await cancelAllExperienceGiftRiskAlerts();
        if (res.code === 0) {
            ElMessage.success(res.message || "操作成功");
            fetchList();
        } else {
            ElMessage.error(res.message || "操作失败");
        }
    }).catch(() => {});
}

onMounted(() => {
    fetchList();
});
</script>

<style scoped>
.search-form {
    margin-bottom: 16px;
}
.mt-4 {
    margin-top: 16px;
}
.text-danger {
    color: #f56c6c;
    font-weight: 600;
}
</style>
