<template>
  <el-popover placement="bottom-start" :width="300" trigger="click">
    <template #reference>
      <el-button size="small">{{ modelValue ? '已选择' : '选择菜单' }}</el-button>
    </template>
    <el-tree
      :data="menuTree"
      show-checkbox
      node-key="id"
      :props="{ label: 'name', children: 'children' }"
      :default-checked-keys="checkedKeys"
      @check="handleCheck"
      default-expand-all
    />
  </el-popover>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { fetch } from '@/api/index'

const props = defineProps<{
  modelValue: string[]
}>()

const emit = defineEmits(['update:modelValue'])

const menuTree = ref<any[]>([])
const checkedKeys = ref<string[]>(props.modelValue || [])

watch(() => props.modelValue, (val) => {
  if (val) checkedKeys.value = [...val]
})

function handleCheck(_node: any, data: any) {
  emit('update:modelValue', data.checkedKeys)
}

async function fetchMenuTree() {
  try {
    const res = await fetch({ url: '/upms/menu/tree' })
    menuTree.value = res.data || []
  } catch {
    // ignore
  }
}

fetchMenuTree()
</script>
