<template>
  <div class="navbar">
    <hamburger
      :is-active="sidebar.opened"
      class="hamburger-container"
      @toggleClick="toggleSideBar"
    />

    <breadcrumb class="breadcrumb-container" />

    <div class="right-menu">
      <el-dropdown class="avatar-container" trigger="click">
        <div class="avatar-wrapper">
          <img v-if="avatar" :src="avatar" class="user-avatar" />
          <img v-else src="@/assets/imgs/avatar.png" class="user-avatar" />
          <!-- <span
            >欢迎你
            <span v-if="userInfo.nickName || userInfo.username">{{
              "，" + userInfo.nickName || userInfo.username
            }}</span></span
          > -->
          <i class="el-icon-caret-bottom" />
        </div>
        <el-dropdown-menu slot="dropdown" class="user-dropdown">
          <router-link to="/">
            <el-dropdown-item>主页</el-dropdown-item>
          </router-link>
          <el-dropdown-item divided @click.native="handleShowUserInfo">
            <span style="display: block">个人资料</span>
          </el-dropdown-item>
          <el-dropdown-item divided @click.native="handleShowPwd">
            <span style="display: block">修改密码</span>
          </el-dropdown-item>
          <el-dropdown-item divided @click.native="logout">
            <span style="display: block">退出</span>
          </el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
    </div>

    <el-drawer
      :title="isUserInfo ? '个人资料' : '修改密码'"
      :visible.sync="showDrawer"
      direction="rtl"
      :before-close="handleClose"
      append-to-body
      v-loading="loading"
    >
      <!-- <span>{{ isUserInfo ? "个人资料" : "修改密码" }}</span> -->
      <el-form
        ref="userInfoForm"
        v-if="isUserInfo"
        :label-width="labelWidth"
        :rules="userInfoRules"
        :model="userInfoForm"
      >
        <el-form-item label="用户名" prop="username">
          <span v-if="!isEditingUserInfo">{{ userInfo.username }}</span>
          <el-input v-else v-model="userInfoForm.username"></el-input>
        </el-form-item>
        <el-form-item label="昵称" prop="nickName">
          <span v-if="!isEditingUserInfo">{{ userInfo.nickName }}</span>
          <el-input v-else v-model="userInfoForm.nickName"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <span v-if="!isEditingUserInfo">{{ userInfo.phone }}</span>
          <el-input v-else v-model="userInfoForm.phone"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click.native="handleSubmitUserInfo">{{
            isEditingUserInfo ? "保存" : "修改个人信息"
          }}</el-button>
          <el-button
            type="primary"
            @click.native="handleCancelChangeUserInfo"
            v-if="isEditingUserInfo"
            >取消</el-button
          >
        </el-form-item>
      </el-form>
      <el-form
        ref="pwdForm"
        :model="pwdForm"
        :label-width="labelWidth"
        :rules="pwdRules"
        v-else
      >
        <el-form-item label="旧密码" prop="oldPwd">
          <el-input v-model="pwdForm.oldPwd" type="password"></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPwd">
          <el-input v-model="pwdForm.newPwd" type="password"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="checkPass">
          <el-input v-model="pwdForm.checkPass" type="password"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click.native="handleSubmitPwd"
            >保存</el-button
          >
          <el-button type="primary" @click.native="handleCancelChangePwd"
            >取消</el-button
          >
        </el-form-item>
      </el-form>
    </el-drawer>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import Breadcrumb from "@/components/Breadcrumb";
import Hamburger from "@/components/Hamburger";
import { editUserInfo, editUserPwd } from "@/api/user";
import { setUserInfo } from "@/utils/auth";
export default {
  components: {
    Breadcrumb,
    Hamburger,
  },
  computed: {
    ...mapGetters(["sidebar", "avatar", "userInfo"]),
  },
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入新密码"));
      } else {
        var pattern =
          /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\\W_!@#$%^&*`~()-+=]+$)(?![a-z0-9]+$)(?![a-z\\W_!@#$%^&*`~()-+=]+$)(?![0-9\\W_!@#$%^&*`~()-+=]+$)[a-zA-Z0-9\\W_!@#$%^&*`~()-+=]{8,30}$/;
        if (!pattern.test(value)) {
          callback(
            new Error(
              "密码长度至少8位，至少含数字,大写字母,小写字母,特殊符其中三种"
            )
          );
        }
        if (this.pwdForm.checkPass !== "") {
          this.$refs.pwdForm.validateField("checkPass");
        }
        callback();
      }
    };

    var validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.pwdForm.newPwd) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      showDrawer: false,
      isUserInfo: true,
      isEditingUserInfo: false,
      userInfoForm: {},
      loading: false,
      labelWidth: "100px",
      userInfoRules: {
        username: [
          {
            required: true,
            message: "请填写用户名",
            trigger: "blur",
          },
        ],
        nickName: [
          {
            required: true,
            message: "请填写昵称",
            trigger: "blur",
          },
        ],
        phone: [
          {
            required: true,
            message: "请填写手机号",
            trigger: "blur",
          },
        ],
      },
      pwdForm: {
        oldPwd: "",
        newPwd: "",
        checkPass: "",
      },
      pwdRules: {
        oldPwd: [
          { trigger: "blur", required: true, message: "请输入当前密码" },
        ],
        newPwd: [{ validator: validatePass, trigger: "blur", required: true }],
        checkPass: [
          { validator: validatePass2, trigger: "blur", required: true },
        ],
      },
    };
  },
  methods: {
    toggleSideBar() {
      this.$store.dispatch("app/toggleSideBar");
    },
    async logout() {
      let res = await this.$store.dispatch("user/logout");
      this.$router.push(`/login?redirect=${this.$route.fullPath}`);
    },

    handleShowUserInfo() {
      this.showDrawer = true;
      this.isUserInfo = true;
    },

    handleShowPwd() {
      this.showDrawer = true;
      this.isUserInfo = false;
    },

    handleSubmitUserInfo() {
      if (this.isEditingUserInfo) {
        this.$refs.userInfoForm.validate(async (valid) => {
          if (valid) {
            this.loading = true;
            let res = await editUserInfo(this.userInfoForm);
            if (res.code == "0") {
              this.$message.success("修改成功！");
              this.$store.commit("user/SET_USERINFO", this.userInfoForm);
              setUserInfo(this.userInfoForm);
            }
            this.loading = false;
            this.isEditingUserInfo = false;
          }
        });
      } else {
        this.isEditingUserInfo = true;
        this.userInfoForm = JSON.parse(JSON.stringify(this.userInfo));
      }
    },

    handleSubmitPwd() {
      this.$refs.pwdForm.validate(async (valid) => {
        if (valid) {
          const { newPwd, oldPwd } = this.pwdForm;
          const params = {
            newPwd,
            oldPwd,
          };
          let res = await editUserPwd(params);
          if (res.code == "0") {
            this.$message.success("修改成功，请重新登录！");
            this.logout();
          }
        }
      });
    },

    handleCancelChangeUserInfo() {
      this.isEditingUserInfo = false;
      this.$refs.userInfoForm.resetFields();
    },

    handleCancelChangePwd() {
      this.showDrawer = false;
      this.reset();
    },
    reset() {
      this.showDrawer = false;
      this.isUserInfo = true;
      this.isEditingUserInfo = false;
      if (this.$refs.userInfoForm) {
        this.$refs.userInfoForm.resetFields();
      }

      if (this.$refs.pwdForm) {
        this.$refs.pwdForm.resetFields();
      }

      if (this.loading) {
        this.loading = false;
      }
    },

    handleClose(done) {
      done();
      this.reset();
    },
  },
};
</script>

<style lang="scss" scoped>
.navbar {
  height: 50px;
  overflow: hidden;
  position: relative;
  background: #fff;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);

  .hamburger-container {
    line-height: 46px;
    height: 100%;
    float: left;
    cursor: pointer;
    transition: background 0.3s;
    -webkit-tap-highlight-color: transparent;

    &:hover {
      background: rgba(0, 0, 0, 0.025);
    }
  }

  .breadcrumb-container {
    float: left;
  }

  .right-menu {
    float: right;
    height: 100%;
    line-height: 50px;

    &:focus {
      outline: none;
    }

    .right-menu-item {
      display: inline-block;
      padding: 0 8px;
      height: 100%;
      font-size: 18px;
      color: #5a5e66;
      vertical-align: text-bottom;

      &.hover-effect {
        cursor: pointer;
        transition: background 0.3s;

        &:hover {
          background: rgba(0, 0, 0, 0.025);
        }
      }
    }

    .avatar-container {
      margin-right: 30px;

      .avatar-wrapper {
        margin-top: 5px;
        position: relative;

        .user-avatar {
          cursor: pointer;
          width: 40px;
          height: 40px;
          border-radius: 10px;
        }

        .el-icon-caret-bottom {
          cursor: pointer;
          position: absolute;
          right: -20px;
          top: 25px;
          font-size: 12px;
        }
      }
    }
  }
}
::v-deep .el-drawer__body {
  padding: 10px 60px 0 20px;
}
</style>
