<template>
  <div class="topcenter">
    <div class="topnav">
      <div class="logo-box">
        <img src="../../assets/logo_white.png">
        {{ $showLogo?'富士行云 · 总部管理平台':'总部管理平台' }}
      </div>
      <div class="left-menu">
        <el-menu mode="horizontal">
          <template v-for="(item, index) in toplist">
            <el-menu-item
              v-if="index < visibleNumber"
              :key="index"
              :index="item.id"
              :class="{ isActive: $store.getters.topnav == item.id }"
              @click="changeTopNav(item.id, item)"
            >
              {{ item.name }}
            </el-menu-item>
          </template>
          <!-- 顶部菜单超出数量折叠 -->
          <el-dropdown
            v-if="toplist.length > visibleNumber"
            index="more"
            :class="{ isActive2: visibleNumber <= navindex }"
            trigger="click"
          >
            <div :class="{ isActive2: visibleNumber <= navindex }">
              更多菜单
              <i class="el-icon-caret-bottom" />
            </div>
            <el-dropdown-menu slot="dropdown">
              <div v-for="(item, index) in toplist" :key="item.id">
                <el-dropdown-item
                  v-if="index >= visibleNumber"
                  :divided="index == visibleNumber ? false : true"
                  @click.native="changeTopNav(item.id, item)"
                >{{
                  item.name
                }}</el-dropdown-item>
              </div>
            </el-dropdown-menu>
          </el-dropdown>
        </el-menu>
      </div>
      <div class="right-menu">
        <template v-if="device !== 'mobile'">
          <!-- <search id="header-search" class="right-menu-item" /> -->

          <!-- <error-log class="errLog-container right-menu-item hover-effect" /> -->
          <!-- <a target="_blank" href="https://bi.wookitech.com/" class="right-menu-item" title="人流统计系统">
         <svg-icon icon-class="personnel" />
       </a> -->
          <!-- <a target="_blank" href="http://smoke.wookitech.com/" class="right-menu-item" title="烟雾感应系统">
         <svg-icon icon-class="smoke" />
       </a>
       <a target="_blank" href="https://manage.wookitech.com/admin/totalData/login.html" class="right-menu-item" title="大数据屏">
         <svg-icon icon-class="detectors" />
       </a>

       <a target="_blank" href="#" class="right-menu-item" title="打印系统">
         <svg-icon icon-class="printing" />
       </a> -->

          <!-- <screenfull id="screenfull" class="right-menu-item hover-effect" /> -->

          <!-- <el-tooltip content="Global Size" effect="dark" placement="bottom">
         <size-select id="size-select" class="right-menu-item hover-effect" />
       </el-tooltip> -->
        </template>

        <el-dropdown
          class="avatar-container right-menu-item hover-effect"
          trigger="click"
        >
          <div class="avatar-wrapper">
            <!-- <img :src="avatar+'?imageView2/1/w/80/h/80'" class="user-avatar"> -->
            <!-- <img src="../../assets/images/topimage.png" class="user-avatar"> -->
            <div style="margin-left: 8px">
              {{ nickname }}
              <i class="el-icon-caret-bottom" />
            </div>
            <!-- <i class="el-icon-caret-bottom" /> -->
          </div>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item
              @click.native="getUserInfo"
            >
              <span style="display:block;">个人信息</span>
            </el-dropdown-item>
            <el-dropdown-item
              divided
              @click.native="resetPassword"
            >
              <span
                style="display:block;"
              >修改密码</span>
            </el-dropdown-item>
            <!-- <router-link to="/">
           <el-dropdown-item>Dashboard</el-dropdown-item>
         </router-link>
         <a target="_blank" href="https://github.com/PanJiaChen/vue-element-admin/">
           <el-dropdown-item>Github</el-dropdown-item>
         </a>
         <a target="_blank" href="https://panjiachen.github.io/vue-element-admin-site/#/">
           <el-dropdown-item>Docs</el-dropdown-item>
         </a> -->
            <el-dropdown-item
              divided
              @click.native="logout"
            ><span
              style="display:block;"
            >退出登录</span></el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
    </div>
    <!-- 修改密码对话框 -->
    <el-dialog
      title="修改密码"
      width="580px"
      height="600px"
      :visible="resetPasswordDialog"
      append-to-body
      :close-on-click-modal="false"
      @close="closeResetPassword"
    >
      <el-form
        ref="resetPasswordForm"
        :model="resetPasswordForm"
        label-width="100px"
        :rules="rules"
      >
        <el-form-item label="原密码：" prop="oldPassword">
          <el-input
            v-model.trim="resetPasswordForm.oldPassword"
            show-password
            type="password"
            clearable
            placeholder="请输入原密码"
          />
        </el-form-item>
        <el-form-item label="密码：" prop="password">
          <el-input
            v-model.trim="resetPasswordForm.password"
            show-password
            type="password"
            clearable
            placeholder="请输入新密码"
            maxlength="16"
          />
          <div class="note">
            6-16位数字、字母、符号，其中数字、字母、符号至少包含两种
          </div>
        </el-form-item>
        <el-form-item label="确认密码：" prop="confirmpassword">
          <el-input
            v-model.trim="resetPasswordForm.confirmpassword"
            show-password
            type="password"
            clearable
            placeholder="请再次输入新密码"
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button
          class="whitebutton"
          @click="closeResetPassword"
        >取消</el-button>
        <el-button
          v-loading="loading"
          type="primary"
          @click="resetPasswordSubmit"
        >确定</el-button>
      </span>
    </el-dialog>

    <!-- 个人信息对话框 -->
    <el-dialog
      title="个人信息"
      class="userinformationdialog"
      width="500px"
      :visible="userInfoDialog"
      append-to-body
      :close-on-click-modal="false"
      @close="closeUserInfoDialog"
    >
      <el-form label-position="right" class="detail-dialog userinformation">
        <el-form-item label="账号：">
          <span>{{ userInformation.username }}</span>
        </el-form-item>
        <el-form-item label="姓名：">
          <span>{{ userInformation.nickname }}</span>
        </el-form-item>
        <el-form-item label="手机号：">
          <span>{{ userInformation.mobile }}</span>
        </el-form-item>
        <el-form-item label="所属组织：">
          <span>{{ userInformation.deptName }}</span>
        </el-form-item>
        <el-form-item label="分配角色：">
          <span>{{ roleNames }}</span>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button
          class="whitebutton"
          @click="closeUserInfoDialog"
        >关 闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import lodash from 'lodash'
import { mapGetters } from 'vuex'
import { getInfo, updatePassword } from '@/apiV2/user'
import secret from '@/utils/secret.js'

export default {
  data() {
    // 检查密码格式
    var checkformat = (rule, value, callback) => {
      // 验证必须包含数字\字母、特殊符号中至少2种元素，且长度在6-16位
      var format = /^(?![0-9]+$)(?![a-zA-Z]+$)(?![`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]]+$)[0-9A-Za-z`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]]{6,16}$/
      if (!format.test(value)) {
        callback(new Error('密码格式不正确'))
      } else {
        if (value == this.resetPasswordForm.oldPassword) {
          callback(new Error('旧密码与新密码不可一致'))
        } else {
          callback()
        }
      }
    }
    // 检查确认密码
    var checkconfirmpassword = (rule, value, callback) => {
      if (value != this.resetPasswordForm.password) {
        callback(new Error('确认新密码不一致'))
      } else {
        callback()
      }
    }
    return {
      nickname: '',
      userInformation: {},
      rolesName: [],
      userInfoDialog: false,
      resetPasswordDialog: false,
      resetPasswordForm: {
        oldPassword: '',
        password: '',
        confirmpassword: ''
      },
      rules: {
        oldPassword: [
          {
            required: true,
            message: '请输入旧密码',
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '请输入新密码', trigger: 'change' },
          {
            min: 5,
            max: 16,
            message: '密码格式不正确',
            trigger: 'change'
          },
          {
            validator: checkformat,
            trigger: 'change'
          }
        ],
        confirmpassword: [
          { required: true, message: '请输入确认密码', trigger: 'change' },
          {
            validator: checkconfirmpassword,
            require: true
          }
        ]
      },
      // 顶部栏初始数
      visibleNumber: 5,
      toplist: this.$store.getters.toplist,
      navindex: ''
    }
  },
  computed: {
    ...mapGetters(['avatar', 'device'])
  },
  watch: {
    'resetPasswordForm.password': function(newValue, oldValue) {
      const regreg = /[^0-9A-Za-z`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]]/g
      if (regreg.test(newValue)) {
        this.resetPasswordForm.password = newValue.replace(regreg, '')
      }
    }
  },
  created() {
    let userInfo = localStorage.getItem('manager-userLogin')
    if (userInfo) {
      userInfo = JSON.parse(userInfo)
      this.nickname = userInfo.nickname
      const that = this
      if (userInfo.updatePasswordMess) {
        this.$notify({
          title: '提示',
          offset: 80,
          dangerouslyUseHTMLString: true,
          message: `<div class="mb-8">${userInfo.updatePasswordMess}</div><div class="text-right color-primary"><a>前去修改</a></div>`,
          onClick: function() {
            that.resetPassword()
            this.close()
          }
        })
      }
    }
  },
  mounted() {
    this.$store.dispatch('dict/dict', this.DICT_CODE.public_cartype)
    var parentId = this.$route.meta.parentId
    if (parentId && typeof parentId != 'undefined') { // 刷新的时候根据当前路由选中顶级菜单
      this.changeTopNav(parentId)
    } else { // 默认进来的时候打开第一个一级菜单下的第一个三级菜单
      this.changeTopNav(this.$store.getters.topnav, this.$store.getters.toplist[0])
    }
    this.$router.beforeEach((to, from, next) => {
      if (to.meta.parentId) {
        this.changeTopNav(to.meta.parentId)
      }
      next()
    })
  },
  beforeMount() {
    window.addEventListener('resize', this.setVisibleNumber)
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.setVisibleNumber)
  },
  methods: {
    // 根据宽度计算设置显示栏数
    setVisibleNumber() {
      const width = document.body.getBoundingClientRect().width / 3
      this.visibleNumber = parseInt(width / 80)
      var thisindex = this.$store.getters.toplist.map((item, index) => {
        if (item.id == this.$store.getters.topnav) {
          return index
        }
      })
      this.navindex = thisindex.filter(item => {
        if (typeof item != 'undefined') {
          return true
        }
      })[0]
    },
    changeTopNav(val, item) {
      this.$store.dispatch('user/changeTopNav', val)
      if (item && item.path != '') {
        this.$router.push(item.path)
      }
      this.setVisibleNumber()
    },
    async logout() {
      this.$store.commit('updateTreeData', [])
      this.$store.commit('CHANGE_CLOUD_CENTER', [])
      await this.$store.dispatch('user/logout')
      this.$router.push(`/login?redirect=${this.$route.fullPath}`)
    },
    // 修改密码
    resetPassword() {
      this.resetPasswordDialog = true
    },
    closeResetPassword() {
      this.resetPasswordDialog = false
      this.resetPasswordForm = {
        oldPassword: '',
        password: '',
        confirmpassword: ''
      }
      this.$refs['resetPasswordForm'].resetFields()
    },
    resetPasswordSubmit() {
      this.$refs['resetPasswordForm'].validate(valid => {
        if (valid) {
          const obj = { ...this.resetPasswordForm }
          obj.oldPassword = secret(obj.oldPassword)
          obj.password = secret(obj.password)
          obj.confirmpassword = secret(obj.confirmpassword)
          updatePassword(obj).then(res => {
            console.log(res)
            if (res.success) {
              this.$message({
                message: '修改成功',
                offset: 60,
                type: 'success'
              })
              this.closeResetPassword()
              this.logout()
            }
          })
        }
      })
    },
    // 个人信息
    async getUserInfo() {
      const res = await getInfo()
      console.log('res', res)
      this.userInformation = lodash.cloneDeep(res.data)
      this.roleNames = this.userInformation.roleNames.join('、')
      this.userInfoDialog = true
    },
    closeUserInfoDialog() {
      this.userInfoDialog = false
    }
  }
}
</script>

<style lang="scss" scoped>
.mobile {
  .logo-box {
    display: none !important;
    > img {
      width: 60px;
      object-fit: cover;
      margin: 0 !important;
    }
  }
  .left-menu {
    font-size: 16px !important;
  }
}
.note {
  color: #a6a6a6;
  line-height: 18px;
  padding-top: 9px;
}
.topcenter {
  height: 200px;
  background: linear-gradient(-90deg, #1c67ff, #5d8bff);
  border-radius: 1px;
  .topnav {
    height: 80px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .logo-box {
      display: flex;
      align-items: center;
      padding-left: 25px;
      font-size: 24px;
      font-weight: 500;
      line-height: 30px;
      white-space: nowrap;
      > img {
        width: 30px;
        margin-right: 11px;
      }
    }
    .left-menu {
      justify-content: space-between;
      white-space: nowrap;
      font-size: 17px;
      display: flex;
      align-items: center;
      text-align: center;
      > ul {
        display: inline-flex;
      }
      .isActive,
      .isActive2 > div,
      .isActive:hover,
      .isActive:visited,
      .isActive:active,
      .isActive2 /deep/.el-submenu__title:hover {
        background: linear-gradient(90deg, #ffa35d, #ff891e);
        color: #fff !important;
        border: none;
      }
      // .isActive::after {
      //   content: '';
      //   height: 4px;
      //   background-color: rgba(0, 153, 255, 1);
      //   position: absolute;
      //   left: 0;
      //   right: 0;
      //   bottom: 0;
      //   margin: auto;
      // }
      /deep/.el-menu--horizontal {
        background: inherit;
        border: none;
        .el-menu-item:hover,
        .el-menu-item:focus,
        .el-submenu .el-submenu__title:hover {
          background: linear-gradient(90deg, #ffa35d, #ff891e) !important;
        }
        .el-menu-item {
          font-size: inherit !important;
          border-radius: 25px;
          cursor: pointer;
          text-align: center;
          position: relative;
          height: 42px;
          line-height: 42px;
          width: 100px;
          float: left;
          margin: 0 10px;
          padding: 0px;
          color: #fff !important;
          border: none !important;
        }
        .el-dropdown {
          font-size: inherit !important;
          cursor: pointer;
          > div {
            border-radius: 25px;
            color: #fff !important;
            border: none !important;
            height: 42px;
            line-height: 42px;
            margin: 0 10px;
            width: 110px;
            text-align: center;
            padding: 0;
            i {
              font-size: 12px;
            }
          }
        }
      }
    }
    .right-menu {
      float: right;
      height: 100%;
      line-height: 80px;
      display: flex;
      align-items: center;
      &:focus {
        outline: none;
      }

      .right-menu-item {
        display: inline-block;
        padding: 0 8px;
        height: 100%;
        font-size: 17px;
        color: #fff;
        vertical-align: text-bottom;
        z-index: 2;
        &.hover-effect {
          cursor: pointer;
          transition: background 0.3s;

          &:hover {
            background: rgba(0, 0, 0, 0.025);
          }
        }
      }
      .avatar-container {
        margin-right: 30px;
        vertical-align: top;
        padding-left: 0;
        .avatar-wrapper {
          position: relative;
          white-space: nowrap;
          .user-avatar {
            cursor: pointer;
            width: 26px;
            height: 26px;
            border-radius: 50%;
            margin-left: 8px;
            margin-top: 27px;
            border: 1px solid #ecf0f1;
            background: #fff;
          }
          .el-icon-caret-bottom {
			cursor: pointer;
            font-size: 12px;
          }
        }
      }
    }
  }
}
.userinformationdialog {
  >>> .el-dialog__body {
    padding: 20px 50px;
  }
  .userinformation {
    .el-form-item {
      margin-bottom: 0;
      margin-right: 0;
      width: 100%;
    }
    .el-form-item__label {
      text-align: right;
    }
  }
  /deep/.remark.el-form-item--medium .el-form-item__label,
  /deep/.remark.el-form-item--medium .el-form-item__content {
    line-height: 36px;
  }
}
</style>
