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

const props = withDefaults(
  defineProps<
    {
      modelValue: CheckboxGroupValueType | undefined | null
      style?: StrAnyObj
      disabled: boolean
      change?: (value: any) => void
    } & FormOptionType
  >(),
  {
    autoLoadOption: true,
    keyName: 'key',
    labelName: 'label',
    disabledName: 'disabled'
  }
)

const options = ref<StrAnyObjArr>([])

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

const computedModelValue = computed({
  get() {
    if (props.modelValue === undefined || props.modelValue === null) {
      return []
    }
    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-checkbox-group
    v-model="computedModelValue"
    :disabled="disabled"
    :style="style"
    @change="(value: any) => change?.(value)"
  >
    <el-checkbox
      v-for="item in options"
      :key="item[props.dict ? 'value' : keyName]"
      :label="item[props.dict ? 'label' : labelName]"
      :value="item[props.dict ? 'value' : keyName]"
      :disabled="item[disabledName]"
      border
    />
  </el-checkbox-group>
</template>
