<template>
  <el-form-item :prop="prop" :label="label" :label-width="options.labelWidth" :rules="rules">
    <span v-if="options.labelDes" slot="label">{{ label }}
      <el-tooltip width="200" trigger="hover" placement="top" effect="dark" :content="options.labelDes">
        <i class="el-icon-question"></i>
      </el-tooltip>
    </span>
    <el-autocomplete v-model="value" style="width: 100%; min-height: 32px;" :fetch-suggestions="querySuggestions" :trigger-on-focus="options.triggerOnFocus"
      v-bind="props" @select="onSelect" @change="onChange" @blur="onBlur">
      <template slot="prepend" v-if="options.prefixIcon">
        <i :class="options.prefixIcon"></i>
      </template>
      <template slot="append" v-if="options.suffixIcon">
        <i :class="options.suffixIcon"></i>
      </template>
    </el-autocomplete>
  </el-form-item>
</template>

<script lang="ts">

import { Vue, Component } from 'vue-property-decorator'
import { mixins } from 'vue-class-component'
import { AutoCompleteDef, AutoCompleteOptions } from '../../type'
import { ArrayDataOptions } from '../../type/common'
import FieldMixins from './FieldMixins'

@Component
export default class AutoCompleteControl extends mixins(FieldMixins) {
  loading = false

  get options () {
    return Object.assign(new AutoCompleteOptions(), this.def?.options)
  }

  get props () {
    return {
      disabled: this.disabled,
      placeholder: this.options?.placeholder || `请输入${this.def?.label}`,
      clearable: this.options?.clearable,
      maxlength: this.options?.maxlength,
      showWordLimit: this.options?.showWordLimit,
      valueKey: this.options?.valueKey,
      ...(this.options?.attrs || {})
    }
  }

  querySuggestions = (queryString: string, cb: (suggestions: ArrayDataOptions) => void) => {
    console.log('queryString', queryString, this.options)

    const fetchSuggestions = this.options?.remoteMethod
    if (!fetchSuggestions) {
      cb()
      return
    }
    this.loading = true
    try {
      fetchSuggestions(queryString, cb, this.getForm)
    } catch (e) {
      this.loading = false
      throw e
    }
  }

  onSelect (item: any) {
    const fn = this.options?.onSelect
    if (fn) fn({ value: this.value, form: this.actualForm, rowForm: this.rowForm })
  }

  onChange (val: any) {
    const fn = this.options?.onChange
    if (fn) fn({ value: this.value, form: this.actualForm, rowForm: this.rowForm })
  }

  onBlur (val: any) {
    const fn = this.options?.onBlur
    if (fn) fn({ value: this.value, form: this.actualForm, rowForm: this.rowForm })
  }

  def!: AutoCompleteDef
}
</script>
