
<!--选择所有幼儿园-->
<template>
  <treeselect
    v-model="localKindergartenId"
    class="j-tree-select"
    :multiple="false"
    :options="kindergartenOptions"
    :default-expand-level="10"
    :placeholder="placeholder"
    :disabled="disabled"
    :searchable="true"
    :disable-branch-nodes="false"
    :no-options-text="noOptionText"
    :flat="true"
    search-nested
    @select="val => $emit('select', val)"
    @input="val => $emit('input', val)"
  />
</template>
<script>
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { fetchBranchTree, fetchHasAuthKindergarten } from '@/api/profile/kindergartenAuth'

export default {
  name: 'SelectBranchTree',
  components: { Treeselect },
  model: {
    prop: 'value',
    event: 'update:value'
  },
  props: {
    // 是否控制根据省市过滤结果
    isControl: {
      type: Boolean,
      default: false
    },
    // 单个选项禁用规则
    disabledRule: {
      type: Function,
      default: () => {
        return false
      }
    },
    value: {
      type: [String, Number],
      default: null
    },
    disabled: {
      type: Boolean,
      default: () => false
    },
    placeholder: {
      type: String,
      default: '请选择幼儿园'
    },
    noOptionText: {
      type: String,
      default: '暂无数据'
    }
  },
  data() {
    return {
      kindergartenOptions: [] // 集团、幼儿园树结构
    }
  },
  computed: {
    localKindergartenId: {
      get() {
        return this.value
      },
      set(val) {
        this.$emit('update:value', val)
      }
    }
  },
  created() {
    if (!this.isControl) this.getKindergartenTree()
  },
  methods: {
    formatTenantTree(list, { id_, label_, children_ }) {
      let obj = {}
      return list.map((item, i) => {
        obj = {
          ...item,
          id: item[id_],
          label: item[label_],
          isDisabled: typeof this.disabledRule === 'function' ? this.disabledRule(item) : false
        }
        if (item[children_] && item[children_].length > 0) {
          obj.children = this.formatTenantTree(item[children_], { id_, label_, children_ })
        }
        return Object.assign({}, item, obj)
      })
    },
    getKindergartenTree(params) {
      fetchBranchTree(params).then(({ data }) => {
        this.kindergartenOptions = this.formatTenantTree(data, { id_: 'id', label_: 'name', children_: 'gardenBranchDtoList' })
      })
    },
    getHasAuthKindergartenTree(params) {
      fetchHasAuthKindergarten(params).then(({ data }) => {
        if (data && data.length > 0) {
          this.kindergartenOptions = this.formatTenantTree(data, {
            id_: 'id', label_: 'name', children_: 'gardenBranchDtoList'
          })
        }
      })
    },
    onResetOptions() {
      this.kindergartenOptions = []
    }
  }
}
</script>
<style scoped lang="scss">
@import "@/assets/styles/treeselect";
.j-tree-select {
//  height: 32px;
  width: 200px;
}
</style>
