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 { openDefaultWebView, state } from '@/state'
import styles from './index.module.less'
import Song from '../component/song'
import { useRouter } from 'vue-router'

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

    expose({
      reload: execute
    })

    return () => {
      const list: any[] = resState.value?.data.rows || []
      if (prevNum.value === 0) {
        prevNum.value = list.length
      }
      return (
        <>
          {prevNum.value > 0 && <Cell title="最近练习" border={false} />}
          <div class={styles.practice}>
            <Song
              list={list}
              onDetail={(item: any) => {
                const url =
                  location.origin +
                  location.pathname +
                  '#/music-detail?id=' +
                  item.id
                openDefaultWebView(url, () => {
                  router.push({
                    path: '/music-detail',
                    query: {
                      id: item.id
                    }
                  })
                })
              }}
            />
          </div>
        </>
      )
    }
  }
})
