import { Sticky, Cell, Tag, Icon, Popup, Tabs, Tab, Dialog } from 'vant'
import {
  RouterView,
  useRouter,
  useRoute,
  onBeforeRouteUpdate
} from 'vue-router'
import { defineComponent, onMounted, reactive, 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 } from '../music'
import SelectSubject from './select-subject'
import { SubjectEnum, useSubjectId } from '@/helpers/hooks'
import { state } from '@/state'
import ColHeader from '@/components/col-header'
import TheSticky from '@/components/the-sticky'

export const mitter = mitt()

const selectTagRef = ref()

export default defineComponent({
  name: 'MusicSearchHeader',
  setup() {
    const subjects: any = useSubjectId(SubjectEnum.SEARCH)
    // 判断是否已有数据
    if (!subjects.id) {
      const users = state.user.data
      const subjectId = users.subjectId
        ? Number(users.subjectId.split(',')[0])
        : ''
      const subjectName = users.subjectName
        ? users.subjectName.split(',')[0]
        : ''
      if (subjectId) {
        useSubjectId(
          SubjectEnum.SEARCH,
          JSON.stringify({
            id: subjectId,
            name: subjectName
          }),
          'set'
        )
      }
    }

    const searchInputRef = ref()
    localStorage.setItem('behaviorId', getRandomKey())
    const router = useRouter()
    const route = useRoute()
    const keyword = ref('')
    const tagids = ref('')
    const tagVisibility = ref(false)
    const words = useLocalStorage<string[]>('music-search', [])
    const activeTab = ref('songe')

    onBeforeRouteUpdate(() => {
      const getSubject: any = useSubjectId(SubjectEnum.SEARCH)
      subject.name = getSubject.name || '全部声部'
      subject.id = getSubject.id
      if (route.path === '/music-songbook/search') {
        keyword.value = ''
        tagids.value = ''
        activeTab.value = 'songe'
        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 onComfirm = (tags, name = '') => {
      const data = Object.values(tags).flat().filter(Boolean).join(',')
      tagids.value = data
      mitter.emit('confirm', tags)
      tagVisibility.value = false
    }

    const onComfirmSubject = (item: any) => {
      // console.log('onSort', item)
      subject.name = item.name
      subject.id = item.id
      useSubjectId(
        SubjectEnum.SEARCH,
        JSON.stringify({
          id: item.id,
          name: item.name
        }),
        'set'
      )
      mitter.emit('confirmSubject', subject)
      subject.show = false
    }

    onMounted(() => {})

    const getSubject: any = useSubjectId(SubjectEnum.SEARCH)
    const subject = reactive({
      show: false,
      name: getSubject.name || '全部声部',
      id: getSubject.id || ''
    })
    return () => {
      return (
        <div class={styles.search}>
          <TheSticky class={styles.sticky}>
            <ColHeader border={false} />
            <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'
                  })
                }
              }}
              v-slots={{
                left: () => (
                  <div
                    class={styles.label}
                    onClick={() => (subject.show = true)}
                  >
                    {subject.name}
                    <Icon
                      classPrefix="iconfont"
                      name="down"
                      size={12}
                      color="#333"
                    />
                  </div>
                )
              }}
            />
            {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>
            )}
          </TheSticky>
          {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>

          {/* 声部弹框 */}
          <Popup
            show={subject.show}
            position="bottom"
            round
            closeable
            safe-area-inset-bottom
            onClose={() => (subject.show = false)}
            onClosed={() => (subject.show = false)}
          >
            <SelectSubject
              searchParams={subject}
              onComfirm={onComfirmSubject}
            />
          </Popup>
        </div>
      )
    }
  }
})
