<template>
  <div class="main-top">
    <div class="top-logo">
      <div class="top-logo-box">
        <img src="@/assets/logo-login.png" v-if="false" />
        <span v-else style="color: #4c84ff; font-weight: bold;">Logo</span>
      </div>
      <div class="text">定位行销管理系统</div>
      <div class="multipleTagStyle">
        <TagsView />
      </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="avatarUrl" />
            <div class="full-name">{{ userStore.userInfo.fullName }}</div>
            <el-icon style="color: #fff"><ArrowDown /></el-icon>
          </div>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="personalCenterFn">个人中心</el-dropdown-item>
              <el-dropdown-item command="logout">退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <div class="role-name" @click="switchRoleVisible = true">
          {{ userStore.userInfo.loginRoleName }}
        </div>
      </div>
    </div>

    <el-dialog
      width="400px"
      title="切换角色"
      v-model="switchRoleVisible"
      :close-on-click-modal="false"
      :append-to-body="true"
    >
      <div class="selectRoleClass" v-for="(item, index) in userStore.userInfo.userRoles" :key="index">
        <el-button v-if="item.id == userStore.userInfo.loginRoleId" type="primary" @click="switchRoleFn(item.id)">
          {{ item.name }}
        </el-button>
        <el-button v-else type="primary" plain @click="switchRoleFn(item.id)">{{ item.name }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessageBox, ElMessage, ElNotification } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { usePermissionStore } from '@/stores/permission'
import { fetchUserInfo, passwordCheckStatus, switchRole } from '@/api/user'
import { fetchDict } from '@/api/dictionary'
import { useAppStore } from '@/stores/app'
import { getRouter } from '@/utils/crypto'
import { getStore } from '@/utils/storage'
import TagsView from './TagsView.vue'

const router = useRouter()
const userStore = useUserStore()
const permStore = usePermissionStore()
const appStore = useAppStore()

const switchRoleVisible = ref(false)
let checkTokenInterval: number | null = null

const avatarUrl = computed(() => {
  const list = userStore.userInfo?.attachDataList
  if (list && list.length > 0) return list[0].url
  return ''
})

async function getCurrUser() {
  try {
    const res = await fetchUserInfo()
    userStore.setUserInfo(res.data)
  } catch (error: any) {
    ElNotification.error({ title: error?.data?.msg || '', message: error?.data?.data || '' })
  }
}

async function getDict() {
  try {
    const res = await fetchDict()
    appStore.setDict(res.data)
  } catch (error: any) {
    ElNotification.error({ title: error?.data?.msg || '', message: error?.data?.data || '' })
  }
}

async function handleCommand(command: string) {
  const fnMap: Record<string, () => void> = {
    personalCenterFn,
    logout
  }
  fnMap[command]?.()
}

async function logout() {
  try {
    await ElMessageBox.confirm('确认退出吗?', '提示', { type: 'warning' })
    const res = await userStore.logoutAction()
    if (res.code === 200) {
      ElMessage.success('已退出登录')
      await permStore.removeRoutes()
      router.push({ name: 'login' })
    }
  } catch {
    // user cancelled
  }
}

async function passwordCheckStatusFn() {
  try {
    const res = await passwordCheckStatus()
    if (res.data === '1') {
      await ElMessageBox.alert('您的密码已经超过90天未更新，请前往个人中心修改密码', '提示', {
        closeOnClickModal: false,
        confirmButtonText: '前往修改',
        type: 'warning'
      })
      personalCenterFn()
    }
  } catch (error: any) {
    ElNotification.error({ title: error?.data?.msg || '', message: error?.data?.data || '' })
  }
}

function personalCenterFn() {
  const path = '/personal-center'
  const hasPath = permStore.multipleTag.filter((o: any) => o.path === path).length > 0
  if (!hasPath) {
    const routeItem = getRouter(permStore.routers, path)
    if (routeItem) {
      permStore.SET_MULTIPLE_TAG([...permStore.multipleTag, routeItem])
    }
  }
  permStore.SET_CUR_TAG(path)
  router.push({ path })
}

function tokenCheckFn() {
  const expireTime = getStore('expireTime')
  const ttl = Math.floor((expireTime - new Date().getTime()) / 1000)
  if (ttl > 0 && ttl < 10 * 60) {
    if (checkTokenInterval) clearInterval(checkTokenInterval)
    ElMessageBox.confirm('有效操作时间不足10分钟, 请重置或退出登录', '提示', {
      confirmButtonText: '重置',
      cancelButtonText: '退出',
      closeOnClickModal: false,
      type: 'warning'
    })
      .then(() => {
        const tmpTtl = Math.floor((expireTime - new Date().getTime()) / 1000)
        if (tmpTtl <= 0) {
          ElMessageBox.alert('超过可操作时间, 请重新登录')
          permStore.removeRoutes()
          router.push({ name: 'login' })
          return
        }
        userStore.refreshTokenAction()
        checkTokenInterval = window.setInterval(tokenCheckFn, 10000)
      })
      .catch(() => {
        ElMessage.success('已退出登录')
        permStore.removeRoutes()
        router.push({ name: 'login' })
      })
  }
}

async function switchRoleFn(roleId: string) {
  if (roleId === userStore.userInfo?.loginRoleId) {
    ElMessage.warning('当前角色已经是' + userStore.userInfo?.loginRoleName)
    return
  }
  switchRoleVisible.value = false
  try {
    const res = await switchRole({ roleId })
    userStore.setUserInfo(res.data)
    userStore.switchRoleFn(res.data)
    const content = [permStore.multipleTag[0]]
    permStore.SET_MULTIPLE_TAG(content)
    permStore.SET_CUR_TAG('/home')
    router.push({ path: '/home' })
    location.reload()
  } catch (error: any) {
    ElNotification.error({ title: error?.data?.msg || '', message: error?.data?.data || '' })
  }
}

onMounted(() => {
  getCurrUser()
  getDict()
  passwordCheckStatusFn()
  checkTokenInterval = window.setInterval(tokenCheckFn, 10000)
})

onBeforeUnmount(() => {
  if (checkTokenInterval) clearInterval(checkTokenInterval)
})
</script>

<style lang="less" scoped>
.main-top {
  background: linear-gradient(to right, #0076ff, #00a2ff);
  width: 100%;
  height: 135px;
  position: absolute;
  border-radius: 0 0 20px 50px;
  display: flex;
  justify-content: space-between;
  color: #fff;
  overflow: hidden;

  .top-logo {
    transition: all 0.3s;
    display: flex;
    align-items: 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;
    }
  }
}

.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;
      }
    }
  }
}

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

  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;
}
</style>
