<template>
  <div class="role-management">
    <div class="page-header">
      <h2>角色管理</h2>
      <el-button 
        type="primary" 
        @click="showAddDialog = true"
        v-if="hasPermission('role:create')"
      >
        <el-icon><Plus /></el-icon>
        添加角色
      </el-button>
    </div>

    <!-- 角色列表 -->
    <div class="table-container">
      <el-table 
        :data="roleList" 
        v-loading="loading"
        stripe
        border
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="角色名称" width="120" />
        <el-table-column prop="code" label="角色代码" width="120" />
        <el-table-column prop="description" label="描述" min-width="200" />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.status === 'active' ? 'success' : 'danger'">
              {{ row.status === 'active' ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="160" />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button 
              size="small" 
              @click="handleViewPermissions(row)"
              v-if="hasPermission('role:view')"
            >
              查看权限
            </el-button>
            <el-button 
              size="small" 
              type="primary" 
              @click="handleEdit(row)"
              v-if="hasPermission('role:edit')"
            >
              编辑
            </el-button>
            <el-button 
              size="small" 
              type="warning" 
              @click="handleSetPermissions(row)"
              v-if="hasPermission('role:permission')"
            >
              设置权限
            </el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click="handleDelete(row)"
              v-if="hasPermission('role:delete') && !row.isSystem"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 添加/编辑角色对话框 -->
    <el-dialog 
      v-model="showAddDialog" 
      :title="editingRole ? '编辑角色' : '添加角色'"
      width="500px"
    >
      <el-form 
        :model="roleForm" 
        :rules="roleFormRules" 
        ref="roleFormRef"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" />
        </el-form-item>
        <el-form-item label="角色代码" prop="code">
          <el-input v-model="roleForm.code" :disabled="!!editingRole" />
        </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-item label="状态" prop="status">
          <el-radio-group v-model="roleForm.status">
            <el-radio label="active">启用</el-radio>
            <el-radio label="inactive">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showAddDialog = false">取消</el-button>
        <el-button type="primary" @click="handleSaveRole" :loading="saving">
          {{ editingRole ? '更新' : '添加' }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 权限设置对话框 -->
    <el-dialog 
      v-model="showPermissionDialog" 
      title="设置角色权限"
      width="800px"
    >
      <div class="permission-setting" v-if="currentRole">
        <div class="role-info">
          <h4>角色：{{ currentRole.name }}</h4>
          <p>{{ currentRole.description }}</p>
        </div>
        
        <el-tree
          ref="permissionTreeRef"
          :data="permissionTree"
          :props="treeProps"
          show-checkbox
          node-key="id"
          :default-checked-keys="selectedPermissions"
          @check="handlePermissionCheck"
        />
      </div>
      
      <template #footer>
        <el-button @click="showPermissionDialog = false">取消</el-button>
        <el-button type="primary" @click="handleSavePermissions" :loading="saving">
          保存权限
        </el-button>
      </template>
    </el-dialog>

    <!-- 查看权限对话框 -->
    <el-dialog 
      v-model="showViewPermissionDialog" 
      title="角色权限详情"
      width="600px"
    >
      <div class="permission-view" v-if="viewingRole">
        <div class="role-info">
          <h4>角色：{{ viewingRole.name }}</h4>
          <p>{{ viewingRole.description }}</p>
        </div>
        
        <div class="permission-list">
          <h5>拥有权限：</h5>
          <div class="permission-tags">
            <el-tag 
              v-for="permission in viewingRole.permissions" 
              :key="permission.id"
              class="permission-tag"
            >
              {{ permission.name }}
            </el-tag>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { usePermissionStore } from '@/stores/permission'

const permissionStore = usePermissionStore()

// 权限检查
const hasPermission = (permission) => {
  return permissionStore.hasPermission.value(permission)
}

// 响应式数据
const loading = ref(false)
const saving = ref(false)
const roleList = ref([])
const showAddDialog = ref(false)
const showPermissionDialog = ref(false)
const showViewPermissionDialog = ref(false)
const editingRole = ref(null)
const currentRole = ref(null)
const viewingRole = ref(null)
const selectedPermissions = ref([])

// 角色表单
const roleForm = reactive({
  name: '',
  code: '',
  description: '',
  status: 'active'
})

// 表单验证规则
const roleFormRules = {
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入角色代码', trigger: 'blur' },
    { pattern: /^[a-zA-Z_][a-zA-Z0-9_]*$/, message: '角色代码只能包含字母、数字和下划线，且以字母或下划线开头', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入角色描述', trigger: 'blur' }
  ]
}

// 权限树配置
const treeProps = {
  children: 'children',
  label: 'name'
}

// 权限树数据
const permissionTree = ref([
  {
    id: 'user',
    name: '用户管理',
    children: [
      { id: 'user:view', name: '查看用户' },
      { id: 'user:create', name: '创建用户' },
      { id: 'user:edit', name: '编辑用户' },
      { id: 'user:delete', name: '删除用户' }
    ]
  },
  {
    id: 'role',
    name: '角色管理',
    children: [
      { id: 'role:view', name: '查看角色' },
      { id: 'role:create', name: '创建角色' },
      { id: 'role:edit', name: '编辑角色' },
      { id: 'role:delete', name: '删除角色' },
      { id: 'role:permission', name: '设置权限' }
    ]
  },
  {
    id: 'cattle',
    name: '牛只管理',
    children: [
      { id: 'cattle:view', name: '查看牛只' },
      { id: 'cattle:create', name: '添加牛只' },
      { id: 'cattle:edit', name: '编辑牛只' },
      { id: 'cattle:delete', name: '删除牛只' }
    ]
  },
  {
    id: 'trading',
    name: '交易管理',
    children: [
      { id: 'trading:view', name: '查看交易' },
      { id: 'trading:create', name: '创建交易' },
      { id: 'trading:edit', name: '编辑交易' },
      { id: 'trading:delete', name: '删除交易' }
    ]
  },
  {
    id: 'monitor',
    name: '监控管理',
    children: [
      { id: 'monitor:view', name: '查看监控' },
      { id: 'monitor:config', name: '配置监控' }
    ]
  },
  {
    id: 'system',
    name: '系统管理',
    children: [
      { id: 'system:config', name: '系统配置' },
      { id: 'system:log', name: '系统日志' },
      { id: 'system:backup', name: '数据备份' }
    ]
  }
])

// 方法
const loadRoleList = async () => {
  try {
    loading.value = true
    
    // 模拟API调用
    const response = await mockRoleAPI.getRoles()
    roleList.value = response.data
  } catch (error) {
    ElMessage.error('加载角色列表失败')
  } finally {
    loading.value = false
  }
}

const handleEdit = (role) => {
  editingRole.value = role
  Object.assign(roleForm, {
    name: role.name,
    code: role.code,
    description: role.description,
    status: role.status
  })
  showAddDialog.value = true
}

const handleDelete = async (role) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除角色 "${role.name}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await mockRoleAPI.deleteRole(role.id)
    ElMessage.success('删除成功')
    loadRoleList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const handleSetPermissions = async (role) => {
  currentRole.value = role
  
  // 获取角色当前权限
  try {
    const response = await mockRoleAPI.getRolePermissions(role.id)
    selectedPermissions.value = response.data.map(p => p.id)
  } catch (error) {
    ElMessage.error('获取角色权限失败')
    return
  }
  
  showPermissionDialog.value = true
}

const handleViewPermissions = async (role) => {
  try {
    const response = await mockRoleAPI.getRolePermissions(role.id)
    viewingRole.value = {
      ...role,
      permissions: response.data
    }
    showViewPermissionDialog.value = true
  } catch (error) {
    ElMessage.error('获取角色权限失败')
  }
}

const handlePermissionCheck = (data, checked) => {
  // 处理权限选择逻辑
}

const handleSaveRole = async () => {
  try {
    await roleFormRef.value.validate()
    
    saving.value = true
    
    if (editingRole.value) {
      await mockRoleAPI.updateRole(editingRole.value.id, roleForm)
      ElMessage.success('更新成功')
    } else {
      await mockRoleAPI.createRole(roleForm)
      ElMessage.success('添加成功')
    }
    
    showAddDialog.value = false
    resetRoleForm()
    loadRoleList()
  } catch (error) {
    ElMessage.error('保存失败')
  } finally {
    saving.value = false
  }
}

const handleSavePermissions = async () => {
  try {
    saving.value = true
    
    const checkedKeys = permissionTreeRef.value.getCheckedKeys()
    const halfCheckedKeys = permissionTreeRef.value.getHalfCheckedKeys()
    const allPermissions = [...checkedKeys, ...halfCheckedKeys]
    
    await mockRoleAPI.updateRolePermissions(currentRole.value.id, allPermissions)
    ElMessage.success('权限设置成功')
    showPermissionDialog.value = false
  } catch (error) {
    ElMessage.error('权限设置失败')
  } finally {
    saving.value = false
  }
}

const resetRoleForm = () => {
  Object.assign(roleForm, {
    name: '',
    code: '',
    description: '',
    status: 'active'
  })
  editingRole.value = null
}

// 模拟API
const mockRoleAPI = {
  async getRoles() {
    const mockData = [
      {
        id: 1,
        name: '超级管理员',
        code: 'super_admin',
        description: '系统超级管理员，拥有所有权限',
        status: 'active',
        isSystem: true,
        createdAt: '2025-01-01 00:00:00'
      },
      {
        id: 2,
        name: '管理员',
        code: 'admin',
        description: '系统管理员，拥有大部分管理权限',
        status: 'active',
        isSystem: false,
        createdAt: '2025-01-01 00:00:00'
      },
      {
        id: 3,
        name: '经理',
        code: 'manager',
        description: '业务经理，负责业务管理',
        status: 'active',
        isSystem: false,
        createdAt: '2025-01-01 00:00:00'
      },
      {
        id: 4,
        name: '操作员',
        code: 'operator',
        description: '日常操作员，负责数据录入和基础操作',
        status: 'active',
        isSystem: false,
        createdAt: '2025-01-01 00:00:00'
      },
      {
        id: 5,
        name: '查看者',
        code: 'viewer',
        description: '只读用户，只能查看数据',
        status: 'active',
        isSystem: false,
        createdAt: '2025-01-01 00:00:00'
      }
    ]
    
    return {
      success: true,
      data: mockData
    }
  },
  
  async createRole(roleData) {
    return { success: true }
  },
  
  async updateRole(id, roleData) {
    return { success: true }
  },
  
  async deleteRole(id) {
    return { success: true }
  },
  
  async getRolePermissions(roleId) {
    // 模拟不同角色的权限
    const permissionMap = {
      1: [ // 超级管理员
        { id: 'user:view', name: '查看用户' },
        { id: 'user:create', name: '创建用户' },
        { id: 'user:edit', name: '编辑用户' },
        { id: 'user:delete', name: '删除用户' },
        { id: 'role:view', name: '查看角色' },
        { id: 'role:create', name: '创建角色' },
        { id: 'role:edit', name: '编辑角色' },
        { id: 'role:delete', name: '删除角色' },
        { id: 'role:permission', name: '设置权限' }
      ],
      2: [ // 管理员
        { id: 'user:view', name: '查看用户' },
        { id: 'user:create', name: '创建用户' },
        { id: 'user:edit', name: '编辑用户' },
        { id: 'cattle:view', name: '查看牛只' },
        { id: 'cattle:create', name: '添加牛只' },
        { id: 'cattle:edit', name: '编辑牛只' }
      ],
      3: [ // 经理
        { id: 'cattle:view', name: '查看牛只' },
        { id: 'trading:view', name: '查看交易' },
        { id: 'trading:create', name: '创建交易' },
        { id: 'monitor:view', name: '查看监控' }
      ],
      4: [ // 操作员
        { id: 'cattle:view', name: '查看牛只' },
        { id: 'cattle:create', name: '添加牛只' },
        { id: 'trading:view', name: '查看交易' }
      ],
      5: [ // 查看者
        { id: 'cattle:view', name: '查看牛只' },
        { id: 'trading:view', name: '查看交易' },
        { id: 'monitor:view', name: '查看监控' }
      ]
    }
    
    return {
      success: true,
      data: permissionMap[roleId] || []
    }
  },
  
  async updateRolePermissions(roleId, permissions) {
    return { success: true }
  }
}

const roleFormRef = ref()
const permissionTreeRef = ref()

onMounted(() => {
  loadRoleList()
})
</script>

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

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #333;
}

.table-container {
  background: white;
  border-radius: 8px;
  padding: 20px;
}

.permission-setting {
  padding: 20px 0;
}

.role-info {
  margin-bottom: 20px;
  padding: 15px;
  background: #f5f5f5;
  border-radius: 8px;
}

.role-info h4 {
  margin: 0 0 10px 0;
  color: #333;
}

.role-info p {
  margin: 0;
  color: #666;
}

.permission-view {
  padding: 20px 0;
}

.permission-list {
  margin-top: 20px;
}

.permission-list h5 {
  margin: 0 0 15px 0;
  color: #333;
}

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

.permission-tag {
  margin: 0;
}
</style>