<script setup>
/**
 * name：
 * user：sa0ChunLuyu
 * date：2022-05-24 10:19:45
 */
import {isDark} from '~/composables'
import {h} from 'vue'
import {useRouterActive, useConfig} from '~/store'
import $router from '~/router'
import Icon from "~/components/Icon.vue";
import {AdminMenuAction, $response} from '~/api'

const menuListItem = (item) => {
  let data = {
    title: item.title,
    name: item.name,
    status: item.status,
    icon: item.icon
  }
  if ('children' in item) {
    data.children = item.children.map((i) => {
      return menuListItem(i)
    })
  }
  return data
}

const getMenu = async () => {
  const response = await AdminMenuAction()
  $response(response, () => {
    menu_list.value = response.data.list.map((item) => {
      return menuListItem(item)
    })
  })
  menu_list.value.unshift({
    title: '首页',
    name: 'index',
    status: 1,
    icon: 'home'
  })
}
onMounted(() => {
  getMenu()
})

function renderIcon(icon) {
  return () => h(Icon, {
    size: 20,
    type: !!icon ? icon : 'round'
  }, {default: () => h(icon)})
}

const menu_list = ref([])
const menuItem = (list) => {
  return list.map((item) => {
    let item_info = {label: item.title, key: item.name, disabled: item.status === 2}
    if ('children' in item) {
      if (item.children.length === 1) {
        item_info = {
          label: item.children[0].title,
          key: item.children[0].name,
          icon: renderIcon(item.children[0].icon)
        }
      } else {
        if (item.children.length !== 0) {
          item_info = {label: item.title, key: item.name, children: menuItem(item.children)}
        }
      }
    }
    if ('query' in item && item.query !== '{}') item_info.query = JSON.parse(item.query)
    if ('params' in item && item.params !== '{}') item_info.params = JSON.parse(item.params)
    if ('icon' in item && item.icon !== '') {
      if (!('icon' in item_info)) item_info.icon = renderIcon(item.icon)
    }
    return item_info
  })
}
const menu_options = computed(() => {
  return menuItem(menu_list.value)
})

const menuUpdate = (_, item) => {
  let push = {name: item.key}
  if ('query' in item) push.query = item.query
  if ('params' in item) push.params = item.params
  try {
    $router.push(push)
  } catch (e) {
    $router.push({
      name: 'index'
    })
  }
}
const $router_active = useRouterActive()
const expanded_keys = computed(() => {
  return $router_active.value.map((item) => {
    return item.key
  })
})
const $config = useConfig()
</script>
<template>
  <n-menu class="menu_wrapper" :indent="12" :value="expanded_keys[expanded_keys.length - 1]" :options="menu_options"
          :watch-props="['defaultExpandedKeys']" :default-expanded-keys="expanded_keys" @update:value="menuUpdate"
          :inverted="$config.layout.sider.inverted || isDark" :collapsed-width="64" :icon-size="20"/>
</template>
