<template>
  <div class="navbar-wrap">
    <el-menu class="navbar" :class="[isFloor && 'tabs-box']" mode="horizontal" background-color="#fff">
      <div class="navbar-left">
        <hamburger class="hamburger-container" :toggleClick="toggleSideBar" :isActive="sidebar.opened"></hamburger>
        <!--        <breadcrumb class="breadcrumb-container"></breadcrumb>-->
        <!-- <tags-view></tags-view> -->
        <div class="menu_cards">
          <div class="menu_card">
            <span class="time">时间:{{ times }}</span>
            <!-- <div class="dropdown shrink-0">
              <icon-calendar />
            </div>
            <div class="dropdown shrink-0">
             <icon-edit />
            </div>
            <div class="dropdown shrink-0">
              <icon-chat-notification />
            </div> -->
            <!-- <div class="dropdown shrink-0">
              <div class="relative">
                  <input
                      type="text"
                      class="form-input ltr:pl-9 rtl:pr-9 ltr:sm:pr-4 rtl:sm:pl-4 ltr:pr-9 rtl:pl-9 peer sm:bg-transparent bg-gray-100 placeholder:tracking-widest"
                      placeholder="Search..."
                  />
                  <button type="button" class="absolute w-9 h-9 inset-0 ltr:right-auto rtl:left-auto appearance-none peer-focus:text-primary">
                      <icon-search class="mx-auto" />
                  </button>
                  <button
                      type="button"
                      class="hover:opacity-80 sm:hidden block absolute top-1/2 -translate-y-1/2 ltr:right-2 rtl:left-2"
                      @click="search = false"
                  >
                      <icon-x-circle />
                  </button>
              </div>
            </div> -->
          </div>
          <div class="menu_card">
            <!-- <div class="dropdown shrink-0">
              <img src="@/assets/img/sun.svg" alt="">
            </div>
            <div class="dropdown shrink-0">
              <img src="@/assets/img/lang.svg" alt="">
            </div>
            <div class="dropdown shrink-0">
              <img src="@/assets/img/massage.svg" alt="">
            </div>
            <div class="dropdown shrink-0">
              <img src="@/assets/img/ideo.svg" alt="">
            </div> -->
          </div>
        </div>
      </div>

      <div class="right-menu">
        <!--        <el-tooltip effect="dark" content="全屏" placement="bottom">-->
        <!--          <screenfull class="screenfull right-menu-item"></screenfull>-->
        <!--        </el-tooltip>-->
        <div>
          当前登录人:<span>{{nickname}}</span>
        </div>
        <el-dropdown class="avatar-container right-menu-item" trigger="click">
          <div class="avatar-wrapper">
            <div class="user-name">
              <span v-if="face==''"> {{ user.username[0] }}</span>
              <img v-else :src="face" alt="" width="40px">
            </div>
            <i class="el-icon-caret-bottom"></i>
          </div>

          <el-dropdown-menu slot="dropdown">
            <router-link to="/">
              <el-dropdown-item> 首页 </el-dropdown-item>
            </router-link>
            <span @click="changePersonal">
              <el-dropdown-item>个人信息</el-dropdown-item>
            </span>
            <span @click="changePassword">
              <el-dropdown-item>修改密码</el-dropdown-item>
            </span>
            <span @click="logout">
              <el-dropdown-item divided>退出登录</el-dropdown-item>
            </span>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
    </el-menu>
    <el-dialog title="修改密码" :visible.sync="dialogVisible" width="500px" append-to-body :close-on-click-modal="false"
      :close-on-press-escape="false">
      <el-form :model="form" :rules="formRules" ref="form" label-width="100px">
        <el-form-item label="原密码" prop="old_passwprd">
          <el-input v-model="form.old_passwprd" placeholder="不修改则不填"></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="password">
          <el-input type="password" autocompete="off" v-model="form.password" placeholder="不修改则不填"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="rep_password">
          <el-input type="password" autocompete="off" v-model="form.rep_password" placeholder="不修改则不填"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="个人信息" :visible.sync="PersonalVisible" width="500px" append-to-body :close-on-click-modal="false"
      :close-on-press-escape="false">
      <el-form :model="PersonalForm" :rules="PersonalRules" ref="Personalform" label-width="100px">
        <el-form-item label="昵称:" prop="nickname">
          <el-input v-model="PersonalForm.nickname" placeholder="请输入昵称"></el-input>
        </el-form-item>
        <el-form-item label="联系方式:" prop="phone">
          <el-input v-model="PersonalForm.phone" placeholder="请输入联系方式"></el-input>
        </el-form-item>
        <el-form-item label="邮箱:" prop="email">
          <el-input v-model="PersonalForm.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="头像:" prop="face">
          <el-upload class="avatar-uploader" :action="MixinUploadApi" :show-file-list="false"
            :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            <img v-if="PersonalForm.face" :src="PersonalForm.face" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="PersonalVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitPersona">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import Breadcrumb from "@/components/Breadcrumb";
import Hamburger from "@/components/Hamburger";
import Screenfull from "@/components/Screenfull";
import LangSelect from "@/components/LangSelect";
import ThemePicker from "@/components/ThemePicker";
import TagsView from "./TagsView";
import IconCalendar from "@/components/icon/icon-calendar.vue";
import IconEdit from "@/components/icon/icon-edit.vue";
import IconChatNotification from "@/components/icon/icon-chat-notification.vue";
import IconSearch from "@/components/icon/icon-search.vue";
import IconXCircle from "@/components/icon/icon-x-circle.vue";
import { RegExp } from "~/ui-utils";
import * as API_Auth from "@/api/auth";
import * as API_Menus from "@/api/menus";
import { asyncRouterMap, constantRouterMap } from "@/router";
import Storage from "@/utils/storage";
export default {
  components: {
    Breadcrumb,
    Hamburger,
    Screenfull,
    LangSelect,
    ThemePicker,
    TagsView,
    IconCalendar,
    IconEdit,
    IconChatNotification,
    IconSearch,
    IconXCircle,
  },
  data() {
    const user = this.MixinClone(this.$store.getters.user);
    return {
      siteType: Storage.getItem("siteType"),
      dialogVisible: false,
      form: {
        old_passwprd: "",
        password: "",
        rep_password: "",
      },
      formRules: {
        old_passwprd: [
          { required: false, message: "请输入原密码！", trigger: "blur" },
        ],
        password: [
          { required: false, message: "请输入新密码！", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              if (value && !RegExp.password.test(value)) {
                callback(new Error("密码应为6-20位英文或数字！"));
              } else {
                callback();
              }
            },
          },
        ],
        rep_password: [
          { required: false, message: "请确认您的新密码！", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              if (value && this.form.password !== value) {
                callback(new Error("两次输入不一致！"));
              } else {
                callback();
              }
            },
          },
        ],
      },
      isFloor: false,
      times: "", //格式化之后的当前时间
      PersonalVisible: false,
      PersonalForm: {
        nickname: '',
        phone: "",
        email: '',
        face: ''
      },
      PersonalRules: {

      },
      nickname:"",
      face:''
    };
  },
  computed: {
    ...mapGetters(["sidebar", "user"]),
  },
  watch: {
    form: {
      handler: function (newVal) {
        const { old_passwprd, password, rep_password } = newVal;
        const required = !!(old_passwprd || password || rep_password);
        this.formRules.old_passwprd[0].required = required;
        this.formRules.password[0].required = required;
        this.formRules.rep_password[0].required = required;
      },
      deep: true,
    },
    dialogVisible: function (newVal) {
      if (!newVal) {
        this.fileList = [];
      }
    },
    $route() {
      if (this.$route.path === "/page/pc-decoration/floor") {
        this.isFloor = true;
      } else {
        this.isFloor = false;
      }
    },
  },
  created() {
    this.getTimes();
  },
  // 在Vue实例销毁前，清除我们的定时器
  beforeDestroy() {
    if (this.times) {
      clearInterval(this.getTimesInterval);
    }
  },
  mounted(){
    API_Auth.getAdministratorDetail(this.$store.getters.user.uid).then(res => {
      this.nickname=res.nickname
      this.face=res.face
    })
  },
  methods: {
    /* 提交个人信息 */
    submitPersona() {
      API_Auth.editAdministrator(this.PersonalForm.uid, this.PersonalForm).then(res => {
        this.$message.success('修改成功!')
        this.PersonalForm = {}
        this.PersonalVisible = false
        API_Auth.getAdministratorDetail(this.$store.getters.user.uid).then(res => {
          res.uid=res.id 
          res.dept_id=res.dept_id
          this.$store.dispatch('updateUserAction', res)
          location.reload();

        })
        //
      })
    },
    handleAvatarSuccess(res, file) {
      this.PersonalForm.face = file.response.url
      // this.reimburForm.file_url = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    /* 修改个人信息 */
    changePersonal() {
      API_Auth.getAdministratorDetail(this.$store.getters.user.uid).then(res => {
        res.uid=res.id 
        res.dept_id=res.dept_id
        this.PersonalForm = res
         this.PersonalVisible = true
      })
     
    },
    getTimes() {
      setInterval(this.getTimesInterval, 1000);
    },
    getTimesInterval: function () {
      let now = new Date();
      let year = now.getFullYear(); // 获取当前时间的年份
      let month = now.getMonth() + 1; // 获取当前时间的月份
      let day = now.getDate(); // 获取当前时间的天数
      let hours = now.getHours(); // 获取当前时间的小时
      let minutes = now.getMinutes(); // 获取当前时间的分数
      let seconds = now.getSeconds(); // 获取当前时间的秒数
      let weekdays = [
        "星期天",
        "星期一",
        "星期二",
        "星期三",
        "星期四",
        "星期五",
        "星期六",
      ];
      let weekday = weekdays[now.getDay()]; // 获取星期几

      // 当小于 10 的时候，在前面加 0
      month = month < 10 ? "0" + month : month;
      day = day < 10 ? "0" + day : day;
      hours = hours < 10 ? "0" + hours : hours;
      minutes = minutes < 10 ? "0" + minutes : minutes;
      seconds = seconds < 10 ? "0" + seconds : seconds;

      // 拼接格式化当前时间
      this.times = `${year}-${month}-${day} ${hours}:${minutes}:${seconds} ${weekday}`;
    },
    // tab(){
    //   document.querySelector('body').classList.add('dark');
    // },
    /** 提交修改密码表单 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          const params = this.MixinClone(this.form);
          if (!params.old_passwprd) {
            delete params.old_passwprd;
            delete params.password;
            delete params.rep_password;
          }
          API_Auth.editUserInfo(params).then(() => {
            this.dialogVisible = false;
            this.$store.dispatch("fedLogoutAction");
            location.reload();
          });
        } else {
          this.$message.error("表单填写有误，请核对！");
        }
      });
    },
    toggleSideBar() {
      this.$store.dispatch("toggleSideBar");
    },
    changePassword() {
      this.dialogVisible = true;
    },
    logout() {
      this.$confirm("确定退出吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$store.dispatch("logoutAction").then(() => {
            const route = this.$router.resolve("/login");
            location.replace(route.href); // 为了重新实例化vue-router对象 避免bug
          });
        })
        .catch(() => { });
    },
  },
};
</script>

<style type="text/scss" lang="scss" scoped>
@import "../../../styles/variables";

.el-dropdown-menu--small .el-dropdown-menu__item {
  min-width: 90px;
}
/deep/.el-menu::after, .el-menu::before {
   display: none;
}
.navbar-wrap {
  // height: 60px;
  position: relative;
  width: calc(100% + 8px);
  left: -8px;
  background-color: $nav_bg !important;
  z-index: 10;
}

/deep/ .el-menu {
  border-bottom: none;
}

.navbar {
  display: flex;
  justify-content: space-between;
  height: 60px;
  border-radius: 0 !important;
  //border-bottom: 1px solid #e9edf0;
  // background-color: $nav_bg !important;
  // border-color: $nav_bg !important;

  &.tabs-box {
    min-width: 1260px;
  }

  .navbar-left {
    float: left;
    display: flex;
    height: 100%;
    align-items: center;
   /*  width: 85%; */
    padding-left: 20px;
  }

  .hamburger-container {
    padding: 0 10px;
  }

  .menu_cards {
    width: 100%;
    display: flex;
    justify-content: space-between;
  }

  .menu_card {
    display: flex;

    .dropdown {
      width: 40px;
      height: 40px;
      margin-left: 8px;
      background-color: rgba(224, 230, 237, 0.4);
      border-radius: 50%;

      img {
        width: 20px;
        height: 20px;
        margin: 10px 10px;
      }
    }

    .time {
      margin-left: 30px;
    }
  }

  .breadcrumb-container {
    float: left;

    /deep/ {
      .el-breadcrumb__separator,
      .el-breadcrumb__item .el-breadcrumb__inner a {
        color: $nav_text !important;
      }

      .el-breadcrumb__item .el-breadcrumb__inner .no-redirect {
        color: $nav_text_active !important;
      }
    }
  }

  .right-menu {
    display: flex;
    align-items: center;
    //float: right;
    height: 100%;
    justify-content: space-between;

    /deep/ svg {
      fill: $nav_text_active !important;
    }

    &:focus {
      outline: none;
    }

    .right-menu-item {
      display: inline-block;
      margin: 0 15px;
    }

    .avatar-container {
      height: 50px;
      margin-right: 30px;
      display: flex;
      align-items: center;

      .switchSites {
        display: flex;
        align-items: center;
        justify-content: center;
        position: relative;
        left: 20px;
        margin-top: 8px;

        .image {
          margin-right: 5px;
        }

        cursor: pointer;
      }

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

        .user-avatar {
          width: 40px;
          height: 40px;
          border-radius: 100%;
        }

        .user-name {
          width: 40px;
          height: 40px;
          border-radius: 50%;
          /* background: #409eff; */
          font-size: 30px;
          line-height: 1.1;
          text-align: center;
          color: #fff;
        }

        .el-icon-caret-bottom {
          position: absolute;
          right: -20px;
          top: 25px;
          font-size: 12px;
        }

        /deep/ .el-icon-caret-bottom {
          color: $nav_text_active !important;
        }
      }
    }
  }
}

/deep/.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
