<template>
  <FlexView :direction="vertical ? 'column' : 'row'" align="center" :gap="10" wrap>
    <ActivityIndicator v-if="loadStatus === 'loading'" />
    <Alert
      v-else-if="loadStatus === 'error'" 
      message="加载失败" 
      description="点击重新加载" 
      type="error" 
      @click="handleLoadData"
    />
    <CheckBoxGroup 
      v-else 
      :modelValue="modelValue"
      :disabled="disabled"
      :multiple="multiple"
      @update:modelValue="handleChange" 
    >
      <CheckBox
        v-for="value in data2"
        :key="value.value"
        :name="value.value"
        :text="value.text" 
        :disabled="value.disable"
      />
    </CheckBoxGroup>
  </FlexView>
</template>

<script setup lang="ts">
import ActivityIndicator from '@/components/basic/ActivityIndicator.vue';
import Alert from '@/components/feedback/Alert.vue';
import CheckBox from '@/components/form/CheckBox.vue';
import CheckBoxGroup from '@/components/form/CheckBoxGroup.vue';
import FlexView from '@/components/layout/FlexView.vue';
import { onMounted, ref, type PropType } from 'vue';

export interface CheckBoxListItem {
  text: string;
  value: any;
  disable?: boolean;
}
export interface CheckBoxListProps {
  multiple?: boolean,
  disabled?: boolean,
  vertical?: boolean,
  className?: string,
  loadData: () => Promise<CheckBoxListItem[]>;
}

const props = defineProps({
  modelValue: {
    type: Array as PropType<string[]>,
    default: () => []
  },
  loadData: {
    type: Function as PropType<CheckBoxListProps['loadData']>,
    default: () => Promise.resolve([])
  },
  disabled: {
    type: Boolean,
    default: false
  },
  multiple: {
    type: Boolean,
    default: false
  },
  className: {
    type: String,
    default: ''
  },
  vertical: {
    type: Boolean,
    default: false
  },
})
const emit = defineEmits(['update:modelValue', 'change'])

const loadStatus = ref<'loading' | 'error' | 'success'>('loading');
const loadError = ref('');
const data2 = ref<CheckBoxListItem[]>([]);

const handleChange = (checkedValues: any[]) => {
  emit('update:modelValue', checkedValues);
  emit('change', checkedValues);
}
const handleLoadData = () => {
  loadStatus.value = 'loading';
  loadError.value = '';
  
  props.loadData().then((v) => {
    data2.value = v;
    loadStatus.value = 'success';
  }).catch((e) => {
    loadError.value = e.message || '加载失败';
    loadStatus.value = 'error';
  });
}
const reload = () => {
  handleLoadData();
}

defineExpose({ reload });

onMounted(() => {
  handleLoadData();
});
</script>