<template>
  <div class="trials-navbar" style="position: relative">
    <div class="leftMenu">
      <!-- <img v-if="language === 'zh' && hospital.HospitalLogoPath" -->
      <img v-if="hospital.HospitalLogoPath" :src="OSSclientConfig.basePath + hospital.HospitalLogoPath"
        crossOrigin="anonymous" alt="" :class="{ img_en: NODE_ENV === 'usa' }"
        :style="`max-height:50px;max-width:${config.logoScale.page * 50}px`" />
      <div v-else style="width: 170px;"></div>
      <!-- <img v-else src="@/assets/zzlogo3.png" alt="" /> -->
      <span style="white-space: nowrap">
        <!-- 中心影像系统（EICS） -->
        {{ $t('trials:trials:title:eics') }}
      </span>
    </div>
    <div class="center-menu">
      <NoticeMarquee />
    </div>
    <div class="right-menu">
      <el-menu :default-active="activeIndex" class="el-menu-demo" mode="horizontal" size="mini" @select="handleSelect">
        <!-- <el-menu-item v-if="!hasPermi(['role:air', 'role:rpm', 'role:radmin', 'role:rcrc', 'role:rir'])" index="1">
          <i class="el-icon-odometer" /> -->
        <!-- 工作台 -->
        <!-- <span slot="title">{{ $t('trials:menuTitle:workbench') }}</span>
        </el-menu-item> -->
        <el-menu-item v-if="hasPermi(['role:pm', 'role:sa', 'role:admin', 'role:dev', 'role:ga'])" index="1">
          <i class="el-icon-odometer" />
          <!-- 检查 -->
          <span slot="title">{{ $t('trials:menuTitle:inspection') }}</span>
        </el-menu-item>
        <el-menu-item v-if="!hasPermi(['role:zys'])" index="2" :disabled="TotalNeedSignSystemDocCount !== 0">
          <i class="el-icon-box" />
          <!-- 我的项目 -->
          <span slot="title">
            {{ $t('trials:tab:trials') }}
          </span>
        </el-menu-item>
        <el-menu-item v-if="
          !hasPermi([
            'role:air',
            'role:rpm',
            'role:radmin',
            'role:rcrc',
            'role:rir',
            'role:zys',
          ])
        " index="3">
          <i class="el-icon-chat-dot-square" />
          <!-- 通知消息 -->
          <span slot="title">{{ $t('trials:tab:notice') }}</span>
        </el-menu-item>

        <el-submenu index="4" class="my_info">
          <span slot="title">
            <i class="el-icon-s-custom" />
            {{ `${name} (${userTypeShortName})` }}
            <!-- <span>{{ userName }}</span>
            <span v="userTypeShortName">({{ userTypeShortName }})</span> -->
          </span>
          <!-- 账户信息 -->
          <el-menu-item v-if="!hasPermi(['role:air'])" index="4-2">{{
            $t('trials:trials-myinfo:title:accountInfo')
          }}</el-menu-item>
          <!-- 管理后台 -->
          <el-menu-item v-if="hasPermi(['role:dev', 'role:sa', 'role:admin', 'role:ga'])" index="4-4">{{
            $t('trials:trials-myinfo:title:system') }}</el-menu-item>
          <!-- 切换角色 -->
          <el-menu-item index="4-5" v-if="hasRole">{{
            $t('trials:trials-myinfo:title:toggleRole')
          }}</el-menu-item>
          <!-- 退出 -->
          <el-menu-item index="4-3">{{
            $t('trials:trials-myinfo:button:loginout')
          }}</el-menu-item>
        </el-submenu>
      </el-menu>
      <TopLang v-if="isDev" />
      <toggleRole v-if="toggleRoleVisible" :visible.sync="toggleRoleVisible" :loading="toggleRoleLoading"
        @save="loginByRole" />
    </div>
  </div>
</template>

<script>
import { loginOut } from '@/api/user'
import { mapGetters, mapMutations } from 'vuex'
import TopLang from './topLang'
import NoticeMarquee from './noticeMarquee'
import { getHospital } from '@/api/hospital.js'
import logoImg from '@/assets/zzlogo2.png'
import { resetRouter } from '@/router'
import toggleRole from '@/components/toggleRole'
export default {
  components: { TopLang, NoticeMarquee, toggleRole },
  data() {
    return {
      logoImg,
      config: WINDOW_CONFIG,
      NODE_ENV: process.env.NODE_ENV, // process.env.NODE_ENV
      activeIndex: '2',
      isReviewer: false,
      // userTypeShortName: zzSessionStorage.getItem('userTypeShortName'),
      notice: '',
      hospital: {
        HospitalLogoPath: null,
        HospitalName: null,
      },
      toggleRoleVisible: false,
      toggleRoleLoading: false,
    }
  },
  computed: {
    ...mapGetters([
      'sidebar',
      'name',
      'userName',
      'device',
      'TotalNeedSignSystemDocCount',
      'language',
      'userTypeShortName'
    ]),
    roles() {
      return this.$store.state.user.roles
    },
    hasRole() {
      return (
        this.roles &&
        this.roles.length > 1 &&
        this.roles.filter((item) => !item.IsUserRoleDisabled).length > 1
      )
    },
    isDev() {
      return process.env.VUE_APP_OSS_PATH === "/hir_test/dist"
    },
    isEN() {
      return this.$i18n.locale !== 'zh'
    }
  },
  watch: {
    $route(v) {
      this.changeRoute(v)
    },
  },
  created() {
    // this.isReviewer = JSON.parse(zzSessionStorage.getItem('IsReviewer'))
    this.changeRoute(this.$route)
    this.getInfo()
    this.$store.dispatch('user/getUserInfo')
  },
  methods: {
    ...mapMutations({ setLanguage: 'lang/setLanguage' }),
    loginByRole(userRoleId) {
      if (this.$store.state.user.userId === userRoleId) {
        this.toggleRoleVisible = false
        this.toggleRoleLoading = false
        return false
      }
      this.toggleRoleLoading = true
      this.$store
        .dispatch('user/loginByRole', { userRoleId })
        .then((res) => {
          if (res) {
            this.$store
              .dispatch('permission/generateRoutes')
              .then(async (res) => {
                if (res && res.length > 0) {
                  resetRouter()
                  await this.$store.dispatch('global/getNoticeList')
                  this.$router.addRoutes(res)
                  this.toggleRoleLoading = false
                  if (this.loginType === 'DevOps') {
                    this.$router.replace({ path: res[0].path })
                    return
                  }
                  if (this.hasPermi(['role:radmin'])) {
                    this.$router.replace({ path: res[0].path })
                    return
                  }
                  if (
                    this.hasPermi(['role:pm', 'role:sa', 'role:admin', 'role:dev', 'role:ga'])
                  ) {
                    history.replaceState(null, null, '/trials/trials-inspection')
                    history.go(0)
                    // this.$router.replace({ path: '/trials/trials-list' })
                  } else {
                    history.replaceState(null, null, '/trials/trials-list')
                    history.go(0)
                    // this.$router.replace({ path: '/trials/trials-workbench' })
                  }
                  this.toggleRoleVisible = false
                  this.toggleRoleLoading = false
                  this.$EventBus.$emit('reload')
                  // this.$nextTick(() => {
                  //   window.location.reload()
                  // })
                } else {
                  // 此账户暂未配置菜单权限，请联系管理员处理后再登录。
                  this.toggleRoleLoading = false
                  this.$message.warning(this.$t('login:message:login2'))
                }
              })
              .catch((err) => {
                this.toggleRoleLoading = false
              })
          } else {
            this.toggleRoleLoading = false
          }
        })
        .catch(() => {
          this.toggleRoleLoading = false
        })
    },
    // 获取医院信息
    async getInfo() {
      try {
        let res = await getHospital()
        if (res.IsSuccess) {
          Object.keys(this.hospital).forEach((key) => {
            this.hospital[key] = res.Result[key]
          })
        }
      } catch (err) {
        console.log(err)
      }
    },
    changeRoute(v) {
      if (v.path === '/trials/trials-inspection') {
        this.activeIndex = '1'
      }
      if (
        v.path === '/trials/trials-list' ||
        ~v.path.indexOf('/trials/trials-panel')
      ) {
        this.activeIndex = '2'
      }
      if (v.path === '/trials/trials-notice') {
        this.activeIndex = '3'
      }
      if (v.path === '/trials/trials-myinfo') {
        this.activeIndex = '4-2'
      }
    },
    handleSelect(key, keyPath) {
      switch (key) {
        case '4-2':
          this.go('/trials/trials-myinfo')
          break
        case '4-3':
          this.logout()
          break
        case '4-4':
          this.go('/system')
          break
        case '4-5':
          this.$store.dispatch('user/getUserInfo').then((res) => {
            this.toggleRoleVisible = true
          })

          break
        case '1':
          this.go('/trials/trials-inspection')
          break
        case '2':
          if (~this.$route.path.indexOf('/trials/trials-panel')) {
            return
          }
          var lastWorkbench = zzSessionStorage.getItem('lastWorkbench')
          if (lastWorkbench) {
            this.go(lastWorkbench)
          } else {
            this.go('/trials/trials-list')
          }
          break
        case '3':
          this.go('/trials/trials-notice')
          break
      }
    },
    toggleSideBar() {
      this.$store.dispatch('app/toggleSideBar')
    },
    async logout() {
      // await loginOut()
      await this.$store.dispatch('user/logout')
      this.$router.push(`/login`)
      this.$i18n.locale = 'zh'
      this.setLanguage('zh')
      this.$updateDictionary()
    },
    go(value) {
      this.$router.push({ path: value })
    },
    account() {
      this.$router.push({ name: 'Account' })
    },
  },
}
</script>

<style lang="scss" scoped>
.trials-navbar {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  height: 70px;
  overflow: hidden;
  background: #fff;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);

  .el-breadcrumb__item {
    font-size: 16px;
  }

  .leftMenu {
    display: flex;
    align-items: center;
    padding-left: 20px;

    img {
      // max-height: 50px;
      margin-right: 10px;
      // max-width: 170px;
    }

    // .img_en {
    //   height: 36px;
    //   min-width: 10px;
    // }

    span {
      font-size: 20px;
      position: relative;
      top: -1px;
    }
  }

  .right-menu,
  .center-menu {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    height: 100%;

    // line-height: 70px;
    &: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 {
      display: inline-block;
      margin-right: 200px;

      .user-avatar {
        margin-top: 5px;
        width: 40px;
        height: 40px;
        border-radius: 10px;
      }
    }

    .dropdown-container {
      cursor: pointer;

      .el-icon-caret-bottom {
        font-size: 12px;
      }
    }

    .el-dropdown-link {
      color: #999c9e;
      cursor: pointer;
    }
  }
}
</style>
<style>
.el-menu--horizontal>.my_info.el-submenu .el-submenu__icon-arrow {
  margin-top: 0;
}
</style>
