<script>
import Select from 'element-ui/lib/select'

export default Object.assign({}, Select, {
  props: Object.assign({}, Select.props, {
    newOption: {
      type: Object
    },
    textField: {
      type: String
    }
  }),
  computed: Object.assign({}, Select.computed, {
    showClose() {
      if (this.newOption) {
        const hasValue = this.multiple
          ? Array.isArray(this.value) && this.value.length > 0
          : this.value !== undefined && this.value !== '';
        const criteria = this.clearable &&
          !this.selectDisabled &&
          this.inputHovering &&
          hasValue;
        return criteria;
      } else {
        const hasValue = this.multiple
          ? Array.isArray(this.value) && this.value.length > 0
          : this.value !== undefined && this.value !== null && this.value !== '';
        const criteria = this.clearable &&
          !this.selectDisabled &&
          this.inputHovering &&
          hasValue;
        return criteria;
      }
    }
  }),
  watch: Object.assign({}, Select.watch, {
    visible(newVal, oldVal) {
      if (!newVal) {
        if (this.newOption) {
          if (this.value === null && (this.selected || !this.selected.currentLabel)) {
            this.setSelected()
          }
        }
      }
      Select.watch.visible.call(this, newVal, oldVal)
    }
  }),
  methods: Object.assign({}, Select.methods, {
    handleQueryChange(val) {
      if (this.previousQuery === val || this.isOnComposition) return;
      if (
        this.previousQuery === null &&
        (typeof this.filterMethod === 'function' || typeof this.remoteMethod === 'function')
      ) {
        if (this.remote && typeof this.remoteMethod === 'function') {
          this.remoteMethod(val);
        } else if (typeof this.filterMethod === 'function') {
          this.filterMethod(val);
        }
      }
      Select.methods.getOption.call(this, val)
    },
    deleteSelected(event) {
      this.$emit('before-clear')
      Select.methods.deleteSelected.call(this, event)
    },
    getOption(value) {
      if (value === null && this.newOption) {
        return {
          value: null,
          currentLabel: this.newOption[this.textField]
        }
      }
      return Select.methods.getOption.call(this, value)
    }
  })
})
</script>
