<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" 
    >
      <FlexCol>
        <CheckBoxTreeListItem
          v-for="item in data2"
          :key="item.value"
          :item="item"
        />
      </FlexCol>
    </CheckBoxGroup>
  </FlexView>
</template>

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

export interface CheckBoxTreeListItem {
  text: string;
  value: any;
  disable?: boolean;
  hasChildren?: boolean;
  children?: CheckBoxTreeListItem[];
}
export interface CheckBoxTreeListProps {
  multiple?: boolean,
  disabled?: boolean,
  vertical?: boolean,
  className?: string,
  loadData: (pid?: number) => Promise<CheckBoxTreeListItem[]>;
}

const props = defineProps<CheckBoxTreeListProps & {
  modelValue?: string[],
}>();
const emit = defineEmits(['update:modelValue', 'change'])

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

provide('loadData', props.loadData);

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>