import router from './router/index'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import getPageTitle from '@/utils/get-page-title'
import { productionManagementCheck } from '@/api/user.js'
// NProgress.configure({ showSpinner: false }) // NProgress Configuration
// && from.path === '/agreement' && from.path === '/policy'
const whiteList = ['/login', '/agreement', '/policy'] // no redirect whitelist
const cgyList = [
    '/harmonic-boot/line/pointmonitoring',
    '/harmonic-boot/region/regionalmonitoring',
    '/harmonic-boot/comper/comprehensiveanalysis',
    '/harmonic-boot/comper/CVT',
    '/Distributedphotovoltaic/homePage',
    '/Statistical-analysis/indicatorClassification',
    '/Statistical-analysis/IndicatorAlarmStatistics',
    '/Statistical-analysis/baselineLevelAssessment',
    '/Statistical-analysis/substationBackgroundHarmonic',
    '/Statistical-analysis/steadyStateIndicators',
    '/Statistical-analysis/transientIndicators'
]
// 免登录判断
import { sm2, encrypt } from '@/assets/commjs/sm2.js'
import { sm3Digest } from '@/assets/commjs/sm3'
import { setDictype, setSysConfig } from '@/utils/auth'
import { gongkey, CodeSr, heBeiToken, menulist, updateFirstPassword, dictypeData, getSysConfig } from '@/api/user'
let routerPath = ''
router.beforeEach(async (to, from, next) => {
    // start progress bar
    // NProgress.start()

    // const parentToken = window.parent?.localStorage.getItem('token') || window.parent?.sessionStorage.getItem('token');
    // if (parentToken) {
    //   console.log('从父页面获取的 token:', parentToken);
    //   // 使用获取到的 token
    // } else {
    //   console.error('未能从父页面获取 token');
    // }
    // set page title
    document.title = getPageTitle(to.meta.title)
    // 超高压河北免登录功能

    if (process.env.VUE_APP_MODE === 'cgyqr') {
        if (process.env.VUE_APP_HB == 'hbqr') {
            // let data = JSON.parse(sessionStorage.getItem('userInfo1'))
            // if (data.userToken == sessionStorage.getItem('HB_TOKEN')) {
            //     setTimeout(() => {
            //         proceed(to, from, next, data.userName)
            //     }, 10)
            // } else {
            //     await logout()
            //     window.sessionStorage.removeItem('cntoken')
            //     sessionStorage.setItem('HB_TOKEN', data.userToken)
            //     setTimeout(() => {
            proceed(to, from, next, 'cdf')
            //     }, 10)
            // }

            // await window.addEventListener('message', async function (e) {
            //     if (e.data.key == 'HB_TOKEN') {
            //         if (e.data.data.userToken == sessionStorage.getItem('HB_TOKEN')) {
            //             setTimeout(() => {
            //                 proceed(to, from, next, e.data.data.userName)
            //                },10)
            //         } else {
            //             await logout()
            //             window.sessionStorage.removeItem('cntoken')
            //             sessionStorage.setItem('HB_TOKEN', e.data.data.userToken)
            //            setTimeout(() => {
            //             proceed(to, from, next, e.data.data.userName)
            //            },10)

            //         }

            //     }
            // })

            // let _sessionUserInfo = sessionStorage.getItem('userInfo')
            //     ? JSON.parse(sessionStorage.getItem('userInfo'))
            //     : null
            // console.log('🚀 ~ 项目获取的token:', _sessionUserInfo)
            // if (_sessionUserInfo) {
            //     await heBeiToken({ token: '111111' }).then(res => {
            //         name = res.data
            //     })
            // }
        } else {
            const response = await fetch('/')
            const flag = response.headers.get('X-Xbqr')
            console.log('🚀 ~ flag:', flag)

            if (flag) {
            // 超高压嵌入 接受父应用传参
            window.addEventListener(
                'message',
                event => {
                    if (event.data && event.data.type === 'iframeNest') {
                        let { accessToken, displayMode, theme } = event.data
                        console.log('我是iframe,我接收到了数据：', accessToken)
                        productionManagementCheck({
                            token: accessToken
                        }).then(res => {
                            console.log('🚀 ~ receiveMessageFromOutside ~ res:', res)
                            if (res.code == 'A0000') {
                                proceed(to, from, next)
                            }
                        })
                    }
                },
                false
            )
            } else {
                proceed(to, from, next)
            }
        }

        // else {
        //     //获取用户信息
        //     await store.dispatch('user/getInfo')
        //     // 根据角色生成可访问的路线图
        //     const accessRoutes = await store.dispatch('permission/generateRoutes')
        //     // 动态添加可访问的路由
        //     router.addRoutes(accessRoutes)
        //     next({ ...to, replace: true })
        // }
    } else if (whiteList.indexOf(to.path) !== -1) {
        next()
    } else {
        const hasGetUserInfo = store.getters.userInfo
        if (hasGetUserInfo) {
            next()
        } else {
            try {
                //获取用户信息
                await store.dispatch('user/getInfo')
                // 根据角色生成可访问的路线图
                const accessRoutes = await store.dispatch('permission/generateRoutes')

                // 动态添加可访问的路由
                router.addRoutes(accessRoutes)
                if (from.path === '/login' && router.match(to).path === '/404') {
                    next({ path: '/', replace: true })
                } else {
                    next({ ...to, replace: true })
                }
            } catch (error) {
                if (error.errorCode === 401 && process.env.NODE_ENV === 'production') {
                    // if (error.errorCode === 401) {
                    // 关闭弹窗
                    document.querySelector('.messageBox401 .el-button').click()
                    await store.dispatch('user/logout', true)
                }
                NProgress.done()
            }
        }
    }
})

async function proceed(to, from, next, HB_NAME) {
    // 打印当前 name 和 sessionStorage 中 cntoken 是否为空的日志
    let name = HB_NAME || 'cdf'
    // 检查 sessionStorage 中是否没有 cntoken
    console.log('🚀 ~ proceed ~ name:', name, window.sessionStorage.getItem('cntoken') == null)
    // 定义默认密码
    if (window.sessionStorage.getItem('cntoken') == null) {
        // 初始化登录表单
        let password = '@#001njcnpqs'
        let loginjmForm = {
            username: '',
            password: '',
            grant_type: 'captcha',
            verifyCode: 0,
            imageCode: ''
            // 对 name 进行加密处理
        }
        let username = encrypt(name)
        // 设置登录表单的用户名

        // 将应用高度存储到 sessionStorage 中
        loginjmForm.username = username
        // 调用 gongkey 函数获取公钥
        window.sessionStorage.setItem('appheight', document.body.offsetHeight - 10)
        await gongkey({ loginName: username }).then(async response => {
            window.publicKey = response.data
            // 将公钥存储到全局变量和 localStorage 中
            window.localStorage.setItem('publicKey', response.data)

            var sm3Pwd = sm3Digest(password)
            // 使用 SM3 算法对密码进行摘要处理
            var jiamipassword = ''
            // 使用 SM2 算法对密码进行加密
            jiamipassword = sm2(sm3Pwd + '|' + password, publicKey, 0)
            loginjmForm.password = jiamipassword
            // 设置登录表单的加密密码

            store
                // 调用 Vuex 的 login 方法进行登录
                .dispatch('user/login', loginjmForm)
                .then(async response => {
                    if (response.code === 'A0101' && response.message === '登录认证,密码失效，请重置') {
                        // 如果登录响应需要重置密码
                        CodeSr().then(response => {
                            // 调用 CodeSr 函数获取验证码图片
                            let blob = new Blob([response], { type: 'image/jpg' })
                            let url = window.URL.createObjectURL(blob)
                        })
                    }
                    await store.dispatch('user/getInfo')
                    // 获取用户信息
                    // 根据角色生成可访问的路线图
                    const accessRoutes = await store.dispatch('permission/generateRoutes')
                    // 动态添加可访问的路由
                    setTimeout(() => {
                        router.addRoutes(accessRoutes)
                        if (response.code === 'A0000') {
                            // 如果登录成功
                            loginjmForm.verifyCode = 0
                            // 重置验证码
                            SysConfig()
                            // 调用 SysConfig 函数进行系统配置
                            // cgyList.indexOf(to.path) !== -1
                            store.dispatch('user/getmenu').then(async response => {
                                await getmuen(response.data[0])
                                router.push({
                                    path: cgyList.indexOf(to.path) !== -1 ? to.path : to.path //routerPath
                                })
                            })
                        }
                        next()
                    }, 500)
                })
                .catch(error => {
                    CodeSr().then(response => {
                        let blob = new Blob([response], { type: 'image/jpg' })
                        let url = window.URL.createObjectURL(blob)
                        this.tokenImg = url
                    })
                })
        })
    } else {
        next()
    }
}

function getmuen(data) {
    if (data.children.length == 0) {
        routerPath = data.routePath
    } else {
        getmuen(data.children[0])
    }
}
function SysConfig() {
    getSysConfig().then(res => {
        const sysdata = res.data
        setSysConfig(JSON.stringify(sysdata))
    })
    dictypeData().then(response => {
        const dictType = response.data
        setDictype(JSON.stringify(dictType))
    })
}

router.afterEach(() => {
    // finish progress bar
    NProgress.done()
})
