<template>
  <div style="padding-right: 0 ;">
    <el-dropdown
      trigger="click"
      placement="top-end"
      @command="handleCommand"
      @visible-change="dropdownClick"
    >
      <span class="avatar-dropdown">
        <div class="user-avatar">
          <img class="user-avatar-img" :src="imgSrc ? imgSrc : defaultimgSrc" />
        </div>
        <div
          class="user-name"
          :style="{
            '--topRightColor': isApp
              ? variables[`${appStyle}-top-right-color`]
              : variables[`${style}-top-right-color`],
          }"
        >
          <span>{{ username }}</span>
          <i
            :class="[
              dropdownVisible ? 'icon-nav-user-fold' : 'icon-nav-user-unfold',
            ]"
          ></i>
        </div>
      </span>

      <el-dropdown-menu slot="dropdown" style="width: 196px">
        <div class="account-info">
          <div class="user-avatar">
            <img
              class="user-avatar-img"
              :src="imgSrc ? imgSrc : defaultimgSrc"
            />
          </div>

          <div class="flex-right">
            <div class="user-name">{{ username }}</div>
            <div v-if="hasPost" class="position" :title="postInfo">
              {{ defaultPost.postName }}({{ defaultPost.orgName }})
            </div>
            <div v-else class="position">{{ $t('Switch.NoPosition') }}</div>
          </div>
        </div>

        <el-dropdown-item
          v-if="perListVal && perListVal.length > 0"
          command="personalInfo"
        >
          <div class="icon-item">
            <i class="iconfont icon-user-info"></i>
            <span>{{ $t('Personal.center') }}</span>
            <!-- <span>{{ $t('Navigator.userInfo') }}</span> -->
          </div>
        </el-dropdown-item>

<!--        <el-dropdown-item>-->
<!--          <el-dropdown placement="left-start" @command="handleLangChange">-->
<!--            <div class="icon-item switch-lang">-->
<!--              <i class="iconfont icon-user-switch-lang"></i>-->
<!--              <span>{{ $t('selectLang.switchLang') }}</span>-->
<!--            </div>-->
<!--            <el-dropdown-menu slot="dropdown">-->
<!--              <el-dropdown-item-->
<!--                v-for="lang in langOptions"-->
<!--                :key="lang.value"-->
<!--                :command="lang.value"-->
<!--              >-->
<!--                <div :class="['sub-dropdown-menu', { active: lang.selected }]">-->
<!--                  <i-->
<!--                    v-if="lang.selected"-->
<!--                    class="iconfont icon-user-popup-choice"-->
<!--                  ></i>-->
<!--                  <div style="width: 60px">{{ lang.label }}</div>-->
<!--                </div>-->
<!--              </el-dropdown-item>-->
<!--            </el-dropdown-menu>-->
<!--          </el-dropdown>-->
<!--        </el-dropdown-item>-->

<!--        <el-dropdown-item>-->
<!--          <el-dropdown placement="left-start" @command="handlePostChange">-->
<!--            <div class="icon-item switch-position">-->
<!--              <i class="iconfont icon-user-switch-position"></i>-->
<!--              <span>{{ $t('Switch.CurrentPosition') }}</span>-->
<!--            </div>-->
<!--            <el-dropdown-menu slot="dropdown">-->
<!--              <template v-if="hasPost">-->
<!--                <el-dropdown-item-->
<!--                  v-for="post in postMap"-->
<!--                  :key="post.postId"-->
<!--                  :command="post"-->
<!--                >-->
<!--                  <div-->
<!--                    :class="['sub-dropdown-menu', { active: post.selected }]"-->
<!--                  >-->
<!--                    <i-->
<!--                      v-if="post.selected"-->
<!--                      class="iconfont icon-user-popup-choice"-->
<!--                    ></i>-->
<!--                    <div style="width: 130px">-->
<!--                      {{ post.postName }}({{ post.orgName }})-->
<!--                    </div>-->
<!--                  </div>-->
<!--                </el-dropdown-item>-->
<!--              </template>-->
<!--              <el-dropdown-item v-else>-->
<!--                {{ $t('Switch.NoPosition') }}-->
<!--              </el-dropdown-item>-->
<!--            </el-dropdown-menu>-->
<!--          </el-dropdown>-->
<!--        </el-dropdown-item>-->

        <el-dropdown-item command="modifyPassword">
          <div class="icon-item">
            <i class="iconfont icon-user-pwd-modify"></i>
            <span>{{ $t('Navigator.ChangePassword') }}</span>
          </div>
        </el-dropdown-item>

        <el-dropdown-item command="logout" divided>
          <div class="user-logout icon-item">
            <i class="iconfont icon-user-logout"></i>
            <span>{{ $t('Exit.System') }}</span>
          </div>
        </el-dropdown-item>
      </el-dropdown-menu>
    </el-dropdown>

    <!-- 个人信息 dialog -->
    <personal-info
      :account-info="accountInfo"
      :personal-info-visible.sync="personalInfoVisible"
    />

    <!-- 修改密码 dialog -->
    <password-modify
      :account-info="accountInfo"
      :password-modify-visible.sync="passwordModifyVisible"
      @logout="logout"
    />

    <HtPerSideBar v-show="false" @perList="perList"></HtPerSideBar>
  </div>
</template>

<script>
  import HtPerSideBar from '@/components/layouts/HtPerSideBar/index.vue'
  import { mapGetters, mapMutations } from 'vuex'
  import { recordRoute } from '@/config'
  import { getDetailByAccountOrId } from '@/api/user'
  import variables from '@/styles/variables.scss'
  import PersonalInfo from '../PersonalInfo'
  import PasswordModify from '../PasswordModify'
  import req from '@/utils/request'
  import { fileUrl } from '@/api/portal'
  export default {
    name: 'HtAvatar',
    components: {
      PersonalInfo,
      PasswordModify,
      HtPerSideBar,
    },
    props: {
      isApp: {
        type: Boolean,
        default: false,
      },
    },
    data() {
      return {
        postMap: {},
        defaultPost: {},
        orgArray: [],
        accountInfo: null,
        dropdownVisible: false,
        personalInfoVisible: false,
        passwordModifyVisible: false,
        perListVal: null,
        imgSrc: '',
        defaultimgSrc: require('@/assets/login_images/user.jpg'),
        langOptions: [
          {
            label: '简体中文',
            value: 'zh-CN',
            selected: false,
          },
          {
            label: '繁体中文',
            value: 'zh-TW',
            selected: false,
          },
          {
            label: '英文',
            value: 'en',
            selected: false,
          },
        ],
      }
    },
    computed: {
      ...mapGetters({
        avatar: 'user/avatar',
        username: 'user/username',
        style: 'settings/style',
        appStyle: 'app/style',
      }),
      variables() {
        return variables
      },
      hasPost() {
        return Object.keys(this.postMap).length > 0
      },
      postInfo() {
        if (this.hasPost) {
          return `${this.defaultPost.postName}(${this.defaultPost.orgName})`
        }
        return '暂无岗位'
      },
    },
    watch: {
      avatar: {
        handler: function (val, oldVal) {
          if (val) {
            this.getImgUrl(val)
          }
        },
        deep: true,
        immediate: true,
      },
    },
    created() {
      const lang = localStorage.getItem('lang')
      if (lang) {
        this.setDefaultLang(lang)
      }
    },
    methods: {
      ...mapMutations('tabsBar', ['delAllVisitedRoutes']),
      // 下拉菜单显示，请求用户详细信息
      dropdownClick(isVisible) {
        this.dropdownVisible = isVisible
        if (isVisible && !this.accountInfo) {
          const { account } = this.$store.state.user
          if (!account) return
          getDetailByAccountOrId(account).then((data) => {
            if (data) {
              this.accountInfo = data
              this.postMap = data.post || {}
              this.orgArray = data.org || []
              for (let key in this.postMap) {
                this.postMap[key].selected = false
              }
              // const postId = localStorage.getItem('currentPostId')
              const postId = sessionStorage.getItem('currentPostId')
              if (postId) {
                this.setDefaultPost(postId)
              } else {
                if (this.orgArray.length) {
                  if (this.orgArray[0].postId) {
                    this.setDefaultPost(this.orgArray[0].postId)
                  } else {
                    this.postMap = []
                  }
                }
                // const t = Object.keys(this.postMap)
                // if (t && t.length) {
                //   this.setDefaultPost(this.postMap[t[0]].postId)
                // }
              }
            }
          })
        }
      },
      handleLangChange(lang) {
        this.setDefaultLang(lang)
        this.handleSetLanguage(lang)
      },
      setDefaultLang(lang) {
        this.langOptions.forEach((item) => {
          if (item.value === lang) {
            item.selected = true
          } else {
            item.selected = false
          }
        })
      },
      perList(val) {
        this.perListVal = val
      },
      handlePostChange(post) {
        if (!post) return
        const postId = post.postId
        this.setDefaultPost(postId)
        this.$message.success('岗位切换成功')
        // localStorage.setItem('currentPostId', postId)
        sessionStorage.setItem('currentPostId', postId)
        req.get(window.context.uc + '/uc/ucGroup/v1/setCookie?postId=' + postId)
        this.$router.go(0)
      },
      setDefaultPost(postId) {
        for (let key in this.postMap) {
          if (this.postMap[key].postId === postId) {
            this.defaultPost = this.postMap[key]
            this.postMap[key].selected = true
          } else {
            this.postMap[key].selected = false
          }
        }
      },
      handleCommand(command) {
        switch (command) {
          case 'personalInfo':
            if (this.perListVal && this.perListVal.length > 0) {
              this.$router.push('/personal/information')
            }

            break
          case 'modifyPassword':
            this.passwordModifyVisible = true
            break
          case 'logout':
            this.logoutWithTips()
            break
        }
      },
      handleSetLanguage(lang) {
        this.$i18n.locale = lang
        this.$validator.locale = lang
        localStorage.setItem('lang', lang)
        let language = this.langOptions.filter((item) => item.value == lang)[0]
          .label
        let message = this.$t('selectLang.switchLangMsg')
        this.$message({
          message: message,
          type: 'success',
        })
      },
      logoutWithTips() {
        const tips = `您确定要退出${this.$baseTitle}吗?`
        const tenantCode = this.$store.state.user.tenantCode
        this.$baseConfirm(tips, null, async () => {
          await this.$store.dispatch('user/logout')
          this.delAllVisitedRoutes()
          // 单点登录模式下重定向到单点退出页面
          if (
            window.ssoConfig.mode == 'cas' ||
            window.ssoConfig.mode == 'oauth'
          ) {
            window.location.href = window.ssoConfig.logout
            return
          }
          let loginPath = '/login'
          if (tenantCode && tenantCode != 'platform') {
            loginPath = loginPath + '/' + tenantCode
          }
          if (recordRoute) {
            const fullPath = this.$route.fullPath
            this.$router.push(loginPath)
          } else {
            this.$router.push(loginPath)
          }
        })
      },
      async logout() {
        await this.$store.dispatch('user/logout')
        if (recordRoute) {
          const fullPath = this.$route.fullPath
          this.$router.push(`/login?redirect=${fullPath}`)
        } else {
          this.$router.push('/login')
        }
      },
      getImgUrl(id) {
        this.$set(this, 'imgSrc', fileUrl(id))
      },
    },
  }
</script>
<style lang="scss" scoped>
  .user-avatar {
    width: 40px;
    height: 40px;
    cursor: pointer;
    border-radius: 50%;
    background: #c0c4cc;
    overflow: hidden;
    display: flex;
    align-items: center;
    justify-content: center;
    .user-avatar-img {
      height: 100%;
      width: 100%;
    }
  }
  .iconfont {
    display: inline-block;
    width: 20px;
    text-align: center;
    font-size: $base-font-size-big;
  }
  .avatar-dropdown {
    display: flex;
    align-content: center;
    align-items: center;
    justify-content: center;
    justify-items: center;
    height: 50px;
    padding: 0;

    .user-name {
      position: relative;
      padding-left: 15px;
      cursor: pointer;
      color: var(--topRightColor);
    }
  }
  .account-info {
    display: flex;
    padding: 8px 16px;
    margin-bottom: 3px;
    border-bottom: 1px solid $base-border-color;
    .flex-right {
      margin-left: 8px;
      .user-name {
        color: $base-font-color;
      }
      .position {
        max-width: 102px;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        color: var(--themeColor);
        font-size: $base-font-size-small;
        padding: 6px;
        margin-top: 5px;
        border-radius: $base-border-radius;
        background-color: rgba(var(--themeColorRgb), 0.08);
      }
    }
  }
  ::v-deep {
    .el-dropdown-menu__item {
      padding: 3px 16px;
      &:hover {
        background: #f9f9f9 !important;
      }
      .el-dropdown {
        width: 100%;
      }
    }
  }
  .user-logout {
    color: #e55555;
    &:hover {
      color: #e55555;
    }
  }
  .icon-item {
    .iconfont {
      display: inline-block;
      margin-right: 8px;
    }
  }

  .switch-lang,
  .switch-position {
    width: 100%;
    &:hover {
      color: var(--themeColor);
      background: #f9f9f9;
    }
  }
  .active {
    color: var(--themeColor);
  }
  .sub-dropdown-menu {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: flex-end;
  }
</style>
