import { ref, computed, onBeforeUpdate } from 'vue'
import { CheckboxGroup as VanCheckboxGroup, Checkbox as VanCheckbox, 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, true, 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 checkboxRefs = ref([])
    const checkRefFn = (el, index) => {
      checkboxRefs.value[index] = el
    }
    const cellToggle = (index) => {
      checkboxRefs.value[index].toggle()
    }
    onBeforeUpdate(() => {
      checkboxRefs.value = []
    })

    const checkboxItem = (option, index) => <VanCheckbox shape="square"
      name={option[optionProps.value.value] ?? option}
      ref={el => checkRefFn(el, index)}
      onclick={e => e.stopPropagation()} />
    // 优化操作-cell增加点击事件
    const cellItem = (option, index) => <VanCell v-slots={{ 'right-icon': () => checkboxItem(option, index) }}
      title={option[optionProps.value.label] ?? option}
      onclick={() => cellToggle(index)}
      clickable />
    const checkboxItems = () => options.value.map(cellItem)

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