<template>
  <div>
    <Poptip v-model="open" placement="bottom" :transfer="true" :width="width">
      <Input
        :style="{width: width}"
        v-model="inputLabel"
        :placeholder="placeholder"
        :size="size"
        :clearable="true"
        :icon="open? 'ios-arrow-up' : 'ios-arrow-down'"
        @on-focus="focus"
        @on-clear="clear"
        @on-blur="blur"
      />
      <div slot="content">
        <div class="list">
          <div
              class="item"
              v-for="(item, index) in showList"
              :key="index"
              @click="itemClick(item, index)"
          >
            {{ item[labelKey] }}
          </div>
        </div>
      </div>
    </Poptip>
  </div>
</template>

<script>
export default {
  name: 'my-select-input',
  data () {
    return {
      inputLabel: '',
      inputValue: '',
      open: false
    }
  },
  props: {
    width: {
      type: String | Number,
      default: ''
    },
    labelKey: {
      type: String,
      default: 'key'
    },
    list: {
      type: Array,
      default () {
        return []
      }
    },
    size: {
      type: String,
      default: ''
    },
    placeholder: {
      type: String,
      default: ''
    },
    data: {
      type: Object,
      default () {
        return {}
      }
    },
    value: {
      type: String | Number,
      default: '',
      require: true
    }
  },
  watch: {
    value: {
      handler (val) {
        this.inputValue = val
      },
      immediate: true
    },
    inputValue (val) {
      this.$emit('input', val)
      if (val === '' || val === null) {
        this.inputLabel = ''
      }
    },
    inputLabel (val) {
      this.$emit('input', val)
    }
  },
  computed: {
    showList () {
      return this.list.filter(item => {
        return String(item[this.labelKey]).indexOf(this.inputLabel) !== -1
      })
    }
  },
  methods: {
    itemClick (item, index) {
      this.inputLabel = item[this.labelKey]
      this.inputValue = item.value
      this.open = false
    },
    clear () {
      setTimeout(() => {
        this.open = true
      }, 10)
    },
    focus () {
    },
    blur () {
    }
  }
}
</script>

<style lang="less" scoped>
.list {
  max-height: 200px;
  overflow: auto;
  .item {
    padding: 5px 10px;
    cursor: pointer;
    &:hover {
      background-color: #eeeeee;
    }
  }
}
/deep/ .ivu-poptip-arrow {
  display: none !important;
}
/deep/ .ivu-poptip-rel {
  width: 100%;
}
</style>
