<template>
  <span v-if="!focus" @click.stop="toggleFocus">
    {{valName}}
    <span class="empty-tip" v-if="!value">(empty)</span>
  </span>
  <el-select ref="ctl" v-model="inputVal" @change="handleChange" v-else>
    <el-option
      v-for="item in dict"
      :key="item.value"
      :label="item.label"
      :value="item.value">
    </el-option>
  </el-select>
</template>

<script>
export default {
  name: 'editable-select',
  props: [
    'value',
    'dict',
  ],
  computed: {
    valName () {
      return ((this.dict || []).filter(x => x.value === this.value)[0] || {}).label
    },
  },
  data () {
    return {
      focus: false,
      inputVal: undefined,
    }
  },
  mounted () {
    if (!window['__editable-blur']) {
      window['__editable-blur'] = () => {}
    }
  },
  methods: {
    toggleFocus () {
      window['__editable-blur']()
      window['__editable-blur'] = this.handleBlur.bind(this)

      this.focus = true
      this.inputVal = this.value
      this.$nextTick(() => {
        if (this.$refs.ctl) this.$refs.ctl.focus()
      })
    },
    handleBlur () {
      this.focus = false
    },
    handleChange() {
      this.focus = false

      if (this.inputVal != this.value) {
        this.$emit('change', this.inputVal )
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.empty-tip {
  font-size: 0.8em;
  color: #aaa;
}
</style>
