import { defineComponent, onMounted, PropType, ref } from 'vue'
import { List } from 'vant'
import Empty from '/src/components/empty'
import request from '/src/helpers/request'
import Item from './base-item'
import { MusicSheelDetail } from '../index.d'
import styles from './base.module.less'

export default defineComponent({
  name: 'MusicList-MusicScore-List',
  props: {
    list: {
      type: Array as PropType<MusicSheelDetail[]>,
      default: () => [],
    },
    url: {
      type: String,
      default: '',
    },
    moreSearch: {
      type: Object,
      default: () => ({}),
    },
  },
  emits: ['refresh'],
  setup(props, { emit }) {
    const loading = ref(false)
    const finished = ref(false)
    const page = ref(1)
    const list = ref<MusicSheelDetail[]>([])
    const listRef = ref()

    const FetchList = async () => {
      if (!props.url) {
        return
      }
      loading.value = true
      try {
        const res = await request(props.url, {
          params: {
            page: page.value,
            ...props.moreSearch,
          },
        })
        list.value = [...list.value, ...res.data.rows]
        finished.value = res.data.totalPage < page.value
      } catch (error) {}
      loading.value = false
    }

    onMounted(FetchList)

    const loadMore = () => {
      if (!loading.value && !finished.value) {
        page.value = page.value + 1
        FetchList()
      }
    }

    return () => {
      // if (loading.value) {
      //   return <Loading />
      // }
      if (!list.value.length && !loading.value) {
        return (
          <Empty description="暂无曲目">
            <span></span>
          </Empty>
        )
      }
      return (
        <div class={styles.tab}>
          <List ref={listRef} class={styles.list} loading={loading.value} finished={finished.value} onLoad={loadMore}>
            {list.value.map((item) => (
              <Item item={item} key={item.id} />
            ))}
          </List>
        </div>
      )
    }
  },
})
