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

        <!-- 搜索栏 -->
        <el-form :model="queryParams" :inline="true" class="search-form">
            <el-form-item>
                <el-input
                    v-model="queryParams.name"
                    placeholder="体验金名称"
                    clearable
                    style="width:160px"
                    @keyup.enter="handleQuery"
                />
            </el-form-item>
            <el-form-item>
                <el-select
                    v-model="queryParams.status"
                    placeholder="状态"
                    clearable
                    style="width:100px"
                >
                    <el-option label="开启" :value="1" />
                    <el-option label="关闭" :value="0" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-select
                    v-model="queryParams.grantType"
                    placeholder="领取方式"
                    clearable
                    style="width:120px"
                >
                    <el-option label="手动赠送" :value="0" />
                    <el-option label="系统触发" :value="1" />
                </el-select>
            </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="primary" :icon="Plus" @click="openDialog(null)">新增</el-button>
            </el-form-item>
        </el-form>

        <!-- 表格 -->
        <el-table :data="tableData" v-loading="loading" border>
            <el-table-column label="编号" prop="id" width="90" align="center" />
            <el-table-column label="体验金名称" prop="name" min-width="140" />
            <el-table-column label="金额(USDT)" prop="amount" width="110" align="center">
                <template #default="{ row }">{{ formatAmount(row.amount) }}</template>
            </el-table-column>
            <el-table-column label="杠杆" prop="leverage" width="80" align="center">
                <template #default="{ row }">{{ row.leverage ?? 2 }}x</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="totalQuantity" width="140" align="center">
                <template #default="{ row }">
                    {{ row.totalQuantity === 0 ? '不限' : row.totalQuantity }}
                    <span style="color:#909399">({{ row.issuedCount ?? 0 }})</span>
                </template>
            </el-table-column>
            <el-table-column label="单人领取上限" prop="perUserLimit" width="110" align="center" />
            <el-table-column label="领取方式" prop="grantType" width="100" align="center">
                <template #default="{ row }">
                    {{ row.grantType == 0 ? '手动赠送' : '系统触发' }}
                </template>
            </el-table-column>
            <el-table-column label="状态" prop="status" width="80" align="center">
                <template #default="{ row }">
                    <el-tag :type="row.status === 1 ? 'success' : 'info'" size="small">
                        {{ row.status === 1 ? '开启' : '关闭' }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="创建时间" prop="createdAt" width="160" align="center">
                <template #default="{ row }">{{ formatDate(row.createdAt) }}</template>
            </el-table-column>
            <el-table-column label="最后修改时间" prop="updatedAt" width="160" align="center">
                <template #default="{ row }">{{ formatDate(row.updatedAt) }}</template>
            </el-table-column>
            <el-table-column label="操作" width="80" align="center" fixed="right">
                <template #default="{ row }">
                    <el-button link type="primary" @click="openDialog(row.id)">修改</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <pagination
            v-if="total > 0"
            :total="total"
            v-model:page="queryParams.pageNo"
            v-model:limit="queryParams.pageSize"
            @pagination="loadList"
        />

        <!-- 新增 / 修改 弹窗 -->
        <el-dialog
            v-model="dialog.visible"
            :title="dialog.isEdit ? '修改体验金产品' : '新增体验金产品'"
            width="560px"
            destroy-on-close
        >
            <el-form
                ref="formRef"
                :model="form"
                :rules="rules"
                label-width="130px"
                class="product-form"
            >
                <el-form-item label="名称" prop="name">
                    <el-input v-model="form.name" placeholder="请输入产品名称" />
                </el-form-item>

                <el-form-item label="金额(USDT)" prop="amount">
                    <el-input-number
                        v-model="form.amount"
                        :min="0.01"
                        :precision="2"
                        :step="10"
                        style="width:100%"
                    />
                </el-form-item>

                <el-form-item label="有效期(天)" prop="validityDays">
                    <el-input-number
                        v-model="form.validityDays"
                        :min="1"
                        :precision="0"
                        style="width:100%"
                    />
                </el-form-item>

                <div class="el-form-item">
                    <label class="el-form-item__label" id="leverage-label">默认杠杆</label>
                    <div class="el-form-item__content">
                        <el-radio-group v-model="form.leverage" aria-labelledby="leverage-label" class="leverage-radio-group">
                            <el-radio-button v-for="n in leverageOptions" :key="n" :value="n">{{ n }}x</el-radio-button>
                        </el-radio-group>
                    </div>
                </div>

                <el-form-item label="发放总量">
                    <el-input-number
                        v-model="form.totalQuantity"
                        :min="0"
                        :precision="0"
                        style="width:100%"
                        placeholder="0表示不限"
                    />
                    <div class="form-tip">0 表示不限</div>
                </el-form-item>

                <el-form-item label="单人领取上限" prop="perUserLimit">
                    <el-input-number
                        v-model="form.perUserLimit"
                        :min="1"
                        :precision="0"
                        style="width:100%"
                    />
                </el-form-item>

                <el-form-item label="单张盈利上限(USDT)">
                    <el-input-number
                        v-model="form.maxProfitPerCard"
                        :min="0.01"
                        :precision="2"
                        :step="10"
                        style="width:100%"
                    />
                    <div class="form-tip">不填则默认等于金额</div>
                </el-form-item>

                <div class="el-form-item">
                    <label class="el-form-item__label" id="coins-label">支持交易对</label>
                    <div class="el-form-item__content">
                        <el-checkbox-group v-model="form.coins" aria-labelledby="coins-label">
                            <el-checkbox label="BTC/USDT" value="BTC/USDT" />
                            <el-checkbox label="ETH/USDT" value="ETH/USDT" />
                        </el-checkbox-group>
                    </div>
                </div>

                <div class="el-form-item">
                    <label class="el-form-item__label" id="grant-type-label">领取方式</label>
                    <div class="el-form-item__content">
                        <el-radio-group v-model="form.grantType" aria-labelledby="grant-type-label">
                            <el-radio :value="0">手动赠送</el-radio>
                            <el-radio :value="1">系统触发</el-radio>
                        </el-radio-group>
                    </div>
                </div>

                <!-- 系统触发 - 触发规则面板 -->
                <el-form-item v-if="form.grantType === 1" label="触发规则">
                    <div class="trigger-panel">
                        <!-- 注册赠送 -->
                        <div class="trigger-item">
                            <el-radio v-model="form.triggerType" :value="0">注册赠送</el-radio>
                            <div class="trigger-sub">
                                <div class="sub-row">
                                    <el-checkbox
                                        v-model="form.hasMinRecharge"
                                        :disabled="form.triggerType !== 0"
                                    >最小充值金额</el-checkbox>
                                    <template v-if="form.triggerType === 0 && form.hasMinRecharge">
                                        <el-input-number
                                            v-model="form.minRechargeAmount"
                                            :min="0.01"
                                            :precision="2"
                                            :controls="false"
                                            style="width:110px"
                                        />
                                        <span class="unit">USDT</span>
                                    </template>
                                </div>
                            </div>
                        </div>

                        <!-- 直邀赠送 -->
                        <div class="trigger-item">
                            <el-radio v-model="form.triggerType" :value="1">直邀赠送</el-radio>
                            <div class="trigger-sub">
                                <!-- 最小开仓金额 独立一行 -->
                                <div class="sub-row">
                                    <el-checkbox
                                        v-model="form.hasMinOpenValue"
                                        :disabled="form.triggerType !== 1"
                                    >最小开仓金额</el-checkbox>
                                    <template v-if="form.triggerType === 1 && form.hasMinOpenValue">
                                        <el-input-number
                                            v-model="form.minOpenValue"
                                            :min="0.01"
                                            :precision="2"
                                            :controls="false"
                                            style="width:110px"
                                        />
                                        <span class="unit">USDT</span>
                                    </template>
                                </div>
                                <!-- 持仓时长 独立一行 -->
                                <div class="sub-row">
                                    <el-checkbox
                                        v-model="form.hasMinHoldMinutes"
                                        :disabled="form.triggerType !== 1"
                                    >持仓时长</el-checkbox>
                                    <template v-if="form.triggerType === 1 && form.hasMinHoldMinutes">
                                        <el-input-number
                                            v-model="form.minHoldMinutes"
                                            :min="1"
                                            :precision="0"
                                            :controls="false"
                                            style="width:100px"
                                        />
                                        <span class="unit">分钟</span>
                                    </template>
                                </div>
                            </div>
                        </div>
                    </div>
                </el-form-item>

                <div class="el-form-item">
                    <label class="el-form-item__label" id="status-label">状态</label>
                    <div class="el-form-item__content">
                        <el-radio-group v-model="form.status" aria-labelledby="status-label">
                            <el-radio :value="1">开启</el-radio>
                            <el-radio :value="0">关闭</el-radio>
                        </el-radio-group>
                    </div>
                </div>
            </el-form>

            <template #footer>
                <el-button @click="dialog.visible = false">取消</el-button>
                <el-button type="primary" :loading="dialog.submitting" @click="submitForm">
                    {{ dialog.isEdit ? '修改' : '添加' }}
                </el-button>
            </template>
        </el-dialog>

    </div>
</template>

<script setup lang="ts">
import { reactive, ref, watch, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { Search, Refresh, Plus } from "@element-plus/icons-vue";
import type { FormInstance } from "element-plus";
import {
    experienceGiftProductPageQuery,
    getExperienceGiftProductDetail,
    saveExperienceGiftProduct,
} from "@/api/activity";

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

const queryParams = reactive({
    name: "",
    status: null as number | null,
    grantType: null as number | null,
    pageNo: 1,
    pageSize: 15,
});

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

function resetQuery() {
    queryParams.name = "";
    queryParams.status = null;
    queryParams.grantType = null;
    queryParams.pageNo = 1;
    loadList();
}

async function loadList() {
    loading.value = true;
    try {
        const params: any = { pageNo: queryParams.pageNo, pageSize: queryParams.pageSize };
        if (queryParams.name) params.name = queryParams.name;
        if (queryParams.status !== null) params.status = queryParams.status;
        if (queryParams.grantType !== null) params.grantType = queryParams.grantType;
        const res: any = await experienceGiftProductPageQuery(params);
        tableData.value = res.data?.content ?? [];
        total.value = res.data?.totalElements ?? 0;
    } finally {
        loading.value = false;
    }
}

// -------- 工具 --------
function formatAmount(val: any) {
    if (val === null || val === undefined) return "0.00";
    return Number(val).toFixed(2);
}
function formatDate(val: any) {
    if (!val) return "-";
    return String(val).replace("T", " ").substring(0, 19);
}

// -------- 杠杆选项 --------
const leverageOptions = [1, 2, 3, 5, 10, 20];

// -------- 表单 --------
const formRef = ref<FormInstance>();

const defaultForm = () => ({
    id: null as number | null,
    name: "",
    amount: null as number | null,
    validityDays: null as number | null,
    leverage: 2,
    totalQuantity: null as number | null,
    perUserLimit: null as number | null,
    maxProfitPerCard: null as number | null,
    coins: [] as string[],
    grantType: 0,
    triggerType: 0,
    hasMinRecharge: false,
    minRechargeAmount: null as number | null,
    hasMinOpenValue: false,
    minOpenValue: null as number | null,
    hasMinHoldMinutes: false,
    minHoldMinutes: null as number | null,
    status: 1,
});

const form = reactive(defaultForm());

const rules = {
    name: [{ required: true, message: "请输入产品名称", trigger: "blur" }],
    amount: [{ required: true, message: "请输入金额", trigger: "blur" }],
    validityDays: [{ required: true, message: "请输入有效期", trigger: "blur" }],
    perUserLimit: [{ required: true, message: "请输入单人领取上限", trigger: "blur" }],
};

// -------- 弹窗 --------
const dialog = reactive({
    visible: false,
    isEdit: false,
    submitting: false,
});

async function openDialog(id: number | null) {
    Object.assign(form, defaultForm());
    dialog.isEdit = id !== null;
    dialog.submitting = false;

    if (id !== null) {
        const res: any = await getExperienceGiftProductDetail(id);
        const d = res.data;
        if (!d) { ElMessage.error("产品不存在"); return; }
        Object.assign(form, {
            id: d.id,
            name: d.name,
            amount: Number(d.amount),
            validityDays: d.validityDays,
            leverage: d.leverage ?? 2,
            totalQuantity: d.totalQuantity ?? 0,
            perUserLimit: d.perUserLimit ?? 1,
            maxProfitPerCard: d.maxProfitPerCard != null ? Number(d.maxProfitPerCard) : null,
            coins: d.coins ?? [],
            grantType: d.grantType ?? 0,
            triggerType: d.triggerType ?? 0,
            hasMinRecharge: d.minRechargeAmount != null,
            minRechargeAmount: d.minRechargeAmount != null ? Number(d.minRechargeAmount) : null,
            hasMinOpenValue: d.minOpenValue != null,
            minOpenValue: d.minOpenValue != null ? Number(d.minOpenValue) : null,
            hasMinHoldMinutes: d.minHoldMinutes != null,
            minHoldMinutes: d.minHoldMinutes ?? null,
            status: d.status ?? 0,
        });
    }

    dialog.visible = true;
}

async function submitForm() {
    if (!formRef.value) return;
    const valid = await formRef.value.validate().catch(() => false);
    if (!valid) return;

    const params: any = {
        name: form.name,
        amount: form.amount,
        validityDays: form.validityDays,
        leverage: form.leverage,
        totalQuantity: form.totalQuantity ?? 0,
        perUserLimit: form.perUserLimit ?? 1,
        grantType: form.grantType,
        status: form.status,
    };

    if (form.id !== null) params.id = form.id;
    if (form.maxProfitPerCard !== null) params.maxProfitPerCard = form.maxProfitPerCard;
    if (form.coins.length > 0) params.coins = form.coins.join(",");

    if (form.grantType === 1) {
        params.triggerType = form.triggerType;
        if (form.triggerType === 0) {
            params.hasMinRecharge = form.hasMinRecharge;
            if (form.hasMinRecharge && form.minRechargeAmount !== null) {
                params.minRechargeAmount = form.minRechargeAmount;
            }
        } else if (form.triggerType === 1) {
            params.hasMinOpenValue = form.hasMinOpenValue;
            if (form.hasMinOpenValue && form.minOpenValue !== null) {
                params.minOpenValue = form.minOpenValue;
            }
            params.hasMinHoldMinutes = form.hasMinHoldMinutes;
            if (form.hasMinHoldMinutes && form.minHoldMinutes !== null) {
                params.minHoldMinutes = form.minHoldMinutes;
            }
        }
    }

    dialog.submitting = true;
    try {
        await saveExperienceGiftProduct(params);
        ElMessage.success(dialog.isEdit ? "修改成功" : "新增成功");
        dialog.visible = false;
        loadList();
    } finally {
        dialog.submitting = false;
    }
}

// 切换触发类型时，重置另一侧的子选项状态
watch(() => form.triggerType, (val) => {
    if (val === 0) {
        form.hasMinOpenValue = false;
        form.minOpenValue = null;
        form.hasMinHoldMinutes = false;
        form.minHoldMinutes = null;
    } else {
        form.hasMinRecharge = false;
        form.minRechargeAmount = null;
    }
});

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

<style lang="scss" scoped>
.search-form {
    margin-bottom: 12px;
}

.product-form {
    .form-tip {
        font-size: 12px;
        color: #909399;
        line-height: 1.4;
        margin-top: 2px;
    }
}

.leverage-radio-group {
    width: 100%;
    display: flex;
}
.leverage-radio-group :deep(.el-radio-button) {
    flex: 1;
}
.leverage-radio-group :deep(.el-radio-button__inner) {
    width: 100%;
    text-align: center;
    padding: 8px 0;
}

.trigger-panel {
    width: 100%;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    padding: 14px 16px;
    background: #fafafa;
    display: flex;
    flex-direction: column;
    gap: 16px;

    .trigger-item {
        display: flex;
        flex-direction: column;
    }

    .trigger-sub {
        margin-left: 24px;
        margin-top: 8px;
        display: flex;
        flex-direction: column;
        gap: 8px;
    }

    .sub-row {
        display: flex;
        align-items: center;
        gap: 6px;
    }

    .unit {
        font-size: 13px;
        color: #606266;
    }
}
</style>
