<template>
  <div :class="{ show: showSearch }" class="header-search">
    <svg-icon class-name="search-icon" icon-class="search" @click.stop="click" />
    <el-select
      ref="headerSearchSelectRef"
      v-model="search"
      :remote-method="querySearch"
      filterable
      default-first-option
      remote
      placeholder="Search"
      class="header-search-select"
      @change="change"
    >
      <el-option
        v-for="option in options"
        :key="option.item.path"
        :value="option.item"
        :label="option.item.title.join(' > ')"
      />
    </el-select>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import path from 'path-browserify'
import Fuse from 'fuse.js'
import type { ElSelect } from 'element-plus'
import { usePermissionStore } from '@/stores/modules/permission'
import type { SearchOption } from '@/types'

interface FuseResultItem {
  path: string
  title: string[]
}

const route = useRoute()
const router = useRouter()
const permissionStore = usePermissionStore()

const headerSearchSelectRef = ref<InstanceType<typeof ElSelect> | null>(null)

const search = ref('')
const options = ref<Fuse.FuseResult<FuseResultItem>[]>([])
const searchPool = ref<FuseResultItem[]>([])
const showSearch = ref(false)

let fuse: Fuse<FuseResultItem> | undefined

const routes = computed(() => permissionStore.routes)

function click() {
  showSearch.value = !showSearch.value
  if (showSearch.value) {
    nextTick(() => {
      headerSearchSelectRef.value?.focus()
    })
  }
}

function close() {
  headerSearchSelectRef.value?.blur()
  options.value = []
  showSearch.value = false
}

function change(val: FuseResultItem) {
  if (isHttp(val.path)) {
    const pindex = val.path.indexOf('http')
    window.open(val.path.substring(pindex), '_blank')
  } else {
    router.push(val.path)
  }
  search.value = ''
  options.value = []
  nextTick(() => {
    showSearch.value = false
  })
}

function initFuse(list: FuseResultItem[]) {
  fuse = new Fuse(list, {
    shouldSort: true,
    threshold: 0.4,
    location: 0,
    distance: 100,
    maxPatternLength: 32,
    minMatchCharLength: 1,
    keys: [
      { name: 'title', weight: 0.7 },
      { name: 'path', weight: 0.3 }
    ]
  })
}

function generateRoutes(
  routes: any[],
  basePath = '/',
  prefixTitle: string[] = []
): FuseResultItem[] {
  const res: FuseResultItem[] = []

  for (const routerItem of routes) {
    // Skip hidden routes
    if (routerItem.hidden) continue

    const data: FuseResultItem = {
      path: !isHttp(routerItem.path) ? path.resolve(basePath, routerItem.path) : routerItem.path,
      title: [...prefixTitle]
    }

    if (routerItem.meta?.title) {
      data.title = [...data.title, routerItem.meta.title]

      if (routerItem.redirect !== 'noRedirect') {
        res.push(data)
      }
    }

    // Recursive child routes
    if (routerItem.children) {
      const tempRoutes = generateRoutes(routerItem.children, data.path, data.title)
      if (tempRoutes.length >= 1) {
        res.push(...tempRoutes)
      }
    }
  }

  return res
}

function querySearch(query: string) {
  if (query !== '' && fuse) {
    options.value = fuse.search(query)
  } else {
    options.value = []
  }
}

function isHttp(url: string): boolean {
  return url.indexOf('http://') !== -1 || url.indexOf('https://') !== -1
}

watch(
  routes,
  () => {
    searchPool.value = generateRoutes(routes.value)
  },
  { immediate: true }
)

watch(searchPool, (list) => {
  initFuse(list)
})

watch(showSearch, (value) => {
  if (value) {
    document.body.addEventListener('click', close)
  } else {
    document.body.removeEventListener('click', close)
  }
})
</script>

<style lang="scss" scoped>
.header-search {
  font-size: 0 !important;

  .search-icon {
    cursor: pointer;
    font-size: 18px;
    vertical-align: middle;
  }

  .header-search-select {
    font-size: 18px;
    transition: width 0.2s;
    width: 0;
    overflow: hidden;
    background: transparent;
    border-radius: 0;
    display: inline-block;
    vertical-align: middle;

    :deep(.el-input__inner) {
      border-radius: 0;
      border: 0;
      padding-left: 0;
      padding-right: 0;
      box-shadow: none !important;
      border-bottom: 1px solid #d9d9d9;
      vertical-align: middle;
    }
  }

  &.show {
    .header-search-select {
      width: 210px;
      margin-left: 10px;
    }
  }
}
</style>
