<template>
  <el-dialog
    v-model="visible"
    title="选择路径权限"
    width="900px"
    append-to-body
    @close="handleClose"
  >
    <div class="permission-selector">
      <!-- 搜索筛选区域 -->
      <div class="filter-section">
        <el-form :inline="true" :model="searchParams" class="search-form">
          <el-form-item label="关键词">
            <el-input
              v-model="searchParams.key"
              placeholder="搜索路径或名称"
              clearable
              @keyup.enter="handleSearch"
              style="width: 200px"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="请求方法">
            <el-select
              v-model="searchParams.method"
              placeholder="全部方法"
              clearable
              style="width: 120px"
            >
              <el-option label="GET" value="GET" />
              <el-option label="POST" value="POST" />
              <el-option label="PUT" value="PUT" />
              <el-option label="DELETE" value="DELETE" />
              <el-option label="PATCH" value="PATCH" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch" :icon="Search">
              搜索
            </el-button>
            <el-button @click="handleReset" :icon="Refresh">
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 权限列表表格 -->
      <el-table
        v-loading="loading"
        :data="filteredList"
        highlight-current-row
        @current-change="handleCurrentChange"
        style="width: 100%"
        :height="400"
        :row-class-name="tableRowClassName"
      >
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column prop="method" label="方法" width="100" align="center">
          <template #default="{ row }">
            <el-tag v-if="row.method" :type="getMethodTag(row.method)" size="small">
              {{ row.method }}
            </el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="path" label="路径" min-width="250" show-overflow-tooltip />
        <el-table-column prop="name" label="名称" min-width="150" show-overflow-tooltip />
        <el-table-column prop="note" label="备注" min-width="150" show-overflow-tooltip />
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container" v-if="total > 0">
        <el-pagination
          v-model:current-page="searchParams.page"
          v-model:page-size="searchParams.count"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          background
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>

      <!-- 已选信息 -->
      <div class="selected-info" v-if="selectedPermission">
        <el-alert type="success" :closable="false">
          <template #title>
            <div class="selected-content">
              <span>已选择: </span>
              <el-tag v-if="selectedPermission.method" :type="getMethodTag(selectedPermission.method)" size="small" style="margin-right: 8px;">
                {{ selectedPermission.method }}
              </el-tag>
              <span class="selected-path">{{ selectedPermission.path }}</span>
              <span class="selected-name" v-if="selectedPermission.name"> - {{ selectedPermission.name }}</span>
            </div>
          </template>
        </el-alert>
      </div>
    </div>

    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleConfirm" :disabled="!selectedPermission">
        确认选择
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Search, Refresh } from '@element-plus/icons-vue'
import { getPermissionList } from '@/api/admin/Permission'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  currentPermissionId: {
    type: Number,
    default: null
  }
})

const emit = defineEmits(['update:modelValue', 'confirm'])

const visible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

// 搜索参数
const searchParams = reactive({
  key: '',
  method: '',
  page: 1,
  count: 20
})

// 状态
const loading = ref(false)
const permissionList = ref([])
const total = ref(0)
const selectedPermission = ref(null)

// 过滤后的列表
const filteredList = computed(() => {
  let list = permissionList.value
  
  // 关键词过滤
  if (searchParams.key) {
    const keyword = searchParams.key.toLowerCase()
    list = list.filter(item => 
      (item.path && item.path.toLowerCase().includes(keyword)) ||
      (item.name && item.name.toLowerCase().includes(keyword)) ||
      (item.note && item.note.toLowerCase().includes(keyword))
    )
  }
  
  // 方法过滤
  if (searchParams.method) {
    list = list.filter(item => item.method === searchParams.method)
  }
  
  return list
})

// 获取方法标签颜色
const getMethodTag = (method) => {
  const tagMap = {
    'GET': 'success',
    'POST': 'primary',
    'PUT': 'warning',
    'DELETE': 'danger',
    'PATCH': 'info'
  }
  return tagMap[method?.toUpperCase()] || 'info'
}

// 表格行样式
const tableRowClassName = ({ row }) => {
  if (selectedPermission.value && row.id === selectedPermission.value.id) {
    return 'selected-row'
  }
  if (props.currentPermissionId && row.id === props.currentPermissionId) {
    return 'current-row'
  }
  return ''
}

// 获取权限列表
const fetchPermissionList = async () => {
  loading.value = true
  try {
    const res = await getPermissionList({
      page: 1,
      count: 10
    })
    if (res.data.code === 200) {
      permissionList.value = res.data.data?.list || []
      total.value = permissionList.value.length
    } else {
      ElMessage.error(res.data.message || '获取权限列表失败')
    }
  } catch (error) {
    console.error('获取权限列表失败:', error)
    ElMessage.error('获取权限列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  searchParams.page = 1
}

// 重置
const handleReset = () => {
  searchParams.key = ''
  searchParams.method = ''
  searchParams.page = 1
}

// 分页
const handleSizeChange = (size) => {
  searchParams.count = size
  searchParams.page = 1
}

const handlePageChange = (page) => {
  searchParams.page = page
}

// 选择行
const handleCurrentChange = (row) => {
  selectedPermission.value = row
}

// 确认选择
const handleConfirm = () => {
  if (selectedPermission.value) {
    emit('confirm', selectedPermission.value)
    handleClose()
  }
}

// 关闭弹窗
const handleClose = () => {
  visible.value = false
  selectedPermission.value = null
  handleReset()
}

// 监听弹窗打开
watch(() => props.modelValue, (val) => {
  if (val) {
    fetchPermissionList()
    // 如果有当前选中的ID，尝试预选
    if (props.currentPermissionId) {
      const found = permissionList.value.find(p => p.id === props.currentPermissionId)
      if (found) {
        selectedPermission.value = found
      }
    }
  }
})
</script>

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

.filter-section {
  margin-bottom: 16px;
  padding: 16px;
  background: #fafbfc;
  border-radius: 4px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.pagination-container {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}

.selected-info {
  margin-top: 16px;
}

.selected-content {
  display: flex;
  align-items: center;
  gap: 4px;
}

.selected-path {
  font-weight: 500;
  color: #303133;
}

.selected-name {
  color: #909399;
}

:deep(.el-table .selected-row) {
  background-color: #ecf5ff !important;
}

:deep(.el-table .current-row) {
  background-color: #f0f9eb !important;
}

:deep(.el-table .selected-row td),
:deep(.el-table .current-row td) {
  background-color: inherit !important;
}

/* 移动端适配 */
@media (max-width: 768px) {
  :deep(.el-dialog) {
    width: 95% !important;
    margin: 2vh auto !important;
  }

  .filter-section {
    padding: 12px;
  }

  .search-form {
    flex-direction: column;
  }

  .search-form .el-form-item {
    margin-right: 0;
    margin-bottom: 8px;
    width: 100%;
  }

  .search-form .el-input,
  .search-form .el-select {
    width: 100% !important;
  }
}
</style>
