<template>
  <div class="selectable-input-container">
    <el-input
      v-model="modelValue"
      style="width: 360px"
      :placeholder="selectValue.placeholder || '请输入' + selectValue.label"
      clearable
    >
      <template #prepend>
        <el-select
          v-model="selectValue"
          style="width: 100px"
          value-key="value"
          :validate-event="false"
          @change="modelValue = ''"
        >
          <el-option
            v-for="item in options"
            :key="item.value"
            :value="item"
            :label="item.label"
            :disabled="item.disabled"
          />
        </el-select>
      </template>
    </el-input>
  </div>
</template>

<script setup lang="ts">
  import { ref } from 'vue';

  const props = defineProps<{
    options: SelectOption[]; // options.value为选择的键
  }>();

  const modelValue = ref(); // modelValue 为输入的值
  const selectValue = ref<SelectOption>(props.options[0]);

  function setValue(key: string, val: string) {
    if (!props.options.some((item) => item.value === key)) return;
    selectValue.value = props.options.find((item) => item.value === key)!;
    modelValue.value = val;
  }

  function getValue() {
    if (!modelValue.value) return null;
    return {
      key: selectValue.value.value,
      value: modelValue.value,
    };
  }
  function clearValue() {
    selectValue.value = props.options[0];
    modelValue.value = undefined;
  }

  defineExpose({
    setValue,
    getValue,
    clearValue,
  });
</script>

<style scoped></style>
