<template>
  <header id="header">
    <div class="wrap">
      <div class="left-part">
        <img v-if="user.isQingQue" class="logo" src="http://gm.nkfzs.com/favicon.ico" alt="游戏中心"/>
        <img v-else class="logo" :src="getAssetsFile('default_logo.png')" alt="游戏中心"/>
        {{ user.projectName }}
      </div>
      <div class="menu">
        <el-menu
          :default-active="route.path"
          class="el-menu-wrapper"
          :ellipsis="false"
          router
          mode="horizontal"
        >
          <el-menu-item index="/home">首页</el-menu-item>
          <el-menu-item index="/cate">分类</el-menu-item>
          <el-menu-item index="/my_game">我的游戏</el-menu-item>
        </el-menu>
      </div>
      <div class="search-wrap">
        <el-autocomplete
          v-model="search.params.keywords"
          :fetch-suggestions="searchChange"
          placeholder="请输入游戏名称"
          :prefix-icon="Search"
          clearable
          @select="handleSelect"
          @keyup.enter="handleKeyEnter"
          maxlength="30"
        />
      </div>
      <div class="mob-search" v-if="route.path === '/home' && platform.mobile">
        <van-search shape='round' @click="router.push({ path: '/search' })" />
      </div>
      <div  class="mini-menu" v-if="platform.mobile && route.path !== '/home' ">
        <img v-if="route.path !== '/search'" :src="getAssetsFile('search_circle.png')" alt="" @click="router.push({ path: '/search' })" />
        <i class="verticle" />
        <img :src="getAssetsFile('menu.png')" alt="" @click="show=true"/>
      </div>
      <div class="user">
        <span v-if="!hasToken" class="el-dropdown-link">
          <img :src="getAssetsFile('gamer.png')" @click="router.push('/login')" />
        </span>
        <el-dropdown v-else trigger="click" >
          <span class="el-dropdown-link">
            <img :src="getAssetsFile('gamer.png')" />
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item class="clearfix" @click="toSetting">
                账号设置
              </el-dropdown-item>
              <el-dropdown-item class="clearfix" @click="logOut">
                退出登录
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>
  </header>
  <div class="header-hidden"/>
  <van-popup
    v-model:show="show"
    position="top"
    :style="{ width: '100%', height: 'auto' }"
  >
    <van-cell
      class="menu_title"
      v-for="(item, index) in user.menuPath"
      :key="index"
      :title="item.text"
      @click="toPath(item.url)"/>
    <van-cell title="账号设置" @click="toSetting"/>
    <van-cell v-if="hasToken" title="退出登录" @click="logOut"/>
  </van-popup>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useStore } from '@/store'
import Message from '@/utils/Message'
import local from '@/utils/local'
import { getGameList } from '@/api/index'
import { Search } from '@element-plus/icons-vue'
import { getAssetsFile } from '@/utils/imgResolve'

// const img:any = inject('img')
const router = useRouter()
const route = useRoute()
const { user } = useStore()
const { search } = useStore()
// showSuccessToast('成功文案')
// showFailToast('失败文案')
const show = ref(false)
const game_name = ref(local.get('searchText') || '')
// 绑定el-autocomplete组件
const hasToken = ref(sessionStorage.getItem('token'))

const currentIndex = ref(local.get('headerPath') || '') // 取保存的title
console.log('currentIndex', currentIndex.value)

if (route.query.account) {
  currentIndex.value = '我的'
  console.log('1234567', currentIndex.value)
}

// 顶部导航栏
onMounted(() => {
  const token = sessionStorage.getItem('token')
  if (token) {
    user.getUserProfile()
  }
})

// 退出登录
const logOut = () => {
  // console.log(22);
  sessionStorage.removeItem('token')
  hasToken.value = ''
  router.push({ path: '/login' })
}
const toSetting = () => {
  router.push('/settings')
}
interface LinkItem {
  id: string
  value: string
}
const links: any = ref<LinkItem[]>([])

const searchChange = async(str: string, cb: (arg: any) => void) => {
  currentIndex.value = ''
  local.remove('headerPath')
  if (str && str.length > 0) {
    game_name.value = str
    try {
      var params = reactive({
        type: 0,
        tag_id: 0,
        page: 1,
        pagesize: 10,
        keywords: str
      })
      var { data } = await getGameList(params)
      links.value = data.data.lists
      links.value = links.value.map((item:any, index:any) => {
        return {
          id: `${index}`,
          value: `${item.screen_name}`
        }
      })
      links.value = links.value.filter((item:any) => {
        return item.value.indexOf(str) > -1
      })
      cb(links.value)
    } catch (error: any) {
      // links.value.push({
      //   id: '-1',
      //   value: '暂无匹配数据'
      // })
      // cb(links.value)
      console.log(error)
      Message.error(error.data.msg)
    }
  } else {
    cb([])
  }
}

const handleSelect = (item: LinkItem) => {
  if (item) {
    if (route.path !== 'search') {
      router.push({ path: '/search' })
    }
    search.onSearch()
    local.set('searchText', game_name.value)
  }
}

// 手动回车跳转搜索页
const handleKeyEnter = () => {
  if (route.path !== 'search') {
    router.push({ path: '/search' })
  }
  search.onSearch()
  local.set('searchText', game_name.value)
}

watch(currentIndex, () => { }, { deep: true, immediate: true })
const platform = computed(() => {
  var u = navigator.userAgent
  return {
    mobile: !!u.match(/AppleWebKit.*Mobile.*/), // 是否为移动终端
    ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), // ios终端
    android: u.indexOf('Android') > -1 || u.indexOf('Adr') > -1, // android终端
    iPhone: u.indexOf('iPhone') > -1, // 是否为iPhone或者QQHD浏览器
    iPad: u.indexOf('iPad') > -1, // 是否iPad
    webApp: u.indexOf('Safari') === -1, // 是否web应该程序，没有头部与底部
    weixin: u.indexOf('MicroMessenger') > -1 // 是否微信
  }
})
const toPath = (url: any) => {
  router.push({ path: url })
  show.value = false
}
</script>

<style lang="scss" scoped>
#header{
    width: 100%;
    max-width: 100vw;
    background-color: #fff;
    position: fixed;
    z-index: 1000;
    .wrap{
        margin: 0 auto;
        height: 100%;
        display: flex;
        justify-content: space-between;
        align-items: center;
        box-sizing: border-box;
        .left-part{
            display: flex;
            align-items: center;
            font-family: 'zihunchaoji';
            white-space: nowrap;
        }
        .menu{
            padding: 0 5rem 0 1rem;
            .el-menu--horizontal.el-menu{
                border: 0;
                >.el-menu-item.is-active{
                    border: 0;
                }
            }
            .el-menu-item{
              border: 0;
            }
        }
        .search-wrap{
          width: 8.5rem;
          :deep(.el-input__wrapper){
              border-radius: 1rem;
          }
        }
        .user{
          cursor: pointer;
          .el-dropdown-link{
            overflow: hidden;
            width: 2rem;
            height: 2rem;
            border-radius: 50%;
            >img{
              width: 2rem;
              height: 2rem;
              display: block;
            }
          }

        }
        .mini-menu{
          display: flex;
          align-items: center;
          >img{
            width: 25px;
            height: 25px;
          }
          .verticle{
            width: 1px;
            height: 30px;
            background-color: #ddd;
            margin: 0 10px;
          }
        }
    }
}
.header-hidden{
  height: 3rem;
}
</style>
