<template>
  <div>
    <v-toolbar
      class="banner"
      density="compact"
      style="padding-left: 0px;height: 50px;font-size: 15px;"
    >
      <div class="innerBox d-flex justify-space-between">
        <div>
          <div class="nav-logo mr-5 mt-1 cursor-pointer" @click="router.push('/recruitHome')">
            <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="menuList">
            <div v-for="val in navList" :key="val.name" class="mr-3">
              <template v-if="val.children">
                <defineListPage v-bind="$attrs" :title="val.title" :list="val.children" @emitClick="handleClick" :closeOnContentClick="true"></defineListPage>
              </template>
              <template v-else>
                <span class="cursor-pointer menuList-first-title" :class="{'active-route' : route.path === val.path}" @click="handleClick(val, true)">{{ val.title }}</span>
              </template>
            </div>
          </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 color-333" v-if="getToken()">
            <span class="cursor-pointer mr-5 commonHover" @click="handleSwitch">我要招聘</span>
            <span class="cursor-pointer commonHover" :class="{'active-route': routeActive === 6}" @click="router.push({ path: paths[6] })">
              <span class="mr-3">
                现金：{{ userAccount?.balance && userAccount?.balance > 0 ? (userAccount?.balance / 100.0).toFixed(2) : 0 }}
                <span style="color: #00000000;">1</span>
                积分：{{ userAccount?.point || 0 }}
              </span>
              <span class="mr-3 ml-3"></span>
            </span>

            <v-menu open-on-hover>
              <template v-slot:activator="{ props }">
                <div class="d-flex ml-3 align-center cursor-pointer" :class="{'active-route': routeActive === 5}" 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 commonHover">
                    {{ baseInfo?.name || userInfo.phone }}
                    <v-icon :color="routeActive === 5 ? '#008979' : '#333'" size="30">mdi-menu-down</v-icon>
                  </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">
            <message-notification v-if="showBall" :path="paths[3]" class="commonHover2" :class="{'active-route': routeActive === 3}"></message-notification>
          </div>
        </div>
        
      </div>
    </v-toolbar>

    <CtDialog :visible="show" title="请选择要切换的公司账号" :footer="true" widthType="2" @close="show = false" @submit="switchSubmit">
      <v-radio-group v-model="radios" :hide-details="true">
        <v-radio v-for="item in enterpriseList" :key="item.enterpriseId" color="primary" :label="item.enterpriseName" :value="item.enterpriseId"></v-radio>
      </v-radio-group>
      <!-- <v-btn :loading="loading1" color="primary" variant="text" @click="newRegistering">{{ btnType ? '注册新企业' : '查看申请进度' }}</v-btn> -->
      <div class="text-end pr-5 pt-5">
        <span class="color-error cursor-pointer text-decoration-underline" @click="newRegistering">{{ btnType ? '都不是我要的？去注册新企业' : '查看申请进度' }}</span>
      </div>
    </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 defineListPage from '@/views/entrances/navBar/components/defineListPage'

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', // 0
  '/recruit/personal/position', // 1
  '/recruit/personal/company', // 2
  '/recruit/personal/message', // 3
  '/recruit/personal/myWallet', // 4
  '/recruit/personal/personalCenter', // 5
  '/recruit/personal/personalCenter/wallet', // 6
]

const navList = [
  // {
  //   title: '直聘',
  //   children: [
  //     {
  //       title: '门墩儿直聘',
  //       appList: [
  //         [{ title: '职位', path: paths[1] }, { title: '公司', path: paths[2] }]
  //       ]
  //     }
  //   ]
  // },
  { title: '直聘', path: '/recruitHome' },
  { title: '甄选', path: '/mall' },
  { title: '猎寻', path: '/headhunting' },
  { title: '火苗儿' },
  { title: '联合会' },
  { title: '数据' },
  { title: '了解门墩儿' }
]

const handleClick = (e, status) => {
  if (!e.path) return
  if (status && e.path !== '/recruitHome') window.open(e.path)
  else router.push(e.path)
}

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

const show = ref(false)
const radios = ref(null)
const enterpriseList = ref([])
// 切换为招聘者
const handleSwitch = async () => {
  await getApplyInfo() // 查询申请信息（注册进度）
  const data = await getUserBindEnterpriseList() // 申请通过才有数据，否则空数组
  enterpriseList.value = data || []
  if (data?.length) {
    radios.value = data[0].enterpriseId
    show.value = true
  } else {
    // router.push('recruit/enterpriseRegister')
    newRegistering() // 既没有存在的企业 又没有申请数据 》 进入注册页面
  }
}

// 切换提交
const switchSubmit = async () => {
  // await logout() // 先退出个人登录
  localStorage.setItem('enterpriseId', radios.value)

  // 跳转企业路由 且验证是否已完善必填基本信息
  window.location.href = '/enterpriseVerification'

  // 获取企业账号令牌以及企业用户个人信息
  // await userStore.changeRole(radios.value)
}

const btnType = ref(0)
// 查看用户是否有在申请中的数据
const getApplyInfo = async () => {
  const data = await getUserRegisterEnterpriseApply()
  localStorage.setItem('userApplyInfo', JSON.stringify(data))
  const status = data?.status || null // 有数据说明有申请

  // 0: 有等待审核的数据或者审核不通过的数据 >查看申请进度
  // 1: 没有正在审核的数据 >注册新企业
  btnType.value = (status === '0' || status === '2') ? 0 : 1
}

// 注册/查看申请进度
const loading1 = ref(false)
const newRegistering = () => {
  loading1.value = true
  const path = btnType.value ? '/recruit/entRegister' : '/recruit/entRegister/inReview'
  router.replace({ path })
}

const handleToPersonalCenter = () => {
  router.push({ path: paths[5] })
}

// 退出登录
const handleLogout = async () => {
  await userStore.userLogout(1)
  showBall.value = false
  if (route.path === '/recruitHome') location.reload()
  else router.push({ path: '/recruitHome' })
}

const items = ref([
  { title: t('setting.accountSettings'), icon: 'mdi-cog-outline', change: () => router.push({ path: '/recruit/personal/personalCenter/accountSettings' }) },
  { title: t('setting.logOut'), icon: 'mdi-logout', change: handleLogout }
])

let baseInfo = ref(JSON.parse(localStorage.getItem('baseInfo')) || {}) // 人才信息
let userInfo = ref(JSON.parse(localStorage.getItem('userInfo')) || {})
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.userInfo).length) userInfo.value = state.userInfo
  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>
