<template>
  <!-- header -->
  <div class="nav">
    <!-- nav -->
    <header id="header">
      <div class="logo-text">
        <img src="/images/ForesightLogo.png" alt="The image cannot be displayed properly" @click="refresh" />
      </div>
      <ul class="nav-list">
        <li class="nav-item" :class="{'active-link': item.link === currentLink}" v-for="item in routerList" :key="item.id" @mouseenter="onNavEnter($event, item)" @mouseleave="onNavLeave($event)">
          <span @click="onNavSkip(item)">{{ item.title }}</span>
          <img v-if="item.children && item.children.length > 0" class="icon-down" src="@/assets/icon/down.svg" alt="">
        </li>
      </ul>
      <ul class="nav-children-list" ref="navChildren" @mouseenter="onNavChildrenEnter()" @mouseleave="onNavChildrenLeave">
        <li class="nav-item" :class="{'active-link': item.link === currentLink}" v-for="item in navChildrenContent" :key="item.id">
          <span @click="onNavSkip(item)">{{ item.title }}</span>
        </li>
      </ul>
      <div class="search max-show">
        <img src="/images/search.svg" alt="The image cannot be displayed properly" @click="isSearch = true" />
        <div class="search-com" v-if="isSearch">
          <search-com show-type="min" @close="isSearch = false"></search-com>
        </div>
      </div>
      <div class="search min-show">
        <img src="/images/search.svg" alt="The image cannot be displayed properly" @click="showSearch = true" />
      </div>
      <div class="menu" @click="showPopup">
        <img src="/images/menu.svg" alt="The image cannot be displayed properly" />
      </div>
    </header>
    <!-- popup menu -->
    <van-popup
      class="popup"
      v-model:show="show"
      position="right"
      overlay-class="header-overlay"
      @closed="hidePopup"
      safe-area-inset-top
      :style="{ width: '50%', height: '100%' }"
    >
      <div class="nav-close"  @click="isInput = false">
        <div class="popup-logo" @click="refresh"></div>
        <span class="close" @click="hidePopup">
          <img src="/images/nav/close.svg" alt="The image cannot be displayed properly">
        </span>
      </div>
      <!-- tipMsg -->
      <div class="popup-nav">
        <ul class="popup-nav-list">
          <li v-for="item in routerList" class="popup-nav-item" :key="item.id">
            <div class="popup-nav-item-title" :class="{'active-link': item.link === currentLink}" @click="onPopupNavItem(item)">
              <span>{{ item.title }}</span>
              <img
                v-if="item.children && item.children.length > 0"
                class="icon-down"
                :class="{'icon-up': havChildId === item.id}"
                src="@/assets/icon/down.svg"
                alt=""
              >
            </div>
            <div class="popup-nav-children-list" v-if="havChildId === item.id">
              <div v-for="cItem in item.children" :key="cItem.id" class="popup-nav-children-item-title" @click="onPopupNavItem(cItem)">{{ cItem.title }}</div>
            </div>
          </li>
        </ul>
      </div>
      <!-- <menu-comp v-show="!isInput" /> -->
      <div class="popup-footer enter-email">
        <div class="subscribe">
          Subscribe
        </div>
        <div class="email">
          <input class="email-input" placeholder="Enter email" type="email" name="email" ref="emailInput" v-model="emailVal">
          <div class="email-submit" @click="onEnter">
            <img src="@/assets/icon/enter.svg" alt="The image cannot be displayed properly">
          </div>
        </div>
        <div class="share-list">
          <img style="cursor:pointer;" :src="item.image" v-for="(item, index) in shareList" @click="handleShare(item)" alt="The image cannot be displayed properly">
        </div>
        <div class="footer-menus">
          <div class="small-font skip-a">
            <span @click="onSkip('http://jobs.foresightventures.com/')">Jobs</span>
          </div>
          <!-- <div class="small-font skip-a">
            <span @click="onSkip('/about')">Team</span>
          </div> -->
          <div class="small-font skip-a">
            <span @click="onSkip('/terms')">Terms of Use</span>
          </div>
          <div class="small-font skip-a">
            <span @click="onSkip('/privacy')">Privacy Policy</span>
          </div>
        </div>
        <!-- 备案号 Internet Content Provider -->
        <div class="footer-provider">
          © 2000-{{ new Date().getFullYear() }}, Foresight Ventures Investments
        </div>
      </div>
    </van-popup>
    <van-popup
      class="search-popup"
      v-model:show="showSearch"
      position="right"
      overlay-class="header-overlay"
      @closed="hideSearchPopup"
      safe-area-inset-top
      :style="{ width: '100%', height: '100%' }"
    >
    <search-com show-type="max" @close="showSearch = false"></search-com>
  </van-popup>
  </div>
</template>
<script setup>
import {onMounted, ref, watch, watchEffect} from 'vue';
import { useRoute, useRouter } from "vue-router";
// import { searchResult } from '../assets/datas/searchResultData'
import { useStore } from 'vuex';
import {getAction, subscribedApi, getNavData} from "../api/manage.js";
import {searchTitleApi} from "../api/research.js";
import MenuComp from "./MenuComp.vue";

const store = useStore();

const route = useRoute();
const router = useRouter();
const routerList = ref([])
const search = ref('');
const searchResult = ref([])
// popup is show
const show = ref(false);
const showSearch = ref(false);
// is oninput
const isInput = ref(false);
// 提示信息列表
// Prompt Information List
const tipList = ref([]);
// 无搜索结果的信息提示
// No information about the search result is displayed
const noResult = ref('');

const navChildren = ref(null)
const navChildrenContent = ref([])

const timer = ref(null)
const havChildId = ref('')
const shareList = ref([])
const emailVal = ref('')
const emailReg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
const isSearch = ref(false)
const currentLink = ref('')

// 判断路由是否发生改变
// Check whether the route is changed
watch(
  () => route,
  (val) => {
    currentLink.value = val.path
    show.value = false
  },
  { deep: true, immediate: true }
)

const onSkip = (url) => {
  const reg = /^(http|https)/
  if (reg.test(url)) {
    window.open(url)
    return
  }
  router.push(url)
}

const onNavSkip = (item) => {
  const reg = /^(http|https)/
  if (reg.test(item.link)) {
    window.open(item.link)
    return
  }
  router.push(item.link)
}

const handleShare = (item)=> {
  window.open(item.link)
}

const onNavEnter = (event, item) => {
  clearInterval(timer.value)
  if (item && item.children.length > 0) {
    const header = document.getElementById('header')
    const left = header.getBoundingClientRect().left
    const nav = event.toElement
    const navLeft = nav.getBoundingClientRect().left
    navChildren.value.style.display = 'flex'
    navChildren.value.style.left = `${navLeft - left - 40}px`
    navChildrenContent.value = item.children
  } else {
    navChildren.value.style.display = 'none'
  }
}

const onNavLeave = (event) => {
  timer.value = setTimeout(() => {
    navChildren.value.style.display = 'none'
  }, 750) 
}

const onNavChildrenEnter = () => {
  clearInterval(timer.value)
}

const onNavChildrenLeave = () => {
  timer.value = setTimeout(() => {
    navChildren.value.style.display = 'none'
  }, 250)
}

const onPopupNavItem = (item) => {
  if (item.children && item.children.length > 0) {
    havChildId.value = havChildId.value ? '' : item.id
    return
  }
  const reg = /^(http|https)/
  if (reg.test(item.link)) {
    window.open(item.link)
    return
  }
  router.push(item.link)
}


// 隐藏弹出层
const hidePopup = () => {
  // reset
  show.value = false
  isInput.value = false;
  search.value = '';
  tipList.value = [];
}

const hideSearchPopup = () => {
  showSearch.value = false
}

// show popup
const showPopup = (type) => {
  show.value = true;
  // if (type == 'search') {
  //   isInput.value = true;
  // } else {
  //   isInput.value = false;
  // }
}

// 订阅
const onEnter = () => {
  if (emailVal.value) {
    if (emailReg.test(emailVal.value)) {
      console.log(emailVal.value)
      subscribedApi({email: emailVal.value}).then((res)=>{
        if (res.code === 1) {
          alert('subscribe success!');
        }
      })
    } else {
      alert('format error!')
    }
  } else {
    alert('value is null!')
  }
  emailVal.value = ''
}

// 输入时触发 oninput
const onInput = () => {
  isInput.value = true;
  store.commit('changeSearchVal', search.value)
  // 发虚拟请求
  // issue a request

  // 正则表达式匹配搜索字符
  const searchReg = new RegExp(search.value, 'gi');
  // 清空搜索结果重新进行
  tipList.value = [];

  if (search.value) {
    getSearchTitle()
  }
}

// 刷新页面 refresh page
const refresh = () => {
  if (route.path === '/') {
    router.go(0);
  } else {
    router.push('/');
  }
}

// 跳转到搜索页面  go to search page
const toSearch = (msg, type) => {
  // 输入框存在内容则携带参数到搜索结果页面
  // If there is any content in the input box, carry parameters to the search results page
  if (msg) {
    switch (type) {
      case 'search':
        store.commit('changeSearchVal', search.value);
        break;
      case 'result':
        store.commit('changeSearchVal', msg.t);
        break;
      default:
        break;
    }
    if (type === 'detail') {
      store.commit('changeSearchVal', msg.t);
      // console.log('route>>>', route)
      if (route.path !== `/ContentPages`) {
        // store.commit('changeSearchVal', .value);
        router.push({path:`/ContentPages`,
          query:{
            contentId: msg.id
          }
      });
      } else {
        router.replace({path:`/ContentPages`,
          query:{
            contentId: msg.id
          }
        });
      }
      show.value = false

      return ;
    }
    if (route.path != '/search/result') {
      store.commit('changeSearchVal', search.value);
      router.push(`/search/result?msg=${search.value}`);
      show.value = false
    } else {
      router.go(0)
    }
  } else {
    alert('Please enter the content')
  }
}

const getNav = ()=>{
  getNavData().then(({data})=>{
    if (data) {
      routerList.value = data.sort((a, b) => a.sort - b.sort);
    }
  })
}

const getShare = ()=>{
  getAction({url: '/index/getShare', params: { type: 'mobile' }}).then(res=>{
    shareList.value = res.data;
  })
}
onMounted(()=>{
  getNav()
  getShare()
  window.addEventListener('keydown', (e)=>{
    if (e.keyCode === 27) {
      show.value = false;
    }
  })
})

const getSearchTitle = ()=>{
  const searchReg = new RegExp(search.value, 'gi');
  searchTitleApi({keyword: search.value}).then(res=>{
    res.data.forEach(item=>{
      console.log('item>>>>', item)
      const result = searchReg.exec(item.title);
      console.log(result)
      if (result) {
        const resultMsg = result.input.replace(searchReg, `<span style="color:#ff6d00">${result[0]}</span>`)
        tipList.value.push({ t: item.title, title: resultMsg, id: item.id });
      }
    })
    if (!tipList.value.length) {
      noResult.value = `There are no results for the search term "${search.value}"`;
    }
  })
}

</script>
<style lang="scss" scoped>
::v-deep .van-popup {
  box-shadow: 0 0px 10px rgb(201, 198, 198);
}

.nav {
  max-width: 1000px;
  padding: 0 46px;
  height: 80Px;
  position: relative;
  margin: 0 auto;
  z-index: 99;
  // @media screen and (min-width: 1440Px) and (max-width: 100vw) {
  //   padding: 0 48px;
  // }
  @media (max-width: 1280Px) {
    padding: 0 40px;
  }
  @media (max-width: 767Px) {
    padding: 0 18px;
  }
  #header {
    height: 80Px;
    position: relative;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .logo-text {
      width: 200px;
      border-radius: 0px;
      margin-right: auto;
      cursor: pointer;
      //display: flex;
      //align-items: center;
      img {
        width: 100%;
        height: auto;
        background-color: #f5f5f5;
      }
    }

    .nav-list {
      margin-right: auto;
      display: flex;
      .nav-item {
        display: flex;
        align-items: center;
        font-family: Cinzel;
        font-size: 12px;
        color: #000000;
        margin-right: 16px;
        cursor: pointer;
        .icon-down {
          margin-left: 10px;
          width: 8px;
        }
      }
    }

    .nav-children-list {
      display: none;
      position: absolute;
      top: 40px;
      z-index: 9;
      width: 90px;
      padding: 6px 10px;
      background: #f5f5f5;
      flex-direction: column;
      box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.15);
      .nav-item {
        display: flex;
        align-items: center;
        font-family: Cinzel;
        font-size: 12px;
        height: 36px;
        cursor: pointer;
      }
    }

    .icon {
      img {
        width: 100%;
      }
    }

    .search {
      position: relative;
      height: 21px;
      width: 21px;
      cursor: pointer;
      .search-com {
        position: absolute;
        top: 25px;
        right: 0;
        width: 430px;
      }
      &.max-show {
        display: inline-flex;
      }
      &.min-show {
        display: none;
      }
    }
    @media (max-width: 1280Px) {
      .search {
        &.max-show {
        display: none;
      }
      &.min-show {
        display: inline-flex;
      }
      }
    }
    .menu {
      margin-left: 22px;
      display: none;
      cursor: pointer;
      width: 21px;
      height: 18px;
      right: 0px;
    }
    @media (max-width: 1280Px) {
      .nav-list {
        display: none;
      }
      .nav-children-list {
        display: none;
      }
      .menu {
        display: inline-flex;
      }
    }
  }

  .popup {
    .nav-close {
      width: 100%;
      margin: 0 auto;
      height: 60px;
      position: relative;
      padding: 0 24px;
      cursor: pointer;
      display: flex;
      align-items: center;
      justify-content: space-between;
      .close {
        font-size: 18px;
        right:36px;
        img {
          width: 18px;
        }
      }

      .popup-logo {
        width: 200px;
        height: 18px;
        background-image: url(/images/ForesightLogo.png);
        background-size: 100% ;
        background-position: center;
        background-repeat: no-repeat;
      }
    }

    .popup-nav {
      .popup-nav-list {
        padding: 0 32px;
        .popup-nav-item {
          font-family: Cinzel;
          font-size: 12px;
          color: #000000;
          border-bottom: 1px solid #EFEFEF;
          cursor: pointer;
          .icon-up {
            transform: rotate(180deg);
          }
          .popup-nav-item-title {
            height: 36px;
            display: flex;
            align-items: center;
            justify-content: space-between;
          }
          .popup-nav-children-list {
            display: flex;
            margin-left: 14px;
            flex-direction: column;
            .popup-nav-children-item-title {
              height: 36px;
              display: flex;
              align-items: center;
            }
          }
        }
      }
    }

    .nav-search {
      max-width: 1000px;
      margin: 12px auto;
      padding: 0 36px;

      .search-input {
        width: 100%;
        height: 48px;
        line-height: 48px;
        background: #F9F9F9;
        border-radius: 50px;
        padding: 0 20px;
        position: relative;
        img {
          cursor: pointer;
        }
        .search-ipt {
          width: 90%;
          font-size: 16px;
          margin: 0 auto;
          background-color: transparent;
          border: none;
          outline: none;
          position: absolute;
          left: 50px
        }

        .search-ipt::placeholder {
          font-family: 'Raleway';
          font-style: normal;
          font-weight: 400;
          font-size: 16px;
          line-height: 24px;
          color: #B6BFC7;
        }

        .ipt-search {
          width: 18px;
          height: 18px;
          position: absolute;
          left: 20px;
          top: 50%;
          transform: translateY(-50%);
        }
        .close {
          width: 14px;
          height: 14px;
          position: absolute;
          right: 20px;
          top: 50%;
          transform: translateY(-50%);
        }
      }
    }

    .tip-msg {
      max-width: 1000px;
      margin: 0 auto;
      height: 440px;
      padding: 24px 36px;
      overflow-y: scroll;

      @media screen and (max-width: 431Px) and (min-width: 0Px) {
        padding: 24px 24px !important;
      }

      @media screen and (min-width: 1440Px) and (max-width: 100vw) {
        padding: 24px 40px !important
      }

      .search-result {
        width: 100%;
        height: 56px;
        font-family: 'Libre Bodoni';
        font-style: normal;
        font-weight: 400;
        font-size: 16px;
        line-height: 56px;
        color: #000000;
        padding: 0 16px;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
      }

      .no-result {
        font-family: 'Libre Bodoni';
        font-style: normal;
        font-weight: 400;
        font-size: 16px;
        color: #000000;
        padding: 0 16px;
      }

      .search-result:hover {
        color: #FF6D00;
        background: rgba(255, 109, 0, 0.1);
      }
    }

    .tip-msg::-webkit-scrollbar {
      display: none;
      /* Chrome Safari */
    }

    .menu-bar {
      max-width: 1000px;
      margin: 0 auto;
      padding: 10px 45px 40px;

      .content {
        margin: 32px 0;
      }
      .other-view {
        font-family: 'Cinzel';
        font-style: normal;
        font-weight: 400;
        font-size: 24px;
        line-height: 32px;
        text-align: right;
        color: #000000;
      }

      .classify {
        font-family: 'Raleway';
        font-style: normal;
        font-weight: 400;
        font-size: 12px;
        line-height: 21px;
        text-align: right;
        color: #00000080;
        //margin-top: 32px;
      }
    }
    .popup-footer {
      margin-top: 50px;
      margin-left: 36px;
      .subscribe {
        font-weight: 400;
        color: rgba(0, 0, 0, 0.5);
        font-family: Libre Bodoni;
        font-size: 16px;
      }
      .email {
        margin-top: 4px;
        height: 24px;
        display: flex;
        .email-input {
          height: 100%;
          border: 1px solid #999;
          padding-left: 10px;
          font-family: Raleway;
          font-size: 12px;
        }
        .email-submit {
          width: 32px;
          border: 1px solid #999;
          border-left: none;
          display: flex;
          align-items: center;
          justify-content: center;
        }
      }
      .share-list {
        margin-top: 15px;
        img {
          width: 20px;
          height: 20px;
          margin-right: 16px;
        }
      }
      .footer-provider {
        margin-top: 16px;
        font-family: Raleway;
        font-size: 10px;
        color: rgba(0, 0, 0, 0.25);
      }
    }
  }
  @media (max-width: 767Px) {
    :deep(.van-popup) {
      width: 100% !important;
    }
  }
}

.margin-top {
  margin-top: 32px;
}
.footer-menus {
  display: flex;
  margin-top: 24px;
  margin-bottom: 18px;
  .small-font {
    font-size: 12px;
    color: #000;
    margin-right: 18px;
    &.skip-a {
      cursor: pointer;
    }
  }
}
.active-link {
  color: rgba(255, 109, 0, 1) !important;
}
</style>
