<template>
  <el-form-item
    :label="showLabel ? label: ''"
    :rules="[...requireRule(required, label, validate), ...rules]"
    :prop="prop"
    :label-width="labelWidth"
  >
    <el-autocomplete
      v-model.trim="formRef.model[prop]"
      :style="{ width }"
      :placeholder="placeholder || `请输入${label}`"
      :fetch-suggestions="querySearch"
      @select="handleSelect"
      @change="handleChange"
      :clearable="clearable"
      :disabled="disabled"
      :maxlength="maxlength"
    ></el-autocomplete>
  </el-form-item>
</template>

<script>
import mixin from "./mixin";
/**
 * 输入框组件
 */
export default {
  mixins: [mixin],
  props: {
    query: {
      type: Function,
      default: () => {},
    },
    pickerLabel: {
      type: Function,
      default: (item) => item,
    },
    maxlength: {
      type: Number,
      default: 20,
    },
    labelWidth: {
      type: String
    },
    trigger: {
      type: String,
      default:'blur'
    }
  },
  methods: {
    querySearch(queryString, cb) {
      this.query(queryString).then(res => {
        if (res.code === 0 || res.code===200) {
          if (res.data){
            cb(res.data.map(item => ({value: this.pickerLabel(item), ...item})))
          }else {
            cb(res.rows.map(item => ({value: this.pickerLabel(item), ...item})))
          }
        } else {
          cb([])
        }
      })
    },
    handleSelect(option){
      this.$emit('selected', this.formRef.model, option)
    },
    handleChange(option){
      this.$emit('changed', this.formRef.model, option)
    },
    focus() {
      this.$emit("focus");
    },
  },
};
</script>

<style>
.el-autocomplete-suggestion{
  min-width: 200px;
  width: auto !important;
}
</style>
