<template>
    <div :class="{ show: show }" class="menu_search">
        <el-icon class="tjm_tools_icon" size="24" :color="layoutStyle=='vertical'?'':'#fff'">
            <tjm-icon-ep-Search @click.stop="click" />
        </el-icon>
        <el-select
            v-model="search"
            :remote-method="querySearch"
            filterable
            default-first-option
            remote
            placeholder="Select"
            ref="menuSearchSelectRef"
            class="menu_search_select"
            auto-complete="off"
            @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>
import Fuse from 'fuse.js' //轻量级模糊查询
import { usePermissionStore } from '@/store/permission'
const search = ref('')
const options = ref([])
const show = ref(false)
const menuSearchSelectRef = ref(null)
const fuse = ref(undefined)
const router = useRouter()
const sidebarRouters = computed(() => usePermissionStore().sidebarRouters)
const searchPool = ref([])
import { useSettingStore } from '@/store/settings.js'
const settingStore = useSettingStore()
const { layoutStyle } = storeToRefs(settingStore)
function change(val) {
    const path = val.path
    const query = val.query
    if (isHttp(path)) {
        // http(s):// 路径新窗口打开
        const pindex = path.indexOf('http')
        window.open(path.substr(pindex, path.length), '_blank')
    }
    if (path.startsWith('/tjmchild')) {
        const parts = path.split('/')
        router.push({
            name: parts[2],
            params: { page: parts.slice(3).join('/') }
        })
    } else {
        if (query) {
            router.push({ path: path, query: JSON.parse(query) })
        } else {
            router.push(path)
        }
    }

    search.value = ''
    options.value = []
    nextTick(() => {
        show.value = false
    })
}
function isHttp(url) {
    return url.indexOf('http://') !== -1 || url.indexOf('https://') !== -1
}

function initFuse(list) {
    fuse.value = new Fuse(list, {
        shouldSort: true, // 是否对结果进行排序
        threshold: 0.4, // 阈值控制匹配的敏感度
        location: 0, // 匹配的位置，0 表示开头匹配
        distance: 100, // 搜索的最大距离
        minMatchCharLength: 1, // 最小匹配字符长度
        keys: [
            {
                name: 'title',
                weight: 0.7
            },
            {
                name: 'path',
                weight: 0.3
            }
        ]
    })
}
watch(searchPool, list => {
    initFuse(list)
})
onMounted(() => {
    searchPool.value = generateRoutes(sidebarRouters.value)
})

watchEffect(() => {
    searchPool.value = generateRoutes(sidebarRouters.value)
})

function getNormalPath(p) {
    if (p.length === 0 || !p || p == 'undefined') {
        return p
    }
    let res = p.replace('//', '/')
    if (res[res.length - 1] === '/') {
        return res.slice(0, res.length - 1)
    }
    return res
}

function generateRoutes(routes, basePath = '', prefixTitle = []) {
    let res = []
    for (const r of routes) {
        if (r.hidden) {
            continue
        }
        const p = r.path.length > 0 && r.path[0] === '/' ? r.path : '/' + r.path
        const data = {
            path: !isHttp(r.path) ? getNormalPath(basePath + p) : r.path,
            title: [...prefixTitle]
        }
        if (r.meta && r.meta.title) {
            data.title = [...data.title, r.meta.title]
            if (r.redirect !== 'noRedirect') {
                res.push(data)
            }
        }
        if (r.query) {
            data.query = r.query
        }
        if (r.children) {
            const tempRoutes = generateRoutes(r.children, '', data.title)
            if (tempRoutes.length >= 1) {
                res = [...res, ...tempRoutes]
            }
        }
    }
    return res
}

function click() {
    show.value = !show.value
    if (show.value) {
        menuSearchSelectRef.value && menuSearchSelectRef.value.focus()
    }
}
function close() {
    menuSearchSelectRef.value && menuSearchSelectRef.value.blur()
    options.value = []
    show.value = false
}

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

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

<style lang='scss' scoped>
.menu_search {
  font-size: 0 !important;
  display: flex;
  align-items: center;
  justify-content: space-around;
  margin-left: 5px;
  .tjm_tools_icon {
    cursor: pointer;
  }
  .menu_search_select {
    font-size: 18px;
    transition: width 0.2s;
    width: 0;
    overflow: hidden;
    background: transparent;
    border-radius: 0;
    display: inline-block;
    vertical-align: middle;
    --el-select-input-focus-border-color: none !important;
    :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 {
    .menu_search_select {
      width: 210px;
      margin-left: 10px;
    }
  }
}
</style>