<template>
  <a-select
    :value="value"
    :options="options"
    :open="false"
    mode="multiple"
    @change="(value) => $emit('change', value)"
    @click.native="select"
  />
</template>

<script>
import cloneDeep from 'lodash.clonedeep'
import pickValues from '@/common/services/pick-values'
import sdTreePickerVue from '@/common/components/sd-tree-picker.vue'
import pickerMixin from '@/common/components/sd-picker/picker-mixin'
import components from './_import-components/sd-select-tree-import'

function parseTreeData(data, flag) {
  // 设置树只有叶子节点可选
  const result = cloneDeep(data)
  const f = (arr) => {
    arr.forEach((a) => {
      if (a.children) {
        f(a.children)
      }
      a.checkable = flag || !a.children
      a.isLeaf = !a.children
    })
  }
  f(result)
  return result
}
export const getLabelByValue = (id, dataSource, showLevel) => {
  let path
  const f = (arr) => {
    arr.forEach((a) => {
      if (path) return
      if (a.children) {
        a.children.forEach((item) => {
          item.path = [...(a.path || [a.name]), item.name]
        })
        f(a.children)
      }
      if (a.id === id) {
        path = a.path || [a.name]
      }
    })
  }
  f(cloneDeep(dataSource))
  return (
    path.slice(parseInt(showLevel) > 0 ? parseInt(showLevel) - 1 : parseInt(showLevel)).join('/') ||
    path.slice(-1)
  )
}
/**
 * 自定义树选者器
 * @displayName SdSelectTree 自定义树选者器
 * @since 8.1.0.25
 */
export default {
  name: 'SdSelectTree',
  components,
  mixins: [pickerMixin],
  props: {
    /**
     * 选择的数据源树结构 [id,name,children]
     */
    dataSource: {
      type: Array,
      default: undefined,
    },
    /**
     * 标签从第几层开始显示
     */
    showLevel: {
      type: [Number, String],
      default: 1,
    },
    /**
     * 所有的节点是否可选
     * @since 8.1.0.30
     */
    allNodesSelectable: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {}
  },
  computed: {
    treeData() {
      return parseTreeData(this.dataSource || [], this.allNodesSelectable)
    },
    options() {
      if (this.value === undefined) {
        return []
      }
      return this.value.map((id) => {
        return { key: id, label: getLabelByValue(id, this.dataSource, this.showLevel) }
      })
    },
  },
  methods: {
    select() {
      pickValues(sdTreePickerVue, {
        loadTreeData: () => {
          return Promise.resolve(this.treeData)
        },
        searchTreeData: (t) => {
          const array = []
          const f = (arr) => {
            arr.forEach((a) => {
              if (a.name.includes(t)) {
                array.push(a)
              }
              if (a.children) {
                a.children.forEach((item) => {
                  item.path = [...(a.path || [a.name]), item.name]
                })
                f(a.children)
              }
            })
          }
          f(this.treeData)
          return Promise.resolve(array)
        },
        value: this.options.map((item) => ({ id: item.key, name: item.label })),
        single: this.single,
        render: (i) => <span title={i.path?.join('/')}>{i.name}</span>,
      }).then((data) => {
        if (!data) {
          return
        }
        this.$emit(
          'change',
          data.map((i) => i.id)
        )
      })
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
</style>

<docs>
```vue
<template>
  <div>
    <sd-select-tree :dataSource="dataSource" v-model="val" :showLevel="2"/>
    <p>v-model的值：{{val}}</p>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        val:undefined,
        dataSource:[{
          id:1,
          name:'张三',
          children:[{
            id:7,
            name:'李四儿子',
          },{
            id:8,
            name:'王五儿子',
          }],
        },{
          id:2,
          name:'李四',
        },{
          id:3,
          name:'王五',
        },]
      }
    },
}
</script>
```
</docs>
