<template>
  <div class="role-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>角色管理</h2>
      <div class="header-actions">
        <button class="btn btn-primary" @click="addRole">添加角色</button>
        <button class="btn btn-secondary" @click="refreshRoles">刷新</button>
      </div>
    </div>
    
    <!-- 角色列表 -->
    <div class="role-list">
      <el-table
        :data="roles"
        style="width: 100%"
        border
        stripe
      >
        <el-table-column
          prop="id"
          label="ID"
          width="80"
          align="center"
        />
        <el-table-column
          prop="name"
          label="角色名称"
          min-width="150"
        />
        <el-table-column
          prop="description"
          label="角色描述"
          min-width="300"
        />
        <el-table-column
          prop="createTime"
          label="创建时间"
          width="180"
          align="center"
        />
        <el-table-column
          prop="userCount"
          label="用户数量"
          width="100"
          align="center"
        />
        <el-table-column
          label="操作"
          width="200"
          align="center"
        >
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              @click="editRole(scope.row)"
              style="margin-right: 8px"
            >
              编辑
            </el-button>
            <el-button
              type="warning"
              size="small"
              @click="managePermissions(scope.row)"
              style="margin-right: 8px"
            >
              权限
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="deleteRole(scope.row.id)"
              :disabled="scope.row.name === '管理员'"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    
    <!-- 分页 -->
    <div v-if="roles.length > 0" class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="roles.length"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    
    <!-- 角色表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEditing ? '编辑角色' : '添加角色'"
      width="500px"
    >
      <el-form
        :model="roleForm"
        :rules="rules"
        ref="roleFormRef"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input
            v-model="roleForm.description"
            type="textarea"
            rows="3"
            placeholder="请输入角色描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">保存</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 权限管理对话框 -->
    <el-dialog
      v-model="permissionDialogVisible"
      title="权限管理"
      width="600px"
    >
      <div class="permission-management">
        <h3>{{ selectedRole.name }} - 权限设置</h3>
        <el-tree
          :data="permissionTree"
          show-checkbox
          node-key="id"
          default-expand-all
          v-model:checkedKeys="checkedPermissions"
          @check="handlePermissionCheck"
        >
          <template #default="{ node }">
            <span class="permission-node">
              {{ node.label }}
            </span>
          </template>
        </el-tree>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="permissionDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="savePermissions">保存权限</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'RoleManagement',
  data() {
    return {
      // 角色列表
      roles: [
        {
          id: 1,
          name: '管理员',
          description: '系统管理员，拥有所有权限',
          createTime: '2024-01-01 00:00:00',
          userCount: 2
        },
        {
          id: 2,
          name: '操作员',
          description: '普通操作员，拥有基本操作权限',
          createTime: '2024-01-01 00:00:00',
          userCount: 15
        },
        {
          id: 3,
          name: '查看员',
          description: '只读权限，只能查看数据',
          createTime: '2024-01-01 00:00:00',
          userCount: 8
        }
      ],
      // 分页信息
      currentPage: 1,
      pageSize: 10,
      // 对话框可见性
      dialogVisible: false,
      permissionDialogVisible: false,
      // 是否为编辑模式
      isEditing: false,
      // 角色表单
      roleForm: {
        id: '',
        name: '',
        description: ''
      },
      // 选中的角色
      selectedRole: {},
      // 表单验证规则
      rules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 2, max: 50, message: '角色名称长度应在2-50个字符之间', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 5, message: '角色描述长度至少为5个字符', trigger: 'blur' }
        ]
      },
      // 权限树
      permissionTree: [
        {
          id: 1,
          label: '系统管理',
          children: [
            {
              id: 11,
              label: '用户管理'
            },
            {
              id: 12,
              label: '角色管理'
            },
            {
              id: 13,
              label: '权限管理'
            },
            {
              id: 14,
              label: '系统设置'
            }
          ]
        },
        {
          id: 2,
          label: '拖轮管理',
          children: [
            {
              id: 21,
              label: '拖轮列表'
            },
            {
              id: 22,
              label: '拖轮详情'
            },
            {
              id: 23,
              label: '拖轮状态'
            },
            {
              id: 24,
              label: '拖轮维护'
            }
          ]
        },
        {
          id: 3,
          label: '任务管理',
          children: [
            {
              id: 31,
              label: '任务列表'
            },
            {
              id: 32,
              label: '任务分配'
            },
            {
              id: 33,
              label: '任务执行'
            },
            {
              id: 34,
              label: '任务统计'
            }
          ]
        },
        {
          id: 4,
          label: '报警管理',
          children: [
            {
              id: 41,
              label: '报警列表'
            },
            {
              id: 42,
              label: '报警处理'
            },
            {
              id: 43,
              label: '报警统计'
            }
          ]
        },
        {
          id: 5,
          label: '报表管理',
          children: [
            {
              id: 51,
              label: '运行报表'
            },
            {
              id: 52,
              label: '任务报表'
            },
            {
              id: 53,
              label: '报警报表'
            }
          ]
        }
      ],
      // 选中的权限
      checkedPermissions: []
    }
  },
  mounted() {
    // 初始化加载角色
    this.loadRoles()
  },
  methods: {
    // 加载角色
    loadRoles() {
      // 实际项目中，这里应该调用后端API获取角色列表
      // 模拟API调用
      setTimeout(() => {
        console.log('Roles loaded successfully')
      }, 500)
    },
    
    // 刷新角色
    refreshRoles() {
      this.loadRoles()
      this.$message.success('角色列表已刷新')
    },
    
    // 添加角色
    addRole() {
      this.roleForm = {
        id: '',
        name: '',
        description: ''
      }
      this.isEditing = false
      this.dialogVisible = true
    },
    
    // 编辑角色
    editRole(role) {
      this.roleForm = { ...role }
      this.isEditing = true
      this.dialogVisible = true
    },
    
    // 删除角色
    deleteRole(id) {
      this.$confirm('确定要删除此角色吗？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const index = this.roles.findIndex(role => role.id === id)
        if (index !== -1) {
          this.roles.splice(index, 1)
          this.$message.success('角色已删除')
        }
      }).catch(() => {
        // 取消删除
      })
    },
    
    // 提交表单
    submitForm() {
      this.$refs.roleFormRef.validate((valid) => {
        if (valid) {
          if (this.isEditing) {
            // 编辑角色
            const index = this.roles.findIndex(role => role.id === this.roleForm.id)
            if (index !== -1) {
              this.roles[index] = { ...this.roleForm }
              this.$message.success('角色已更新')
            }
          } else {
            // 添加角色
            const newRole = {
              ...this.roleForm,
              id: this.roles.length + 1,
              createTime: new Date().toLocaleString('zh-CN'),
              userCount: 0
            }
            this.roles.push(newRole)
            this.$message.success('角色已添加')
          }
          this.dialogVisible = false
        } else {
          return false
        }
      })
    },
    
    // 管理权限
    managePermissions(role) {
      this.selectedRole = { ...role }
      // 模拟加载角色权限
      this.checkedPermissions = this.getRolePermissions(role.id)
      this.permissionDialogVisible = true
    },
    
    // 获取角色权限
    getRolePermissions(roleId) {
      // 实际项目中，这里应该调用后端API获取角色权限
      // 模拟数据
      if (roleId === 1) {
        // 管理员拥有所有权限
        return [1, 11, 12, 13, 14, 2, 21, 22, 23, 24, 3, 31, 32, 33, 34, 4, 41, 42, 43, 5, 51, 52, 53]
      } else if (roleId === 2) {
        // 操作员拥有部分权限
        return [2, 21, 22, 23, 3, 31, 32, 33, 4, 41, 42]
      } else {
        // 查看员只拥有查看权限
        return [21, 22, 23, 31, 41, 51, 52, 53]
      }
    },
    
    // 处理权限选择
    handlePermissionCheck() {
      // 权限选择逻辑
    },
    
    // 保存权限
    savePermissions() {
      // 实际项目中，这里应该调用后端API保存角色权限
      // 模拟保存
      setTimeout(() => {
        this.$message.success('权限已保存')
        this.permissionDialogVisible = false
      }, 500)
    },
    
    // 分页处理
    handleSizeChange(size) {
      this.pageSize = size
    },
    
    handleCurrentChange(current) {
      this.currentPage = current
    }
  }
}
</script>

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

/* 页面标题 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #e2e8f0;
}

.page-header h2 {
  margin: 0;
  color: #1e293b;
  font-size: 24px;
  font-weight: 600;
}

.header-actions {
  display: flex;
  gap: 12px;
}

/* 角色列表 */
.role-list {
  margin-bottom: 24px;
}

/* 分页 */
.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 30px;
}

/* 权限管理 */
.permission-management {
  margin-bottom: 20px;
}

.permission-management h3 {
  margin: 0 0 20px 0;
  color: #1e293b;
  font-size: 18px;
  font-weight: 600;
}

.permission-node {
  font-size: 14px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .header-actions {
    width: 100%;
    justify-content: flex-start;
  }
  
  .pagination {
    justify-content: center;
  }
}
</style>