import { computed } from 'vue'
import { RadioGroup as VanRadioGroup, Radio as VanRadio, cell as VanCell } from 'vant'
import { useFormInput, useOptions } from '../../../hooks/form-input'
import { formInputProps } from '../../form-input-props'
export default {
  props: formInputProps,
  setup (props, context) {
    const { emitModelValue, width, ...formInput } = useFormInput(props, context)
    const { optionProps, options, getValue, getModelValue, getOtherValue } = useOptions(props, false, formInput.emitInput)
    // 另一个键
    const otherKey = computed(() => {
      return props.config?.otherKey ?? ''
    })
    const proxyValue = computed(() => {
      return getValue(props.modelValue)
    })
    const emitInput = (value) => {
      const modelValue = getModelValue(value)
      context.emit('update:modelValue', modelValue)
      if (otherKey.value) {
        const otherValue = getOtherValue(modelValue, value)
        context.emit('update:otherValue', otherValue)
      }
    }

    const radioItem = (option) => <VanRadio name={option[optionProps.value.value] ?? option} />
    // 优化操作-cell增加点击事件
    const cellItem = (option) => <VanCell v-slots={{ 'right-icon': () => radioItem(option) }}
      title={option[optionProps.value.label] ?? option}
      onclick={() => emitInput(option[optionProps.value.value] ?? option)}
      clickable />
    const radioItems = () => options.value.map(cellItem)

    return () => <VanRadioGroup modelValue={proxyValue.value}
      onUpdate:modelValue={emitInput}
      style={{ width: width.value }}>
      {radioItems()}
    </VanRadioGroup>
  }
}
