<template>
  <a-tree-select
    :model-value="modelValue"
    :field-names="{ title: 'name', key: 'id' }"
    @update:model-value="onUpdate"
    :data="authOptions"
    tree-checked-strategy="child"
    :tree-checkable="multiple"
    :max-tag-count="2"
    allow-search
    allow-clear
    :filter-tree-node="filterTreeNode"
    placeholder="请选择负责人" />
</template>
<script setup>
import { ref, onMounted, defineProps, defineEmits } from 'vue'
import advertCommonApi from '@/views/v1/api/advert/common'

const authOptions = ref([])

const props = defineProps({
  modelValue: {
    type: [Array],
    default: [],
  },
  multiple: {
    type: Boolean,
    default: false,
  },
})

const emit = defineEmits(['update:modelValue'])
const onUpdate = (val) => {
  emit('update:modelValue', val)
}
// 搜索
const filterTreeNode = (inputText, node) => {
  return node.name.toLowerCase().indexOf(inputText.toLowerCase()) > -1
}

// 获取后台归属人列表
const getAuthList = async () => {
  const res = await advertCommonApi.getAuthOptionsApi()
  if (res.code == 200) {
    if (props.multiple) {
      authOptions.value = res.data
    } else {
      const data = await handleData(res.data)
      authOptions.value = data
    }
  }
}

// 处理数据
const handleData = (data) => {
  return new Promise((resolve) => {
    for (const item of data) {
      if (item.id.includes('dept_id_')) {
        item.disabled = true
      }
      if (item.children) {
        handleData(item.children)
      }
    }
    resolve(data)
  })
}

onMounted(() => {
  getAuthList()
})
</script>
