<template>
  <el-config-provider :locale="locale">
    <div class="layout">
      <el-container v-if="userInfo" class="container">
        <el-aside class="aside">
          <div class="port"><img src="./assets/logo.png" alt="">{{userInfo.userType==3?'教师端':'学生端'}}</div>
          <el-menu :router="true" active-text-color="#3A84FF" text-color="#94979B" class="menu" :default-active='parentPath'>
            <el-menu-item index="/psychology">
              <i class="el-icon-chat-dot-round"></i>
              <template #title>咨询预约</template>
            </el-menu-item>
            <el-menu-item index="/term" v-if="userInfo.userType==3">
              <i class="el-icon-date"></i>
              <template #title>教师排班</template>
            </el-menu-item>
            <el-menu-item index="/coach" v-if="userInfo.userType==3">
              <i class="el-icon-collection-tag"></i>
              <template #title>个案辅导</template>
            </el-menu-item>
            <el-menu-item index="/userExtraInfo" v-if="userInfo.userType==3">
              <i class="el-icon-info"></i>
              <template #title>基本信息导入</template>
            </el-menu-item>
            <el-menu-item index="/science">
              <i class="el-icon-data-analysis"></i>
              <template #title>心晴悦读室</template>
            </el-menu-item>
            <el-menu-item index="/study">
              <i class="el-icon-reading"></i>
              <template #title>数字学习馆</template>
            </el-menu-item>
            <el-menu-item index="/experience">
              <i class="el-icon-guide"></i>
              <template #title>解忧杂货铺</template>
            </el-menu-item>
            <div class="line"></div>
            <el-menu-item @click="handleCareer" style="color:rgb(148, 151, 155) !important;">
              <i class="el-icon-connection" style="color:rgb(148, 151, 155) !important;"></i>
              <template #title>学生生涯规划服务系统</template>
            </el-menu-item>
          </el-menu>
        </el-aside>
        <el-container class="content">
          <Header :name='userInfo.name' />
          <div class="main">
            <router-view />
          </div>
        </el-container>
      </el-container>
      <p v-else class="loading">载入中...</p>
    </div>
  </el-config-provider>
</template>

<script>
import { ElConfigProvider } from 'element-plus'
import zhCn from 'element-plus/lib/locale/lang/zh-cn'
import { getCurrentInstance,onMounted, onUnmounted, reactive, toRefs, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import Header from '@/components/Header.vue'
import { ElMessage } from 'element-plus'
import { pathMap } from '@/utils'
import axios from '@/utils/axios'
import vConsole from 'vconsole'
export default {
  name: 'App',
  components: {
    [ElConfigProvider.name]: ElConfigProvider,
    Header
  },

  setup () {
    // new vConsole()
    const router = useRouter()
    const store = useStore()
    const state = reactive({
      currentPath: '/psychology',
      userInfo: ''
    })
     const internalInstance = getCurrentInstance()
    const unwatch = router.beforeEach((to, from, next) => {
      console.log(to)
      next()
      state.currentPath = to.path
      document.title = pathMap[to.name]
    })
    // 用于设置左侧导航栏选中状态
    const parentPath = computed(() => {
      switch (state.currentPath) {
        case '/experience':
        case '/experience_detail':
        case '/experience_audit':
          return '/experience'
        case '/study':
        case '/study_second':
        case '/study_detail':
          return '/study'
        case '/science':
        case '/science_detail':
          return '/science'
        case '/userExtraInfo':
        case '/infoDetail':
          return '/userExtraInfo'
        case '/coach':
        case '/assessment':
        case '/interview':
          return '/coach'
        case '/term':
        case '/scheduling':
        case '/scheduling_detail':
          return '/term'
        case '/psychology':
        case '/psychology_reserve':
        case '/psychology_record':
          return '/psychology'
      }
    })
    onMounted(() => {
      const code = getQueryVariable('code')
      let userInfo = localStorage.getItem('userInfo');
      let apiUrl = internalInstance.appContext.config.globalProperties.apiUrl
      // console.log(process.env.NODE_ENV)
      if (process.env.NODE_ENV === "production") {
        if (!userInfo) {
          if (!code) {
              console.log('没有code，跳登录页')
            location.href = `http://10.238.0.183/base/ssologin/authorize?response_type=code&client_id=Psak6iLPYlWUH2xM&redirect_uri=${apiUrl}`;//新昌内网
            // location.href = `http://61.175.247.164:9366/base/ssologin/authorize?response_type=code&client_id=Psak6iLPYlWUH2xM&redirect_uri=${apiUrl}`;//21公司的服务器
          } else {
            axios.get(`/User/LoginUserInfo?code=${code}&redirectUrl=${apiUrl}`).then(res => {
              console.log('获取用户信息:', res)
              store.commit('setUserInfo', res)
              localStorage.setItem('userInfo', JSON.stringify(res));
              state.userInfo = res
            }).catch(err => {
              console.log('获取用户信息失败,err', err)
              alert('获取用户信息失败，请重新登录后再次访问')
              // location.href = 'http://10.238.0.183/base/ssologin/authorize?response_type=code&client_id=Psak6iLPYlWUH2xM&redirect_uri=http://10.238.0.182:8090/';
            })
          }
        } else {
          state.userInfo = JSON.parse(userInfo)
          store.commit('setUserInfo', JSON.parse(userInfo))
        }
      } else {
        setTimeout(() => {
          let userInfo = {
            class: "三年二班",
            male: "男",
            name: "小明",
            userId: "2",
            startYear: 2019,
            userType: 3,//1学生，2老师，3心理老师  1和2 都没有权限排班
          }
          store.commit('setUserInfo', userInfo)
          localStorage.setItem('userInfo', JSON.stringify(userInfo));
          state.userInfo = userInfo
        }, 2000)
      }
    })
    onUnmounted(() => {
      unwatch()
    })
    const handleCareer = () => {
      location.href = `https://www.sxh985.com/home?userName=${state.userInfo.name}&userUniqueId=${state.userInfo.userId}&&schoolYear=${state.userInfo.startYear}`
    }
    // 获取链接参数
    const getQueryVariable = (variable) => {
      // 取地址栏参数
      var query = window.location.search.substr(1);
      if (!query && window.location.hash.indexOf('?') > -1) {
        query = window.location.hash.split("?")[1];
      }
      var vars = query.split('&')
      for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split('=')
        if (pair[0] === variable) {
          return pair[1]
        }
      }
      return false
    }
    return {
      ...toRefs(state),
      locale: zhCn,
      handleCareer,
      parentPath
    }
  }
}
</script>

<style lang="scss" scoped>
.layout {
  min-height: 100vh;
  background-color: #ffffff;
}
.container {
  height: 100vh;
}
.loading{
  font-size: 50px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);
}
.aside {
  width: 293px !important;
  /* background-color: #222832; */
  overflow: hidden;
  overflow-y: auto;
  -ms-overflow-style: none;
  overflow: -moz-scrollbars-none;
  &::-webkit-scrollbar {
    display: none;
  }
  .el-menu-item {
    font-size: 21px;
    padding: 0 50px !important;
    display: flex;
    align-items: center;
    line-height: 30px;
    height: 80px;
    white-space: break-spaces;
  }

  .el-menu-item.is-active i {
    color: #3a84ff;
  }
  .el-menu-item [class^="el-icon-"] {
    font-size: 21px;
    margin-right: 30px;
  }
  .port {
    font-size: 21px;
    font-weight: bold;
    display: flex;
    align-items: center;
    padding-left: 52px;
    height: 85px;
    img {
      width: 67px;
      margin-right: 8px;
    }
  }

  .line {
    width: 193px;
    margin: 0 auto;
    border-top: 1px solid hsla(0, 0%, 100%, 0.05);
    border-bottom: 1px solid #dbdfe9;
    margin-top: 30px;
    margin-bottom: 40px;
  }
}
.content {
  display: flex;
  flex-direction: column;
  max-height: 100vh;
  overflow: hidden;
}
.main {
  height: calc(100vh - 85px);
  overflow: auto;
  padding: 30px;
  background: #f5f7fa;
}
</style>
<style lang="scss">
body {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
  color: #333;
}
.el-menu {
  border-right: none !important;
}
.el-submenu {
  border-top: 1px solid hsla(0, 0%, 100%, 0.05);
  border-bottom: 1px solid rgba(0, 0, 0, 0.2);
}
.el-submenu:first-child {
  border-top: none;
}
.el-submenu [class^="el-icon-"] {
  vertical-align: -1px !important;
}
a {
  color: #409eff;
  text-decoration: none;
}
.el-pagination {
  text-align: center;
  margin-top: 20px;
}
.el-popper__arrow {
  display: none;
}

// 子页面顶部返回按钮与标题
.sub_back {
  display: inline-block;
  color: #3a84ff;
  font-size: 14px;
  cursor: pointer;
}
.sub_title {
  font-size: 16px;
  color: #1b253a;
  margin-top: 7px;
  padding-bottom: 10px;
}
</style>
