<template>
  <div class="kintoneplugin-input-container flex-row">
    <plugin-label v-if="label" :label="label" :required-icon="requiredIcon" />
    <kuc-text v-bind="textProps" :value="modelValue" @change="updateValue" />
  </div>
</template>

<script setup lang="ts">
import type { KucEvent } from '@/types/my-kintone';
import type { TextProps, TextInputEventDetail } from 'kintone-ui-component/lib/text';
import { defineProps, defineEmits, computed } from 'vue';

// kuc 不支持 v-model 的写法，所以如果想要使用需要包装一下
const props = withDefaults(defineProps<TextProps & {
  modelValue: string;
}>(), {
  // boolean 的处理有点问题，这里手动重新定义
  disabled: undefined,
  requiredIcon: undefined,
  visible: undefined
});

const emit = defineEmits<{
  (e: 'update:modelValue', value: string): void;
}>();

const textProps = computed<TextProps>(() => {
  const baseProps = {
    ...props,
    label: '', // 在 plugin-label 处显示 label，不传入 text
    className: `kuc-text-input${props.className ? ` ${props.className}` : ''}`,
  };

  // 过滤掉所有值为 undefined 的属性
  return Object.fromEntries(
    Object.entries(baseProps).filter(([_, value]) => value !== undefined)
  ) as TextProps;
});

const updateValue = ({ detail }: KucEvent<TextInputEventDetail>) => {
  emit('update:modelValue', detail.value || '');
};
</script>
