<template>
  <el-select
    v-model="localKindergartenId"
    placeholder="请选择所属幼儿园"
    :disabled="disabled"
    filterable
    clearable
    @change="onChange"
  >
    <el-option
      v-for="garden in kindergartenList"
      :key="garden.id"
      :label="garden.kindergartenName"
      :value="garden.id"
    />
  </el-select>
</template>
<script>
import { fetchAllKindergarten } from '@/api/system/branch'

export default {
  name: 'SelectKindergarten',
  model: {
    prop: 'value',
    event: 'update:value'
  },
  props: {
    value: {
      type: String,
      default: ''
    },
    disabled: {
      type: Boolean,
      default: false
    },
    onFilter: {
      type: Function,
      default: null
    }
  },
  data() {
    return {
      kindergartenList: [],
      allkindergarten: []
    }
  },
  computed: {
    localKindergartenId: {
      get() {
        return this.value
      },
      set(val) {
        this.$emit('update:value', val)
      }
    }
  },
  watch: {
    onFilter(fn) {
      this.kindergartenList = fn && typeof fn === 'function' ? fn(this.allkindergarten) : this.allkindergarten
    }
  },
  created() {
    this.getKindergartenList()
  },
  methods: {
    getKindergartenList() {
      fetchAllKindergarten().then(({ data }) => {
        this.allkindergarten = data
        this.kindergartenList = data && data.length > 0
          ? this.onFilter && typeof this.onFilter === 'function' ? this.onFilter(data) : data
          : []
      })
    },
    onChange(val) {
      const row = this.kindergartenList.find(item => item.id === val)
      this.$emit('change', row)
    }
  }
}
</script>

<style scoped lang="scss">

</style>
