<template>
  <div :class="['top-nav', 'top-nav-style-' + curTheme]">
    <!-- 展开缩进菜单 -->
    <div class='icon-dent' @click='dent'>
      <i class='iconfont' :class='navClass' />
    </div>
    <!-- 页面标题 -->
    <div class='page-title'>{{ $route.matched[this.$route.matched.length - 1].meta.name }}</div>
    <!-- 个人信息 -->
    <div class='person'>
      <el-dropdown class='system-menu' trigger='click' @command='handleCommand'>
        <div class='dropdown-show'>
          <el-avatar size='small' :src='avatarUrl' />
          <div class='full-name'>{{ userInfo.fullName }}</div>
          <i class='el-icon-arrow-down el-icon--right'></i>
        </div>
        <el-dropdown-menu slot='dropdown'>
          <el-dropdown-item command='personalCenterFn'>个人中心</el-dropdown-item>
          <!-- <el-dropdown-item command="password">修改密码</el-dropdown-item> -->
          <el-dropdown-item command='logout'>退出登录</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
      <div :class="['role-name', 'role-name-style-' + curTheme]">
        <!-- <div class="name-s" v-for="(item, index) in userInfo.roleNames" :key="index">
          <div class="text">{{ item }}</div>
          <div class="line"></div>
        </div> -->
        <div class='name-s'>
          <div class='text' @click='switchRoleVisible = true'>{{ userInfo.loginRoleName }}</div>
        </div>
      </div>
      <div class='theme-change' @click='themeChange'>
        <el-tooltip effect='dark' :content='themeText[curTheme]' placement='bottom'>
          <i :class="['icon', 'el-icon-s-open', 'theme-' + curTheme]"></i>
        </el-tooltip>
      </div>
    </div>
    <!-- 切换角色弹窗 -->
    <el-dialog width='400px' title='切换角色' :visible.sync='switchRoleVisible' :close-on-click-modal='false'>
      <div class='selectRoleClass' v-for='(item, index) in userInfo.roleNames' :key='index'>
        <el-button v-if='item == userInfo.loginRoleName' type='primary' @click='switchRole(item)'>{{ item }}</el-button>
        <el-button v-else type='primary' plain @click='switchRole(item)'>{{ item }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { fetchUserInfo, passwordCheckStatus, switchRole } from '@api/upms/api-user';
import { fetchDict } from '@api/upms/api-dictionary';
import { getRouter } from '@utils/util';
import { getStore } from '@utils/store';

export default {
  name: 'Top',
  components: {},
  data() {
    return {
      roleNames: ['管理员', '成员', '会员'],
      activeIndex: '1',
      passDialog: false,
      themeText: {
        dark: '切换浅色主题',
        light: '切换深色主题'
      },
      userInfo: {
        attachDataList: []
      },
      checkTokenInterval: null,
      switchRoleVisible: false
    };
  },
  computed: {
    navClass() {
      return this.$store.state.app.nav.navClass;
    },
    routers() {
      return this.$store.getters.routers;
    },
    avatarUrl() {
      if (this.userInfo.attachDataList.length > 0) {
        return this.userInfo.attachDataList[0].url;
      } else {
        return '';
      }
    },
    multipleTag() {
      return this.$store.getters.multipleTag;
    },
    curTheme() {
      return this.$store.getters.curTheme;
    }
  },
  methods: {
    themeChange() {
      let curTheme = this.curTheme;
      let changeTheme = '';
      switch (curTheme) {
        case 'dark':
          changeTheme = 'light';
          this.$store.dispatch('setCurTheme', changeTheme);
          break;

        case 'light':
          changeTheme = 'dark';
          this.$store.dispatch('setCurTheme', changeTheme);
          break;

        default:
          break;
      }
    },
    getCurrUser() {
      let vm = this;
      fetchUserInfo().then(
        (res) => {
          vm.userInfo = res.data;
          vm.$store.dispatch('setUserInfo', res.data);
        },
        (error) => {
          vm.$notify.error({
            title: error.data.msg,
            message: error.data.data
          });
        }
      );
    },
    getDict() {
      let vm = this;
      fetchDict().then(
        (res) => {
          this.$store.dispatch('setDict', res.data);
        },
        (error) => {
          vm.$notify.error({
            title: error.data.msg,
            message: error.data.data
          });
        }
      );
    },
    dent() {
      this.$store.dispatch('isCollapseClick');
    },
    handleCommand(command) {
      this[command]();
    },
    logout() {
      this.$confirm('确认退出吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.$store.dispatch('logout').then((res) => {
          if (res.code === '000000') {
            this.$message.success('已退出登录');
            this.$store.dispatch('removeRoutes');
            this.$router.push({ name: 'login' });
          }
        });
      });
    },
    passwordCheckStatusFn() {
      let vm = this;
      passwordCheckStatus().then(
        (res) => {
          if (res.data === '1') {
            // 弹出提示窗,点击是的时候,弹出修改密码框框,否则取消
            vm.$alert('密码距离过期不足30天, 请前往个人中心修改密码', '提示', {
              closeOnClickModal: false,
              confirmButtonText: '前往修改',
              type: 'warning'
            }).then(() => {
              this.personalCenterFn();
            });
          }
        },
        (error) => {
          vm.$notify.error({
            title: error.data.msg,
            message: error.data.data
          });
        }
      );
    },
    personalCenterFn() {
      const path = '/personal-center';
      let hasPath = this.multipleTag.filter((o) => o.path === path).length > 0;
      if (!hasPath) {
        let router = getRouter(this.routers, path);
        if (router) {
          this.multipleTag.push(router);
        }
      }
      this.$store.dispatch('setMultipleTag', this.multipleTag);
      this.$store.dispatch('setCurTag', path);
      this.$router.push({ path: path });
    },
    tokenCheckFn() {
      let vm = this;
      let expireTime = getStore('expireTime');
      // token有效期小于10分钟
      let ttl = Math.floor((expireTime - new Date().getTime()) / 1000);
      if (ttl > 0 && ttl < 10 * 60) {
        clearInterval(vm.checkTokenInterval);
        vm.$confirm('有效操作时间不足10分钟, 请重置或退出登录', '提示', {
          confirmButtonText: '重置',
          cancelButtonText: '退出',
          closeOnClickModal: false,
          type: 'warning'
        })
          .then(() => {
            // 点击确定之后请求后台
            let tmpTtl = Math.floor((expireTime - new Date().getTime()) / 1000);
            if (tmpTtl <= 0) {
              vm.$alert('超过可操作时间, 请重新登录');
              vm.$store.dispatch('removeRoutes');
              vm.$router.push({ name: 'login' });
              return;
            }
            vm.$store.dispatch('refreshToken');
            this.checkTokenInterval = setInterval(this.tokenCheckFn, 10000);
          })
          .catch(() => {
            // 取消则返回登录页
            vm.$message.success('已退出登录');
            vm.$store.dispatch('removeRoutes');
            vm.$router.push({ name: 'login' });
          });
      }
    },
    switchRole(roleName) {
      let vm = this;
      if (roleName === vm.userInfo.loginRoleName) {
        vm.$message.warning('当前角色已经是' + roleName);
        return;
      }
      let params = {
        roleCnName: roleName
      };
      vm.switchRoleVisible = false;
      switchRole(params).then(
        (res) => {
          vm.userInfo = res.data;
          vm.$store.dispatch('setUserInfo', res.data);
          vm.$store.dispatch('switchRole', res.data);
          let content = [vm.multipleTag[0]];
          this.$store.dispatch('setMultipleTag', content);
          this.$store.dispatch('setCurTag', '/home');
          this.$router.push({ path: '/home' });
          location.reload();
        },
        (error) => {
          vm.$notify.error({
            title: error.data.msg,
            message: error.data.data
          });
        }
      );
    }
  },
  created() {
    this.getCurrUser();
    this.getDict();
    this.passwordCheckStatusFn();
    this.checkTokenInterval = setInterval(this.tokenCheckFn, 10000);
  },
  beforeDestroy() {
    clearInterval(this.checkTokenInterval);
  }
};
</script>

<style scoped lang='less'>
.top-nav {
  display: flex;
  align-items: center;
  box-sizing: border-box;

  .icon-dent {
    width: 50px;
    height: 50px;
    color: @theme-dark-gray-color;
    display: flex;
    align-items: center;
    justify-content: center;

    &:hover {
      cursor: pointer;
      background-color: @theme-light-color - 20;
    }

    i {
      font-size: 20px;
    }
  }

  .page-title {
    font-size: 20px;
    color: @theme-dark-color;
    padding-bottom: 2px;
  }

  .person {
    margin-left: auto;
    display: flex;
    align-items: center;

    .system-menu {
      cursor: pointer;

      .dropdown-show {
        display: flex;
        align-items: center;

        .full-name {
          color: #333;
          padding-left: 10px;
        }
      }
    }

    .role-name {
      padding: 4px 10px;
      border-radius: 6px;
      margin-left: 10px;
      display: flex;
      align-items: center;

      .name-s {
        display: flex;
        align-items: center;

        .text {
          font-size: 12px;
          cursor: pointer;
        }

        .line {
          width: 1px;
          height: 10px;
          background-color: #fff;
          margin: 0 10px;
        }

        &:last-child {
          .line {
            display: none;
          }
        }
      }
    }

    .theme-change {
      width: 30px;
      height: 30px;
      display: flex;
      align-items: center;
      justify-content: center;
      margin: 0 12px;
      cursor: pointer;

      .icon {
        font-size: 24px;
      }
    }
  }

  .selectRoleClass {
    margin: 0 auto;
    text-align: center;
    padding-top: 10px;
    padding-bottom: 20px;
  }

  .selectRoleClass button {
    width: 200px;
  }
}
</style>
