import { createApp } from 'vue';
import App from './App.vue';
import router from './router';
import store from './store';
import Vant from 'vant';
import { ConfigProvider } from 'vant';
import 'vant/lib/index.css';
import './styles/app.less';
import './styles/font.less';
import http from './plugins/http';
import colors from './plugins/colors';
// import ElementUI from 'element-ui';
// import 'element-ui/lib/theme-chalk/index.css';
import PageTitle from './components/PageTitle';
import LikeButton from './components/LikeButton.vue';
import Driver from './components/Driver.vue';
import common from './mixins/common';
import VueClipboard from 'vue-clipboard2';
import queryString from 'query-string';
import PageBar from './components/PageBar';
import eruda from 'eruda';
import mitt from 'mitt';
import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';
import calendar from 'dayjs/plugin/calendar';
import duration from 'dayjs/plugin/duration';
import isSameOrBefore from 'dayjs/plugin/isSameOrBefore';
import customParseFormat from 'dayjs/plugin/customParseFormat';
import { Toast, Dialog } from 'vant';
import { useCssVar } from '@vueuse/core';
import { computed } from 'vue';

const appHeight = useCssVar('--app-height', document.documentElement);
const onWindowResize = () => {
    if (navigator.userAgent.includes('#cordova#')) {
        appHeight.value = `${window.screen.height}px`;
    } else {
        appHeight.value = `${window.innerHeight}px`;
    }
};
window.addEventListener('resize', onWindowResize);
onWindowResize();
Toast.setDefaultOptions('loading', { duration: 0 });
require('dayjs/locale/zh-cn');

const emitter = mitt();

dayjs.locale('zh-cn');
dayjs.extend(relativeTime);
dayjs.extend(calendar);
dayjs.extend(duration);
dayjs.extend(isSameOrBefore);
dayjs.extend(customParseFormat);

let showConsole = localStorage.getItem('showConsole');
if (showConsole && parseInt(showConsole) > new Date().getTime()) {
    eruda.init();
}
store.commit('setFirstUrl', location.href);

import ImgContent from './components/ImgContent.vue';
const safeTop = useCssVar('--safe-top', document.documentElement);
const safeBottom = useCssVar('--safe-bottom', document.documentElement);
const safeLeft = useCssVar('--safe-left', document.documentElement);
const safeRight = useCssVar('--safe-right', document.documentElement);
const calcSafeArea = () => {
    safeTop.value = getComputedStyle(document.documentElement).getPropertyValue('--sat').replaceAll(' ', '');
    safeBottom.value = getComputedStyle(document.documentElement).getPropertyValue('--sab').replaceAll(' ', '');
    safeLeft.value = getComputedStyle(document.documentElement).getPropertyValue('--sal').replaceAll(' ', '');
    safeRight.value = getComputedStyle(document.documentElement).getPropertyValue('--sar').replaceAll(' ', '');
    if (navigator.userAgent.includes('#testSafeTop#')) {
        safeTop.value = '30px';
    }
};
const barHeight = computed(() => Number((safeTop.value || '0').replace('px', '')) + 46);

const app = createApp(App)
    .use(Vant)
    .use(http)
    .use(colors)
    // .use(ElementUI)
    .use(ConfigProvider)
    .use(VueClipboard)
    .mixin(common)
    .component('page-title', PageTitle)
    .component('like-button', LikeButton)
    .component('driver', Driver)
    // .component('van-image', ImgContent)
    .component('page-bar', PageBar)
    .use(store)
    .use(router)
    .provide('appHeight', appHeight)
    .provide('safeTop', safeTop)
    .provide('safeBottom', safeBottom)
    .provide('safeLeft', safeLeft)
    .provide('safeRight', safeRight)
    .provide('barHeight', barHeight.value);
app.config.globalProperties.emitter = emitter;
app.config.globalProperties.dayjs = dayjs;

let query = queryString.parse(location.search);
if (query.code) {
    http.http.post('/user/code2openId', { code: query.code }).then(res => {
        localStorage.setItem('openId', res);
    });
} else {
    if (/micromessenger/i.test(navigator.userAgent) && !/localhost|(192\.168)/i.test(location.host)) {
        // document.location.replace(location.origin + '/wx/redirect?redirectUrl=' + location.href);
    }
}
// store.dispatch('getTime');
if (query.invitor) {
    store.commit('setInvitor', query.invitor);

    if (query.id) {
        store.commit('setProductId', query.id);
    }
}
if (query.from) {
    store.commit('setFrom', query.from);
}
if (query.inviteCode) {
    store.commit('setInviteCode', query.inviteCode);
}
if (query.review === 'true' || query.review === true) {
    store.commit('setReview', true);
}
if (query.reviewPay === 'true' || query.reviewPay === true || sessionStorage.getItem('reviewPay')) {
    store.commit('setReviewPay', true);
    sessionStorage.setItem('reviewPay', true);
}
const style = document.documentElement.style;
style.setProperty('--safe-top', 'env(safe-area-inset-top)');
style.setProperty('--safe-bottom', 'env(safe-area-inset-bottom)');
style.setProperty('--safe-left', 'env(safe-area-inset-left)');
style.setProperty('--safe-right', 'env(safe-area-inset-right)');

const isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent);

const loadSplash = (onload, onerror) =>
    new Promise((resolve, reject) => {
        let isHide = false;
        function hideSplash() {
            if (isHide) return;
            isHide = true;
            splash.style.opacity = 0;
            setTimeout(() => {
                // document.body.removeChild(splash);
            }, 800);
            resolve();
        }

        const splash = document.createElement('img');
        splash.className = 'splash-screen';
        splash.onload = () => {
            onload && onload();
            setTimeout(() => {
                hideSplash();
            }, 2000);
        };
        splash.onerror = () => {
            hideSplash();
            onerror && onerror();
        };
        setTimeout(() => {
            hideSplash();
        }, 5000);
        splash.src = 'https://nanjingnft.oss-cn-hangzhou.aliyuncs.com/font/splash.jpg?ts=' + new Date().getTime();
        // document.body.append(splash);
    });

if (navigator.userAgent.includes('#cordova#')) {
    document.addEventListener(
        'deviceready',
        function () {
            StatusBar.overlaysWebView(true);
            if ('1' === window.localStorage.getItem('AppTips')) {
                try {
                    window.cordova.plugins.UmengPlugin.initPush(deviceToken => {
                        console.log('deviceToken=' + deviceToken);
                    });
                } catch (e) {}
            }
            function mountApp() {
                window.$vm = app.mount('#app');
                http.http
                    .get('/appVersion/checkUpdate', {
                        platform: window.cordova.platformId,
                        version: navigator.appInfo.version
                    })
                    .then(res => {
                        if (res.needUpdate) {
                            window.$vm.$dialog.alert({
                                message: '检测到新版本，请下载更新',
                                confirmButtonText: '下载更新',
                                beforeClose(action, done) {
                                    console.log(action);
                                    location.href = 'http://download.raex.vip';
                                }
                            });
                        }
                    });
            }
            loadSplash(
                () => {
                    setTimeout(() => {
                        navigator.splashscreen.hide();
                    }, 100);
                    mountApp();
                },
                () => {
                    navigator.splashscreen.hide();
                    mountApp();
                }
            ).then(res => {
                StatusBar.styleDefault();
            });
            calcSafeArea();
            if ('android' === window.cordova.platformId) {
                window.AndroidNotch.getInsetTop(
                    px => {
                        console.log('getInsetTop=' + px);
                        safeTop.value = px + 'px';
                    },
                    err => console.error('Failed to get insets top:', err)
                );

                window.AndroidNotch.getInsetRight(
                    px => {
                        safeRight.value = px + 'px';
                    },
                    err => console.error('Failed to get insets right:', err)
                );

                window.AndroidNotch.getInsetBottom(
                    px => {
                        safeBottom.value = px + 'px';
                    },
                    err => console.error('Failed to get insets bottom:', err)
                );

                window.AndroidNotch.getInsetLeft(
                    px => {
                        safeLeft.value = px + 'px';
                    },
                    err => console.error('Failed to get insets left:', err)
                );
            } else {
                calcSafeArea();
                setTimeout(() => {
                    calcSafeArea();
                }, 500);
            }

            let t = 0;
            document.addEventListener(
                'backbutton',
                e => {
                    if (window.$vm.$route.matched.find(i => i.name === 'index')) {
                        e.preventDefault();
                        let t1 = new Date().getTime();
                        console.log(t1 - t);
                        if (t1 - t < 1000) {
                            navigator.app.exitApp();
                        } else {
                            t = t1;
                            window.$vm.$toast('再按一次退出');
                        }
                    } else {
                        window.$vm.$router.go(-1);
                    }
                },
                false
            );

            if ('ios' === window.cordova.platformId) {
                window.store.register(
                    ['68', '108', '198', '288', '588', '998'].map(id => {
                        return {
                            id,
                            alias: id,
                            type: window.store.CONSUMABLE
                        };
                    })
                );
                window.store.error(function (error) {
                    console.log('ERROR ' + error.code + ': ' + error.message);
                });
                ['68', '108', '198', '288', '588', '998'].forEach(id => {
                    window.store
                        .when(id)
                        .updated(product => {
                            emitter.emit('iapEvent', { event: 'updated', product });
                        })
                        .requested(product => {
                            emitter.emit('iapEvent', { event: 'requested', product });
                        })
                        .initiated(product => {
                            emitter.emit('iapEvent', { event: 'initiated', product });
                        })
                        .cancelled(product => {
                            emitter.emit('iapEvent', { event: 'cancelled', product });
                        })
                        .approved(product => {
                            product.finish();
                            emitter.emit('iapEvent', { event: 'approved', product });
                        })
                        .verified(product => {
                            emitter.emit('iapEvent', { event: 'verified', product });
                        })
                        .finished(product => {
                            emitter.emit('iapEvent', { event: 'finished', product });
                        });
                });
                window.store.refresh();
            }
        },
        false
    );
} else {
    window.$vm = app.mount('#app');
    // loadSplash().then(res => {

    // });
}
