<template>
  <div class="et-select">
    <el-select v-bind="$attrs" v-on="$listeners" v-load-more="onRemoteMore" :popper-class="popperClass">
      <template v-if="$slots.prefix" #prefix>
        <!--
          @slot Select 组件头部内容
        -->
        <slot name="prefix"></slot>
      </template>
      <template v-if="$slots.empty" #empty>
        <!--
          @slot 无选项时的列表
        -->
        <slot name="empty"></slot>
      </template>
      <template v-if="$slots.default" #default>
        <!--
          @slot Option 组件列表
        -->
        <slot></slot>
        <div class="scroll-loading" v-if="scrollLoading">{{ scrollLoadingText }}</div>
      </template>
    </el-select>
  </div>
</template>

<script lang="ts">
import { Component, Vue, Prop } from 'vue-property-decorator'
import { LoadMore } from './directive'

/**
 * 封装 element-ui 组件库 Select 选择器
 * @see https://element.eleme.cn/#/zh-CN/component/select
 */
@Component({
  name: 'EtSelect',
  directives: {
    LoadMore,
  },
})
export default class extends Vue {
  /**
   * 是否滚动到底部加载
   */
  @Prop({ default: false, type: Boolean }) private scrollMore!: boolean
  /**
   * 是否正在滚动加载
   */
  @Prop({ default: false, type: Boolean }) private scrollLoading!: boolean
  /**
   * 滚动加载时显示的文字
   */
  @Prop({ default: '加载中', type: String }) private scrollLoadingText!: string
  /**
   * 滚动到底部加载触发方法
   */
  @Prop({ type: Function }) private scrollMoreMethod!: Function
  /**
   * Select 下拉框高度
   */
  @Prop({ default: 150, type: Number }) private dropdownHeight!: number

  mounted() {
    if (this.$el) {
      const el = this.$el
      const wrapper = el.querySelector('.el-select-dropdown .el-select-dropdown__wrap')
      if (wrapper) (wrapper as HTMLElement).style.height = this.dropdownHeight + 'px'
    }
  }

  get popperClass() {
    if (this.scrollMore) {
      return 'scroll-more'
    }
    return ''
  }

  private onRemoteMore() {
    if (this.scrollMore && typeof this.scrollMoreMethod === 'function' && !this.scrollLoading) {
      this.scrollMoreMethod()
    }
  }
}
</script>
