<template>
  <el-select
    :model-value="modelValue"
    :placeholder="placeholder"
    :disabled="isDisabled"
    :clearable="clearable"
    :filterable="filterable"
    @update:model-value="handleChange"
    @blur="handleBlur"
    @focus="handleFocus"
  >
    <el-option
      v-for="option in options"
      :key="option.value"
      :label="option.label"
      :value="option.value"
      :disabled="option.disabled"
    />
  </el-select>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import type { FieldConfig } from '@/types/form'

interface Props {
  modelValue: any
  field: FieldConfig
  disabled?: boolean
  readonly?: boolean
  clearable?: boolean
  filterable?: boolean
}

interface Emits {
  (e: 'update:modelValue', value: any): void
  (e: 'blur', event: FocusEvent): void
  (e: 'focus', event: FocusEvent): void
}

const props = withDefaults(defineProps<Props>(), {
  clearable: true,
  filterable: true
})

const emit = defineEmits<Emits>()

const placeholder = computed(() => props.field.placeholder || `请选择${props.field.label}`)

const isDisabled = computed(() => {
  if (props.disabled) return true
  if (typeof props.field.disabled === 'function') {
    return false
  }
  return props.field.disabled || false
})

const options = computed(() => props.field.options || [])

const handleChange = (value: any) => {
  emit('update:modelValue', value)
}

const handleBlur = (event: FocusEvent) => {
  emit('blur', event)
}

const handleFocus = (event: FocusEvent) => {
  emit('focus', event)
}
</script>

<style scoped lang="scss">
.el-select {
  width: 100%;
}
</style>
