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

        <!-- 搜索栏 -->
        <el-form :model="queryParams" :inline="true" class="search-form">
            <el-form-item>
                <el-select
                    v-model="queryParams.productId"
                    placeholder="体验金产品名称"
                    clearable
                    style="width:200px"
                    @change="handleQuery"
                >
                    <el-option
                        v-for="p in productOptions"
                        :key="p.id"
                        :label="p.name"
                        :value="p.id"
                    />
                </el-select>
            </el-form-item>
            <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.grantTimeRange"
                    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="success" @click="openGrantDialog">赠送</el-button>
            </el-form-item>
        </el-form>

        <!-- 赠送记录列表 -->
        <el-table :data="tableData" v-loading="loading" border stripe>
            <el-table-column label="体验金产品名称" prop="productName" min-width="150" />
            <el-table-column label="体验金ID" prop="id" width="100" align="center" />
            <el-table-column label="用户UID" prop="memberId" width="100" align="center" />
            <el-table-column label="体验金金额" prop="amount" width="120" align="center">
                <template #default="{ row }">{{ Number(row.amount).toFixed(2) }}</template>
            </el-table-column>
            <el-table-column label="有效期" prop="validityDays" width="80" align="center">
                <template #default="{ row }">{{ row.validityDays }}天</template>
            </el-table-column>
            <el-table-column label="赠送时间" prop="createdAt" width="160" align="center" />
            <el-table-column label="失效时间" prop="expireAt" width="160" align="center" />
        </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"
        />

        <!-- 赠送弹窗 -->
        <el-dialog v-model="grantDialog.visible" title="赠送" width="500px" :close-on-click-modal="false">
            <el-form :model="grantForm" :rules="grantRules" ref="grantFormRef" label-width="110px">
                <el-form-item label="选择体验金类型" prop="productId" required>
                    <el-select v-model="grantForm.productId" placeholder="请选择" style="width:100%">
                        <el-option
                            v-for="p in productOptions"
                            :key="p.id"
                            :label="p.name"
                            :value="p.id"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="赠送对象" prop="memberIds" required>
                    <el-input
                        v-model="grantForm.memberIds"
                        type="textarea"
                        :rows="5"
                        placeholder="批量赠送请按如下格式使用&quot;;&quot;将UID隔开填写：&#10;UID;UID;UID"
                        style="width:100%"
                    />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="grantDialog.visible = false">取消</el-button>
                <el-button type="primary" @click="submitGrant">赠送</el-button>
            </template>
        </el-dialog>

        <!-- 身份验证弹窗 -->
        <el-dialog v-model="verifyDialog.visible" title="身份验证" width="380px" :close-on-click-modal="false">
            <p style="margin-bottom:16px;color:#666">请输入谷歌验证码</p>
            <el-input
                v-model="verifyForm.code"
                placeholder="请输入谷歌验证码"
                show-password
            />
            <template #footer>
                <el-button @click="verifyDialog.visible = false">取消</el-button>
                <el-button type="primary" @click="confirmGrant" :loading="submitting">确认</el-button>
            </template>
        </el-dialog>

    </div>
</template>

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

// ── 产品下拉（搜索筛选 + 赠送弹窗共用） ──────────────────────────────────
const productOptions = ref<any[]>([]);
async function loadProductOptions() {
    try {
        const res: any = await listManualExperienceGiftProducts();
        if (res.code === 0) productOptions.value = res.data || [];
    } catch {}
}

// ── 查询参数 ──────────────────────────────────────────────────────────────
const defaultQuery = () => ({
    productId: null as number | null,
    memberId: "" as string,
    grantTimeRange: null as string[] | null,
    pageNo: 1,
    pageSize: 15,
});
const queryParams = reactive(defaultQuery());
const total = ref(0);
const loading = ref(false);
const tableData = ref<any[]>([]);

async function fetchList() {
    loading.value = true;
    try {
        const [grantStart, grantEnd] = queryParams.grantTimeRange || [];
        const res: any = await experienceGiftRecordPageQuery({
            productId: queryParams.productId || undefined,
            memberId: queryParams.memberId || undefined,
            grantType: 0,               // 仅查手动赠送记录
            grantStartTime: grantStart || undefined,
            grantEndTime: grantEnd || 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();
}

// ── 赠送弹窗 ──────────────────────────────────────────────────────────────
const grantDialog = reactive({ visible: false });
const grantFormRef = ref();
const grantForm = reactive({ productId: null as number | null, memberIds: "" });
const grantRules = {
    productId: [{ required: true, message: "请选择体验金类型", trigger: "change" }],
    memberIds: [{ required: true, message: "请输入赠送对象UID", trigger: "blur" }],
};

function openGrantDialog() {
    grantForm.productId = null;
    grantForm.memberIds = "";
    grantDialog.visible = true;
}

async function submitGrant() {
    try {
        await grantFormRef.value.validate();
    } catch {
        return;
    }
    grantDialog.visible = false;
    verifyForm.code = "";
    verifyDialog.visible = true;
}

// ── 身份验证弹窗 ─────────────────────────────────────────────────────────
const verifyDialog = reactive({ visible: false });
const verifyForm = reactive({ code: "" });
const submitting = ref(false);

async function confirmGrant() {
    submitting.value = true;
    try {
        const res: any = await grantExperienceGift({
            productId: grantForm.productId,
            memberIds: grantForm.memberIds,
        });
        if (res.code === 0) {
            ElMessage.success(res.message || "赠送成功");
            verifyDialog.visible = false;
            handleQuery();
        } else {
            ElMessage.error(res.message || "赠送失败");
        }
    } catch {
        // 错误已由请求拦截器统一提示，此处不重复弹出
    } finally {
        submitting.value = false;
    }
}

// ── 初始化 ───────────────────────────────────────────────────────────────
onMounted(() => {
    loadProductOptions();
    fetchList();
});
</script>

<style scoped>
.search-form {
    margin-bottom: 16px;
}
.mt-4 {
    margin-top: 16px;
}
</style>
