<template>
  <TreeSelect
    :placeholder="placeholder"
    :data="data"
    :append-to-body="appendToBody"
    :clearable="clearable"
    :inline="inline"
    node-key="value"
    :multiple="multiple"
    :default-expand-all="true"
  />
</template>

<script>
import TreeSelect from '@/components/common/TreeSelect'
import { fetchAll } from '@/api/cms/category'

export default {
  name: 'CategorySelect',
  components: { TreeSelect },
  props: {
    valueKey: {
      default: 'id'
    },
    multiple: {
      default: true
    },
    inline: {
      default: true
    },
    placeholder: {
      default: '请选择栏目'
    },
    // 是否可清空
    clearable: {
      type: Boolean,
      default: false
    },
    appendToBody: {
      default: false
    },
    // 需被排除的栏目ID
    excludeValue: {},
    // 顶部补充的选项
    firstOptions: {
      default () {
        return []
      }
    }
  },
  data () {
    return {
      data: []
    }
  },
  watch: {
    excludeValue () {
      this.fetchData()
    }
  },
  methods: {
    /**
     * 获取所有菜单
     */
    fetchData () {
      fetchAll()
        .then(records => {
          this.data = [
            ...this.firstOptions
          ]
          this.__fillData(this.data, records)
        })
        .catch(e => {
          this.$tip.apiFailed(e)
        })
    },
    // 填充栏目树
    __fillData (list, pool) {
      for (const category of pool) {
        // 已排除
        if (category[this.valueKey] === this.excludeValue) {
          continue
        }
        const categoryNode = {
          value: category[this.valueKey],
          label: category.title,
          // 禁用非常规栏目
          disabled: category.type !== this.$const.CATEGORY_TYPE.DEFAULT
        }
        list.push(categoryNode)
        if (category.children != null && category.children.length > 0) {
          categoryNode.children = []
          this.__fillData(categoryNode.children, category.children)
          if (categoryNode.children.length === 0) {
            delete categoryNode.children
          }
        }
      }
    }
  },
  created () {
    this.fetchData()
  }
}
</script>
