import { defineComponent, onMounted, onUnmounted, ref } from 'vue'
import { useLocalStorage } from '@vueuse/core'
import AlbumList from '../album'
import MusicList from '../list'
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'

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 tagids = ref(route.query.tagids || '')
    const subject = ref()
    const tagVisibility = ref(false)
    const words = useLocalStorage<string[]>('music-search', [])
    const activeTab = ref('songe')

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

    const onSearch = val => {
      keyword.value = val
      const indexOf = words.value.indexOf(val)
      if (indexOf > -1) {
        words.value.splice(indexOf, 1)
      }
      if (val) {
        words.value.unshift(val)
        words.value.length = Math.min(words.value.length, 5)
      }
      const activeRef = activeTab.value === 'album' ? albumList : musicList
      ;(activeRef.value as any).onSearch?.(val)
    }

    const onComfirm = tags => {
      const data = Object.values(tags).flat().filter(Boolean).join(',')
      tagids.value = data
      const activeRef = activeTab.value === 'album' ? albumList : musicList
      ;(activeRef.value as any).onComfirm?.(tags)
      tagVisibility.value = false
    }

    const onConfirmSubject = (item: any) => {
      subject.value = item.id
      const activeRef = activeTab.value === 'album' ? albumList : musicList
      ;(activeRef.value as any).onComfirmSubject?.(item)
    }

    const albumList = ref(null)
    const musicList = ref(null)

    const changeTab = (val: any) => {
      activeTab.value = val
    }

    onMounted(() => {
      mitter.on('changeTab', changeTab)
      mitter.on('search', onSearch)
      mitter.on('confirm', onComfirm)
      mitter.on('confirmSubject', onConfirmSubject)
    })

    onUnmounted(() => {
      mitter.off('changeTab', changeTab)
      mitter.off('search', onSearch)
      mitter.off('confirm', onComfirm)
      mitter.off('confirmSubject', onConfirmSubject)
    })

    return () => {
      return (
        <div class={styles.search}>
          {activeTab.value === 'album' ? (
            <AlbumList
              hideSearch
              ref={albumList}
              defauleParams={{
                search: keyword.value,
                tagids: tagids.value,
                albumTagIds: tagids.value,
                subjectIds: subject.value
              }}
            />
          ) : (
            <MusicList
              hideSearch
              ref={musicList}
              onItemClick={(item: any) => {
                router.push({
                  path: '/music-detail',
                  query: {
                    id: item.id,
                    albumId: route.params.id
                  }
                })
              }}
              defauleParams={{
                search: keyword.value,
                tagids: tagids.value,
                musicTagIds: tagids.value,
                subjectIds: subject.value
              }}
            />
          )}
        </div>
      )
    }
  }
})
