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

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 rows = ref<any[]>([])
    const data = ref<any>(null)
    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/favorite', {
          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
    }

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

    expose({
      reset,
      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={() => {
                  reset()
                  emit('favorite')
                }}
              />
            ))
          : !loading.value && (
              <ColResult
                tips="暂无收藏单曲"
                classImgSize="SMALL"
                btnStatus={false}
              />
            )}
      </List>
    )
  }
})
