<template>
  <div class="permission-route-container">
    <!-- 主容器 -->
    <el-card class="main-container" shadow="never">
      <!-- 搜索和操作栏 -->
      <div class="filter-section">
        <div class="filter-content">
          <el-form :inline="true" :model="queryParams" class="search-form">
            <el-form-item label="关键词">
              <el-input v-model="queryParams.key" placeholder="请输入关键词搜索" clearable style="width: 250px" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleQuery">
                <el-icon><Search /></el-icon>查询
              </el-button>
              <el-button @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
          <div class="action-bar">
            <el-button type="primary" @click="handleAdd">
              <el-icon><Plus /></el-icon>新增路由权限
            </el-button>
            <el-button type="success" @click="fetchPermissionList">
              <el-icon><Refresh /></el-icon>刷新
            </el-button>
          </div>
        </div>
      </div>

      <!-- 路由权限列表 -->
      <div class="table-section">
        <el-table
          v-loading="loading"
          :data="permissionList"
          style="width: 100%"
          :header-cell-style="{ background: '#fafafa', color: '#333', fontWeight: 600 }"
        >
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column prop="name" label="权限名称" min-width="200" />
          <el-table-column prop="path" label="路由路径" min-width="300" />
          <el-table-column prop="note" label="说明" min-width="250" show-overflow-tooltip />
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
              <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页 -->
        <el-pagination
          v-model:current-page="queryParams.page"
          v-model:page-size="queryParams.count"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
          class="pagination"
        />
      </div>
    </el-card>

    <!-- 路由权限表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增路由权限' : '编辑路由权限'"
      width="600px"
    >
      <el-form
        ref="permissionFormRef"
        :model="permissionForm"
        :rules="permissionRules"
        label-width="120px"
      >
        <el-form-item label="权限名称" prop="name">
          <el-input v-model="permissionForm.name" placeholder="请输入权限名称" />
        </el-form-item>
        <el-form-item label="路由路径" prop="path">
          <el-input v-model="permissionForm.path" placeholder="请输入路由路径，如: /api/v1/admin/..." />
        </el-form-item>
        <el-form-item label="说明" prop="note">
          <el-input v-model="permissionForm.note" type="textarea" :rows="3" placeholder="请输入说明" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Refresh } from '@element-plus/icons-vue'
import { 
  getPermissionList, 
  addPermissionInfo, 
  updatePermissionInfo, 
  deletePermissionInfo 
} from '@/api/admin/Permission'

// 查询参数
const queryParams = reactive({
  key: '',
  page: 1,
  count: 10
})

// 路由权限表单
const permissionForm = reactive({
  id: undefined,
  path: '',
  name: '',
  note: ''
})

const permissionRules = {
  path: [
    { required: true, message: '请输入路由路径', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入权限名称', trigger: 'blur' }
  ]
}

// 状态数据
const loading = ref(false)
const permissionList = ref([])
const total = ref(0)
const dialogVisible = ref(false)
const dialogType = ref('add')
const permissionFormRef = ref(null)

// 获取路由权限列表
const fetchPermissionList = async () => {
  loading.value = true
  try {
    const res = await getPermissionList(queryParams)
    console.log('路由权限列表数据:', res.data)
    if (res.data.code === 200) {
      permissionList.value = res.data.data.list || []
      total.value = res.data.data.all_count || 0
    }
  } catch (error) {
    console.error('获取路由权限列表失败:', error)
    ElMessage.error('获取路由权限列表失败')
  } finally {
    loading.value = false
  }
}

// 查询
const handleQuery = () => {
  queryParams.page = 1
  fetchPermissionList()
}

// 重置查询
const resetQuery = () => {
  queryParams.key = ''
  queryParams.page = 1
  fetchPermissionList()
}

// 分页
const handleSizeChange = (size) => {
  queryParams.count = size
  fetchPermissionList()
}

const handleCurrentChange = (page) => {
  queryParams.page = page
  fetchPermissionList()
}

// 新增路由权限
const handleAdd = () => {
  dialogType.value = 'add'
  dialogVisible.value = true
  Object.assign(permissionForm, {
    id: undefined,
    path: '',
    name: '',
    note: ''
  })
  permissionFormRef.value?.resetFields()
}

// 编辑路由权限
const handleEdit = (row) => {
  dialogType.value = 'edit'
  dialogVisible.value = true
  Object.assign(permissionForm, {
    id: row.id,
    path: row.path,
    name: row.name,
    note: row.note || ''
  })
}

// 删除路由权限
const handleDelete = (row) => {
  ElMessageBox.confirm(`确认删除路由权限 ${row.name} 吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await deletePermissionInfo({ id: row.id })
      if (res.data.code === 200) {
        ElMessage.success('删除成功')
        fetchPermissionList()
      }
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error(error.response?.data?.message || '删除失败')
    }
  }).catch(() => {})
}

// 提交表单
const submitForm = () => {
  permissionFormRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        console.log('提交路由权限数据:', permissionForm)
        
        let res
        if (dialogType.value === 'add') {
          res = await addPermissionInfo(permissionForm)
        } else {
          res = await updatePermissionInfo(permissionForm)
        }
        if (res.data.code === 200) {
          ElMessage.success(dialogType.value === 'add' ? '新增成功' : '修改成功')
          dialogVisible.value = false
          fetchPermissionList()
        }
      } catch (error) {
        console.error('操作失败:', error)
        ElMessage.error(error.response?.data?.message || '操作失败')
      }
    }
  })
}

// 初始化
onMounted(() => {
  fetchPermissionList()
})
</script>

<style scoped>
.permission-route-container {
  padding: 0;
}

.main-container {
  border: 1px solid #e1e8ed;
  background: #ffffff;
}

.filter-section {
  padding: 0;
  border-bottom: 1px solid #e1e8ed;
  background: #fafbfc;
}

.filter-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  gap: 20px;
  flex-wrap: wrap;
}

.search-form {
  margin: 0;
  flex: 1;
  display: flex;
  align-items: center;
  gap: 12px;
}

.search-form :deep(.el-form-item) {
  margin-bottom: 0;
}

.action-bar {
  display: flex;
  gap: 12px;
  flex-shrink: 0;
}

.table-section {
  padding: 0;
}

.pagination {
  margin-top: 20px;
  padding: 16px 20px;
  border-top: 1px solid #e1e8ed;
  background: #fafbfc;
  justify-content: flex-end;
}

/* 表格样式优化 */
:deep(.el-table) {
  border: none;
  color: #2c3e50;
}

:deep(.el-table__header) {
  background: #f8f9fa;
}

:deep(.el-table th) {
  background: #f8f9fa !important;
  border-bottom: 2px solid #e1e8ed;
  color: #2c3e50;
  font-weight: 600;
  font-size: 13px;
}

:deep(.el-table td) {
  border-bottom: 1px solid #f0f2f5;
  color: #34495e;
}

:deep(.el-table tr:hover > td) {
  background-color: #f8f9fa !important;
}

:deep(.el-card__body) {
  padding: 0;
}
</style>
