<script lang="ts" setup>
import { computed, reactive, ref, unref, watch } from 'vue'
import { useDataSource } from './hooks/useDataSource'
import { usePagination } from './hooks/usePagination'

defineOptions({ name: 'CollapseItem' })

const props = defineProps({
  title: {
    type: String,
    default: '',
    required: true,
  },
  name: {
    type: String,
    default: '',
    required: true,
  },
  dataSource: {
    type: Array as PropType<TagOption[]>,
    default: () => [],
  },
  request: {
    type: Function as PropType<(...arg: any[]) => Promise<any>>,
    default: null,
  },
  pagination: {
    type: Object as PropType<PageParam>,
    default: () => ({
      pageNo: 1,
      pageSize: 20,
    }),
  },
})

const emit = defineEmits<{
  (e: 'update:checked-keys', value: string[]): void
  (e: 'fetch-success', value: TagOption[])
}>()

interface TagOption {
  key: string
  label: string
}

interface PageParam {
  pageNo: number
  pageSize: number
}

const colorStyle = {
  color: '#BBB',
  textColor: '#555',
  borderColor: '#555',
}

const checkedKeys = reactive<string[]>([])

function handleChange(key: string, value: boolean) {
  const checked = value

  if (checked) {
    checkedKeys.push(key)
  }
  else {
    const index = checkedKeys.indexOf(key)
    if (index !== -1)
      checkedKeys.splice(index, 1)
  }

  emit('update:checked-keys', checkedKeys)
}

function isChecked(key: string) {
  return checkedKeys.includes(key)
}

const optionData = ref<TagOption[]>([])

watch(optionData, () => {
  const data = unref(optionData)
  const firstOptionKey = data.length > 0 ? data[0].key : null

  if (firstOptionKey)
    checkedKeys.push(firstOptionKey)
})

const getProps = computed(() => {
  return { ...props }
})

const { getPagination } = usePagination(getProps)

useDataSource(getProps, { optionData, getPagination }, emit)
</script>

<template>
  <n-collapse-item :title="title" :name="name">
    <n-space>
      <n-tag
        v-for="item in optionData" :key="item.key" class="aside-tag-item" :checked="isChecked(item.key)"
        :color="colorStyle" checkable @update:checked="handleChange(item.key, $event)"
      >
        {{ item.label }}
      </n-tag>
    </n-space>
  </n-collapse-item>
</template>

<style lang="less" scoped></style>
