<script lang="ts">
export default { name: "ActivityLandingPage" };
</script>

<script setup lang="ts">
import { reactive, ref, onMounted } from "vue";
import { ElMessage } from "element-plus";
import {
    landingPageQuery,
    getLandingPageDetail,
    saveLandingPage,
} from "@/api/activity/index";

// ── 列表 ─────────────────────────────────────────────────────────────────────
const state = reactive({
    loading:  false,
    rows:     [] as any[],
    total:    0,
    pageNo:   1,
    pageSize: 15,
    filterTitle: "",
});

async function load() {
    state.loading = true;
    try {
        const params: any = { type: 100, pageNo: state.pageNo, pageSize: state.pageSize };
        if (state.filterTitle) params.title = state.filterTitle;
        const res: any = await landingPageQuery(params);
        const page = res?.data ?? {};
        state.rows  = page.content ?? [];
        state.total = page.totalElements ?? 0;
    } catch {
    } finally {
        state.loading = false;
    }
}

function handleSearch() { state.pageNo = 1; load(); }
function handleReset()  { state.filterTitle = ""; handleSearch(); }

// ── 编辑弹框 ──────────────────────────────────────────────────────────────────
const dialogVisible = ref(false);
const saving = ref(false);
const isEdit = ref(false);

const emptyForm = () => ({
    id:            null as number | null,
    title:         "",
    activityLink:  "",
    newUserReward: "",
    inviteReward:  "",
    validityDays:  "",
    activityRules: "",
});

const form = reactive(emptyForm());

function openCreate() {
    Object.assign(form, emptyForm());
    isEdit.value = false;
    dialogVisible.value = true;
}

async function openEdit(row: any) {
    Object.assign(form, emptyForm());
    isEdit.value = true;
    try {
        const res: any = await getLandingPageDetail(row.id);
        const d = res?.data ?? {};
        form.id           = d.id;
        form.title        = d.title        ?? "";
        form.activityLink = d.activityLink ?? "";
        try {
            const s = JSON.parse(d.settings || "{}");
            form.newUserReward = String(s.newUserReward ?? "");
            form.inviteReward  = String(s.inviteReward  ?? "");
            form.validityDays  = String(s.validityDays  ?? "");
            form.activityRules = d.activityRules ?? "";
        } catch {}
    } catch {
        ElMessage.error("加载详情失败");
        return;
    }
    dialogVisible.value = true;
}

async function handleSave() {
    if (!form.title.trim()) { ElMessage.warning("请填写活动名称"); return; }

    saving.value = true;
    try {
        await saveLandingPage({
            id:            form.id ?? undefined,
            title:         form.title,
            activityLink:  form.activityLink,
            status:        1,
            activityRules: form.activityRules || null,
            settings: JSON.stringify({
                newUserReward: form.newUserReward,
                inviteReward:  form.inviteReward,
                validityDays:  form.validityDays,
            }),
        });
        ElMessage.success("保存成功");
        dialogVisible.value = false;
        load();
    } catch {
    } finally {
        saving.value = false;
    }
}

function parseSettings(settings: string) {
    try {
        const s = JSON.parse(settings || "{}");
        if (s.newUserReward == null && s.inviteReward == null) return "—";
        return `新用户 ${s.newUserReward}U / 邀请 ${s.inviteReward}U / ${s.validityDays}天`;
    } catch { return "—"; }
}

onMounted(load);
</script>

<template>
    <div class="app-container">
        <!-- 搜索栏 -->
        <el-card shadow="never" style="margin-bottom: 12px">
            <el-form inline>
                <el-form-item label="活动名称">
                    <el-input
                        v-model="state.filterTitle"
                        placeholder="搜索名称"
                        clearable
                        style="width: 180px"
                        @keyup.enter="handleSearch"
                    />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleSearch">搜索</el-button>
                    <el-button @click="handleReset">重置</el-button>
                    <el-button type="success" @click="openCreate">+ 新建活动</el-button>
                </el-form-item>
            </el-form>
        </el-card>

        <!-- 列表 -->
        <el-card shadow="never">
            <el-table
                v-loading="state.loading"
                :data="state.rows"
                border
                stripe
                size="small"
                style="width: 100%"
            >
                <el-table-column label="ID" prop="id" width="80" align="center" />
                <el-table-column label="活动名称" prop="title" min-width="160" />
                <el-table-column label="标识码" prop="activityLink" width="180">
                    <template #default="{ row }">
                        <el-tag v-if="row.activityLink" type="info" size="small">{{ row.activityLink }}</el-tag>
                        <span v-else style="color:#c0c4cc">—</span>
                    </template>
                </el-table-column>
                <el-table-column label="奖励配置" min-width="240">
                    <template #default="{ row }">{{ parseSettings(row.settings) }}</template>
                </el-table-column>
                <el-table-column label="操作" width="100" fixed="right" align="center">
                    <template #default="{ row }">
                        <el-button size="small" @click="openEdit(row)">编辑</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <el-empty
                v-if="!state.loading && state.rows.length === 0"
                description="暂无数据"
                style="padding: 40px 0"
            />

            <div v-if="state.total > 0" class="pagination-wrap">
                <el-pagination
                    v-model:current-page="state.pageNo"
                    :page-size="state.pageSize"
                    :total="state.total"
                    layout="total, prev, pager, next, jumper"
                    background
                    @current-change="load"
                />
            </div>
        </el-card>

        <!-- 新增 / 编辑弹框 -->
        <el-dialog
            v-model="dialogVisible"
            :title="isEdit ? '编辑活动落地页' : '新建活动落地页'"
            width="520px"
            :close-on-click-modal="false"
            destroy-on-close
        >
            <el-form label-width="140px">
                <el-form-item label="活动名称" required>
                    <el-input v-model="form.title" placeholder="请输入活动名称" clearable />
                </el-form-item>

                <el-form-item label="活动标识码">
                    <el-input
                        v-model="form.activityLink"
                        placeholder="如 experience_invite"
                        clearable
                    />
                    <div style="font-size: 12px; color: #909399; margin-top: 4px">
                        App 按此标识码查询对应活动，同类型活动请使用不同标识码
                    </div>
                </el-form-item>

                <el-divider content-position="left">奖励配置</el-divider>

                <el-form-item label="新用户奖励（U）">
                    <el-input v-model="form.newUserReward" placeholder="如 50" style="width: 180px" />
                </el-form-item>

                <el-form-item label="邀请奖励（U）">
                    <el-input v-model="form.inviteReward" placeholder="如 100" style="width: 180px" />
                </el-form-item>

                <el-form-item label="体验金有效期（天）">
                    <el-input v-model="form.validityDays" placeholder="如 7" style="width: 180px" />
                </el-form-item>

                <el-divider content-position="left">活动规则</el-divider>

                <el-form-item label="活动规则">
                    <div style="width: 100%">
                        <el-input
                            v-model="form.activityRules"
                            type="textarea"
                            :rows="6"
                            :maxlength="2000"
                            show-word-limit
                            placeholder="每行一条规则，支持换行，最多 2000 字符"
                        />
                        <div style="font-size: 12px; color: #909399; margin-top: 4px">
                            留空则 App 显示默认规则文案
                        </div>
                    </div>
                </el-form-item>
            </el-form>

            <template #footer>
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" :loading="saving" @click="handleSave">保存</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<style scoped>
.pagination-wrap {
    display: flex;
    justify-content: flex-end;
    padding: 12px 0 0;
}
</style>
