<script setup lang="ts">
import { EpPropMergeType } from 'element-plus/es/utils'
import { StrAnyObj, StrAnyObjArr } from '@/typings'
import { FormOptionType } from '@/components/AForm/type'
import { getAsyncResult, getResult } from '@/utils'
import { getDictByCode } from '@/utils/dict'

const props = withDefaults(
  defineProps<
    {
      modelValue: EpPropMergeType<
        readonly [StringConstructor, NumberConstructor, BooleanConstructor],
        unknown,
        unknown
      >
      style?: StrAnyObj
      disabled?: boolean
      change?: (value: any) => void
    } & FormOptionType
  >(),
  {
    disabled: false,
    autoLoadOption: true,
    keyName: 'key',
    labelName: 'label',
    disabledName: 'disabled'
  }
)

const options = ref<StrAnyObjArr>([])

const emits = defineEmits(['update:modelValue'])

const computedModelValue = computed({
  get() {
    return props.modelValue
  },
  set(newValue) {
    emits('update:modelValue', newValue)
  }
})

defineExpose({ loadOption, reloadOption, clearOption })

if (props.autoLoadOption) {
  loadOption()
}

function loadOption() {
  if (props.dict) {
    getDictByCode(props.dict).then((resp) => {
      options.value = resp
    })
  } else {
    getAsyncResult<StrAnyObjArr>(props.option, []).then((resp) => {
      options.value = resp
    })
  }
}

function reloadOption() {
  clearOption()
  loadOption()
}

function clearOption() {
  emits('update:modelValue', null)
  options.value = []
}
</script>

<template>
  <el-radio-group
    v-model="computedModelValue"
    :disabled="disabled"
    :style="style"
    @change="(value: any) => change?.(value)"
  >
    <el-radio
      v-for="item in options"
      :key="item[props.dict ? 'value' : keyName]"
      :label="item[props.dict ? 'label' : labelName]"
      :value="item[props.dict ? 'value' : keyName]"
      :disabled="getResult(item[disabledName], false)"
      border
    />
  </el-radio-group>
</template>
