import { Sticky, Cell, Tag, Icon, Popup, Tabs, Tab, Dialog } from 'vant'
import {
  RouterView,
  useRouter,
  useRoute,
  onBeforeRouteUpdate,
  onBeforeRouteLeave
} from 'vue-router'
import { defineComponent, onMounted, ref, watch } from 'vue'
import mitt from 'mitt'
import Search from '@/components/col-search'
import { useLocalStorage } from '@vueuse/core'
import styles from './index.module.less'
import classNames from 'classnames'
import SelectTag from './select-tag'
import { getRandomKey, musicBuy } from '../music'

export const mitter = mitt()

const selectTagRef = ref()

export default defineComponent({
  name: 'MusicSearchHeader',
  setup() {
    const searchInputRef = ref()
    localStorage.setItem('behaviorId', getRandomKey())
    const router = useRouter()
    const route = useRoute()
    const loading = ref(false)
    const keyword = ref('')
    const tagids = ref('')
    const albumRows = ref([])
    const sheetRows = ref([])
    const tagVisibility = ref(false)
    const words = useLocalStorage<string[]>('music-search', [])
    const activeTab = ref('songe')

    onBeforeRouteUpdate(() => {
      // console.log('onBeforeRouteUpdate', route.fullPath)
      if (route.path === '/music-songbook/search') {
        keyword.value = ''
        tagids.value = ''
        activeTab.value = 'songe'
        // console.log('onBeforeRouteUpdate')
        try {
          selectTagRef.value?.resetTags?.()
        } catch (error) {
          console.log(error)
        }
      }
      return true
    })

    watch(activeTab, val => {
      mitter.emit('changeTab', val)
    })

    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)
      }
      mitter.emit('search', val)
      // const activeRef = activeTab.value === 'album' ? albumList : musicList
      // ;(activeRef.value as any).onSearch?.(val)
      // FetchList()
    }

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

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

    onMounted(() => {
      // const activeRef = activeTab.value === 'album' ? albumList : musicList
      // ;(activeRef.value as any).onSearch?.('')
      // console.log(searchInputRef.value)
    })
    return () => {
      return (
        <div class={styles.search}>
          <Sticky class={styles.sticky}>
            <Search
              modelValue={keyword.value}
              showAction
              ref={searchInputRef}
              onSearch={onSearch}
              onFilter={() => (tagVisibility.value = true)}
              filterDot={!!tagids.value}
              onClick={() => {
                if (route.path === '/music-songbook') {
                  router.push({
                    path: '/music-songbook/search'
                  })
                }
              }}
            />
            {route.path === '/music-songbook/search' && (
              <Tabs
                color="var(--van-primary)"
                background="transparent"
                lineWidth={20}
                shrink
                v-model:active={activeTab.value}
                onChange={val => (activeTab.value = val)}
              >
                <Tab title="单曲" name="songe"></Tab>
                <Tab title="专辑" name="album"></Tab>
              </Tabs>
            )}
          </Sticky>
          {words.value.length > 0 && route.path === '/music-songbook/search' && (
            <div class={classNames(styles.keywords, 'van-hairline--bottom')}>
              <div class={styles.content}>
                {words.value.map(item => (
                  <Tag
                    round
                    class={styles.searchKeyword}
                    key={item}
                    onClick={() => onSearch(item)}
                  >
                    {item}
                  </Tag>
                ))}
              </div>
              <Icon
                class={styles.remove}
                name="delete-o"
                onClick={() => (words.value = [])}
              />
            </div>
          )}
          <RouterView />
          <Popup
            show={tagVisibility.value}
            round
            closeable
            position="bottom"
            style={{ height: '60%' }}
            teleport="body"
            onUpdate:show={val => (tagVisibility.value = val)}
          >
            <SelectTag
              ref={selectTagRef}
              onConfirm={onComfirm}
              onCancel={() => {}}
            />
          </Popup>
        </div>
      )
    }
  }
})
