import request from '@/utils/request'
import { buildZtree, extractCheckedKeys, postForm } from '@/utils/legacyRequest'

function normalizeMenuListResponse(response) {
  const list = Array.isArray(response)
    ? response
    : Array.isArray(response && response.data)
      ? response.data
      : []
  return { data: list }
}

function normalizeMenuPayload(data = {}) {
  return {
    menuId: data.menuId,
    parentId: data.parentId,
    menuName: data.menuName,
    orderNum: data.orderNum,
    url: data.url,
    target: data.target,
    menuType: data.menuType,
    visible: data.visible,
    isRefresh: data.isRefresh,
    perms: data.perms,
    icon: data.icon,
    remark: data.remark
  }
}

// 查询菜单列表
export function listMenu(query) {
  return postForm('/system/menu/list', query).then(normalizeMenuListResponse)
}

// 查询菜单详细
export function getMenu(menuId) {
  return listMenu().then(response => {
    const flatList = response.data || []
    const matched = flatList.find(item => String(item.menuId) === String(menuId))
    return { data: matched || null }
  })
}

// 查询菜单下拉树结构
export function treeselect() {
  return request({
    url: '/system/menu/menuTreeData',
    method: 'get'
  }).then(response => {
    const treeList = Array.isArray(response) ? response : (response.data || [])
    return { data: buildZtree(treeList) }
  })
}

// 根据角色ID查询菜单下拉树结构
export function roleMenuTreeselect(roleId) {
  return request({
    url: '/system/menu/roleMenuTreeData',
    method: 'get',
    params: { roleId }
  }).then(response => {
    const treeList = Array.isArray(response) ? response : (response.data || [])
    return {
      menus: buildZtree(treeList),
      checkedKeys: extractCheckedKeys(treeList)
    }
  })
}

// 新增菜单
export function addMenu(data) {
  return postForm('/system/menu/add', normalizeMenuPayload(data))
}

// 修改菜单
export function updateMenu(data) {
  return postForm('/system/menu/edit', normalizeMenuPayload(data))
}

// 保存菜单排序
export function updateMenuSort(data) {
  return postForm('/system/menu/updateSort', data)
}

// 删除菜单
export function delMenu(menuId) {
  return request({
    url: '/system/menu/remove/' + menuId,
    method: 'get'
  })
}
