<template>
  <div class="menu-manage-container">
    <el-card class="main-container" shadow="never">
      <div class="filter-section">
        <div class="filter-content">
          <el-form :inline="true" :model="queryParams" class="filter-form">
            <el-form-item label="关键词">
              <el-input v-model="queryParams.key" placeholder="菜单名称/路径" clearable style="width: 180px" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="父级菜单">
              <el-select v-model="queryParams.parent_id" placeholder="全部" clearable style="width: 160px">
                <el-option v-for="m in parentMenuOptions" :key="m.id" :label="m.title" :value="m.id" />
              </el-select>
            </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-radio-group v-model="viewMode" size="default" @change="handleViewModeChange">
              <el-radio-button value="list">
                <el-icon style="vertical-align: -2px;"><Grid /></el-icon> 列表视图
              </el-radio-button>
              <el-radio-button value="tree">
                <el-icon style="vertical-align: -2px;"><Connection /></el-icon> 树状视图
              </el-radio-button>
            </el-radio-group>
            <el-button v-if="viewMode === 'list'" type="primary" @click="handleAdd(null)">
              <el-icon><Plus /></el-icon>新增顶级菜单
            </el-button>
            <el-button type="success" @click="handleRefresh">
              <el-icon><Refresh /></el-icon>刷新
            </el-button>
          </div>
        </div>
      </div>

      <!-- 列表视图 -->
      <div v-if="viewMode === 'list'" class="table-section">
        <el-table
          v-loading="loading"
          :data="menuList"
          style="width: 100%"
          row-key="id"
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
          :header-cell-style="{ background: '#fafafa', color: '#333', fontWeight: 600 }"
        >
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column prop="title" label="菜单名称" min-width="180" />
          <el-table-column prop="path" label="路径" min-width="200">
            <template #default="{ row }">
              <el-tag size="small" type="info">{{ row.path || '-' }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="icon" label="图标" width="120">
            <template #default="{ row }">
              <div v-if="row.icon" style="display: flex; align-items: center; gap: 6px;">
                <el-icon><component :is="row.icon" /></el-icon>
                <span>{{ row.icon }}</span>
              </div>
              <span v-else class="text-muted">-</span>
            </template>
          </el-table-column>
          <el-table-column prop="parentId" label="父级ID" width="80">
            <template #default="{ row }">
              {{ row.parentId ?? '-' }}
            </template>
          </el-table-column>
          <el-table-column label="创建时间" width="170">
            <template #default="{ row }">
              {{ formatDate(row.CreatedAt) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="250" fixed="right">
            <template #default="{ row }">
              <div class="action-buttons">
                <el-button type="primary" link @click="handleAdd(row)">添加子菜单</el-button>
                <el-button type="warning" link @click="handleEdit(row)">编辑</el-button>
                <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
              </div>
            </template>
          </el-table-column>
          <template #empty>
            <el-empty description="暂无菜单数据" :image-size="80" />
          </template>
        </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>

      <!-- 树状视图 -->
      <div v-if="viewMode === 'tree'" v-loading="myPermLoading" class="tree-section">
        <el-tree
          v-if="myPermTree.length > 0"
          :data="myPermTree"
          node-key="id"
          default-expand-all
          :expand-on-click-node="false"
        >
          <template #default="{ data }">
            <div class="perm-tree-node">
              <el-icon v-if="data.icon" style="margin-right: 6px; flex-shrink: 0;"><component :is="data.icon" /></el-icon>
              <span class="perm-tree-title">{{ data.title }}</span>
              <el-tag size="small" type="info" style="margin-left: 8px;">{{ data.path || '-' }}</el-tag>
              <el-tag :type="data.enable ? 'success' : 'danger'" size="small" style="margin-left: 6px;">
                {{ data.enable ? '启用' : '禁用' }}
              </el-tag>
            </div>
          </template>
        </el-tree>
        <el-empty v-if="!myPermLoading && myPermTree.length === 0" description="暂无菜单权限数据" :image-size="80" />
      </div>
    </el-card>

    <!-- 菜单表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增菜单' : '编辑菜单'"
      width="550px"
      append-to-body
    >
      <el-form ref="formRef" :model="menuForm" :rules="menuRules" label-width="100px">
        <el-form-item label="菜单名称" prop="title">
          <el-input v-model="menuForm.title" placeholder="请输入菜单名称" />
        </el-form-item>
        <el-form-item label="菜单路径" prop="path">
          <MenuPathSelector v-model="menuForm.path" />
        </el-form-item>
        <el-form-item label="菜单图标" prop="icon">
          <IconSelector v-model="menuForm.icon" />
        </el-form-item>
        <el-form-item label="父级菜单">
          <el-select v-model="menuForm.parent_id" placeholder="无（顶级菜单）" clearable style="width: 100%">
            <el-option label="无（顶级菜单）" :value="0" />
            <el-option v-for="m in parentMenuOptions" :key="m.id" :label="m.title" :value="m.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus, Refresh, Grid, Connection } from '@element-plus/icons-vue'
import { getWebRoutsList, addWebRouts, updateWebRouts, deleteWebRouts, getMyWebRoutsPermission } from '@/api/admin/webRouts'
import { formatDate as formatDateTool } from '@/utils/tool'
import IconSelector from '@/components/admin/IconSelector.vue'
import MenuPathSelector from '@/components/admin/MenuPathSelector.vue'

const loading = ref(false)
const menuList = ref([])
const parentMenuOptions = ref([])
const total = ref(0)
const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref(null)
const viewMode = ref('list')

const queryParams = reactive({
  page: 1,
  count: 10,
  key: '',
  parent_id: null
})

const menuForm = reactive({
  id: undefined,
  title: '',
  path: '',
  icon: '',
  parent_id: 0
})

const menuRules = {
  title: [{ required: true, message: '请输入菜单名称', trigger: 'blur' }],
  path: [{ required: true, message: '请输入菜单路径', trigger: 'blur' }]
}

const formatDate = (dateStr) => formatDateTool(dateStr)

const flattenForParent = (list) => {
  const result = []
  for (const item of list) {
    result.push(item)
    if (item.children?.length) {
      result.push(...flattenForParent(item.children))
    }
  }
  return result
}

const fetchMenuList = async () => {
  loading.value = true
  try {
    const params = {}
    Object.keys(queryParams).forEach(key => {
      if (queryParams[key] !== '' && queryParams[key] !== null && queryParams[key] !== undefined) {
        params[key] = queryParams[key]
      }
    })
    const res = await getWebRoutsList(params)
    if (res.data.code === 200) {
      menuList.value = res.data.data?.list || []
      total.value = res.data.data?.all_count || 0
      parentMenuOptions.value = flattenForParent(menuList.value)
    }
  } catch (error) {
    console.error('获取菜单列表失败:', error)
    ElMessage.error('获取菜单列表失败')
  } finally {
    loading.value = false
  }
}

const handleQuery = () => {
  queryParams.page = 1
  fetchMenuList()
}

const resetQuery = () => {
  queryParams.key = ''
  queryParams.parent_id = null
  queryParams.page = 1
  fetchMenuList()
}

const handleSizeChange = (size) => {
  queryParams.count = size
  fetchMenuList()
}

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

const handleAdd = (parentRow) => {
  dialogType.value = 'add'
  dialogVisible.value = true
  Object.assign(menuForm, {
    id: undefined,
    title: '',
    path: '',
    icon: '',
    parent_id: parentRow?.id || 0
  })
  formRef.value?.resetFields()
}

const handleEdit = (row) => {
  dialogType.value = 'edit'
  dialogVisible.value = true
  Object.assign(menuForm, {
    id: row.id,
    title: row.title,
    path: row.path,
    icon: row.icon,
    parent_id: row.parentId || 0
  })
}

const handleDelete = (row) => {
  ElMessageBox.confirm(`确认删除菜单「${row.title}」吗？删除后其子菜单也将受到影响。`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await deleteWebRouts({ id: row.id })
      if (res.data.code === 200) {
        ElMessage.success('删除成功')
        fetchMenuList()
      } else {
        ElMessage.error(res.data.message || '删除失败')
      }
    } catch (error) {
      ElMessage.error(error.response?.data?.message || '删除失败')
    }
  }).catch(() => {})
}

const submitForm = () => {
  formRef.value?.validate(async (valid) => {
    if (!valid) return
    try {
      const submitData = {
        title: menuForm.title,
        path: menuForm.path,
        icon: menuForm.icon
      }
      if (menuForm.parent_id) {
        submitData.parent_id = menuForm.parent_id
      }
      let res
      if (dialogType.value === 'add') {
        res = await addWebRouts(submitData)
      } else {
        submitData.id = menuForm.id
        res = await updateWebRouts(submitData)
      }
      if (res.data.code === 200) {
        ElMessage.success(dialogType.value === 'add' ? '新增成功' : '修改成功')
        dialogVisible.value = false
        fetchMenuList()
      } else {
        ElMessage.error(res.data.message || '操作失败')
      }
    } catch (error) {
      ElMessage.error(error.response?.data?.message || '操作失败')
    }
  })
}

const myPermLoading = ref(false)
const myPermTree = ref([])

const fetchMyPermission = async () => {
  myPermLoading.value = true
  try {
    const res = await getMyWebRoutsPermission()
    if (res.data.code === 200) {
      myPermTree.value = res.data.data || []
    } else {
      ElMessage.error(res.data.message || '获取失败')
    }
  } catch (error) {
    console.error('获取我的菜单权限失败:', error)
    ElMessage.error('获取我的菜单权限失败')
  } finally {
    myPermLoading.value = false
  }
}

const handleViewModeChange = (mode) => {
  if (mode === 'list') {
    fetchMenuList()
  } else {
    fetchMyPermission()
  }
}

const handleRefresh = () => {
  if (viewMode.value === 'list') {
    fetchMenuList()
  } else {
    fetchMyPermission()
  }
}

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

<style scoped>
.menu-manage-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: flex-start; padding: 16px 20px; gap: 20px; flex-wrap: wrap; }
.filter-form { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
.filter-form :deep(.el-form-item) { margin-bottom: 0; margin-right: 8px; }
.filter-form :deep(.el-form-item__label) { font-size: 13px; }
.action-bar { display: flex; gap: 12px; flex-shrink: 0; }
.table-section { padding: 0; }
.action-buttons { display: flex; gap: 8px; align-items: center; }
.text-muted { color: #c0c4cc; }
.pagination { margin-top: 20px; padding: 16px 20px; border-top: 1px solid #e1e8ed; background: #fafbfc; justify-content: flex-end; }
.dialog-footer { display: flex; justify-content: flex-end; gap: 12px; }
:deep(.el-card__body) { padding: 0; }
: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; }
.tree-section { padding: 16px 20px; min-height: 300px; }
.perm-tree-node { display: flex; align-items: center; padding: 2px 0; width: 100%; }
.perm-tree-title { font-size: 13px; font-weight: 500; }
.tree-section :deep(.el-tree-node__content) { height: 38px; }
.tree-section :deep(.el-tree-node__content:hover) { background-color: #f5f7fa; }
.action-bar { display: flex; gap: 12px; flex-shrink: 0; align-items: center; }
</style>
