import { defineComponent, reactive, ref, watch } from 'vue'
import { List } from 'vant'
import request from '@/helpers/request'
import { useRoute, useRouter } from 'vue-router'
import ColResult from '@/components/col-result'
import { state } from '@/state'
import styles from './index.module.less'
import Song from '../component/song'
import { number } from 'echarts/core'

export default defineComponent({
  name: 'MusicList',
  emits: ['favorite'],
  props: {
    gift: {
      type: Number,
      default: 0
    }
  },
  setup(props, { expose, emit }) {
    const route = useRoute()
    const router = useRouter()
    const params = reactive({
      search: (route.query.search as string) || '',
      musicTagIds: route.query.tagids || '',
      gift: props.gift,
      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('/music/sheet/my', {
          method: state.platformType === 'TEACHER' ? 'POST' : 'GET',
          prefix:
            state.platformType === 'TEACHER' ? '/api-teacher' : '/api-student',
          params,
          data: state.platformType === 'TEACHER' ? 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
    }

    watch(
      () => props.gift,
      gift => {
        isError.value = false
        rows.value = []
        params.page = 1
        finished.value = false
        params.gift = gift
        FetchList()
      }
    )
    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 ? (
          <div class={styles.personalSong}>
            <Song
              list={rows.value}
              onDetail={(item: any) => {
                router.push({
                  path: '/music-detail',
                  query: {
                    id: item.id
                  }
                })
              }}
            />
          </div>
        ) : (
          !loading.value && (
            <ColResult tips="暂无单曲" classImgSize="SMALL" btnStatus={false} />
          )
        )}
      </List>
    )
  }
})
