import { defineComponent, reactive, ref } from 'vue'
import { List } from 'vant'
import request from '@/helpers/request'
import Item from '../album/item'
import { useRoute, useRouter } from 'vue-router'
import ColResult from '@/components/col-result'
import { state } from '@/state'
import MusicGrid from '../component/music-grid'
import styles from './index.module.less'

export default defineComponent({
  name: 'MusicList',
  setup() {
    const route = useRoute()
    const router = useRouter()
    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('/music/album/favorite', {
          prefix:
            state.platformType === 'TEACHER' ? '/api-teacher' : '/api-student',
          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
    }

    return () => (
      <List
        loading={loading.value}
        finished={finished.value}
        finished-text={rows.value.length ? '没有更多了' : ''}
        onLoad={FetchList}
        error={isError.value}
      >
        {rows.value.length ? (
          <div class={styles.musicGrid}>
            <MusicGrid
              list={data.value.rows}
              onGoto={(n: any) => {
                router.push({
                  name: 'music-album-detail',
                  params: {
                    id: n.id
                  }
                })
              }}
            />
          </div>
        ) : (
          !loading.value && (
            <ColResult
              tips="暂无收藏专辑"
              classImgSize="SMALL"
              btnStatus={false}
            />
          )
        )}
      </List>
    )
  }
})
