<template>
  <el-select
    v-model="_value"
    :size="size" 
    remote
    :remote-method="onFetch"
    :placeholder="placeholder || '请选择服务分类'"
    :loading="loading"
    reserve-keyword
    filterable
    clearable
  >
    <el-option 
      v-for="item in list" 
      :key="item.id" 
      :value="item.id" 
      :label="item.cat_name"
    />
  </el-select>
</template>


<script>
import asyncRequest from "@/apis/components/search"
export default {
  name:'SearchCategory',
  props:['size', 'value', 'placeholder', 'level'],
  data(){
    return {
      loading: false,
      list: []
    }
  },
  computed:{
    _value:{
        get(){
          return this.value
        },
        set(newVal){
          const current = this.list.find(({id}) => id === newVal)
          this.$emit('update:value', newVal)
          this.$emit('change', current)
        }
    }
  },
  methods:{
    async onFetch(cat_name = ""){
      const { code, data } = await asyncRequest.category({ cat_name })
      if(code !== 1) return
      this.list = data
    },
    async init(id){
      const { code, data } = await asyncRequest.category({})
      if(code !== 1) return
      this.list = data || []
      this._value = id
    }
  }
}
</script>
