import request from '@/helpers/request'
import { useAsyncState } from '@vueuse/core'
import { defineComponent, ref } from 'vue'
import { Cell, Skeleton } from 'vant'
import Item from '../list/item'
import { musicBuy } from '../music'

export default defineComponent({
  name: 'Practice',
  emits: ['favorite'],
  setup(props, { expose, emit }) {
    /** 这里条数不会变动，设置固定高度避免抖动 */
    const prevNum = ref(0)
    const { isLoading, state, execute } = useAsyncState(
      (args): Promise<any> =>
        request.get('/api-student/music/sheet/practice', {
          params: {
            rows: args?.rows || 3
          }
        }),
      null
    )

    expose({
      reload: execute
    })

    return () => {
      const list: any[] = state.value?.data.rows || []
      if (prevNum.value === 0) {
        prevNum.value = list.length
      }
      return (
        <>
          {prevNum.value > 0 && <Cell title="最近练习" />}
          {Array.from(Array(prevNum.value)).map((_, index) => {
            const item = list[index]
            console.log(list, item)
            if (!item) {
              return <Skeleton row={5} />
            }
            return (
              <Item
                key={item.id}
                data={item}
                onClick={() => musicBuy(item)}
                onFavorite={() => {
                  emit('favorite')
                }}
              />
            )
          })}
        </>
      )
    }
  }
})
