<template>
  <div
    :class="{ nav: true, 'header-fixed ': isFixed, 'home-nav': isHome }"
    id="navbar"
  >
    <div class="container">
      <div class="logo-container animate__animated animate__fadeInLeft">
        <img src="@/assets/imgs/home/logo.png" />
      </div>
      <div class="right">
        <div class="tabs animate__animated animate__fadeInUp">
          <div
            class="tab-item"
            :class="{
              activeHome: currentTab.name == item.name && isHome,
              active: currentTab.name == item.name && !isHome,
            }"
            v-for="(item, index) in pages"
            :key="index"
            @click="handleClickTab(item)"
          >
            <!-- <div ></div> -->
            <router-link :to="item.path">{{ item.name }} </router-link>
          </div>
        </div>
        <div class="tools animate__animated animate__fadeInRight">
          <div class="wrapper">
            <el-dropdown trigger="click">
              <el-button round>
                <i class="el-icon-user"></i>
                <i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item
                  v-if="!hasToken"
                  @click.native="handleToLogin"
                  class="operation-item"
                  >登陆
                </el-dropdown-item>
                <el-dropdown-item
                  v-if="hasToken"
                  class="operation-item"
                  @click.native="handleToPersonal"
                >
                  个人中心</el-dropdown-item
                >
                <el-dropdown-item v-if="hasToken" @click.native="handleLogOut">
                  <span>退出</span>
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </div>
        </div>
      </div>
    </div>
    <el-dialog :visible.sync="loginVisible" append-to-body>
      <div slot="title" class="login-title">
        <div
          :class="['title-item', isLoginByUsername ? 'active' : '']"
          @click="handleChangeLoginWay('username')"
        >
          账号登录
        </div>
        <div
          :class="['title-item', isLoginByUsername ? '' : 'active']"
          @click="handleChangeLoginWay('phone')"
        >
          手机号登录
        </div>
        <div class="line"></div>
      </div>
      <div class="login">
        <el-form
          :model="loginForm"
          :label-position="labelPosition"
          ref="loginForm"
          :rules="loginRules"
        >
          <el-form-item :label-width="formLabelWidth" prop="account">
            <el-input
              v-model="loginForm.account"
              autocomplete="off"
              clearable
              :placeholder="isLoginByUsername ? '账号' : '手机号'"
            ></el-input>
          </el-form-item>
          <el-form-item :label-width="formLabelWidth" prop="password">
            <el-input
              v-model="loginForm.password"
              autocomplete="off"
              type="password"
              clearable
              show-password
              placeholder="密码"
            ></el-input>
          </el-form-item>
          <el-form-item :label-width="formLabelWidth">
            <el-row :gutter="10">
              <el-col :span="12">
                <el-form-item prop="captcha">
                  <el-input
                    ref="captcha"
                    v-model="loginForm.captcha"
                    placeholder="请输入验证码"
                    name="captcha"
                    tabindex="3"
                    auto-complete="on"
                    @keyup.enter.native="handleLoginSubmit"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12" class="captcha">
                <img
                  v-if="requestCodeSuccess"
                  :src="captchaImgSrc"
                  @click="handleGetCaptcha"
                />
                <img
                  v-else
                  src="@/assets/404_images/checkcode.png"
                  @click="handleGetCaptcha"
                />
              </el-col>
            </el-row>
          </el-form-item>
        </el-form>
        <div class="opration">
          <el-button
            round
            @click="handleLoginSubmit"
            size="small"
            :loading="loading"
            class="loginBtn"
            >登 陆</el-button
          >
          <div class="register" @click="handleToRegister">注册</div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import { getVerify } from "@/api/user";
export default {
  name: "NavBar",
  computed: {
    ...mapGetters([
      "token",
      "userInfo",
      "curPath",
      "navBarFixed",
      "showLoginDialog",
    ]),
    hasToken() {
      return this.token;
    },
  },
  watch: {
    curPath: {
      handler: function (value) {
        this.isHome = value.name == "home";
        this.currentTab = {
          name: value.name,
          path: value.path,
        };

        if (value.name.indexOf("display") != -1) {
          this.currentTab = {
            name: "展览",
            path: "/display",
          };
        }
        if (value.name.indexOf("culturalRelic") != -1) {
          this.currentTab = {
            name: "文物展",
            path: "/culturalRelic",
          };
        }
        if (value.name.indexOf("museum") != -1) {
          this.currentTab = {
            name: "博物馆",
            path: "/museum",
          };
        }
      },
      immediate: true,
    },
    navBarFixed(value) {
      console.log("navBarFixed", value);
    },
    showLoginDialog(value) {
      this.loginVisible = value;
    },
    loginVisible(value) {
      if (value) {
        this.handleGetCaptcha();
      }
    },
  },
  data() {
    var validateAccout = (rule, value, callback) => {
      if (value === "") {
        let text = this.isLoginByUsername ? "账号" : "手机号";
        callback(new Error("请输入" + text));
      } else {
        if (!this.isLoginByUsername) {
          var pattern = /^((0\d{2,3}-\d{7,8})|(1[3584]\d{9}))$/;
          if (!pattern.test(value)) {
            callback(new Error("请输入合法手机号/电话号"));
          } else {
            callback();
          }
        } else {
          callback();
        }
      }
    };
    return {
      pages: [
        {
          name: "首页",
          path: "/",
        },
        {
          name: "精品展",
          path: "/boutique",
        },
        {
          name: "虚拟展厅",
          path: "/virtual",
        },
        {
          name: "展览",
          path: "/display",
        },
        {
          name: "文物展",
          path: "/culturalRelic",
        },
        {
          name: "博物馆",
          path: "/museum",
        },
      ],
      currentTab: {
        name: "首页",
        path: "/",
      },
      isHome: true,
      isFixed: false,
      offsetTop: 0,
      loginVisible: false,
      loginForm: {
        account: "",
        password: "",
        captcha: "",
      },
      requestCodeSuccess: false,
      captchaImgSrc: "",
      formLabelWidth: "1px",
      labelPosition: "right",
      loading: false,
      loginRules: {
        account: [
          { validator: validateAccout, required: true, trigger: "blur" },
        ],
        password: [{ required: true, trigger: "blur", message: "请输入密码" }],
        captcha: [{ required: true, trigger: "blur", message: "请输入验证码" }],
      },
      isLoginByUsername: true,
    };
  },
  mounted() {
    window.addEventListener("scroll", this.initHeight);
    this.$nextTick(() => {
      this.offsetTop = document.querySelector("#navbar").offsetTop;
    });
  },
  methods: {
    initHeight() {
      let scrollTop =
        window.pageYOffset ||
        document.documentElement.scrollTop ||
        document.body.scrollTop;
      this.isFixed = scrollTop > this.offsetTop ? true : false;
    },

    handleToRegister() {
      this.$router.push("/register?redirect=" + this.$route.fullPath);
      this.handleCloseLogin();
    },

    handleToLogin() {
      this.loginVisible = true;
    },

    handleToPersonal() {
      this.$router.push("/personal");
    },

    async handleLogOut() {
      this.$confirm("是否确定退出?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          await this.$store.dispatch("user/logout");
          let path = this.$route.fullPath;
          if (path.indexOf("/personal") != -1) {
            this.$router.push("/");
          }
          this.$message.success("已成功退出！");
        })
        .catch((err) => {
          console.log();
        });
    },

    handleClickTab(tab) {
      this.currentTab = tab;
    },

    handleLoginSubmit() {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          // debugger
          this.loading = true;
          const { account, password, captcha } = this.loginForm;
          const params = {
            captcha,
            password,
          };
          if (this.isLoginByUsername) {
            params.username = account;
          } else {
            params.phone = account;
          }
          this.$store
            .dispatch("user/login", params)
            .then((res) => {
              if (res.code == "0") {
                this.handleCloseLogin();
                if (this.$route.name !== "home") {
                  this.$router.push({
                    path: this.$route.query.redirect || "/",
                  });
                }
              }
              this.loading = false;
            })
            .catch((err) => {
              console.log(err);
              this.loading = false;
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    handleCloseLogin() {
      this.loginVisible = false;
      this.$refs["loginForm"].resetFields;
    },

    handleGetCaptcha() {
      this.currdatetime = new Date().getTime();
      getVerify()
        .then((res) => {
          this.requestCodeSuccess = true;
          const imgSrc = window.URL.createObjectURL(res);
          this.captchaImgSrc = imgSrc;
        })
        .catch(() => {
          this.requestCodeSuccess = false;
        });
    },

    handleChangeLoginWay(type) {
      this.isLoginByUsername = type === "username";
      let line = document.getElementsByClassName("line")[0];
      if (this.isLoginByUsername) {
        line.style.left = "24px";
      } else {
        line.style.left = "136px";
      }
    },
  },

  destroyed() {
    window.removeEventListener("scroll", this.initHeight);
  },
};
</script>

<style lang="scss" scoped>
.tab-item {
  a {
    color: #fff;
    text-decoration: none;
  }
}

.home-nav {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 9;
  background-color: rgba(#000, 0.25) !important;
}
.header-fixed {
  position: fixed !important;
  background-color: #2069c4 !important;
  z-index: 99;
  top: 0;
}

.nav {
  height: 100px;
  width: 100%;
  transition: all 0.5s ease;
  background-color: #2069c4;
  box-shadow: rgba(0, 0, 0, 0.3) 0 1px 5px 0px;
  .container {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 70px 0 100px;
    overflow: hidden;
    .logo-container {
      width: 380px;
      height: 74px;
    }
    .right {
      display: flex;
      height: 100%;
      align-items: center;

      .tabs {
        display: flex;
        margin-right: 80px;
        min-width: 512px;
        height: 100%;
        .tab-item {
          margin-right: 70px;
          color: #fff;
          display: flex;
          align-items: center;
          font-family: "Alibaba-PuHuiTi";
          position: relative;
          height: 100%;
          text-align: center;

          a {
            font-size: 18px;
            white-space: nowrap;
            transition: all 0.5s ease;
          }

          &:hover {
            a {
              // color: #182f68;
              color: #fff8a3;
              text-shadow: 0 1px 2px #9fafcb, 1px 0px 2px #9fafcb;
            }
          }
          .router-link-exact-active {
            // color: #182f68;
            color: #fff8a3;
            text-shadow: 0 1px 2px #9fafcb, 1px 0px 2px #9fafcb;
          }
        }
      }
    }
  }
}
@keyframes fadeUp {
  from {
    transform: translateY(200);
  }
  to {
    transform: translateY(0);
  }
}

@keyframes fadeLeft {
  from {
    transform: translateX(-1000);
  }
  to {
    transform: translateX(0);
  }
}
::v-deep .tools {
  .el-button {
    background: transparent;
    border-color: #fff;
    color: #fff;
    i {
      font-size: 16px;
    }
  }
}

.el-dropdown-menu {
  background-color: #fff;
  // border: 1px solid #8a919f;
}
.el-dropdown-menu__item {
  background-color: transparent;
  // color: #fff;
  color: #8a919f;
  a {
    text-decoration: none;
    color: #8a919f;
  }
}

.el-dropdown-menu__item:focus,
.el-dropdown-menu__item:not(.is-disabled):hover {
  background-color: #f8f8f8;
  color: #8a919f;
}

.login {
  .title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30px;
    .text {
      font-weight: bold;
      font-size: 24px;
      color: #666;
    }
    .close {
      font-size: 34px;
      cursor: pointer;
      color: #ccc;
    }
  }
  .login-box {
    width: 500px;
    margin: auto;
  }
}
.opration {
  display: flex;
  justify-content: space-between;
  flex-direction: column;
  margin-top: 20px;
  .register {
    display: flex;
    justify-content: center;
    margin-top: 20px;
    font-size: 14px;
    cursor: pointer;
    &:hover {
      color: #2069c4;
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: center;
}

.captcha {
  display: flex;
  justify-content: flex-end;
  img {
    margin-top: 2px;
    height: 40px;
  }
}

::v-deep .loginBtn {
  padding: 16px !important;
  border-radius: 0 !important;
  width: 100%;
  background-color: #2069c4;
  color: #fff;
  font-size: 14px;
  &:hover {
    filter: brightness(0.9) !important;
    background-color: #2069c4;
    color: #fff;
    border: none;
    border-radius: 0 !important;
    padding: 16px !important;
    width: 100%;
    font-size: 14px;
  }
}
::v-deep .el-dialog {
  width: 380px;
  border-radius: 0;
  .el-dialog__body {
    padding: 20px 30px 60px !important;
  }
}

::v-deep .el-input__inner {
  background: #e8f0fe;
  border: none;
}

::v-deep .el-dialog__header {
  padding: 48px 30px 10px !important;
  color: #666 !important;
  font-weight: bold;
}

::v-deep .el-dialog__headerbtn {
  top: 48px !important;
  font-size: 24px;
  right: 30px;
}

.login-title {
  display: flex;
  position: relative;
  .title-item {
    margin-right: 40px;
    cursor: pointer;
    position: relative;
    &:hover {
      color: #2069c4;
    }
  }

  .active {
    color: #2069c4;
  }
  .line {
    width: 18px;
    height: 4px;
    background-color: #2069c4;
    // border-radius: 4px;
    position: absolute;
    left: 24px;
    bottom: -14px;
    transition: all 0.3s ease;
  }
}
</style>
