<template>
    <div class="operation-permission-container">
        <el-row :gutter="20">
            <!-- 左侧：用户列表 -->
            <el-col :span="8">
                <el-card class="user-card">
                    <template #header>
                        <div class="card-header">
                            <span class="card-title">用户列表</span>
                            <el-tag type="success" size="small" style="margin-left: 10px;">
                                用户专属权限
                            </el-tag>
                        </div>
                    </template>

                    <el-table
                        :data="paginatedUserList"
                        highlight-current-row
                        @current-change="handleUserChange"
                        v-loading="userLoading"
                        style="width: 100%"
                        max-height="500"
                    >
                        <el-table-column prop="name" label="用户名称" width="120" />
                        <el-table-column prop="mobile" label="手机号" />
                        <el-table-column prop="roleId" label="角色ID" width="80" />
                    </el-table>

                    <!-- 分页器 -->
                    <div style="margin-top: 15px; text-align: center">
                        <el-pagination
                            v-model:current-page="pagination.currentPage"
                            v-model:page-size="pagination.pageSize"
                            :page-sizes="[10, 20, 50, 100]"
                            :total="userList.length"
                            layout="total, sizes, prev, pager, next"
                            @size-change="handleSizeChange"
                            @current-change="handleCurrentChange"
                        />
                    </div>
                </el-card>
            </el-col>

            <!-- 右侧：用户权限分配 -->
            <el-col :span="16">
                <el-card class="permission-card">
                    <template #header>
                        <div class="card-header">
                            <span class="card-title">
                                {{ currentUser ? `${currentUser.name} - 操作权限分配` : '请选择用户' }}
                            </span>
                            <el-tag type="success" size="small" style="margin-left: 10px;">
                                用户ID: {{ currentUser ? currentUser.id : '-' }}
                            </el-tag>
                            <el-button
                                type="primary"
                                size="small"
                                @click="handleSaveUserPermissions"
                                :disabled="!currentUser"
                                :loading="saveLoading"
                                style="margin-left: 10px;"
                            >
                                保存用户权限
                            </el-button>
                            <el-button
                                type="danger"
                                size="small"
                                @click="handleClearUserPermissions"
                                :disabled="!currentUser"
                                :loading="clearLoading"
                                style="margin-left: 10px;"
                            >
                                清空用户权限
                            </el-button>
                        </div>
                    </template>

                    <div v-if="currentUser" v-loading="permissionLoading">
                        <el-alert
                            title="用户专属操作权限管理"
                            type="info"
                            :closable="false"
                            style="margin-bottom: 20px"
                        >
                            <template #default>
                                <div>
                                    <p><strong>当前系统使用基于用户的操作权限管理</strong></p>
                                    <p>• 修改权限只影响当前选择的用户</p>
                                    <p>• 当前用户: <strong>{{ currentUser.name }}</strong> (ID: {{ currentUser.id }})</p>
                                    <p>• 角色ID: <strong>{{ currentUser.roleId }}</strong></p>
                                    <p>• 勾选操作权限后，该用户可以执行相应的按钮操作（新增、编辑、删除等）</p>
                                </div>
                            </template>
                        </el-alert>

                        <el-tree
                            ref="userPermissionTreeRef"
                            :data="permissionTree"
                            show-checkbox
                            node-key="id"
                            :default-expand-all="true"
                            :props="treeProps"
                            :check-strictly="true"
                        >
                            <template #default="{ node, data }">
                                <span class="tree-node">
                                    <el-icon v-if="data.icon" style="margin-right: 5px">
                                        <component :is="data.icon" />
                                    </el-icon>
                                    <span>{{ data.label }}</span>
                                </span>
                            </template>
                        </el-tree>
                    </div>
                </el-card>
            </el-col>
        </el-row>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
    getUserList,
    getMenuTree,
    getUserMenuIds,
    assignUserMenus,
    clearUserMenus,
} from '@/api/permission.js';
import usePermissionStore from '@/store/permission.js';

// 用户相关数据
const userLoading = ref(false);
const userList = ref([]);
const currentUser = ref(null);

// 分页数据
const pagination = reactive({
    currentPage: 1,
    pageSize: 10,
});

// 计算分页后的用户列表
const paginatedUserList = computed(() => {
    const start = (pagination.currentPage - 1) * pagination.pageSize;
    const end = start + pagination.pageSize;
    return userList.value.slice(start, end);
});

// 权限相关数据
const permissionLoading = ref(false);
const saveLoading = ref(false);
const clearLoading = ref(false);
const permissionTree = ref([]);
const userPermissionTreeRef = ref(null);
const treeProps = {
    children: 'children',
    label: 'label',
};

// 初始化
onMounted(() => {
    loadUserList();
});

// 加载用户列表
const loadUserList = async () => {
    userLoading.value = true;
    try {
        const res = await getUserList();
        if (res.code === 200) {
            userList.value = res.data || [];
        }
    } catch (error) {
        console.error('加载用户列表失败:', error);
        ElMessage.error('加载用户列表失败');
    } finally {
        userLoading.value = false;
    }
};

// 用户选择改变
const handleUserChange = async (row) => {
    if (!row) return;
    

    currentUser.value = row;
    await loadPermissionTree();
    await loadUserPermissions(row.id);
};

// 加载用户已分配的权限
const loadUserPermissions = async (userId) => {

    try {
        const res = await getUserMenuIds(userId);

        if (res.code === 200) {
            const menuIds = res.data || [];

            // 设置权限树选中状态
            await nextTick();
            if (userPermissionTreeRef.value) {
                userPermissionTreeRef.value.setCheckedKeys(menuIds);

            }
        }
    } catch (error) {
        console.error('加载用户权限失败:', error);
        ElMessage.error('加载用户权限失败');
    }
};

// 保存用户权限
const handleSaveUserPermissions = async () => {
    if (!currentUser.value) {
        ElMessage.warning('请先选择用户');
        return;
    }

    // 确认对话框
    try {
        await ElMessageBox.confirm(
            `您即将为用户 ${currentUser.value.name} (ID: ${currentUser.value.id}) 设置操作权限。\n\n这将只影响当前选择的用户。\n\n确定要继续吗？`,
            '确认用户权限修改',
            {
                confirmButtonText: '确定修改',
                cancelButtonText: '取消',
                type: 'warning',
                dangerouslyUseHTMLString: false
            }
        );
    } catch {
        return;
    }

    // 获取选中的节点
    const checkedKeys = userPermissionTreeRef.value.getCheckedKeys();
    const halfCheckedKeys = userPermissionTreeRef.value.getHalfCheckedKeys();
    const allKeys = [...checkedKeys, ...halfCheckedKeys];

    const saveData = {
        userId: currentUser.value.id,
        menuIds: allKeys,
    };

    saveLoading.value = true;
    try {
        const res = await assignUserMenus(saveData);

        if (res.code === 200) {
            ElMessage.success(`用户 ${currentUser.value.name} 的操作权限保存成功！`);

            // 权限保存成功后，刷新权限数据
            try {
                const permissionStore = usePermissionStore();
                await permissionStore.refreshPermissions();
                ElMessage.success('权限已保存并刷新成功！');

            } catch (error) {
                console.error('刷新权限失败:', error);
                ElMessage.warning('权限已保存，但刷新失败，请手动刷新页面');
            }
        } else {
            ElMessage.error(res.msg || '保存失败');
            console.error('用户权限保存失败:', res);
        }
    } catch (error) {
        console.error('保存用户权限失败:', error);
        ElMessage.error('保存失败');
    } finally {
        saveLoading.value = false;
    }
};

// 清空用户权限
const handleClearUserPermissions = async () => {
    if (!currentUser.value) {
        ElMessage.warning('请先选择用户');
        return;
    }

    // 确认对话框
    try {
        await ElMessageBox.confirm(
            `您即将清空用户 ${currentUser.value.name} (ID: ${currentUser.value.id}) 的所有权限。\n\n清空后，该用户将无法执行任何操作。\n\n确定要继续吗？`,
            '确认清空用户权限',
            {
                confirmButtonText: '确定清空',
                cancelButtonText: '取消',
                type: 'warning',
                dangerouslyUseHTMLString: false
            }
        );
    } catch {
        return;
    }

    clearLoading.value = true;
    try {
        const res = await clearUserMenus(currentUser.value.id);

        if (res.code === 200) {
            ElMessage.success(`用户 ${currentUser.value.name} 的权限已清空！`);

            // 重新加载用户权限（显示空权限）
            await loadUserPermissions(currentUser.value.id);
            
            // 权限清空后，刷新权限数据
            try {
                const permissionStore = usePermissionStore();
                await permissionStore.refreshPermissions();
                ElMessage.success('权限已清空并刷新成功！');

            } catch (error) {
                console.error('刷新权限失败:', error);
                ElMessage.warning('权限已清空，但刷新失败，请手动刷新页面');
            }
        } else {
            ElMessage.error(res.msg || '清空失败');
            console.error('用户权限清空失败:', res);
        }
    } catch (error) {
        console.error('清空用户权限失败:', error);
        ElMessage.error('清空失败');
    } finally {
        clearLoading.value = false;
    }
};

// 加载权限树（包含所有菜单和按钮）
const loadPermissionTree = async () => {
    permissionLoading.value = true;
    try {
        const res = await getMenuTree();
        if (res.code === 200) {
            permissionTree.value = res.data;
        }
    } catch (error) {
        console.error('加载权限树失败:', error);
        ElMessage.error('加载权限树失败');
    } finally {
        permissionLoading.value = false;
    }
};

// 分页处理
const handleSizeChange = (size) => {
    pagination.pageSize = size;
    pagination.currentPage = 1;
};

const handleCurrentChange = (page) => {
    pagination.currentPage = page;
};
</script>

<style scoped>
.operation-permission-container {
    padding: 20px;
}

.card-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.card-title {
    font-weight: bold;
    font-size: 16px;
}

.tree-node {
    display: flex;
    align-items: center;
}

.user-card,
.permission-card {
    height: 100%;
}
</style>