import { defineComponent, reactive, ref } from 'vue'
import { List } from 'vant'
import request from '@/helpers/request'
import Item from '../list/item'
import { musicBuy } from '../music'
import { useRoute } from 'vue-router'
import ColResult from '@/components/col-result'

export default defineComponent({
  name: 'MusicList',
  emits: ['favorite'],
  setup(props, { expose, emit }) {
    const route = useRoute()
    const params = reactive({
      search: (route.query.search as string) || '',
      musicTagIds: route.query.tagids || '',
      page: 1
    })
    const data = ref<any>(null)
    const rows = ref<any[]>([])
    const loading = ref(false)
    const finished = ref(false)
    const isError = ref(false)

    const FetchList = async () => {
      if (loading.value) {
        return
      }
      loading.value = true
      isError.value = false
      try {
        const res = await request('/api-student/music/sheet/my', {
          params
        })
        rows.value = [...rows.value, ...res.data.rows]
        data.value = res.data
        params.page = res.data.pageNo + 1
        finished.value = res.data.pageNo >= res.data.totalPage
      } catch (error) {
        isError.value = true
      }
      loading.value = false
    }

    expose({
      reset: () => {
        isError.value = false
        rows.value = []
        params.page = 1
        finished.value = false
        FetchList()
      },
      FetchList
    })

    return () => (
      <List
        loading={loading.value}
        finished={finished.value}
        finished-text={rows.value.length ? '没有更多了' : ''}
        onLoad={FetchList}
        error={isError.value}
      >
        {rows.value.length
          ? rows.value.map(item => (
              <Item
                data={item}
                onClick={() => musicBuy(item)}
                onFavorite={() => emit('favorite')}
              />
            ))
          : !loading.value && (
              <ColResult
                tips="暂无单曲"
                classImgSize="SMALL"
                btnStatus={false}
              />
            )}
      </List>
    )
  }
})
