<template>
    <div>
        <el-card class="user-list">
            <div class="header">
                <el-row class="header-title" :gutter="10">
                    <el-col :span="24">用户管理</el-col>
                </el-row>
                <el-row class="header-button" :gutter="10">
                    <el-col :span="2">
                        <div>
                            <el-button type="primary" @click="showAddUserDialog">新增</el-button>
                        </div>
                    </el-col>
                    <el-col :span="2">
                        <!-- <div>
                            <el-button type="danger" @click="handleDeleteSelected">删除所选</el-button>
                        </div> -->
                    </el-col>
                    <el-col :span="18"></el-col>
                    <el-col :span="2">
                        <el-dropdown trigger="click">
                            <el-button type="default">表格列设置</el-button>
                            <template #dropdown>
                                <el-dropdown-menu>
                                    <el-dropdown-item v-for="(column, index) in columns" :key="index">
                                        <el-checkbox v-model="column.visible">{{ column.label }}</el-checkbox>
                                    </el-dropdown-item>
                                </el-dropdown-menu>
                            </template>
                        </el-dropdown>
                    </el-col>
                </el-row>
            </div>

            <el-row>
                <el-col :span="24">
                    <div class="table-part">
                        <el-table v-loading="loading" :data="tableData" 
                            class="user-table" border>
                            <el-table-column v-if="getColumnVisibility('selection')" type="selection"
                                min-width="55"></el-table-column>
                            <el-table-column v-if="getColumnVisibility('id')" prop="id" label="序号"
                                min-width="100"></el-table-column>
                            <el-table-column v-if="getColumnVisibility('username')" prop="username" label="用户名"
                                min-width="180"></el-table-column>
                            <el-table-column v-if="getColumnVisibility('email')" prop="email" label="邮箱"
                                min-width="200"></el-table-column>
                            <el-table-column v-if="getColumnVisibility('actions')" label="操作" min-width="200" align="center">
                                <template #default="scope">
                                    <el-button type="text" size="small"
                                        @click="showEditUserDialog(scope.row)">编辑</el-button>
                                    <el-button type="text" size="small" @click="confirmDelete(scope.row)">删除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                </el-col>
            </el-row>
        </el-card>

        <!-- 用户弹窗 -->
        <el-dialog :title="isEdit ? '编辑用户' : '新增用户'" v-model="userDialogVisible" width="30%">
            <el-form :model="newUserForm" ref="newUserFormRef" :rules="rules" label-width="80px">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="newUserForm.username" :disabled="isEdit" />
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="newUserForm.email" :disabled="isEdit" />
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="newUserForm.password" type="password" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="userDialogVisible = false">取消</el-button>
                <el-button type="primary" v-if="!isEdit" @click="handleAddUser">新增</el-button>
                <el-button type="primary" v-else @click="handleEditUser">修改</el-button>
            </template>
        </el-dialog>
    </div>
</template>
  
<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { BoxApi } from '@/utils/boxApi';

// 表格列配置
const columns = ref([
    { label: '序号', prop: 'id', visible: true },
    { label: '用户名', prop: 'username', visible: true },
    { label: '邮箱', prop: 'email', visible: true },
    { label: '操作', prop: 'actions', visible: true },
    { label: '选择', prop: 'selection', visible: true }
]);

// 表格数据
const tableData = ref([]); // 动态表格数据
const loading = ref(false);
const selectedRows = ref<any[]>([]);
const userDialogVisible = ref(false); // 控制用户弹窗的显示
const isEdit = ref(false); // 控制是否为编辑模式

// 用户表单数据
const newUserForm = ref({
    username: '',
    email: '',
    password: ''
});
const newUserFormRef = ref(); // 引用表单实例
const rules = {
    username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
    email: [{ required: true, message: '请输入邮箱', trigger: 'blur' }],
    password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
};

// 从 localStorage 中获取保存的 token
const token = localStorage.getItem('alertToken');
// const token = "";

// 创建 BoxApi 实例并设置 token
let apiInstance = new BoxApi();
if (token) {
    apiInstance.setToken(token); // 确保在请求前设置 token
} else {
    console.error('Token is missing. Please login.');
}

// 获取列的可见状态
const getColumnVisibility = (prop: string) => {
    const column = columns.value.find((col) => col.prop === prop);
    return column ? column.visible : false;
};

// 刷新表格数据
const refreshTable = async () => {
    loading.value = true;
    try {
        const users = await apiInstance.getAllUsers(); // 调用getAllUsers方法获取用户
        tableData.value = users.map((user: any, index: number) => ({
            id: index + 1, // 增加id索引
            username: user.username,
            email: user.email
        }));
    } catch (error) {
        ElMessage.error('刷新用户列表失败');
    } finally {
        loading.value = false;
    }
};

// 在页面加载时获取用户数据
onMounted(() => {
    refreshTable();
});

// 显示新增用户弹窗
const showAddUserDialog = () => {
    isEdit.value = false; // 切换到新增模式
    newUserForm.value = { username: '', email: '', password: '' }; // 重置表单
    userDialogVisible.value = true;
};

// 显示编辑用户弹窗
const showEditUserDialog = (user: any) => {
    isEdit.value = true; // 切换到编辑模式
    newUserForm.value = { ...user, password: '' }; // 填充表单数据，但密码保持为空
    userDialogVisible.value = true;
};

// 新增用户
const handleAddUser = () => {
    newUserFormRef.value?.validate(async (valid: boolean) => {
        if (valid) {
            try {
                const res = await apiInstance.addUser(newUserForm.value.username, newUserForm.value.password, newUserForm.value.email);
                ElMessage.success('新增用户成功');
                userDialogVisible.value = false;
                refreshTable();
            } catch (error: any) {
                if (error && error.ec !== undefined && error.dm && error.em) {
                    const errMessage = `
                  <div> 错误代码: ${error.ec}</div>
                  <div> 描述: ${error.dm}</div>
                  <div> 信息: ${error.em}</div>
              `;
                    ElMessage({
                        message: errMessage,
                        type: 'error',
                        dangerouslyUseHTMLString: true,
                        duration: 3000,
                        offset: 50
                    });
                } else {
                    ElMessage.error('新增用户失败');
                }
            }
        } else {
            ElMessage.warning('表单验证失败，请检查输入');
        }
    });
};

// 编辑用户（调用 resetUser 更新所有用户信息）
const handleEditUser = () => {
    newUserFormRef.value?.validate(async (valid: boolean) => {
        if (valid) {
            try {
                const res = await apiInstance.resetUser(
                    newUserForm.value.username,
                    newUserForm.value.password,
                    newUserForm.value.email
                );
                ElMessage.success('用户信息修改成功');
                userDialogVisible.value = false;
                refreshTable();
            } catch (error: any) {
                ElMessage.error('修改用户信息失败');
            }
        }
    });
};

// 确认删除弹窗
const confirmDelete = (row: any) => {
    ElMessageBox.confirm(`是否确认删除用户 ${row.username}?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(() => {
        handleDelete(row);  // 用户确认后执行删除操作
    }).catch(() => {
        ElMessage.info('已取消删除');
    });
};

// 删除单个用户
const handleDelete = async (row: any) => {
    try {
        await apiInstance.rmUser(row.username);  // 调用 rmUser API
        ElMessage.success(`用户 ${row.username} 删除成功`);
        refreshTable(); // 删除成功后刷新表格
    } catch (error) {
        ElMessage.error('删除用户失败');
    }
};

// 删除选中用户
const handleDeleteSelected = () => {
    if (selectedRows.value.length === 0) {
        ElMessage.warning('请选择要删除的用户');
        return;
    }
    ElMessage.success('删除成功');
};

</script>

  
<style scoped>
.user-list {
    width: auto;
    overflow: auto;
    /* min-height: 650px; */
    /* height: 100vh; */
    max-width: 100%;
}

.user-table{
    
}

.header {
    display: flex;
    flex-direction: column;
    width: 100%;
    margin-bottom: 20px;
}

.header-title {
    width: 100%;
    padding-left: 0px;
    font-size: 24px;
    font-weight: bold;
}

.header-button {
    width: 100%;
    display: flex;
    margin-top: 20px;
}

.header-button .el-button {
    width: 100px;
    height: 30px;
    display: flex;
    justify-content: center;
}

.table-part {
    overflow: auth;
    width: 100%;
    height: 100%;
    padding-left: 1px;
    /* 外边距设定值后列自动扩大问题 */
    box-sizing: border-box;
}
</style>