<template>
  <div v-if="!hideHeader" ref="head" class="header isFixed">
    <div class="header-container">
      <div class="flex">
        <div class="logo" @click="toIndex">
          <img
            v-show="forums && forums.set_site"
            :src="
              forums && forums.set_site && forums.set_site.site_logo
                ? forums.set_site.site_logo
                : require('@/assets/logo.png')
            "
            alt="头部logo"
          />
        </div>
        <div class="knowledge" @click="knowledge">
          <img class="knowledgeImg" src="@/assets/zhishiku.png" alt="" />
        </div>
        <el-input
          v-model="inputVal"
          autocomplete="off"
          size="medium"
          :placeholder="$t('search.search')"
          class="h-search"
          :disabled="siteClose"
          @keyup.enter.native="onClickSearch"
        >
          <svg-icon
            slot="suffix"
            type="search"
            class="el-input__icon"
            @click="onClickSearch"
          />
        </el-input>
        <template>
          <div
            v-if="showSyncWanPan"
            v-loading="showSyncWanPanloading"
            class="knowledge"
            @click="SyncWanPan"
          >
            刷新知识库
          </div>
        </template>
      </div>
      <div>
        <!-- 未登录 -->
        <div v-if="siteClose || !islogin">
          <el-button
            v-if="siteClose || !userId"
            size="small"
            class="h-button h-button1"
            @click="login"
          >
            {{ $t("user.login") }}
          </el-button>
        </div>
        <!-- 已登录 -->
        <div
          v-if="userId && JSON.stringify(userInfo) !== '{}' && !siteClose"
          class="flex"
        >
          <avatar
            :user="{
              id: userInfo.id,
              username: userInfo.username,
              avatarUrl: userInfo.avatarUrl,
              isReal: userInfo.isReal
            }"
            :size="35"
            :round="true"
          />
          <nuxt-link
            v-if="userInfo.username && userInfo.id"
            :to="`/user/${userInfo.id}`"
            class="menu-item user-name text-hidden"
          >
            {{ userInfo.username }}
          </nuxt-link>
          <nuxt-link to="/my/notice" class="menu-item notice-btn">
            <span class="flex">
              {{ $t("home.tabsNews") }}
              <span
                v-if="
                  userInfo.unreadNotifications &&
                    userInfo.unreadNotifications > 0
                "
                class="unread-notice"
                >{{
                  userInfo.unreadNotifications > 99
                    ? "99+"
                    : userInfo.unreadNotifications
                }}</span
              >
            </span>
          </nuxt-link>
          <nuxt-link to="/my/profile" class="menu-item">{{
            $t("profile.personalhomepage")
          }}</nuxt-link>
          <div class="menu-item" @click="logout">{{ $t("user.logout") }}</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import loginAbout from "@/mixin/loginAbout";
import jwt from "jsonwebtoken";
import axios from "@/plugins/axios.js";
import config from "@/config.js";
export default {
  name: "Header",
  mixins: [loginAbout],
  props: {
    headImg: {
      type: String,
      default: ""
    }
  },
  data() {
    return {
      showSyncWanPanloading: false,
      showSyncWanPan: false,
      inputVal: "",
      isTest:false,
      code: "", // 邀请码
      canReg: false,
      siteClose: false,
      userInfoTimer: null, // 定时器
      offsetTop: 0,
      imgurl: require("@/assets/logo.png"),
      islogin: true,
      hideHeader: false, // 不需要头部右侧部分
      preurl: "/"
    };
  },
  computed: {
    userId() {
      return this.$store.state.user.info.id;
    },
    forums() {
      return this.$store.state.site.info.attributes || {};
    },
    userInfo() {
      //   var result = axios.request({
      //   url: 'https://sso.bailuntec.com/GetUserResource',
      //   headers: {
      //     Authorization: token,
      //     "Content-Type": "application/x-www-form-urlencoded",
      //     "Access-Control-Allow-Origin": "*",

      //   },
      //   withCredentials: true, // 跨域
      //   method: 'get'
      // }).then((res)=>{
      //   console.log(res.data.result);
      // })

      if (!!this.$store.state.user) {
        const users = this.$store.state.user.info.attributes;
        if (!!users) {
          if (users.username == "熊裕文") {
            this.showSyncWanPan = true;
          }
        }
      }
      return this.$store.state.user.info.attributes || {};
    }
  },
  watch: {
    // 监听路由变化
    $route(to) {
      if (to.path === "/site/close") {
        this.siteClose = true;
      } else {
        this.siteClose = false;
      }
    }
  },
  mounted() {
    this.showSyncWanPan = false;
    // 获取cookies拿到token
    var token = this.getCookie("BailunToken");
    this.isTest=false;
    if(this.isTest)
    {
         token =
      "Bearer%20eyJhbGciOiJSUzI1NiIsImtpZCI6IjQ1ZmMzZDYzYjRmNGM5YjAzMWVhNjQ0MzhhNTE1NmM3IiwidHlwIjoiSldUIn0.eyJuYmYiOjE2MTAxNzMxNTAsImV4cCI6MT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Gqkmc7fnbF79ni4YtvxgYhQHAl-v9BNJF3OtQKXnGtGSaUC8rMTxzg";
    }else{
      token = token.replace("Bearer%20", "").replace("Bearer ", "");
    }
    if (token) {
      // 有值
      const jwt = require("jsonwebtoken");
      const wxUserid = this.isTest?"xiongyuwen":jwt.decode(token).WxUserId;
      // 更加微信用户id获取对应得用户信息并返回
      axios
        .get(`https://discuz.bailuntec.com/api/login?useid=${wxUserid}`)
        // .get(`http://discuz.bailuntec.com/api/login?useid=chenqi`)
        .then(res => {
          if (res.data.data.relationships.users.data.id) {
            localStorage.setItem(
              "user_id",
              res.data.data.relationships.users.data.id
            );
            localStorage.setItem(
              "access_token",
              res.data.data.attributes.access_token
            );
            if (!this.islogin) {
              this.toIndex();
            }
          }
        });
    }
    const { code, preurl } = this.$route.query;
    if (preurl) {
      this.preurl = preurl;
    }
    if (code !== "undefined") {
      this.code = code;
    }
    if (process.client && this.$route.query.q) {
      this.inputVal = this.$route.query.q;
    }
    if (process.client && this.$route.path !== "/site/close") {
      window.setTimeout(this.reloadUserInfo(), 5000);
    }
    if (this.$route.path === "/site/close") {
      this.siteClose = true;
    }
    if (
      this.$route.path === "/user/warning" &&
      this.$store.getters["session/get"]("isLogin")
    ) {
      // 用户审核页面如果有登录态先清除,从注册拓展过来的会有登录态，避免审核中点击回到首页大量报错审核中情况
      this.$store.dispatch("session/logout");
    }
    this.$nextTick(() => {
      const id = localStorage.getItem("user_id");
      this.islogin = id;
    });
    const items = ["/user/supple-mentary"];
    if (items.indexOf(this.$route.path) !== -1) {
      this.hideHeader = true;
    }
  },
  destroyed() {
    if (process.client) {
      window.clearInterval(this.userInfoTimer);
    }
  },
  methods: {
    // 获取cookie
    getCookie: function(cname) {
      const name = `${cname}=`;
      const ca = document.cookie.split(";");
      console.log("获取cookie,现在循环");
      for (let i = 0; i < ca.length; i++) {
        let c = ca[i];
        console.log(c);
        while (c.charAt(0) == " ") c = c.substring(1);
        if (c.indexOf(name) != -1) {
          return c.substring(name.length, c.length);
        }
      }
      return "";
    },
    SyncWanPan() {
      // alert('开始授权')
      // this.getCode();
      this.showSyncWanPanloading = true;
      axios
        .get(`${config.WEI_PAN_URL}/weipan/ProcessWeiPanWorker`)
        .then(res => {
          if (res.data.statusCode == 200) {
            this.$message.success(res.data.result);
          } else {
            this.$message.err(res.data.result);
          }
          this.showSyncWanPanloading = false;
        });
    },
    // 退出
    logout() {
      this.$store.dispatch("session/logout").then(() => {
        location.href = `${this.$route.fullPath}`;
      });
    },
    // 轮询获取用户信息，用于判断是否有新消息
    reloadUserInfo() {
      if (this.userInfo && this.userInfo.id) {
        window.clearInterval(this.userInfoTimer);
        this.userInfoTimer = window.setInterval(this.getUserInfo, 60000);
      }
    },
    // 从store里面获取用户信息
    async getUserInfo() {
      try {
        await this.$store.dispatch("user/getUserInfo", this.userId);
      } catch (err) {
        console.log("header getUserInfo err", err);
      }
    },
    // 跳往注册页面
    // register() {
    //   this.toregister(this.code);
    // },
    // 跳转登录页面
    login() {
      this.headerTologin();
    },
    // 跳转搜索页面
    onClickSearch() {
      if (this.inputVal) {
        this.$router.push(`/site/search?q=${this.inputVal}`);
      }
    },
    // 跳转首页
    toIndex() {
      this.$router.push("/category");
    },
    knowledge() {
      this.$router.push(`/knowledge`);
    }
  }
};
</script>
<style lang="scss" scoped>
@import "@/assets/css/variable/color.scss";
.header {
  height: 65px;
  background: rgba(255, 255, 255, 1);
  box-shadow: 0px 3px 5px rgba(0, 0, 0, 0.03);
  opacity: 1;
  @media screen and (max-width: 1005px) {
    height: 50px;
    width: 100%;
    min-width: 768px;
  }
  .header-container {
    margin: 0 auto;
    width: 1005px;
    height: 65px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .flex {
      display: flex;
      align-items: center;
    }
    @media screen and (max-width: 1005px) {
      width: 100%;
      min-width: 768px;
      padding: 0 14px;
      height: 50px;
    }
    .logo {
      max-width: 280px;
      max-height: 35px;
      height: 24px;
      cursor: pointer;
      display: flex;
      @media screen and (max-width: 1005px) {
        max-width: 135px;
        max-height: 30px;
      }
      img {
        height: 24px;
        // width: 100%;
      }
    }
    .knowledge {
      margin-left: 5px;
      cursor: pointer;
    }
    .knowledgeImg {
      height: 25px;
      margin-top: 6px;
    }
    .logo2 {
      background-position: center center;
      background-size: contain;
      background-repeat: no-repeat;
      height: 24px;
      width: 100%;
      max-width: 100%;
      cursor: pointer;
    }
    ::v-deep.h-search {
      margin-left: 30px;
      width: 298px;
      height: 36px;
      @media screen and (max-width: 1005px) {
        width: 180px;
        height: 30px;
      }
      .el-input__inner {
        border-radius: 2px;
        color: #000;
        border-color: rgba(237, 237, 237, 0.66);
        @media screen and (max-width: 1005px) {
          height: 30px;
          line-height: 30px;
        }
      }
      .el-input__icon {
        width: 14px;
        margin-right: 8px;
      }
      .el-input__suffix {
        line-height: 36px;
        @media screen and (max-width: 1005px) {
          line-height: 30px;
        }
      }
    }

    .h-button {
      width: 60px;
      height: 35px;
      border-color: $color-blue-base;
      font-size: 14px;
      border-radius: 2px;
      &.h-button1 {
        background: #ffffff;
        color: $color-blue-base;
        transition: all 0.2s ease-in-out;
        &:hover {
          background: #e5f2ff;
          border: 1px solid #d4e6fc;
        }
      }
      &.h-button2 {
        color: #fff;
        background: $color-blue-base;
        color: #fff;
        &:hover {
          background: $color-blue-deep;
          border-color: $color-blue-deep;
        }
      }
    }
    .menu-item {
      color: #6d6d6d;
      font-size: 16px;
      margin-left: 30px;
      cursor: pointer;
      @media screen and (max-width: 1005px) {
        font-size: 14px;
        margin-left: 15px;
      }
      &:hover {
        color: $color-blue-base;
      }
    }
    .user-name {
      margin-left: 10px;
      max-width: 120px;
    }
    .notice-btn {
      line-height: 1;
      .flex {
        display: flex;
        align-items: center;
      }
      .unread-notice {
        font-size: 12px;
        color: #fff;
        background: #ff0000;
        padding: 1px 6px;
        border-radius: 6px;
        margin-left: 2px;
      }
    }
    .avatar {
      width: 35px;
      height: 35px;
      border-radius: 50%;
      vertical-align: bottom;
      display: inline-block !important;
    }
  }
}
.isFixed {
  position: -webkit-sticky;
  position: sticky;
  top: 0;
  width: 100%;
  z-index: 8;
}
.search-logo {
  width: 14px;
  height: 14px;
  display: inline-block;
  vertical-align: middle;
}
</style>
