<template>
    <div class="common-layout">
        <el-container style="height: 100%;">
            <el-header>
                <el-menu :default-active="activeIndex" class="el-menu-demo" mode="horizontal">
                    <el-menu-item v-for="(item, index) in menuList.list" :key="index" :index="item.menuName" v-show="item.isShow">
                        <router-link :to="{name: item.router}">{{ item.name }}</router-link>
                    </el-menu-item>
                </el-menu>
                <span class="website-name">{{ store.website.name }}</span>
                <div class="head-photo" v-show="userInfo?.exp">
                    <el-dropdown>
                        <el-avatar :size="35" :src="userInfo?.picture" />
                        <template #dropdown>
                            <el-dropdown-menu v-if="userInfo?.name">
                                <div style="margin: 5px 10px;">
                                    <p>{{ userInfo.name }}</p>
                                    <p>ID: {{ userInfo.sub }}</p>
                                </div>
                                <el-dropdown-item @click="gotoInfo()">
                                    <el-icon><Postcard /></el-icon>
                                    {{ $t('home.baseInfo') }}
                                </el-dropdown-item>
                                <!-- <el-dropdown-item @click="websiteChange = true">
                                    <el-icon><Postcard /></el-icon>
                                    切换站点
                                </el-dropdown-item> -->
                                <el-dropdown-item @click="loginOut()">
                                    <el-icon><SwitchButton /></el-icon>
                                    {{ $t('home.logout') }}
                                </el-dropdown-item>
                            </el-dropdown-menu>
                            <el-dropdown-menu v-else>
                                <el-dropdown-item @click="toTeammodel()">
                                    <el-icon><Position /></el-icon>
                                    {{ $t('home.toLogin') }}
                                </el-dropdown-item>
                            </el-dropdown-menu>
                        </template>
                    </el-dropdown>
                </div>
                <div class="head-photo" v-show="!userInfo?.exp">
                    <p @click="toTeammodel()" style="height: 35px; line-height: 35px;">{{ $t('home.login') }}</p>
                </div>
            </el-header>
            <el-main>
                <router-view></router-view>
            </el-main>
        </el-container>
        <el-dialog v-model="websiteChange" title="切换站点" width="30%">
            <el-select v-model="webSelect" class="m-2" placeholder="请选择要切换的站点">
                <el-option v-for="item in otherWebsite" :disabled="item.route === currentSite" :key="item.route" :label="item.name" :value="item.route" />
            </el-select>
            <template #footer>
            <span class="dialog-footer">
                <!-- <el-button @click="dialogVisible = false">Cancel</el-button> -->
                <el-button type="primary" @click="webSelChange()">切换</el-button>
            </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { computed, getCurrentInstance, onMounted, reactive, ref, toRaw, watch } from "vue"
import { useRoute, useRouter } from 'vue-router'
// import { useStore } from "vuex"
import { SwitchButton, Postcard, Position } from '@element-plus/icons-vue'
import { useStore } from "@/pinia/common"
import { ElLoading, ElMessage } from "element-plus"
import jwtDecode from "jwt-decode"

const router = useRouter()
const route = useRoute()
let store = useStore()
let { proxy } = getCurrentInstance()

let activeIndex = ref(route.meta.activeName)
let websiteChange = ref(false)
let webSelect = ref("")
let otherWebsite = ref([])
let userInfo = ref({})

let isExpert = computed(() => {
    if(store.userInfo.roles && store.userInfo.roles.includes('expert')) {
        return true
    } else {
        return false
    }
})

let menuList = reactive({list: [
    {
        name: proxy.$t('home.menulist.homepage'),
        menuName: 'home',
        router: 'homePage',
        isShow: true
    },
    {
        name: proxy.$t('home.menulist.myActivity'),
        menuName: 'myActivity',
        router: 'myActivity',
        isShow: true
    },
    {
        name: proxy.$t('home.menulist.myReview'),
        menuName: 'myReview',
        router: 'myReview',
        isShow: isExpert
    }
]})

onMounted(() => {
    if(localStorage.getItem("auth_token")) {
        let infos = jwtDecode(localStorage.getItem("auth_token"))
        userInfo.value = infos
        store.setUserInfo(infos)
        let schools = JSON.parse(localStorage.getItem("schools"))
        store.setSchoolList(schools)
    }
})

await getWebsite()

function gotoInfo() {
    activeIndex.value = '-1'
    router.push("/home/basicInfo")
}

function loginOut() {
    localStorage.removeItem("auth_token")
    localStorage.removeItem("access_token")
    localStorage.removeItem("access_token")
    localStorage.removeItem("expires_in")
    store.setSchoolList([])
    store.setUserInfo({})
    userInfo.value = {}
    menuList.list.splice(2, 1)
    router.push({path: '/home/homePage'})
    ElMessage({
        type: 'warning',
        message: proxy.$t('elMessage.logout')
    })
    // location.href = "https://account.teammodel.cn/?callback=" + window.location.href
}

function getWebsite() {
    return new Promise((r, j) => {
        /* const loading = ElLoading.service({
            lock: true,
            text: '加载中',
            background: 'rgba(0, 0, 0, 0.7)'
        }) */
        let areaRoute = window.location.pathname.split('/')
        let params = {
            route: areaRoute[1]
        }
        proxy.$api.getWebsite(params).then(res => {
            if(res.code === 200) {
                // res.website.blobUrl = res.blobUrl
                store.setWebsite(res.website)
                otherWebsite.value = res.websites
            } else if(res.code === 2) {
                ElMessage({
                    type: 'error',
                    message: proxy.$t('elMessage.noRoute')
                })
            }
            r(200)
        }).finally(() => {
            // loading.close()
        })
    })
    
}

function webSelChange() {
    /* let host = window.location.host
    location.href = host + '/' + webSelect.value + '/home/homePage' */
    // 切换到对应站点？？？
}
function toTeammodel() {
    location.href = "https://account.teammodel.cn/?callback=" + window.location.href
}

function login() {
    /* const loading = ElLoading.service({
        lock: true,
        text: '登录中',
        background: 'rgba(0, 0, 0, 0.7)'
    }) */
    // 获取登录后返回的ticket
    let search = window.location.search
    let ticket = ''
    let token = ''
    if(search.includes('ticket')) {
        ticket = search.split('?')[1].split("&")[0].split('ticket=')[1]
    } else if(search.includes('token')) {
        token = search.split('?token=')[1]
    }
    let areaRoute = window.location.pathname.split('/')
    // ticket 只用一次，不用存在localStorage
    // token token过期或从其他活动跳转过来传
    let params = {
        route: areaRoute[1],
    }
    if(ticket) {
        params.ticket = ticket
    } else if(token) {
        params.token = token
    } else {
        params.token = localStorage.getItem("auth_token")
    }
    proxy.$api.loginPortal(params).then(res => {
        if(res.code === 200) {
            if(ticket || token) router.push({path: '/home/homePage'})
            if(!localStorage.getItem("auth_token")) localStorage.setItem("auth_token", res.token)
            localStorage.setItem("access_token", res.auth_token.access_token)
            localStorage.setItem("schools", JSON.stringify(res.schools))
            localStorage.setItem("expires_in", res.auth_token.expires_in)
            store.setSchoolList(res.schools)
            store.setUserInfo(jwtDecode(res.token))
            userInfo.value = jwtDecode(res.token)
        } else {
            localStorage.removeItem("auth_token")
            localStorage.removeItem("access_token")
            localStorage.removeItem("access_token")
            localStorage.removeItem("expires_in")
            sessionStorage.setItem('loginOut', res.msg)
            store.setSchoolList([])
            store.setUserInfo({})
            userInfo.value = {}
            router.push({path: '/home/homePage'})
            ElMessage({
                type: 'warning',
                message: '请重新登录'
            })
        }
    }).finally(() => {
        // loginLoad.close()
    })
}

let currentSite = computed(() => {
    return window.location.pathname.split('/')[1]
})

// 监听是否带参数，
let ticket = computed(() => {
    let search = window.location.search
    if(search.includes('ticket')) {
        return search.split('?')[1].split("&")[0].split('ticket=')[1]
    } else {
        return ''
    }
})

// 监听是否带参数，
let authToken = computed(() => {
    let search = window.location.search
    if(search.includes('token')) {
        return search.split('?token=')[1]
    } else {
        return ''
    }
})

watch(route, (newVal, oldVal) => {
    activeIndex.value = newVal.meta.activeName
}, {deep: true}, {immediate: true})

watch([ticket, authToken], ([newValue1, newValue2], [oldValue1, oldValue2]) => {
    if([newValue1, newValue2]) {
        login()
    }
}, {immediate: true})

</script>

<style lang="less">
.common-layout {
    height: 100%;

    .el-main {
        padding: 0;
        height: 100%;
    }
    .head-photo {
        position: absolute;
        top: 11px;
        right: 40px;
        margin-right: 40px;
        cursor: pointer;
        .user_avatar{
            width: 36px;
            height: 36px;
            border-radius: 50%;
            background-color: #72727f;
        }
    }
    .website-name {
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
        font-size: 1.5rem;
    }
    .el-header {
        position: relative;
        // padding: 0;
        // border-bottom: solid 1px var(--el-menu-border-color);
        background-color: #15559a;
        color: #fff;
        
        a {
            text-decoration: none; /* 移除链接默认的下划线 */
        }
        
        .el-menu {
            background-color: #15559a;
            min-width: 350px;
        }
        .el-menu--horizontal.el-menu {
            border-bottom: none;
        }
        .el-menu--horizontal>.el-menu-item {
            color: #F1F1E6;
        }

        .el-menu--horizontal>.el-menu-item.is-active {
            border-bottom-color: #fff;
            // border-bottom: none;
            color: #fff !important;
            // font-size: 16px;
            font-weight: bold;
        }
        .el-menu--horizontal .el-menu-item:not(.is-disabled):focus, .el-menu--horizontal .el-menu-item:not(.is-disabled):hover {
            background-color: #15559a;
            // font-size: 16px;
            // font-weight: bold;
            border-bottom: 2px solid #fff;
        }
    }
    .el-avatar {
        outline: none;
    }
}
</style>