<template>
  <view class="form-input">
    <view class="form-input__label" v-if="label">
      {{ label }}
      <text class="form-input__required" v-if="required">*</text>
    </view>
    <view class="form-input__wrapper">
      <input
        class="form-input__field"
        :type="type"
        :placeholder="placeholder"
        :value="modelValue"
        :disabled="disabled"
        :maxlength="maxlength"
        @input="handleInput"
        @blur="handleBlur"
        @focus="handleFocus"
      />
      <view class="form-input__suffix" v-if="$slots.suffix">
        <slot name="suffix"></slot>
      </view>
    </view>
    <view class="form-input__error" v-if="error">{{ error }}</view>
  </view>
</template>

<script setup>
// 定义props
const props = defineProps({
  // 输入框的值
  modelValue: {
    type: [String, Number],
    default: ''
  },
  // 标签
  label: {
    type: String,
    default: ''
  },
  // 占位符
  placeholder: {
    type: String,
    default: ''
  },
  // 输入框类型
  type: {
    type: String,
    default: 'text'
  },
  // 是否必填
  required: {
    type: Boolean,
    default: false
  },
  // 是否禁用
  disabled: {
    type: Boolean,
    default: false
  },
  // 最大长度
  maxlength: {
    type: Number,
    default: 140
  },
  // 错误信息
  error: {
    type: String,
    default: ''
  }
})

// 定义emits
const emit = defineEmits(['update:modelValue', 'blur', 'focus'])

/**
 * 处理输入事件
 * @param {Event} e 输入事件对象
 */
function handleInput(e) {
  emit('update:modelValue', e.detail.value)
}

/**
 * 处理失去焦点事件
 * @param {Event} e 失去焦点事件对象
 */
function handleBlur(e) {
  emit('blur', e.detail.value)
}

/**
 * 处理获得焦点事件
 * @param {Event} e 获得焦点事件对象
 */
function handleFocus(e) {
  emit('focus', e.detail.value)
}
</script>

<style lang="scss" scoped>
.form-input {
  margin-bottom: 32rpx;
  
  &__label {
    font-size: 28rpx;
    color: #333;
    margin-bottom: 16rpx;
  }
  
  &__required {
    color: #ff4d4f;
    margin-left: 4rpx;
  }
  
  &__wrapper {
    display: flex;
    align-items: center;
    border: 1rpx solid #d9d9d9;
    border-radius: 8rpx;
    padding: 0 24rpx;
    background-color: #fff;
  }
  
  &__field {
    flex: 1;
    height: 80rpx;
    font-size: 28rpx;
    color: #333;
  }
  
  &__suffix {
    margin-left: 16rpx;
  }
  
  &__error {
    font-size: 24rpx;
    color: #ff4d4f;
    margin-top: 8rpx;
  }
}
</style>