<template>
  <div class="menu-management">
    <el-card>
      <template #header>
        <div class="card-title">
          <span>菜单管理</span>
          <el-button
            type="primary"
            @click="handleAdd"
          >
            新增菜单
          </el-button>
        </div>
      </template>
      <el-table
        v-loading="loading"
        :data="dataSource"
        :pagination="false"
        row-key="id"
        style="width: 100%"
      >
        <el-table-column
          prop="menuName"
          label="菜单名称"
        />
        <el-table-column
          label="菜单类型"
          width="100"
        >
          <template #default="{ row }">
            <el-tag 
              :type="row.menuType === 'M' ? 'info' : row.menuType === 'C' ? 'success' : 'warning'"
              effect="dark"
              style="font-weight: 500; font-size: 14px;"
            >
              {{ row.menuType === 'M' ? '目录' : row.menuType === 'C' ? '菜单' : '按钮' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="perms"
          label="权限标识"
        />
        <el-table-column
          prop="component"
          label="组件"
        />
        <el-table-column
          prop="orderNum"
          label="排序"
          width="80"
        />
        <el-table-column
          label="状态"
          width="80"
        >
          <template #default="{ row }">
            <el-tag :type="row.status === '0' ? 'success' : 'danger'">
              {{ row.status === '0' ? '显示' : '隐藏' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          width="150"
        >
          <template #default="{ row }">
            <el-button
              type="primary"
              link
              size="small"
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              link
              size="small"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog
      v-model="modalVisible"
      :title="modalTitle"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="formState"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item
          label="菜单名称"
          prop="menuName"
        >
          <el-input v-model="formState.menuName" />
        </el-form-item>
        <el-form-item label="父级菜单">
          <el-tree-select
            v-model="formState.parentId"
            :data="menuTree"
            placeholder="请选择父级菜单"
            clearable
            check-strictly
          />
        </el-form-item>
        <el-form-item
          label="菜单类型"
          prop="menuType"
        >
          <el-select v-model="formState.menuType">
            <el-option
              value="M"
              label="目录"
            />
            <el-option
              value="C"
              label="菜单"
            />
            <el-option
              value="F"
              label="按钮"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="formState.menuType !== 'F'"
          label="路由地址"
          prop="perms"
        >
          <el-input v-model="formState.perms" />
        </el-form-item>
        <el-form-item
          v-if="formState.menuType === 'C'"
          label="组件路径"
          prop="component"
        >
          <el-input v-model="formState.component" />
        </el-form-item>
        <el-form-item
          label="排序"
          prop="orderNum"
        >
          <el-input-number v-model="formState.orderNum" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="formState.status">
            <el-option
              value="0"
              label="显示"
            />
            <el-option
              value="1"
              label="隐藏"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="modalVisible = false">
          取消
        </el-button>
        <el-button
          type="primary"
          @click="handleModalOk"
        >
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'

const loading = ref(false)
const dataSource = ref([])
const menuTree = ref<any[]>([])
const modalVisible = ref(false)
const modalTitle = ref('')
const formRef = ref()
const formState = reactive({
  id: null, menuName: '', parentId: 0, menuType: 'C', perms: '', component: '', orderNum: 0, status: '0'
})

const formRules = {
  menuName: [
    { required: true, message: '请输入菜单名称', trigger: 'blur' },
    { min: 2, max: 50, message: '菜单名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  menuType: [
    { required: true, message: '请选择菜单类型', trigger: 'change' }
  ],
  perms: [
    { required: true, message: '请输入路由地址', trigger: 'blur' },
    { pattern: /^\/[a-zA-Z0-9/_-]*$/, message: '路由地址格式不正确，应以/开头', trigger: 'blur' }
  ],
  component: [
    { required: true, message: '请输入组件路径', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9/-]+$/, message: '组件路径格式不正确', trigger: 'blur' }
  ],
  orderNum: [
    { required: true, message: '请输入排序', trigger: 'blur' },
    { type: 'number', min: 0, message: '排序必须大于等于0', trigger: 'blur' }
  ]
}

const fetchData = async () => {
  loading.value = true
  try {
    const res: any = await request.get('/menus')
    dataSource.value = res
    menuTree.value = buildTreeSelect(res)
  } finally {
    loading.value = false
  }
}

const buildTreeSelect = (menus: any[]): any[] => {
  return menus.map(m => ({ value: m.id, label: m.menuName, children: m.children ? buildTreeSelect(m.children) : undefined }))
}

const handleAdd = () => {
  modalTitle.value = '新增菜单'
  Object.assign(formState, { id: null, menuName: '', parentId: 0, menuType: 'C', perms: '', component: '', orderNum: 0, status: '0' })
  modalVisible.value = true
}

const handleEdit = (row: any) => {
  modalTitle.value = '编辑菜单'
  Object.assign(formState, row)
  modalVisible.value = true
}

const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm('确定要删除该菜单吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await request.delete(`/menus/${row.id}`)
    ElMessage.success('删除成功')
    fetchData()
  } catch (error) {
    console.error('删除菜单失败:', error)
  }
}

const handleModalOk = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    if (formState.id) {
      await request.put(`/menus/${formState.id}`, formState)
    } else {
      await request.post('/menus', formState)
    }
    ElMessage.success('操作成功')
    modalVisible.value = false
    fetchData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
    }
  }
}

onMounted(() => fetchData())
</script>

<style scoped lang="css">
.menu-management .card-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
