<template>
    <div class="app-container">
        <!-- 搜索栏 -->
        <el-form :model="queryParams" inline>
            <el-form-item label="会员ID">
                <el-input
                    v-model="queryParams.memberId"
                    placeholder="请输入会员ID"
                    clearable
                    style="width: 150px"
                    @keyup.enter="handleQuery"
                />
            </el-form-item>
            <el-form-item label="设备指纹">
                <el-input
                    v-model="queryParams.deviceFingerprint"
                    placeholder="设备指纹（模糊）"
                    clearable
                    style="width: 220px"
                    @keyup.enter="handleQuery"
                />
            </el-form-item>
            <el-form-item label="设备型号">
                <el-input
                    v-model="queryParams.deviceModel"
                    placeholder="设备型号（模糊）"
                    clearable
                    style="width: 180px"
                    @keyup.enter="handleQuery"
                />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="handleQuery">搜索</el-button>
                <el-button @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <!-- 数据表格 -->
        <el-table v-loading="loading" :data="list" border stripe>
            <el-table-column label="会员ID" prop="member_id" width="100" />
            <el-table-column label="设备指纹" prop="device_fingerprint" min-width="180" show-overflow-tooltip />
            <el-table-column label="设备类型" prop="device_type" width="90">
                <template #default="{ row }">
                    <el-tag v-if="row.device_type === 1" type="info" size="small">iOS</el-tag>
                    <el-tag v-else-if="row.device_type === 2" type="success" size="small">Android</el-tag>
                    <span v-else>—</span>
                </template>
            </el-table-column>
            <el-table-column label="设备型号" prop="device_model" min-width="140" show-overflow-tooltip />
            <el-table-column label="系统版本" prop="os_version" width="120" show-overflow-tooltip />
            <el-table-column label="关联账号数" prop="account_count" width="100" align="center">
                <template #default="{ row }">
                    <el-tag
                        :type="row.account_count > 2 ? 'danger' : row.account_count > 1 ? 'warning' : 'success'"
                        size="small"
                    >{{ row.account_count }}</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="登录次数" prop="login_count" width="85" align="center" />
            <el-table-column label="首次登录" prop="first_login_time" width="160" />
            <el-table-column label="最后登录" prop="last_login_time" width="160" />
            <el-table-column label="最后IP" prop="last_login_ip" width="130" />
            <el-table-column label="状态" width="85" align="center">
                <template #default="{ row }">
                    <el-tag v-if="row.banned" type="danger" size="small">已封禁</el-tag>
                    <el-tag v-else type="success" size="small">正常</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="140" fixed="right" align="center">
                <template #default="{ row }">
                    <el-button
                        v-if="!row.banned"
                        type="danger"
                        size="small"
                        @click="openBanDialog(row)"
                    >封禁</el-button>
                    <el-button
                        v-else
                        type="warning"
                        size="small"
                        @click="handleUnban(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="[20, 50, 100]"
            layout="total, sizes, prev, pager, next"
            style="margin-top: 16px; text-align: right"
            @current-change="handleQuery"
            @size-change="handleQuery"
        />

        <!-- 封禁弹窗 -->
        <el-dialog v-model="banDialog.visible" title="封禁设备" width="480px">
            <el-form :model="banDialog" label-width="90px">
                <el-form-item label="设备指纹">
                    <span style="word-break: break-all; font-size: 12px; color: #666">
                        {{ banDialog.deviceFingerprint }}
                    </span>
                </el-form-item>
                <el-form-item label="封禁原因">
                    <el-input
                        v-model="banDialog.reason"
                        type="textarea"
                        :rows="3"
                        placeholder="可选填写封禁原因"
                    />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="banDialog.visible = false">取消</el-button>
                <el-button type="danger" :loading="banDialog.loading" @click="confirmBan">确认封禁</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { deviceMonitorPage, deviceBan, deviceUnban } from "@/api/member/deviceMonitor";

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

const queryParams = reactive({
    pageNo: 1,
    pageSize: 20,
    memberId: "",
    deviceFingerprint: "",
    deviceModel: "",
});

const banDialog = reactive({
    visible: false,
    loading: false,
    deviceFingerprint: "",
    reason: "",
});

async function handleQuery() {
    loading.value = true;
    try {
        const res: any = await deviceMonitorPage({
            ...queryParams,
            memberId: queryParams.memberId ? Number(queryParams.memberId) : undefined,
        });
        if (res.code === 0) {
            list.value = res.data.list || [];
            total.value = res.data.total || 0;
        } else {
            ElMessage.error(res.message || "查询失败");
        }
    } catch {
        ElMessage.error("查询失败");
    } finally {
        loading.value = false;
    }
}

function resetQuery() {
    queryParams.pageNo = 1;
    queryParams.pageSize = 20;
    queryParams.memberId = "";
    queryParams.deviceFingerprint = "";
    queryParams.deviceModel = "";
    handleQuery();
}

function openBanDialog(row: any) {
    banDialog.deviceFingerprint = row.device_fingerprint;
    banDialog.reason = "";
    banDialog.visible = true;
}

async function confirmBan() {
    banDialog.loading = true;
    try {
        const res: any = await deviceBan({
            deviceFingerprint: banDialog.deviceFingerprint,
            reason: banDialog.reason,
        });
        if (res.code === 0) {
            ElMessage.success("封禁成功");
            banDialog.visible = false;
            handleQuery();
        } else {
            ElMessage.error(res.message || "封禁失败");
        }
    } catch {
        ElMessage.error("封禁失败");
    } finally {
        banDialog.loading = false;
    }
}

async function handleUnban(row: any) {
    await ElMessageBox.confirm(`确定解封该设备？`, "提示", { type: "warning" });
    try {
        const res: any = await deviceUnban({ deviceFingerprint: row.device_fingerprint });
        if (res.code === 0) {
            ElMessage.success("解封成功");
            handleQuery();
        } else {
            ElMessage.error(res.message || "解封失败");
        }
    } catch (e: any) {
        if (e !== "cancel") ElMessage.error("解封失败");
    }
}

onMounted(handleQuery);
</script>
