<template>
  <div class="app-header">
    <div class="header-wrapper">
      <div class="header-inner">
        <div class="left-info">
          <router-link class="title-sec" :to="{
              name: language == '' ? 'home' : 'homeEn',
              params: { lang: language },
            }">
            <img v-if="language == ''" src="@/assets/images/logo_cn2.png" alt="logo" class="logo cn-logo" />
            <img v-else src="@/assets/images/logo_en2.png" alt="logo" class="logo" />
          </router-link>
        </div>
        <div v-if="pcShow" class="home-nav-bar pc">
          <div class="home-nav-bar-top">
            <div class="search">
              <n-input-group>
                <n-button size="large" color="#355672" @click="handleSearch" style="padding: 0 10px"><n-icon :component="MdSearch" size="30" color="#fff" /></n-button>
                <n-input @keydown.enter="keyDown" type="text" size="large" :placeholder="t('report.content.keyword')" v-model:value="keyword" clearable style="background-color: #fafafa" />
                <n-select style="width: 200px" clearable :placeholder="t('report.content.keywordType')" v-model:value="selectTypeValue" :options="selectTypeList" />
              </n-input-group>
            </div>
            <template v-if="language == ''">
              <template v-if="isLogin">
                <div class="userInfo">
                  <img class="avatar" src="@/assets/images/avatar.png" alt="avatar" width="30" />
                  <span class="username" @click="toMine">{{
                    userInfo.name
                  }}</span>
                  <span>|</span>
                  <span class="logout" @click="handleLogout">退出登录</span>
                </div>
              </template>
              <template v-if="!isLogin">
                <div class="login" @click="handleSignIn">登录</div>
              </template>
            </template>
            <p class="home-tel" v-else>
              <n-icon :component="IosCall" size="30" />
              <a href="tel:1-8884226999">+1-888 422 6999 (US)</a>
            </p>
          </div>
          <div class="home-nav">
            <div class="home-nav-link">
              <router-link id="nav-item" class="nav-item" :to="{
                  name: language == '' ? 'home' : 'homeEn',
                  params: { lang: language },
                }">
                <span class="txt">{{ t("common.navigate.home") }}</span>
              </router-link>
              <n-dropdown :options="reportOptions" trigger="hover" size="huge" @select="chooseReportMenu">
                <router-link id="nav-item" class="nav-item" :to="{ name: 'reports', params: { lang: language } }">
                  <span class="txt">{{ t("common.navigate.report") }}</span>
                </router-link>
              </n-dropdown>
              <n-dropdown :options="bulletinOptions" trigger="hover" size="huge" @select="chooseBulletinMenu" v-if="language == ''">
                <router-link id="nav-item" class="nav-item" :to="{
                    name: 'bulletinThinkTank',
                    params: { marketType: 'industry-brief' },
                  }">
                  <span class="txt">简报智库</span>
                </router-link>
              </n-dropdown>
              <router-link id="nav-item" class="nav-item" :to="{ name: 'marketIndex', params: { lang: language } }">
                <span class="txt">{{ t("common.navigate.market") }}</span>
              </router-link>
              <n-dropdown :options="newsOptions" trigger="hover" size="huge" @select="chooseNewsMenu">
                <router-link id="nav-item" class="nav-item" :to="{ name: 'newsCategories', params: { lang: language } }">
                  <span class="txt">{{ t("common.navigate.news") }}</span>
                </router-link>
              </n-dropdown>
              <n-dropdown :options="aboutOptions" trigger="hover" size="huge" @select="chooseAboutMenu">
                <router-link id="nav-item" class="nav-item" :to="{ name: 'about', params: { lang: language } }">
                  <span class="txt">{{ t("common.navigate.aboutUs") }}</span>
                </router-link>
              </n-dropdown>
              <router-link id="nav-item" class="nav-item" :to="{ name: 'contactUsIndex', params: { lang: language } }">
                <span class="txt">{{ t("common.navigate.contactUs") }}</span>
              </router-link>
            </div>
            <div id="nav-item" class="lang">
              <!-- <a class="txt" @click="lang('zh-CN')">{{ t('common.lang.zh-CN') }}</a>
            <span class="separator txt">|</span>
            <a class="txt" @click="lang('en-US')">{{ t('common.lang.en-US') }}</a> -->
              <n-icon :component="IosGlobe" size="22" />
              <select class="lang-select" @change="lang($event.target.value)" v-model="langSelected">
                <option value="zh-CN">中文</option>
                <option value="en-US">English</option>
              </select>
            </div>
          </div>

          <!-- <div class="nav-search">
            <a @click="search"><n-icon :component="MdSearch" size="20"/></a>
            <input type="text" class="nav-search-ipt" v-model="keyword"/>
          </div> -->
        </div>

        <!--手机端导航-->
        <div v-if="!pcShow" class="mobile">
          <n-dropdown trigger="click" :size="language ? 'small' : 'huge'" :options="mobileMenu" @select="chooseMenu" placement="bottom-start" :class="language">
            <n-icon :component="MdApps" size="80" color="#fff" />
          </n-dropdown>
        </div>
      </div>

      <div v-if="!pcShow" class="header-lang">
        <div class="mobile-search">
          <n-input-group>
            <n-button size="large" color="#355672" @click="handleSearch" style="padding: 0 10px"><n-icon :component="MdSearch" size="30" color="#fff" /></n-button>
            <n-input type="text" size="large" :placeholder="t('report.content.keyword')" v-model:value="keyword" clearable style="background-color: #fafafa" />
            <n-select style="width: 240px" clearable :placeholder="t('report.content.keywordType')" v-model:value="selectTypeValue" :options="selectTypeList" />
          </n-input-group>
        </div>
        <div class="top-login">
          <template v-if="language == ''">
            <div class="userInfo" v-if="isLogin">
              <span>{{ userInfo.name }}</span>
              <span>|</span>
              <span @click="toMine">个人中心</span>
              <span>|</span>
              <span class="logout" @click="handleLogout">退出登录</span>
            </div>
            <div class="login" @click="handleSignIn" v-if="!isLogin">登录</div>
          </template>
          <div>
            <a class="txt" @click="lang('zh-CN')">{{
              t("common.lang.zh-CN")
            }}</a>
            <span class="separator txt">|</span>
            <a class="txt" @click="lang('en-US')">{{
              t("common.lang.en-US")
            }}</a>
          </div>
        </div>
      </div>
    </div>
    <n-modal :show="signInVisible" preset="dialog" :title="signInTitle" :showIcon="false" :close-on-esc="false" :mask-closable="false" @close="signInVisible = false" :class="{ 'login-dialog': !pcShow }">
      <SignInLogin @closeSginDialog="closeSginDialog" v-if="sginType == 'login'"></SignInLogin>
      <SignInRegister @closeSginDialog="closeSginDialog" v-if="sginType == 'register'"></SignInRegister>
      <SignInForgot @closeSginDialog="closeSginDialog" v-if="sginType == 'forgot'"></SignInForgot>
    </n-modal>
    <n-modal v-model:show="logoutVisible" preset="dialog" title="提示" :showIcon="false" content="确认退出登录吗?" positive-text="确认" negative-text="取消" :close-on-esc="false" :mask-closable="false" @positive-click="submitLogoutCallback" @negative-click="cancelLogoutCallback" :class="{ 'login-dialog': !pcShow }" />
  </div>
</template>

<script lang="ts" setup>
import { useI18n } from "vue-i18n";
import { useLocaleStoreWithOut } from "@/store";
import {
  DropdownOption,
  NDropdown,
  NIcon,
  NButton,
  NInput,
  NInputGroup,
  NSelect,
  NSpace,
  NModal,
  createDiscreteApi,
} from "naive-ui";
import {
  Component,
  h,
  onMounted,
  ref,
  onUnmounted,
  onBeforeMount,
  watch,
  computed,
  inject,
  onServerPrefetch,
} from "vue";
import { getLocalSessionNews, getLocalSessionReport } from "@/store/cache";
import { useRouter, useRoute } from "vue-router";
import {
  MdApps,
  MdHome,
  IosPaper,
  IosSearch,
  MdToday,
  MdPeople,
  MdSearch,
  IosCall,
  IosGlobe,
} from "@vicons/ionicons4";
import { langOnBrowser } from "@/utils";
import SignInLogin from "@/components/Login/index.vue";
import SignInRegister from "@/components/Login/register.vue";
import SignInForgot from "@/components/Login/forgot.vue";
import { useUserStore } from "@/store/user";
import { logOut_Api } from "@/api/mine";

const { t } = useI18n();
const router = useRouter();
const route = useRoute();
const userStore = useUserStore();
const pcShow = ref(true);
const keyword = ref<string>(""); //关键字

const renderIcon = (icon: string) => {
  return () => {
    return h("span", { class: icon });
  };
};
const renderIconC4 = (icon: Component) => {
  return () => {
    return h(NIcon, null, {
      default: () => h(icon),
    });
  };
};

// const renderIconLabel = (option: DropdownOption) => {
//   return h('a',{ onclick: () => chooseMenu, target: '_blank' },{ default: () => option.label});
// }
const reportOptions = [] as any; //报告列表
const newsOptions = [] as any; //行业资讯
const aboutOptions = [] as any; //关于我们
const bulletinOptions = [] as any; // 简报智库

const mobileMenu = [
  { label: t("common.navigate.home"), key: "home", name: "home" },
  {
    label: t("common.navigate.report"),
    key: "reports",
    children: reportOptions,
    name: "reports",
  },
  {
    label: "简报智库",
    key: "bulletin",
    children: bulletinOptions,
    name: "bulletin",
  },
  { label: t("common.navigate.market"), key: "market", name: "marketIndex" },
  {
    label: t("common.navigate.news"),
    key: "newsCategories",
    children: newsOptions,
    name: "newsCategories",
  },
  {
    label: t("common.navigate.aboutUs"),
    key: "about",
    children: aboutOptions,
    name: "about",
  },
  {
    label: t("common.navigate.contactUs"),
    key: "contactUs",
    name: "contactUsIndex",
  },
];
const language = ref<string>("");
const langSelected = ref<string>("zh-CN");
const selectTypeValue = ref();
const selectTypeList = ref([
  {
    label: t("common.navigate.report"),
    value: "reports",
  },
  {
    label: t("common.navigate.news"),
    value: "newsCategories",
  },
  {
    label: t("common.navigate.bulletin"),
    value: "bulletinThinkTank",
  },
]);
const signInVisible = ref<boolean>(false);
const signInTitle = ref<string>("");
const sginType = ref<string>("login");
const logoutVisible = ref(false);

const userInfo = computed(() => userStore.getUserInfo);
const isLogin = computed(() =>
  userStore.getToken && userStore.getUserInfo ? true : false
);

watch(
  () => userStore.getSearchType,
  (val) => {
    selectTypeValue.value = val || null;
  }
);

watch(langSelected, () => {
  if (langSelected.value == "en-US") {
    selectTypeList.value = [
      {
        label: t("common.navigate.report"),
        value: "reports",
      },
      {
        label: t("common.navigate.news"),
        value: "newsCategories",
      },
    ];
    userStore.resetState();
  }
});

watch(
  () => userStore.getShowLoginDialog,
  (newval, oldval) => {
    signInVisible.value = newval;
    sginType.value = "login";
  }
);

watch(signInVisible, (val) => {
  if (val === false) {
    userStore.setShowLoginDialog(false);
  }
});
//const logo = ref<string>('logo_cn.png');

// onUnmounted(() => {
//   window.removeEventListener('scroll',onScroll);
// });

// const route = useRoute();
// function onScroll(){
//   const scrollTop = document.documentElement.scrollTop;
//   if(scrollTop === 0 && (route.name === 'home' || 'marketIndex' === route.name || 'homeEn' === route.name)){
//     logo.value = language.value == ''?'logo_cn.png':'logo_en.png';
//   }else{
//     logo.value = language.value == ''?'logo_cn2.png':'logo_en2.png';
//   }
// }

// 中英文切换
function lang(locale: string) {
  useLocaleStoreWithOut().setLocaleInfo(locale);
  document.querySelector("html")?.setAttribute("lang", locale);
  let url = router.currentRoute.value.href;
  // const params = currentRoute.value.params;
  if (locale === "en-US") {
    url = "/en" + url;
    if (
      [
        "bulletinThinkTank",
        "bulletinDetail",
        "mineCenter",
        "mineUpdatePwd",
        "payBack",
        "qualify",
      ].includes(route.name)
    ) {
      url = "/en";
    }
  } else {
    if (url.includes("/en")) {
      url = url.replace("/en", "");
    }
    if (!url) {
      url = "/";
    }
  }
  // console.log(currentRoute.value);
  // router.push({ name: 'home', params: params});
  // 切换语言后，需要重新设置浏览器地址
  //location.reload();
  location.href = url;
}

// 研究报告菜单切换
function chooseReportMenu(key: string | number, _option: DropdownOption) {
  router.push({
    name: "reports",
    params: { category: key, lang: language.value },
  });
  //router.push({ path: '/reports/'+key+'/'+option.label})
}

// 行业资讯
function chooseNewsMenu(key: string | number) {
  router.push({
    name: "newsCategories",
    params: { marketType: key, lang: language.value },
  });
}

onBeforeMount(async () => {
  pcShow.value = !isMobile();
});

onMounted(async () => {
  //window.addEventListener('scroll',onScroll);
  const value = langOnBrowser();
  language.value = value === "en-US" ? "en" : "";
  langSelected.value = value;

  // 下拉菜单
  const cacheDict = await getLocalSessionReport();
  cacheDict?.forEach(
    (vo: { dictLabel: any; dictValue: any; dictIcon: any }) => {
      reportOptions.push({
        label: vo.dictLabel,
        key: vo.dictValue,
        icon: renderIcon(vo.dictIcon),
        name: "reports",
      });
    }
  );

  const cacheDictNews = await getLocalSessionNews();
  cacheDictNews?.forEach((vo: any) => {
    newsOptions.push({
      label: vo.dictLabel,
      key: vo.dictValue,
      icon: renderIcon(vo.dictIcon),
      name: "newsCategories",
    });
  });

  aboutOptions.push({
    label: t("common.navAboutUs.comp"),
    name: "about",
    icon: renderIcon("iconfont iconfont icon-ziyuan"),
  });
  aboutOptions.push({
    label: t("common.navAboutUs.method"),
    name: "link",
    icon: renderIcon("iconfont icon-chaxun"),
  });
  aboutOptions.push({
    label: t("common.navAboutUs.order"),
    name: "order",
    icon: renderIcon("iconfont icon-a-dingdanguanli2x"),
  });
  aboutOptions.push({
    label: t("common.navAboutUs.term"),
    name: "term",
    icon: renderIcon("iconfont icon-shejiyukaifa-"),
  });

  if (language.value == "") {
    aboutOptions.push({
      label: t("common.navAboutUs.qualify"),
      name: "qualify",
      icon: renderIcon("iconfont iconfont icon-ziyuan"),
    });
  }

  bulletinOptions.push({
    label: "行业简报",
    name: "bulletinThinkTank",
    marketType: "industry-brief",
    icon: renderIcon("bqfl-iconfont bqfl-iconfont icon-zhinengjianbao"),
  });
  bulletinOptions.push({
    label: "企业洞察",
    name: "bulletinThinkTank",
    marketType: "enterprise-hole-analysis",
    icon: renderIcon("bqfl-iconfont bqfl-iconfont icon-yanjiubaogao"),
  });
});

// 关于我们跳转
function chooseAboutMenu(key: string | number, option: DropdownOption) {
  router.push({ name: option.name, params: { lang: language.value } });
}

// 关于简报智库
function chooseBulletinMenu(key: string | number, _option: DropdownOption) {
  console.log("_option===>", _option);
  router.push({
    name: "bulletinThinkTank",
    params: {
      marketType: _option.marketType,
    },
  });
}

// 手机端跳转
function chooseMenu(key: string | number, option: DropdownOption) {
  if ("reports" === option.name) {
    router.push({
      name: option.name,
      params: { category: key, lang: language.value },
    });
  } else if ("newsCategories" === option.name) {
    router.push({
      name: option.name,
      params: { marketType: key, lang: language.value },
    });
  } else if ("home" === option.name) {
    router.push({
      name: language.value === "" ? "home" : "homeEn",
      params: { marketType: key, lang: language.value },
    });
  } else {
    router.push({ name: option.name, params: { lang: language.value } });
  }
}

function handleSearch() {
  switch (selectTypeValue.value) {
    case "reports":
      router.push({
        name: "reports",
        params: { lang: language.value, keyword: keyword.value },
      });
      break;
    case "newsCategories":
      router.push({
        name: "newsCategories",
        params: { lang: language.value, keyword: keyword.value },
      });
      break;
    case "bulletinThinkTank":
      router.push({
        name: "bulletinThinkTank",
        params: { marketType: "industry-brief", title: keyword.value },
      });
      break;
    default:
      router.push({
        name: "reports",
        params: { lang: language.value, keyword: keyword.value },
      });
      break;
  }
}

function keyDown() {
  handleSearch();
}

const handleSignIn = () => {
  signInVisible.value = true;
  sginType.value = "login";
  signInTitle.value = "登录";
};

const toMine = () => {
  router.push({
    name: "mine",
  });
};

const handleLogout = () => {
  logoutVisible.value = true;
};

const submitLogoutCallback = () => {
  logOut_Api().then((res) => {
    NMessage.message.success("退出成功");
    userStore.resetState();
    router.push("/");
  });
};

const cancelLogoutCallback = () => {
  logoutVisible.value = false;
};

const closeSginDialog = (type: string) => {
  switch (type) {
    case "success":
      signInVisible.value = false;
      break;
    case "login":
      break;
    case "register":
      sginType.value = type;
      signInTitle.value = "注册账号";
      break;
    case "forgot":
      sginType.value = type;
      signInTitle.value = "忘记密码";
      break;
    default:
      break;
  }
};

const NMessage = createDiscreteApi(["message"]);
</script>
<style lang="scss">
.app-header {
  z-index: 9;
  width: 100%;
  position: fixed;
  left: 0;
  top: 0;
  background: #fff;
  height: 140px;
  box-shadow: 2.5px 4.33px 15px 0px rgb(0 0 0 / 15%);

  .header-wrapper {
    transition: all 0.3s;

    .header-inner {
      width: 1200px;
      margin: 0 auto;
      height: 140px;
      display: flex;
      flex-flow: row nowrap;
      align-items: center;
      justify-content: space-between;

      .left-info {
        display: flex;
        flex-flow: row nowrap;
        align-items: center;

        .title-sec {
          position: relative;
          display: flex;
          flex-flow: row nowrap;
          align-items: center;
          margin-right: 15px;
          cursor: pointer;

          .title-logo {
            position: absolute;
            top: 0;
            left: 0;
            display: block;
            width: 100%;
            height: 80px;
            overflow: hidden;
            font-size: 0;
          }

          .logo {
            height: 80px;
            width: 100%;
            max-width: 240px;
            object-fit: contain;
          }

          .cn-logo {
            height: 120px;
          }

          .sub-title {
            font-size: 12px;
            color: #fff;
            margin-bottom: 2px;
          }

          .title {
            font-size: 18px;
            font-weight: bold;
            color: #fff;
          }
        }
      }

      .login-box {
        display: flex;
        flex-flow: row nowrap;
        align-items: center;

        .msg-box {
          color: #fff;
          font-size: 15px;
          margin-right: 15px;
          transition: all 0.5s;
          cursor: pointer;

          &:hover {
            color: $blue;
          }
        }

        .avator-box {
          width: 30px;
          height: 30px;
          margin-right: 15px;
          border-radius: 15px;
          overflow: hidden;

          .avator {
            display: block;
            width: 100%;
            height: 100%;
          }
        }

        .basic-info {
          cursor: pointer;
          color: #fff;
          outline: none !important;
        }

        .btn-group {
          .register {
            background: #fff;
            color: #000;
            border-color: #fff;
            margin-left: 5px;

            &:hover {
              color: $blue;
              border-color: $blue;
            }
          }
        }
      }

      .tool-group {
        display: flex;
        flex-flow: row nowrap;
        align-items: center;

        .tool-item {
          margin-right: 20px;
          color: #409eff;
          font-size: 15px;
          cursor: pointer;
        }

        .icon {
          font-size: 20px;
        }
      }
    }

    .home-nav-bar {
      margin: 0;
      height: 140px;
      display: flex;
      flex-flow: row nowrap;
      align-items: center;
      justify-content: center;
      width: calc(100% - 350px);
      flex-wrap: wrap;

      //border-top: 1px solid rgba(255, 255, 255, 0.2);
      .home-nav-bar-top {
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: space-between;

        .search {
          width: 45rem;

          .n-base-selection {
            height: 100%;
            --n-border: 1px solid #18a058 !important;

            .n-base-selection-label {
              height: 100%;
              background-color: #18a058 !important;

              .n-base-selection-input,
              .n-base-selection-placeholder__inner {
                color: #fff;
              }
            }
          }
        }

        .home-tel {
          //color: #fff;
          .n-icon {
            vertical-align: middle;
            border-radius: 100%;
            //border: 1px solid #fff;
            margin-right: 10px;
          }

          > a {
            font-size: 18px;
          }
        }

        .userInfo {
          display: flex;
          align-items: center;

          .avatar {
            width: 30px;
            height: 30px;
            margin-right: 10px;
            vertical-align: middle;
            border-radius: 50%;
          }

          .username {
            font-size: 16px;
          }

          span {
            margin-right: 10px;
            cursor: pointer;

            &:last-child {
              margin-right: 0;
            }
          }
        }

        .login {
          width: 110px;
          height: 40px;
          text-align: center;
          line-height: 40px;
          color: #ffffff;
          font-size: 16px;
          background-color: #18a058;
          border-radius: 20px;
          cursor: pointer;
        }
      }

      .home-nav {
        width: 100%;
        display: flex;
        justify-content: space-between;

        .home-nav-link {
          display: flex;
        }
      }

      .nav-item {
        height: 100%;
        margin-right: 2rem;
        display: flex;
        flex-flow: row nowrap;
        align-items: center;
        justify-content: center;
        cursor: pointer;

        .txt {
          font-size: 1.2rem;
          color: #000;
          font-weight: 600;
        }

        &.router-link-active {
          position: relative;

          &::after {
            position: absolute;
            left: 0;
            bottom: 0;
            content: "";
            width: 100%;
            height: 3px;
            background: #000;
          }
        }

        &:hover {
          position: relative;

          &::after {
            position: absolute;
            left: 0;
            bottom: 0;
            content: "";
            width: 100%;
            height: 3px;
            background: #000;
          }
        }
      }
    }
  }
}

.lang {
  font-weight: 600;
  font-size: 18px;
  margin: 0 20px;

  .separator {
    padding: 0 7px;
  }

  .n-icon {
    vertical-align: middle;
    //color: #fff;
  }

  .lang-select {
    border: none;
    outline: none;
    margin-left: 2px;
    width: 100px;
    font-size: 15px;
    background: none;

    //color: #fff;
    option {
      color: #000;
    }
  }
}

.nav-search {
  width: 200px;

  .n-icon {
    margin-right: -25px;
    vertical-align: middle;
  }

  .nav-search-ipt {
    border: none;
    width: 200px;
    height: 30px;
    font-size: 1em;
    padding-left: 30px;
  }
}

.n-dropdown-option-body__label {
  font-weight: 600;
}

.n-dialog {
  min-width: 550px;
  padding-top: 48px;
  border-radius: 20px;

  .n-dialog__title {
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 24px;
    color: #1a1a1a;
    font-weight: bold;
    text-align: center;
  }
}

.login-dialog.n-dialog {
  min-width: auto;

  padding-top: 20px;
  border-radius: 10px;

  .n-dialog__title {
    font-size: 18px;
  }

  .n-dialog__content {
    .container {
      padding: 20px 10px;

      .login-btn {
        height: 45px;
      }

      .n-form {
        .n-form-item {
          .n-form-item-label {
            width: 85px !important;
            font-size: 12px;
          }

          .n-form-item-feedback-wrapper {
            min-height: 10px;
          }
        }
      }
    }
  }
}
</style>
