<template>
  <div class="permission-manage">
    <div class="permission-tree">
      <el-card>
        <template #header>
          <div class="header">
            <span>权限管理</span>
            <el-button type="primary" @click="handleAddPermission(null)">新增权限</el-button>
          </div>
        </template>
        <el-tree
          :data="permissionTree"
          :props="{ label: 'name' }"
          node-key="id"
          default-expand-all
        >
          <template #default="{ node, data }">
            <div class="custom-tree-node">
              <div>
                <span>{{ data.name }}</span>
                <el-tag size="small" class="ml-10">{{ data.code }}</el-tag>
                <el-tag size="small" type="success" class="ml-10">
                  {{ getTypeText(data.type) }}
                </el-tag>
              </div>
              <div>
                <el-button type="primary" size="small" @click.stop="handleAddPermission(data)">
                  添加子权限
                </el-button>
                <el-button type="warning" size="small" @click.stop="handleEditPermission(data)">
                  编辑
                </el-button>
                <el-popconfirm title="确认删除?" @confirm="handleDeletePermission(data.id)">
                  <template #reference>
                    <el-button type="danger" size="small" @click.stop>删除</el-button>
                  </template>
                </el-popconfirm>
              </div>
            </div>
          </template>
        </el-tree>
      </el-card>
    </div>

    <!-- 权限表单对话框 -->
    <el-dialog v-model="permissionDialogVisible" :title="isEdit ? '编辑权限' : '新增权限'">
      <el-form :model="permissionForm" label-width="100px" :rules="permissionRules" ref="permissionFormRef">
        <el-form-item label="上级权限">
          <el-input v-model="parentPermissionName" disabled />
        </el-form-item>
        <el-form-item v-if="permissionForm.type !== 1" label="权限名称" prop="permissionName">
          <el-input v-model="permissionForm.permissionName" placeholder="请输入权限名称" />
        </el-form-item>
        <el-form-item v-if="permissionForm.type !== 1" label="权限编码" prop="permissionCode">
          <el-input v-model="permissionForm.permissionCode" placeholder="请输入权限编码" />
        </el-form-item>
        <el-form-item v-if="permissionForm.type === 1" label="目录名称" prop="permissionName">
          <el-input v-model="permissionForm.permissionName" placeholder="请输入目录名称" />
        </el-form-item>
        <el-form-item label="权限类型" prop="type">
          <el-select v-model="permissionForm.type" placeholder="请选择权限类型" style="width: 100%">
            <el-option :value="1" label="目录" />
            <el-option :value="2" label="菜单" />
            <el-option :value="3" label="接口" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="permissionForm.type === 1 || permissionForm.type === 2" label="路由路径" prop="path">
          <el-input v-model="permissionForm.path" placeholder="请输入路由路径" />
        </el-form-item>
        <el-form-item v-if="permissionForm.type === 1 || permissionForm.type === 2" label="组件路径" prop="component">
          <el-input v-model="permissionForm.component" placeholder="请输入组件路径" />
        </el-form-item>
        <el-form-item v-if="permissionForm.type === 1 || permissionForm.type === 2" label="图标" prop="icon">
          <el-input v-model="permissionForm.icon" placeholder="请输入图标" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="permissionForm.sort" :min="0" />
        </el-form-item>
        <el-form-item label="权限描述" prop="description">
          <el-input v-model="permissionForm.description" placeholder="请输入权限描述" type="textarea" />
        </el-form-item>
        <el-form-item label="状态">
          <el-switch v-model="permissionForm.status" :active-value="1" :inactive-value="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="permissionDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitPermissionForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { getPermissionTree, addPermission, updatePermission, deletePermission } from '@/api/permission'

export default {
  name: 'PermissionManage',
  setup() {
    // 权限树数据
    const loading = ref(false)
    const permissionTree = ref([])
    
    // 权限表单数据
    const permissionFormRef = ref(null)
    const permissionDialogVisible = ref(false)
    const isEdit = ref(false)
    const parentPermissionName = ref('')
    const permissionForm = reactive({
      id: '',
      parentId: null,
      permissionName: '',
      permissionCode: '',
      description: '',
      type: 1,
      path: '',
      component: '',
      icon: '',
      sort: 0,
      status: 1
    })
    const permissionRules = {
      permissionName: [{ required: true, message: '请输入权限名称', trigger: 'blur' }],
      permissionCode: [{ required: true, message: '请输入权限编码', trigger: 'blur', validator: (rule, value, callback) => {
        if (permissionForm.type === 1) {
          callback(); // 目录类型不验证编码
        } else if (!value) {
          callback(new Error('请输入权限编码'));
        } else {
          callback();
        }
      }}],
      type: [{ required: true, message: '请选择权限类型', trigger: 'change' }]
    }
    
    // 获取权限树
    const fetchPermissionTree = async () => {
      loading.value = true
      try {
        const res = await getPermissionTree()
        permissionTree.value = res.data || []
      } catch (error) {
        console.error('获取权限树失败', error)
        ElMessage.error('获取权限树失败')
      } finally {
        loading.value = false
      }
    }
    
    // 获取权限类型文本
    const getTypeText = (type) => {
      switch (type) {
        case 1:
          return '目录'
        case 2:
          return '菜单'
        case 3:
          return '接口'
        default:
          return '未知'
      }
    }
    
    // 新增权限
    const handleAddPermission = (parentNode) => {
      isEdit.value = false
      permissionForm.id = ''
      permissionForm.parentId = parentNode ? parentNode.id : null
      permissionForm.permissionName = ''
      permissionForm.permissionCode = ''
      permissionForm.description = ''
      permissionForm.type = 1
      permissionForm.path = ''
      permissionForm.component = ''
      permissionForm.icon = ''
      permissionForm.sort = 0
      permissionForm.status = 1
      permissionForm.isDel = 0
      
      parentPermissionName.value = parentNode ? parentNode.name : '无（根权限）'
      
      permissionDialogVisible.value = true
    }
    
    // 编辑权限
    const handleEditPermission = (node) => {
      isEdit.value = true
      permissionForm.id = node.id
      permissionForm.parentId = node.parentId
      permissionForm.permissionName = node.name
      permissionForm.permissionCode = node.code
      permissionForm.description = node.description
      permissionForm.type = node.type
      permissionForm.path = node.path || ''
      permissionForm.component = node.component || ''
      permissionForm.icon = node.icon || ''
      permissionForm.sort = node.sort
      permissionForm.status = node.status
      
      // 查找父节点名称
      if (node.parentId) {
        const findParentName = (nodes, id) => {
          for (const item of nodes) {
            if (item.id === id) {
              return item.name
            }
            if (item.children && item.children.length > 0) {
              const name = findParentName(item.children, id)
              if (name) return name
            }
          }
          return null
        }
        
        parentPermissionName.value = findParentName(permissionTree.value, node.parentId) || '未知'
      } else {
        parentPermissionName.value = '无（根权限）'
      }
      
      permissionDialogVisible.value = true
    }
    
    // 提交权限表单
    const submitPermissionForm = async () => {
      if (!permissionFormRef.value) return
      
      await permissionFormRef.value.validate(async (valid) => {
        if (valid) {
          try {
            // 如果是目录类型，自动设置一个空的编码值
            if (permissionForm.type === 1) {
              permissionForm.permissionCode = '';
            }
            
            const data = {
              id: permissionForm.id,
              parentId: permissionForm.parentId,
              permissionName: permissionForm.permissionName,
              permissionCode: permissionForm.permissionCode,
              description: permissionForm.description,
              type: permissionForm.type,
              path: permissionForm.path,
              component: permissionForm.component,
              icon: permissionForm.icon,
              sort: permissionForm.sort,
              status: permissionForm.status
            }
            
            if (isEdit.value) {
              await updatePermission(data)
              ElMessage.success('更新成功')
            } else {
              await addPermission(data)
              ElMessage.success('添加成功')
            }
            permissionDialogVisible.value = false
            fetchPermissionTree()
          } catch (error) {
            console.error(isEdit.value ? '更新权限失败' : '添加权限失败', error)
            ElMessage.error(isEdit.value ? '更新权限失败' : '添加权限失败')
          }
        }
      })
    }
    
    // 删除权限
    const handleDeletePermission = async (id) => {
      try {
        await deletePermission(id)
        ElMessage.success('删除成功')
        fetchPermissionTree()
      } catch (error) {
        console.error('删除权限失败', error)
        ElMessage.error('删除权限失败')
      }
    }
    
    onMounted(() => {
      fetchPermissionTree()
    })
    
    return {
      loading,
      permissionTree,
      permissionFormRef,
      permissionDialogVisible,
      isEdit,
      parentPermissionName,
      permissionForm,
      permissionRules,
      getTypeText,
      handleAddPermission,
      handleEditPermission,
      submitPermissionForm,
      handleDeletePermission
    }
  }
}
</script>

<style scoped>
.permission-manage {
  padding: 20px;
}
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-right: 8px;
}
.ml-10 {
  margin-left: 10px;
}
</style> 