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

import { Button, Divider, Input, Select } from 'ant-design-vue';

export interface RemoteOption {
  label: string;
  value: string;
  /** 是否为用户自由输入生成的兜底项 */
  __custom?: boolean;
}

const props = defineProps<{
  /** 选项数据 */
  options?: any | { value: string }[];
  /** 占位符 */
  placeholder?: string;
  /** v-model */
  value?: string;
}>();

const emit = defineEmits(['update:value']);

const VNodes = defineComponent({
  props: {
    vnodes: {
      type: Object,
      required: true,
    },
  },
  render() {
    return this.vnodes;
  },
});

const items = ref<{ value: string }[]>(props.options || []);
// const value = computed(() => props.value || items.value[0]?.value);
const value = ref(props.value || items.value[0]?.value);
const inputRef = ref();
const inputValue = ref('');

// 监听 props.value 变化，更新本地 value
watch(
  () => props.options,
  (newValue) => {
    value.value = props.value && props.value !== '' ? props.value : newValue.value[0]?.value;
  },
  { immediate: true, deep: true },
);

// 监听本地 value 变化，触发 update:value 事件
watch(value, (newValue) => {
  emit('update:value', newValue);
});

const addItem = (e: Event) => {
  e.preventDefault();
  const newItemValue = inputValue.value;
  items.value.push({
    value: newItemValue,
  });
  // 将新添加的选项设为选中值
  value.value = newItemValue;
  inputValue.value = '';
  setTimeout(() => {
    inputRef.value?.focus();
  }, 0);
};
</script>
<template>
  <Select v-model:value="value" placeholder="请选择或新增" :options="items">
    <template #dropdownRender="{ menuNode: menu }">
      <VNodes :vnodes="menu" />
      <Divider style="margin: 4px 0" />
      <div style="padding: 4px 8px; display: flex">
        <Input
          ref="inputRef"
          v-model:value="inputValue"
          placeholder="在此手动输入"
          style="flex: 1"
        />
        <Button type="text" @click="addItem">
          <template #icon>
            <!-- <PlusOutlined /> -->
          </template>
          新增
        </Button>
      </div>
    </template>
  </Select>
</template>
