import stringify from '@/utils/querystring'
import { timeFormat } from '@/uni_modules/uv-ui-tools/libs/function/index.js';
import router from './router'
import cookie from './cookie'
import { PARAMS_KEY } from "@/hooks/useRouter";

/**
 * 未登录无权限
 */
export const handleLoginFailure = () => {
    // todo 添加记录参数逻辑
    // router.replace({
    //   path: '/pages/login/login',
    // })
    const routes = getCurrentPages();
    const curRoute = routes[routes.length - 1];
    if (["pages/login/guid", "pages/login/index"].includes(curRoute.route)) {
        return;
    }
    const lastFullPath = `/${curRoute.route}?${PARAMS_KEY}=${curRoute.options[PARAMS_KEY]}`
    uni.setStorage({
        key: 'lastFullPath',
        data:lastFullPath
    })
    uni.redirectTo({
        url: '/pages/login/guid',
    })
}

export const afterLogin = () => {
    const tabsList = [
        '/pages/goodsCategory/goodsCategory',
        '/pages/index/index',
        '/pages/shoppingCart/shoppingCart',
        '/pages/user/user'
    ]
    const lastPath = uni.getStorageSync('lastFullPath');
    if (lastPath) {
        const str = lastPath.split("?")
        if (tabsList.includes(str[0])) {
            uni.switchTab({url: lastPath})
        } else {
            uni.redirectTo({url: lastPath})
        }
        uni.removeStorageSync('lastFullPath')
    } else {
        uni.switchTab({url: '/pages/index/index'})
    }
}

export function parseUrl(location) {
    if (typeof location === 'string') return location
    const {url, query} = location

    const queryStr = stringify(query)

    if (!queryStr) {
        return url
    }

    return `${ url }?${ queryStr }`
}


export function objectURLToBlob(url) {
    return new Promise(resolve => {
        const http = new XMLHttpRequest()
        http.open('GET', url, true)
        http.responseType = 'blob'
        http.onload = function (e) {
            if (this.status == 200 || this.status === 0) {
                resolve(this.response)
            }
        }
        http.send()
    })
}

/**
 * 判断h5环境是否在微信浏览器内
 * @returns {boolean}
 */
export function h5InWeChat() {
    if (!navigator || (navigator && !navigator.userAgent)) return false
    let ua = navigator.userAgent.toLowerCase();
    return ua.match(/MicroMessenger/i) == "micromessenger"
}

export function createMessage(msg, data) {
    return {
        msg,
        data
    }
}


const toAuth = () => {
    uni.showToast({
        title: '暂未开放',
        icon: 'none',
        duration: 2000,
    })
}

export default {
    install: (app, options) => {
        // 在这里编写插件代码
        // 注入一个全局可用的 $translate() 方法
        app.config.globalProperties.$yrouter = router
        app.config.globalProperties.$cookie = cookie
        app.config.globalProperties.$toAuth = toAuth
        app.config.globalProperties.$timeFormat = timeFormat
        app.config.globalProperties.$onClickLeft = () => {
            uni.navigateBack()
            // router.back()
        }

        // #ifdef H5
        app.config.globalProperties.$platform = 'h5'
        // #endif

        // #ifdef APP-PLUS
        // app端
        app.config.globalProperties.$platform = 'app'
        // #endif

        // #ifdef MP-WEIXIN
        app.config.globalProperties.$platform = 'routine'
        // #endif
    },
}
