<template>
  <div class="main-nav">
    <header class="nav-header">
      <!-- 左侧 nav -->
      <div class="leftNav">
        <a class="logoBox" href="/entry">
          <el-button type="info">&lt; 返回</el-button>
        </a>
        <ul class="nav-menu">
          <!-- menu -->
          <template v-for="m in menuLeft">
            <li :key="m.$index" class="menu-item">
              <a
                :class="perUrl === m.link.split('/')[1] ? 'navColor' : ''"
                v-t="m.t"
                :href="m.link || 'javascript:'"
              ></a>
            </li>
          </template>
        </ul>
      </div>
      <!-- 右侧 nav -->
      <div class="rightNav" :style="{width: rightNavWidth}">
        <ul class="nav-menu">
          <!-- menu -->
          <template v-for="m in menuRight">
            <li
              :key="m.$index"
              class="menu-item"
              v-if="userData != '' && userData != undefined"
            >
              <a
                :class="perUrl === m.link.split('/')[1] ? 'navColor' : ''"
                v-t="m.t"
                :href="m.link || 'javascript:'"
              ></a>
            </li>
          </template>

          <!-- 汇率 -->
          <li class="menu-item no-padding">
            <el-dropdown
              @command="switchRate"
              trigger="click"
              class="menu-item-inner nav-dropdown nav-dropdown-i18n"
            >
              <span class="dropdown-link">
                <span v-text="$t(exRate.current.name)"></span>
                <i class="el-icon-arrow-down el-icon--right"></i>
              </span>
              <el-dropdown-menu
                :appendToBody="false"
                :visibleArrow="false"
                :boundariesPadding="0"
                slot="dropdown"
                class="exRateDropdown"
              >
                <el-dropdown-item
                  v-for="items in exRate.list"
                  :key="items.id"
                  :command="items.id"
                >
                  <div
                    class="dropdown-menu-item-inner"
                    :class="[{'is-active': exRate.current === items}]"
                  >
                    <i
                      class="menu-item-icon el-icon-check"
                      v-if="exRate.current === items"
                    ></i>
                    <span class="menu-item-text">{{ $t(items.name) }}</span>
                  </div>
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </li>

          <!-- i18n menu -->
          <li class="menu-item no-padding">
            <el-dropdown
              @command="switchLang"
              trigger="click"
              class="menu-item-inner nav-dropdown nav-dropdown-i18n"
            >
              <span class="dropdown-link">
                <span v-text="lang.current.name"></span>
                <i class="el-icon-arrow-down el-icon--right"></i>
              </span>
              <el-dropdown-menu
                :appendToBody="false"
                :visibleArrow="false"
                :boundariesPadding="0"
                slot="dropdown"
                class="langDropdown"
              >
                <el-dropdown-item
                  v-for="item in lang.list"
                  :key="item.lang"
                  :command="item.lang"
                >
                  <div
                    class="dropdown-menu-item-inner"
                    :class="[{'is-active': lang.current === item}]"
                  >
                    <i
                      class="menu-item-icon el-icon-check"
                      v-if="lang.current === item"
                    ></i>
                    <span class="menu-item-text">{{ item.name }}</span>
                  </div>
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </li>

          <!-- user 登录 -->
          <li class="menu-item" v-if="userData == '' || userData == undefined">
            <a :href="'/login?perUrl=' + perUrl" key="login">
              <div class="login">{{ $t('nav.menu_signIn') }}</div>
            </a>
            <!-- <a v-else href="/personal?perUrl=personal" key="personal">
              <div class="userAvatar">
                <img v-if="headerImg == null" src="../../assets/logo.png" />
                <img v-else :src="headerImg" />
              </div>
            </a>
          <a v-if="userData != '' && userData != undefined" @click="exit">
            {{ $t('nav.menu_logOut') }}
            </a>-->
          </li>

          <!-- 注册按钮 -->
          <li class="menu-item" v-if="userData == '' || userData == undefined">
            <a
              :href="'/login?perUrl=' + perUrl + '#/signUp'"
              class="registered"
            >
              <span>{{ $t('login.signUp.btn') }}</span>
            </a>
          </li>
          <!-- 用户手机号码 -->
          <li class="menu-item" v-if="userData != '' && userData != undefined">
            <el-dropdown
              @command="switchPage"
              trigger="click"
              class="menu-item-inner nav-dropdown"
            >
              <span class="dropdown-link">
                <span>
                  {{
                    userData.mobilePhone.replace(
                      /^(\d{3})\d*(\d{4})$/,
                      '$1****$2'
                    )
                  }}
                </span>
                <i class="el-icon-arrow-down el-icon--right"></i>
              </span>
              <el-dropdown-menu
                :appendToBody="false"
                :visibleArrow="false"
                :boundariesPadding="0"
                slot="dropdown"
                class="userDropdown"
              >
                <el-dropdown-item
                  v-for="item in personal.list"
                  :key="item.id"
                  :command="item.id"
                  :class="[{logOut: item.id == 'out'}]"
                >
                  <div
                    class="dropdown-menu-item-inner"
                    :class="[{'is-active': personal.current === item}]"
                  >
                    <!-- <i
                    class="menu-item-icon el-icon-check"
                    v-if="personal.current === item"
                    ></i>-->
                    <span class="menu-item-text">{{ item.name }}</span>
                  </div>
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </li>
        </ul>
      </div>
    </header>
    <div
      class="counting"
      @click="showCounting = !showCounting"
      :style="{width: showCounting ? '150px' : '30px'}"
      v-if="reqType == 0"
    >
      <p>
        考试进行中
        <i class="el-icon-d-arrow-right" v-if="!showCounting"></i>
        <i class="el-icon-d-arrow-left" v-else></i>
      </p>
      <br />
      <p v-if="showCounting">
        <span>{{ hour }}</span
        >&nbsp;:&nbsp; <span>{{ mins }}</span
        >&nbsp;:&nbsp;
        <span>{{ sec }}</span>
      </p>
    </div>
  </div>
</template>

<script>
import {getCurrentLanguage} from '@/common/i18n';
import {getExchangeRateCookie, setExchangeRateCookie} from '@/utils/auth';
import {logOut} from '@/api/user';
import {FILE_URL} from '@/api/app';
import {submit, reStart} from '@/api/yyyf';
import {signUp, signIn} from '@/api/user';
import {yyyfUrl} from '@/api/app.js';

const Menu = {
  icon: [{t: 'nav.menu_name', link: '/'}],
  left: [
    {t: 'nav.menu_home', link: '/'},
    {t: 'nav.menu_markets', link: '/price'},
    {t: 'nav.menu_exchange', link: '/trade'},
    {t: 'nav.menu_OTC', link: '/exchange'},
    {t: 'footer.white', link: '/white'},
  ],
  right: [
    {t: 'nav.menu_fall', link: '/announce'},
    {t: 'nav.menu_orders', link: '/entrust'},
    {t: 'nav.menu_dingdan', link: '/order'},
    {t: 'nav.menu_funds', link: '/balances'},
  ],
};

export default {
  name: 'nav-header',
  props: {
    border: {
      type: Boolean,
      default: true,
    },
    borderStyle: {
      type: String,
      default: 'default',
      validator: val => ['default', 'full'].indexOf(val) > -1,
    },
  },

  data() {
    return {
      menuIcon: Menu.icon,
      menuLeft: Menu.left,
      menuRight: Menu.right,
      lang: {
        current: {lang: 'zh-CN', name: '简体中文'},
        list: [
          // {lang: 'zh-HK', name: '繁體中文'},
          {lang: 'zh-CN', name: this.$t('nav.menu_china')},
          {lang: 'en', name: 'English'},
        ],
      },
      exRate: {
        current: {id: 'USD', name: 'nav.menu_USD'},
        list: [
          {id: 'HKD', name: 'nav.menu_HK'},
          {id: 'USD', name: 'nav.menu_USD'},
          {id: 'CNY', name: 'nav.menu_CNY'},
          // {id: 'EUR', name: 'nav.menu_EUR'},
        ],
      },
      personal: {
        current: {id: 'profile', name: this.$t('personal.leftNav.profile')},
        list: [
          {id: 'profile', name: this.$t('personal.leftNav.profile')},
          {id: 'security', name: this.$t('personal.leftNav.security')},
          {id: 'manner', name: this.$t('personal.leftNav.manner')},
          {id: 'prove', name: this.$t('personal.leftNav.prove')},
          /* {id: 'out', name: this.$t('nav.menu_logOut')},*/
        ],
      },
      userData: '',
      headerImg: '',
      perUrl: 'personal',
      file: '',
      showCounting: true,
      //0 考试 1 练习 2 不计分
      reqType: 2,
      //剩余时间
      remainingTime: 0,
      //防止重复提交
      isSubmit: false,
      hour: 0,
      mins: 0,
      sec: 0,
      setIntervalInt: 0,
    };
  },

  computed: {
    rightNavWidth: function() {
      if (this.userData != '' && this.userData != undefined) {
        return '42%';
      } else {
        return '18%';
      }
    },
  },

  created() {
    let yyyfToken = localStorage.getItem('yyyfToken');
    this.isSubmit = localStorage.getItem('isSubmit') == 'true' ? true : false;
    if (yyyfToken == '' || yyyfToken == undefined) {
      this.$alert('未从以渔有方登录，点击确定返回登录', '提示', {
        type: 'error',
        showClose: false,
        confirmButtonText: '确定',
        confirmButtonClass: 'btn-self-style',
        callback: () => {
          window.location.href = yyyfUrl;
        },
      });
    } else {
      //请求类型
      this.reqType = localStorage.getItem('reqType');
      //如果考试
      if (this.reqType == 0) {
        //获取考试剩余时间
        this.remainingTime = localStorage.getItem('remainingTime');
        //启动倒计时
        this.setIntervalInt = setInterval(this.showTime, 1000);
      }
      this.file = FILE_URL;
      this.perUrl = window.location.pathname.split('/')[1];
      // console.log(this.perUrl);

      // this.userData = Cookie.get('userData');
      this.userData = localStorage.getItem('userData');

      if (this.userData != '' && this.userData != undefined) {
        this.userData = JSON.parse(localStorage.getItem('userData'));
        // console.log(this.userData);
        if (this.userData.avatar != null) {
          this.headerImg = this.file + this.userData.avatar;
        } else {
          this.headerImg = this.userData.avatar;
        }
      }
      // console.log(this.headerImg);

      const currentLang = getCurrentLanguage();
      for (let item of this.lang.list) {
        if (item.lang === currentLang) {
          this.lang.current = item;
          break;
        }
      }
      const currentrate = getExchangeRateCookie();
      for (let item of this.exRate.list) {
        if (item.id === currentrate) {
          this.exRate.current = item;
          // setExchangeRateCookie(currentrate);
          break;
        }
      }
    }
  },

  methods: {
    showTime: function() {
      let remainingTime = this.remainingTime;
      remainingTime -= 1;
      localStorage.setItem('remainingTime', remainingTime);
      this.remainingTime = remainingTime;
      let h = 0;
      let m = 0;
      let s = 0;
      if (remainingTime > 0) {
        h = Math.floor(remainingTime / 60 / 60);
        m = Math.floor((remainingTime / 60) % 60);
        s = Math.floor(remainingTime % 60);
      }
      if (h < 10) {
        this.hour = this.format(h, 2);
      } else {
        this.hour = h;
      }
      this.mins = this.format(m, 2);
      this.sec = this.format(s, 2);
      if (h <= 0 && m <= 0 && s <= 0) {
        if (!this.isSubmit)
          this.$message.warning('考试时间到,系统将自动提交试卷');
        this.submitExam();
      }
    },
    format: function(num, n) {
      return (Array(n).join(0) + num).slice(-n);
    },
    sign(params) {
      signUp(params).then(res => {
        if (res.data.code === 200) {
          this.login({
            tel: params.tel,
            password: params.password,
          });
        } else {
          this.$message.warning(res.data.msg);
          this.isSubmit = false;
        }
      });
    },
    login(params) {
      signIn(params).then(res => {
        // console.log(res);
        if (res.data.code === 200) {
          //判断是否保存自动登录
          // if( this.checked === true ){
          //   Cookie.set('phoneNum',num)
          //   Cookie.set('password',pass)
          // }
          //保存登录的token到cookie
          // Cookie.set('token', res.data.data.token);
          localStorage.setItem('token', res.data.data.token);
          //重复提交标识
          localStorage.setItem('isSubmit', JSON.stringify(false));
          //保存登录的用户信息到cookie
          // Cookie.set('userData', res.data.data);
          localStorage.setItem('userData', JSON.stringify(res.data.data));
          // console.log(JSON.parse(localStorage.getItem('userData')));

          // 保存userID的信息到cookie
          // Cookie.set('userID', res.data.data.id);
          localStorage.setItem('userID', res.data.data.id);

          // 保存邀请码信息
          localStorage.setItem('invitationCode', res.data.data.invitationCode);
          this.isSubmit = false;
          location.href = '/entry';
        } else {
          this.$message.warning(res.data.msg);
          this.isSubmit = false;
        }
      });
    },
    closeWindow: function() {
      if (
        navigator.userAgent.indexOf('Firefox') != -1 ||
        navigator.userAgent.indexOf('Chrome') != -1
      ) {
        window.location.href = 'about:blank';
        window.close();
      } else {
        window.opener = null;
        window.open('', '_self');
        window.close();
      }
    },
    switchLang(command) {
      if (!command) {
        return;
      }
      let u = new URL(location.href);
      u.searchParams.set('lang', command);
      location.href = u.href;
    },
    switchRate(command) {
      if (!command) {
        return;
      }
      // let currentrate = getExchangeRateCookie();
      // console.log('1111'+ currentrate);
      // for (let item of this.exRate.list) {
      //   if (item.id === currentrate) {
      //     setExchangeRateCookie(command);
      //     this.exRate.current = item;
      //     break;
      //   }
      // };
      setExchangeRateCookie(command);
      window.location.reload();
      // console.log('1111'+ setExchangeRateCookie(command));
    },
    switchPage(command) {
      if (!command) {
        return;
      }
      if (command === 'out') {
        this.exit();
      } else {
        location.href = '/personal?perUrl=' + this.perUrl + '#/' + command;
      }
    },
    exit(params) {
      logOut().then(res => {
        if (res.data.code === 200 || res.data.code === 202) {
          // Cookie.set('userData', '');
          localStorage.setItem('userData', '');
          localStorage.removeItem('userpass');
          localStorage.removeItem('userdate');
          localStorage.removeItem('nowPassNOValue');
          if (params == undefined) {
            //window.location.href = '/';
            this.closeWindow();
          }

          // let pathName = window.location.pathname.split('/')[1];
          // console.log(pathName);
          //判断是否从个人中心页面退出登录
          // if (pathName === 'personal') {
          //   window.location.href = '/login';
          // } else {
          //   window.location.href = this.perUrl;
          // }
        } else {
          this.$message.warning(res.data.msg);
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
@import '../../common/style/base';
// .main-nav{
//   padding: 0 20px;
// }
.nav-header {
  max-width: 100%;
  min-width: 1180px;
  height: 65px;
  line-height: 65px;
  background-color: #23252b;
  display: flex;
  flex-wrap: nowrap;
  justify-content: space-between;
  // padding: 0 $cec-header-padding;

  $local-menu-text-color: #6880a0;

  .logoBox {
    display: flex;
    align-items: center;
    // margin-left: 12.6%;
    margin-right: 7.9%;

    img {
      width: 45px;
      height: 45px;
    }
  }

  h2 {
    margin: 0;
    padding: 0;
  }

  .mainTitle {
    color: #fff;
    font-size: 28px;
    font-weight: normal;
    margin-left: 9px;
  }

  .leftNav {
    width: 45%;
    flex: 1;
    display: flex;
    margin-left: 2%;

    .nav-menu {
      width: 60%;
    }

    .menu-item {
      margin-right: 3%;
    }
  }

  .centerNav {
    //flex: 1;
    width: 230px;

    .el-button {
      color: #ffffff;
    }
  }

  .rightNav {
    width: 10%;
    margin-right: 2%;
    // width: 350px;
    // display: flex;
    // flex-direction: row-reverse;
    .nav-menu {
      // width: 350px;
      //     display: flex;
      // flex-direction: row-reverse;
    }
  }

  .nav-menu {
    display: flex;
    flex-wrap: wrap;
    height: 100%;
    justify-content: space-between;

    .menu-item {
      display: flex;
      align-items: center;

      font-size: 14px;
      color: $local-menu-text-color;

      &.no-padding {
        padding: 0;
      }

      > a {
        // color: $local-menu-text-color;
        color: #545663;

        &.is-active {
          color: white;
        }
      }

      span {
        color: #545663;
      }
    }

    /* 对 直接子代 a ，和 .menu-item-inner 进行定位布局 */
    .menu-item > a,
    .menu-item-inner {
      display: flex;
      align-items: center;

      box-sizing: border-box;
      // padding: 0 10px;
    }
  }

  .nav-menuRight {
    display: flex;
    flex-wrap: wrap;
    height: 100%;
    // justify-content: space-between;
    .menu-item {
      display: flex;
      align-items: center;
      font-size: 14px;
      color: $local-menu-text-color;

      &.no-padding {
        padding: 0;
      }

      > a {
        // color: $local-menu-text-color;
        color: #545663;

        &.is-active {
          color: white;
        }
      }

      span {
        color: #545663;
      }
    }

    /* 对 直接子代 a ，和 .menu-item-inner 进行定位布局 */
    .menu-item > a,
    .menu-item-inner {
      display: flex;
      align-items: center;

      box-sizing: border-box;
      // padding: 0 10px;
    }
  }

  .navColor {
    color: #e8494a !important;
    position: relative;

    &::after {
      content: '';
      width: 100%;
      height: 3px;
      background-color: #e8494a;
      position: absolute;
      bottom: 1%;
      left: 0;
    }
  }

  .nav-menu {
    /* logo area */
    .nav-logo-area {
      padding: 0;

      .logo_text {
        font-size: 26px;
        color: #ffffff;
      }
    }
  }

  @at-root {
    &_bordered {
      border-bottom: 1px solid #1f3e5a;
    }
  }

  /* 导航栏 下拉菜单 */
  .nav-dropdown {
    &.el-dropdown {
      justify-content: center;
    }

    .dropdown-link {
      cursor: pointer;
      color: $local-menu-text-color;
    }

    .el-dropdown-menu {
      background-color: #fff;
      border: none;
      border-radius: 4px;
      margin: 0;
      padding: 0;
      top: 55px !important;

      &__item {
        height: 42px;
        line-height: 42px;

        &:not(.is-disabled):hover {
          background-color: #d3dae2;
        }

        .is-active {
          color: #666 !important;
        }
      }

      .dropdown-menu-item-inner {
        color: #666;
      }
    }

    .exRateDropdown {
      left: -100% !important;
    }

    .langDropdown {
      left: -50% !important;
    }

    .userDropdown {
      left: -5% !important;
      width: 110px;

      .el-dropdown-menu__item {
        padding: 0;
      }

      .dropdown-menu-item-inner {
        text-align: center;
      }
    }
  }

  .logOut {
    border-top: 1px solid rgba(237, 238, 243, 1);
    height: 50px !important;
    line-height: 50px !important;
  }

  .nav-dropdown-i18n {
    height: 100%;

    .dropdown-menu-item-inner {
      width: 135 - 2 * 20px; // 20px 为 el-dropdown-item padding
      color: $local-menu-text-color;
      padding-left: 25px;
      box-sizing: border-box;
      position: relative;

      &.is-active {
        color: white;
      }
    }

    .menu-item-icon {
      position: absolute;
      left: 0;
      line-height: 42px;
      font-size: 1.2em;
      font-weight: bold;
      color: $cec-color-text-regular;
    }
  }

  .registered {
    width: 70px;
    height: 28px;
    background-color: #e8494a;
    border-radius: 14px;
    font-size: 14px;
    padding: 0;
    border-color: #3e5173;
    transition: all 0.2s linear;
    cursor: pointer;
    display: flex;
    justify-content: center;
    align-items: center;

    span {
      color: #fff !important;
    }

    &:hover {
      background-color: #fff;

      span {
        color: #e8494a !important;
      }
    }
  }

  // .userAvatar {
  //   width: 40px;
  //   height: 40px;
  //   border-radius: 40px;
  //   overflow: hidden;
  //   display: flex;
  //   align-items: center;
  //   justify-content: center;
  //   background-color: #fff;
  //   img {
  //     width: 100%;
  //   }
  // }
}

.main-nav {
  .counting {
    position: fixed;
    top: 50%;
    left: 0;
    transform: translateY(-50%);
    width: 150px;
    background: #2b2c35;
    border: 1px solid rgba(71, 71, 71, 0.1);
    border-radius: 4px 4px 4px 4px;
    color: #fff;
    display: flex;
    flex-direction: column;
    justify-content: center;
    height: 200px;
    z-index: 999;
    cursor: pointer;

    p {
      width: 100%;
      text-align: center;
    }
  }
}

.btn-self-style {
  background: #f56c6c !important;
  color: #fff !important;
}
</style>
