import Vue from 'vue'
import VueRouter from 'vue-router'
import NavLayout from "@/components/layout/NavLayout"
import store from '@/store'
import { isSupportHtml5Plus } from '@/utils/platform'
import { setTitle } from "@/utils/title"
import Login from '@/views/login/Login'
import Register from '@/views/login/Register'
import FotgetPassword from '@/views/login/FotgetPassword'

import personal from './personal'
import {getPublicKey, getHwlyyDecrypt, checkWlyyLogin, findOneUserFormat} from '@/api/login'
import JSEncrypt from "@/utils/jsencrypt";
import { Toast } from 'vant'
import { findLoginRoleMenuTree } from '@/api/login'
import { _ } from 'core-js'
Vue.use(VueRouter)

const routes = [
    {
        path: '/',
        redirect: '/home'
    },
	{
        path: '/404',
        name: '404',
        component: () => import('@/views/404/404.vue')
    },
    {
        path: '/login',
        name: 'login',
        component: Login,
        meta: {
            title: '登录',
            hasTop: false
        }
    },
    {
        path: '/register',
        name: 'register',
        component: Register,
        meta: {
            title: '注册'
        }
    },
    {
        path: '/fotgetPassword',
        name: 'fotgetPassword',
        component: FotgetPassword,
        meta: {
            title: '忘记密码',
        }
    },
    {
        path: '/home',
        name: 'home',
        component: NavLayout,
        redirect: "/home/index",
        children: [{
            path: "index",
            name: "homeIndex",
            component: () => import('@/views/index/Index'),
            meta: {
                title: '首页',
                hasBot: true,
                hasTop: false
            }
        }]
    },
]

const whiteList = [
	'/login', 
	'/register', 
	'/fotgetPassword',
]

const router = new VueRouter({
    mode: 'history',
    base: process.env.BASE_URL,
    routes: routes.concat( personal )
})


function redirectToLogin(to, from, next) {
    let isApp = to.query.isApp || isSupportHtml5Plus
    if(isApp) {
        next(`/login?isApp=1&redirectUrl=${encodeURIComponent(to.fullPath)}`)
    } else {
      next('/login')
    }
}

var routerLoaded = false
function formatAuthMenu(menu){
    if(menu){
        return _.map(menu, v=>{
            return {
                name: v.name,
                url: v.url,
                type: v.type,
                children: v.children? formatAuthMenu(v.children) : []
            }
        })
    }
}

router.beforeEach(async (to, from, next) => {
    if(!to.query.VNK){
        //因为引入navigation组件  beforeEach会执行两次 第一次无VNK 第二次为设置VNK值  所以当VNK不存在时 直接跳过
        next()
        return
    }
    if(to.query._noTop==1){
        store.dispatch('SetNoTop', true)
    }
    new Promise((resolve, reject)=>{
        if(to.query._code){
            authLogin(to.query._code, to)
                .then(res=>{
                    Toast.clear()
                    resolve()
                })
        } else {
            resolve()
        }
    })
    .then(res=>{
        if((store.getters.user && store.getters.user.accessToken)) {
            if(!routerLoaded){
                findOneUserFormat({
                    id: store.getters.user.id
                }).then(userInfo2 => {
                    var userInfo = _.assignIn(store.getters.user, userInfo2);
                    store
                        .dispatch('SetLoginUser', userInfo)
                        .then(res=>{
                            next()
                            // findLoginRoleMenuTree({
                            //     roleId: store.getters.user.curRoleId
                            // })
                            // .then(res=>{
                            //     routerLoaded = true
                            //     var routeList = formatAuthMenu(res.detailModelList)
                            //     store.dispatch('SetAuthMenu', routeList)
                            //     console.log('routeList', routeList)
                            //     next()
                            // })
                            // .catch(err=>{
                            //     console.error(err)
                            // })
                        })
                }).catch(err=>{
                    routerLoaded = true
                    console.error(err)
                })
            } else {
                next()
            }
        } else {
            routerLoaded = false
            if( whiteList.indexOf(to.path) > -1) {
                next()
            } else {
                redirectToLogin(to, from, next)
            }
        }
    })
    .catch(err=>{
        console.error(err)
    })
})

function authLogin(code, to){
    return new Promise((resolve, reject)=>{
        Toast.loading({
            message: '授权登录中..',
            duration: 0,
            forbidClick: true
        })
        getHwlyyDecrypt({code: decodeURIComponent(code)})
            .then(data=>{
                return new Promise((resolve, reject)=>{
                    getPublicKey({})
                        .then(res=>{
                            var encrypt = new JSEncrypt()
                            encrypt.setPublicKey(res.obj.publicKey)
                            resolve(encrypt.encrypt(data.obj.code))
                        })
                        .catch(err=>{
                            reject(err)
                        })
                })
            })
            .then(code=>{
                return checkWlyyLogin({
                    code: code,
                    client_id: store.getters.clientId,
                    login_type: 1
                })
            })
            .then(res=>{
                if(res.obj && res.obj.authCode==1){
                    var userInfo  = res.obj.WlyyUserSimple
                    userInfo.token = userInfo.accessToken
                    userInfo.clientType = to.query.clientType//1 来自i健康app 区域互联网
                    store.dispatch('SetLoginUser', userInfo)
                    findOneUserFormat({
                        id: userInfo.id
                    }).then(userInfo2 => {
                        userInfo = _.assignIn(userInfo, userInfo2);
                        store
                            .dispatch('SetLoginUser', userInfo)
                            .then(res=>{
                                resolve()
                            })
                    }).catch(err=>{
                        console.error(err)
                    })
                    // // "saasAdmin"： "管理员"； regionAdmin" "区域管理员" ; communityAdmin "社区管理员" ;  "  "replenisher"： "补货员"
                    // // 18补货员 19社区管理员 20区域管理员 21超管
                    // var dictList = {
                    //     18: {
                    //         curRoleCode: "replenisher",
                    //         curRoleName: "补货员"
                    //     },
                    //     19: {
                    //         curRoleCode: "communityAdmin",
                    //         curRoleName: "社区管理员"
                    //     },
                    //     20: {
                    //         curRoleCode: "regionAdmin",
                    //         curRoleName: "区域管理员"
                    //     },
                    //     21: {
                    //         curRoleCode: "saasAdmin",
                    //         curRoleName: "管理员"
                    //     },
                    // }
                    // var { curRoleCode, curRoleName } = dictList[to.query._role]
                    // userInfo.curRoleCode = curRoleCode
                    // userInfo.curRoleName = curRoleName
                    // store
                    //     .dispatch('SetLoginUser', userInfo)
                    //     .then(res=>{
                    //         resolve()
                    //     })
                } else {
                    Toast(res.message|| (res.obj&&res.obj.mes))
                    reject(res)
                }
            })
            .catch(err=>{
                console.error(err)
                // Toast("获取医生数据错误")
                reject(err)
            })
    })
}

const noSetTitleList = []
router.afterEach((to, from) => {
    // 更新页面标题
    console.log(to,from)
    if (to.meta && to.meta.title && noSetTitleList.indexOf(to.path)==-1) {
        setTitle(to.meta.title)
        store.dispatch("SetPageTitle", to.meta.title)
    }
    else if(noSetTitleList.indexOf(to.path)>-1){
      
    }
    window.scrollTo(0, 0);
})



export default router
