import { defineComponent, onMounted, onUnmounted, reactive, ref } from 'vue'
import { useLocalStorage } from '@vueuse/core'
import styles from './index.module.less'
import { useRoute, useRouter } from 'vue-router'
import { getRandomKey } from '../music'
import { mitter } from './header'
import { SubjectEnum, useSubjectId } from '@/helpers/hooks'
import { List } from 'vant'
import Song from '../component/song'
import ColResult from '@/components/col-result'
import { openDefaultWebView, state } from '@/state'
import request from '@/helpers/request'

export default defineComponent({
  name: 'MusicSearch',
  emits: ['confirm'],
  setup() {
    localStorage.setItem('behaviorId', getRandomKey())
    const route = useRoute()
    const router = useRouter()
    const keyword = ref(route.query.keyword || '')
    const subject = ref()

    const getSubject: any = useSubjectId(SubjectEnum.SEARCH)
    subject.value = getSubject.id

    const onSearch = val => {
      keyword.value = val

      if (data.value) {
        data.value.rows = []
      }
      params.name = val
      params.page = 1
      FetchList()
    }

    const params = reactive({
      name: (route.query.search as string) || '',
      rows: 20,
      page: 1
    })
    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.post(
          `/api-student/music/sheet/searchTenant`,
          {
            data: params
          }
        )
        if (data.value) {
          const result = (data.value?.rows || []).concat(
            res.data.music.rows || []
          )
          data.value.rows = result
        }
        data.value = data.value || res.data.music

        const temp = data.value.rows || []
        temp.forEach((item: any) => {
          if (keyword.value) {
            item.musicSheetName = item.musicSheetName.replace(
              keyword.value,
              `<span style="color: #FE2451">${keyword.value}</span>`
            )
          }
        })
        data.value.rows = temp

        params.page = res.data.music.pageNo + 1
        finished.value = res.data.music.pageNo >= res.data.music.totalPage
      } catch (error) {
        isError.value = true
      }
      loading.value = false
    }

    onMounted(() => {
      mitter.on('search', onSearch)
      FetchList()
    })

    onUnmounted(() => {
      mitter.off('search', onSearch)
    })

    return () => {
      return (
        <div class={[styles.search, styles.searchAlbum]}>
          {data.value && data.value.rows.length ? (
            <List
              // loading={loading.value}
              finished={finished.value}
              finished-text={data.value && data.value.rows.length ? '' : ''}
              onLoad={FetchList}
              error={isError.value}
              immediateCheck={false}
            >
              <Song
                showTitleImg
                list={data.value.rows}
                onDetail={(item: any) => {
                  const url =
                    location.origin +
                    location.pathname +
                    '#/music-detail?id=' +
                    item.id +
                    '&tenantAlbumId=' +
                    item.tenantAlbumId +
                    '&type=search'
                  openDefaultWebView(url, () => {
                    router.push({
                      path: '/music-detail',
                      query: {
                        id: item.id,
                        tenantAlbumId: item.tenantAlbumId,
                        type: 'search'
                      }
                    })
                  })
                }}
              />
            </List>
          ) : (
            !loading.value && <ColResult tips="暂无曲目" btnStatus={false} />
          )}
        </div>
      )
    }
  }
})
