<!--
 * @Description: 内嵌label表单（input、select）
 * @Autor: Heloise
 * @Date: 2022-05-24 09:43:48
 * @LastEditors: Heloise
 * @LastEditTime: 2022-10-20 17:46:21
-->
<template>
  <div
    ref="inlineFormItem"
    class="el-inline-form-item"
    :class="[`el-inline-form-item-${type}`]"
  >
    <el-input
      v-if="type === 'input'"
      ref="labelInput"
      v-bind="$attrs"
      v-on="$listeners"
      v-model="inlineValue"
      @focus="onfocus"
      @blur="onblur"
    >
      <template slot="prefix">{{ label }}：</template>
    </el-input>
    <div v-if="type === 'select'" tabindex="0" @blur="onblur" @focus="onfocus">
      <el-select
        ref="labelSelect"
        v-bind="$attrs"
        v-on="$listeners"
        v-model="inlineValue"
        :multiple="multiple"
        :labelWidth="labelWidth"
        @blur="onblur()"
        @focus="onfocus('inner')"
      >
        <template slot="prefix">{{ label }}：</template>
        <el-option
          v-for="item in options"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
        </el-option>
      </el-select>
    </div>
  </div>
</template>

<script>
export default {
  name: 'ElInlineFormItem',
  props: {
    type: {
      type: String, // 输入框、下拉选择器
      default: 'input'
    },
    multiple: {
      type: Boolean,
      default: false
    },
    label: String, // 标签名称
    value: [String, Number, Array],
    options: {
      type: Array, // 下拉选择器选择项
      default: () => []
    }
  },
  data() {
    return {
      str: '', // ref名称
      labelWidth: 0 // 标签宽度
    };
  },
  computed: {
    inlineValue: {
      get() {
        return this.value;
      },
      set(value) {
        this.$emit('input', value);
      }
    }
  },
  mounted() {
    this.str = `label${this.type.slice(0, 1).toUpperCase()}${this.type
      .slice(1)
      .toLowerCase()}`;

    this.labelWidth = this.$refs[this.str]
      ? this.$refs[this.str].$el
        .getElementsByClassName('el-input__prefix')[0]
        .getBoundingClientRect().width
      : 0;
  },
  methods: {
    onfocus(string) {
      if (string === 'inner') {
        if (!this.multiple) {
          this.$refs[this.str].$el.style.boxShadow = '0px 1px 4px 0px #A3B6FE';
        }
      } else {
        this.$refs[this.str].$el.style.boxShadow = '0px 1px 4px 0px #A3B6FE';
      }
    },
    onblur() {
      this.$refs[this.str].$el.style.boxShadow = 'none';
    }
  }
};
</script>
