<template>
  <Page
    description="管理系统角色权限信息"
    title="角色管理"
  >
    <div class="flex flex-col gap-4">
      <!-- 搜索表单 -->
      <el-card>
        <el-form :model="searchForm" inline>
          <el-form-item label="角色名称">
            <el-input
              v-model="searchForm.keyword"
              placeholder="请输入角色名称"
              clearable
              @keyup.enter="handleSearch"
            />
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
              <el-option label="正常" :value="1" />
              <el-option label="禁用" :value="0" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <Icon icon="ep:search" class="mr-1" />
              搜索
            </el-button>
            <el-button @click="handleReset">
              <Icon icon="ep:refresh" class="mr-1" />
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 操作按钮和数据表格 -->
      <el-card>
        <div class="mb-4">
          <el-button type="primary" @click="handleAdd">
            <Icon icon="ep:plus" class="mr-1" />
            新增角色
          </el-button>
          <el-button
            type="danger"
            :disabled="!selectedRows.length"
            @click="handleBatchDelete"
          >
            <Icon icon="ep:delete" class="mr-1" />
            批量删除
          </el-button>
        </div>

    <!-- 数据表格 -->
    <el-table
      v-loading="loading"
      :data="tableData"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="roleId" label="ID" width="80" />
      <el-table-column prop="roleName" label="角色名称" min-width="150" />
      <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
      <el-table-column prop="rules" label="权限规则" min-width="200">
        <template #default="{ row }">
          <el-tag v-if="row.rules === '*'" type="danger">超级管理员</el-tag>
          <el-tag v-else-if="!row.rules" type="info">无权限</el-tag>
          <el-tooltip v-else :content="row.rules" placement="top">
            <el-tag type="primary">{{ getPermissionCount(row.rules) }}个权限</el-tag>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="80">
        <template #default="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'danger'">
            {{ row.status === 1 ? '正常' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180">
        <template #default="{ row }">
          {{ formatTime(row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="280" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="handleEdit(row)">
            编辑
          </el-button>
          <el-button type="warning" size="small" @click="handleSetPermission(row)">
            设置权限
          </el-button>
          <el-button type="info" size="small" @click="handleViewUsers(row)">
            查看用户
          </el-button>
          <el-button
            type="danger"
            size="small"
            @click="handleDelete(row)"
            :disabled="row.roleId === 1"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-wrapper">
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.limit"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="formData.roleName" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="3"
            placeholder="请输入角色描述"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 权限设置对话框 -->
    <el-dialog
      v-model="permissionDialogVisible"
      title="设置权限"
      width="800px"
      @close="handlePermissionDialogClose"
    >
      <div class="permission-content">
        <div class="permission-header">
          <span>为角色 "{{ currentRole?.roleName }}" 设置权限</span>
          <div class="permission-actions">
            <el-button size="small" @click="handleExpandAll">展开全部</el-button>
            <el-button size="small" @click="handleCollapseAll">收起全部</el-button>
            <el-button size="small" @click="handleCheckAll">全选</el-button>
            <el-button size="small" @click="handleUncheckAll">取消全选</el-button>
          </div>
        </div>
        <el-tree
          ref="permissionTreeRef"
          :data="permissionTreeData"
          :props="treeProps"
          show-checkbox
          node-key="id"
          :default-checked-keys="checkedPermissions"
          :default-expand-all="false"
          class="permission-tree"
        >
          <template #default="{ node, data }">
            <div class="tree-node">
              <Icon :icon="data.icon || 'ep:folder'" class="mr-2" />
              <span>{{ data.title }}</span>
              <el-tag v-if="data.type" size="small" class="ml-2">
                {{ getNodeTypeText(data.type) }}
              </el-tag>
            </div>
          </template>
        </el-tree>
      </div>
      <template #footer>
        <el-button @click="permissionDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSavePermission" :loading="permissionLoading">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 用户列表对话框 -->
    <el-dialog
      v-model="userDialogVisible"
      title="角色用户列表"
      width="800px"
    >
      <div class="user-content">
        <div class="user-header">
          <span>角色 "{{ currentRole?.roleName }}" 的用户列表</span>
          <el-button type="primary" size="small" @click="handleAddUser">
            <Icon icon="ep:plus" class="mr-1" />
            添加用户
          </el-button>
        </div>
        <el-table v-loading="userLoading" :data="roleUsers">
          <el-table-column prop="userId" label="用户ID" width="80" />
          <el-table-column prop="username" label="用户名" min-width="120" />
          <el-table-column prop="realName" label="真实姓名" min-width="120" />
          <el-table-column prop="mobile" label="手机号" min-width="120" />
          <el-table-column prop="email" label="邮箱" min-width="150" />
          <el-table-column prop="status" label="状态" width="80">
            <template #default="{ row }">
              <el-tag :type="row.status === 1 ? 'success' : 'danger'">
                {{ row.status === 1 ? '正常' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100">
            <template #default="{ row }">
              <el-button
                type="danger"
                size="small"
                @click="handleRemoveUser(row)"
              >
                移除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>

    <!-- 添加用户对话框 -->
    <el-dialog
      v-model="addUserDialogVisible"
      title="添加用户到角色"
      width="600px"
    >
      <el-form :model="addUserForm" label-width="100px">
        <el-form-item label="选择用户">
          <el-select
            v-model="addUserForm.userIds"
            multiple
            placeholder="请选择用户"
            style="width: 100%"
            filterable
            remote
            :remote-method="searchUsers"
            :loading="searchUserLoading"
          >
            <el-option
              v-for="user in availableUsers"
              :key="user.userId"
              :label="`${user.username} (${user.realName})`"
              :value="user.userId"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addUserDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveAddUser" :loading="addUserLoading">
          确定
        </el-button>
      </template>
    </el-dialog>
    </div>
  </Page>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue';
import { ElMessage, ElMessageBox, type FormInstance, type ElTree } from 'element-plus';
import { Icon } from '@iconify/vue';
import { Page } from '@vben/common-ui';
import {
  getRoleListApi,
  createRoleApi,
  updateRoleApi,
  deleteRoleApi,
  batchDeleteRolesApi,
  getRoleUsersApi,
  addRoleUserApi,
  removeRoleUserApi,
  getPermissionTreeApi,
  type Role,
  type CreateRoleParams,
  type UpdateRoleParams,
  type PermissionTreeNode,
} from '#/api/rbac';
import { getAdminListApi, type AdminUser } from '#/api/user';

// 响应式数据
const loading = ref(false);
const submitLoading = ref(false);
const permissionLoading = ref(false);
const userLoading = ref(false);
const addUserLoading = ref(false);
const searchUserLoading = ref(false);
const tableData = ref<Role[]>([]);
const selectedRows = ref<Role[]>([]);
const currentRole = ref<Role | null>(null);
const roleUsers = ref<AdminUser[]>([]);
const availableUsers = ref<AdminUser[]>([]);
const permissionTreeData = ref<PermissionTreeNode[]>([]);
const checkedPermissions = ref<string[]>([]);

// 搜索表单
const searchForm = reactive({
  keyword: '',
  status: undefined as number | undefined,
});

// 分页
const pagination = reactive({
  page: 1,
  limit: 20,
  total: 0,
});

// 对话框
const dialogVisible = ref(false);
const permissionDialogVisible = ref(false);
const userDialogVisible = ref(false);
const addUserDialogVisible = ref(false);
const isEdit = ref(false);
const formRef = ref<FormInstance>();
const permissionTreeRef = ref<InstanceType<typeof ElTree>>();

// 表单数据
const formData = reactive<CreateRoleParams & { roleId?: number }>({
  roleName: '',
  description: '',
  status: 1,
});

// 添加用户表单
const addUserForm = reactive({
  userIds: [] as number[],
});

// 树形组件配置
const treeProps = {
  children: 'children',
  label: 'title',
};

// 表单验证规则
const formRules = {
  roleName: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 50, message: '角色名称长度在 2 到 50 个字符', trigger: 'blur' },
  ],
  description: [
    { max: 200, message: '描述不能超过 200 个字符', trigger: 'blur' },
  ],
};

// 计算属性
const dialogTitle = computed(() => (isEdit.value ? '编辑角色' : '新增角色'));

// 方法
const formatTime = (timestamp: number) => {
  if (!timestamp) return '-';
  return new Date(timestamp * 1000).toLocaleString();
};

const getPermissionCount = (rules: string) => {
  if (!rules || rules === '*') return 0;
  try {
    const ruleArray = rules.split(',').filter(Boolean);
    return ruleArray.length;
  } catch {
    return 0;
  }
};

const getNodeTypeText = (type: string) => {
  const map = {
    menu: '菜单',
    button: '按钮',
    api: '接口',
  };
  return map[type as keyof typeof map] || type;
};

const loadData = async () => {
  loading.value = true;
  try {
    const params = {
      page: pagination.page,
      limit: pagination.limit,
      keyword: searchForm.keyword || undefined,
      status: searchForm.status,
    };
    const result = await getRoleListApi(params);
    tableData.value = result.list;
    pagination.total = result.total;
  } catch (error) {
    ElMessage.error('加载数据失败');
  } finally {
    loading.value = false;
  }
};

const loadPermissionTree = async () => {
  try {
    const result = await getPermissionTreeApi();
    permissionTreeData.value = result;
  } catch (error) {
    ElMessage.error('加载权限树失败');
  }
};

const loadRoleUsers = async (roleId: number) => {
  userLoading.value = true;
  try {
    const result = await getRoleUsersApi(roleId);
    roleUsers.value = result;
  } catch (error) {
    ElMessage.error('加载角色用户失败');
  } finally {
    userLoading.value = false;
  }
};

const searchUsers = async (keyword: string) => {
  if (!keyword) {
    availableUsers.value = [];
    return;
  }
  
  searchUserLoading.value = true;
  try {
    const result = await getAdminListApi({
      page: 1,
      limit: 20,
      keyword,
    });
    availableUsers.value = result.list;
  } catch (error) {
    ElMessage.error('搜索用户失败');
  } finally {
    searchUserLoading.value = false;
  }
};

const handleSearch = () => {
  pagination.page = 1;
  loadData();
};

const handleReset = () => {
  searchForm.keyword = '';
  searchForm.status = undefined;
  handleSearch();
};

const handleSizeChange = (size: number) => {
  pagination.limit = size;
  loadData();
};

const handleCurrentChange = (page: number) => {
  pagination.page = page;
  loadData();
};

const handleSelectionChange = (selection: Role[]) => {
  selectedRows.value = selection;
};

const handleAdd = () => {
  isEdit.value = false;
  resetForm();
  dialogVisible.value = true;
};

const handleEdit = (row: Role) => {
  isEdit.value = true;
  Object.assign(formData, {
    roleId: row.roleId,
    roleName: row.roleName,
    description: row.description,
    status: row.status,
  });
  dialogVisible.value = true;
};

const handleDelete = async (row: Role) => {
  if (row.roleId === 1) {
    ElMessage.warning('超级管理员角色不能删除');
    return;
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要删除角色 "${row.roleName}" 吗？`,
      '确认删除',
      {
        type: 'warning',
      }
    );
    await deleteRoleApi(row.roleId);
    ElMessage.success('删除成功');
    loadData();
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败');
    }
  }
};

const handleBatchDelete = async () => {
  const canDeleteRoles = selectedRows.value.filter(row => row.roleId !== 1);
  if (canDeleteRoles.length === 0) {
    ElMessage.warning('选中的角色中没有可删除的角色');
    return;
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${canDeleteRoles.length} 个角色吗？`,
      '确认删除',
      {
        type: 'warning',
      }
    );
    const roleIds = canDeleteRoles.map(row => row.roleId);
    await batchDeleteRoleApi(roleIds);
    ElMessage.success('删除成功');
    loadData();
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败');
    }
  }
};

const handleSetPermission = async (row: Role) => {
  currentRole.value = row;
  await loadPermissionTree();
  
  // 解析当前角色的权限
  if (row.rules && row.rules !== '*') {
    checkedPermissions.value = row.rules.split(',').filter(Boolean);
  } else {
    checkedPermissions.value = [];
  }
  
  permissionDialogVisible.value = true;
};

const handleViewUsers = async (row: Role) => {
  currentRole.value = row;
  await loadRoleUsers(row.roleId);
  userDialogVisible.value = true;
};

const handleAddUser = () => {
  addUserForm.userIds = [];
  availableUsers.value = [];
  addUserDialogVisible.value = true;
};

const handleRemoveUser = async (user: AdminUser) => {
  try {
    await ElMessageBox.confirm(
      `确定要将用户 "${user.username}" 从角色中移除吗？`,
      '确认移除',
      {
        type: 'warning',
      }
    );
    await removeRoleUserApi(currentRole.value!.roleId, user.userId);
    ElMessage.success('移除成功');
    loadRoleUsers(currentRole.value!.roleId);
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('移除失败');
    }
  }
};

const handleSaveAddUser = async () => {
  if (!addUserForm.userIds.length) {
    ElMessage.warning('请选择要添加的用户');
    return;
  }
  
  addUserLoading.value = true;
  try {
    await addRoleUsersApi(currentRole.value!.roleId, addUserForm.userIds);
    ElMessage.success('添加成功');
    addUserDialogVisible.value = false;
    loadRoleUsers(currentRole.value!.roleId);
  } catch (error) {
    ElMessage.error('添加失败');
  } finally {
    addUserLoading.value = false;
  }
};

const handleExpandAll = () => {
  const tree = permissionTreeRef.value;
  if (tree) {
    const expandAll = (nodes: PermissionTreeNode[]) => {
      nodes.forEach(node => {
        tree.setExpanded(node.id, true);
        if (node.children) {
          expandAll(node.children);
        }
      });
    };
    expandAll(permissionTreeData.value);
  }
};

const handleCollapseAll = () => {
  const tree = permissionTreeRef.value;
  if (tree) {
    const collapseAll = (nodes: PermissionTreeNode[]) => {
      nodes.forEach(node => {
        tree.setExpanded(node.id, false);
        if (node.children) {
          collapseAll(node.children);
        }
      });
    };
    collapseAll(permissionTreeData.value);
  }
};

const handleCheckAll = () => {
  const tree = permissionTreeRef.value;
  if (tree) {
    const getAllNodeIds = (nodes: PermissionTreeNode[]): string[] => {
      let ids: string[] = [];
      nodes.forEach(node => {
        ids.push(node.id);
        if (node.children) {
          ids = ids.concat(getAllNodeIds(node.children));
        }
      });
      return ids;
    };
    const allIds = getAllNodeIds(permissionTreeData.value);
    tree.setCheckedKeys(allIds);
  }
};

const handleUncheckAll = () => {
  const tree = permissionTreeRef.value;
  if (tree) {
    tree.setCheckedKeys([]);
  }
};

const handleSavePermission = async () => {
  const tree = permissionTreeRef.value;
  if (!tree || !currentRole.value) return;
  
  permissionLoading.value = true;
  try {
    const checkedKeys = tree.getCheckedKeys() as string[];
    const halfCheckedKeys = tree.getHalfCheckedKeys() as string[];
    const allCheckedKeys = [...checkedKeys, ...halfCheckedKeys];
    
    await setRolePermissionApi(currentRole.value.roleId, allCheckedKeys);
    ElMessage.success('权限设置成功');
    permissionDialogVisible.value = false;
    loadData();
  } catch (error) {
    ElMessage.error('权限设置失败');
  } finally {
    permissionLoading.value = false;
  }
};

const handleSubmit = async () => {
  if (!formRef.value) return;
  
  try {
    await formRef.value.validate();
    submitLoading.value = true;
    
    if (isEdit.value) {
      const updateData: UpdateRoleParams = {
        roleId: formData.roleId!,
        roleName: formData.roleName,
        description: formData.description,
        status: formData.status,
      };
      await updateRoleApi(updateData);
      ElMessage.success('更新成功');
    } else {
      const createData: CreateRoleParams = {
        roleName: formData.roleName,
        description: formData.description,
        status: formData.status,
      };
      await createRoleApi(createData);
      ElMessage.success('创建成功');
    }
    
    dialogVisible.value = false;
    loadData();
  } catch (error) {
    ElMessage.error(isEdit.value ? '更新失败' : '创建失败');
  } finally {
    submitLoading.value = false;
  }
};

const handleDialogClose = () => {
  formRef.value?.resetFields();
  resetForm();
};

const handlePermissionDialogClose = () => {
  currentRole.value = null;
  checkedPermissions.value = [];
  permissionTreeData.value = [];
};

const resetForm = () => {
  Object.assign(formData, {
    roleId: undefined,
    roleName: '',
    description: '',
    status: 1,
  });
};

// 生命周期
onMounted(() => {
  loadData();
});
</script>

<style scoped>
.role-page {
  padding: 20px;
}

.search-form {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.action-buttons {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.permission-content {
  max-height: 500px;
  overflow-y: auto;
}

.permission-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.permission-actions {
  display: flex;
  gap: 8px;
}

.permission-tree {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 10px;
}

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

.user-content {
  max-height: 500px;
  overflow-y: auto;
}

.user-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}
</style>