import {
  Sticky,
  Cell,
  Tag,
  Icon,
  Popup,
  Tabs,
  Tab,
  Dialog,
  Button,
  DropdownMenu,
  DropdownItem
} from 'vant'
import {
  RouterView,
  useRouter,
  useRoute,
  onBeforeRouteUpdate
} from 'vue-router'
import { defineComponent, nextTick, onMounted, reactive, ref, watch } from 'vue'
import mitt from 'eventemitter3'
import Search from '@/components/col-search'
import { useLocalStorage, useThrottleFn } from '@vueuse/core'
import styles from './index.module.less'
import classNames from 'classnames'
import { getRandomKey } from '../music'
import SelectSubject from './select-subject'
import { SubjectEnum, useSubjectId } from '@/helpers/hooks'
import { state } from '@/state'
import TheSticky from '@/components/the-sticky'
import bgImg from '../../images/bg-image-search.png'
import iconSearch from './icon-search.png'
import iconDelete from './icon-delete.png'
import request from '@/helpers/request'
import { browser } from '@/helpers/utils'
import ColHeader from '@/components/col-header'
import ColResult from '@/components/col-result'
import { postMessage } from '@/helpers/native-message'

export const mitter = new mitt()

const selectTagRef = ref()

export const openWebViewOrWeb = (url: string, callback: any) => {
  if (browser().isApp) {
    postMessage({
      api: 'openWebView',
      content: {
        url: url, //`${location.origin}/tenant/#/music-album-detail/${item.id}`,
        orientation: 1,
        isHideTitle: false
      }
    })
  } else {
    // router.push({
    //   path: '/music-album-detail/' + item.id
    // })
    callback && callback()
  }
}

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'
        )
      }
    }

    localStorage.setItem('behaviorId', getRandomKey())
    const router = useRouter()
    const route = useRoute()
    const searchResultStatus = ref(false)
    const keyword = ref('')
    const tagids = ref('')
    const words = useLocalStorage<string[]>(
      route.path === '/music-songbook/search'
        ? 'music-search'
        : 'music-search-ablum',
      []
    )
    const activeTab = ref('all')

    if (route.path === '/music-songbook/result') {
      keyword.value = route.query.search as string
      tagids.value = ''
      activeTab.value = 'all'
    }

    onBeforeRouteUpdate((to, form) => {
      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 = 'all'
        try {
          selectTagRef.value?.resetTags?.()
        } catch (error) {
          console.log(error)
        }
      }
      if (to.path === '/music-songbook/result') {
        keyword.value = to.query.search as string
        console.log(keyword.value, 'value', route.query)
        tagids.value = ''
        activeTab.value = 'all'
      }
      return true
    })

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

    // 输入时搜索
    const searchList = ref<any>([])
    const onInputSearch = useThrottleFn(async (val: any) => {
      try {
        let tData: any = {}
        if (route.path === '/music-songbook/searchAlbum') {
          const { data } = await request.post(
            '/api-student/music/sheet/searchTenant',
            {
              hideLoading: true,
              data: {
                // subjectId: subjects.id,
                name: val,
                rows: 10
              }
            }
          )
          tData = data
        } else {
          const { data } = await request.post(
            '/api-student/music/sheet/search',
            {
              hideLoading: true,
              data: {
                subjectId: subjects.id,
                name: val,
                rows: 10
              }
            }
          )
          tData = data
        }

        const tempMusics = tData.musicNames || []
        tempMusics.forEach((item: any, index: number) => {
          if (index < 10) {
            item.name = item.name.replace(val, `<span>${val}</span>`)
          }
        })
        searchList.value = tempMusics
        searchResultStatus.value = keyword.value ? true : false
      } catch {
        //
      }
    }, 300)

    const onSearch = val => {
      console.log('object :>> ', val)
      keyword.value = val
      const indexOf = words.value.indexOf(val)
      if (indexOf > -1) {
        words.value.splice(indexOf, 1)
      }
      if (val) {
        words.value.unshift(val)
        // console.log(words.value.length, 'words.value.length')
        words.value.length = Math.min(words.value.length, 10)
        // 结合搜索
        if (route.path === '/music-songbook/search') defaultClose()
        // 机构专辑搜索
        if (route.path === '/music-songbook/searchAlbum') defaultClose()
      }
      // 机构专辑详情
      if (route.path !== '/music-songbook/searchAlbum') {
        // 综合搜索
        if (route.path !== '/music-songbook/result') {
          router.replace({
            path: '/music-songbook/result',
            query: {
              search: val
            }
          })
          searchResultStatus.value = false
          searchList.value = []
        } else {
          searchResultStatus.value = false
          mitter.emit('search', val)
        }
      } else {
        searchResultStatus.value = false
        mitter.emit('search', val)
      }
    }
    const searchRef = ref()
    const onComfirmSubject = (item: any) => {
      // console.log('onSort', item)
      subject.name = item.name
      subject.id = item.id
      searchRef.value.toggle()
      useSubjectId(
        SubjectEnum.SEARCH,
        JSON.stringify({
          id: item.id,
          name: item.name
        }),
        'set'
      )
      subject.show = false
      mitter.emit('confirmSubject', subject)
    }

    const getSubject: any = useSubjectId(SubjectEnum.SEARCH)
    const subject = reactive({
      show: false,
      name: getSubject.name || '全部声部',
      id: getSubject.id || ''
    })

    const tagRef = ref<any>([])
    const collapse = reactive({
      line: 0,
      arrowStatus: false
    })

    // 历史搜索默认收起
    const defaultClose = () => {
      nextTick(() => {
        if (!words.value || !words.value.length) {
          return
        }
        let offsetLeft = -1
        collapse.line = 0
        const tags = tagRef.value
        tags.forEach((item: any, index: number) => {
          try {
            item.$el.style.display = 'block'
            if (index === 0) {
              collapse.line = 1
              offsetLeft = item.$el.offsetLeft
            } else if (item.$el.offsetLeft === offsetLeft && index != 0) {
              // 如果某个标签的offsetLeft和第一个标签的offsetLeft相等  说明增加了一行
              collapse.line += 1
            }

            if (!collapse.arrowStatus) {
              if (collapse.line > 1) {
                //从第3行开始 隐藏标签
                item.$el.style.display = 'none'
              } else {
                item.$el.style.display = 'block'
              }
            } else {
              item.$el.style.display = 'block'
            }
          } catch (e: any) {
            console.log(e, 'Error')
          }
        })
      })
    }
    // 首先调用默认收起的方法
    if (route.path === '/music-songbook/search') defaultClose()
    if (route.path === '/music-songbook/searchAlbum') defaultClose()

    onMounted(() => {
      postMessage({
        api: 'backIconChange',
        content: { backIconHide: true }
      })
    })
    return () => {
      return (
        <div class={styles.search}>
          <div class={styles.sticky}>
            <TheSticky position="top">
              <ColHeader
                isFixed={false}
                background="transparent"
                isBack={false}
                title=" "
              />
              <Search
                modelValue={keyword.value}
                background="transparent"
                showAction
                onInput={(val: any) => {
                  keyword.value = val
                  if (val) {
                    onInputSearch(val)
                  } else {
                    searchList.value = []
                    searchResultStatus.value = false
                    if (route.path === '/music-songbook/result') {
                      router.replace('/music-songbook/search')
                    }

                    if (route.path === '/music-songbook/searchAlbum') {
                      mitter.emit('search', '')
                    }
                  }
                }}
                onSearch={(val: any) => {
                  if (!val) {
                    if (route.path === '/music-songbook/searchAlbum') {
                      mitter.emit('search', '')
                    }
                    return
                  }
                  keyword.value = val
                  onSearch(val)
                  // searchResultStatus.value = true
                }}
                type="tenant"
                v-slots={{
                  left: () =>
                    route.path !== '/music-songbook/searchAlbum' && (
                      <DropdownMenu>
                        <DropdownItem
                          // titleClass={styles.titleActive}
                          title={subject.name}
                          ref={searchRef}
                        >
                          <SelectSubject
                            isReset
                            searchParams={subject}
                            onComfirm={onComfirmSubject}
                          />
                        </DropdownItem>
                      </DropdownMenu>
                    ),
                  action: () => (
                    <span
                      class={styles.searchCancel}
                      onClick={() => {
                        if (browser().isApp) {
                          postMessage({ api: 'back' })
                        } else {
                          router.back()
                        }
                      }}
                    >
                      取消
                    </span>
                  )
                }}
              />
              {route.path === '/music-songbook/result' &&
                !searchResultStatus.value && (
                  <Tabs
                    color="var(--van-primary)"
                    background="transparent"
                    lineWidth={20}
                    shrink
                    class={styles.tagTabs}
                    v-model:active={activeTab.value}
                    onChange={val => (activeTab.value = val)}
                  >
                    <Tab title="综合" name="all"></Tab>
                    <Tab title="单曲" name="songe"></Tab>
                    <Tab title="专辑" name="album"></Tab>
                  </Tabs>
                )}
            </TheSticky>
            <img class={styles.bgImg} src={bgImg} />
          </div>
          {words.value.length > 0 &&
            (route.path === '/music-songbook/search' ||
              route.path === '/music-songbook/searchAlbum') && (
              <div class={styles.keywordSection}>
                <div class={styles.keywordTitle}>
                  <span class={styles.t}>搜索历史</span>
                  <Icon
                    class={styles.remove}
                    name={iconDelete}
                    onClick={() => (words.value = [])}
                  />
                </div>
                <div class={classNames(styles.keywords)}>
                  <div class={styles.content}>
                    {words.value.map((item: any, index: number) => (
                      <Tag
                        ref={(el: any) => (tagRef.value[index] = el)}
                        round
                        class={[styles.searchKeyword, 'van-ellipsis']}
                        key={item}
                        onClick={() => {
                          keyword.value = item
                          onSearch(item)
                        }}
                      >
                        {item}
                      </Tag>
                    ))}
                    {collapse.line > 1 && (
                      <span
                        class={[styles.arrowMore]}
                        onClick={() => {
                          collapse.arrowStatus = !collapse.arrowStatus
                          defaultClose()
                        }}
                      >
                        <Icon
                          name={
                            collapse.arrowStatus ? 'arrow-up' : 'arrow-down'
                          }
                        />
                      </span>
                    )}
                  </div>
                </div>
              </div>
            )}
          {route.path === '/music-songbook/search' && (
            <Tabs
              color="var(--van-primary)"
              background="transparent"
              lineWidth={20}
              shrink
              class={styles.tagTabs}
              v-model:active={activeTab.value}
              onChange={val => (activeTab.value = val)}
            >
              <Tab title="综合" name="all"></Tab>
              <Tab title="单曲" name="songe"></Tab>
              <Tab title="专辑" name="album"></Tab>
            </Tabs>
          )}
          <RouterView />

          <div
            class={[styles.searchResult]}
            style={{ display: searchResultStatus.value ? 'block' : 'none' }}
          >
            <div class={styles.searchGroups}>
              {searchList.value.map((item: any) => (
                <div
                  class={styles.searchItem}
                  onClick={() => {
                    if (item.type === 'ALBUM') {
                      openWebViewOrWeb(
                        `${location.origin}/tenant/#/music-album-detail/${item.id}`,
                        () => {
                          router.push({
                            path: '/music-album-detail/' + item.id
                          })
                        }
                      )
                    } else {
                      openWebViewOrWeb(
                        `${location.origin}/tenant/#/music-detail?id=${
                          item.id
                        }&tenantAlbumId=${
                          route.path === '/music-songbook/searchAlbum'
                            ? item.tenantAlbumId
                            : ''
                        }&type=search`,
                        () => {
                          router.push({
                            path: '/music-detail',
                            query: {
                              id: item.id,
                              tenantAlbumId:
                                route.path === '/music-songbook/searchAlbum'
                                  ? item.tenantAlbumId
                                  : '',
                              type: 'search'
                            }
                          })
                        }
                      )
                    }
                  }}
                >
                  <img src={iconSearch} class={styles.iconSearch} />
                  <span class={styles.rName} v-html={item.name}></span>
                </div>
              ))}

              {searchList.value.length <= 0 && (
                <ColResult tips="暂无搜索结果" btnStatus={false} />
              )}
            </div>
          </div>
        </div>
      )
    }
  }
})
