<template>
  <div>
    <v-toolbar
      class="banner"
      density="compact"
      style="padding-left: 0px;height: 50px;font-size: 14px;"
    >
      <div class="innerBox d-flex justify-space-between">
        <div>
          <div class="nav-logo" style="cursor: pointer;" @click="handleLogoClick">
            <v-img src="../../assets/logo.png"  aspect-ratio="16/9" cover :width="90" style="height: 40px"></v-img>
          </div>
          <!-- <div class="nav-city">
            <p class="nav-city-box">
              <v-icon color="primary">mdi-map-marker</v-icon>
              <span class="nav-city-selected">广州</span>
              <span class="switchover-city nav-city-selected">[{{ $t('sys.switchCities') }}]</span>
            </p>
          </div> -->
          <div class="nav">
            <ul>
              <li v-for="(k, listIndex) in list" :key="k.text" :class="{'routeActive': routeActive === listIndex}">
                <a :href="k.path" style="font-size: 14px;" class="aLink">{{ k.text }}</a>
              </li>
            </ul>
          </div>
        </div>
        
        <div class="d-flex user-nav">
          <div class="btns d-flex align-center" v-if="!getToken()">
            <v-btn class="half-button" border color="primary" size="small" @click="handleLogin">{{ $t('login.loginOrRegister') }}</v-btn>
          </div>
          
          <!-- 头像用户名 -->
          <div class="d-flex align-center" v-if="getToken()">
            <span class="cursor-pointer mr-5" @click="changeLoginType">我要招聘</span>
            <span class="cursor-pointer" @click="router.push({ path: '/recruit/personal/myWallet' })">{{t('resume.accountWithdrawal')}}：{{ userAccount?.balance || 0 }}</span>
            <span class="mr-3 ml-3 cursor-pointer" @click="router.push({ path: '/recruit/personal/myWallet' })">{{t('resume.goldCoins')}}：{{ userAccount?.point || 0 }}</span>

            
            <v-menu open-on-hover>
              <template v-slot:activator="{ props }">
                <div class="d-flex ml-3 align-center cursor-pointer" v-bind="props" @click="handleToPersonalCenter">
                  <v-avatar>
                    <v-img alt="John" :src="getUserAvatar(baseInfo?.avatar, baseInfo?.sex)"></v-img>
                  </v-avatar>
                  <div class="ml-3">{{ baseInfo?.name || $t('sys.tourist') }}</div>
                </div>
              </template>

              <v-list>
                <v-list-item v-for="(item, index) in items" :key="index" @click="item.change">
                  <template v-slot:prepend>
                    <v-icon :icon="item.icon"></v-icon>
                  </template>
                  <v-list-item-title>{{ item.title }}</v-list-item-title>
                </v-list-item>
              </v-list>
            </v-menu>
          </div>

          <!-- 语言切换 -->
          <!-- <v-menu>
            <template v-slot:activator="{ props }">
              <v-btn
                class="ml-3"
                color="primary"
                icon="mdi-translate"
                size="small"
                v-bind="props"
              >
              </v-btn>
            </template>
            <v-list density="compact" color="primary">
              <v-list-item
                v-for="item in localeStore.localeMap"
                :key="item.name"
                :value="item.lang"
                :active="localeStore.currentLocale.lang === item.lang"
                @click="handleChangeLocale(item)"
              >
                <v-list-item-title>{{ item.name }}</v-list-item-title>
              </v-list-item>
            </v-list>
          </v-menu> -->
          <div class="d-flex align-center" v-if="showBall">
            <!-- <span class="cursor-pointer mx-5" @click="router.push({ path: '/recruit/personal/TaskCenter' })">{{ $t('sys.signIn') }}</span> -->
            <!-- <span class="cursor-pointer" @click="router.push({ path: '/recruit/personal/message' })">{{ $t('sys.news') }}</span> -->
            <!-- <v-badge
              color="error"
              dot
              :model-value="useIM.unreadCount > 0"
            >
              <v-btn class="ml-1" size="small" icon="mdi-bell-outline" @click="router.push({ path: '/recruit/personal/message' })"></v-btn>
            </v-badge> -->
            <message-notification v-if="showBall" :path="paths[3]" :class="{'routeActive': routeActive === 3}"></message-notification>
            
          </div>
        </div>
        
      </div>
    </v-toolbar>

    <CtDialog :visible="show" title="请选择要切换的公司账号" :footer="true" widthType="2" @close="show = false" @submit="handleSubmit">
      <v-radio-group v-model="radios">
        <v-radio v-for="item in enterpriseList" :key="item.enterpriseId" color="primary" :label="item.enterpriseName" :value="item.enterpriseId"></v-radio>
      </v-radio-group>
    </CtDialog>
  </div>
</template>

<script setup>
import { computed, onMounted, ref } from 'vue'
import { getToken } from '@/utils/auth'
import { useUserStore } from '@/store/user'
// import { useLocaleStore } from '@/store/locale'
import { useI18n } from '@/hooks/web/useI18n'
import CtDialog from '@/components/CtDialog'
import { useRoute } from 'vue-router'; const route = useRoute()
import { useRouter } from 'vue-router'; const router = useRouter()
import { getUserBindEnterpriseList, getUserRegisterEnterpriseApply } from '@/api/personal/user'
import MessageNotification from '../message.vue'
import { getUserAvatar } from '@/utils/avatar'

// import { useIMStore } from '@/store/im'
defineOptions({ name: 'personal-navbar' })

defineProps({
  sticky: {
    type: Boolean,
    default: true
  }
})

const showBall = ref(false)

onMounted(() => {
  if (getToken()) {
    showBall.value = true
  }
})

// const useIM = useIMStore()

const { t } = useI18n()
// const localeStore = useLocaleStore()
const userStore = useUserStore()

const paths = [
  '/recruitHome',
  '/recruit/personal/position',
  '/recruit/personal/company',
  '/recruit/personal/message',
  ]
const list = ref([
  { text: t('common.home'), path: paths[0] },
  { text: t('common.position'), path: paths[1] },
  { text: t('common.company'), path: paths[2] }
])

const routeActive = computed(() => {
  const index = paths.findIndex(item => item === route.path)
  return index
})

const handleLogoClick = () => { window.open('/') } // 点击logo
const handleSubmit = () => { toEnterprise(radios.value) }

// 查看用户是否有企业
const show = ref(false)
const radios = ref(null)
const enterpriseList = ref([])
const changeLoginType = async () => {
  const data = await getUserBindEnterpriseList() // 申请通过才有数据，否则空数组
  enterpriseList.value = data || []
  if (data?.length) {
    if (data.length > 1) {
      show.value = true
      radios.value = data[0].enterpriseId
    } else {
      //只有一个企业直接切换
      toEnterprise(data[0].enterpriseId)
    }
  }
  else getApplyInfo()
}
// 切换为招聘者
const toEnterprise = async (enterpriseId) => {
  await getUserBindEnterpriseList({ enterpriseId })
  // 获取企业账号令牌以及企业用户个人信息
  await userStore.changeRole(enterpriseId)
  // router.push({ path: '/recruit/enterprise' })
  window.location.href = '/recruit/enterprise'
}

// 查看用户是否有在申请中的数据
const getApplyInfo = async () => {
  const data = await getUserRegisterEnterpriseApply()
  const bool = data && Object.keys(data).length // 已经有数据说明已经申请过了
  const path = bool ? '/recruit/enterprise/register/inReview' : '/recruit/enterprise/register'
  router.replace({ path })
}

const handleToPersonalCenter = () => {
  router.push({ path: '/recruit/personal/personalCenter' })
}

// 退出登录
const handleLogout = async () => {
  await userStore.userLogout(1)
  router.push({ path: '/login' })
}

const items = ref([
  { title: t('vipPackage.purchasePackage'), icon: 'mdi-gift-outline', change: () => router.push({ path: '/recruit/personal/purchasePackage' }) },
  { title: t('resume.onlineResume'), icon: 'mdi-list-box-outline', change: () => router.push({ path: '/recruit/personal/resume' }) },
  { title: t('setting.accountSettings'), icon: 'mdi-cog-outline', change: () => router.push({ path: '/recruit/personal/accountSettings/accountBinding' }) },
  // { title: t('setting.switchToRecruit'), icon: 'mdi-swap-horizontal', change: changeLoginType },
  { title: t('publicRecruitment.bountyRewards'), icon: 'mdi-google-circles-extended', change: () => router.push({ path: '/publicRecruitment' }) },
  { title: t('points.wallet'), icon: ' mdi-database-outline', change: () => router.push({ path: '/recruit/personal/myWallet' }) },
  { title: t('taskCenter.taskCenter'), icon: 'mdi-calendar-check-outline', change: () => router.push({ path: '/recruit/personal/TaskCenter' }) },
  { title: t('setting.logOut'), icon: 'mdi-logout', change: handleLogout }
])

let baseInfo = ref(JSON.parse(localStorage.getItem('baseInfo')) || {}) // 人才信息
let userAccount = ref(JSON.parse(localStorage.getItem('userAccount')) || {}) // 账户信息

userStore.$subscribe((mutation, state) => {
  if (Object.keys(state.baseInfo).length) baseInfo.value = state.baseInfo
  if (Object.keys(state.userAccount).length) userAccount.value = state.userAccount
})

const handleLogin = () => {
  router.push({ path: '/login' })
}

// 语言切换
// const handleChangeLocale = (item) => {
//   localeStore.setCurrentLocale(item)
//   location.reload()
// }
</script>

<style lang="scss" scoped>
@import '@/styles/personal/navBar.scss'
</style>
