<template>
  <div class="main-top">
    <div class="top-logo">
      <div class="top-logo-box">
        <img src="@/assets/logo-login.png" />
      </div>
      <!-- <img src="https://gw.alipayobjects.com/zos/rmsportal/KDpgvguMpGfqaHPjicRK.svg" /> -->
      <div class="text">定位行销管理系统</div>
      <div class="multipleTagStyle">
        <MultipleTag />
      </div>
    </div>

    <div class="top-right">
      <div class="person">
        <el-dropdown class="system-menu" trigger="click" @command="handleCommand">
          <div class="dropdown-show">
            <el-avatar size="small" :src="require('@/assets/teacher.png')" />
            <!-- <el-avatar size="small" :src="avatarUrl ? avatarUrl : require('@/assets/teacher.png')" /> -->
            <div class="full-name">{{ userInfo.fullName }}</div>
            <i class="el-icon-arrow-down el-icon--right" style="color: #fff"></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" @click="switchRoleVisible = true">
          {{ userInfo.loginRoleName }}
        </div>
      </div>
    </div>
    <!-- 切换角色弹窗 -->
    <el-dialog
      width="400px"
      title="切换角色"
      :visible.sync="switchRoleVisible"
      :close-on-click-modal="false"
      :append-to-body="true"
    >
      <div class="selectRoleClass" v-for="(item, index) in userInfo.userRoles" :key="index">
        <el-button v-if="item.id == userInfo.loginRoleId" type="primary" @click="switchRole(item.id)"
          >{{ item.name }}
        </el-button>
        <el-button v-else type="primary" plain @click="switchRole(item.id)">{{ item.name }}</el-button>
      </div>
    </el-dialog>
    <vue-particles
      class="particles-top"
      shapeType="circle"
      color="#fff"
      lines-color="#fff"
      hover-mode="repulse"
      click-mode="repulse"
      :particle-opacity="1"
      :particles-number="150"
      :particle-size="2"
      :lines-width="1"
      :line-opacity="0.6"
      :lines-distance="100"
      :move-speed="1.5"
      :hover-effect="false"
    />
  </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';
import MultipleTag from '@views/layout/multiple-tag';

export default {
  components: { MultipleTag },
  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: {
    toWelcomeLargeScreen() {
      this.$router.push('/largeScreen');
    },
    toLargeScreen() {
      this.$router.push({ path: '/largeScreenV2', query: { cityCode: '450900000000' } });
    },
    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 === 200) {
            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('您的密码已经超过90天未更新，请前往个人中心修改密码', '提示', {
              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(roleId) {
      let vm = this;
      if (roleId === vm.userInfo.loginRoleId) {
        vm.$message.warning('当前角色已经是' + vm.userInfo.loginRoleName);
        return;
      }
      let params = {
        roleId: roleId
      };
      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);
  },
  mounted() {},
  beforeDestroy() {
    clearInterval(this.checkTokenInterval);
  }
};
</script>

<style lang="less" scoped>
.top-right {
  padding: 30px;
  display: flex;
  align-items: center;
  height: 35px;
  z-index: 1;
  cursor: pointer;
}

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

  .system-menu {
    cursor: pointer;

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

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

.main-top {
  background: linear-gradient(to right, #0076ff, #00a2ff);
  width: 100%;
  height: 135px;
  position: absolute;
  border-radius: 0 0 20px 50px;
  // z-index: 0;
  display: flex;
  justify-content: space-between;
  color: #fff;
  overflow: hidden;

  .top-logo {
    transition: all 0.3s;
    display: flex;
    align-items: center;
    // justify-content: center;
    padding: 20px 20px;
    height: 55px;
    flex: 1;

    &-box {
      width: 40px;
      height: 40px;
      background: #fff;
      border-radius: 6px;
      display: flex;
      align-items: center;
      justify-content: center;

      img {
        display: block;
        width: 70%;
      }
    }

    .text {
      color: #fff;
      font-size: 24px;
      margin-left: 20px;
      font-weight: bold;
    }
  }
}

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

.selectRoleClass button {
  width: 200px;
}

.role-name {
  background: #0fce8b;
  padding: 8px 12px;
  margin-left: 16px;
  border-radius: 4px;
  font-size: 14px;
  line-height: 1;
}

.multipleTagStyle {
  flex: 1;
  margin-left: 32px;
  width: 800px;
  overflow: hidden;
}

/deep/ .el-tabs__nav-wrap i {
  color: #fff;
}

.particles-top {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
}
</style>
