<template>
  <el-select
    class="article-tag-select"
    :class="{select__block: !inline}"
    :placeholder="placeholder"
    :clearable="clearable"
    :disabled="disabled"
    :multiple="multiple"
    :model-value="modelValue"
    filterable
    remote
    :remote-method="fetchList"
    @update:modelValue="$emit('update:modelValue', $event)"
    @change="$emit('change', $event)"
    @input="$emit('input', $event)"
  >
    <el-option
      v-for="data in computedList"
      :key="data.id"
      :value="data[valueKey]"
      :label="data.title"
    />
  </el-select>
</template>

<script>
import { fetchProfileList4Select } from '@/api/cms/article'

export default {
  name: 'ArticleSelect',
  props: {
    modelValue: {},
    valueKey: {
      default: 'id'
    },
    disabled: {
      default: false
    },
    placeholder: {
      default: '请选择文章'
    },
    inline: {
      default: true
    },
    multiple: {
      default: false
    },
    clearable: {
      default: true
    },
    // 顶部补充的选项列表
    firstOptions: {
      type: Array,
      default () {
        return []
      }
    }
  },
  data () {
    return {
      loading: false,
      list: []
    }
  },
  computed: {
    computedList () {
      return [
        ...this.firstOptions,
        ...this.list
      ]
    }
  },
  methods: {
    // 查询数据
    fetchList (kwd = '') {
      if (this.loading) {
        return
      }
      this.loading = true
      fetchProfileList4Select({
        uids: this.modelValue == null ? [] : [this.modelValue],
        kwd
      })
        .then(data => {
          this.list = data
        })
        .catch(e => {
          this.$tip.apiFailed(e)
        })
        .finally(() => {
          this.loading = false
        })
    }
  },
  created () {
    this.fetchList()
  }
}
</script>
<style lang="scss" scoped>
.select__block {
  display: block;
}
</style>
