<template>
  <div>
    <el-card style="height: calc(100vh - 112px);">
      <!-- <template #header>菜单管理</template> -->

      <div style="margin-bottom: 12px">
        <el-button type="primary" @click="load">刷新</el-button>
        <el-button @click="toggleExpandAll" style="border: 1px solid var(--ios-primary); color: var(--ios-primary);">
          {{ isAllExpanded ? '折叠' : '展开' }}
        </el-button>
        <el-button @click="openCreate(0)" style="border: 1px solid var(--ios-primary); color: var(--ios-primary);">新增菜单</el-button>
      </div>

      <el-table
        ref="tableRef"
        :data="menuTree"
        v-loading="loading"
        style="width: 100%"
        row-key="id"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        
      >
        <el-table-column prop="name" label="菜单名称" width="200" />
        <el-table-column prop="icon" label="图标" width="100">
          <template #default="{ row }">
            <component :is="row.icon" v-if="row.icon" style="width: 16px; height: 16px" />
          </template>
        </el-table-column>
        <el-table-column prop="type" label="类型" width="100">
          <template #default="{ row }">
            <el-tag v-if="row.type === 'D'">目录</el-tag>
            <el-tag v-else-if="row.type === 'M'" type="success">菜单</el-tag>
            <el-tag v-else type="info">按钮</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="perms" label="权限标识" />
        <!-- <el-table-column prop="path" label="路由路径" /> -->
        <el-table-column prop="component" label="组件路径" />
        
        <el-table-column prop="sort" label="排序" width="100" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">{{ row.status === 1 ? '正常' : '禁用' }}</el-tag>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="visible" label="可见" width="70">
          <template #default="{ row }">
            <el-tag :type="row.visible === 1 ? 'success' : 'info'">{{ row.visible === 1 ? '显示' : '隐藏' }}</el-tag>
          </template>
        </el-table-column> -->
        <el-table-column label="操作" width="160">
          <template #default="{ row }">
            <div style="display: flex; align-items: center">
              <el-tooltip content="编辑" placement="top">
                <el-button type="primary" text bg :icon="EditPen" style="font-size: 15px; padding: 6px 8px" @click="openEdit(row)" />
              </el-tooltip>
              <el-tooltip content="新增子项" placement="top">
                <el-button type="primary" text bg :icon="Plus" style="font-size: 15px; padding: 6px 8px" @click="openCreate(row.id)" />
              </el-tooltip>
              <el-tooltip content="删除" placement="top">
                <el-button type="danger" text bg :icon="Delete" style="font-size: 15px; padding: 6px 8px" @click="handleDelete(row)" />
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog v-model="dialogOpen" :title="formData.id ? '编辑菜单' : '新增菜单'" width="600px">
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px" v-loading="formLoading">
        <el-form-item label="上级菜单" prop="parentId">
          <el-tree-select
            v-model="formData.parentId"
            :data="menuOptions"
            :props="{ label: 'name', children: 'children' }"
            node-key="id"
            check-strictly
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="菜单类型" prop="type">
          <el-radio-group v-model="formData.type">
            <el-radio value="D">目录</el-radio>
            <el-radio value="M">菜单</el-radio>
            <el-radio value="B">按钮</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="菜单名称" prop="name">
          <el-input v-model="formData.name" />
        </el-form-item>
        <el-form-item label="路由路径" prop="path" v-if="formData.type !== 'B'">
          <el-input v-model="formData.path" placeholder="例如：/system/user" />
        </el-form-item>
        <el-form-item label="组件路径" prop="component" v-if="formData.type === 'M'">
          <el-input v-model="formData.component" placeholder="例如：admin/system/User" />
        </el-form-item>
        <el-form-item label="权限标识" prop="perms" v-if="formData.type !== 'D'">
          <el-input v-model="formData.perms" placeholder="例如：system:user:view" />
        </el-form-item>
        <el-form-item label="图标" prop="icon" v-if="formData.type !== 'B'">
          <el-popover placement="bottom-start" :width="480" trigger="click">
            <template #reference>
              <el-input v-model="formData.icon" placeholder="点击选择图标" readonly>
                <template #prefix>
                  <component :is="formData.icon" v-if="formData.icon" style="width: 16px; height: 16px" />
                  <el-icon v-else><Search /></el-icon>
                </template>
              </el-input>
            </template>
            <div class="icon-selector">
              <el-input v-model="iconSearch" placeholder="搜索图标" prefix-icon="Search" clearable style="margin-bottom: 12px" />
              <div class="icon-list">
                <div
                  v-for="name in filteredIcons"
                  :key="name"
                  class="icon-item"
                  :class="{ active: formData.icon === name }"
                  @click="formData.icon = name"
                >
                  <component :is="Icons[name]" style="width: 20px; height: 20px" />
                  <span class="icon-name">{{ name }}</span>
                </div>
              </div>
            </div>
          </el-popover>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="排序" prop="sort">
              <el-input-number v-model="formData.sort" :min="0" />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="显示状态" prop="visible" v-if="formData.type !== 'B'">
              <el-radio-group v-model="formData.visible">
                <el-radio :value="1">显示</el-radio>
                <el-radio :value="0">隐藏</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col> -->
        </el-row>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :value="1">启用</el-radio>
            <el-radio :value="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogOpen = false">取消</el-button>
        <el-button type="primary" :loading="formLoading" @click="saveMenu">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { onMounted, reactive, ref, computed, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Delete, EditPen, Plus, Search } from '@element-plus/icons-vue'
import * as Icons from '@element-plus/icons-vue'
import {
  createMenu,
  deleteMenu,
  fetchMenuTree,
  updateMenu,
} from '../../../api/system'

import { useMenuStore } from '../../../stores/menu'

const menuTree = ref([])
const loading = ref(false)
const menuStore = useMenuStore()
const tableRef = ref()
const isAllExpanded = ref(false)

// Icon Selector
const iconSearch = ref('')
const iconList = Object.keys(Icons).filter(k => k !== 'default')
const filteredIcons = computed(() => {
  if (!iconSearch.value) return iconList
  return iconList.filter(k => k.toLowerCase().includes(iconSearch.value.toLowerCase()))
})

function applyAllExpanded(expanded) {
  const table = tableRef.value
  if (!table) return

  const visit = (nodes) => {
    if (!Array.isArray(nodes) || nodes.length === 0) return
    for (const node of nodes) {
      table.toggleRowExpansion(node, expanded)
      if (node?.children?.length) {
        visit(node.children)
      }
    }
  }

  visit(menuTree.value)
}

function toggleExpandAll() {
  const next = !isAllExpanded.value
  isAllExpanded.value = next
  applyAllExpanded(next)
}

async function load() {
  loading.value = true
  try {
    menuTree.value = await fetchMenuTree()
    await nextTick()
    if (isAllExpanded.value) {
      applyAllExpanded(true)
    }
  } finally {
    loading.value = false
  }
}

// Form
const dialogOpen = ref(false)
const formLoading = ref(false)
const formRef = ref(null)
const formData = reactive({
  id: undefined,
  parentId: 0,
  type: 'M',
  name: '',
  path: '',
  component: '',
  perms: '',
  icon: '',
  sort: 0,
  visible: 1,
  status: 1,
})
const rules = reactive({
  name: [{ required: true, message: '请输入菜单名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择类型', trigger: 'change' }],
})

// We need a flat list or tree for the "Parent Menu" selector.
// We can reuse `menuTree` for the TreeSelect.
// We should insert a "Root" node option.
const menuOptions = ref([])

function updateMenuOptions() {
  const root = { id: 0, name: '主类目', children: [] }
  // Deep copy menuTree to avoid modifying the view
  // And maybe disable self and children to prevent cycles (if editing)
  menuOptions.value = [root, ...menuTree.value]
}

function openCreate(parentId = 0) {
  formData.id = undefined
  formData.parentId = parentId
  formData.type = 'M'
  formData.name = ''
  formData.path = ''
  formData.component = ''
  formData.perms = ''
  formData.icon = ''
  formData.sort = 0
  formData.visible = 1
  formData.status = 1
  updateMenuOptions()
  dialogOpen.value = true
}

function openEdit(row) {
  Object.assign(formData, row)
  if (formData.parentId === null || formData.parentId === undefined) {
    formData.parentId = 0
  }
  updateMenuOptions()
  dialogOpen.value = true
}

async function saveMenu() {
  if (formRef.value) {
    await formRef.value.validate()
  } else {
    return
  }
  formLoading.value = true
  try {
    if (formData.id) {
      await updateMenu(formData)
      ElMessage.success('更新成功')
    } else {
      await createMenu(formData)
      ElMessage.success('创建成功')
    }
    dialogOpen.value = false
    load()
    // Refresh the sidebar menu store as well
    menuStore.routesLoaded = false
    await menuStore.fetchMenus()
  } catch (e) {
    ElMessage.error(e?.response?.data?.message || '保存失败')
  } finally {
    formLoading.value = false
  }
}

function handleDelete(row) {
  ElMessageBox.confirm(`确认删除菜单 "${row.name}" 吗？`, '提示', {
    type: 'warning',
  }).then(async () => {
    try {
      await deleteMenu(row.id)
      ElMessage.success('删除成功')
      load()
      // Refresh the sidebar menu store as well
      menuStore.routesLoaded = false
      await menuStore.fetchMenus()
    } catch (e) {
      ElMessage.error(e?.response?.data?.message || '删除失败')
    }
  })
}

onMounted(load)
</script>

<style scoped>
.icon-list {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 6px;
  height: 300px;
  overflow-y: auto;

}
.icon-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 8px;
  cursor: pointer;
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 4px;
  transition: all 0.2s;
  height: 50px;
  width: 80px;
  box-sizing: border-box;
}
.icon-item:hover {
  border-color: var(--el-color-primary);
  background-color: var(--el-color-primary-light-9);
}
.icon-item.active {
  border-color: var(--el-color-primary);
  background-color: var(--el-color-primary-light-8);
  color: var(--el-color-primary);
}
.icon-name {
  margin-top: 4px;
  font-size: 10px;
  color: #666;
  width: 100%;
  text-align: center;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>

