<script setup lang="ts">
import {useCodes} from '/src/stores/codeStore.ts'

const detailCode = useCodes()
export interface VSelectProps {
  raw?: boolean
  multiple?: boolean
  cd_grp?: string
  placeholder?: string
}

defineOptions({
  inheritAttrs: false,
})

const modelValue = defineModel<any>({
  default: '',
})
const props = defineProps<VSelectProps>()
const attrs = useAttrs()

const { field, id } = useVFieldContext({
  create: false,
  help: 'VSelect',
})

const internal = computed({
  get() {
    if (field?.value) {
      return field.value.value
    }
    else {
      return modelValue.value
    }
  },
  set(value: any) {
    if (field?.value) {
      field.value.setValue(value)
    }
    modelValue.value = value
  },
})

const classes = computed(() => {
  if (props.raw) return []

  return ['select', props.multiple && 'is-multiple']
})

const cdItems = ref<Array<{ cd: string; nm: string }>>([])

watch(() => props.cd_grp, async (newVal) => {
  if (newVal) {
    await detailCode.setDetailCode(newVal)
    cdItems.value = detailCode.getCodeList(newVal)
  }
}, { immediate: true })
</script>

<template>
  <div :class="classes">
    <select
      :id="id"
      v-bind="attrs"
      v-model="internal"
      :name="id"
      :multiple="props.multiple"
      @change="field?.handleChange"
      @blur="field?.handleBlur"
    >
      <option value="">{{ props.placeholder || '선택하세요' }}</option>
      <option
        v-for="item in cdItems"
        :key="item.cd"
        :value="item.cd"
      >
        <slot name="code" :item="item">
          {{ item.nm }}
        </slot>
      </option>
    </select>
  </div>
</template>
